@adcp/sdk 14.0.0-beta.5 → 14.0.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/lib/core/AgentClient.d.ts.map +1 -1
  2. package/dist/lib/core/AgentClient.js +26 -10
  3. package/dist/lib/core/AgentClient.js.map +1 -1
  4. package/dist/lib/core/AgentClient.mjs +26 -10
  5. package/dist/lib/core/AgentClient.mjs.map +1 -1
  6. package/dist/lib/core/AsyncHandler.d.mts +4 -2
  7. package/dist/lib/core/AsyncHandler.d.ts +4 -2
  8. package/dist/lib/core/AsyncHandler.d.ts.map +1 -1
  9. package/dist/lib/core/AsyncHandler.js +15 -1
  10. package/dist/lib/core/AsyncHandler.js.map +1 -1
  11. package/dist/lib/core/AsyncHandler.mjs +15 -1
  12. package/dist/lib/core/AsyncHandler.mjs.map +1 -1
  13. package/dist/lib/core/SingleAgentClient.d.mts +3 -1
  14. package/dist/lib/core/SingleAgentClient.d.ts +3 -1
  15. package/dist/lib/core/SingleAgentClient.d.ts.map +1 -1
  16. package/dist/lib/core/SingleAgentClient.js +158 -39
  17. package/dist/lib/core/SingleAgentClient.js.map +1 -1
  18. package/dist/lib/core/SingleAgentClient.mjs +167 -40
  19. package/dist/lib/core/SingleAgentClient.mjs.map +1 -1
  20. package/dist/lib/core/TaskExecutor.d.mts +57 -2
  21. package/dist/lib/core/TaskExecutor.d.ts +57 -2
  22. package/dist/lib/core/TaskExecutor.d.ts.map +1 -1
  23. package/dist/lib/core/TaskExecutor.js +382 -44
  24. package/dist/lib/core/TaskExecutor.js.map +1 -1
  25. package/dist/lib/core/TaskExecutor.mjs +382 -45
  26. package/dist/lib/core/TaskExecutor.mjs.map +1 -1
  27. package/dist/lib/core/request-proposals-guard.d.mts +11 -0
  28. package/dist/lib/core/request-proposals-guard.d.ts +12 -0
  29. package/dist/lib/core/request-proposals-guard.d.ts.map +1 -0
  30. package/dist/lib/core/request-proposals-guard.js +65 -0
  31. package/dist/lib/core/request-proposals-guard.js.map +1 -0
  32. package/dist/lib/core/request-proposals-guard.mjs +39 -0
  33. package/dist/lib/core/request-proposals-guard.mjs.map +1 -0
  34. package/dist/lib/core/webhook-registration.d.mts +5 -0
  35. package/dist/lib/core/webhook-registration.d.ts +5 -0
  36. package/dist/lib/core/webhook-registration.d.ts.map +1 -1
  37. package/dist/lib/core/webhook-registration.js +13 -0
  38. package/dist/lib/core/webhook-registration.js.map +1 -1
  39. package/dist/lib/core/webhook-registration.mjs +13 -0
  40. package/dist/lib/core/webhook-registration.mjs.map +1 -1
  41. package/dist/lib/media-buy/compatibility.d.mts +45 -10
  42. package/dist/lib/media-buy/compatibility.d.ts +45 -10
  43. package/dist/lib/media-buy/compatibility.d.ts.map +1 -1
  44. package/dist/lib/media-buy/compatibility.js +295 -113
  45. package/dist/lib/media-buy/compatibility.js.map +1 -1
  46. package/dist/lib/media-buy/compatibility.mjs +295 -113
  47. package/dist/lib/media-buy/compatibility.mjs.map +1 -1
  48. package/dist/lib/schemas-data/v2.5/_provenance.json +1 -1
  49. package/dist/lib/testing/storyboard/validations.d.mts +1 -1
  50. package/dist/lib/testing/storyboard/validations.d.ts +1 -1
  51. package/dist/lib/types/core.generated.d.mts +334 -85
  52. package/dist/lib/types/core.generated.d.ts +334 -85
  53. package/dist/lib/types/core.generated.d.ts.map +1 -1
  54. package/dist/lib/types/core.generated.js.map +1 -1
  55. package/dist/lib/types/decline-proposals.d.ts +0 -5
  56. package/dist/lib/types/index.d.mts +2 -0
  57. package/dist/lib/types/index.d.ts +2 -0
  58. package/dist/lib/types/index.d.ts.map +1 -1
  59. package/dist/lib/types/index.js.map +1 -1
  60. package/dist/lib/types/index.mjs.map +1 -1
  61. package/dist/lib/types/request-proposals.d.ts +254 -36
  62. package/dist/lib/types/schemas.generated.d.ts +3123 -835
  63. package/dist/lib/types/schemas.generated.d.ts.map +1 -1
  64. package/dist/lib/types/schemas.generated.js +192 -85
  65. package/dist/lib/types/schemas.generated.js.map +1 -1
  66. package/dist/lib/types/schemas.generated.mjs +192 -85
  67. package/dist/lib/types/schemas.generated.mjs.map +1 -1
  68. package/dist/lib/types/tools.generated.d.mts +1 -121
  69. package/dist/lib/types/tools.generated.d.ts +1 -121
  70. package/dist/lib/types/tools.generated.d.ts.map +1 -1
  71. package/dist/lib/types/tools.generated.js.map +1 -1
  72. package/dist/lib/version.d.mts +3 -3
  73. package/dist/lib/version.d.ts +3 -3
  74. package/dist/lib/version.js +3 -3
  75. package/dist/lib/version.js.map +1 -1
  76. package/dist/lib/version.mjs +3 -3
  77. package/dist/lib/version.mjs.map +1 -1
  78. package/docs/guides/MEDIA-BUY-3.2-COMPATIBILITY.md +28 -14
  79. package/docs/llms.txt +1 -1
  80. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/media-buy/compatibility.ts"],"sourcesContent":["import { createHash, randomBytes } from 'node:crypto';\nimport type { AgentClient, CanonicalProjectionTaskOptions, ProposalRefinementTaskOptions } from '../core/AgentClient';\nimport type {\n InputHandler,\n TaskOptions,\n TaskResult,\n TaskResultCompleted,\n TaskResultFailure,\n TaskResultIntermediate,\n} from '../core/ConversationTypes';\nimport { attachMatch } from '../core/match';\nimport { generateIdempotencyKey, isValidIdempotencyKey, type MutatingRequestInput } from '../utils/idempotency';\nimport { canonicalize } from '../utils/jcs';\nimport { extractAdcpErrorInfo, extractCorrelationId } from '../utils/error-extraction';\nimport { assertValidIdempotencyReplayTtlSeconds, type AdcpCapabilities } from '../utils/capabilities';\nimport { TOOL_REQUEST_SCHEMAS } from '../utils/tool-request-schemas';\nimport type {\n AcceptProposalRequest,\n AcceptProposalResponse,\n BuyProductsRequest,\n BuyProductsResponse,\n CanonicalProduct,\n CanonicalProposal,\n ControlMediaBuyRequest,\n ControlMediaBuyResponse,\n CreateMediaBuyResponse,\n CreateMediaBuyRequest,\n DeclineProposalsRequest,\n DeclineProposalsResponse,\n GetProductsResponse,\n GetMediaBuyDeliveryRequest,\n GetMediaBuyDeliveryResponse,\n GetMediaBuysRequest,\n GetMediaBuysResponse,\n ListProductsRequest,\n ListProductsResponse,\n Product,\n Proposal,\n RefineProposalsResponse,\n RequestProposalsRequest,\n RequestProposalsResponse,\n UpdateMediaBuyResponse,\n} from '../types/tools.generated';\nimport type { CompatibilityPurchaseCoordinatorInput } from '../types/core.generated';\nimport type {\n CanonicalCreateMediaBuyRequest,\n CanonicalGetProductsRequest,\n CanonicalUpdateMediaBuyRequest,\n} from '../v2/projection/creative-delivery';\nimport type { RefineProposalsInput } from '../negotiation/types';\nimport {\n assertRefineProposalsResponse,\n isStrictDateTime,\n proposalTermsDigest,\n validateRefineProposalsResponseShape,\n} from '../negotiation/verification';\nimport { isAdcpOperationSuccess } from '../utils/response-unwrapper';\nimport { ConfigurationError } from '../errors';\nimport { createAbortError, isAbortOrTimeoutError, MAX_TIMER_DELAY_MS, withAbortSignal } from '../protocols/abort';\nimport { formatIssues, validateResponse } from '../validation/schema-validator';\nimport { validateRequest } from '../validation/schema-validator';\nimport {\n createInMemoryLegacyPurchaseContinuationStore,\n type LegacyPurchaseClaim,\n type LegacyPurchaseBinding,\n type LegacyPurchaseContinuationRecord,\n type LegacyPurchaseContinuationStore,\n type LegacyPurchaseLoss,\n type LegacyPurchaseSourceVersion,\n type LegacyPurchaseTerminalResult,\n type ReconcileLegacyPurchase,\n} from './legacy-purchase-continuation';\n\nexport type MediaBuyLifecycle = 'compact' | 'established';\nexport type MediaBuyCompatibility = 'native' | 'lossless_projection' | 'lossy_projection';\ntype CompactLifecycleToolName =\n | 'list_products'\n | 'request_proposals'\n | 'refine_proposals'\n | 'decline_proposals'\n | 'buy_products'\n | 'accept_proposal'\n | 'control_media_buy';\n\nconst LIST_PRODUCTS_FIELDS = new Set([\n 'account',\n 'adcp_major_version',\n 'adcp_version',\n 'brand',\n 'context',\n 'context_id',\n 'criteria',\n 'cursor',\n 'fields',\n 'governance_context',\n 'idempotency_key',\n 'if_feed_version',\n 'if_pricing_version',\n 'max_results',\n 'push_notification_config',\n]);\nconst REQUEST_PROPOSALS_FIELDS = new Set([\n 'account',\n 'adcp_major_version',\n 'adcp_version',\n 'brand',\n 'brief',\n 'context',\n 'context_id',\n 'criteria',\n 'governance_context',\n 'idempotency_key',\n 'opportunity',\n 'push_notification_config',\n]);\nconst REFINE_PROPOSALS_FIELDS = new Set([\n 'adcp_major_version',\n 'adcp_version',\n 'context',\n 'context_id',\n 'governance_context',\n 'idempotency_key',\n 'push_notification_config',\n 'refinements',\n]);\nconst DECLINE_PROPOSALS_FIELDS = new Set([\n 'adcp_major_version',\n 'adcp_version',\n 'context',\n 'context_id',\n 'declines',\n 'governance_context',\n 'idempotency_key',\n 'opportunity',\n 'push_notification_config',\n]);\nconst BUY_PRODUCTS_FIELDS = new Set([\n 'account',\n 'adcp_major_version',\n 'adcp_version',\n 'advertiser_industry',\n 'agency_estimate_number',\n 'bidding',\n 'brand',\n 'budget_allocation',\n 'budget_cap_timezone',\n 'context',\n 'daily_budget_cap',\n 'end_time',\n 'ext',\n 'feed_version',\n 'governance_context',\n 'idempotency_key',\n 'invoice_recipient',\n 'opportunity',\n 'pacing',\n 'paused',\n 'pricing_version',\n 'purchase_order_ref',\n 'purchases',\n 'push_notification_config',\n 'reporting_webhook',\n 'start_time',\n 'total_budget',\n]);\nconst ACCEPT_PROPOSAL_FIELDS = new Set([\n 'account',\n 'adcp_major_version',\n 'adcp_version',\n 'budget_cap_timezone',\n 'context',\n 'daily_budget_cap',\n 'ext',\n 'established_fallback',\n 'governance_context',\n 'idempotency_key',\n 'io_acceptance',\n 'opportunity',\n 'proposal_id',\n 'proposal_terms_digest',\n 'purchase_order_ref',\n 'push_notification_config',\n 'reporting_webhook',\n 'total_budget',\n]);\nconst CONTROL_MEDIA_BUY_FIELDS = new Set([\n 'account',\n 'adcp_major_version',\n 'adcp_version',\n 'bidding',\n 'budget_allocation',\n 'budget_cap_timezone',\n 'canceled',\n 'cancellation_reason',\n 'context',\n 'daily_budget_cap',\n 'ext',\n 'governance_context',\n 'idempotency_key',\n 'media_buy_id',\n 'pacing',\n 'packages',\n 'paused',\n 'push_notification_config',\n 'reporting_webhook',\n 'revision',\n 'total_budget',\n]);\nconst V25_OFFER_FILTER_FIELDS = new Set([\n 'budget_range',\n 'channels',\n 'countries',\n 'delivery_type',\n 'end_date',\n 'is_fixed_price',\n 'min_exposures',\n 'standard_formats_only',\n 'start_date',\n]);\nconst V30_OFFER_FILTER_FIELDS = new Set([\n ...V25_OFFER_FILTER_FIELDS,\n 'exclusivity',\n 'required_performance_standards',\n 'trusted_match',\n]);\nconst V31_OFFER_FILTER_FIELDS = new Set([\n ...V30_OFFER_FILTER_FIELDS,\n 'audio_distribution_types',\n 'pricing_currencies',\n 'required_metrics',\n 'required_vendor_metrics',\n 'social_placement_surfaces',\n 'sponsored_placement_types',\n 'video_placement_types',\n]);\nconst V30_PURCHASE_FIELDS = new Set([\n 'agency_estimate_number',\n 'budget',\n 'context',\n 'end_time',\n 'ext',\n 'impressions',\n 'pacing',\n 'pricing_option_id',\n 'product_id',\n 'start_time',\n 'targeting_overlay',\n]);\nconst V25_PURCHASE_FIELDS = new Set([\n 'budget',\n 'ext',\n 'impressions',\n 'pacing',\n 'pricing_option_id',\n 'product_id',\n 'targeting_overlay',\n]);\nconst V31_PURCHASE_FIELDS = new Set([...V30_PURCHASE_FIELDS, 'format_option_refs']);\nconst V32_PURCHASE_FIELDS = new Set([\n ...V31_PURCHASE_FIELDS,\n 'audience_evidence_pins',\n 'audience_evidence_requirements',\n 'bidding',\n 'daily_budget_cap',\n 'min_spend_target',\n]);\nconst V30_TARGETING_FIELDS = new Set([\n 'age_restriction',\n 'audience_exclude',\n 'audience_include',\n 'axe_exclude_segment',\n 'axe_include_segment',\n 'collection_list',\n 'collection_list_exclude',\n 'daypart_targets',\n 'device_platform',\n 'device_type',\n 'device_type_exclude',\n 'frequency_cap',\n 'geo_countries',\n 'geo_countries_exclude',\n 'geo_metros',\n 'geo_metros_exclude',\n 'geo_postal_areas',\n 'geo_postal_areas_exclude',\n 'geo_proximity',\n 'geo_regions',\n 'geo_regions_exclude',\n 'keyword_targets',\n 'language',\n 'negative_keywords',\n 'property_list',\n 'store_catchments',\n]);\nconst V31_TARGETING_FIELDS = new Set([...V30_TARGETING_FIELDS, 'signal_targeting', 'signal_targeting_groups']);\nconst V30_POSTAL_SYSTEMS = new Set([\n 'us_zip',\n 'us_zip_plus_four',\n 'gb_outward',\n 'gb_full',\n 'ca_fsa',\n 'ca_full',\n 'de_plz',\n 'fr_code_postal',\n 'au_postcode',\n 'ch_plz',\n 'at_plz',\n]);\nconst V30_METRO_SYSTEMS = new Set(['nielsen_dma', 'uk_itl1', 'uk_itl2', 'eurostat_nuts2', 'custom']);\nconst V31_TIME_GRANULARITIES = new Set(['hourly', 'daily', 'monthly']);\nconst V30_AVAILABLE_METRICS = new Set([\n 'impressions',\n 'spend',\n 'clicks',\n 'ctr',\n 'video_completions',\n 'completion_rate',\n 'conversions',\n 'conversion_value',\n 'roas',\n 'cost_per_acquisition',\n 'new_to_brand_rate',\n 'viewability',\n 'engagement_rate',\n 'views',\n 'completed_views',\n 'leads',\n 'reach',\n 'frequency',\n 'grps',\n 'quartile_data',\n 'dooh_metrics',\n 'cost_per_click',\n]);\nconst V25_AVAILABLE_METRICS = new Set([\n 'impressions',\n 'spend',\n 'clicks',\n 'ctr',\n 'video_completions',\n 'completion_rate',\n 'conversions',\n 'viewability',\n 'engagement_rate',\n]);\nconst V31_AVAILABLE_METRICS = new Set([\n 'impressions',\n 'spend',\n 'clicks',\n 'ctr',\n 'views',\n 'completed_views',\n 'completion_rate',\n 'conversions',\n 'conversion_value',\n 'roas',\n 'cost_per_acquisition',\n 'new_to_brand_rate',\n 'leads',\n 'reach',\n 'frequency',\n 'grps',\n 'engagements',\n 'engagement_rate',\n 'follows',\n 'saves',\n 'profile_visits',\n 'viewability',\n 'quartile_data',\n 'dooh_metrics',\n 'cost_per_click',\n 'cost_per_completed_view',\n 'cpm',\n 'downloads',\n 'units_sold',\n 'new_to_brand_units',\n 'plays',\n 'incremental_sales_lift',\n 'brand_lift',\n 'foot_traffic',\n 'conversion_lift',\n 'brand_search_lift',\n]);\nconst V30_PRODUCT_FIELDS = new Set([\n 'product_id',\n 'name',\n 'description',\n 'publisher_properties',\n 'channels',\n 'placements',\n 'delivery_type',\n 'exclusivity',\n 'pricing_options',\n 'forecast',\n 'reporting_capabilities',\n 'catalog_types',\n 'max_optimization_goals',\n 'catalog_match',\n 'brief_relevance',\n 'expires_at',\n]);\nconst V31_PRODUCT_FIELDS = new Set([\n ...V30_PRODUCT_FIELDS,\n 'video_placement_types',\n 'audio_distribution_types',\n 'sponsored_placement_types',\n 'social_placement_surfaces',\n 'format_options',\n 'signal_targeting_allowed',\n 'signal_targeting_rules',\n]);\nconst LEGACY_REPORTING_DIMENSIONS = new Set(['geo', 'device_type', 'device_platform', 'audience', 'placement']);\nconst ESTABLISHED_TOOL_FOR_COMPACT: Readonly<Record<CompactLifecycleToolName, string>> = {\n list_products: 'get_products',\n request_proposals: 'get_products',\n refine_proposals: 'get_products',\n decline_proposals: 'get_products',\n buy_products: 'create_media_buy',\n accept_proposal: 'create_media_buy',\n control_media_buy: 'update_media_buy',\n};\n\n/** Guarantees that the established lifecycle cannot enforce atomically. */\nexport type MediaBuyCompatibilityLoss =\n | 'feed_version_not_atomic'\n | 'pricing_version_not_atomic'\n | 'proposal_terms_digest_not_enforced'\n | 'proposal_terms_digest_unavailable'\n | 'proposal_snapshot_not_immutable'\n | 'proposal_hold_not_verifiable'\n | 'revision_not_atomic'\n | 'proposal_decline_not_terminal'\n | 'proposal_decline_reason_not_forwarded';\n\nexport interface MediaBuyCompatibilityReport {\n negotiated_version: string;\n lifecycle: MediaBuyLifecycle;\n tools_used: string[];\n compatibility: MediaBuyCompatibility;\n warnings: string[];\n losses: MediaBuyCompatibilityLoss[];\n}\n\ntype WithCompatibility<T> = T & { compatibility: MediaBuyCompatibilityReport };\n\nexport type CompatibilityDeferredContinuation<TCompleted, TWire> = Omit<\n NonNullable<TaskResultIntermediate<TWire>['deferred']>,\n 'resume'\n> & {\n resume: (input: unknown) => Promise<CompatibilityTaskResult<TCompleted, TWire>>;\n};\n\nexport type CompatibilitySubmittedContinuation<TCompleted, TWire> = Omit<\n NonNullable<TaskResultIntermediate<TWire>['submitted']>,\n 'waitForCompletion'\n> & {\n waitForCompletion: (\n pollInterval?: number,\n signal?: AbortSignal\n ) => Promise<CompatibilityTaskResult<TCompleted, TWire>>;\n};\n\ntype CompatibilityTaskResultIntermediate<TCompleted, TWire> = Omit<\n TaskResultIntermediate<TWire>,\n 'deferred' | 'submitted'\n> & {\n deferred?: CompatibilityDeferredContinuation<TCompleted, TWire>;\n submitted?: CompatibilitySubmittedContinuation<TCompleted, TWire>;\n};\n\n/**\n * A projected compatibility result is status-aware: completed success data is\n * the stable compatibility view, while non-terminal and failure data remains\n * the SDK-returned compact or canonical-established source shape until a\n * completed result can be projected.\n */\nexport type CompatibilityTaskResult<TCompleted, TWire = TCompleted> =\n | WithCompatibility<TaskResultCompleted<TCompleted>>\n | WithCompatibility<CompatibilityTaskResultIntermediate<TCompleted, TWire>>\n | WithCompatibility<TaskResultFailure<TWire>>;\n\nexport type CompatibleProduct = Product | CanonicalProduct;\nexport type CompatibleProposal = Proposal | CanonicalProposal;\n\ntype CompactRefinementResult = NonNullable<RefineProposalsResponse['results']>[number];\ntype CompactRevisedResult = Extract<CompactRefinementResult, { outcome: 'revised' }>;\ntype CompactPartialResult = Extract<CompactRefinementResult, { outcome: 'partial' }>;\ntype CompactFinalizedResult = Extract<CompactRefinementResult, { outcome: 'finalized' }>;\ntype CompactUnableResult = Extract<CompactRefinementResult, { outcome: 'unable' }>;\n\n/**\n * Refine result with the canonical proposal base exposed at the coordinator\n * boundary. The generated response keeps the native outcome discriminants;\n * this compatibility view additionally makes the canonical proposal fields\n * explicit for callers on every proposal-bearing result arm.\n */\nexport type CompatibleRefinementResult =\n | (Omit<CompactRevisedResult, 'proposals'> & {\n proposals: (CanonicalProposal & { proposal_status: 'draft'; parent_proposal_id: string })[];\n })\n | (Omit<CompactPartialResult, 'proposals'> & {\n proposals: (CanonicalProposal & { proposal_status: 'draft'; parent_proposal_id: string })[];\n })\n | (Omit<CompactFinalizedResult, 'proposal'> & {\n proposal: CanonicalProposal & {\n proposal_status: 'committed';\n parent_proposal_id: string;\n expires_at: string;\n };\n })\n | CompactUnableResult;\n\nexport type CompatibleDeclineResult =\n | { proposal_id: string; outcome: 'declined' }\n | { proposal_id: string; outcome: 'unable'; reason: string };\nexport type CompatibleProjectedDeclineResult = {\n proposal_id: string;\n /** Legacy get_products omit is not a seller-confirmed terminal decline. */\n outcome: 'unconfirmed';\n};\n\ntype CompatibleErrors =\n | NonNullable<GetProductsResponse['errors']>\n | NonNullable<RequestProposalsResponse['errors']>\n | NonNullable<RefineProposalsResponse['errors']>\n | NonNullable<DeclineProposalsResponse['errors']>;\ntype CompatibleContext =\n | NonNullable<GetProductsResponse['context']>\n | NonNullable<ListProductsResponse['context']>\n | NonNullable<RequestProposalsResponse['context']>\n | NonNullable<RefineProposalsResponse['context']>\n | NonNullable<DeclineProposalsResponse['context']>;\n\nexport interface CompatibleProductsResponse {\n /** Present only when the seller returned product rows (conditional reads may return only `unchanged`). */\n products?: CompatibleProduct[];\n proposals?: CompatibleProposal[];\n feed_version?: string;\n pricing_version?: string;\n unchanged?: true;\n /** Lifecycle-neutral cursor for the next page. */\n next_cursor?: string;\n pagination?: GetProductsResponse['pagination'];\n cache_scope?: 'public' | 'account';\n errors?: CompatibleErrors;\n context?: CompatibleContext;\n /** SDK-returned source object, retained for fields outside the stable compatibility view. */\n raw: ListProductsResponse | EstablishedProductsWireResponse;\n}\n\ninterface CompatibleProposalResponseBase {\n proposals?: CompatibleProposal[];\n products?: CompatibleProduct[];\n errors?: CompatibleErrors;\n context?: CompatibleContext;\n}\n\nexport interface CompatibleRequestProposalsResponse extends CompatibleProposalResponseBase {\n operation: 'request';\n /** `legacy_unavailable` never overstates an empty legacy response as a seller rejection. */\n outcome: 'proposed' | 'products_available' | 'rejected' | 'legacy_unavailable';\n reason?: string;\n suggestions?: string[];\n incomplete?: RequestProposalsResponse['incomplete'];\n purchase_continuation?: RequestProposalsResponse['purchase_continuation'];\n raw: RequestProposalsResponse | EstablishedProductsWireResponse;\n}\n\nexport interface CompatibleRefineProposalsResponse extends CompatibleProposalResponseBase {\n operation: 'refine';\n /** Native result arms remain available in `results`; legacy projection is explicitly named. */\n outcome: 'native_results' | 'legacy_projected' | 'legacy_unavailable';\n results?: CompatibleRefinementResult[];\n reason?: string;\n suggestions?: string[];\n raw: RefineProposalsResponse | EstablishedProductsWireResponse;\n}\n\nexport interface CompatibleDeclineProposalsResponse extends CompatibleProposalResponseBase {\n operation: 'decline';\n outcome: 'native_results' | 'legacy_unconfirmed';\n results: (CompatibleDeclineResult | CompatibleProjectedDeclineResult)[];\n raw: DeclineProposalsResponse | EstablishedProductsWireResponse;\n}\n\nexport type CompatibleProposalResponse =\n | CompatibleRequestProposalsResponse\n | CompatibleRefineProposalsResponse\n | CompatibleDeclineProposalsResponse;\n\ntype TaskResultData<TResult> = TResult extends TaskResult<infer TData> ? TData : never;\n/** Canonical SDK source returned by established `get_products`, including projection diagnostics. */\nexport type EstablishedProductsWireResponse = TaskResultData<Awaited<ReturnType<AgentClient['getProducts']>>>;\n\n/** SDK-returned source data retained before a completed list response is projected. */\nexport type CompatibleProductsWireResponse =\n | TaskResultData<Awaited<ReturnType<AgentClient['listProducts']>>>\n | EstablishedProductsWireResponse;\n/** SDK-returned source data retained while a proposal request is non-terminal or failed. */\nexport type CompatibleRequestProposalsWireResponse =\n | TaskResultData<Awaited<ReturnType<AgentClient['requestProposals']>>>\n | EstablishedProductsWireResponse;\n/** SDK-returned source data retained while proposal refinement is non-terminal or failed. */\nexport type CompatibleRefineProposalsWireResponse =\n | TaskResultData<Awaited<ReturnType<AgentClient['refineProposals']>>>\n | EstablishedProductsWireResponse;\n/** SDK-returned source data retained while proposal decline is non-terminal or failed. */\nexport type CompatibleDeclineProposalsWireResponse =\n | TaskResultData<Awaited<ReturnType<AgentClient['declineProposals']>>>\n | EstablishedProductsWireResponse;\n\nexport interface MediaBuyLifecycleCoordinatorOptions {\n /** Prefer compact when advertised. Established is useful for a dual-surface test lane. */\n preferredLifecycle?: 'auto' | MediaBuyLifecycle;\n /** Named representational losses explicitly accepted for legacy mutations. */\n allowedLosses?: readonly MediaBuyCompatibilityLoss[];\n /**\n * Stable, non-secret, server-controlled identity for the authenticated\n * principal/tenant that owns this coordinator. Never derive it from buyer\n * request content. It salts proposal snapshots so multi-tenant runners\n * cannot reuse a snapshot across principals. Required for established\n * proposal acceptance; without it snapshots are not retained.\n */\n principalScope?: string;\n /**\n * Stable, non-secret identity for the authenticated seller/account session.\n * Persist and reuse it when a coordinator is rehydrated. It is required for\n * AdCP 2.5 sellers that do not provide a server context ID.\n */\n legacyPurchaseSellerSessionScope?: string;\n /** Durable storage for products-only legacy purchase continuations. */\n legacyPurchaseContinuationStore?: LegacyPurchaseContinuationStore;\n /** Lifetime of a projected continuation. Defaults to five minutes. */\n legacyPurchaseContinuationTtlMs?: number;\n /** Age after which an unresolved claim is reconciled instead of reported in-flight. */\n legacyPurchaseClaimTimeoutMs?: number;\n /** Bounded deterministic-replay window after the first claim. Defaults to 24 hours. */\n legacyPurchaseOperationTtlMs?: number;\n /** Application-owned authoritative reconciliation for ambiguous legacy creates. */\n reconcileLegacyPurchase?: ReconcileLegacyPurchase;\n}\n\nexport type LegacyPurchaseContinuationErrorCode =\n | 'not_found'\n | 'expired'\n | 'binding_mismatch'\n | 'selection_mismatch'\n | 'loss_mismatch'\n | 'request_invalid'\n | 'conflict'\n | 'in_flight'\n | 'ambiguous'\n | 'store_error';\n\n/** Fail-closed local error raised before a legacy create is sent or replayed. */\nexport class LegacyPurchaseContinuationError extends Error {\n readonly name = 'LegacyPurchaseContinuationError';\n\n constructor(\n readonly code: LegacyPurchaseContinuationErrorCode,\n message: string,\n readonly retryable = false,\n readonly recovery?: string,\n cause?: unknown\n ) {\n super(message, cause === undefined ? undefined : { cause });\n }\n}\n\n/**\n * Inputs the established create_media_buy proposal path requires but the\n * compact accept_proposal request intentionally does not repeat. Callers may\n * supply this on every compatibility-facade acceptance: compact sellers ignore\n * it, while established sellers use it without pretending it came from the\n * seller's proposal snapshot.\n */\nexport interface EstablishedProposalAcceptanceFallback {\n brand: CanonicalCreateMediaBuyRequest['brand'];\n start_time: CanonicalCreateMediaBuyRequest['start_time'];\n end_time: CanonicalCreateMediaBuyRequest['end_time'];\n}\n\n/**\n * Compatibility-facade acceptance input. A digest remains mandatory on the\n * native compact lane. It is optional only for an established lane whose\n * missing digest/snapshot guarantees have been explicitly accepted.\n */\nexport type CompatibleAcceptProposalRequest = Omit<AcceptProposalRequest, 'proposal_terms_digest'> & {\n proposal_terms_digest?: string;\n established_fallback?: EstablishedProposalAcceptanceFallback;\n};\n\nexport interface MediaBuyLifecycleCompatibilityErrorOptions {\n operation: string;\n negotiatedVersion: string;\n lifecycle: MediaBuyLifecycle;\n feature: string;\n message: string;\n losses?: readonly MediaBuyCompatibilityLoss[];\n recovery?: string;\n code?: 'UNSUPPORTED_FEATURE' | 'PROPOSAL_DIGEST_MISMATCH';\n}\n\n/** Structured preflight failure raised before an incompatible mutation is sent. */\nexport class MediaBuyLifecycleCompatibilityError extends Error {\n readonly name = 'MediaBuyLifecycleCompatibilityError';\n readonly code: 'UNSUPPORTED_FEATURE' | 'PROPOSAL_DIGEST_MISMATCH';\n readonly operation: string;\n readonly negotiatedVersion: string;\n readonly lifecycle: MediaBuyLifecycle;\n readonly feature: string;\n readonly losses: readonly MediaBuyCompatibilityLoss[];\n readonly recovery: string;\n\n constructor(options: MediaBuyLifecycleCompatibilityErrorOptions) {\n super(options.message);\n this.code = options.code ?? 'UNSUPPORTED_FEATURE';\n this.operation = options.operation;\n this.negotiatedVersion = options.negotiatedVersion;\n this.lifecycle = options.lifecycle;\n this.feature = options.feature;\n this.losses = options.losses ?? [];\n this.recovery =\n options.recovery ??\n 'Remove the unsupported compact guarantee, select a compact-capable seller, or explicitly allow the named loss.';\n }\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : {};\n}\n\nfunction safeDiagnostic(value: unknown, maxLength: number): string {\n const raw = String(value);\n const escaped = raw.replace(/[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]/gu, character => {\n const code = character.codePointAt(0) ?? 0;\n return `\\\\u${code.toString(16).padStart(4, '0')}`;\n });\n return escaped.length > maxLength ? `${escaped.slice(0, maxLength - 1)}…` : escaped;\n}\n\nfunction requestFingerprint(value: unknown): string {\n return createHash('sha256').update(canonicalize(value)).digest('base64url');\n}\n\nfunction retiredAcceptancePositions(key: string, salt: Uint8Array, bitCount: number): number[] {\n const digest = createHash('sha256').update(salt).update(key).digest();\n return [0, 4, 8, 12, 16, 20, 24, 28].map(offset => digest.readUInt32BE(offset) % bitCount);\n}\n\nfunction array(value: unknown): unknown[] {\n return Array.isArray(value) ? value : [];\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nconst CREDENTIAL_SHAPED_KEYS = new Set([\n 'authorization',\n 'credential',\n 'credentials',\n 'token',\n 'authtoken',\n 'apikey',\n 'password',\n 'secret',\n 'clientsecret',\n 'refreshtoken',\n 'accesstoken',\n 'bearer',\n 'sessiontoken',\n 'privatekey',\n 'signingkey',\n 'jwt',\n 'signature',\n 'signedpayload',\n 'cookie',\n 'setcookie',\n]);\n\nfunction isCredentialShapedKey(key: string): boolean {\n return CREDENTIAL_SHAPED_KEYS.has(key.replace(/[-_]/g, '').toLowerCase());\n}\n\nfunction containsCredentialShapedKey(value: unknown, seen = new WeakSet<object>()): boolean {\n if (value === null || typeof value !== 'object') return false;\n if (seen.has(value)) return false;\n seen.add(value);\n if (Array.isArray(value)) return value.some(item => containsCredentialShapedKey(item, seen));\n return Object.entries(value).some(\n ([key, nested]) => isCredentialShapedKey(key) || containsCredentialShapedKey(nested, seen)\n );\n}\n\nfunction containsPresignedUrl(value: unknown, seen = new WeakSet<object>()): boolean {\n if (typeof value === 'string') {\n try {\n const url = new URL(value);\n const sensitiveQueryKeys = new Set([\n 'x-amz-credential',\n 'x-amz-signature',\n 'x-goog-credential',\n 'x-goog-signature',\n 'signature',\n 'sig',\n 'token',\n 'access_token',\n ]);\n return [...url.searchParams.keys()].some(key => sensitiveQueryKeys.has(key.toLowerCase()));\n } catch {\n return false;\n }\n }\n if (value === null || typeof value !== 'object') return false;\n if (seen.has(value)) return false;\n seen.add(value);\n return Object.values(value).some(nested => containsPresignedUrl(nested, seen));\n}\n\ninterface ParsedRelease {\n major: number;\n minor: number;\n patch: number;\n prerelease?: string;\n}\n\nfunction parseRelease(value: string): ParsedRelease | undefined {\n const match = /^v?(\\d+)\\.(\\d+)(?:\\.(\\d+))?(?:-([A-Za-z0-9.-]+))?(?:\\+[A-Za-z0-9.-]+)?$/.exec(value.trim());\n if (!match) return undefined;\n return {\n major: Number(match[1]),\n minor: Number(match[2]),\n patch: Number(match[3] ?? 0),\n ...(match[4] !== undefined && { prerelease: match[4] }),\n };\n}\n\nfunction comparePrerelease(left: string | undefined, right: string | undefined): number {\n if (left === right) return 0;\n if (left === undefined) return 1;\n if (right === undefined) return -1;\n const leftParts = left.split('.');\n const rightParts = right.split('.');\n for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {\n const a = leftParts[index];\n const b = rightParts[index];\n if (a === undefined) return -1;\n if (b === undefined) return 1;\n if (a === b) continue;\n const aNumeric = /^\\d+$/.test(a);\n const bNumeric = /^\\d+$/.test(b);\n if (aNumeric && bNumeric) return Number(a) - Number(b);\n if (aNumeric !== bNumeric) return aNumeric ? -1 : 1;\n return a.localeCompare(b);\n }\n return 0;\n}\n\nfunction compareRelease(left: string, right: string): number {\n const a = parseRelease(left);\n const b = parseRelease(right);\n if (!a || !b) return 0;\n return a.major - b.major || a.minor - b.minor || a.patch - b.patch || comparePrerelease(a.prerelease, b.prerelease);\n}\n\nfunction isCompactRelease(value: string): boolean {\n const release = parseRelease(value);\n return release !== undefined && (release.major > 3 || (release.major === 3 && release.minor >= 2));\n}\n\nfunction negotiatedVersion(capabilities: AdcpCapabilities, clientVersion: string): string {\n if (capabilities.version === 'v2') return '2.5';\n if (capabilities.servedVersion && parseRelease(capabilities.servedVersion)) {\n if (compareRelease(capabilities.servedVersion, clientVersion) > 0) {\n const displayedServedVersion = capabilities.servedVersion.slice(0, 64);\n throw new ConfigurationError(\n `The seller served AdCP ${displayedServedVersion}, which is newer than the client pin ${clientVersion}; the response cannot be interpreted safely.`\n );\n }\n return capabilities.servedVersion;\n }\n const advertisedVersions = capabilities.supportedVersions?.filter(version => parseRelease(version) !== undefined);\n const candidates = advertisedVersions?.filter(\n version => parseRelease(version) !== undefined && compareRelease(version, clientVersion) <= 0\n );\n if (candidates?.length) return [...candidates].sort(compareRelease).at(-1)!;\n if (advertisedVersions?.length) {\n throw new ConfigurationError(\n `The seller advertises only AdCP versions newer than the client pin ${clientVersion}; no compatible wire version can be negotiated.`\n );\n }\n if (capabilities._synthetic && capabilities.mediaBuyLifecycleTools?.length && isCompactRelease(clientVersion)) {\n // Compact tool names are authoritative wire evidence. A failed\n // capabilities call must not route a compact-only seller to aliases it\n // does not expose.\n return clientVersion;\n }\n // AdCP 3.0 predates release-precision capability metadata. A real v3\n // capability response with none of the fields above is therefore a 3.0\n // lane; reporting the client's newer pin would overstate the wire release.\n return '3.0';\n}\n\nconst MAX_PROPOSAL_TRAVERSAL_NODES = 4096;\nconst LEGACY_PROPOSAL_RAW = Symbol('legacyProposalRaw');\nconst LEGACY_PURCHASE_CLIENT_SCOPES = new WeakMap<AgentClient, string>();\nconst COMPACT_REQUEST_PROPOSALS_RESPONSE_FIELDS = new Set([\n 'adcp_version',\n 'outcome',\n 'reason',\n 'suggestions',\n 'proposals',\n 'products',\n 'incomplete',\n 'purchase_continuation',\n 'targeting_resolution',\n 'status',\n 'task_id',\n 'message',\n 'errors',\n 'context',\n 'ext',\n 'replayed',\n]);\nconst COMPACT_DECLINE_PROPOSALS_RESPONSE_FIELDS = new Set([\n 'adcp_version',\n 'results',\n 'status',\n 'task_id',\n 'message',\n 'errors',\n 'context',\n 'ext',\n 'replayed',\n]);\n\nfunction projectProducts(data: unknown, lifecycle: MediaBuyLifecycle): CompatibleProductsResponse {\n const source = compactWirePayload(data);\n const feedVersion = optionalString(lifecycle === 'compact' ? source.feed_version : source.wholesale_feed_version);\n const pricingVersion = optionalString(source.pricing_version);\n const nextCursor = optionalString(lifecycle === 'compact' ? source.next_cursor : record(source.pagination).cursor);\n return {\n ...(Array.isArray(source.products) && { products: source.products as CompatibleProduct[] }),\n ...(Array.isArray(source.proposals) && { proposals: source.proposals as CompatibleProposal[] }),\n ...(feedVersion && { feed_version: feedVersion }),\n ...(pricingVersion && { pricing_version: pricingVersion }),\n ...((source.unchanged === true || source.outcome === 'unchanged') && { unchanged: true as const }),\n ...(nextCursor && { next_cursor: nextCursor }),\n ...(source.pagination !== undefined && { pagination: source.pagination as GetProductsResponse['pagination'] }),\n ...((source.cache_scope === 'public' || source.cache_scope === 'account') && {\n cache_scope: source.cache_scope,\n }),\n ...(Array.isArray(source.errors) && { errors: source.errors as CompatibleErrors }),\n ...(source.context !== undefined && { context: source.context as CompatibleContext }),\n raw: source as ListProductsResponse | EstablishedProductsWireResponse,\n };\n}\n\nfunction proposalRows(source: Record<string, unknown>): CompatibleProposal[] | undefined {\n const proposals: CompatibleProposal[] = [];\n let sawProposalContainer = false;\n const roots: unknown[] = [];\n if (source.proposals !== undefined) roots.push(source.proposals);\n if (source.proposal !== undefined) roots.push(source.proposal);\n const results = array(source.results);\n if (results.length > MAX_PROPOSAL_TRAVERSAL_NODES) {\n throw new TypeError('proposal response exceeded the bounded traversal limit.');\n }\n for (const result of results) {\n const row = record(result);\n if (row.proposals !== undefined) roots.push(row.proposals);\n if (row.proposal !== undefined) roots.push(row.proposal);\n }\n const stack = roots.reverse();\n const seen = new WeakSet<object>();\n let visited = 0;\n while (stack.length > 0) {\n const value = stack.pop();\n if (value === null || typeof value !== 'object' || seen.has(value)) continue;\n seen.add(value);\n visited += 1;\n if (visited > MAX_PROPOSAL_TRAVERSAL_NODES) {\n throw new TypeError('proposal response exceeded the bounded traversal limit.');\n }\n if (Array.isArray(value)) {\n sawProposalContainer = true;\n if (stack.length + value.length > MAX_PROPOSAL_TRAVERSAL_NODES) {\n throw new TypeError('proposal response exceeded the bounded traversal limit.');\n }\n for (let index = value.length - 1; index >= 0; index -= 1) stack.push(value[index]);\n continue;\n }\n const candidate = value as Record<string, unknown>;\n if (optionalString(candidate.proposal_id)) {\n sawProposalContainer = true;\n proposals.push(candidate as CompatibleProposal);\n }\n // Reverse push preserves the prior depth-first proposals-then-proposal order.\n if (candidate.proposal !== undefined) stack.push(candidate.proposal);\n if (candidate.proposals !== undefined) stack.push(candidate.proposals);\n }\n return sawProposalContainer ? proposals : undefined;\n}\n\nfunction proposalResponseBase(source: Record<string, unknown>): CompatibleProposalResponseBase {\n const proposals = proposalRows(source);\n return {\n ...(proposals !== undefined && { proposals }),\n ...(Array.isArray(source.products) && { products: source.products as CompatibleProduct[] }),\n ...(Array.isArray(source.errors) && { errors: source.errors as CompatibleErrors }),\n ...(source.context !== undefined && { context: source.context as CompatibleContext }),\n };\n}\n\n/**\n * Remove SDK-only response annotations before validating or exposing the\n * seller's wire payload. `_message` is synthesized by the response unwrapper\n * from MCP/A2A text parts after schema validation; it never crossed the AdCP\n * tool boundary and therefore must not be mistaken for an undeclared seller\n * field. Keep this allowlist deliberately narrow so seller-controlled\n * underscore fields still fail closed.\n */\nfunction compactWirePayload(data: unknown): Record<string, unknown> {\n const source = record(data);\n if (!Object.hasOwn(source, '_message')) return source;\n const { _message: _sdkMessage, ...wire } = source;\n return wire;\n}\n\nfunction assertCompactRequestProposalsCompletion(source: Record<string, unknown>, negotiatedVersion: string): void {\n const unsupportedFields = Object.keys(source).filter(field => !COMPACT_REQUEST_PROPOSALS_RESPONSE_FIELDS.has(field));\n if (unsupportedFields.length > 0) {\n throw new TypeError(\n `request_proposals returned a malformed compact completion: undeclared fields ${unsupportedFields.join(', ')}.`\n );\n }\n const normalized = source.status === undefined ? { ...source, status: 'completed' } : source;\n if (normalized.status !== 'completed' || Object.hasOwn(normalized, 'task_id')) {\n throw new TypeError(\n 'request_proposals returned a malformed compact completion: the completed sync arm must not contain submitted status or task_id.'\n );\n }\n if (source.outcome === 'products_available' || source.purchase_continuation !== undefined) {\n throw new TypeError(\n 'request_proposals returned the projection-only products_available outcome from a native compact seller.'\n );\n }\n const validation = validateResponse('request_proposals', normalized, negotiatedVersion);\n if (!validation.valid) {\n throw new TypeError(\n `request_proposals returned a malformed compact completion: ${formatIssues(validation.issues)}`\n );\n }\n}\n\nfunction projectRequestProposals(\n data: unknown,\n lifecycle: MediaBuyLifecycle,\n negotiatedVersion?: string\n): CompatibleRequestProposalsResponse {\n const source = compactWirePayload(data);\n if (lifecycle === 'compact') assertCompactRequestProposalsCompletion(source, negotiatedVersion ?? '3.2');\n const base = proposalResponseBase(source);\n const nativeOutcome = source.outcome === 'proposed' || source.outcome === 'rejected' ? source.outcome : undefined;\n const projectedProductsAvailable = lifecycle === 'established' && source.outcome === 'products_available';\n const outcome =\n nativeOutcome ??\n (projectedProductsAvailable ? 'products_available' : undefined) ??\n (lifecycle === 'established' && (base.proposals?.length ?? 0) > 0 ? 'proposed' : 'legacy_unavailable');\n return {\n ...base,\n operation: 'request',\n outcome,\n ...(typeof source.reason === 'string' && { reason: source.reason }),\n ...(Array.isArray(source.suggestions) && { suggestions: source.suggestions as string[] }),\n ...(Array.isArray(source.incomplete) && {\n incomplete: source.incomplete as RequestProposalsResponse['incomplete'],\n }),\n ...(source.purchase_continuation !== undefined && {\n purchase_continuation: source.purchase_continuation as RequestProposalsResponse['purchase_continuation'],\n }),\n raw: ((source as Record<PropertyKey, unknown>)[LEGACY_PROPOSAL_RAW] ?? source) as\n | RequestProposalsResponse\n | EstablishedProductsWireResponse,\n };\n}\n\nfunction projectRefineProposals(\n data: unknown,\n lifecycle: MediaBuyLifecycle,\n refinements: RefineProposalsInput['refinements']\n): CompatibleRefineProposalsResponse {\n const source = compactWirePayload(data);\n const proposalIds = refinements.map(refinement => refinement.proposal_id);\n if (lifecycle === 'compact') {\n // Verify the complete response root before following any seller-controlled\n // proposal container or result branch.\n assertRefineProposalsResponse({ refinements }, source);\n }\n const base = proposalResponseBase(source);\n const sourceResults = array(source.results);\n if (lifecycle === 'compact') {\n if (sourceResults.length !== proposalIds.length) {\n throw new TypeError('refine_proposals returned a different result count than the requested refinement count.');\n }\n sourceResults.forEach((value, index) => {\n const result = record(value);\n const requestedProposalId = proposalIds[index];\n const sourceProposalId = optionalString(result.source_proposal_id);\n if (requestedProposalId === undefined || sourceProposalId !== requestedProposalId) {\n throw new TypeError(\n `refine_proposals result ${index} did not identify the corresponding source proposal from the request.`\n );\n }\n const children = [...array(result.proposals), ...(result.proposal === undefined ? [] : [result.proposal])];\n if (result.outcome === 'revised' || result.outcome === 'partial' || result.outcome === 'finalized') {\n const shape = validateRefineProposalsResponseShape({ results: [result], products: [] });\n if (!shape.ok) {\n throw new TypeError(`refine_proposals result ${index} did not contain complete canonical proposal data.`);\n }\n const expectedStatus = result.outcome === 'finalized' ? 'committed' : 'draft';\n if (children.some(child => record(child).proposal_status !== expectedStatus)) {\n throw new TypeError(\n `refine_proposals result ${index} returned a proposal with an invalid status for its ${String(result.outcome)} outcome.`\n );\n }\n if (result.outcome === 'finalized' && children.some(child => !isStrictDateTime(record(child).expires_at))) {\n throw new TypeError(`refine_proposals result ${index} returned a finalized proposal without a valid expiry.`);\n }\n }\n children.forEach(child => {\n if (optionalString(record(child).parent_proposal_id) !== sourceProposalId) {\n throw new TypeError(\n `refine_proposals result ${index} returned a proposal with invalid parent_proposal_id lineage.`\n );\n }\n });\n });\n }\n const nativeResults = Array.isArray(source.results) ? (sourceResults as CompatibleRefinementResult[]) : undefined;\n const outcome =\n lifecycle === 'compact'\n ? 'native_results'\n : (base.proposals?.length ?? 0) > 0\n ? 'legacy_projected'\n : 'legacy_unavailable';\n return {\n ...base,\n operation: 'refine',\n outcome,\n ...(nativeResults !== undefined && { results: nativeResults }),\n ...(typeof source.reason === 'string' && { reason: source.reason }),\n ...(Array.isArray(source.suggestions) && { suggestions: source.suggestions as string[] }),\n raw: source as RefineProposalsResponse | EstablishedProductsWireResponse,\n };\n}\n\nfunction projectDeclineProposals(\n data: unknown,\n lifecycle: MediaBuyLifecycle,\n proposalIds: readonly string[],\n negotiatedVersion?: string\n): CompatibleDeclineProposalsResponse {\n const source = compactWirePayload(data);\n if (lifecycle === 'compact') {\n const unsupportedFields = Object.keys(source).filter(\n field => !COMPACT_DECLINE_PROPOSALS_RESPONSE_FIELDS.has(field)\n );\n if (unsupportedFields.length > 0) {\n throw new TypeError(\n `decline_proposals returned a malformed compact completion: undeclared fields ${unsupportedFields.join(', ')}.`\n );\n }\n const validation = validateResponse('decline_proposals', source, negotiatedVersion ?? '3.2');\n if (!validation.valid || validation.variant !== 'sync') {\n throw new TypeError(\n `decline_proposals returned a malformed compact completion: ${formatIssues(validation.issues)}`\n );\n }\n }\n const base = proposalResponseBase(source);\n const sourceResults = array(source.results);\n if (lifecycle === 'compact' && sourceResults.length !== proposalIds.length) {\n throw new TypeError('decline_proposals returned a different result count than the requested proposal count.');\n }\n const results =\n lifecycle === 'compact'\n ? sourceResults.map((result, index) => {\n const row = record(result);\n const requestedProposalId = proposalIds[index];\n const sellerProposalId = optionalString(row.proposal_id);\n if (requestedProposalId === undefined) {\n throw new TypeError('decline_proposals returned more result rows than requested proposals.');\n }\n if (Object.keys(row).some(key => !['proposal_id', 'outcome', 'reason'].includes(key))) {\n throw new TypeError(`decline_proposals result ${index} contained an undeclared field.`);\n }\n if (Object.hasOwn(row, 'proposal_id') && sellerProposalId === undefined) {\n throw new TypeError(`decline_proposals result ${index} contained an invalid proposal_id.`);\n }\n if (sellerProposalId !== undefined && sellerProposalId !== requestedProposalId) {\n throw new TypeError(\n `decline_proposals result ${index} identified a different proposal than the corresponding request.`\n );\n }\n if (row.outcome === 'declined') {\n if (Object.hasOwn(row, 'reason')) {\n throw new TypeError(`decline_proposals declined result ${index} must not contain a reason.`);\n }\n return { proposal_id: requestedProposalId, outcome: 'declined' as const };\n }\n if (row.outcome === 'unable') {\n const reason = optionalString(row.reason);\n if (!reason) {\n throw new TypeError(`decline_proposals unable result ${index} requires a non-empty reason.`);\n }\n return { proposal_id: requestedProposalId, outcome: 'unable' as const, reason };\n }\n throw new TypeError(`decline_proposals result ${index} contained an invalid outcome.`);\n })\n : proposalIds.map(proposal_id => ({ proposal_id, outcome: 'unconfirmed' as const }));\n return {\n ...base,\n operation: 'decline',\n outcome: lifecycle === 'compact' ? 'native_results' : 'legacy_unconfirmed',\n results,\n raw: source as DeclineProposalsResponse | EstablishedProductsWireResponse,\n };\n}\n\ninterface AcceptanceReservation {\n kind: 'native' | 'established';\n state: 'in-flight' | 'retryable' | 'retired';\n retryKind?: 'paused' | 'commit-uncertain';\n requestFingerprint: string;\n idempotencyKey?: string;\n skipIdempotencyAutoInject: boolean;\n readonly retryDeadlineMs?: number;\n taskId?: string;\n}\n\ninterface ProposalSnapshotEntry {\n proposal: Record<string, unknown>;\n bytes: number;\n principalScope: string;\n executable: boolean;\n accountScope?: string;\n canonicalTermsDigest?: string;\n acceptance?: AcceptanceReservation;\n /** Synthetic entry used only to share a native acceptance fence. */\n nativeAcceptanceOnly?: boolean;\n}\n\ninterface ProposalSnapshotStore {\n entries: Map<string, ProposalSnapshotEntry>;\n proposalAcceptances: Map<\n string,\n { snapshotKey: string; snapshot: ProposalSnapshotEntry; reservation: AcceptanceReservation }\n >;\n pendingDeclines: Set<PendingDeclineLease>;\n pendingDeclineProposalIdCount: number;\n pendingRefinements: Set<PendingRefinementLease>;\n pendingRefinementProposalIdCount: number;\n bytes: number;\n registry: ProposalSnapshotStoreRegistry;\n activeCoordinators: number;\n}\n\ninterface ProposalSnapshotStoreRegistry {\n stores: Map<string, ProposalSnapshotStore>;\n retiredAcceptanceSegments?: Map<number, Uint8Array>;\n retiredAcceptanceSalt?: Uint8Array;\n}\n\ninterface SafeProposalSnapshot {\n proposal: Record<string, unknown>;\n canonicalTermsDigest?: string;\n}\n\ntype ProposalMutationState = 'in-flight' | 'paused' | 'commit-uncertain' | 'retired';\n\ninterface ProposalMutationReservation {\n proposalIds: readonly string[];\n state: ProposalMutationState;\n requestFingerprint: string;\n idempotencyKey?: string;\n skipIdempotencyAutoInject: boolean;\n /** Fixed from the seller's advertised replay TTL at the first dispatch. */\n readonly retryDeadlineMs?: number;\n attemptEpoch: number;\n owner: object;\n timer?: ReturnType<typeof setTimeout>;\n}\n\ninterface PendingDeclineLease extends ProposalMutationReservation {\n operation: 'decline';\n}\n\ninterface PendingRefinementLease extends ProposalMutationReservation {\n operation: 'refine';\n sources: readonly { key: string; entry: ProposalSnapshotEntry }[];\n}\n\nconst SNAPSHOT_COMMERCIAL_TERM_FIELDS = [\n 'brand',\n 'start_time',\n 'end_time',\n 'total_budget',\n 'daily_budget_cap',\n 'budget_cap_timezone',\n 'purchase_order_ref',\n] as const;\n\nfunction safeProposalSnapshot(candidate: Record<string, unknown>): SafeProposalSnapshot | null {\n if (containsCredentialShapedKey(candidate) || containsPresignedUrl(candidate)) return null;\n const proposalId = optionalString(candidate.proposal_id);\n if (!proposalId || proposalId.length > 255) return null;\n const proposal: Record<string, unknown> = { proposal_id: proposalId };\n const proposalStatus = candidate.proposal_status;\n if (proposalStatus !== undefined) {\n if (typeof proposalStatus !== 'string' || !['draft', 'committed', 'accepted'].includes(proposalStatus)) return null;\n proposal.proposal_status = proposalStatus;\n }\n const proposalKind = candidate.proposal_kind;\n if (proposalKind !== undefined) {\n if (\n typeof proposalKind !== 'string' ||\n !['new_media_buy', 'media_buy_update', 'media_buy_cancellation'].includes(proposalKind)\n )\n return null;\n proposal.proposal_kind = proposalKind;\n }\n const termsDigest = candidate.terms_digest;\n if (termsDigest !== undefined) {\n if (typeof termsDigest !== 'string' || !/^sha256:[A-Za-z0-9_-]{43}$/.test(termsDigest)) return null;\n proposal.terms_digest = termsDigest;\n }\n const expiresAt = candidate.expires_at;\n if (expiresAt !== undefined) {\n if (typeof expiresAt !== 'string' || !isStrictDateTime(expiresAt)) return null;\n proposal.expires_at = expiresAt;\n }\n const sourceTerms = record(candidate.commercial_terms);\n let canonicalTermsDigest: string | undefined;\n if (Object.keys(sourceTerms).length > 0) {\n // Inspect the complete seller payload before reducing it to the execution\n // allow-list. A secret in an otherwise unused field must make the proposal\n // ineligible for caching rather than merely disappearing from the snapshot.\n try {\n canonicalTermsDigest = proposalTermsDigest(sourceTerms);\n } catch {\n return null;\n }\n const safeTerms: Record<string, unknown> = {};\n for (const field of SNAPSHOT_COMMERCIAL_TERM_FIELDS) {\n if (sourceTerms[field] !== undefined) safeTerms[field] = sourceTerms[field];\n }\n proposal.commercial_terms = safeTerms;\n }\n return { proposal, ...(canonicalTermsDigest && { canonicalTermsDigest }) };\n}\n\nconst proposalSnapshotStores = new WeakMap<AgentClient, ProposalSnapshotStoreRegistry>();\nconst acceptanceReservationOwners = new WeakMap<AcceptanceReservation, MediaBuyLifecycleCoordinator>();\nconst MAX_PRINCIPAL_STORES_PER_AGENT = 256;\nconst RETIRED_ACCEPTANCE_SEGMENT_COUNT = 256;\nconst RETIRED_ACCEPTANCE_SEGMENT_BYTES = 256 * 1024;\n\nfunction proposalSnapshotStoreFor(agent: AgentClient, principalScope?: string): ProposalSnapshotStore {\n let registry = proposalSnapshotStores.get(agent);\n if (!registry) {\n registry = { stores: new Map() };\n proposalSnapshotStores.set(agent, registry);\n }\n const key = principalScope === undefined ? '\\u0000unscoped' : `principal:${principalScope}`;\n const existing = registry.stores.get(key);\n if (existing) {\n existing.activeCoordinators += 1;\n return existing;\n }\n if (registry.stores.size >= MAX_PRINCIPAL_STORES_PER_AGENT) {\n for (const [candidateKey, candidate] of registry.stores) {\n if (\n candidate.activeCoordinators === 0 &&\n candidate.entries.size === 0 &&\n candidate.proposalAcceptances.size === 0 &&\n candidate.pendingDeclines.size === 0 &&\n candidate.pendingRefinements.size === 0\n ) {\n registry.stores.delete(candidateKey);\n break;\n }\n }\n }\n if (registry.stores.size >= MAX_PRINCIPAL_STORES_PER_AGENT) {\n throw new ConfigurationError(\n `Media-buy lifecycle principal partitions are limited to ${MAX_PRINCIPAL_STORES_PER_AGENT} per AgentClient. Dispose inactive coordinators or use a separate AgentClient.`,\n 'mediaBuy.principalScope'\n );\n }\n const created: ProposalSnapshotStore = {\n entries: new Map(),\n proposalAcceptances: new Map(),\n pendingDeclines: new Set(),\n pendingDeclineProposalIdCount: 0,\n pendingRefinements: new Set(),\n pendingRefinementProposalIdCount: 0,\n bytes: 0,\n registry,\n activeCoordinators: 1,\n };\n registry.stores.set(key, created);\n return created;\n}\n\n/**\n * Negotiated compact-first media-buy facade.\n *\n * Every established projection is assembled field-by-field. Tool selection\n * is final before dispatch, so ambiguous failures never trigger a second\n * mutation through the other lifecycle.\n */\nexport class MediaBuyLifecycleCoordinator {\n readonly negotiated_version: string;\n readonly lifecycle: MediaBuyLifecycle;\n readonly tools: ReadonlySet<string>;\n\n private readonly allowedLosses: ReadonlySet<MediaBuyCompatibilityLoss>;\n private readonly preferredLifecycle: 'auto' | MediaBuyLifecycle;\n private readonly principalScope?: string;\n private readonly configuredLegacyPurchaseSellerSessionScope?: string;\n private resolvedLegacyPurchaseSellerSessionScope?: string;\n private readonly legacyPurchaseContinuationStore: LegacyPurchaseContinuationStore;\n private readonly legacyPurchaseContinuationTtlMs: number;\n private readonly legacyPurchaseClaimTimeoutMs: number;\n private readonly legacyPurchaseOperationTtlMs: number;\n private readonly reconcileLegacyPurchase?: ReconcileLegacyPurchase;\n private readonly proposalSnapshotStore: ProposalSnapshotStore;\n private readonly pendingProposalTasks = new Map<\n string,\n {\n accountScope?: string;\n project?: (data: unknown) => unknown;\n retainProposals: boolean;\n onPause?: () => void;\n onAuthoritativeFailure?: () => void;\n authoritativeTaskNames?: ReadonlySet<string>;\n preserveAuthoritativeProposals?: boolean;\n onTerminalFailure?: () => void;\n }\n >();\n private readonly pendingProposalTaskTimers = new Map<string, ReturnType<typeof setTimeout>>();\n private proposalTaskUnsubscribe?: () => void;\n private readonly pendingAcceptanceTasks = new Map<\n string,\n { snapshotKey: string; snapshot: ProposalSnapshotEntry; reservation: AcceptanceReservation }\n >();\n private readonly ownedAcceptanceReservations = new Map<\n AcceptanceReservation,\n { snapshotKey: string; snapshot: ProposalSnapshotEntry }\n >();\n private readonly pendingAcceptanceTaskTimers = new Map<string, ReturnType<typeof setTimeout>>();\n private readonly acceptanceRetryExpiryTimers = new Map<AcceptanceReservation, ReturnType<typeof setTimeout>>();\n private readonly proposalDispatchUnsubscribes = new Set<() => void>();\n private readonly declineLeaseOwner = {};\n private readonly refinementLeaseOwner = {};\n private acceptanceTaskUnsubscribe?: () => void;\n private disposed = false;\n private readonly idempotencyReplayTtlMs?: number;\n private static readonly MAX_PROPOSAL_SNAPSHOTS = 256;\n private static readonly MAX_PROPOSAL_SNAPSHOT_BYTES = 256 * 1024;\n private static readonly MAX_PROPOSAL_SNAPSHOT_TOTAL_BYTES = 4 * 1024 * 1024;\n private static readonly MAX_PRINCIPAL_SCOPE_BYTES = 256;\n private static readonly MAX_PENDING_DECLINES = 256;\n private static readonly MAX_PENDING_DECLINE_PROPOSAL_IDS = 1024;\n private static readonly MAX_PENDING_REFINEMENTS = 256;\n private static readonly MAX_PENDING_REFINEMENT_PROPOSAL_IDS = 1024;\n private static readonly PROPOSAL_TASK_WATCH_TTL_MS = 5 * 60 * 1000;\n\n private constructor(\n private readonly agent: AgentClient,\n capabilities: AdcpCapabilities,\n options: MediaBuyLifecycleCoordinatorOptions\n ) {\n this.negotiated_version = negotiatedVersion(capabilities, agent.getAdcpVersion());\n this.tools = new Set([...(capabilities.mediaBuyLifecycleTools ?? []), ...(capabilities.discoveredTools ?? [])]);\n this.preferredLifecycle = options.preferredLifecycle ?? 'auto';\n this.allowedLosses = new Set(options.allowedLosses ?? []);\n const replayTtlSeconds = capabilities.idempotency?.replayTtlSeconds;\n if (replayTtlSeconds !== undefined) {\n assertValidIdempotencyReplayTtlSeconds(replayTtlSeconds);\n this.idempotencyReplayTtlMs = replayTtlSeconds * 1000;\n }\n if (options.principalScope !== undefined) {\n if (typeof options.principalScope !== 'string' || options.principalScope.trim().length === 0) {\n throw new TypeError('Media-buy lifecycle principalScope must be a non-empty string when provided.');\n }\n const normalizedScope = options.principalScope.trim();\n if (/[\\u0000-\\u001f\\u007f]/.test(normalizedScope)) {\n throw new TypeError('Media-buy lifecycle principalScope must not contain control characters.');\n }\n if (\n new TextEncoder().encode(normalizedScope).byteLength > MediaBuyLifecycleCoordinator.MAX_PRINCIPAL_SCOPE_BYTES\n ) {\n throw new TypeError(\n `Media-buy lifecycle principalScope must be at most ${MediaBuyLifecycleCoordinator.MAX_PRINCIPAL_SCOPE_BYTES} UTF-8 bytes.`\n );\n }\n }\n this.principalScope = options.principalScope?.trim();\n if (\n options.legacyPurchaseSellerSessionScope !== undefined &&\n (typeof options.legacyPurchaseSellerSessionScope !== 'string' ||\n options.legacyPurchaseSellerSessionScope.trim().length === 0)\n ) {\n throw new TypeError(\n 'Media-buy lifecycle legacyPurchaseSellerSessionScope must be a non-empty string when provided.'\n );\n }\n this.configuredLegacyPurchaseSellerSessionScope = options.legacyPurchaseSellerSessionScope?.trim();\n this.legacyPurchaseContinuationStore =\n options.legacyPurchaseContinuationStore ?? createInMemoryLegacyPurchaseContinuationStore();\n this.legacyPurchaseContinuationTtlMs = options.legacyPurchaseContinuationTtlMs ?? 5 * 60 * 1000;\n this.legacyPurchaseClaimTimeoutMs = options.legacyPurchaseClaimTimeoutMs ?? 30 * 1000;\n this.legacyPurchaseOperationTtlMs = options.legacyPurchaseOperationTtlMs ?? 24 * 60 * 60 * 1000;\n for (const [name, value] of [\n ['legacyPurchaseContinuationTtlMs', this.legacyPurchaseContinuationTtlMs],\n ['legacyPurchaseClaimTimeoutMs', this.legacyPurchaseClaimTimeoutMs],\n ['legacyPurchaseOperationTtlMs', this.legacyPurchaseOperationTtlMs],\n ] as const) {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new TypeError(`Media-buy lifecycle ${name} must be a positive safe integer.`);\n }\n }\n this.reconcileLegacyPurchase = options.reconcileLegacyPurchase;\n this.lifecycle = this.selectLifecycle('list_products');\n this.proposalSnapshotStore = proposalSnapshotStoreFor(agent, this.principalScope);\n }\n\n static async negotiate(\n agent: AgentClient,\n options: MediaBuyLifecycleCoordinatorOptions = {}\n ): Promise<MediaBuyLifecycleCoordinator> {\n return new MediaBuyLifecycleCoordinator(agent, await agent.getCapabilities(), options);\n }\n\n /** Initial negotiation report. Operation calls return their own exact tool report. */\n report(): MediaBuyCompatibilityReport {\n return this.makeReport(this.lifecycle, [], []);\n }\n\n private assertActive(operation: string): void {\n if (!this.disposed) return;\n throw new ConfigurationError(\n `Cannot call ${operation} after disposing the media-buy lifecycle coordinator. Negotiate a new coordinator.`,\n 'mediaBuy.lifecycleCoordinator'\n );\n }\n\n private pendingDeclineRetryCandidate(proposalIds: readonly string[]): PendingDeclineLease | undefined {\n const wanted = new Set(proposalIds);\n const overlapping = [...this.proposalSnapshotStore.pendingDeclines].filter(\n lease => lease.state !== 'retired' && lease.proposalIds.some(proposalId => wanted.has(proposalId))\n );\n const candidate = overlapping.length === 1 ? overlapping[0] : undefined;\n return candidate &&\n candidate.proposalIds.length === wanted.size &&\n candidate.proposalIds.every(proposalId => wanted.has(proposalId)) &&\n (candidate.state === 'paused' || candidate.state === 'commit-uncertain')\n ? candidate\n : undefined;\n }\n\n private pendingRefinementRetryCandidate(proposalIds: readonly string[]): PendingRefinementLease | undefined {\n const wanted = new Set(proposalIds);\n const overlapping = [...this.proposalSnapshotStore.pendingRefinements].filter(\n lease => lease.state !== 'retired' && lease.proposalIds.some(proposalId => wanted.has(proposalId))\n );\n const candidate = overlapping.length === 1 ? overlapping[0] : undefined;\n return candidate &&\n candidate.proposalIds.length === wanted.size &&\n candidate.proposalIds.every(proposalId => wanted.has(proposalId)) &&\n (candidate.state === 'paused' || candidate.state === 'commit-uncertain')\n ? candidate\n : undefined;\n }\n\n private mutationAttemptIsCurrent(\n reservation: PendingDeclineLease | PendingRefinementLease,\n attemptEpoch: number\n ): boolean {\n return reservation.state !== 'retired' && reservation.attemptEpoch === attemptEpoch;\n }\n\n private scheduleProposalMutationTimer(\n reservation: PendingDeclineLease | PendingRefinementLease,\n attemptEpoch: number\n ): void {\n if (reservation.timer) clearTimeout(reservation.timer);\n reservation.timer = undefined;\n if (!this.mutationAttemptIsCurrent(reservation, attemptEpoch)) return;\n const now = Date.now();\n const deadline = reservation.retryDeadlineMs;\n if (reservation.state !== 'in-flight' && (deadline === undefined || deadline <= now)) {\n this.retireAmbiguousProposalMutation(reservation, attemptEpoch);\n return;\n }\n const delay =\n reservation.state === 'in-flight'\n ? deadline === undefined\n ? MediaBuyLifecycleCoordinator.PROPOSAL_TASK_WATCH_TTL_MS\n : Math.min(MediaBuyLifecycleCoordinator.PROPOSAL_TASK_WATCH_TTL_MS, deadline - now)\n : deadline! - now;\n const timer = setTimeout(() => {\n if (!this.mutationAttemptIsCurrent(reservation, attemptEpoch) || reservation.timer !== timer) return;\n reservation.timer = undefined;\n if (reservation.state === 'in-flight' && deadline !== undefined && Date.now() < deadline) {\n reservation.state = 'commit-uncertain';\n this.scheduleProposalMutationTimer(reservation, attemptEpoch);\n return;\n }\n this.retireAmbiguousProposalMutation(reservation, attemptEpoch);\n }, delay);\n timer.unref?.();\n reservation.timer = timer;\n }\n\n private assertProposalMutationRetryWindow(\n reservation: PendingDeclineLease | PendingRefinementLease,\n operation: 'declineProposals' | 'refineProposals'\n ): void {\n if (reservation.idempotencyKey && reservation.retryDeadlineMs && reservation.retryDeadlineMs > Date.now()) return;\n this.retireAmbiguousProposalMutation(reservation, reservation.attemptEpoch);\n throw this.unsupported(\n operation,\n operation === 'declineProposals' ? 'proposal_decline_retry_window' : 'proposal_refinement_retry_window',\n 'The seller no longer guarantees idempotent replay of this proposal mutation. Reconcile its outcome before any different mutation.'\n );\n }\n\n private beginProposalMutationRetry<T extends PendingDeclineLease | PendingRefinementLease>(\n reservation: T,\n owner: object,\n operation: 'declineProposals' | 'refineProposals'\n ): T {\n this.assertProposalMutationRetryWindow(reservation, operation);\n if (reservation.timer) clearTimeout(reservation.timer);\n reservation.timer = undefined;\n reservation.attemptEpoch += 1;\n reservation.state = 'in-flight';\n reservation.owner = owner;\n this.scheduleProposalMutationTimer(reservation, reservation.attemptEpoch);\n return reservation;\n }\n\n private preserveAmbiguousProposalMutation(\n reservation: PendingDeclineLease | PendingRefinementLease,\n attemptEpoch: number,\n state: 'paused' | 'commit-uncertain' = 'commit-uncertain'\n ): void {\n if (!this.mutationAttemptIsCurrent(reservation, attemptEpoch)) return;\n if (!reservation.idempotencyKey || !reservation.retryDeadlineMs || reservation.retryDeadlineMs <= Date.now()) {\n this.retireAmbiguousProposalMutation(reservation, attemptEpoch);\n return;\n }\n // Once an attempt is commit-uncertain, a later local pause cannot weaken\n // the fence back to merely paused.\n if (reservation.state !== 'commit-uncertain') reservation.state = state;\n this.scheduleProposalMutationTimer(reservation, attemptEpoch);\n }\n\n private retireAmbiguousProposalMutation(\n reservation: PendingDeclineLease | PendingRefinementLease,\n attemptEpoch: number\n ): void {\n if (!this.mutationAttemptIsCurrent(reservation, attemptEpoch)) return;\n reservation.proposalIds.forEach(proposalId => this.markCommitUncertainProposalMutation(proposalId));\n if (reservation.operation === 'decline') this.retirePendingDecline(reservation, attemptEpoch);\n else this.retirePendingRefinement(reservation, attemptEpoch);\n }\n\n private proposalMutationIdempotency(\n callerValue: unknown,\n retry: PendingDeclineLease | PendingRefinementLease | undefined,\n skipIdempotencyAutoInject: boolean\n ): { idempotencyKey?: string; skipIdempotencyAutoInject: boolean } {\n const callerKey = optionalString(callerValue);\n const retrySkip = retry?.skipIdempotencyAutoInject;\n const effectiveSkip = retrySkip ?? skipIdempotencyAutoInject;\n const idempotencyKey =\n callerKey ?? retry?.idempotencyKey ?? (!effectiveSkip && !retry ? generateIdempotencyKey() : undefined);\n return {\n ...(idempotencyKey && { idempotencyKey }),\n skipIdempotencyAutoInject: effectiveSkip,\n };\n }\n\n private beginPendingDecline(\n proposalIds: readonly string[],\n requestFingerprintValue: string,\n idempotencyKey: string | undefined,\n skipIdempotencyAutoInject: boolean\n ): PendingDeclineLease {\n const retainedProposalIds = [...new Set(proposalIds)];\n const retry = this.pendingDeclineRetryCandidate(retainedProposalIds);\n const hasPendingDecline = retainedProposalIds.some(proposalId => this.isProposalDeclinePending(proposalId));\n if (hasPendingDecline) {\n if (retry) this.assertProposalMutationRetryWindow(retry, 'declineProposals');\n if (\n retry &&\n retry.idempotencyKey !== undefined &&\n retry.requestFingerprint === requestFingerprintValue &&\n retry.idempotencyKey === idempotencyKey &&\n retry.skipIdempotencyAutoInject === skipIdempotencyAutoInject\n ) {\n return this.beginProposalMutationRetry(retry, this.declineLeaseOwner, 'declineProposals');\n }\n throw this.unsupported(\n 'declineProposals',\n retry ? 'proposal_decline_retry' : 'proposal_decline_pending',\n retry\n ? 'A paused proposal decline may retry only the exact same request and idempotency key. No mutation was sent.'\n : 'A requested proposal already has an unresolved decline in this principal scope. Wait for it to finish before declining again.'\n );\n }\n if (retainedProposalIds.some(proposalId => this.isCommitUncertainProposalMutation(proposalId))) {\n throw this.unsupported(\n 'declineProposals',\n 'proposal_mutation_commit_uncertain',\n 'A prior mutation of a requested proposal has an unreconciled outcome. No decline was sent.'\n );\n }\n if (\n retainedProposalIds.some(proposalId => {\n const reservation = this.proposalSnapshotStore.proposalAcceptances.get(proposalId)?.reservation;\n return reservation?.state === 'retryable' && reservation.retryKind === 'commit-uncertain';\n })\n ) {\n throw this.unsupported(\n 'declineProposals',\n 'proposal_acceptance_commit_uncertain',\n 'A requested proposal has an acceptance whose commit outcome is unknown. Reconcile or exactly retry that acceptance before declining it.'\n );\n }\n if (\n retainedProposalIds.some(\n proposalId => this.proposalSnapshotStore.proposalAcceptances.get(proposalId)?.reservation.state === 'in-flight'\n )\n ) {\n throw this.unsupported(\n 'declineProposals',\n 'proposal_acceptance_pending',\n 'A requested proposal has an in-flight acceptance in this principal scope. Wait for it to finish before declining it.'\n );\n }\n if (retainedProposalIds.some(proposalId => this.isCommitUncertainProposal(proposalId))) {\n throw this.unsupported(\n 'declineProposals',\n 'proposal_acceptance_commit_uncertain',\n 'A requested proposal has an acceptance whose commit outcome is unknown. Reconcile the media buy by natural key before sending a different mutation.'\n );\n }\n if (retainedProposalIds.some(proposalId => this.isAcceptedProposal(proposalId))) {\n throw this.unsupported(\n 'declineProposals',\n 'proposal_terminal',\n 'A requested proposal has already been accepted in this principal scope. No decline was sent.'\n );\n }\n if (retainedProposalIds.some(proposalId => this.isProposalRefinementPending(proposalId))) {\n throw this.unsupported(\n 'declineProposals',\n 'proposal_refinement_pending',\n 'A requested proposal has an unresolved refinement in this principal scope. Wait for that refinement to finish before declining it.'\n );\n }\n if (\n this.proposalSnapshotStore.pendingDeclines.size >= MediaBuyLifecycleCoordinator.MAX_PENDING_DECLINES ||\n this.proposalSnapshotStore.pendingDeclineProposalIdCount + retainedProposalIds.length >\n MediaBuyLifecycleCoordinator.MAX_PENDING_DECLINE_PROPOSAL_IDS\n ) {\n throw new ConfigurationError(\n 'Too many media-buy proposal declines are still pending. Complete, cancel, or dispose outstanding decline tasks before dispatching another.',\n 'mediaBuy.pendingDeclines'\n );\n }\n const lease: PendingDeclineLease = {\n operation: 'decline',\n proposalIds: retainedProposalIds,\n state: 'in-flight',\n requestFingerprint: requestFingerprintValue,\n ...(idempotencyKey && { idempotencyKey }),\n skipIdempotencyAutoInject,\n attemptEpoch: 1,\n owner: this.declineLeaseOwner,\n };\n if (this.idempotencyReplayTtlMs !== undefined) {\n Object.defineProperty(lease, 'retryDeadlineMs', {\n value: Date.now() + this.idempotencyReplayTtlMs,\n enumerable: true,\n writable: false,\n configurable: false,\n });\n }\n this.proposalSnapshotStore.pendingDeclines.add(lease);\n this.proposalSnapshotStore.pendingDeclineProposalIdCount += retainedProposalIds.length;\n this.scheduleProposalMutationTimer(lease, lease.attemptEpoch);\n return lease;\n }\n\n private finishPendingDecline(lease: PendingDeclineLease, attemptEpoch = lease.attemptEpoch): void {\n if (!this.mutationAttemptIsCurrent(lease, attemptEpoch)) return;\n lease.state = 'retired';\n if (lease.timer) clearTimeout(lease.timer);\n lease.timer = undefined;\n this.proposalSnapshotStore.pendingDeclines.delete(lease);\n this.proposalSnapshotStore.pendingDeclineProposalIdCount -= lease.proposalIds.length;\n }\n\n private retirePendingDecline(lease: PendingDeclineLease, attemptEpoch = lease.attemptEpoch): void {\n if (!this.mutationAttemptIsCurrent(lease, attemptEpoch)) return;\n this.invalidateProposalSnapshots(lease.proposalIds, undefined, false, true);\n this.finishPendingDecline(lease, attemptEpoch);\n }\n\n private pausePendingDecline(lease: PendingDeclineLease, attemptEpoch = lease.attemptEpoch): void {\n this.preserveAmbiguousProposalMutation(lease, attemptEpoch, 'paused');\n }\n\n private preparePendingDeclineSettlement(\n lease: PendingDeclineLease,\n response: CompatibleDeclineProposalsResponse,\n attemptEpoch = lease.attemptEpoch\n ): () => void {\n const locallyTerminalIds = response.results\n .filter(result => result.outcome === 'declined' || result.outcome === 'unconfirmed')\n .map(result => result.proposal_id);\n return () => {\n if (!this.mutationAttemptIsCurrent(lease, attemptEpoch)) return;\n this.invalidateProposalSnapshots(locallyTerminalIds, undefined, false, true);\n this.finishPendingDecline(lease, attemptEpoch);\n };\n }\n\n private isProposalDeclinePending(proposalId: string): boolean {\n for (const lease of this.proposalSnapshotStore.pendingDeclines) {\n if (lease.state !== 'retired' && lease.proposalIds.includes(proposalId)) return true;\n }\n return false;\n }\n\n private beginPendingRefinement(\n proposalIds: readonly string[],\n rejectTerminalProposal: boolean,\n requestFingerprintValue: string,\n idempotencyKey: string | undefined,\n skipIdempotencyAutoInject: boolean\n ): PendingRefinementLease {\n const retainedProposalIds = [...new Set(proposalIds)];\n const retry = this.pendingRefinementRetryCandidate(retainedProposalIds);\n if (\n retainedProposalIds.some(\n proposalId => this.isProposalRefinementPending(proposalId) || this.isProposalDeclinePending(proposalId)\n )\n ) {\n if (retry) this.assertProposalMutationRetryWindow(retry, 'refineProposals');\n if (\n retry &&\n !retainedProposalIds.some(proposalId => this.isProposalDeclinePending(proposalId)) &&\n retry.idempotencyKey !== undefined &&\n retry.requestFingerprint === requestFingerprintValue &&\n retry.idempotencyKey === idempotencyKey &&\n retry.skipIdempotencyAutoInject === skipIdempotencyAutoInject\n ) {\n return this.beginProposalMutationRetry(retry, this.refinementLeaseOwner, 'refineProposals');\n }\n throw this.unsupported(\n 'refineProposals',\n retry ? 'proposal_refinement_retry' : 'proposal_mutation_pending',\n retry\n ? 'A paused proposal refinement may retry only the exact same request and idempotency key. No mutation was sent.'\n : 'A requested proposal already has an unresolved refinement or decline in this principal scope. Wait for it to finish before refining again.'\n );\n }\n if (retainedProposalIds.some(proposalId => this.isCommitUncertainProposalMutation(proposalId))) {\n throw this.unsupported(\n 'refineProposals',\n 'proposal_mutation_commit_uncertain',\n 'A prior mutation of a requested proposal has an unreconciled outcome. No refinement was sent.'\n );\n }\n if (\n retainedProposalIds.some(proposalId => {\n const reservation = this.proposalSnapshotStore.proposalAcceptances.get(proposalId)?.reservation;\n return reservation?.state === 'retryable' && reservation.retryKind === 'commit-uncertain';\n })\n ) {\n throw this.unsupported(\n 'refineProposals',\n 'proposal_acceptance_commit_uncertain',\n 'A requested proposal has an acceptance whose commit outcome is unknown. Reconcile or exactly retry that acceptance before refining it.'\n );\n }\n if (retainedProposalIds.some(proposalId => this.proposalSnapshotStore.proposalAcceptances.has(proposalId))) {\n throw this.unsupported(\n 'refineProposals',\n 'proposal_acceptance_pending',\n 'A requested proposal is already being accepted in this principal scope. No refinement was sent.'\n );\n }\n if (retainedProposalIds.some(proposalId => this.isCommitUncertainProposal(proposalId))) {\n throw this.unsupported(\n 'refineProposals',\n 'proposal_acceptance_commit_uncertain',\n 'A requested proposal has an acceptance whose commit outcome is unknown. Reconcile the media buy by natural key before refining it.'\n );\n }\n if (rejectTerminalProposal && retainedProposalIds.some(proposalId => this.isTerminalProposal(proposalId))) {\n throw this.unsupported(\n 'refineProposals',\n 'proposal_terminal',\n 'A requested proposal is terminal in this principal scope. Only a terminal decline remains safe; no refinement was sent.'\n );\n }\n const wanted = new Set(retainedProposalIds);\n const sources = [...this.proposalSnapshotStore.entries].flatMap(([key, entry]) =>\n entry.principalScope === this.principalScope && wanted.has(String(entry.proposal.proposal_id))\n ? [{ key, entry }]\n : []\n );\n if (sources.some(({ entry }) => entry.acceptance !== undefined)) {\n throw this.unsupported(\n 'refineProposals',\n 'proposal_acceptance_pending',\n 'A requested proposal is already being accepted in this principal scope. No refinement was sent.'\n );\n }\n if (\n this.proposalSnapshotStore.pendingRefinements.size >= MediaBuyLifecycleCoordinator.MAX_PENDING_REFINEMENTS ||\n this.proposalSnapshotStore.pendingRefinementProposalIdCount + retainedProposalIds.length >\n MediaBuyLifecycleCoordinator.MAX_PENDING_REFINEMENT_PROPOSAL_IDS\n ) {\n throw new ConfigurationError(\n 'Too many media-buy proposal refinements are still pending. Complete, cancel, or dispose outstanding refinement tasks before dispatching another.',\n 'mediaBuy.pendingRefinements'\n );\n }\n const lease: PendingRefinementLease = {\n operation: 'refine',\n proposalIds: retainedProposalIds,\n sources,\n state: 'in-flight',\n requestFingerprint: requestFingerprintValue,\n ...(idempotencyKey && { idempotencyKey }),\n skipIdempotencyAutoInject,\n attemptEpoch: 1,\n owner: this.refinementLeaseOwner,\n };\n if (this.idempotencyReplayTtlMs !== undefined) {\n Object.defineProperty(lease, 'retryDeadlineMs', {\n value: Date.now() + this.idempotencyReplayTtlMs,\n enumerable: true,\n writable: false,\n configurable: false,\n });\n }\n for (const { entry } of sources) entry.executable = false;\n this.proposalSnapshotStore.pendingRefinements.add(lease);\n this.proposalSnapshotStore.pendingRefinementProposalIdCount += retainedProposalIds.length;\n this.scheduleProposalMutationTimer(lease, lease.attemptEpoch);\n return lease;\n }\n\n private finishPendingRefinement(lease: PendingRefinementLease, attemptEpoch = lease.attemptEpoch): void {\n if (!this.mutationAttemptIsCurrent(lease, attemptEpoch)) return;\n lease.state = 'retired';\n if (lease.timer) clearTimeout(lease.timer);\n lease.timer = undefined;\n this.proposalSnapshotStore.pendingRefinements.delete(lease);\n this.proposalSnapshotStore.pendingRefinementProposalIdCount -= lease.proposalIds.length;\n }\n\n private restorePendingRefinement(lease: PendingRefinementLease, attemptEpoch = lease.attemptEpoch): void {\n if (!this.mutationAttemptIsCurrent(lease, attemptEpoch)) return;\n this.finishPendingRefinement(lease, attemptEpoch);\n for (const { key, entry } of lease.sources) {\n const proposalId = String(entry.proposal.proposal_id);\n if (\n this.proposalSnapshotStore.entries.get(key) === entry &&\n !this.isTerminalProposal(proposalId) &&\n !this.isCommitUncertainProposalMutation(proposalId)\n ) {\n entry.executable = true;\n }\n }\n }\n\n private retirePendingRefinement(lease: PendingRefinementLease, attemptEpoch = lease.attemptEpoch): void {\n if (!this.mutationAttemptIsCurrent(lease, attemptEpoch)) return;\n this.finishPendingRefinement(lease, attemptEpoch);\n this.invalidateProposalSnapshots(lease.proposalIds, undefined, false, true);\n }\n\n private pausePendingRefinement(lease: PendingRefinementLease, attemptEpoch = lease.attemptEpoch): void {\n this.preserveAmbiguousProposalMutation(lease, attemptEpoch, 'paused');\n }\n\n private settlePendingRefinement(\n lease: PendingRefinementLease,\n response: CompatibleRefineProposalsResponse,\n attemptEpoch = lease.attemptEpoch\n ): void {\n this.preparePendingRefinementSettlement(lease, response, attemptEpoch)();\n }\n\n private preparePendingRefinementSettlement(\n lease: PendingRefinementLease,\n response: CompatibleRefineProposalsResponse,\n attemptEpoch = lease.attemptEpoch\n ): () => void {\n const unableProposalIds = new Set(\n response.outcome === 'native_results'\n ? (response.results ?? [])\n .filter(result => result.outcome === 'unable')\n .map(result => result.source_proposal_id)\n : []\n );\n const replacementProposalIds = new Set(\n response.outcome === 'legacy_projected'\n ? (response.proposals ?? [])\n .map(proposal => optionalString(record(proposal).proposal_id))\n .filter((proposalId): proposalId is string => proposalId !== undefined)\n : []\n );\n return () => {\n if (!this.mutationAttemptIsCurrent(lease, attemptEpoch)) return;\n this.finishPendingRefinement(lease, attemptEpoch);\n const replacementSourceIds = lease.proposalIds.filter(proposalId => replacementProposalIds.has(proposalId));\n const terminalProposalIds = lease.proposalIds.filter(\n proposalId => !unableProposalIds.has(proposalId) && !replacementProposalIds.has(proposalId)\n );\n // A legacy exact replay after an ambiguous first attempt cannot prove\n // that a same-ID proposal row is a fresh immutable source rather than\n // the already-consumed pre-mutation snapshot. Keep that source retired;\n // distinct child proposal IDs returned by the replay are still cached.\n this.invalidateProposalSnapshots(replacementSourceIds, undefined, false, attemptEpoch > 1);\n this.invalidateProposalSnapshots(terminalProposalIds, undefined, false, true);\n for (const { key, entry } of lease.sources) {\n const proposalId = String(entry.proposal.proposal_id);\n if (\n unableProposalIds.has(proposalId) &&\n this.proposalSnapshotStore.entries.get(key) === entry &&\n !this.isTerminalProposal(proposalId)\n ) {\n entry.executable = true;\n }\n }\n };\n }\n\n private isProposalRefinementPending(proposalId: string): boolean {\n for (const lease of this.proposalSnapshotStore.pendingRefinements) {\n if (lease.state !== 'retired' && lease.proposalIds.includes(proposalId)) return true;\n }\n return false;\n }\n\n private selectLifecycle(compactTool: string): MediaBuyLifecycle {\n const establishedTool = ESTABLISHED_TOOL_FOR_COMPACT[compactTool as CompactLifecycleToolName];\n if (this.preferredLifecycle === 'established') {\n if (isCompactRelease(this.negotiated_version) && !this.tools.has(establishedTool)) {\n throw this.unsupported(\n compactTool,\n 'established_lifecycle_not_advertised',\n `The seller provides no discovery evidence that ${establishedTool} is callable. ` +\n 'The forced established diagnostic lane was not selected.',\n 'compact'\n );\n }\n return 'established';\n }\n if (isCompactRelease(this.negotiated_version) && this.tools.has(compactTool)) return 'compact';\n if (this.preferredLifecycle === 'compact') {\n throw this.unsupported(\n compactTool,\n compactTool,\n `The negotiated ${this.negotiated_version} lifecycle does not advertise ${compactTool}.`\n );\n }\n if (isCompactRelease(this.negotiated_version) && !this.tools.has(establishedTool)) {\n throw this.unsupported(\n compactTool,\n 'lifecycle_tool_not_advertised',\n `The seller advertises neither ${compactTool} nor its established counterpart ${establishedTool}. No request was sent.`,\n 'compact'\n );\n }\n return 'established';\n }\n\n private assertSharedToolAdvertised(tool: 'get_media_buys' | 'get_media_buy_delivery'): void {\n if (!isCompactRelease(this.negotiated_version) || this.tools.has(tool)) return;\n throw this.unsupported(\n tool,\n 'lifecycle_tool_not_advertised',\n `The negotiated ${this.negotiated_version} seller does not advertise ${tool}. No request was sent.`,\n this.lifecycle\n );\n }\n\n private makeReport(\n lifecycle: MediaBuyLifecycle,\n toolsUsed: string[],\n losses: MediaBuyCompatibilityLoss[],\n warnings: string[] = []\n ): MediaBuyCompatibilityReport {\n return {\n negotiated_version: this.negotiated_version,\n lifecycle,\n tools_used: toolsUsed,\n compatibility: lifecycle === 'compact' ? 'native' : losses.length ? 'lossy_projection' : 'lossless_projection',\n warnings,\n losses,\n };\n }\n\n private unsupported(\n operation: string,\n feature: string,\n message: string,\n lifecycle: MediaBuyLifecycle = 'established'\n ): MediaBuyLifecycleCompatibilityError {\n return new MediaBuyLifecycleCompatibilityError({\n operation,\n negotiatedVersion: this.negotiated_version,\n lifecycle,\n feature: safeDiagnostic(feature, 512),\n message: safeDiagnostic(message, 2048),\n });\n }\n\n private requireAllowed(operation: string, losses: MediaBuyCompatibilityLoss[]): void {\n const refused = losses.filter(loss => !this.allowedLosses.has(loss));\n if (!refused.length) return;\n throw new MediaBuyLifecycleCompatibilityError({\n operation,\n negotiatedVersion: this.negotiated_version,\n lifecycle: 'established',\n feature: refused.join(', '),\n losses: refused,\n message:\n `${operation} cannot preserve ${refused.join(', ')} on the established lifecycle. ` +\n `No mutation was sent. Opt in with allowedLosses only after accepting the named guarantee loss.`,\n });\n }\n\n private assertValidCompactRequest(\n tool: CompactLifecycleToolName,\n params: unknown,\n lifecycle: MediaBuyLifecycle,\n mutating = false\n ): void {\n const input = record(params);\n const candidate =\n mutating && !optionalString(input.idempotency_key)\n ? { ...input, idempotency_key: generateIdempotencyKey() }\n : input;\n const result = TOOL_REQUEST_SCHEMAS[tool]!.safeParse(candidate);\n if (result.success) return;\n const details = result.error.issues\n .slice(0, 5)\n .map(issue => `${issue.path.join('.') || '<root>'}: ${issue.message}`)\n .join('; ');\n throw this.unsupported(\n tool,\n 'compact_request_validation',\n `The compact ${tool} intent is invalid and was not projected: ${details}`,\n lifecycle\n );\n }\n\n private assertOnlyFields(operation: string, value: Record<string, unknown>, allowed: ReadonlySet<string>): void {\n const unsupportedFields = Object.keys(value).filter(key => !allowed.has(key));\n if (unsupportedFields.length === 0) return;\n throw this.unsupported(\n operation,\n unsupportedFields.join(','),\n `${operation} fields ${unsupportedFields.join(', ')} have no declared compatibility projection.`\n );\n }\n\n private assertCompactWireFieldsAbsent(\n operation: string,\n value: Record<string, unknown>,\n fields: readonly string[]\n ): void {\n if (isCompactRelease(this.negotiated_version)) return;\n const unsupportedFields = fields.filter(field => Object.hasOwn(value, field));\n if (unsupportedFields.length === 0) return;\n throw this.unsupported(\n operation,\n unsupportedFields.join(','),\n `The negotiated ${this.negotiated_version} established tool cannot represent compact fields ${unsupportedFields.join(\n ', '\n )}. No mutation was sent.`\n );\n }\n\n private assertLegacyReferenceShapes(operation: string, input: Record<string, unknown>): void {\n if (isCompactRelease(this.negotiated_version)) return;\n const rejectBrandCountries = (brand: unknown, path: string): void => {\n if (Object.hasOwn(record(brand), 'countries')) {\n throw this.unsupported(\n operation,\n `${path}.countries`,\n `The negotiated ${this.negotiated_version} BrandRef cannot represent compact country-qualified identity. No request was sent.`\n );\n }\n };\n if (input.brand !== undefined) rejectBrandCountries(input.brand, 'brand');\n if (input.account !== undefined) {\n const account = record(input.account);\n for (const field of ['operator_unit', 'currency', 'timezone']) {\n if (Object.hasOwn(account, field)) {\n throw this.unsupported(\n operation,\n `account.${field}`,\n `The negotiated ${this.negotiated_version} AccountRef cannot represent compact ${field} identity. No request was sent.`\n );\n }\n }\n if (account.brand !== undefined) rejectBrandCountries(account.brand, 'account.brand');\n }\n }\n\n private assertLegacyOfferFilterShapes(operation: string, offerFilters: Record<string, unknown>): void {\n if (isCompactRelease(this.negotiated_version)) return;\n if (offerFilters.is_fixed_price === false) {\n throw this.unsupported(\n operation,\n 'criteria.offer_filters.is_fixed_price',\n 'Legacy is_fixed_price=false also matches contingent pricing, while compact filtering excludes it. No request was sent.'\n );\n }\n for (const field of ['required_performance_standards', 'required_vendor_metrics']) {\n for (const [index, item] of array(offerFilters[field]).entries()) {\n if (Object.hasOwn(record(record(item).vendor), 'countries')) {\n throw this.unsupported(\n operation,\n `criteria.offer_filters.${field}[${index}].vendor.countries`,\n `The negotiated ${this.negotiated_version} vendor BrandRef cannot represent compact country-qualified identity. No request was sent.`\n );\n }\n }\n }\n }\n\n private assertLegacyTargetingOverlay(operation: string, value: unknown, path: string): void {\n if (value === undefined || isCompactRelease(this.negotiated_version)) return;\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw this.unsupported(operation, path, `${path} must be an object. No request was sent.`);\n }\n const targeting = value as Record<string, unknown>;\n if (compareRelease(this.negotiated_version, '3.0') < 0) {\n if (Object.keys(targeting).length > 0) {\n throw this.unsupported(\n operation,\n path,\n `The negotiated ${this.negotiated_version} targeting field names are not compatible with compact targeting_overlay. No request was sent.`\n );\n }\n return;\n }\n const allowed = compareRelease(this.negotiated_version, '3.1') >= 0 ? V31_TARGETING_FIELDS : V30_TARGETING_FIELDS;\n const unsupported = Object.keys(targeting).filter(field => !allowed.has(field));\n if (unsupported.length > 0) {\n throw this.unsupported(\n operation,\n `${path}.${unsupported.join(',')}`,\n `The negotiated ${this.negotiated_version} targeting schema cannot represent ${unsupported.join(\n ', '\n )}. No request was sent.`\n );\n }\n for (const [index, language] of array(targeting.language).entries()) {\n if (typeof language !== 'string' || !/^[a-z]{2}$/.test(language)) {\n throw this.unsupported(\n operation,\n `${path}.language[${index}]`,\n `The negotiated ${this.negotiated_version} targeting schema accepts only two-letter lowercase language codes. No request was sent.`\n );\n }\n }\n if (compareRelease(this.negotiated_version, '3.1') >= 0) return;\n for (const field of ['geo_postal_areas', 'geo_postal_areas_exclude']) {\n for (const [index, areaValue] of array(targeting[field]).entries()) {\n const area = record(areaValue);\n if (Object.hasOwn(area, 'country') || !V30_POSTAL_SYSTEMS.has(String(area.system))) {\n throw this.unsupported(\n operation,\n `${path}.${field}[${index}]`,\n `The negotiated ${this.negotiated_version} postal targeting supports only legacy country-fused postal systems. No request was sent.`\n );\n }\n }\n }\n }\n\n private assertLegacyMetrics(operation: string, value: unknown, path: string): void {\n if (value === undefined || isCompactRelease(this.negotiated_version)) return;\n const supported =\n compareRelease(this.negotiated_version, '3.1') >= 0\n ? V31_AVAILABLE_METRICS\n : compareRelease(this.negotiated_version, '3.0') >= 0\n ? V30_AVAILABLE_METRICS\n : V25_AVAILABLE_METRICS;\n const unsupported = array(value).filter(metric => typeof metric !== 'string' || !supported.has(metric));\n if (unsupported.length === 0) return;\n throw this.unsupported(\n operation,\n path,\n `The negotiated ${this.negotiated_version} metric enum cannot represent ${unsupported.map(String).join(', ')}. No request was sent.`\n );\n }\n\n private assertLegacyReportingWebhook(operation: string, value: unknown, path = 'reporting_webhook'): void {\n if (value === undefined || isCompactRelease(this.negotiated_version)) return;\n this.assertLegacyMetrics(operation, record(value).requested_metrics, `${path}.requested_metrics`);\n }\n\n private assertLegacyPushNotification(operation: string, value: unknown): void {\n if (value === undefined || isCompactRelease(this.negotiated_version)) return;\n const config = record(value);\n if (compareRelease(this.negotiated_version, '3.0') < 0 && config.authentication === undefined) {\n throw this.unsupported(\n operation,\n 'push_notification_config.authentication',\n `The negotiated ${this.negotiated_version} push notification schema requires explicit authentication. No request was sent.`\n );\n }\n if (compareRelease(this.negotiated_version, '3.1') < 0 && Object.hasOwn(config, 'operation_id')) {\n throw this.unsupported(\n operation,\n 'push_notification_config.operation_id',\n `The negotiated ${this.negotiated_version} push notification registration cannot preserve compact operation_id correlation. No request was sent.`\n );\n }\n }\n\n private assertLegacyProductFields(operation: string, value: unknown): void {\n if (value === undefined || isCompactRelease(this.negotiated_version)) return;\n const supported = compareRelease(this.negotiated_version, '3.1') >= 0 ? V31_PRODUCT_FIELDS : V30_PRODUCT_FIELDS;\n const unsupported = array(value).filter(field => typeof field !== 'string' || !supported.has(field));\n if (unsupported.length === 0) return;\n throw this.unsupported(\n operation,\n 'fields',\n `The negotiated ${this.negotiated_version} product field enum cannot represent ${unsupported\n .map(String)\n .join(', ')}. No request was sent.`\n );\n }\n\n private legacyPurchaseSourceVersion(): LegacyPurchaseSourceVersion {\n if (compareRelease(this.negotiated_version, '3.1') >= 0) return '3.1';\n if (compareRelease(this.negotiated_version, '3.0') >= 0) return '3.0';\n return '2.5';\n }\n\n private legacyPurchaseLosses(sourceVersion: LegacyPurchaseSourceVersion): LegacyPurchaseLoss[] {\n return [\n 'feed_version_not_atomic',\n 'pricing_version_not_atomic',\n ...(sourceVersion === '2.5' ? (['mutation_idempotency_not_guaranteed'] as const) : []),\n ];\n }\n\n private legacyPurchaseBinding(accountScope: string): LegacyPurchaseBinding {\n const agent = this.agent.getAgent();\n const contextId = this.agent.getContextId();\n if (this.resolvedLegacyPurchaseSellerSessionScope === undefined) {\n let sessionScope = this.configuredLegacyPurchaseSellerSessionScope ?? contextId;\n if (sessionScope === undefined && this.legacyPurchaseSourceVersion() === '2.5') {\n throw new ConfigurationError(\n 'Products-only AdCP 2.5 purchase continuations require mediaBuy.legacyPurchaseSellerSessionScope when the seller provides no context ID.'\n );\n }\n if (sessionScope === undefined) {\n sessionScope = LEGACY_PURCHASE_CLIENT_SCOPES.get(this.agent);\n if (sessionScope === undefined) {\n sessionScope = randomBytes(32).toString('base64url');\n LEGACY_PURCHASE_CLIENT_SCOPES.set(this.agent, sessionScope);\n }\n }\n this.resolvedLegacyPurchaseSellerSessionScope = sessionScope;\n }\n return {\n principalScope: this.principalScope!,\n accountScope,\n sellerScope: requestFingerprint({ id: agent.id, uri: agent.agent_uri, protocol: agent.protocol }),\n clientSessionScope: this.resolvedLegacyPurchaseSellerSessionScope,\n sourceAdcpVersion: this.legacyPurchaseSourceVersion(),\n ...(contextId !== undefined && { discoveryContextId: contextId }),\n };\n }\n\n private async projectLegacyProductsAvailable(\n data: unknown,\n accountScope: string | undefined,\n discoveryRequestFingerprint: string\n ): Promise<unknown> {\n const source = compactWirePayload(data);\n if ((proposalRows(source)?.length ?? 0) > 0 || !Array.isArray(source.products) || source.products.length === 0) {\n return data;\n }\n // The arm is a compatibility projection for pre-3.2 sellers only. A\n // dual-surface 3.2 seller forced through its established facade remains a\n // native 3.2 peer and cannot be relabelled as a 3.1 source.\n const negotiatedRelease = parseRelease(this.negotiated_version);\n if (\n negotiatedRelease &&\n (negotiatedRelease.major > 3 || (negotiatedRelease.major === 3 && negotiatedRelease.minor >= 2))\n )\n return data;\n if (!this.principalScope) {\n return data;\n }\n if (!accountScope) {\n return data;\n }\n if (containsCredentialShapedKey(source) || containsPresignedUrl(source)) {\n throw new LegacyPurchaseContinuationError(\n 'request_invalid',\n 'The legacy products-only response contains credential-shaped material and cannot be persisted.'\n );\n }\n const observedBytes = Buffer.byteLength(canonicalize(source), 'utf8');\n if (observedBytes > 256 * 1024) {\n throw new LegacyPurchaseContinuationError(\n 'store_error',\n 'The legacy products-only response exceeds the 256 KiB continuation snapshot limit.'\n );\n }\n const productIds = source.products.map(product => optionalString(record(product).product_id));\n if (productIds.some(productId => productId === undefined) || new Set(productIds).size !== productIds.length) {\n throw new TypeError('The legacy products-only response did not contain distinct non-empty product IDs.');\n }\n const hasBoundPricingOptions = source.products.every(product => {\n const pricingOptionIds = array(record(product).pricing_options).map(option =>\n optionalString(record(option).pricing_option_id)\n );\n return (\n pricingOptionIds.length > 0 &&\n pricingOptionIds.every(pricingOptionId => pricingOptionId !== undefined) &&\n new Set(pricingOptionIds).size === pricingOptionIds.length\n );\n });\n if (!hasBoundPricingOptions) return data;\n const binding = this.legacyPurchaseBinding(accountScope);\n const sourceAdcpVersion = binding.sourceAdcpVersion;\n const losses = this.legacyPurchaseLosses(sourceAdcpVersion);\n const expiresAt = new Date(Date.now() + this.legacyPurchaseContinuationTtlMs).toISOString();\n const issuanceFingerprint = requestFingerprint({\n ...binding,\n discoveryRequestFingerprint,\n observedResponse: source,\n });\n let storedRecord: LegacyPurchaseContinuationRecord | undefined;\n for (let attempt = 0; attempt < 4 && !storedRecord; attempt += 1) {\n const token = randomBytes(24).toString('base64url');\n const continuation: LegacyPurchaseContinuationRecord = {\n token,\n ...binding,\n expiresAt,\n issuanceFingerprint,\n discoveryRequestFingerprint,\n observedResponse: source,\n productIds: productIds as string[],\n losses,\n operation: { state: 'available' },\n };\n try {\n const created = await this.legacyPurchaseContinuationStore.create(continuation);\n if (created.outcome === 'capacity') {\n throw new LegacyPurchaseContinuationError(\n 'store_error',\n 'The legacy purchase continuation store is at capacity.',\n true\n );\n }\n storedRecord = created.record;\n } catch (error) {\n if (error instanceof LegacyPurchaseContinuationError) throw error;\n throw new LegacyPurchaseContinuationError(\n 'store_error',\n 'Could not persist the legacy purchase continuation.',\n true,\n undefined,\n error\n );\n }\n }\n if (!storedRecord) {\n throw new LegacyPurchaseContinuationError(\n 'store_error',\n 'Could not allocate a unique legacy purchase continuation token.',\n true\n );\n }\n const projected: Record<PropertyKey, unknown> = {\n outcome: 'products_available',\n products: source.products,\n ...(Array.isArray(source.incomplete) && { incomplete: source.incomplete }),\n ...(Array.isArray(source.errors) && { errors: source.errors }),\n ...(source.context !== undefined && { context: source.context }),\n purchase_continuation: {\n kind: 'legacy_create',\n continuation_token: storedRecord.token,\n continuation_expires_at: storedRecord.expiresAt,\n source_adcp_version: storedRecord.sourceAdcpVersion,\n product_ids: storedRecord.productIds,\n losses: storedRecord.losses,\n requires_explicit_acceptance: true,\n },\n };\n Object.defineProperty(projected, LEGACY_PROPOSAL_RAW, { value: source, enumerable: false });\n return projected;\n }\n\n private async prepareLegacyProposalResult<T>(\n result: TaskResult<T>,\n accountScope: string | undefined,\n discoveryRequestFingerprint: string\n ): Promise<TaskResult<T>> {\n const prepare = (value: unknown): Promise<unknown> =>\n this.projectLegacyProductsAvailable(value, accountScope, discoveryRequestFingerprint);\n if (\n result.success &&\n result.status === 'completed' &&\n isAdcpOperationSuccess(result.data, result.metadata.taskName)\n ) {\n (result as TaskResult<unknown>).data = await prepare(result.data);\n }\n if (result.submitted) {\n const submitted = result.submitted;\n (result as { submitted?: unknown }).submitted = {\n ...submitted,\n track: async (transport?: import('../protocols').TransportOptions) => {\n const task = await submitted.track(transport);\n if (\n task.status === 'completed' &&\n task.result !== undefined &&\n isAdcpOperationSuccess(task.result, task.taskType)\n ) {\n task.result = await prepare(task.result);\n }\n return task;\n },\n waitForCompletion: async (pollInterval?: number, signal?: AbortSignal) =>\n this.prepareLegacyProposalResult(\n await submitted.waitForCompletion(pollInterval, signal),\n accountScope,\n discoveryRequestFingerprint\n ),\n };\n }\n if (result.deferred) {\n const deferred = result.deferred;\n (result as { deferred?: unknown }).deferred = {\n ...deferred,\n resume: async (input: unknown) =>\n this.prepareLegacyProposalResult(await deferred.resume(input), accountScope, discoveryRequestFingerprint),\n };\n }\n return result;\n }\n\n private assertLegacyReportingDimensions(operation: string, value: unknown): void {\n if (value === undefined || isCompactRelease(this.negotiated_version)) return;\n const dimensions = record(value);\n const unsupported = Object.keys(dimensions).filter(field => !LEGACY_REPORTING_DIMENSIONS.has(field));\n if (unsupported.length > 0) {\n throw this.unsupported(\n operation,\n `reporting_dimensions.${unsupported.join(',')}`,\n `The negotiated ${this.negotiated_version} seller cannot represent reporting dimensions ${unsupported.join(\n ', '\n )}. No request was sent.`\n );\n }\n if (compareRelease(this.negotiated_version, '3.1') >= 0) return;\n const geo = record(dimensions.geo);\n const legacySystems =\n geo.geo_level === 'postal_area' ? V30_POSTAL_SYSTEMS : geo.geo_level === 'metro' ? V30_METRO_SYSTEMS : undefined;\n if (legacySystems && (Object.hasOwn(geo, 'country') || !legacySystems.has(String(geo.system)))) {\n throw this.unsupported(\n operation,\n 'reporting_dimensions.geo',\n `The negotiated ${this.negotiated_version} delivery breakdown requires a valid legacy country-fused metro or postal system. No request was sent.`\n );\n }\n }\n\n private assertProposalLifecycleAvailable(operation: string): void {\n if (compareRelease(this.negotiated_version, '3.0') >= 0) return;\n throw this.unsupported(\n operation,\n 'proposal_lifecycle',\n `The negotiated ${this.negotiated_version} seller has no proposal object or proposal-binding mutation. No request was sent.`\n );\n }\n\n private accountScope(account: unknown): string | undefined {\n const value = record(account);\n return Object.keys(value).length > 0 ? canonicalize(value) : undefined;\n }\n\n private snapshotKey(proposalId: string, accountScope: string | undefined): string {\n return `${this.principalScope ?? 'missing-principal-scope'}\\u0000${accountScope ?? 'unscoped'}\\u0000${proposalId}`;\n }\n\n private proposalScopes(proposalIds: readonly string[]): string[] {\n const wanted = new Set(proposalIds);\n const scopes = new Set<string>();\n for (const entry of this.proposalSnapshotStore.entries.values()) {\n if (\n entry.principalScope === this.principalScope &&\n entry.accountScope &&\n wanted.has(String(entry.proposal.proposal_id))\n ) {\n scopes.add(entry.accountScope);\n }\n }\n return [...scopes];\n }\n\n private removeProposalSnapshot(key: string): void {\n const existing = this.proposalSnapshotStore.entries.get(key);\n if (existing) {\n this.proposalSnapshotStore.bytes -= existing.bytes;\n }\n this.proposalSnapshotStore.entries.delete(key);\n }\n\n private retainProposalSnapshot(key: string, entry: ProposalSnapshotEntry): void {\n this.proposalSnapshotStore.entries.set(key, entry);\n this.proposalSnapshotStore.bytes += entry.bytes;\n }\n\n private isRetiredAcceptanceKey(key: string): boolean {\n const registry = this.proposalSnapshotStore.registry;\n const salt = registry.retiredAcceptanceSalt;\n if (!salt) return false;\n const segmentIndex =\n createHash('sha256')\n .update(salt)\n .update(this.principalScope ?? '\\u0000unscoped')\n .digest()\n .readUInt32BE(0) % RETIRED_ACCEPTANCE_SEGMENT_COUNT;\n const bits = registry.retiredAcceptanceSegments?.get(segmentIndex);\n if (!bits) return false;\n return retiredAcceptancePositions(key, salt, bits.length * 8).every(position => {\n const mask = 1 << (position & 7);\n return (bits[position >> 3]! & mask) !== 0;\n });\n }\n\n private markRetiredAcceptanceKey(key: string): void {\n const registry = this.proposalSnapshotStore.registry;\n const salt = (registry.retiredAcceptanceSalt ??= randomBytes(16));\n const segmentIndex =\n createHash('sha256')\n .update(salt)\n .update(this.principalScope ?? '\\u0000unscoped')\n .digest()\n .readUInt32BE(0) % RETIRED_ACCEPTANCE_SEGMENT_COUNT;\n const segments = (registry.retiredAcceptanceSegments ??= new Map());\n let bits = segments.get(segmentIndex);\n if (!bits) {\n bits = new Uint8Array(RETIRED_ACCEPTANCE_SEGMENT_BYTES);\n segments.set(segmentIndex, bits);\n }\n for (const position of retiredAcceptancePositions(key, salt, bits.length * 8)) {\n bits[position >> 3] = bits[position >> 3]! | (1 << (position & 7));\n }\n }\n\n private terminalProposalKey(proposalId: string): string {\n return `${this.principalScope ?? 'missing-principal-scope'}\\u0000terminal-proposal\\u0000${proposalId}`;\n }\n\n private isTerminalProposal(proposalId: string): boolean {\n return this.isRetiredAcceptanceKey(this.terminalProposalKey(proposalId));\n }\n\n private markTerminalProposal(proposalId: string): void {\n this.markRetiredAcceptanceKey(this.terminalProposalKey(proposalId));\n }\n\n private terminalAcceptanceProposalKey(proposalId: string): string {\n return `${this.principalScope ?? 'missing-principal-scope'}\\u0000terminal-acceptance-proposal\\u0000${proposalId}`;\n }\n\n private isTerminalAcceptanceProposal(proposalId: string): boolean {\n return this.isRetiredAcceptanceKey(this.terminalAcceptanceProposalKey(proposalId));\n }\n\n private markTerminalAcceptanceProposal(proposalId: string): void {\n this.markRetiredAcceptanceKey(this.terminalAcceptanceProposalKey(proposalId));\n }\n\n private acceptedProposalKey(proposalId: string): string {\n return `${this.principalScope ?? 'missing-principal-scope'}\\u0000accepted-proposal\\u0000${proposalId}`;\n }\n\n private isAcceptedProposal(proposalId: string): boolean {\n return this.isRetiredAcceptanceKey(this.acceptedProposalKey(proposalId));\n }\n\n private markAcceptedProposal(proposalId: string): void {\n this.markRetiredAcceptanceKey(this.acceptedProposalKey(proposalId));\n }\n\n private commitUncertainProposalKey(proposalId: string): string {\n return `${this.principalScope ?? 'missing-principal-scope'}\\u0000commit-uncertain-proposal\\u0000${proposalId}`;\n }\n\n private isCommitUncertainProposal(proposalId: string): boolean {\n return this.isRetiredAcceptanceKey(this.commitUncertainProposalKey(proposalId));\n }\n\n private markCommitUncertainProposal(proposalId: string): void {\n this.markRetiredAcceptanceKey(this.commitUncertainProposalKey(proposalId));\n }\n\n private commitUncertainProposalMutationKey(proposalId: string): string {\n return `${this.principalScope ?? 'missing-principal-scope'}\\u0000commit-uncertain-proposal-mutation\\u0000${proposalId}`;\n }\n\n private isCommitUncertainProposalMutation(proposalId: string): boolean {\n return this.isRetiredAcceptanceKey(this.commitUncertainProposalMutationKey(proposalId));\n }\n\n private markCommitUncertainProposalMutation(proposalId: string): void {\n this.markRetiredAcceptanceKey(this.commitUncertainProposalMutationKey(proposalId));\n }\n\n private enforceProposalSnapshotLimits(): void {\n while (\n this.proposalSnapshotStore.entries.size > MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOTS ||\n this.proposalSnapshotStore.bytes > MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOT_TOTAL_BYTES\n ) {\n const oldest = [...this.proposalSnapshotStore.entries].find(\n ([, entry]) =>\n entry.acceptance?.state !== 'in-flight' &&\n !this.isProposalRefinementPending(String(entry.proposal.proposal_id))\n );\n if (!oldest) break;\n const [key, entry] = oldest;\n if (entry.acceptance?.state === 'retryable') {\n this.retireAcceptance(key, entry, entry.acceptance);\n } else {\n this.removeProposalSnapshot(key);\n }\n }\n }\n\n private invalidateProposalSnapshots(\n proposalIds: readonly string[],\n accountScope?: string,\n preserveScope = false,\n retireAcceptances = false\n ): void {\n if (retireAcceptances) proposalIds.forEach(proposalId => this.markTerminalProposal(proposalId));\n const wanted = new Set(proposalIds);\n for (const [key, entry] of [...this.proposalSnapshotStore.entries]) {\n if (entry.principalScope !== this.principalScope) continue;\n if (!wanted.has(String(entry.proposal.proposal_id))) continue;\n if (accountScope !== undefined && entry.accountScope !== accountScope) continue;\n if (entry.acceptance) {\n if (retireAcceptances) this.retireAcceptance(key, entry, entry.acceptance);\n continue;\n }\n if (preserveScope && entry.accountScope) {\n this.removeProposalSnapshot(key);\n const proposal = { proposal_id: entry.proposal.proposal_id };\n const bytes = new TextEncoder().encode(`${key}${JSON.stringify(proposal)}`).byteLength;\n this.retainProposalSnapshot(key, {\n proposal,\n bytes,\n principalScope: entry.principalScope,\n executable: false,\n accountScope: entry.accountScope,\n });\n } else {\n this.removeProposalSnapshot(key);\n }\n }\n }\n\n private proposalIdsIn(data: unknown): string[] {\n const ids = new Set<string>();\n const seen = new WeakSet<object>();\n const stack = [data];\n let visited = 0;\n while (stack.length > 0) {\n const value = stack.pop();\n if (value === null || typeof value !== 'object' || seen.has(value)) continue;\n seen.add(value);\n visited += 1;\n if (visited > MAX_PROPOSAL_TRAVERSAL_NODES) return this.cachedProposalIds();\n if (Array.isArray(value)) {\n if (stack.length + value.length > MAX_PROPOSAL_TRAVERSAL_NODES) return this.cachedProposalIds();\n for (let index = value.length - 1; index >= 0; index -= 1) stack.push(value[index]);\n continue;\n }\n const candidate = value as Record<string, unknown>;\n const proposalId = optionalString(candidate.proposal_id);\n if (proposalId) ids.add(proposalId);\n if (candidate.results !== undefined) stack.push(candidate.results);\n if (candidate.proposal !== undefined) stack.push(candidate.proposal);\n if (candidate.proposals !== undefined) stack.push(candidate.proposals);\n }\n return [...ids];\n }\n\n private cachedProposalIds(accountScope?: string): string[] {\n if (!this.principalScope) return [];\n const ids = new Set<string>();\n for (const entry of this.proposalSnapshotStore.entries.values()) {\n if (entry.principalScope !== this.principalScope || entry.acceptance) continue;\n if (accountScope !== undefined && entry.accountScope !== accountScope) continue;\n ids.add(String(entry.proposal.proposal_id));\n }\n return [...ids];\n }\n\n private cachedProposalIdsIn(data: unknown, accountScope?: string): string[] {\n const wanted = new Set(this.cachedProposalIds(accountScope));\n if (wanted.size === 0) return [];\n const found: string[] = [];\n const seen = new WeakSet<object>();\n const stack = [data];\n let visited = 0;\n while (stack.length > 0 && wanted.size > 0) {\n const value = stack.pop();\n if (value === null || typeof value !== 'object' || seen.has(value)) continue;\n seen.add(value);\n visited += 1;\n if (visited > MAX_PROPOSAL_TRAVERSAL_NODES) return this.cachedProposalIds(accountScope);\n if (Array.isArray(value)) {\n if (stack.length + value.length > MAX_PROPOSAL_TRAVERSAL_NODES) {\n return this.cachedProposalIds(accountScope);\n }\n for (let index = value.length - 1; index >= 0; index -= 1) stack.push(value[index]);\n continue;\n }\n const candidate = value as Record<string, unknown>;\n const proposalId = optionalString(candidate.proposal_id);\n if (proposalId && wanted.delete(proposalId)) found.push(proposalId);\n if (candidate.results !== undefined) stack.push(candidate.results);\n if (candidate.proposal !== undefined) stack.push(candidate.proposal);\n if (candidate.proposals !== undefined) stack.push(candidate.proposals);\n }\n return found;\n }\n\n private safeProposalPayload(data: unknown): { snapshots: SafeProposalSnapshot[] } | undefined {\n const snapshots = new Map<string, { snapshot: SafeProposalSnapshot; bytes: number } | null>();\n const seen = new WeakSet<object>();\n let bytes = 0;\n let overflowed = false;\n const stack = [data];\n let visited = 0;\n try {\n while (stack.length > 0 && !overflowed) {\n const value = stack.pop();\n if (value === null || typeof value !== 'object' || seen.has(value)) continue;\n seen.add(value);\n visited += 1;\n if (visited > MAX_PROPOSAL_TRAVERSAL_NODES) {\n overflowed = true;\n break;\n }\n if (Array.isArray(value)) {\n if (stack.length + value.length > MAX_PROPOSAL_TRAVERSAL_NODES) {\n overflowed = true;\n break;\n }\n for (let index = value.length - 1; index >= 0; index -= 1) stack.push(value[index]);\n continue;\n }\n const candidate = value as Record<string, unknown>;\n const proposalId = optionalString(candidate.proposal_id);\n if (proposalId) {\n if (!snapshots.has(proposalId) && snapshots.size >= MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOTS) {\n overflowed = true;\n return;\n }\n const prior = snapshots.get(proposalId);\n if (prior) bytes -= prior.bytes;\n const safe = safeProposalSnapshot(candidate);\n if (safe) {\n // Detach while this listener still owns the checked representation.\n // Later task-update listeners may mutate the shared TaskInfo object.\n const detached = structuredClone(safe);\n const candidateBytes = new TextEncoder().encode(JSON.stringify(detached.proposal)).byteLength;\n if (\n candidateBytes > MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOT_BYTES ||\n bytes + candidateBytes > MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOT_TOTAL_BYTES\n ) {\n overflowed = true;\n return;\n }\n snapshots.set(proposalId, { snapshot: detached, bytes: candidateBytes });\n bytes += candidateBytes;\n } else {\n // Preserve last-observation semantics: a later unsafe duplicate must\n // revoke an earlier safe representation of the same proposal ID.\n snapshots.set(proposalId, null);\n }\n }\n if (candidate.results !== undefined) stack.push(candidate.results);\n if (candidate.proposal !== undefined) stack.push(candidate.proposal);\n if (candidate.proposals !== undefined) stack.push(candidate.proposals);\n }\n } catch {\n return undefined;\n }\n if (overflowed) return undefined;\n const retained = [...snapshots.values()].flatMap(snapshot => (snapshot ? [snapshot.snapshot] : []));\n return retained.length > 0 ? { snapshots: retained } : undefined;\n }\n\n private captureProposalDispatch<T, U>(\n accountScope: string | undefined,\n dispatch: () => Promise<TaskResult<T>>,\n adapt: (result: TaskResult<T>) => U | Promise<U>,\n projectCompletion?: (data: T) => unknown,\n onCompletionFailure?: () => void,\n retainCompletionProposals = true,\n prepareMatchedCompletion?: (projected: unknown) => () => void,\n onAuthoritativeFailure?: () => void\n ): Promise<U> {\n const captured = new Map<\n string,\n | {\n kind: 'success';\n proposalIds: string[];\n payload?: { snapshots: SafeProposalSnapshot[] };\n settle?: () => void;\n bytes: number;\n }\n | { kind: 'failure'; proposalIds: string[]; authoritative: boolean; bytes: number }\n >();\n let capturedPayloadBytes = 0;\n let captureOverflowed = false;\n const releaseTaskListener = this.agent.onTaskUpdate(task => {\n if (this.disposed) return;\n if (['pending', 'running', 'working', 'submitted'].includes(task.status)) return;\n const operationSucceeded =\n task.status === 'completed' && task.result !== undefined && isAdcpOperationSuccess(task.result, task.taskType);\n const authoritativeFailure =\n task.status === 'failed' ||\n task.status === 'governance-denied' ||\n (task.status === 'completed' &&\n task.result !== undefined &&\n !isAdcpOperationSuccess(task.result, task.taskType));\n let projectedResult = task.result;\n let projectionSucceeded = operationSucceeded;\n if (operationSucceeded && projectCompletion) {\n try {\n projectedResult = projectCompletion(task.result as T);\n } catch {\n projectionSucceeded = false;\n }\n }\n let settle: (() => void) | undefined;\n if (projectionSucceeded && prepareMatchedCompletion) {\n try {\n settle = prepareMatchedCompletion(projectedResult);\n } catch {\n projectionSucceeded = false;\n }\n }\n const safe =\n projectionSucceeded && retainCompletionProposals ? this.safeProposalPayload(projectedResult) : undefined;\n const proposalIds =\n retainCompletionProposals && projectedResult !== undefined\n ? this.cachedProposalIdsIn(projectedResult, accountScope)\n : [];\n const metadataBytes = new TextEncoder().encode(JSON.stringify(proposalIds)).byteLength;\n const safeBytes = safe ? new TextEncoder().encode(JSON.stringify(safe)).byteLength : 0;\n const retainSafe =\n safe !== undefined &&\n metadataBytes + safeBytes <= MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOT_TOTAL_BYTES;\n const bytes = retainSafe ? safeBytes : 0;\n const replaced = captured.get(task.taskId);\n if (replaced) capturedPayloadBytes -= replaced.bytes;\n captured.delete(task.taskId);\n captured.set(\n task.taskId,\n projectionSucceeded\n ? {\n kind: 'success',\n proposalIds,\n ...(retainSafe && { payload: safe }),\n ...(settle && { settle }),\n bytes,\n }\n : { kind: 'failure', proposalIds, authoritative: authoritativeFailure, bytes }\n );\n capturedPayloadBytes += bytes;\n while (capturedPayloadBytes > MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOT_TOTAL_BYTES) {\n const oldestWithPayload = [...captured].find(([, entry]) => entry.kind === 'success' && entry.payload);\n if (!oldestWithPayload) break;\n const [taskId, entry] = oldestWithPayload;\n if (entry.kind !== 'success') continue;\n capturedPayloadBytes -= entry.bytes;\n captured.set(taskId, {\n kind: 'success',\n proposalIds: entry.proposalIds,\n ...(entry.settle && { settle: entry.settle }),\n bytes: 0,\n });\n }\n while (captured.size > 32) {\n const oldest = captured.keys().next().value as string | undefined;\n if (oldest === undefined) break;\n capturedPayloadBytes -= captured.get(oldest)?.bytes ?? 0;\n captured.delete(oldest);\n captureOverflowed = true;\n }\n });\n let released = false;\n const unsubscribe = (): void => {\n if (released) return;\n released = true;\n releaseTaskListener();\n this.proposalDispatchUnsubscribes.delete(unsubscribe);\n };\n this.proposalDispatchUnsubscribes.add(unsubscribe);\n let dispatched: Promise<TaskResult<T>>;\n try {\n dispatched = dispatch();\n } catch (error) {\n unsubscribe();\n return Promise.reject(error);\n }\n return dispatched\n .then(\n async result => {\n this.assertActive('proposal dispatch completion');\n const racedCompletion = captured.get(result.metadata.taskId);\n if (racedCompletion?.kind === 'success') {\n racedCompletion.settle?.();\n this.invalidateProposalSnapshots(racedCompletion.proposalIds, accountScope);\n if (racedCompletion.payload) {\n for (const snapshot of racedCompletion.payload.snapshots) {\n this.rememberSafeProposalSnapshot(snapshot, accountScope);\n }\n }\n } else if (racedCompletion?.kind === 'failure') {\n if (racedCompletion.authoritative && onAuthoritativeFailure) {\n onAuthoritativeFailure();\n } else {\n this.invalidateProposalSnapshots(racedCompletion.proposalIds, accountScope);\n onCompletionFailure?.();\n }\n } else if (captureOverflowed) {\n // The dispatch task ID is not knowable until dispatch returns. If\n // unrelated terminal events overflow the bounded correlation map,\n // a missing match might be the evicted task. Retire every mutable\n // snapshot in scope rather than leave stale execution evidence.\n this.invalidateProposalSnapshots(this.cachedProposalIds(accountScope), accountScope);\n onCompletionFailure?.();\n }\n // adaptProjectedResult installs the long-lived watcher, when needed,\n // before this pre-dispatch listener is released.\n const output = await adapt(result);\n if (racedCompletion || captureOverflowed) this.forgetProposalTask(result.metadata.taskId);\n return output;\n },\n error => {\n if (this.disposed) throw error;\n // A terminal event can beat a transport failure. Without the\n // dispatch result there is no trustworthy task ID for correlation,\n // so any captured terminal evidence makes every mutable snapshot in\n // this scope unsafe to reuse.\n if (captured.size > 0 || captureOverflowed) {\n this.invalidateProposalSnapshots(this.cachedProposalIds(accountScope), accountScope);\n onCompletionFailure?.();\n }\n throw error;\n }\n )\n .finally(unsubscribe);\n }\n\n private watchProposalTask(\n taskId: string | undefined,\n accountScope: string | undefined,\n project: ((data: unknown) => unknown) | undefined,\n retainProposals: boolean,\n onPause?: () => void,\n onTerminalFailure?: () => void,\n onAuthoritativeFailure?: () => void,\n preserveAuthoritativeProposals = false,\n authoritativeTaskNames: ReadonlySet<string> = new Set()\n ): void {\n if (!taskId) return;\n this.pendingProposalTasks.delete(taskId);\n this.pendingProposalTasks.set(taskId, {\n accountScope,\n ...(project && { project }),\n retainProposals,\n ...(onPause && { onPause }),\n ...(onAuthoritativeFailure && { onAuthoritativeFailure }),\n authoritativeTaskNames,\n ...(preserveAuthoritativeProposals && { preserveAuthoritativeProposals }),\n ...(onTerminalFailure && { onTerminalFailure }),\n });\n const priorTimer = this.pendingProposalTaskTimers.get(taskId);\n if (priorTimer) clearTimeout(priorTimer);\n const timer = setTimeout(() => {\n const pending = this.pendingProposalTasks.get(taskId);\n if (!pending || this.pendingProposalTaskTimers.get(taskId) !== timer) return;\n pending.onTerminalFailure?.();\n this.forgetProposalTask(taskId);\n }, MediaBuyLifecycleCoordinator.PROPOSAL_TASK_WATCH_TTL_MS);\n timer.unref?.();\n this.pendingProposalTaskTimers.set(taskId, timer);\n while (this.pendingProposalTasks.size > MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOTS) {\n const oldest = this.pendingProposalTasks.keys().next().value as string | undefined;\n if (oldest === undefined) break;\n this.forgetProposalTask(oldest);\n }\n const handleUpdate = (task: import('../core/ConversationTypes').TaskInfo): void => {\n if (this.disposed) return;\n const pending = this.pendingProposalTasks.get(task.taskId);\n if (!pending) return;\n if (\n task.status === 'completed' &&\n task.result !== undefined &&\n pending.authoritativeTaskNames?.has(task.taskType) &&\n isAdcpOperationSuccess(task.result, task.taskType)\n ) {\n try {\n const projected = pending.project ? pending.project(task.result) : task.result;\n if (pending.retainProposals) this.rememberProposals(projected, pending.accountScope);\n } catch {\n this.invalidateProposalSnapshots(this.proposalIdsIn(task.result), pending.accountScope);\n pending.onTerminalFailure?.();\n }\n } else if (['pending', 'running', 'working', 'submitted'].includes(task.status)) {\n return;\n } else if (task.status === 'input-required' || task.status === 'auth-required') {\n pending.onPause?.();\n } else if (\n (task.status === 'failed' || task.status === 'governance-denied' || task.status === 'completed') &&\n pending.authoritativeTaskNames?.has(task.taskType)\n ) {\n if (task.result !== undefined && !pending.preserveAuthoritativeProposals) {\n this.invalidateProposalSnapshots(this.proposalIdsIn(task.result), pending.accountScope);\n }\n pending.onAuthoritativeFailure?.();\n } else {\n if (task.result !== undefined) {\n this.invalidateProposalSnapshots(this.proposalIdsIn(task.result), pending.accountScope);\n }\n pending.onTerminalFailure?.();\n }\n this.forgetProposalTask(task.taskId);\n };\n if (!this.proposalTaskUnsubscribe) {\n this.proposalTaskUnsubscribe = this.agent.onTaskUpdate(handleUpdate);\n }\n }\n\n private forgetProposalTask(taskId: string): void {\n this.pendingProposalTasks.delete(taskId);\n const timer = this.pendingProposalTaskTimers.get(taskId);\n if (timer) clearTimeout(timer);\n this.pendingProposalTaskTimers.delete(taskId);\n if (this.pendingProposalTasks.size === 0) {\n this.proposalTaskUnsubscribe?.();\n this.proposalTaskUnsubscribe = undefined;\n }\n }\n\n private ownsAcceptance(\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation\n ): boolean {\n const proposalId = String(snapshot.proposal.proposal_id);\n const global = this.proposalSnapshotStore.proposalAcceptances.get(proposalId);\n return (\n this.proposalSnapshotStore.entries.get(snapshotKey) === snapshot &&\n snapshot.acceptance === reservation &&\n global?.snapshotKey === snapshotKey &&\n global.snapshot === snapshot &&\n global.reservation === reservation\n );\n }\n\n private releaseAcceptanceOwnership(reservation: AcceptanceReservation): void {\n const owner = acceptanceReservationOwners.get(reservation);\n if (!owner) return;\n owner.ownedAcceptanceReservations.delete(reservation);\n if (reservation.taskId) owner.forgetAcceptanceTask(reservation.taskId, reservation);\n const retryExpiryTimer = owner.acceptanceRetryExpiryTimers.get(reservation);\n if (retryExpiryTimer) clearTimeout(retryExpiryTimer);\n owner.acceptanceRetryExpiryTimers.delete(reservation);\n acceptanceReservationOwners.delete(reservation);\n }\n\n private scheduleAcceptanceRetryExpiry(\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation\n ): void {\n const deadline = reservation.retryDeadlineMs;\n if (deadline === undefined || deadline <= Date.now()) {\n this.retireAcceptance(snapshotKey, snapshot, reservation);\n return;\n }\n const priorTimer = this.acceptanceRetryExpiryTimers.get(reservation);\n if (priorTimer) clearTimeout(priorTimer);\n const timer = setTimeout(() => {\n this.retireAcceptance(snapshotKey, snapshot, reservation);\n }, deadline - Date.now());\n timer.unref?.();\n this.acceptanceRetryExpiryTimers.set(reservation, timer);\n }\n\n private assertAcceptanceRetryWindow(\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation\n ): void {\n if (reservation.retryDeadlineMs !== undefined && reservation.retryDeadlineMs > Date.now()) return;\n this.retireAcceptance(snapshotKey, snapshot, reservation);\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_retry_window',\n 'The seller no longer guarantees idempotent replay of this paused acceptance. Reconcile by natural key before any new mutation.'\n );\n }\n\n private restoreAcceptance(\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation\n ): void {\n if (!this.ownsAcceptance(snapshotKey, snapshot, reservation) || reservation.state !== 'in-flight') return;\n this.proposalSnapshotStore.proposalAcceptances.delete(String(snapshot.proposal.proposal_id));\n this.releaseAcceptanceOwnership(reservation);\n delete snapshot.acceptance;\n if (snapshot.nativeAcceptanceOnly) this.removeProposalSnapshot(snapshotKey);\n else snapshot.executable = true;\n }\n\n private retireAcceptance(\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation,\n disposition: 'terminal' | 'accepted' | 'commit-uncertain' = reservation.retryKind === 'commit-uncertain'\n ? 'commit-uncertain'\n : 'terminal'\n ): void {\n if (!this.ownsAcceptance(snapshotKey, snapshot, reservation) || reservation.state === 'retired') return;\n const proposalId = String(snapshot.proposal.proposal_id);\n if (disposition === 'commit-uncertain') {\n this.markCommitUncertainProposal(proposalId);\n } else {\n this.markTerminalAcceptanceProposal(proposalId);\n if (disposition === 'accepted') this.markAcceptedProposal(proposalId);\n }\n reservation.state = 'retired';\n snapshot.executable = false;\n this.proposalSnapshotStore.proposalAcceptances.delete(proposalId);\n this.releaseAcceptanceOwnership(reservation);\n this.markTerminalProposal(proposalId);\n for (const [key, sibling] of [...this.proposalSnapshotStore.entries]) {\n if (sibling.principalScope !== this.principalScope || sibling.proposal.proposal_id !== proposalId) continue;\n if (sibling.acceptance && sibling.acceptance !== reservation) {\n sibling.acceptance.state = 'retired';\n this.releaseAcceptanceOwnership(sibling.acceptance);\n }\n sibling.executable = false;\n this.removeProposalSnapshot(key);\n this.markRetiredAcceptanceKey(key);\n }\n }\n\n private preserveAmbiguousAcceptance(\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation,\n taskId?: string,\n retryKind: 'paused' | 'commit-uncertain' = 'commit-uncertain'\n ): void {\n if (!this.ownsAcceptance(snapshotKey, snapshot, reservation) || reservation.state !== 'in-flight') return;\n reservation.retryKind = retryKind;\n if (!reservation.idempotencyKey || reservation.retryDeadlineMs === undefined) {\n this.retireAcceptance(snapshotKey, snapshot, reservation);\n return;\n }\n reservation.state = 'retryable';\n snapshot.executable = false;\n this.watchAcceptanceTask(\n taskId ?? `acceptance-retry:${generateIdempotencyKey()}`,\n snapshotKey,\n snapshot,\n reservation\n );\n this.scheduleAcceptanceRetryExpiry(snapshotKey, snapshot, reservation);\n }\n\n private transitionAcceptanceResult<T>(\n result: TaskResult<T>,\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation\n ): void {\n if (!this.ownsAcceptance(snapshotKey, snapshot, reservation) || reservation.state !== 'in-flight') return;\n if (result.status === 'input-required' || result.status === 'auth-required' || result.status === 'deferred') {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation, result.metadata.taskId, 'paused');\n return;\n }\n if (\n result.status === 'completed' &&\n result.data !== undefined &&\n !isAdcpOperationSuccess(result.data, result.metadata.taskName)\n ) {\n this.restoreAcceptance(snapshotKey, snapshot, reservation);\n this.forgetAcceptanceTask(result.metadata.taskId, reservation);\n return;\n }\n if (!result.success) {\n if (result.metadata.taskName === 'unknown') {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation, result.metadata.taskId);\n return;\n }\n this.restoreAcceptance(snapshotKey, snapshot, reservation);\n this.forgetAcceptanceTask(result.metadata.taskId, reservation);\n return;\n }\n if (result.status === 'working' || result.status === 'submitted') {\n this.watchAcceptanceTask(result.metadata.taskId, snapshotKey, snapshot, reservation);\n return;\n }\n this.retireAcceptance(snapshotKey, snapshot, reservation, 'accepted');\n this.forgetAcceptanceTask(result.metadata.taskId, reservation);\n }\n\n private transitionAcceptanceTask(\n task: import('../core/ConversationTypes').TaskInfo,\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation,\n watchedTaskId = task.taskId\n ): void {\n if (!this.ownsAcceptance(snapshotKey, snapshot, reservation) || reservation.state !== 'in-flight') return;\n if (['input-required', 'auth-required', 'needs_input', 'deferred'].includes(task.status)) {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation, watchedTaskId, 'paused');\n return;\n }\n if (['pending', 'running', 'working', 'submitted', 'deferred'].includes(task.status)) return;\n if (task.status === 'completed') {\n if (isAdcpOperationSuccess(task.result, task.taskType)) {\n this.retireAcceptance(snapshotKey, snapshot, reservation, 'accepted');\n } else {\n this.restoreAcceptance(snapshotKey, snapshot, reservation);\n }\n } else if (['failed', 'rejected', 'canceled', 'governance-denied'].includes(task.status)) {\n this.restoreAcceptance(snapshotKey, snapshot, reservation);\n } else {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation, watchedTaskId);\n return;\n }\n this.forgetAcceptanceTask(watchedTaskId, reservation);\n }\n\n private watchAcceptanceTask(\n taskId: string | undefined,\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation\n ): void {\n if (!taskId) return;\n if (reservation.taskId && reservation.taskId !== taskId) {\n this.forgetAcceptanceTask(reservation.taskId, reservation);\n }\n reservation.taskId = taskId;\n this.pendingAcceptanceTasks.set(taskId, { snapshotKey, snapshot, reservation });\n const priorTimer = this.pendingAcceptanceTaskTimers.get(taskId);\n if (priorTimer) clearTimeout(priorTimer);\n const timer = setTimeout(() => {\n if (reservation.state === 'in-flight') {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation, taskId, 'commit-uncertain');\n }\n this.forgetAcceptanceTask(taskId, reservation);\n }, MediaBuyLifecycleCoordinator.PROPOSAL_TASK_WATCH_TTL_MS);\n timer.unref?.();\n this.pendingAcceptanceTaskTimers.set(taskId, timer);\n const handleUpdate = (task: import('../core/ConversationTypes').TaskInfo): void => {\n if (this.disposed) return;\n const pending = this.pendingAcceptanceTasks.get(task.taskId);\n if (!pending) return;\n this.transitionAcceptanceTask(task, pending.snapshotKey, pending.snapshot, pending.reservation, task.taskId);\n };\n if (!this.acceptanceTaskUnsubscribe) {\n this.acceptanceTaskUnsubscribe = this.agent.onTaskUpdate(handleUpdate);\n }\n }\n\n private forgetAcceptanceTask(taskId: string, reservation?: AcceptanceReservation): void {\n const pending = this.pendingAcceptanceTasks.get(taskId);\n if (reservation && pending?.reservation !== reservation) return;\n this.pendingAcceptanceTasks.delete(taskId);\n const timer = this.pendingAcceptanceTaskTimers.get(taskId);\n if (timer) clearTimeout(timer);\n this.pendingAcceptanceTaskTimers.delete(taskId);\n if (this.pendingAcceptanceTasks.size === 0) {\n this.acceptanceTaskUnsubscribe?.();\n this.acceptanceTaskUnsubscribe = undefined;\n }\n }\n\n private attachAcceptanceTransitions<T>(\n result: TaskResult<T>,\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation\n ): TaskResult<T> {\n this.assertActive('acceptance result projection');\n const localTaskId = result.metadata.taskId;\n this.transitionAcceptanceResult(result, snapshotKey, snapshot, reservation);\n if (result.submitted) {\n const submitted = result.submitted;\n (result as { submitted?: unknown }).submitted = {\n ...submitted,\n track: async (transport?: import('../protocols').TransportOptions) => {\n try {\n this.assertActive('acceptance track continuation');\n const task = await submitted.track(transport);\n this.assertActive('acceptance track continuation');\n this.transitionAcceptanceTask(task, snapshotKey, snapshot, reservation, localTaskId);\n return task;\n } catch (error) {\n if (!this.disposed) {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation, localTaskId);\n }\n throw error;\n }\n },\n waitForCompletion: async (pollInterval?: number, signal?: AbortSignal) => {\n try {\n this.assertActive('acceptance completion continuation');\n const completed = await submitted.waitForCompletion(pollInterval, signal);\n this.assertActive('acceptance completion continuation');\n this.transitionAcceptanceResult(completed, snapshotKey, snapshot, reservation);\n return completed;\n } catch (error) {\n if (!this.disposed) {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation, localTaskId);\n }\n throw error;\n }\n },\n };\n }\n if (result.deferred) {\n const deferred = result.deferred;\n (result as { deferred?: unknown }).deferred = {\n ...deferred,\n resume: async (input: unknown) => {\n try {\n this.assertActive('acceptance resume continuation');\n if (\n !this.ownsAcceptance(snapshotKey, snapshot, reservation) ||\n reservation.state !== 'retryable' ||\n reservation.retryKind !== 'paused'\n ) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_continuation_stale',\n 'This deferred acceptance continuation no longer owns the shared reservation. No continuation was sent.'\n );\n }\n const proposalId = String(snapshot.proposal.proposal_id);\n if (this.isProposalDeclinePending(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_decline_pending',\n 'The proposal has an unresolved decline in this principal scope. Wait for or reconcile that decline before resuming acceptance.'\n );\n }\n this.assertAcceptanceRetryWindow(snapshotKey, snapshot, reservation);\n if (reservation.taskId) this.forgetAcceptanceTask(reservation.taskId, reservation);\n const retryTimer = this.acceptanceRetryExpiryTimers.get(reservation);\n if (retryTimer) clearTimeout(retryTimer);\n this.acceptanceRetryExpiryTimers.delete(reservation);\n reservation.state = 'in-flight';\n delete reservation.retryKind;\n const resumed = await deferred.resume(input);\n this.assertActive('acceptance resume continuation');\n return this.attachAcceptanceTransitions(resumed, snapshotKey, snapshot, reservation);\n } catch (error) {\n if (!this.disposed) {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation, localTaskId);\n }\n throw error;\n }\n },\n };\n }\n return result;\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n for (const unsubscribe of [...this.proposalDispatchUnsubscribes]) unsubscribe();\n for (const decline of [...this.proposalSnapshotStore.pendingDeclines]) {\n if (decline.owner !== this.declineLeaseOwner) continue;\n this.preserveAmbiguousProposalMutation(decline, decline.attemptEpoch);\n }\n for (const refinement of [...this.proposalSnapshotStore.pendingRefinements]) {\n if (refinement.owner !== this.refinementLeaseOwner) continue;\n this.preserveAmbiguousProposalMutation(refinement, refinement.attemptEpoch);\n }\n for (const taskId of [...this.pendingProposalTasks.keys()]) this.forgetProposalTask(taskId);\n this.proposalTaskUnsubscribe?.();\n this.proposalTaskUnsubscribe = undefined;\n for (const [reservation, pending] of [...this.ownedAcceptanceReservations]) {\n if (reservation.state === 'in-flight') {\n this.preserveAmbiguousAcceptance(\n pending.snapshotKey,\n pending.snapshot,\n reservation,\n reservation.taskId,\n 'commit-uncertain'\n );\n }\n if (reservation.state === 'retryable' && reservation.retryKind === 'commit-uncertain') {\n if (reservation.taskId) this.forgetAcceptanceTask(reservation.taskId, reservation);\n continue;\n }\n this.retireAcceptance(pending.snapshotKey, pending.snapshot, reservation, 'terminal');\n this.releaseAcceptanceOwnership(reservation);\n }\n this.acceptanceTaskUnsubscribe?.();\n this.acceptanceTaskUnsubscribe = undefined;\n this.proposalSnapshotStore.activeCoordinators -= 1;\n }\n\n private rememberProposals(data: unknown, accountScope?: string): void {\n if (this.disposed || !this.principalScope) return;\n const seen = new WeakSet<object>();\n const stack = [data];\n let visited = 0;\n while (stack.length > 0) {\n const value = stack.pop();\n if (value === null || typeof value !== 'object' || seen.has(value)) continue;\n seen.add(value);\n visited += 1;\n if (visited > MAX_PROPOSAL_TRAVERSAL_NODES) {\n this.invalidateProposalSnapshots(this.cachedProposalIds(accountScope), accountScope);\n return;\n }\n if (Array.isArray(value)) {\n if (stack.length + value.length > MAX_PROPOSAL_TRAVERSAL_NODES) {\n this.invalidateProposalSnapshots(this.cachedProposalIds(accountScope), accountScope);\n return;\n }\n for (let index = value.length - 1; index >= 0; index -= 1) stack.push(value[index]);\n continue;\n }\n const candidate = value as Record<string, unknown>;\n const proposalId = optionalString(candidate.proposal_id);\n if (proposalId) {\n if (this.isProposalRefinementPending(proposalId)) continue;\n const key = this.snapshotKey(proposalId, accountScope);\n if (this.isTerminalProposal(proposalId) || this.isRetiredAcceptanceKey(key)) continue;\n if (this.proposalSnapshotStore.entries.get(key)?.acceptance) continue;\n // A newly observed seller representation supersedes the prior one.\n // Invalidate first so an unsafe, oversized, or unserializable\n // replacement cannot leave stale executable terms behind.\n this.removeProposalSnapshot(key);\n try {\n const safeSnapshot = safeProposalSnapshot(candidate);\n if (!safeSnapshot) continue;\n this.rememberSafeProposalSnapshot(safeSnapshot, accountScope);\n } catch {\n // Seller responses must be JSON. An unserializable proposal is not a\n // safe immutable acceptance snapshot, so leave it out of the cache.\n }\n }\n if (candidate.results !== undefined) stack.push(candidate.results);\n if (candidate.proposal !== undefined) stack.push(candidate.proposal);\n if (candidate.proposals !== undefined) stack.push(candidate.proposals);\n }\n }\n\n private rememberSafeProposalSnapshot(snapshot: SafeProposalSnapshot, accountScope?: string): void {\n if (this.disposed || !this.principalScope) return;\n const proposalId = optionalString(snapshot.proposal.proposal_id);\n if (!proposalId) return;\n if (this.isProposalRefinementPending(proposalId)) return;\n const key = this.snapshotKey(proposalId, accountScope);\n if (\n this.isTerminalProposal(proposalId) ||\n this.isRetiredAcceptanceKey(key) ||\n this.proposalSnapshotStore.entries.get(key)?.acceptance\n ) {\n return;\n }\n this.removeProposalSnapshot(key);\n const bytes = new TextEncoder().encode(`${key}${JSON.stringify(snapshot)}`).byteLength;\n if (bytes > MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOT_BYTES) return;\n const retained = structuredClone(snapshot);\n this.retainProposalSnapshot(key, {\n proposal: retained.proposal,\n bytes,\n principalScope: this.principalScope,\n executable: true,\n ...(accountScope && { accountScope }),\n ...(retained.canonicalTermsDigest && { canonicalTermsDigest: retained.canonicalTermsDigest }),\n });\n this.enforceProposalSnapshotLimits();\n }\n\n private adaptProjectedResult<T, U>(\n result: TaskResult<T>,\n report: MediaBuyCompatibilityReport,\n project: (data: T) => U,\n accountScope?: string,\n retainProposals = false,\n pendingDecline?: PendingDeclineLease,\n pendingRefinement?: PendingRefinementLease,\n mutationAttemptEpoch?: number\n ): CompatibilityTaskResult<U, T> {\n const localTaskId = result.metadata.taskId;\n const mutationReservation = pendingDecline ?? pendingRefinement;\n const attemptEpoch = mutationAttemptEpoch ?? mutationReservation?.attemptEpoch;\n const mutationAttemptIsCurrent = (): boolean =>\n !mutationReservation ||\n (attemptEpoch !== undefined && this.mutationAttemptIsCurrent(mutationReservation, attemptEpoch));\n const adapt = (current: TaskResult<T>): CompatibilityTaskResult<U, T> => {\n this.assertActive('lifecycle result projection');\n const attemptWasCurrent = mutationAttemptIsCurrent();\n const currentTaskIsAuthoritative = report.tools_used.includes(current.metadata.taskName);\n const currentAuthoritativeFailure =\n currentTaskIsAuthoritative &&\n (current.status === 'failed' ||\n current.status === 'governance-denied' ||\n (current.status === 'completed' && !isAdcpOperationSuccess(current.data, current.metadata.taskName)));\n if (\n current.success &&\n current.status === 'completed' &&\n isAdcpOperationSuccess(current.data, current.metadata.taskName)\n ) {\n let projected: U;\n try {\n projected = project(current.data);\n } catch (error) {\n if (retainProposals && attemptWasCurrent) {\n // A malformed replacement is still authoritative evidence that\n // the seller re-used this proposal ID. Revoke any older executable\n // snapshot before surfacing the projection error.\n this.invalidateProposalSnapshots(this.proposalIdsIn(current.data), accountScope);\n }\n throw error;\n }\n if (retainProposals && attemptWasCurrent) this.rememberProposals(projected, accountScope);\n (current as TaskResult<unknown>).data = projected;\n } else if (\n retainProposals &&\n mutationAttemptIsCurrent() &&\n current.data !== undefined &&\n !(pendingRefinement && currentAuthoritativeFailure)\n ) {\n this.invalidateProposalSnapshots(this.proposalIdsIn(current.data), accountScope);\n }\n if (\n mutationAttemptIsCurrent() &&\n (retainProposals || pendingDecline || pendingRefinement) &&\n ['working', 'submitted'].includes(current.status)\n ) {\n this.watchProposalTask(\n localTaskId,\n accountScope,\n data => project(data as T),\n retainProposals,\n () => {\n if (attemptEpoch === undefined) return;\n if (pendingDecline && !this.disposed) this.pausePendingDecline(pendingDecline, attemptEpoch);\n if (pendingRefinement && !this.disposed) this.pausePendingRefinement(pendingRefinement, attemptEpoch);\n },\n () => {\n if (attemptEpoch === undefined) return;\n if (pendingDecline && !this.disposed) this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch);\n if (pendingRefinement && !this.disposed)\n this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n },\n () => {\n if (attemptEpoch === undefined) return;\n if (pendingDecline && !this.disposed) this.retirePendingDecline(pendingDecline, attemptEpoch);\n if (pendingRefinement && !this.disposed) this.restorePendingRefinement(pendingRefinement, attemptEpoch);\n },\n pendingRefinement !== undefined,\n new Set(report.tools_used)\n );\n } else if (mutationAttemptIsCurrent() && (retainProposals || pendingDecline || pendingRefinement)) {\n this.forgetProposalTask(localTaskId);\n }\n\n const output = current as unknown as TaskResult<U>;\n if (current.submitted) {\n const submitted = current.submitted;\n (output as { submitted?: unknown }).submitted = {\n ...submitted,\n track: async (transport?: import('../protocols').TransportOptions) => {\n try {\n this.assertActive('lifecycle track continuation');\n const task = await submitted.track(transport);\n this.assertActive('lifecycle track continuation');\n const completedSuccessfully =\n task.status === 'completed' &&\n task.result !== undefined &&\n report.tools_used.includes(task.taskType) &&\n isAdcpOperationSuccess(task.result, task.taskType);\n const authoritativeFailure =\n report.tools_used.includes(task.taskType) &&\n (task.status === 'failed' ||\n task.status === 'governance-denied' ||\n (task.status === 'completed' &&\n task.result !== undefined &&\n !isAdcpOperationSuccess(task.result, task.taskType)));\n if (completedSuccessfully) {\n const continuationWasCurrent = mutationAttemptIsCurrent();\n let projected: U;\n try {\n projected = project(task.result as T);\n } catch (error) {\n if (retainProposals && continuationWasCurrent) {\n this.invalidateProposalSnapshots(this.proposalIdsIn(task.result), accountScope);\n }\n throw error;\n }\n if (retainProposals && continuationWasCurrent) this.rememberProposals(projected, accountScope);\n task.result = projected;\n if (retainProposals && continuationWasCurrent) this.forgetProposalTask(localTaskId);\n } else if (\n retainProposals &&\n mutationAttemptIsCurrent() &&\n !(pendingRefinement && authoritativeFailure) &&\n !['pending', 'running', 'working', 'submitted'].includes(task.status)\n ) {\n if (task.result !== undefined) {\n this.invalidateProposalSnapshots(this.proposalIdsIn(task.result), accountScope);\n }\n if (mutationAttemptIsCurrent()) this.forgetProposalTask(localTaskId);\n }\n if (\n pendingDecline &&\n !['pending', 'running', 'working', 'submitted', 'input-required', 'auth-required', 'deferred'].includes(\n task.status\n )\n ) {\n if (attemptEpoch !== undefined) {\n if (completedSuccessfully) this.finishPendingDecline(pendingDecline, attemptEpoch);\n else this.retirePendingDecline(pendingDecline, attemptEpoch);\n }\n }\n if (\n pendingRefinement &&\n !completedSuccessfully &&\n !['pending', 'running', 'working', 'submitted', 'input-required', 'auth-required', 'deferred'].includes(\n task.status\n )\n ) {\n if (attemptEpoch !== undefined) {\n if (authoritativeFailure) this.restorePendingRefinement(pendingRefinement, attemptEpoch);\n else this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n }\n }\n if (task.status === 'input-required' || task.status === 'auth-required') {\n if (attemptEpoch !== undefined) {\n if (pendingDecline) this.pausePendingDecline(pendingDecline, attemptEpoch);\n if (pendingRefinement) this.pausePendingRefinement(pendingRefinement, attemptEpoch);\n }\n this.forgetProposalTask(localTaskId);\n }\n return task;\n } catch (error) {\n if (attemptEpoch !== undefined) {\n if (pendingDecline && !this.disposed)\n this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch);\n if (pendingRefinement && !this.disposed)\n this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n }\n throw error;\n }\n },\n waitForCompletion: async (pollInterval?: number, signal?: AbortSignal) => {\n try {\n this.assertActive('lifecycle completion continuation');\n return adapt(await submitted.waitForCompletion(pollInterval, signal));\n } catch (error) {\n if (attemptEpoch !== undefined) {\n if (pendingDecline && !this.disposed)\n this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch);\n if (pendingRefinement && !this.disposed)\n this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n }\n throw error;\n }\n },\n };\n }\n if (current.deferred) {\n const deferred = current.deferred;\n (output as { deferred?: unknown }).deferred = {\n ...deferred,\n resume: async (input: unknown) => {\n let resumedEpoch = attemptEpoch;\n try {\n this.assertActive('lifecycle resume continuation');\n if (mutationReservation) {\n if (\n attemptEpoch === undefined ||\n !this.mutationAttemptIsCurrent(mutationReservation, attemptEpoch) ||\n mutationReservation.state !== 'paused'\n ) {\n throw this.unsupported(\n pendingDecline ? 'declineProposals' : 'refineProposals',\n 'proposal_mutation_continuation_stale',\n 'This deferred proposal-mutation continuation no longer owns the shared reservation. No continuation was sent.'\n );\n }\n const operation = pendingDecline ? 'declineProposals' : 'refineProposals';\n const owner = pendingDecline ? this.declineLeaseOwner : this.refinementLeaseOwner;\n this.beginProposalMutationRetry(mutationReservation, owner, operation);\n resumedEpoch = mutationReservation.attemptEpoch;\n }\n const resumed = await deferred.resume(input);\n if (!mutationReservation) return adapt(resumed);\n return this.adaptProjectedResult(\n resumed,\n report,\n project,\n accountScope,\n retainProposals,\n pendingDecline,\n pendingRefinement,\n resumedEpoch\n );\n } catch (error) {\n if (resumedEpoch !== undefined) {\n if (pendingDecline && !this.disposed)\n this.preserveAmbiguousProposalMutation(pendingDecline, resumedEpoch);\n if (pendingRefinement && !this.disposed)\n this.preserveAmbiguousProposalMutation(pendingRefinement, resumedEpoch);\n }\n throw error;\n }\n },\n };\n }\n if (pendingDecline && current.status === 'completed') {\n if (attemptEpoch !== undefined) {\n if (isAdcpOperationSuccess(current.data, current.metadata.taskName))\n this.finishPendingDecline(pendingDecline, attemptEpoch);\n else this.retirePendingDecline(pendingDecline, attemptEpoch);\n }\n } else if (pendingDecline && (current.status === 'failed' || current.status === 'governance-denied')) {\n if (attemptEpoch !== undefined) this.retirePendingDecline(pendingDecline, attemptEpoch);\n }\n if (\n pendingRefinement &&\n ((current.status === 'completed' && !isAdcpOperationSuccess(current.data, current.metadata.taskName)) ||\n current.status === 'failed' ||\n current.status === 'governance-denied')\n ) {\n if (attemptEpoch !== undefined) {\n if (currentAuthoritativeFailure) this.restorePendingRefinement(pendingRefinement, attemptEpoch);\n else this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n }\n }\n if (current.status === 'input-required' || current.status === 'auth-required' || current.status === 'deferred') {\n if (attemptEpoch !== undefined) {\n if (pendingDecline) this.pausePendingDecline(pendingDecline, attemptEpoch);\n if (pendingRefinement) this.pausePendingRefinement(pendingRefinement, attemptEpoch);\n }\n }\n return Object.assign(output, { compatibility: report }) as unknown as CompatibilityTaskResult<U, T>;\n };\n return adapt(result);\n }\n\n async listProducts(\n params: ListProductsRequest,\n inputHandler?: InputHandler,\n options?: CanonicalProjectionTaskOptions\n ): Promise<CompatibilityTaskResult<CompatibleProductsResponse, CompatibleProductsWireResponse>> {\n this.assertActive('listProducts');\n const input = record(params);\n const lifecycle = this.selectLifecycle('list_products');\n this.assertLegacyReferenceShapes('listProducts', input);\n if (lifecycle === 'compact') {\n this.assertValidCompactRequest('list_products', params, lifecycle);\n const result = await this.agent.listProducts(params, inputHandler, options);\n return this.adaptProjectedResult(result, this.makeReport(lifecycle, ['list_products'], []), data =>\n projectProducts(data, lifecycle)\n );\n }\n\n this.assertOnlyFields('listProducts', input, LIST_PRODUCTS_FIELDS);\n if (\n compareRelease(this.negotiated_version, '3.0') < 0 &&\n ['cursor', 'max_results', 'fields'].some(field => Object.hasOwn(input, field))\n ) {\n throw this.unsupported(\n 'listProducts',\n 'cursor,max_results,fields',\n `The negotiated ${this.negotiated_version} get_products request has no pagination or response-field selection. No request was sent.`\n );\n }\n if (\n compareRelease(this.negotiated_version, '3.1') < 0 &&\n ['if_feed_version', 'if_pricing_version'].some(field => Object.hasOwn(input, field))\n ) {\n throw this.unsupported(\n 'listProducts',\n 'if_feed_version,if_pricing_version',\n `The negotiated ${this.negotiated_version} get_products request cannot condition on feed or pricing versions. No request was sent.`\n );\n }\n this.assertLegacyProductFields('listProducts', input.fields);\n if (input.criteria !== undefined || input.governance_context !== undefined || input.context_id !== undefined) {\n throw this.unsupported(\n 'listProducts',\n 'criteria/governance_context/context_id',\n 'Compact list_products criteria, governance context, and explicit context IDs have no general lossless established mapping.'\n );\n }\n if (input.push_notification_config !== undefined && compareRelease(this.negotiated_version, '3.1') < 0) {\n throw this.unsupported(\n 'listProducts',\n 'push_notification_config',\n `The negotiated ${this.negotiated_version} get_products request cannot carry push_notification_config.`\n );\n }\n const request: CanonicalGetProductsRequest = {\n buying_mode: 'wholesale',\n ...(input.idempotency_key !== undefined && { idempotency_key: input.idempotency_key as string }),\n ...(input.account !== undefined && { account: input.account as CanonicalGetProductsRequest['account'] }),\n ...(input.brand !== undefined && { brand: input.brand as CanonicalGetProductsRequest['brand'] }),\n ...(Array.isArray(input.fields) && { fields: input.fields as CanonicalGetProductsRequest['fields'] }),\n ...(compareRelease(this.negotiated_version, '3.0') >= 0 &&\n (input.cursor !== undefined || input.max_results !== undefined) && {\n pagination: {\n ...(input.cursor !== undefined && { cursor: input.cursor }),\n ...(input.max_results !== undefined && { max_results: input.max_results }),\n } as CanonicalGetProductsRequest['pagination'],\n }),\n ...(input.if_feed_version !== undefined && { if_wholesale_feed_version: input.if_feed_version as string }),\n ...(input.if_pricing_version !== undefined && { if_pricing_version: input.if_pricing_version as string }),\n ...(input.context !== undefined && { context: input.context as CanonicalGetProductsRequest['context'] }),\n ...(input.push_notification_config !== undefined && {\n push_notification_config:\n input.push_notification_config as CanonicalGetProductsRequest['push_notification_config'],\n }),\n };\n this.assertValidCompactRequest('list_products', params, lifecycle);\n const result = await this.agent.getProducts(request, inputHandler, options);\n return this.adaptProjectedResult(result, this.makeReport(lifecycle, ['get_products'], []), data =>\n projectProducts(data, lifecycle)\n );\n }\n\n async requestProposals(\n params: MutatingRequestInput<RequestProposalsRequest>,\n inputHandler?: InputHandler,\n options?: CanonicalProjectionTaskOptions\n ): Promise<CompatibilityTaskResult<CompatibleRequestProposalsResponse, CompatibleRequestProposalsWireResponse>> {\n this.assertActive('requestProposals');\n const input = record(params);\n const lifecycle = this.selectLifecycle('request_proposals');\n this.assertLegacyReferenceShapes('requestProposals', input);\n if (lifecycle === 'compact') {\n this.assertValidCompactRequest('request_proposals', params, lifecycle, true);\n const accountScope = this.accountScope(input.account);\n return this.captureProposalDispatch(\n accountScope,\n () => this.agent.requestProposals(params, inputHandler, options),\n result =>\n this.adaptProjectedResult(\n result,\n this.makeReport(lifecycle, ['request_proposals'], []),\n data => projectRequestProposals(data, lifecycle, this.negotiated_version),\n accountScope,\n true\n ),\n data => projectRequestProposals(data, lifecycle, this.negotiated_version)\n );\n }\n\n this.assertOnlyFields('requestProposals', input, REQUEST_PROPOSALS_FIELDS);\n const criteria = record(input.criteria);\n this.assertOnlyFields(\n 'requestProposals.criteria',\n criteria,\n new Set([\n 'product_ids',\n 'offer_filters',\n 'targeting_overlay',\n 'required_overlay_support',\n 'catalog',\n 'policy_ids',\n 'ext',\n ])\n );\n this.assertCompactWireFieldsAbsent('requestProposals.criteria', criteria, [\n 'targeting_overlay',\n 'required_overlay_support',\n ]);\n if (!optionalString(input.brief)) {\n throw this.unsupported('requestProposals', 'brief', 'Proposal requests require a non-empty brief.');\n }\n const accountScope = this.accountScope(input.account);\n if (\n criteria.ext !== undefined ||\n input.opportunity !== undefined ||\n input.governance_context !== undefined ||\n input.context_id !== undefined\n ) {\n throw this.unsupported(\n 'requestProposals',\n 'structured proposal context',\n 'The established proposal request cannot losslessly carry compact ext, opportunity, or governance context.'\n );\n }\n if (input.push_notification_config !== undefined && compareRelease(this.negotiated_version, '3.1') < 0) {\n throw this.unsupported(\n 'requestProposals',\n 'push_notification_config',\n `The negotiated ${this.negotiated_version} get_products request cannot carry push_notification_config.`\n );\n }\n const offerFilters = record(criteria.offer_filters);\n this.assertLegacyOfferFilterShapes('requestProposals', offerFilters);\n this.assertLegacyMetrics(\n 'requestProposals',\n offerFilters.required_metrics,\n 'criteria.offer_filters.required_metrics'\n );\n if (criteria.product_ids !== undefined) {\n throw this.unsupported(\n 'requestProposals',\n 'criteria.product_ids',\n 'Established get_products has no normative product-ID proposal filter.'\n );\n }\n if (criteria.catalog !== undefined) {\n throw this.unsupported(\n 'requestProposals',\n 'criteria.catalog',\n 'Compact catalog selection omits the full legacy catalog metadata required by get_products. No request was sent.'\n );\n }\n const legacyOfferFilterFields =\n compareRelease(this.negotiated_version, '3.1') >= 0\n ? V31_OFFER_FILTER_FIELDS\n : compareRelease(this.negotiated_version, '3.0') >= 0\n ? V30_OFFER_FILTER_FIELDS\n : V25_OFFER_FILTER_FIELDS;\n this.assertOnlyFields('requestProposals.criteria.offer_filters', offerFilters, legacyOfferFilterFields);\n const filters = Object.fromEntries(\n Object.entries(offerFilters).filter(([key]) => legacyOfferFilterFields.has(key))\n );\n const request: CanonicalGetProductsRequest = {\n buying_mode: 'brief',\n brief: input.brief as string,\n ...(optionalString(input.idempotency_key)\n ? { idempotency_key: optionalString(input.idempotency_key) }\n : !options?.skipIdempotencyAutoInject\n ? { idempotency_key: generateIdempotencyKey() }\n : {}),\n ...(input.account !== undefined && { account: input.account as CanonicalGetProductsRequest['account'] }),\n ...(input.brand !== undefined && { brand: input.brand as CanonicalGetProductsRequest['brand'] }),\n ...(Object.keys(filters).length > 0 && {\n filters: filters as CanonicalGetProductsRequest['filters'],\n }),\n ...(criteria.targeting_overlay !== undefined && {\n targeting_overlay: criteria.targeting_overlay as CanonicalGetProductsRequest['targeting_overlay'],\n }),\n ...(criteria.required_overlay_support !== undefined && {\n required_overlay_support:\n criteria.required_overlay_support as CanonicalGetProductsRequest['required_overlay_support'],\n }),\n ...(criteria.catalog !== undefined && { catalog: criteria.catalog as CanonicalGetProductsRequest['catalog'] }),\n ...(Array.isArray(criteria.policy_ids) && { required_policies: criteria.policy_ids as string[] }),\n ...(input.push_notification_config !== undefined && {\n push_notification_config:\n input.push_notification_config as CanonicalGetProductsRequest['push_notification_config'],\n }),\n ...(input.context !== undefined && { context: input.context as CanonicalGetProductsRequest['context'] }),\n };\n this.assertValidCompactRequest('request_proposals', params, lifecycle, true);\n return this.captureProposalDispatch(\n accountScope,\n () => this.agent.getProducts(request, inputHandler, options),\n async result => {\n const prepared = await this.prepareLegacyProposalResult(result, accountScope, requestFingerprint(request));\n return this.adaptProjectedResult(\n prepared,\n this.makeReport(lifecycle, ['get_products'], []),\n data => projectRequestProposals(data, lifecycle),\n accountScope,\n true\n );\n },\n data => projectRequestProposals(data, lifecycle)\n );\n }\n\n /**\n * Redeem a beta.4 `legacy_create` continuation. This is an SDK-local\n * coordinator operation; the input object itself is never sent on the wire.\n */\n async continueLegacyPurchase(\n input: CompatibilityPurchaseCoordinatorInput,\n inputHandler?: InputHandler,\n options?: TaskOptions\n ): Promise<TaskResult<CreateMediaBuyResponse>> {\n this.assertActive('continueLegacyPurchase');\n if (!this.principalScope) {\n throw new LegacyPurchaseContinuationError(\n 'binding_mismatch',\n 'Legacy purchase continuation redemption requires a stable principalScope.'\n );\n }\n const value = record(input);\n const allowedInputFields = new Set([\n 'idempotency_key',\n 'continuation_token',\n 'account',\n 'selected_product_ids',\n 'accepted_losses',\n 'legacy_create_request',\n ]);\n if (Object.keys(value).some(key => !allowedInputFields.has(key))) {\n throw new LegacyPurchaseContinuationError(\n 'request_invalid',\n 'Legacy purchase continuation input contains an unknown field.'\n );\n }\n const idempotencyKey = optionalString(value.idempotency_key);\n const token = optionalString(value.continuation_token);\n if (\n !idempotencyKey ||\n !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(idempotencyKey)\n ) {\n throw new LegacyPurchaseContinuationError('request_invalid', 'idempotency_key must be a UUID.');\n }\n if (!token || token.length < 16) {\n throw new LegacyPurchaseContinuationError(\n 'request_invalid',\n 'continuation_token must contain at least 16 characters.'\n );\n }\n const selectedProductIds = array(value.selected_product_ids);\n if (\n selectedProductIds.length === 0 ||\n selectedProductIds.some(productId => !optionalString(productId)) ||\n new Set(selectedProductIds).size !== selectedProductIds.length\n ) {\n throw new LegacyPurchaseContinuationError(\n 'selection_mismatch',\n 'selected_product_ids must be a non-empty set of distinct product IDs.'\n );\n }\n const acceptedLosses = array(value.accepted_losses);\n if (\n acceptedLosses.some(\n loss =>\n !['feed_version_not_atomic', 'pricing_version_not_atomic', 'mutation_idempotency_not_guaranteed'].includes(\n String(loss)\n )\n ) ||\n new Set(acceptedLosses).size !== acceptedLosses.length\n ) {\n throw new LegacyPurchaseContinuationError(\n 'loss_mismatch',\n 'accepted_losses contains an unknown or duplicate loss.'\n );\n }\n let continuation: LegacyPurchaseContinuationRecord | undefined;\n try {\n continuation = await this.legacyPurchaseContinuationStore.get(token);\n } catch (error) {\n throw new LegacyPurchaseContinuationError(\n 'store_error',\n 'Could not load the legacy purchase continuation.',\n true,\n undefined,\n error\n );\n }\n if (!continuation)\n throw new LegacyPurchaseContinuationError('not_found', 'Legacy purchase continuation not found.');\n const accountScope = this.accountScope(value.account);\n if (!accountScope) {\n throw new LegacyPurchaseContinuationError(\n 'binding_mismatch',\n 'Legacy purchase continuation redemption requires an explicit account.'\n );\n }\n const expectedBinding = this.legacyPurchaseBinding(accountScope);\n const stableBindingMatches =\n continuation.principalScope === expectedBinding.principalScope &&\n continuation.accountScope === expectedBinding.accountScope &&\n continuation.sellerScope === expectedBinding.sellerScope &&\n continuation.clientSessionScope === expectedBinding.clientSessionScope &&\n continuation.sourceAdcpVersion === expectedBinding.sourceAdcpVersion;\n const discoveryBindingMatches =\n continuation.operation.state !== 'available' ||\n continuation.discoveryContextId === expectedBinding.discoveryContextId;\n if (!stableBindingMatches || !discoveryBindingMatches) {\n throw new LegacyPurchaseContinuationError(\n 'binding_mismatch',\n 'Legacy purchase continuation does not belong to this principal, account, seller, or authenticated session.'\n );\n }\n const exactSet = (left: readonly unknown[], right: readonly unknown[]): boolean =>\n left.length === right.length && left.every(item => right.includes(item));\n if (!exactSet(acceptedLosses, continuation.losses)) {\n throw new LegacyPurchaseContinuationError(\n 'loss_mismatch',\n 'accepted_losses must exactly match the loss set returned with the continuation.'\n );\n }\n if (!selectedProductIds.every(productId => continuation!.productIds.includes(String(productId)))) {\n throw new LegacyPurchaseContinuationError(\n 'selection_mismatch',\n 'selected_product_ids contains a product not bound to this continuation.'\n );\n }\n const legacyRequest = record(value.legacy_create_request);\n if (Object.hasOwn(legacyRequest, 'proposal_id')) {\n throw new LegacyPurchaseContinuationError(\n 'request_invalid',\n 'legacy_create_request must use explicit packages and must not execute a proposal.'\n );\n }\n const packages = array(legacyRequest.packages);\n const packageProductIds = packages.map(pkg => optionalString(record(pkg).product_id));\n if (\n packages.length === 0 ||\n packageProductIds.some(productId => productId === undefined) ||\n new Set(packageProductIds).size !== packageProductIds.length ||\n !exactSet(packageProductIds, selectedProductIds)\n ) {\n throw new LegacyPurchaseContinuationError(\n 'selection_mismatch',\n 'The distinct legacy_create_request package product IDs must exactly match selected_product_ids.'\n );\n }\n const observedPricingOptions = new Map<string, Set<string>>();\n for (const product of array(record(continuation.observedResponse).products)) {\n const productRecord = record(product);\n const productId = optionalString(productRecord.product_id);\n if (!productId) continue;\n observedPricingOptions.set(\n productId,\n new Set(\n array(productRecord.pricing_options)\n .map(option => optionalString(record(option).pricing_option_id))\n .filter((pricingOptionId): pricingOptionId is string => pricingOptionId !== undefined)\n )\n );\n }\n if (\n packages.some(pkg => {\n const packageRecord = record(pkg);\n const productId = optionalString(packageRecord.product_id);\n const pricingOptionId = optionalString(packageRecord.pricing_option_id);\n return !productId || !pricingOptionId || !observedPricingOptions.get(productId)?.has(pricingOptionId);\n })\n ) {\n throw new LegacyPurchaseContinuationError(\n 'selection_mismatch',\n 'Every legacy_create_request package pricing_option_id must match an option observed for its selected product.'\n );\n }\n if (continuation.sourceAdcpVersion !== '2.5' && this.accountScope(legacyRequest.account) !== accountScope) {\n throw new LegacyPurchaseContinuationError(\n 'binding_mismatch',\n 'legacy_create_request.account must match the continuation account.'\n );\n }\n const validation = validateRequest(\n 'create_media_buy',\n legacyRequest,\n continuation.sourceAdcpVersion === '2.5' ? 'v2.5' : continuation.sourceAdcpVersion\n );\n if (!validation.valid) {\n throw new LegacyPurchaseContinuationError(\n 'request_invalid',\n `legacy_create_request is invalid for AdCP ${continuation.sourceAdcpVersion}: ${formatIssues(validation.issues)}`\n );\n }\n const claim: LegacyPurchaseClaim = {\n idempotencyKey,\n inputFingerprint: requestFingerprint(input),\n operationKey: requestFingerprint({\n operation: 'continueLegacyPurchase',\n principalScope: expectedBinding.principalScope,\n accountScope: expectedBinding.accountScope,\n sellerScope: expectedBinding.sellerScope,\n clientSessionScope: expectedBinding.clientSessionScope,\n idempotencyKey,\n }),\n claimedAt: new Date().toISOString(),\n replayExpiresAt: new Date(Date.now() + this.legacyPurchaseOperationTtlMs).toISOString(),\n selectedProductIds: selectedProductIds.map(String),\n ...(optionalString(legacyRequest.idempotency_key ?? legacyRequest.buyer_ref) !== undefined && {\n sourceMutationKey: optionalString(legacyRequest.idempotency_key ?? legacyRequest.buyer_ref),\n }),\n };\n let claimedForDispatch = false;\n const claimBeforeDispatch = async (\n effectiveParams: unknown,\n context: { governanceAdjusted: boolean }\n ): Promise<{ action: 'dispatch_committed' } | { action: 'return'; result: TaskResult<CreateMediaBuyResponse> }> => {\n // Legacy continuation consent binds the complete pre-governance purchase.\n // Unlike native 3.2 proposal execution, it has no mechanism for the\n // caller to approve rewritten commercial terms, so fail closed before\n // claiming whenever governance changed the seller payload.\n if (context.governanceAdjusted) {\n throw new LegacyPurchaseContinuationError(\n 'request_invalid',\n 'Governance conditions cannot rewrite a legacy purchase continuation request.'\n );\n }\n const finalRequest = record(effectiveParams);\n const finalPackages = array(finalRequest.packages);\n const finalProductIds = finalPackages.map(pkg => optionalString(record(pkg).product_id));\n if (\n finalPackages.length === 0 ||\n finalProductIds.some(productId => productId === undefined) ||\n new Set(finalProductIds).size !== finalProductIds.length ||\n !exactSet(finalProductIds, selectedProductIds)\n ) {\n throw new LegacyPurchaseContinuationError(\n 'selection_mismatch',\n 'The final seller payload product IDs must exactly match the continuation selection.'\n );\n }\n if (\n finalPackages.some(pkg => {\n const packageRecord = record(pkg);\n const productId = optionalString(packageRecord.product_id);\n const pricingOptionId = optionalString(packageRecord.pricing_option_id);\n return !productId || !pricingOptionId || !observedPricingOptions.get(productId)?.has(pricingOptionId);\n })\n ) {\n throw new LegacyPurchaseContinuationError(\n 'selection_mismatch',\n 'The final seller payload pricing options must match the observed product snapshot.'\n );\n }\n if (continuation.sourceAdcpVersion !== '2.5' && this.accountScope(finalRequest.account) !== accountScope) {\n throw new LegacyPurchaseContinuationError(\n 'binding_mismatch',\n 'The final seller payload account must match the continuation account.'\n );\n }\n const finalMutationKey = optionalString(finalRequest.idempotency_key ?? finalRequest.buyer_ref);\n if (claim.sourceMutationKey !== undefined && finalMutationKey !== claim.sourceMutationKey) {\n throw new LegacyPurchaseContinuationError(\n 'binding_mismatch',\n 'The final seller payload mutation key must match the continuation request.'\n );\n }\n\n let claimed;\n try {\n claimed = await this.legacyPurchaseContinuationStore.claim(token, {\n claim,\n expected: expectedBinding,\n });\n } catch (error) {\n throw new LegacyPurchaseContinuationError(\n 'store_error',\n 'Could not atomically claim the legacy purchase continuation.',\n true,\n undefined,\n error\n );\n }\n if (claimed.outcome === 'missing') {\n throw new LegacyPurchaseContinuationError('not_found', 'Legacy purchase continuation not found.');\n }\n if (claimed.outcome === 'conflict') {\n throw new LegacyPurchaseContinuationError(\n 'conflict',\n 'Legacy purchase continuation was already claimed by a different coordinator operation.'\n );\n }\n if (claimed.outcome === 'expired') {\n throw new LegacyPurchaseContinuationError(\n 'expired',\n 'The legacy purchase continuation or its deterministic replay window has expired.'\n );\n }\n if (claimed.outcome === 'binding_mismatch') {\n throw new LegacyPurchaseContinuationError(\n 'binding_mismatch',\n 'Legacy purchase continuation does not belong to this principal, account, seller session, and source version.'\n );\n }\n if (claimed.outcome === 'replay') return { action: 'return', result: attachMatch(claimed.result) };\n if (claimed.outcome === 'in_flight' || claimed.outcome === 'ambiguous') {\n const age =\n Date.now() -\n Date.parse(\n claimed.record.operation.state === 'available' ? claim.claimedAt : claimed.record.operation.claimedAt\n );\n if (claimed.outcome === 'in_flight' && age < this.legacyPurchaseClaimTimeoutMs) {\n throw new LegacyPurchaseContinuationError(\n 'in_flight',\n 'The exact legacy purchase continuation operation is still in flight.',\n true\n );\n }\n if (this.reconcileLegacyPurchase) {\n let reconciled;\n try {\n reconciled = await this.reconcileLegacyPurchase(claimed.record, input);\n } catch (error) {\n throw this.legacyPurchaseAmbiguousError('Legacy create reconciliation failed without authority.', error);\n }\n if (reconciled.outcome === 'completed') {\n const terminal = this.assertLegacyPurchaseTerminalResult(reconciled.result, continuation.sourceAdcpVersion);\n return {\n action: 'return',\n result: attachMatch(await this.completeLegacyPurchase(token, claim, terminal)),\n };\n }\n }\n throw new LegacyPurchaseContinuationError(\n 'ambiguous',\n 'The legacy create outcome is not authoritative; reconcile it before any further mutation.',\n false,\n 'Configure reconcileLegacyPurchase to query the seller by an application-owned natural key.'\n );\n }\n claimedForDispatch = true;\n return { action: 'dispatch_committed' };\n };\n\n try {\n const result = await this.agent.createMediaBuyLegacyWithPreDispatch(\n legacyRequest as unknown as CreateMediaBuyRequest,\n claimBeforeDispatch,\n inputHandler,\n {\n ...options,\n skipAccountValidation: true,\n skipIdempotencyAutoInject: true,\n }\n );\n if (!claimedForDispatch) return result;\n return this.trackLegacyPurchaseResult(token, claim, result);\n } catch (error) {\n if (!claimedForDispatch) throw error;\n if (error instanceof LegacyPurchaseContinuationError) {\n if (error.code === 'ambiguous') {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'create_media_buy_result_invalid');\n }\n throw error;\n }\n await this.markLegacyPurchaseAmbiguous(token, claim, 'create_media_buy_transport_uncertain');\n throw this.legacyPurchaseAmbiguousError('The legacy create transport failed after the token was claimed.', error);\n }\n }\n\n private async completeLegacyPurchase(\n token: string,\n claim: LegacyPurchaseClaim,\n result: LegacyPurchaseTerminalResult\n ): Promise<LegacyPurchaseTerminalResult> {\n try {\n const completed = await this.legacyPurchaseContinuationStore.complete(token, claim, result);\n if (completed.outcome === 'completed') return completed.result;\n } catch (error) {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'completion_persistence_failed');\n throw new LegacyPurchaseContinuationError(\n 'store_error',\n 'Could not persist the legacy create result; the outcome is ambiguous.',\n false,\n 'Reconcile the seller mutation by its application-owned natural key.',\n error\n );\n }\n await this.markLegacyPurchaseAmbiguous(token, claim, 'completion_compare_and_set_failed');\n throw new LegacyPurchaseContinuationError(\n 'store_error',\n 'Could not atomically persist the legacy create result; the outcome is ambiguous.',\n false,\n 'Reconcile the seller mutation by its application-owned natural key.'\n );\n }\n\n private legacyPurchaseAmbiguousError(message: string, cause?: unknown): LegacyPurchaseContinuationError {\n return new LegacyPurchaseContinuationError(\n 'ambiguous',\n message,\n false,\n 'Configure reconcileLegacyPurchase to query the seller by the durable sourceMutationKey or sellerTaskId.',\n cause\n );\n }\n\n private assertLegacyPurchaseTerminalResult(\n candidate: unknown,\n sourceVersion: LegacyPurchaseSourceVersion\n ): LegacyPurchaseTerminalResult {\n const result = record(candidate) as Partial<TaskResult<CreateMediaBuyResponse>>;\n const metadata = record(result.metadata);\n if (metadata.taskName !== 'create_media_buy') {\n throw this.legacyPurchaseAmbiguousError('The legacy create terminal result has the wrong task identity.');\n }\n if (result.status === 'completed' && result.success === true) {\n if (result.data === undefined) {\n throw this.legacyPurchaseAmbiguousError('The seller reported completion without a create_media_buy result.');\n }\n const validation = validateResponse(\n 'create_media_buy',\n result.data,\n sourceVersion === '2.5' ? 'v2.5' : sourceVersion\n );\n if (!validation.valid) {\n throw this.legacyPurchaseAmbiguousError(\n `The seller returned an invalid terminal create_media_buy result: ${formatIssues(validation.issues)}`\n );\n }\n } else if (\n (result.status !== 'failed' && result.status !== 'governance-denied') ||\n result.success !== false ||\n typeof result.error !== 'string'\n ) {\n throw this.legacyPurchaseAmbiguousError('The legacy create result is not a valid terminal TaskResult.');\n }\n\n // Functions and typed Error prototypes are not portable durable-store\n // values. Structured AdCP error data remains available for replay.\n const {\n match: _match,\n errorInstance: _errorInstance,\n conversation: _conversation,\n debug_logs: _debugLogs,\n ...serializable\n } = result as TaskResult<CreateMediaBuyResponse>;\n void _match;\n void _errorInstance;\n void _conversation;\n void _debugLogs;\n if (containsCredentialShapedKey(serializable) || containsPresignedUrl(serializable)) {\n throw this.legacyPurchaseAmbiguousError(\n 'The legacy create terminal result contains credential-shaped material and cannot be persisted.'\n );\n }\n if (Buffer.byteLength(canonicalize(serializable), 'utf8') > 256 * 1024) {\n throw this.legacyPurchaseAmbiguousError(\n 'The legacy create terminal result exceeds the 256 KiB durable replay limit.'\n );\n }\n return serializable as LegacyPurchaseTerminalResult;\n }\n\n private async markLegacyPurchaseAmbiguous(token: string, claim: LegacyPurchaseClaim, reason: string): Promise<void> {\n try {\n await this.legacyPurchaseContinuationStore.markAmbiguous(token, claim, reason);\n } catch {\n // The original mutation/storage error remains more actionable. Stores\n // must make claim records durable before returning from claim().\n }\n }\n\n private async trackLegacyPurchaseResult(\n token: string,\n claim: LegacyPurchaseClaim,\n result: TaskResult<CreateMediaBuyResponse>\n ): Promise<TaskResult<CreateMediaBuyResponse>> {\n if (result.status === 'completed' || result.status === 'failed' || result.status === 'governance-denied') {\n // TaskExecutor also uses status=failed for local response-schema and\n // unknown-envelope failures. Those do not prove that the seller\n // authoritatively rejected the mutation: it may have succeeded and\n // returned a malformed completion. Persist only structured AdCP\n // failures; otherwise fence the claimed operation as ambiguous.\n if (result.status === 'failed' && result.adcpError === undefined) {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'create_media_buy_failure_not_authoritative');\n throw this.legacyPurchaseAmbiguousError(\n 'The legacy create failure was not an authoritative structured AdCP error.'\n );\n }\n const terminal = this.assertLegacyPurchaseTerminalResult(result, this.legacyPurchaseSourceVersion());\n return attachMatch(await this.completeLegacyPurchase(token, claim, terminal));\n }\n if (result.submitted) {\n const submitted = result.submitted;\n try {\n const recorded = await this.legacyPurchaseContinuationStore.recordSubmittedTask(token, claim, submitted.taskId);\n if (!recorded) {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'submitted_task_persistence_failed');\n throw this.legacyPurchaseAmbiguousError('Could not durably bind the submitted seller task.');\n }\n } catch (error) {\n if (error instanceof LegacyPurchaseContinuationError) throw error;\n await this.markLegacyPurchaseAmbiguous(token, claim, 'submitted_task_persistence_failed');\n throw this.legacyPurchaseAmbiguousError('Could not durably bind the submitted seller task.', error);\n }\n const failureFieldsFromTask = (task: Awaited<ReturnType<typeof submitted.track>>) => {\n const adcpError = extractAdcpErrorInfo(task.result);\n const correlationId = extractCorrelationId(task.result);\n return {\n // tasks/get free text is not a durable-safe boundary. Preserve a\n // structured AdCP message when present; otherwise replay a generic\n // error while retaining the seller payload in data for inspection.\n error: adcpError?.message ?? 'Legacy create failed.',\n ...(adcpError !== undefined && { adcpError }),\n ...(correlationId !== undefined && { correlationId }),\n };\n };\n const observeTask = async (\n transport?: import('../protocols').TransportOptions,\n observationSignal?: AbortSignal\n ) => {\n try {\n const task = observationSignal\n ? await withAbortSignal([observationSignal], undefined, () => submitted.track(transport))\n : await submitted.track(transport);\n if (['completed', 'failed', 'rejected', 'canceled', 'governance-denied'].includes(task.status)) {\n if (task.taskType !== 'create_media_buy') {\n throw this.legacyPurchaseAmbiguousError('The tracked seller task has the wrong task identity.');\n }\n if (task.status === 'completed' && task.result === undefined) {\n throw this.legacyPurchaseAmbiguousError(\n 'The tracked seller task reported completion without a create_media_buy result.'\n );\n }\n const completedSuccessfully =\n task.status === 'completed' && isAdcpOperationSuccess(task.result, task.taskType);\n if (\n !completedSuccessfully &&\n task.status !== 'governance-denied' &&\n extractAdcpErrorInfo(task.result) === undefined\n ) {\n throw this.legacyPurchaseAmbiguousError(\n 'The tracked legacy create failure was not an authoritative structured AdCP error.'\n );\n }\n const terminal = this.assertLegacyPurchaseTerminalResult(\n {\n success: completedSuccessfully,\n status: completedSuccessfully\n ? 'completed'\n : task.status === 'governance-denied'\n ? 'governance-denied'\n : 'failed',\n ...(completedSuccessfully\n ? { data: task.result }\n : {\n ...failureFieldsFromTask(task),\n ...(task.result !== undefined && { data: task.result }),\n }),\n metadata: {\n ...result.metadata,\n status: completedSuccessfully\n ? 'completed'\n : task.status === 'governance-denied'\n ? 'governance-denied'\n : 'failed',\n timestamp: new Date().toISOString(),\n },\n },\n this.legacyPurchaseSourceVersion()\n );\n const canonical = await this.completeLegacyPurchase(token, claim, terminal);\n return {\n ...task,\n status: canonical.status,\n taskType: 'create_media_buy',\n ...(canonical.data !== undefined ? { result: canonical.data } : { result: undefined }),\n ...(canonical.status === 'completed'\n ? { error: undefined }\n : { error: canonical.error ?? 'Legacy create failed.' }),\n updatedAt: Date.now(),\n };\n }\n return task;\n } catch (error) {\n // A shared observer may disappear while its tasks/get request is in\n // flight. A late rejection belongs to that abandoned local observer;\n // it is not evidence that the seller mutation itself is ambiguous.\n if (observationSignal?.aborted) throw createAbortError(observationSignal.reason);\n if (error instanceof LegacyPurchaseContinuationError) {\n if (error.code === 'ambiguous') {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'tracked_task_result_invalid');\n }\n throw error;\n }\n await this.markLegacyPurchaseAmbiguous(token, claim, 'tasks_get_transport_uncertain');\n throw this.legacyPurchaseAmbiguousError('Legacy create task tracking failed after claim.', error);\n }\n };\n const resultFromTask = (\n task: Awaited<ReturnType<typeof submitted.track>>\n ): TaskResult<CreateMediaBuyResponse> | undefined => {\n const metadata = {\n ...result.metadata,\n taskName: task.taskType,\n timestamp: new Date().toISOString(),\n };\n if (\n task.status === 'completed' &&\n task.result !== undefined &&\n isAdcpOperationSuccess(task.result, task.taskType)\n ) {\n return attachMatch({\n success: true,\n status: 'completed',\n data: task.result as CreateMediaBuyResponse,\n metadata: { ...metadata, status: 'completed' },\n });\n }\n if (task.status === 'unknown') {\n throw this.legacyPurchaseAmbiguousError(\n 'tasks/get returned an unrecognizable response for the submitted legacy purchase.'\n );\n }\n if (['completed', 'failed', 'rejected', 'canceled', 'governance-denied'].includes(task.status)) {\n const status = task.status === 'governance-denied' ? 'governance-denied' : 'failed';\n return attachMatch({\n success: false,\n status,\n ...failureFieldsFromTask(task),\n ...(task.result !== undefined && { data: task.result as CreateMediaBuyResponse }),\n metadata: { ...metadata, status },\n } as TaskResult<CreateMediaBuyResponse>);\n }\n if (task.status === 'input-required' || task.status === 'auth-required') {\n return attachMatch({\n success: true,\n status: task.status,\n ...(task.result !== undefined && { data: task.result as CreateMediaBuyResponse }),\n metadata: { ...metadata, status: task.status },\n } as TaskResult<CreateMediaBuyResponse>);\n }\n return undefined;\n };\n type SharedCompletion = {\n controller: AbortController;\n pollInterval: number;\n promise: Promise<TaskResult<CreateMediaBuyResponse>>;\n settled: boolean;\n subscriberIntervals: Map<symbol, number>;\n wake?: () => void;\n };\n const waitForNextPoll = (state: SharedCompletion, signal: AbortSignal) =>\n new Promise<void>((resolve, reject) => {\n if (signal.aborted) {\n reject(createAbortError(signal.reason));\n return;\n }\n const timer = setTimeout(finish, state.pollInterval);\n const abort = () => finish(createAbortError(signal.reason));\n const wake = () => finish();\n state.wake = wake;\n signal.addEventListener('abort', abort, { once: true });\n function finish(error?: Error) {\n clearTimeout(timer);\n signal.removeEventListener('abort', abort);\n if (state.wake === wake) state.wake = undefined;\n if (error) reject(error);\n else resolve();\n }\n });\n const pollTrackedCompletion = async (state: SharedCompletion, signal: AbortSignal) => {\n while (true) {\n if (signal.aborted) throw createAbortError(signal.reason);\n const task = await observeTask(undefined, signal);\n const observed = resultFromTask(task);\n if (observed) return this.trackLegacyPurchaseResult(token, claim, observed);\n await waitForNextPoll(state, signal);\n }\n };\n let sharedCompletion: SharedCompletion | undefined;\n const waitForSharedCompletion = (requestedPollInterval = 60_000, signal?: AbortSignal) => {\n if (\n !Number.isFinite(requestedPollInterval) ||\n requestedPollInterval < 0 ||\n requestedPollInterval > MAX_TIMER_DELAY_MS\n ) {\n throw new RangeError(`pollInterval must be a finite non-negative number <= ${MAX_TIMER_DELAY_MS}`);\n }\n const pollInterval = requestedPollInterval;\n if (sharedCompletion === undefined) {\n const state: SharedCompletion = {\n controller: new AbortController(),\n pollInterval,\n promise: undefined as unknown as Promise<TaskResult<CreateMediaBuyResponse>>,\n settled: false,\n subscriberIntervals: new Map(),\n };\n state.promise = pollTrackedCompletion(state, state.controller.signal).then(\n completed => {\n state.settled = true;\n // A pause is authoritative for current observers but is not a\n // terminal result. A later wait must be able to start a fresh\n // tasks/get epoch after the caller supplies the required input.\n if (\n (completed.status === 'input-required' || completed.status === 'auth-required') &&\n sharedCompletion === state\n ) {\n sharedCompletion = undefined;\n }\n return completed;\n },\n error => {\n if (sharedCompletion === state) sharedCompletion = undefined;\n throw error;\n }\n );\n sharedCompletion = state;\n }\n const state = sharedCompletion;\n const subscription = Symbol('legacy-purchase-completion-subscriber');\n state.subscriberIntervals.set(subscription, pollInterval);\n const activeInterval = Math.min(...state.subscriberIntervals.values());\n if (activeInterval < state.pollInterval) {\n state.pollInterval = activeInterval;\n state.wake?.();\n } else {\n state.pollInterval = activeInterval;\n }\n return withAbortSignal([signal], undefined, () => state.promise).finally(() => {\n state.subscriberIntervals.delete(subscription);\n if (state.subscriberIntervals.size > 0) {\n state.pollInterval = Math.min(...state.subscriberIntervals.values());\n } else if (!state.settled && sharedCompletion === state) {\n sharedCompletion = undefined;\n // This controller only stops the SDK-owned track/sleep loop. It is\n // never forwarded to waitForCompletion, so an observation timeout\n // cannot become an A2A tasks/cancel request.\n state.controller.abort(createAbortError('No legacy purchase completion observers remain.'));\n }\n });\n };\n (result as { submitted?: unknown }).submitted = {\n ...submitted,\n track: (transport?: import('../protocols').TransportOptions) => observeTask(transport),\n waitForCompletion: async (pollInterval?: number, signal?: AbortSignal) => {\n // Validate caller input before entering the uncertainty boundary so\n // only this local RangeError bypasses durable ambiguity handling.\n if (\n pollInterval !== undefined &&\n (!Number.isFinite(pollInterval) || pollInterval < 0 || pollInterval > MAX_TIMER_DELAY_MS)\n ) {\n throw new RangeError(`pollInterval must be a finite non-negative number <= ${MAX_TIMER_DELAY_MS}`);\n }\n try {\n return await waitForSharedCompletion(pollInterval, signal);\n } catch (error) {\n // A caller stopping its own observation says nothing about the\n // seller mutation. The background observer retains ownership.\n if (isAbortOrTimeoutError(error)) throw error;\n if (error instanceof LegacyPurchaseContinuationError) {\n if (error.code === 'ambiguous') {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'completion_wait_result_invalid');\n }\n throw error;\n }\n await this.markLegacyPurchaseAmbiguous(token, claim, 'completion_wait_transport_uncertain');\n throw this.legacyPurchaseAmbiguousError('Legacy create completion waiting failed after claim.', error);\n }\n },\n };\n\n // Give the returned continuation's caller the first opportunity to set\n // its desired poll interval. If it does not, begin one bounded,\n // SDK-owned track loop on the next timer turn. The timeout races only\n // that observer subscription and never reaches the seller transport.\n const watchSignal = AbortSignal.timeout(Math.min(this.legacyPurchaseOperationTtlMs, 5 * 60 * 1000));\n void new Promise<void>(resolve => setTimeout(resolve, 0))\n .then(() => waitForSharedCompletion(undefined, watchSignal))\n .catch(async error => {\n if (watchSignal.aborted || isAbortOrTimeoutError(error)) return;\n await this.markLegacyPurchaseAmbiguous(token, claim, 'background_completion_watch_uncertain');\n // The durable ambiguous state is the observable outcome. Avoid an\n // unhandled rejection from this best-effort background observer.\n void error;\n });\n }\n if (result.deferred) {\n const deferred = result.deferred;\n (result as { deferred?: unknown }).deferred = {\n ...deferred,\n resume: async (resumeInput: unknown) => {\n try {\n return await this.trackLegacyPurchaseResult(token, claim, await deferred.resume(resumeInput));\n } catch (error) {\n if (error instanceof LegacyPurchaseContinuationError) {\n if (error.code === 'ambiguous') {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'deferred_resume_result_invalid');\n }\n throw error;\n }\n await this.markLegacyPurchaseAmbiguous(token, claim, 'deferred_resume_transport_uncertain');\n throw this.legacyPurchaseAmbiguousError('Legacy create deferred resume failed after claim.', error);\n }\n },\n };\n }\n return attachMatch(result);\n }\n\n async refineProposals(\n params: RefineProposalsInput,\n inputHandler?: InputHandler,\n options?: ProposalRefinementTaskOptions\n ): Promise<CompatibilityTaskResult<CompatibleRefineProposalsResponse, CompatibleRefineProposalsWireResponse>> {\n this.assertActive('refineProposals');\n const lifecycle = this.selectLifecycle('refine_proposals');\n this.assertValidCompactRequest('refine_proposals', params, lifecycle, true);\n if (lifecycle === 'compact') {\n const proposalIds = params.refinements.map(refinement => refinement.proposal_id);\n const retry = this.pendingRefinementRetryCandidate(proposalIds);\n const identity = this.proposalMutationIdempotency(\n params.idempotency_key,\n retry,\n Boolean(options?.skipIdempotencyAutoInject)\n );\n const request: RefineProposalsInput = identity.idempotencyKey\n ? { ...params, idempotency_key: identity.idempotencyKey }\n : params;\n const scopes = this.proposalScopes(proposalIds);\n const accountScope = scopes.length === 1 ? scopes[0] : undefined;\n const pendingRefinement = this.beginPendingRefinement(\n proposalIds,\n true,\n requestFingerprint(request),\n identity.idempotencyKey,\n identity.skipIdempotencyAutoInject\n );\n const attemptEpoch = pendingRefinement.attemptEpoch;\n const dispatchOptions = retry\n ? { ...options, skipIdempotencyAutoInject: retry.skipIdempotencyAutoInject }\n : options;\n const projectOnly = (data: CompatibleRefineProposalsWireResponse) =>\n projectRefineProposals(data, lifecycle, params.refinements);\n const projectAndSettle = (data: CompatibleRefineProposalsWireResponse) => {\n try {\n const projected = projectOnly(data);\n this.settlePendingRefinement(pendingRefinement, projected, attemptEpoch);\n return projected;\n } catch (error) {\n if (!this.disposed) this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n throw error;\n }\n };\n try {\n return await this.captureProposalDispatch(\n accountScope,\n () => this.agent.refineProposals(request, inputHandler, dispatchOptions),\n result =>\n this.adaptProjectedResult(\n result,\n this.makeReport(lifecycle, ['refine_proposals'], []),\n projectAndSettle,\n accountScope,\n true,\n undefined,\n pendingRefinement,\n attemptEpoch\n ),\n projectOnly,\n () => this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch),\n true,\n projected =>\n this.preparePendingRefinementSettlement(\n pendingRefinement,\n projected as CompatibleRefineProposalsResponse,\n attemptEpoch\n ),\n () => this.restorePendingRefinement(pendingRefinement, attemptEpoch)\n );\n } catch (error) {\n if (!this.disposed) this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n throw error;\n }\n }\n\n this.assertProposalLifecycleAvailable('refineProposals');\n\n this.assertOnlyFields('refineProposals', record(params), REFINE_PROPOSALS_FIELDS);\n const legacyRefine: Record<string, unknown>[] = [];\n if (params.refinements.length === 0) {\n throw this.unsupported('refineProposals', 'refinements', 'Proposal refinement requires at least one entry.');\n }\n if (params.governance_context !== undefined) {\n throw this.unsupported(\n 'refineProposals',\n 'governance_context',\n 'Established get_products refinement cannot carry compact governance_context.'\n );\n }\n if ((params as Record<string, unknown>).context_id !== undefined) {\n throw this.unsupported(\n 'refineProposals',\n 'context_id',\n 'Established get_products refinement cannot carry an explicit compact context_id.'\n );\n }\n if (params.push_notification_config !== undefined && compareRelease(this.negotiated_version, '3.1') < 0) {\n throw this.unsupported(\n 'refineProposals',\n 'push_notification_config',\n `The negotiated ${this.negotiated_version} get_products request cannot carry push_notification_config.`\n );\n }\n for (const refinement of params.refinements) {\n const refinementInput = record(refinement);\n if (!optionalString(refinementInput.proposal_id)) {\n throw this.unsupported(\n 'refineProposals',\n 'proposal_id',\n 'Every proposal refinement requires a real proposal_id.'\n );\n }\n if (refinement.action === 'finalize') {\n const unsupportedFields = Object.keys(refinementInput).filter(key => key !== 'proposal_id' && key !== 'action');\n if (unsupportedFields.length > 0) {\n throw this.unsupported(\n 'refineProposals',\n `finalize.${unsupportedFields.join(',')}`,\n `Legacy finalize cannot carry additional compact refinement fields: ${unsupportedFields.join(', ')}.`\n );\n }\n legacyRefine.push({ scope: 'proposal', proposal_id: refinement.proposal_id, action: 'finalize' });\n continue;\n }\n if (refinement.action !== 'revise') {\n throw this.unsupported(\n 'refineProposals',\n 'action',\n `Unsupported compact proposal refinement action: ${String(refinementInput.action)}.`\n );\n }\n const reviseFields = new Set([\n 'proposal_id',\n 'action',\n 'constraints',\n 'product_changes',\n 'alternatives',\n 'ask',\n 'criteria',\n 'change_kind',\n ]);\n const unknownFields = Object.keys(refinementInput).filter(key => !reviseFields.has(key));\n if (unknownFields.length > 0) {\n throw this.unsupported(\n 'refineProposals',\n `refinement.${unknownFields.join(',')}`,\n `Compact proposal refinement fields ${unknownFields.join(', ')} have no declared legacy projection.`\n );\n }\n if (refinement.constraints || refinement.alternatives || refinement.criteria || refinement.change_kind) {\n throw this.unsupported(\n 'refineProposals',\n 'structured proposal refinement',\n 'Hard constraints, alternatives, criteria, and amendment kinds cannot be guaranteed by legacy refinement.'\n );\n }\n legacyRefine.push({\n scope: 'proposal',\n proposal_id: refinement.proposal_id,\n ...(refinement.ask !== undefined && { ask: refinement.ask }),\n });\n for (const [productId, action] of Object.entries(refinement.product_changes ?? {})) {\n if (action !== 'include' && action !== 'omit') {\n throw this.unsupported(\n 'refineProposals',\n `product_changes.${productId}`,\n `Legacy product refinement supports only include or omit, not ${String(action)}.`\n );\n }\n legacyRefine.push({ scope: 'product', product_id: productId, action });\n }\n }\n const proposalIds = params.refinements.map(refinement => refinement.proposal_id);\n const retry = this.pendingRefinementRetryCandidate(proposalIds);\n const identity = this.proposalMutationIdempotency(\n params.idempotency_key,\n retry,\n Boolean(options?.skipIdempotencyAutoInject)\n );\n const request: CanonicalGetProductsRequest = {\n buying_mode: 'refine',\n refine: legacyRefine as CanonicalGetProductsRequest['refine'],\n ...(identity.idempotencyKey && { idempotency_key: identity.idempotencyKey }),\n ...(params.push_notification_config !== undefined && {\n push_notification_config:\n params.push_notification_config as unknown as CanonicalGetProductsRequest['push_notification_config'],\n }),\n ...(params.context !== undefined && { context: params.context as CanonicalGetProductsRequest['context'] }),\n };\n const scopes = this.proposalScopes(proposalIds);\n const accountScope = scopes.length === 1 ? scopes[0] : undefined;\n const pendingRefinement = this.beginPendingRefinement(\n proposalIds,\n true,\n requestFingerprint(request),\n identity.idempotencyKey,\n identity.skipIdempotencyAutoInject\n );\n const attemptEpoch = pendingRefinement.attemptEpoch;\n const dispatchOptions = retry\n ? { ...options, skipIdempotencyAutoInject: retry.skipIdempotencyAutoInject }\n : options;\n const projectOnly = (data: CompatibleRefineProposalsWireResponse) =>\n projectRefineProposals(data, lifecycle, params.refinements);\n const projectAndSettle = (data: CompatibleRefineProposalsWireResponse) => {\n try {\n const projected = projectOnly(data);\n this.settlePendingRefinement(pendingRefinement, projected, attemptEpoch);\n return projected;\n } catch (error) {\n if (!this.disposed) this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n throw error;\n }\n };\n try {\n return await this.captureProposalDispatch(\n accountScope,\n () => this.agent.getProducts(request, inputHandler, dispatchOptions),\n result =>\n this.adaptProjectedResult(\n result,\n this.makeReport(lifecycle, ['get_products'], []),\n projectAndSettle,\n accountScope,\n true,\n undefined,\n pendingRefinement,\n attemptEpoch\n ),\n projectOnly,\n () => this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch),\n true,\n projected =>\n this.preparePendingRefinementSettlement(\n pendingRefinement,\n projected as CompatibleRefineProposalsResponse,\n attemptEpoch\n ),\n () => this.restorePendingRefinement(pendingRefinement, attemptEpoch)\n );\n } catch (error) {\n if (!this.disposed) this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n throw error;\n }\n }\n\n async declineProposals(\n params: MutatingRequestInput<DeclineProposalsRequest>,\n inputHandler?: InputHandler,\n options?: CanonicalProjectionTaskOptions\n ): Promise<CompatibilityTaskResult<CompatibleDeclineProposalsResponse, CompatibleDeclineProposalsWireResponse>> {\n this.assertActive('declineProposals');\n const input = record(params);\n const lifecycle = this.selectLifecycle('decline_proposals');\n const projectOnly = (data: unknown, proposalIds: readonly string[]) =>\n projectDeclineProposals(data, lifecycle, proposalIds, this.negotiated_version);\n if (lifecycle === 'compact') {\n this.assertValidCompactRequest('decline_proposals', params, lifecycle, true);\n const proposalIds = array(input.declines)\n .map(value => optionalString(record(value).proposal_id))\n .filter((value): value is string => value !== undefined);\n const retry = this.pendingDeclineRetryCandidate(proposalIds);\n const identity = this.proposalMutationIdempotency(\n input.idempotency_key,\n retry,\n Boolean(options?.skipIdempotencyAutoInject)\n );\n const request = identity.idempotencyKey ? { ...params, idempotency_key: identity.idempotencyKey } : params;\n const pendingDecline = this.beginPendingDecline(\n proposalIds,\n requestFingerprint(request),\n identity.idempotencyKey,\n identity.skipIdempotencyAutoInject\n );\n const attemptEpoch = pendingDecline.attemptEpoch;\n const dispatchOptions = retry\n ? { ...options, skipIdempotencyAutoInject: retry.skipIdempotencyAutoInject }\n : options;\n const projectAndSettle = (data: unknown) => {\n try {\n const projected = projectOnly(data, proposalIds);\n this.preparePendingDeclineSettlement(pendingDecline, projected, attemptEpoch)();\n return projected;\n } catch (error) {\n if (!this.disposed) this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch);\n throw error;\n }\n };\n try {\n return await this.captureProposalDispatch(\n undefined,\n () => this.agent.declineProposals(request, inputHandler, dispatchOptions),\n result =>\n this.adaptProjectedResult(\n result,\n this.makeReport(lifecycle, ['decline_proposals'], []),\n projectAndSettle,\n undefined,\n false,\n pendingDecline,\n undefined,\n attemptEpoch\n ),\n data => projectOnly(data, proposalIds),\n () => this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch),\n false,\n projected =>\n this.preparePendingDeclineSettlement(\n pendingDecline,\n projected as CompatibleDeclineProposalsResponse,\n attemptEpoch\n )\n );\n } catch (error) {\n if (!this.disposed) this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch);\n throw error;\n }\n }\n\n this.assertProposalLifecycleAvailable('declineProposals');\n\n this.assertOnlyFields('declineProposals', input, DECLINE_PROPOSALS_FIELDS);\n for (const [index, value] of array(input.declines).entries()) {\n this.assertOnlyFields(\n `declineProposals.declines[${index}]`,\n record(value),\n new Set(['proposal_id', 'reason', 'detail'])\n );\n }\n const losses: MediaBuyCompatibilityLoss[] = [\n 'proposal_decline_not_terminal',\n 'proposal_decline_reason_not_forwarded',\n ];\n this.requireAllowed('declineProposals', losses);\n if (input.opportunity !== undefined || input.governance_context !== undefined || input.context_id !== undefined) {\n throw this.unsupported(\n 'declineProposals',\n 'opportunity/governance_context/context_id',\n 'Established proposal omit cannot preserve compact opportunity, governance, or explicit context-ID semantics.'\n );\n }\n if (input.push_notification_config !== undefined && compareRelease(this.negotiated_version, '3.1') < 0) {\n throw this.unsupported(\n 'declineProposals',\n 'push_notification_config',\n `The negotiated ${this.negotiated_version} get_products request cannot carry push_notification_config.`\n );\n }\n const declines = array(input.declines).map(item => {\n const decline = record(item);\n return { scope: 'proposal', proposal_id: decline.proposal_id, action: 'omit' };\n });\n const proposalIds = declines.map(decline => String(decline.proposal_id));\n const retry = this.pendingDeclineRetryCandidate(proposalIds);\n const identity = this.proposalMutationIdempotency(\n input.idempotency_key,\n retry,\n Boolean(options?.skipIdempotencyAutoInject)\n );\n const request: CanonicalGetProductsRequest = {\n buying_mode: 'refine',\n refine: declines as CanonicalGetProductsRequest['refine'],\n ...(identity.idempotencyKey && { idempotency_key: identity.idempotencyKey }),\n ...(input.push_notification_config !== undefined && {\n push_notification_config:\n input.push_notification_config as CanonicalGetProductsRequest['push_notification_config'],\n }),\n ...(input.context !== undefined && { context: input.context as CanonicalGetProductsRequest['context'] }),\n };\n this.assertValidCompactRequest('decline_proposals', params, lifecycle, true);\n const pendingDecline = this.beginPendingDecline(\n proposalIds,\n requestFingerprint(request),\n identity.idempotencyKey,\n identity.skipIdempotencyAutoInject\n );\n const attemptEpoch = pendingDecline.attemptEpoch;\n const dispatchOptions = retry\n ? { ...options, skipIdempotencyAutoInject: retry.skipIdempotencyAutoInject }\n : options;\n const projectAndSettle = (data: unknown) => {\n try {\n const projected = projectOnly(data, proposalIds);\n this.preparePendingDeclineSettlement(pendingDecline, projected, attemptEpoch)();\n return projected;\n } catch (error) {\n if (!this.disposed) this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch);\n throw error;\n }\n };\n try {\n return await this.captureProposalDispatch(\n undefined,\n () => this.agent.getProducts(request, inputHandler, dispatchOptions),\n result =>\n this.adaptProjectedResult(\n result,\n this.makeReport(lifecycle, ['get_products'], losses, [\n 'Legacy proposal omit is not a seller-confirmed terminal decline.',\n 'Legacy proposal omit cannot forward the compact decline reason or detail.',\n ]),\n projectAndSettle,\n undefined,\n false,\n pendingDecline,\n undefined,\n attemptEpoch\n ),\n data => projectOnly(data, proposalIds),\n () => this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch),\n false,\n projected =>\n this.preparePendingDeclineSettlement(\n pendingDecline,\n projected as CompatibleDeclineProposalsResponse,\n attemptEpoch\n )\n );\n } catch (error) {\n if (!this.disposed) this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch);\n throw error;\n }\n }\n\n async buyProducts(\n params: MutatingRequestInput<BuyProductsRequest>,\n inputHandler?: InputHandler,\n options?: TaskOptions\n ): Promise<CompatibilityTaskResult<BuyProductsResponse | CreateMediaBuyResponse>> {\n this.assertActive('buyProducts');\n const input = record(params);\n const lifecycle = this.selectLifecycle('buy_products');\n this.assertLegacyReferenceShapes('buyProducts', input);\n if (lifecycle === 'compact') {\n this.assertValidCompactRequest('buy_products', params, lifecycle, true);\n const result = await this.agent.buyProducts(params, inputHandler, options);\n return this.adaptProjectedResult(result, this.makeReport(lifecycle, ['buy_products'], []), data => data);\n }\n\n this.assertOnlyFields('buyProducts', input, BUY_PRODUCTS_FIELDS);\n this.assertLegacyReportingWebhook('buyProducts', input.reporting_webhook);\n this.assertCompactWireFieldsAbsent('buyProducts', input, [\n 'budget_allocation',\n 'daily_budget_cap',\n 'budget_cap_timezone',\n 'pacing',\n 'bidding',\n 'governance_context',\n 'opportunity',\n 'total_budget',\n ]);\n if (compareRelease(this.negotiated_version, '3.0') < 0) {\n this.assertCompactWireFieldsAbsent('buyProducts', input, [\n 'advertiser_industry',\n 'agency_estimate_number',\n 'invoice_recipient',\n 'push_notification_config',\n ]);\n }\n this.assertLegacyPushNotification('buyProducts', input.push_notification_config);\n if (Object.hasOwn(input, 'paused') && compareRelease(this.negotiated_version, '3.1') < 0) {\n throw this.unsupported(\n 'buyProducts',\n 'paused',\n `The negotiated ${this.negotiated_version} create_media_buy request cannot represent paused.`\n );\n }\n if (!optionalString(input.feed_version)) {\n throw this.unsupported('buyProducts', 'feed_version', 'Compact buy_products requires a real feed_version.');\n }\n if (input.pricing_version !== undefined && !optionalString(input.pricing_version)) {\n throw this.unsupported(\n 'buyProducts',\n 'pricing_version',\n 'When provided, compact pricing_version must be a non-empty seller version.'\n );\n }\n if (input.ext !== undefined) {\n throw this.unsupported('buyProducts', 'ext', 'Compact buy_products.ext has no declared legacy projection.');\n }\n const losses: MediaBuyCompatibilityLoss[] = ['feed_version_not_atomic'];\n if (input.pricing_version !== undefined) losses.push('pricing_version_not_atomic');\n this.requireAllowed('buyProducts', losses);\n for (const field of ['account', 'brand', 'start_time', 'end_time', 'purchases']) {\n if (input[field] === undefined) {\n throw this.unsupported('buyProducts', field, `Legacy create_media_buy requires ${field}.`);\n }\n }\n const purchases = array(input.purchases);\n if (purchases.length === 0) {\n throw this.unsupported('buyProducts', 'purchases', 'Legacy create_media_buy requires at least one purchase.');\n }\n const packageFields = isCompactRelease(this.negotiated_version)\n ? V32_PURCHASE_FIELDS\n : compareRelease(this.negotiated_version, '3.1') >= 0\n ? V31_PURCHASE_FIELDS\n : compareRelease(this.negotiated_version, '3.0') >= 0\n ? V30_PURCHASE_FIELDS\n : V25_PURCHASE_FIELDS;\n const packages = purchases.map((value, index) => {\n const purchase = record(value);\n const unsupportedFields = Object.keys(purchase).filter(key => !packageFields.has(key));\n if (unsupportedFields.length) {\n throw this.unsupported(\n 'buyProducts',\n `purchases[${index}].${unsupportedFields.join(',')}`,\n `Compact purchase fields ${unsupportedFields.join(', ')} have no declared legacy package projection.`\n );\n }\n if (!optionalString(purchase.product_id) || !optionalString(purchase.pricing_option_id)) {\n throw this.unsupported(\n 'buyProducts',\n `purchases[${index}]`,\n 'Every purchase requires real product_id and pricing_option_id values from seller discovery.'\n );\n }\n this.assertLegacyTargetingOverlay(\n 'buyProducts',\n purchase.targeting_overlay,\n `purchases[${index}].targeting_overlay`\n );\n return Object.fromEntries(Object.entries(purchase).filter(([key]) => packageFields.has(key)));\n });\n const request: MutatingRequestInput<CanonicalCreateMediaBuyRequest> = {\n account: input.account as CanonicalCreateMediaBuyRequest['account'],\n brand: input.brand as CanonicalCreateMediaBuyRequest['brand'],\n start_time: input.start_time as CanonicalCreateMediaBuyRequest['start_time'],\n end_time: input.end_time as CanonicalCreateMediaBuyRequest['end_time'],\n packages: packages as CanonicalCreateMediaBuyRequest['packages'],\n ...(input.idempotency_key !== undefined && { idempotency_key: input.idempotency_key as string }),\n ...(input.total_budget !== undefined && {\n total_budget: input.total_budget as CanonicalCreateMediaBuyRequest['total_budget'],\n }),\n ...(input.daily_budget_cap !== undefined && { daily_budget_cap: input.daily_budget_cap as number }),\n ...(input.budget_cap_timezone !== undefined && { budget_cap_timezone: input.budget_cap_timezone as string }),\n ...(input.budget_allocation !== undefined && {\n budget_allocation: input.budget_allocation as CanonicalCreateMediaBuyRequest['budget_allocation'],\n }),\n ...(input.pacing !== undefined && { pacing: input.pacing as CanonicalCreateMediaBuyRequest['pacing'] }),\n ...(input.bidding !== undefined && { bidding: input.bidding as CanonicalCreateMediaBuyRequest['bidding'] }),\n ...(input.paused !== undefined && { paused: input.paused as boolean }),\n ...(input.advertiser_industry !== undefined && {\n advertiser_industry: input.advertiser_industry as CanonicalCreateMediaBuyRequest['advertiser_industry'],\n }),\n ...(input.purchase_order_ref !== undefined && { po_number: input.purchase_order_ref as string }),\n ...(input.agency_estimate_number !== undefined && {\n agency_estimate_number: input.agency_estimate_number as string,\n }),\n ...(input.invoice_recipient !== undefined && {\n invoice_recipient: input.invoice_recipient as CanonicalCreateMediaBuyRequest['invoice_recipient'],\n }),\n ...(input.governance_context !== undefined && { governance_context: input.governance_context as string }),\n ...(input.opportunity !== undefined && {\n opportunity: input.opportunity as CanonicalCreateMediaBuyRequest['opportunity'],\n }),\n ...(input.reporting_webhook !== undefined && {\n reporting_webhook: input.reporting_webhook as CanonicalCreateMediaBuyRequest['reporting_webhook'],\n }),\n ...(input.push_notification_config !== undefined && {\n push_notification_config:\n input.push_notification_config as CanonicalCreateMediaBuyRequest['push_notification_config'],\n }),\n ...(input.context !== undefined && { context: input.context as CanonicalCreateMediaBuyRequest['context'] }),\n };\n this.assertValidCompactRequest('buy_products', params, lifecycle, true);\n const result = await this.agent.createMediaBuy(request, inputHandler, options);\n return this.adaptProjectedResult(\n result,\n this.makeReport(lifecycle, ['create_media_buy'], losses, [\n 'The established mutation cannot atomically fence the selected feed/pricing snapshot.',\n ]),\n data => data\n );\n }\n\n async acceptProposal(\n params: MutatingRequestInput<CompatibleAcceptProposalRequest>,\n inputHandler?: InputHandler,\n options?: TaskOptions\n ): Promise<CompatibilityTaskResult<AcceptProposalResponse | CreateMediaBuyResponse>> {\n this.assertActive('acceptProposal');\n const input = record(params);\n const lifecycle = this.selectLifecycle('accept_proposal');\n this.assertLegacyReferenceShapes('acceptProposal', input);\n if (lifecycle === 'compact') {\n const proposalId = optionalString(input.proposal_id);\n if (proposalId && this.isProposalDeclinePending(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_decline_pending',\n 'The proposal has an unresolved decline in this principal scope. Wait for or reconcile that decline before accepting it.'\n );\n }\n if (proposalId && this.isProposalRefinementPending(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_refinement_pending',\n 'The proposal has an unresolved refinement in this principal scope. Wait for or reconcile that refinement before accepting it.'\n );\n }\n if (proposalId && this.isCommitUncertainProposalMutation(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_mutation_commit_uncertain',\n 'The proposal has a decline or refinement whose commit outcome is unknown. Reconcile it before sending an acceptance.'\n );\n }\n if (proposalId && this.isCommitUncertainProposal(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_commit_uncertain',\n 'The proposal has an established acceptance whose commit outcome is unknown. Reconcile the media buy by natural key before sending another acceptance.'\n );\n }\n if (proposalId && this.isTerminalAcceptanceProposal(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_terminal',\n 'The proposal is terminal in this principal scope. No acceptance was sent.'\n );\n }\n if (proposalId && this.isTerminalProposal(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_terminal',\n 'The proposal was already consumed by a terminal lifecycle mutation in this principal scope. No acceptance was sent.'\n );\n }\n const { established_fallback: _fallback, ...compactInput } = input;\n this.assertValidCompactRequest('accept_proposal', compactInput, lifecycle, true);\n if (!proposalId) {\n throw this.unsupported('acceptProposal', 'proposal_id', 'Native proposal acceptance requires a proposal_id.');\n }\n const prior = this.proposalSnapshotStore.proposalAcceptances.get(proposalId);\n if (\n prior?.reservation.kind === 'established' &&\n prior.reservation.state === 'retryable' &&\n prior.reservation.retryKind === 'commit-uncertain'\n ) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_commit_uncertain',\n 'The proposal has an established acceptance whose commit outcome is unknown. Reconcile or exactly retry that established acceptance before sending a compact acceptance.'\n );\n }\n if (prior?.reservation.state === 'in-flight' || prior?.reservation.kind === 'established') {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_pending',\n 'The proposal already has an acceptance reservation in this principal scope. Wait for it to finish before retrying.'\n );\n }\n const retryable = prior?.reservation.state === 'retryable' ? prior.reservation : undefined;\n if (retryable) this.assertAcceptanceRetryWindow(prior!.snapshotKey, prior!.snapshot, retryable);\n const skipIdempotencyAutoInject =\n retryable?.skipIdempotencyAutoInject ?? Boolean(options?.skipIdempotencyAutoInject);\n const idempotencyKey =\n optionalString(compactInput.idempotency_key) ??\n retryable?.idempotencyKey ??\n (!skipIdempotencyAutoInject ? generateIdempotencyKey() : undefined);\n const request = {\n ...compactInput,\n ...(idempotencyKey && { idempotency_key: idempotencyKey }),\n } as MutatingRequestInput<AcceptProposalRequest>;\n const fingerprint = requestFingerprint(request);\n if (\n retryable &&\n (retryable.kind !== 'native' ||\n retryable.requestFingerprint !== fingerprint ||\n retryable.idempotencyKey !== idempotencyKey ||\n retryable.skipIdempotencyAutoInject !== skipIdempotencyAutoInject)\n ) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_retry',\n 'A paused or commit-uncertain native acceptance may retry only the exact same request and idempotency key. No mutation was sent.'\n );\n }\n if (retryable?.taskId) this.forgetAcceptanceTask(retryable.taskId, retryable);\n if (retryable) this.releaseAcceptanceOwnership(retryable);\n const accountScope = this.accountScope(compactInput.account);\n const snapshotKey = prior?.snapshotKey ?? `${this.snapshotKey(proposalId, accountScope)}\\u0000native-acceptance`;\n const snapshot =\n prior?.snapshot ??\n ({\n proposal: { proposal_id: proposalId },\n bytes: new TextEncoder().encode(snapshotKey).byteLength,\n principalScope: this.principalScope ?? '',\n executable: false,\n nativeAcceptanceOnly: true,\n ...(accountScope && { accountScope }),\n } satisfies ProposalSnapshotEntry);\n if (!prior) {\n this.retainProposalSnapshot(snapshotKey, snapshot);\n this.enforceProposalSnapshotLimits();\n if (this.proposalSnapshotStore.entries.get(snapshotKey) !== snapshot) {\n throw new ConfigurationError(\n 'The media-buy proposal snapshot limit could not retain a native acceptance fence.',\n 'mediaBuy.proposalSnapshots'\n );\n }\n }\n const retryDeadlineMs =\n retryable?.retryDeadlineMs ??\n (this.idempotencyReplayTtlMs !== undefined ? Date.now() + this.idempotencyReplayTtlMs : undefined);\n const reservation: AcceptanceReservation = {\n kind: 'native',\n state: 'in-flight',\n requestFingerprint: fingerprint,\n skipIdempotencyAutoInject,\n ...(idempotencyKey && { idempotencyKey }),\n };\n if (retryDeadlineMs !== undefined) {\n Object.defineProperty(reservation, 'retryDeadlineMs', {\n value: retryDeadlineMs,\n enumerable: true,\n writable: false,\n configurable: false,\n });\n }\n snapshot.executable = false;\n snapshot.acceptance = reservation;\n this.proposalSnapshotStore.proposalAcceptances.set(proposalId, { snapshotKey, snapshot, reservation });\n this.ownedAcceptanceReservations.set(reservation, { snapshotKey, snapshot });\n acceptanceReservationOwners.set(reservation, this);\n let result: TaskResult<AcceptProposalResponse>;\n try {\n result = await this.agent.acceptProposal(request, inputHandler, {\n ...options,\n skipIdempotencyAutoInject,\n });\n } catch (error) {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation);\n throw error;\n }\n const transitioned = this.attachAcceptanceTransitions(result, snapshotKey, snapshot, reservation);\n return this.adaptProjectedResult(transitioned, this.makeReport(lifecycle, ['accept_proposal'], []), data => data);\n }\n\n this.assertProposalLifecycleAvailable('acceptProposal');\n this.assertOnlyFields('acceptProposal', input, ACCEPT_PROPOSAL_FIELDS);\n this.assertLegacyReportingWebhook('acceptProposal', input.reporting_webhook);\n this.assertLegacyPushNotification('acceptProposal', input.push_notification_config);\n this.assertCompactWireFieldsAbsent('acceptProposal', input, [\n 'daily_budget_cap',\n 'budget_cap_timezone',\n 'governance_context',\n 'opportunity',\n ]);\n const suppliedDigest = optionalString(input.proposal_terms_digest);\n if (input.ext !== undefined) {\n throw this.unsupported('acceptProposal', 'ext', 'Compact accept_proposal.ext has no declared legacy projection.');\n }\n const proposalId = optionalString(input.proposal_id);\n if (!proposalId || input.account === undefined) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_id/account',\n 'Legacy proposal acceptance requires a real proposal_id and account.'\n );\n }\n if (!this.principalScope) {\n throw this.unsupported(\n 'acceptProposal',\n 'principal_scope',\n 'Established proposal acceptance requires a stable, non-secret principalScope when negotiating the coordinator. No mutation was sent.'\n );\n }\n if (this.isProposalDeclinePending(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_decline_pending',\n 'The proposal has an unresolved decline in this principal scope. Wait for that decline to finish before accepting it.'\n );\n }\n if (this.isProposalRefinementPending(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_refinement_pending',\n 'The proposal has an unresolved refinement in this principal scope. Wait for that refinement to finish before accepting it.'\n );\n }\n const accountScope = this.accountScope(input.account);\n const snapshotKey = accountScope ? this.snapshotKey(proposalId, accountScope) : undefined;\n const globalAcceptance = this.proposalSnapshotStore.proposalAcceptances.get(proposalId);\n if (globalAcceptance && globalAcceptance.snapshotKey !== snapshotKey) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_pending',\n 'The proposal already has an acceptance reservation in this principal scope. Reuse the original account scope for an exact retry.'\n );\n }\n if (globalAcceptance?.reservation.state === 'in-flight') {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_pending',\n 'The proposal already has an in-flight acceptance in this principal scope. Wait for it to finish before retrying.'\n );\n }\n const snapshot = snapshotKey ? this.proposalSnapshotStore.entries.get(snapshotKey) : undefined;\n const retryableAcceptance =\n globalAcceptance?.reservation.state === 'retryable' ? globalAcceptance.reservation : undefined;\n if (!snapshot || (!snapshot.executable && !retryableAcceptance)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_snapshot/account_scope',\n 'No proposal snapshot is available in the supplied principal and account scope. Request/finalize it through this coordinator first.'\n );\n }\n if (retryableAcceptance) this.assertAcceptanceRetryWindow(snapshotKey!, snapshot, retryableAcceptance);\n const proposal = snapshot.proposal;\n if (proposal.proposal_status !== undefined && proposal.proposal_status !== 'committed') {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_status',\n `Legacy create_media_buy projection cannot accept a proposal in ${String(proposal.proposal_status)} status.`\n );\n }\n if (proposal.proposal_kind !== undefined && proposal.proposal_kind !== 'new_media_buy') {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_kind',\n `Legacy create_media_buy projection supports only new_media_buy proposals, not ${String(proposal.proposal_kind)}.`\n );\n }\n\n const losses = ['proposal_terms_digest_not_enforced'] as MediaBuyCompatibilityLoss[];\n const expiresAt = proposal.expires_at;\n if (expiresAt === undefined) {\n losses.push('proposal_hold_not_verifiable');\n } else {\n if (!isStrictDateTime(expiresAt)) {\n throw this.unsupported(\n 'acceptProposal',\n 'expires_at',\n 'The proposal carries an invalid seller hold expiry. No mutation was sent.'\n );\n }\n const expiry = Date.parse(expiresAt);\n if (!retryableAcceptance && expiry <= Date.now()) {\n throw this.unsupported('acceptProposal', 'expires_at', 'The proposal is expired. No mutation was sent.');\n }\n }\n\n const sellerDigest = optionalString(proposal.terms_digest);\n const terms = record(proposal.commercial_terms);\n const digestBoundTerms = Boolean(sellerDigest && Object.keys(terms).length > 0);\n if (sellerDigest && snapshot.canonicalTermsDigest) {\n if (sellerDigest !== snapshot.canonicalTermsDigest) {\n throw new MediaBuyLifecycleCompatibilityError({\n operation: 'acceptProposal',\n negotiatedVersion: this.negotiated_version,\n lifecycle,\n feature: 'seller_proposal_terms_digest',\n code: 'PROPOSAL_DIGEST_MISMATCH',\n message: 'The seller digest is not bound to the cached commercial terms. No mutation was sent.',\n });\n }\n if (!suppliedDigest || suppliedDigest !== sellerDigest) {\n throw new MediaBuyLifecycleCompatibilityError({\n operation: 'acceptProposal',\n negotiatedVersion: this.negotiated_version,\n lifecycle,\n feature: 'proposal_terms_digest',\n code: 'PROPOSAL_DIGEST_MISMATCH',\n message: 'The proposal digest differs from the seller-provided snapshot. No mutation was sent.',\n });\n }\n } else {\n losses.push('proposal_terms_digest_unavailable', 'proposal_snapshot_not_immutable');\n }\n\n this.requireAllowed('acceptProposal', losses);\n const resolvedAcceptanceField = (field: string): unknown => {\n const termValue = terms[field];\n const inputValue = input[field];\n if (!digestBoundTerms || termValue === undefined) return inputValue;\n if (inputValue !== undefined) {\n let matches = false;\n try {\n matches = canonicalize(inputValue) === canonicalize(termValue);\n } catch {\n matches = false;\n }\n if (!matches) {\n throw new MediaBuyLifecycleCompatibilityError({\n operation: 'acceptProposal',\n negotiatedVersion: this.negotiated_version,\n lifecycle,\n feature: field,\n code: 'PROPOSAL_DIGEST_MISMATCH',\n message: `Acceptance field ${field} conflicts with the digest-bound seller terms. No mutation was sent.`,\n });\n }\n }\n return termValue;\n };\n const totalBudget = resolvedAcceptanceField('total_budget');\n const dailyBudgetCap = resolvedAcceptanceField('daily_budget_cap');\n const budgetCapTimezone = resolvedAcceptanceField('budget_cap_timezone');\n const purchaseOrderRef = resolvedAcceptanceField('purchase_order_ref');\n if (\n !isCompactRelease(this.negotiated_version) &&\n [dailyBudgetCap, budgetCapTimezone].some(value => value !== undefined)\n ) {\n throw this.unsupported(\n 'acceptProposal',\n 'commercial_terms.daily_budget_cap,budget_cap_timezone',\n `The negotiated ${this.negotiated_version} create_media_buy schema cannot represent compact budget-cap terms. No mutation was sent.`\n );\n }\n const fallback = record(input.established_fallback);\n const brand = terms.brand ?? fallback.brand;\n const startTime = terms.start_time ?? fallback.start_time;\n const endTime = terms.end_time ?? fallback.end_time;\n if (!brand || !startTime || !endTime) {\n throw this.unsupported(\n 'acceptProposal',\n 'established_fallback',\n 'The proposal does not carry compact commercial terms. Supply established_fallback with the original brand and flight.'\n );\n }\n this.assertLegacyReferenceShapes('acceptProposal', { brand });\n if (\n input.idempotency_key !== undefined &&\n (typeof input.idempotency_key !== 'string' || !isValidIdempotencyKey(input.idempotency_key))\n ) {\n throw this.unsupported(\n 'acceptProposal',\n 'idempotency_key',\n 'Established proposal acceptance requires a 16-255 character protocol idempotency key. No mutation was sent.'\n );\n }\n const callerIdempotencyKey = optionalString(input.idempotency_key);\n const acceptanceIdempotencyKey = retryableAcceptance\n ? (callerIdempotencyKey ?? retryableAcceptance.idempotencyKey)\n : (callerIdempotencyKey ?? (!options?.skipIdempotencyAutoInject ? generateIdempotencyKey() : undefined));\n const request: MutatingRequestInput<CanonicalCreateMediaBuyRequest> = {\n account: input.account as CanonicalCreateMediaBuyRequest['account'],\n brand: brand as CanonicalCreateMediaBuyRequest['brand'],\n start_time: startTime as CanonicalCreateMediaBuyRequest['start_time'],\n end_time: endTime as CanonicalCreateMediaBuyRequest['end_time'],\n proposal_id: proposalId,\n ...(acceptanceIdempotencyKey !== undefined && { idempotency_key: acceptanceIdempotencyKey }),\n ...(totalBudget !== undefined && {\n total_budget: totalBudget as CanonicalCreateMediaBuyRequest['total_budget'],\n }),\n ...(dailyBudgetCap !== undefined && { daily_budget_cap: dailyBudgetCap as number }),\n ...(budgetCapTimezone !== undefined && { budget_cap_timezone: budgetCapTimezone as string }),\n ...(purchaseOrderRef !== undefined && { po_number: purchaseOrderRef as string }),\n ...(input.io_acceptance !== undefined && {\n io_acceptance: input.io_acceptance as CanonicalCreateMediaBuyRequest['io_acceptance'],\n }),\n ...(input.governance_context !== undefined && { governance_context: input.governance_context as string }),\n ...(input.opportunity !== undefined && {\n opportunity: input.opportunity as CanonicalCreateMediaBuyRequest['opportunity'],\n }),\n ...(input.reporting_webhook !== undefined && {\n reporting_webhook: input.reporting_webhook as CanonicalCreateMediaBuyRequest['reporting_webhook'],\n }),\n ...(input.push_notification_config !== undefined && {\n push_notification_config:\n input.push_notification_config as CanonicalCreateMediaBuyRequest['push_notification_config'],\n }),\n ...(input.context !== undefined && { context: input.context as CanonicalCreateMediaBuyRequest['context'] }),\n };\n const fingerprint = requestFingerprint(request);\n if (retryableAcceptance && fingerprint !== retryableAcceptance.requestFingerprint) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_retry',\n 'A paused established acceptance must retry the exact same request and idempotency key. No mutation was sent.'\n );\n }\n if (retryableAcceptance) this.assertAcceptanceRetryWindow(snapshotKey!, snapshot, retryableAcceptance);\n if (retryableAcceptance?.taskId) {\n this.forgetAcceptanceTask(retryableAcceptance.taskId, retryableAcceptance);\n }\n if (retryableAcceptance) this.releaseAcceptanceOwnership(retryableAcceptance);\n const retryDeadlineMs =\n retryableAcceptance?.retryDeadlineMs ??\n (this.idempotencyReplayTtlMs !== undefined ? Date.now() + this.idempotencyReplayTtlMs : undefined);\n // Acceptance is one-shot even though the established seller has no\n // compact proposal state transition. The in-map reservation prevents\n // concurrent rediscovery from reauthorizing the proposal. Only an exact\n // paused retry can reuse it; ambiguous outcomes remain fail-closed.\n const reservation: AcceptanceReservation = {\n kind: 'established',\n state: 'in-flight',\n requestFingerprint: fingerprint,\n skipIdempotencyAutoInject:\n retryableAcceptance?.skipIdempotencyAutoInject ?? Boolean(options?.skipIdempotencyAutoInject),\n ...(acceptanceIdempotencyKey && { idempotencyKey: acceptanceIdempotencyKey }),\n };\n if (retryDeadlineMs !== undefined) {\n Object.defineProperty(reservation, 'retryDeadlineMs', {\n value: retryDeadlineMs,\n enumerable: true,\n writable: false,\n configurable: false,\n });\n }\n snapshot.executable = false;\n snapshot.acceptance = reservation;\n this.proposalSnapshotStore.proposalAcceptances.set(proposalId, {\n snapshotKey: snapshotKey!,\n snapshot,\n reservation,\n });\n this.ownedAcceptanceReservations.set(reservation, { snapshotKey: snapshotKey!, snapshot });\n acceptanceReservationOwners.set(reservation, this);\n const dispatchOptions = retryableAcceptance\n ? { ...options, skipIdempotencyAutoInject: retryableAcceptance.skipIdempotencyAutoInject }\n : options;\n let result: TaskResult<CreateMediaBuyResponse>;\n try {\n result = await this.agent.createMediaBuy(request, inputHandler, dispatchOptions);\n } catch (error) {\n this.preserveAmbiguousAcceptance(snapshotKey!, snapshot, reservation);\n throw error;\n }\n const transitioned = this.attachAcceptanceTransitions(result, snapshotKey!, snapshot, reservation);\n return this.adaptProjectedResult(\n transitioned,\n this.makeReport(lifecycle, ['create_media_buy'], losses, [\n 'The established seller accepted its ordinary proposal_id mutation without compact digest enforcement.',\n ...(losses.includes('proposal_terms_digest_unavailable')\n ? [\n 'The seller supplied no terms digest or immutable compact commercial-terms snapshot; none was synthesized.',\n ]\n : []),\n ]),\n data => data\n );\n }\n\n async controlMediaBuy(\n params: MutatingRequestInput<ControlMediaBuyRequest>,\n inputHandler?: InputHandler,\n options?: TaskOptions\n ): Promise<CompatibilityTaskResult<ControlMediaBuyResponse | UpdateMediaBuyResponse>> {\n this.assertActive('controlMediaBuy');\n const input = record(params);\n const lifecycle = this.selectLifecycle('control_media_buy');\n this.assertLegacyReferenceShapes('controlMediaBuy', input);\n if (lifecycle === 'compact') {\n this.assertValidCompactRequest('control_media_buy', params, lifecycle, true);\n const result = await this.agent.controlMediaBuy(params, inputHandler, options);\n return this.adaptProjectedResult(result, this.makeReport(lifecycle, ['control_media_buy'], []), data => data);\n }\n\n this.assertOnlyFields('controlMediaBuy', input, CONTROL_MEDIA_BUY_FIELDS);\n this.assertLegacyReportingWebhook('controlMediaBuy', input.reporting_webhook);\n this.assertLegacyPushNotification('controlMediaBuy', input.push_notification_config);\n this.assertCompactWireFieldsAbsent('controlMediaBuy', input, [\n 'total_budget',\n 'daily_budget_cap',\n 'budget_cap_timezone',\n 'budget_allocation',\n 'pacing',\n 'bidding',\n 'governance_context',\n ]);\n if (compareRelease(this.negotiated_version, '3.0') < 0) {\n this.assertCompactWireFieldsAbsent('controlMediaBuy', input, ['reporting_webhook']);\n }\n const losses: MediaBuyCompatibilityLoss[] = [];\n if (compareRelease(this.negotiated_version, '3.0') < 0) {\n if (Object.hasOwn(input, 'canceled') || Object.hasOwn(input, 'cancellation_reason')) {\n throw this.unsupported(\n 'controlMediaBuy',\n 'canceled,cancellation_reason',\n `The negotiated ${this.negotiated_version} update_media_buy request cannot represent cancellation.`\n );\n }\n losses.push('revision_not_atomic');\n this.requireAllowed('controlMediaBuy', losses);\n }\n if (\n input.account === undefined ||\n !optionalString(input.media_buy_id) ||\n !Number.isInteger(input.revision) ||\n (input.revision as number) < 1\n ) {\n throw this.unsupported(\n 'controlMediaBuy',\n 'account/media_buy_id/revision',\n 'Legacy media-buy control requires a real account, media_buy_id, and positive compact revision.'\n );\n }\n if (input.ext !== undefined) {\n throw this.unsupported(\n 'controlMediaBuy',\n 'ext',\n 'Compact control_media_buy.ext has no declared legacy projection.'\n );\n }\n let packages: CanonicalUpdateMediaBuyRequest['packages'] | undefined;\n if (input.packages !== undefined) {\n if (!Array.isArray(input.packages) || input.packages.length === 0) {\n throw this.unsupported(\n 'controlMediaBuy',\n 'packages',\n 'Compact package controls must be a non-empty array when provided.'\n );\n }\n const packageControlFields = new Set([\n 'package_id',\n 'bidding',\n 'budget',\n 'canceled',\n 'cancellation_reason',\n 'daily_budget_cap',\n 'impressions',\n 'keyword_targets_add',\n 'keyword_targets_remove',\n 'min_spend_target',\n 'negative_keywords_add',\n 'negative_keywords_remove',\n 'optimization_goals',\n 'pacing',\n 'paused',\n 'targeting_overlay',\n ]);\n packages = input.packages.map((value, index) => {\n const packageControl = record(value);\n this.assertCompactWireFieldsAbsent(`controlMediaBuy.packages[${index}]`, packageControl, [\n 'bidding',\n 'daily_budget_cap',\n 'min_spend_target',\n ]);\n if (compareRelease(this.negotiated_version, '3.0') < 0) {\n const v3OnlyFields = [\n 'canceled',\n 'cancellation_reason',\n 'keyword_targets_add',\n 'keyword_targets_remove',\n 'negative_keywords_add',\n 'negative_keywords_remove',\n 'optimization_goals',\n ].filter(field => Object.hasOwn(packageControl, field));\n if (v3OnlyFields.length > 0) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].${v3OnlyFields.join(',')}`,\n `The negotiated ${this.negotiated_version} package update cannot represent ${v3OnlyFields.join(\n ', '\n )}. No mutation was sent.`\n );\n }\n }\n if (!isCompactRelease(this.negotiated_version) && Object.hasOwn(packageControl, 'optimization_goals')) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].optimization_goals`,\n `The negotiated ${this.negotiated_version} optimization goal union cannot represent every compact vendor_metric goal. No mutation was sent.`\n );\n }\n if (!isCompactRelease(this.negotiated_version) && packageControl.budget === null) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].budget`,\n `The negotiated ${this.negotiated_version} package update cannot represent compact budget=null. No mutation was sent.`\n );\n }\n const unsupportedFields = Object.keys(packageControl).filter(key => !packageControlFields.has(key));\n if (unsupportedFields.length > 0) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].${unsupportedFields.join(',')}`,\n `Compact package control fields ${unsupportedFields.join(', ')} have no declared legacy projection.`\n );\n }\n if (!optionalString(packageControl.package_id)) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].package_id`,\n 'Every compact package control requires a real package_id.'\n );\n }\n this.assertLegacyTargetingOverlay(\n 'controlMediaBuy',\n packageControl.targeting_overlay,\n `packages[${index}].targeting_overlay`\n );\n if (packageControl.canceled !== undefined && packageControl.canceled !== true) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].canceled`,\n 'Compact package canceled may only be true when present.'\n );\n }\n if (Object.hasOwn(packageControl, 'cancellation_reason') && !Object.hasOwn(packageControl, 'canceled')) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].cancellation_reason`,\n 'Compact package cancellation_reason requires canceled=true.'\n );\n }\n const keywordDeltaFields = [\n 'keyword_targets_add',\n 'keyword_targets_remove',\n 'negative_keywords_add',\n 'negative_keywords_remove',\n ];\n if (!isCompactRelease(this.negotiated_version)) {\n for (const field of ['keyword_targets_remove', 'negative_keywords_add', 'negative_keywords_remove']) {\n for (const [itemIndex, item] of array(packageControl[field]).entries()) {\n if (Object.hasOwn(record(item), 'bid_price')) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].${field}[${itemIndex}].bid_price`,\n `The negotiated ${this.negotiated_version} ${field} item cannot represent compact bid_price. No mutation was sent.`\n );\n }\n }\n }\n }\n if (\n Object.hasOwn(packageControl, 'targeting_overlay') &&\n keywordDeltaFields.some(field => Object.hasOwn(packageControl, field))\n ) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].targeting_overlay`,\n 'Compact package targeting_overlay cannot be combined with keyword deltas.'\n );\n }\n const canceledPackageConflicts = [\n 'budget',\n 'daily_budget_cap',\n 'min_spend_target',\n 'impressions',\n 'pacing',\n 'bidding',\n 'paused',\n 'targeting_overlay',\n ...keywordDeltaFields,\n 'optimization_goals',\n ];\n if (\n Object.hasOwn(packageControl, 'canceled') &&\n canceledPackageConflicts.some(field => Object.hasOwn(packageControl, field))\n ) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].canceled`,\n 'Compact package cancellation cannot be combined with other package controls.'\n );\n }\n return Object.fromEntries(\n Object.entries(packageControl).filter(([key]) => packageControlFields.has(key))\n ) as NonNullable<CanonicalUpdateMediaBuyRequest['packages']>[number];\n });\n }\n if (input.canceled !== undefined && input.canceled !== true) {\n throw this.unsupported(\n 'controlMediaBuy',\n 'canceled',\n 'Compact media-buy canceled may only be true when present.'\n );\n }\n if (Object.hasOwn(input, 'cancellation_reason') && !Object.hasOwn(input, 'canceled')) {\n throw this.unsupported(\n 'controlMediaBuy',\n 'cancellation_reason',\n 'Compact media-buy cancellation_reason requires canceled=true.'\n );\n }\n const canceledControlConflicts = [\n 'paused',\n 'total_budget',\n 'daily_budget_cap',\n 'budget_cap_timezone',\n 'budget_allocation',\n 'pacing',\n 'bidding',\n 'packages',\n 'reporting_webhook',\n ];\n if (Object.hasOwn(input, 'canceled') && canceledControlConflicts.some(field => Object.hasOwn(input, field))) {\n throw this.unsupported(\n 'controlMediaBuy',\n 'canceled',\n 'Compact media-buy cancellation cannot be combined with other operational controls.'\n );\n }\n const request: MutatingRequestInput<CanonicalUpdateMediaBuyRequest> = {\n account: input.account as CanonicalUpdateMediaBuyRequest['account'],\n media_buy_id: input.media_buy_id as string,\n ...(input.idempotency_key !== undefined && { idempotency_key: input.idempotency_key as string }),\n revision: input.revision as number,\n ...(input.paused !== undefined && { paused: input.paused as boolean }),\n ...(input.canceled !== undefined && { canceled: input.canceled as true }),\n ...(input.cancellation_reason !== undefined && { cancellation_reason: input.cancellation_reason as string }),\n ...(input.governance_context !== undefined && { governance_context: input.governance_context as string }),\n ...(input.total_budget !== undefined && {\n total_budget: input.total_budget as CanonicalUpdateMediaBuyRequest['total_budget'],\n }),\n ...(input.daily_budget_cap !== undefined && {\n daily_budget_cap: input.daily_budget_cap as CanonicalUpdateMediaBuyRequest['daily_budget_cap'],\n }),\n ...(input.budget_cap_timezone !== undefined && {\n budget_cap_timezone: input.budget_cap_timezone as CanonicalUpdateMediaBuyRequest['budget_cap_timezone'],\n }),\n ...(input.budget_allocation !== undefined && {\n budget_allocation: input.budget_allocation as CanonicalUpdateMediaBuyRequest['budget_allocation'],\n }),\n ...(input.pacing !== undefined && { pacing: input.pacing as CanonicalUpdateMediaBuyRequest['pacing'] }),\n ...(input.bidding !== undefined && { bidding: input.bidding as CanonicalUpdateMediaBuyRequest['bidding'] }),\n ...(packages !== undefined && { packages }),\n ...(input.reporting_webhook !== undefined && {\n reporting_webhook: input.reporting_webhook as CanonicalUpdateMediaBuyRequest['reporting_webhook'],\n }),\n ...(input.push_notification_config !== undefined && {\n push_notification_config:\n input.push_notification_config as CanonicalUpdateMediaBuyRequest['push_notification_config'],\n }),\n ...(input.context !== undefined && { context: input.context as CanonicalUpdateMediaBuyRequest['context'] }),\n };\n this.assertValidCompactRequest('control_media_buy', params, lifecycle, true);\n const result = await this.agent.updateMediaBuy(request, inputHandler, options);\n return this.adaptProjectedResult(\n result,\n this.makeReport(\n lifecycle,\n ['update_media_buy'],\n losses,\n losses.length ? ['The v2.5 update cannot atomically enforce the compact revision token.'] : []\n ),\n data => data\n );\n }\n\n async getMediaBuys(\n params: GetMediaBuysRequest,\n inputHandler?: InputHandler,\n options?: TaskOptions\n ): Promise<CompatibilityTaskResult<GetMediaBuysResponse>> {\n this.assertActive('getMediaBuys');\n if (compareRelease(this.negotiated_version, '3.0') < 0) {\n throw this.unsupported(\n 'getMediaBuys',\n 'media_buy_readback',\n `The negotiated ${this.negotiated_version} seller has no get_media_buys tool.`\n );\n }\n this.assertSharedToolAdvertised('get_media_buys');\n const input = record(params);\n this.assertLegacyReferenceShapes('getMediaBuys', input);\n if (compareRelease(this.negotiated_version, '3.1') < 0) {\n this.assertCompactWireFieldsAbsent('getMediaBuys', input, ['include_webhook_activity', 'webhook_activity_limit']);\n }\n if (!isCompactRelease(this.negotiated_version)) {\n this.assertCompactWireFieldsAbsent('getMediaBuys', input, ['indicator_types']);\n }\n const result = await this.agent.getMediaBuys(params, inputHandler, options);\n return this.adaptProjectedResult(result, this.makeReport(this.lifecycle, ['get_media_buys'], []), data => data);\n }\n\n async getMediaBuyDelivery(\n params: GetMediaBuyDeliveryRequest,\n inputHandler?: InputHandler,\n options?: TaskOptions\n ): Promise<CompatibilityTaskResult<GetMediaBuyDeliveryResponse>> {\n this.assertActive('getMediaBuyDelivery');\n if (compareRelease(this.negotiated_version, '3.0') < 0) {\n throw this.unsupported(\n 'getMediaBuyDelivery',\n 'media_buy_delivery_readback',\n `The negotiated ${this.negotiated_version} delivery request cannot safely represent the compact account-scoped readback.`\n );\n }\n this.assertSharedToolAdvertised('get_media_buy_delivery');\n const input = record(params);\n if (compareRelease(this.negotiated_version, '3.1') < 0) {\n this.assertCompactWireFieldsAbsent('getMediaBuyDelivery', input, [\n 'include_window_breakdown',\n 'time_granularity',\n ]);\n } else if (\n !isCompactRelease(this.negotiated_version) &&\n input.time_granularity !== undefined &&\n !V31_TIME_GRANULARITIES.has(String(input.time_granularity))\n ) {\n throw this.unsupported(\n 'getMediaBuyDelivery',\n 'time_granularity',\n `The negotiated ${this.negotiated_version} delivery request cannot represent compact time granularity ${String(input.time_granularity)}. No request was sent.`\n );\n }\n this.assertLegacyReportingDimensions('getMediaBuyDelivery', input.reporting_dimensions);\n this.assertLegacyReferenceShapes('getMediaBuyDelivery', input);\n const result = await this.agent.getMediaBuyDelivery(params, inputHandler, options);\n return this.adaptProjectedResult(\n result,\n this.makeReport(this.lifecycle, ['get_media_buy_delivery'], []),\n data => data\n );\n }\n}\n\nexport function negotiateMediaBuyLifecycle(\n agent: AgentClient,\n options: MediaBuyLifecycleCoordinatorOptions = {}\n): Promise<MediaBuyLifecycleCoordinator> {\n return MediaBuyLifecycleCoordinator.negotiate(agent, options);\n}\n"],"mappings":"AAAA,SAAS,YAAY,mBAAmB;AAUxC,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB,6BAAwD;AACzF,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB,4BAA4B;AAC3D,SAAS,8CAAqE;AAC9E,SAAS,4BAA4B;AAmCrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,kBAAkB,uBAAuB,oBAAoB,uBAAuB;AAC7F,SAAS,cAAc,wBAAwB;AAC/C,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,OASK;AAaP,MAAM,uBAAuB,oBAAI,IAAI;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,MAAM,2BAA2B,oBAAI,IAAI;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,MAAM,0BAA0B,oBAAI,IAAI;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,MAAM,2BAA2B,oBAAI,IAAI;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,MAAM,sBAAsB,oBAAI,IAAI;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,MAAM,yBAAyB,oBAAI,IAAI;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,MAAM,2BAA2B,oBAAI,IAAI;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAC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AAK,2BAA2B,wBAAwB;AACxD,UAAM,QAAQ,OAAO,MAAM;AAC3B,QAAI,eAAe,KAAK,oBAAoB,KAAK,IAAI,GAAG;AACtD,WAAK,8BAA8B,uBAAuB,OAAO;AAAA,QAC/D;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH,WACE,CAAC,iBAAiB,KAAK,kBAAkB,KACzC,MAAM,qBAAqB,UAC3B,CAAC,uBAAuB,IAAI,OAAO,MAAM,gBAAgB,CAAC,GAC1D;AACA,YAAM,KAAK;AAAA,QACT;AAAA,QACA;AAAA,QACA,kBAAkB,KAAK,kBAAkB,+DAA+D,OAAO,MAAM,gBAAgB,CAAC;AAAA,MACxI;AAAA,IACF;AACA,SAAK,gCAAgC,uBAAuB,MAAM,oBAAoB;AACtF,SAAK,4BAA4B,uBAAuB,KAAK;AAC7D,UAAM,SAAS,MAAM,KAAK,MAAM,oBAAoB,QAAQ,cAAc,OAAO;AACjF,WAAO,KAAK;AAAA,MACV;AAAA,MACA,KAAK,WAAW,KAAK,WAAW,CAAC,wBAAwB,GAAG,CAAC,CAAC;AAAA,MAC9D,UAAQ;AAAA,IACV;AAAA,EACF;AACF;AAEO,SAAS,2BACd,OACA,UAA+C,CAAC,GACT;AACvC,SAAO,6BAA6B,UAAU,OAAO,OAAO;AAC9D;","names":["negotiatedVersion","entry","result","accountScope","state","proposalIds","retry","identity","request","scopes","pendingRefinement","attemptEpoch","dispatchOptions","projectOnly","projectAndSettle","pendingDecline","proposalId","fingerprint","snapshotKey","snapshot","retryDeadlineMs","reservation","transitioned"]}
1
+ {"version":3,"sources":["../../../src/lib/media-buy/compatibility.ts"],"sourcesContent":["import { createHash, randomBytes } from 'node:crypto';\nimport type { AgentClient, CanonicalProjectionTaskOptions, ProposalRefinementTaskOptions } from '../core/AgentClient';\nimport type {\n InputHandler,\n TaskInfo,\n TaskOptions,\n TaskResult,\n TaskResultCompleted,\n TaskResultFailure,\n TaskResultIntermediate,\n} from '../core/ConversationTypes';\nimport type { BeforeProtocolDispatchContext, BeforeProtocolDispatchHookResult } from '../core/TaskExecutor';\nimport { attachMatch } from '../core/match';\nimport { generateIdempotencyKey, isValidIdempotencyKey, type MutatingRequestInput } from '../utils/idempotency';\nimport { canonicalize } from '../utils/jcs';\nimport { extractAdcpErrorInfo, extractCorrelationId } from '../utils/error-extraction';\nimport { assertValidIdempotencyReplayTtlSeconds, type AdcpCapabilities } from '../utils/capabilities';\nimport { TOOL_REQUEST_SCHEMAS } from '../utils/tool-request-schemas';\nimport type {\n AcceptProposalRequest,\n AcceptProposalResponse,\n BuyProductsRequest,\n BuyProductsResponse,\n CanonicalProduct,\n CanonicalProposal,\n ControlMediaBuyRequest,\n ControlMediaBuyResponse,\n CreateMediaBuyResponse,\n CreateMediaBuyRequest,\n DeclineProposalsRequest,\n DeclineProposalsResponse,\n GetProductsResponse,\n GetMediaBuyDeliveryRequest,\n GetMediaBuyDeliveryResponse,\n GetMediaBuysRequest,\n GetMediaBuysResponse,\n ListProductsRequest,\n ListProductsResponse,\n Product,\n Proposal,\n RefineProposalsResponse,\n RequestProposalsRequest,\n RequestProposalsResponse,\n UpdateMediaBuyResponse,\n} from '../types/tools.generated';\nimport type { CompatibilityPurchaseCoordinatorInput } from '../types/core.generated';\nimport type {\n CanonicalCreateMediaBuyRequest,\n CanonicalGetProductsRequest,\n CanonicalUpdateMediaBuyRequest,\n} from '../v2/projection/creative-delivery';\nimport type { RefineProposalsInput } from '../negotiation/types';\nimport {\n assertRefineProposalsResponse,\n isStrictDateTime,\n proposalTermsDigest,\n validateRefineProposalsResponseShape,\n} from '../negotiation/verification';\nimport { isAdcpOperationSuccess } from '../utils/response-unwrapper';\nimport { ConfigurationError } from '../errors';\nimport { createAbortError, isAbortOrTimeoutError, MAX_TIMER_DELAY_MS, withAbortSignal } from '../protocols/abort';\nimport { formatIssues, validateResponse } from '../validation/schema-validator';\nimport { validateRequest } from '../validation/schema-validator';\nimport {\n createInMemoryLegacyPurchaseContinuationStore,\n type LegacyPurchaseClaim,\n type LegacyPurchaseBinding,\n type LegacyPurchaseContinuationRecord,\n type LegacyPurchaseContinuationStore,\n type LegacyPurchaseLoss,\n type LegacyPurchaseSourceVersion,\n type LegacyPurchaseTerminalResult,\n type ReconcileLegacyPurchase,\n} from './legacy-purchase-continuation';\n\nexport type MediaBuyLifecycle = 'compact' | 'established';\nexport type MediaBuyCompatibility = 'native' | 'lossless_projection' | 'lossy_projection';\ntype CompactLifecycleToolName =\n | 'list_products'\n | 'request_proposals'\n | 'refine_proposals'\n | 'decline_proposals'\n | 'buy_products'\n | 'accept_proposal'\n | 'control_media_buy';\n\nconst LIST_PRODUCTS_FIELDS = new Set([\n 'account',\n 'adcp_major_version',\n 'adcp_version',\n 'brand',\n 'context',\n 'context_id',\n 'criteria',\n 'cursor',\n 'fields',\n 'governance_context',\n 'idempotency_key',\n 'if_feed_version',\n 'if_pricing_version',\n 'max_results',\n 'push_notification_config',\n]);\nconst REQUEST_PROPOSALS_FIELDS = new Set([\n 'account',\n 'adcp_major_version',\n 'adcp_version',\n 'brand',\n 'brief',\n 'context',\n 'context_id',\n 'criteria',\n 'governance_context',\n 'idempotency_key',\n 'opportunity',\n 'push_notification_config',\n]);\nconst REFINE_PROPOSALS_FIELDS = new Set([\n 'adcp_major_version',\n 'adcp_version',\n 'context',\n 'context_id',\n 'governance_context',\n 'idempotency_key',\n 'push_notification_config',\n 'refinements',\n]);\nconst DECLINE_PROPOSALS_FIELDS = new Set([\n 'adcp_major_version',\n 'adcp_version',\n 'context',\n 'context_id',\n 'declines',\n 'governance_context',\n 'idempotency_key',\n 'opportunity',\n 'push_notification_config',\n]);\nconst BUY_PRODUCTS_FIELDS = new Set([\n 'account',\n 'adcp_major_version',\n 'adcp_version',\n 'advertiser_industry',\n 'agency_estimate_number',\n 'bidding',\n 'brand',\n 'budget_allocation',\n 'budget_cap_timezone',\n 'context',\n 'daily_budget_cap',\n 'end_time',\n 'ext',\n 'feed_version',\n 'governance_context',\n 'idempotency_key',\n 'invoice_recipient',\n 'opportunity',\n 'pacing',\n 'paused',\n 'pricing_version',\n 'purchase_order_ref',\n 'purchases',\n 'push_notification_config',\n 'reporting_webhook',\n 'start_time',\n 'total_budget',\n]);\nconst ACCEPT_PROPOSAL_FIELDS = new Set([\n 'account',\n 'adcp_major_version',\n 'adcp_version',\n 'budget_cap_timezone',\n 'context',\n 'daily_budget_cap',\n 'ext',\n 'established_fallback',\n 'governance_context',\n 'idempotency_key',\n 'io_acceptance',\n 'opportunity',\n 'proposal_id',\n 'proposal_terms_digest',\n 'purchase_order_ref',\n 'push_notification_config',\n 'reporting_webhook',\n 'total_budget',\n]);\nconst CONTROL_MEDIA_BUY_FIELDS = new Set([\n 'account',\n 'adcp_major_version',\n 'adcp_version',\n 'bidding',\n 'budget_allocation',\n 'budget_cap_timezone',\n 'canceled',\n 'cancellation_reason',\n 'context',\n 'daily_budget_cap',\n 'ext',\n 'governance_context',\n 'idempotency_key',\n 'media_buy_id',\n 'name',\n 'pacing',\n 'packages',\n 'paused',\n 'push_notification_config',\n 'reporting_webhook',\n 'revision',\n 'total_budget',\n]);\nconst V25_OFFER_FILTER_FIELDS = new Set([\n 'budget_range',\n 'channels',\n 'countries',\n 'delivery_type',\n 'end_date',\n 'is_fixed_price',\n 'min_exposures',\n 'standard_formats_only',\n 'start_date',\n]);\nconst V30_OFFER_FILTER_FIELDS = new Set([\n ...V25_OFFER_FILTER_FIELDS,\n 'exclusivity',\n 'required_performance_standards',\n 'trusted_match',\n]);\nconst V31_OFFER_FILTER_FIELDS = new Set([\n ...V30_OFFER_FILTER_FIELDS,\n 'audio_distribution_types',\n 'pricing_currencies',\n 'required_metrics',\n 'required_vendor_metrics',\n 'social_placement_surfaces',\n 'sponsored_placement_types',\n 'video_placement_types',\n]);\nconst V30_PURCHASE_FIELDS = new Set([\n 'agency_estimate_number',\n 'budget',\n 'context',\n 'end_time',\n 'ext',\n 'impressions',\n 'pacing',\n 'pricing_option_id',\n 'product_id',\n 'start_time',\n 'targeting_overlay',\n]);\nconst V25_PURCHASE_FIELDS = new Set([\n 'budget',\n 'ext',\n 'impressions',\n 'pacing',\n 'pricing_option_id',\n 'product_id',\n 'targeting_overlay',\n]);\nconst V31_PURCHASE_FIELDS = new Set([...V30_PURCHASE_FIELDS, 'format_option_refs']);\nconst V32_PURCHASE_FIELDS = new Set([\n ...V31_PURCHASE_FIELDS,\n 'audience_evidence_pins',\n 'audience_evidence_requirements',\n 'bidding',\n 'daily_budget_cap',\n 'min_spend_target',\n]);\nconst V30_TARGETING_FIELDS = new Set([\n 'age_restriction',\n 'audience_exclude',\n 'audience_include',\n 'axe_exclude_segment',\n 'axe_include_segment',\n 'collection_list',\n 'collection_list_exclude',\n 'daypart_targets',\n 'device_platform',\n 'device_type',\n 'device_type_exclude',\n 'frequency_cap',\n 'geo_countries',\n 'geo_countries_exclude',\n 'geo_metros',\n 'geo_metros_exclude',\n 'geo_postal_areas',\n 'geo_postal_areas_exclude',\n 'geo_proximity',\n 'geo_regions',\n 'geo_regions_exclude',\n 'keyword_targets',\n 'language',\n 'negative_keywords',\n 'property_list',\n 'store_catchments',\n]);\nconst V31_TARGETING_FIELDS = new Set([...V30_TARGETING_FIELDS, 'signal_targeting', 'signal_targeting_groups']);\nconst V30_POSTAL_SYSTEMS = new Set([\n 'us_zip',\n 'us_zip_plus_four',\n 'gb_outward',\n 'gb_full',\n 'ca_fsa',\n 'ca_full',\n 'de_plz',\n 'fr_code_postal',\n 'au_postcode',\n 'ch_plz',\n 'at_plz',\n]);\nconst V30_METRO_SYSTEMS = new Set(['nielsen_dma', 'uk_itl1', 'uk_itl2', 'eurostat_nuts2', 'custom']);\nconst V31_TIME_GRANULARITIES = new Set(['hourly', 'daily', 'monthly']);\nconst V30_AVAILABLE_METRICS = new Set([\n 'impressions',\n 'spend',\n 'clicks',\n 'ctr',\n 'video_completions',\n 'completion_rate',\n 'conversions',\n 'conversion_value',\n 'roas',\n 'cost_per_acquisition',\n 'new_to_brand_rate',\n 'viewability',\n 'engagement_rate',\n 'views',\n 'completed_views',\n 'leads',\n 'reach',\n 'frequency',\n 'grps',\n 'quartile_data',\n 'dooh_metrics',\n 'cost_per_click',\n]);\nconst V25_AVAILABLE_METRICS = new Set([\n 'impressions',\n 'spend',\n 'clicks',\n 'ctr',\n 'video_completions',\n 'completion_rate',\n 'conversions',\n 'viewability',\n 'engagement_rate',\n]);\nconst V31_AVAILABLE_METRICS = new Set([\n 'impressions',\n 'spend',\n 'clicks',\n 'ctr',\n 'views',\n 'completed_views',\n 'completion_rate',\n 'conversions',\n 'conversion_value',\n 'roas',\n 'cost_per_acquisition',\n 'new_to_brand_rate',\n 'leads',\n 'reach',\n 'frequency',\n 'grps',\n 'engagements',\n 'engagement_rate',\n 'follows',\n 'saves',\n 'profile_visits',\n 'viewability',\n 'quartile_data',\n 'dooh_metrics',\n 'cost_per_click',\n 'cost_per_completed_view',\n 'cpm',\n 'downloads',\n 'units_sold',\n 'new_to_brand_units',\n 'plays',\n 'incremental_sales_lift',\n 'brand_lift',\n 'foot_traffic',\n 'conversion_lift',\n 'brand_search_lift',\n]);\nconst V30_PRODUCT_FIELDS = new Set([\n 'product_id',\n 'name',\n 'description',\n 'publisher_properties',\n 'channels',\n 'placements',\n 'delivery_type',\n 'exclusivity',\n 'pricing_options',\n 'forecast',\n 'reporting_capabilities',\n 'catalog_types',\n 'max_optimization_goals',\n 'catalog_match',\n 'brief_relevance',\n 'expires_at',\n]);\nconst V31_PRODUCT_FIELDS = new Set([\n ...V30_PRODUCT_FIELDS,\n 'video_placement_types',\n 'audio_distribution_types',\n 'sponsored_placement_types',\n 'social_placement_surfaces',\n 'format_options',\n 'signal_targeting_allowed',\n 'signal_targeting_rules',\n]);\nconst LEGACY_REPORTING_DIMENSIONS = new Set(['geo', 'device_type', 'device_platform', 'audience', 'placement']);\nconst ESTABLISHED_TOOL_FOR_COMPACT: Readonly<Record<CompactLifecycleToolName, string>> = {\n list_products: 'get_products',\n request_proposals: 'get_products',\n refine_proposals: 'get_products',\n decline_proposals: 'get_products',\n buy_products: 'create_media_buy',\n accept_proposal: 'create_media_buy',\n control_media_buy: 'update_media_buy',\n};\n\n/** Guarantees that the established lifecycle cannot enforce atomically. */\nexport type MediaBuyCompatibilityLoss =\n | 'feed_version_not_atomic'\n | 'pricing_version_not_atomic'\n | 'proposal_terms_digest_not_enforced'\n | 'proposal_terms_digest_unavailable'\n | 'proposal_snapshot_not_immutable'\n | 'proposal_hold_not_verifiable'\n | 'revision_not_atomic'\n | 'proposal_decline_not_terminal'\n | 'proposal_decline_reason_not_forwarded';\n\nexport interface MediaBuyCompatibilityReport {\n negotiated_version: string;\n lifecycle: MediaBuyLifecycle;\n tools_used: string[];\n compatibility: MediaBuyCompatibility;\n warnings: string[];\n losses: MediaBuyCompatibilityLoss[];\n}\n\ntype WithCompatibility<T> = T & { compatibility: MediaBuyCompatibilityReport };\n\nexport type CompatibilityDeferredContinuation<TCompleted, TWire> = Omit<\n NonNullable<TaskResultIntermediate<TWire>['deferred']>,\n 'resume'\n> & {\n resume: (input: unknown) => Promise<CompatibilityTaskResult<TCompleted, TWire>>;\n};\n\nexport type CompatibilitySubmittedContinuation<TCompleted, TWire> = Omit<\n NonNullable<TaskResultIntermediate<TWire>['submitted']>,\n 'waitForCompletion'\n> & {\n waitForCompletion: (\n pollInterval?: number,\n signal?: AbortSignal\n ) => Promise<CompatibilityTaskResult<TCompleted, TWire>>;\n};\n\ntype CompatibilityTaskResultIntermediate<TCompleted, TWire> = Omit<\n TaskResultIntermediate<TWire>,\n 'deferred' | 'submitted'\n> & {\n deferred?: CompatibilityDeferredContinuation<TCompleted, TWire>;\n submitted?: CompatibilitySubmittedContinuation<TCompleted, TWire>;\n};\n\n/**\n * A projected compatibility result is status-aware: completed success data is\n * the stable compatibility view, while non-terminal and failure data remains\n * the SDK-returned compact or canonical-established source shape until a\n * completed result can be projected.\n */\nexport type CompatibilityTaskResult<TCompleted, TWire = TCompleted> =\n | WithCompatibility<TaskResultCompleted<TCompleted>>\n | WithCompatibility<CompatibilityTaskResultIntermediate<TCompleted, TWire>>\n | WithCompatibility<TaskResultFailure<TWire>>;\n\nexport type CompatibleProduct = Product | CanonicalProduct;\nexport type CompatibleProposal = Proposal | CanonicalProposal;\n\ntype CompactRefinementResult = NonNullable<RefineProposalsResponse['results']>[number];\ntype CompactRevisedResult = Extract<CompactRefinementResult, { outcome: 'revised' }>;\ntype CompactPartialResult = Extract<CompactRefinementResult, { outcome: 'partial' }>;\ntype CompactFinalizedResult = Extract<CompactRefinementResult, { outcome: 'finalized' }>;\ntype CompactUnableResult = Extract<CompactRefinementResult, { outcome: 'unable' }>;\n\n/**\n * Refine result with the canonical proposal base exposed at the coordinator\n * boundary. The generated response keeps the native outcome discriminants;\n * this compatibility view additionally makes the canonical proposal fields\n * explicit for callers on every proposal-bearing result arm.\n */\nexport type CompatibleRefinementResult =\n | (Omit<CompactRevisedResult, 'proposals'> & {\n proposals: (CanonicalProposal & { proposal_status: 'draft'; parent_proposal_id: string })[];\n })\n | (Omit<CompactPartialResult, 'proposals'> & {\n proposals: (CanonicalProposal & { proposal_status: 'draft'; parent_proposal_id: string })[];\n })\n | (Omit<CompactFinalizedResult, 'proposal'> & {\n proposal: CanonicalProposal & {\n proposal_status: 'committed';\n parent_proposal_id: string;\n expires_at: string;\n };\n })\n | CompactUnableResult;\n\nexport type CompatibleDeclineResult =\n | { proposal_id: string; outcome: 'declined' }\n | { proposal_id: string; outcome: 'unable'; reason: string };\nexport type CompatibleProjectedDeclineResult = {\n proposal_id: string;\n /** Legacy get_products omit is not a seller-confirmed terminal decline. */\n outcome: 'unconfirmed';\n};\n\ntype CompatibleErrors =\n | NonNullable<GetProductsResponse['errors']>\n | NonNullable<RequestProposalsResponse['errors']>\n | NonNullable<RefineProposalsResponse['errors']>\n | NonNullable<DeclineProposalsResponse['errors']>;\ntype CompatibleContext =\n | NonNullable<GetProductsResponse['context']>\n | NonNullable<ListProductsResponse['context']>\n | NonNullable<RequestProposalsResponse['context']>\n | NonNullable<RefineProposalsResponse['context']>\n | NonNullable<DeclineProposalsResponse['context']>;\n\nexport interface CompatibleProductsResponse {\n /** Present only when the seller returned product rows (conditional reads may return only `unchanged`). */\n products?: CompatibleProduct[];\n proposals?: CompatibleProposal[];\n feed_version?: string;\n pricing_version?: string;\n unchanged?: true;\n /** Lifecycle-neutral cursor for the next page. */\n next_cursor?: string;\n pagination?: GetProductsResponse['pagination'];\n cache_scope?: 'public' | 'account';\n errors?: CompatibleErrors;\n context?: CompatibleContext;\n /** SDK-returned source object, retained for fields outside the stable compatibility view. */\n raw: ListProductsResponse | EstablishedProductsWireResponse;\n}\n\ninterface CompatibleProposalResponseBase {\n proposals?: CompatibleProposal[];\n products?: CompatibleProduct[];\n errors?: CompatibleErrors;\n context?: CompatibleContext;\n}\n\ntype CompatibleRequestProposalsResponseBase = Omit<CompatibleProposalResponseBase, 'proposals' | 'products'> & {\n operation: 'request';\n raw: RequestProposalsResponse | EstablishedProductsWireResponse;\n};\n\n/** Completed request-proposal projection with branch fields narrowed by `outcome`. */\nexport type CompatibleRequestProposalsResponse = CompatibleRequestProposalsResponseBase &\n (\n | {\n outcome: 'proposed';\n proposals: CompatibleProposal[];\n products?: CompatibleProduct[];\n incomplete?: RequestProposalsIncomplete;\n reason?: never;\n suggestions?: never;\n purchase_continuation?: never;\n }\n | {\n outcome: 'products_available';\n proposals?: never;\n products: CompatibleProduct[];\n incomplete?: RequestProposalsIncomplete;\n reason?: never;\n suggestions?: never;\n purchase_continuation: RequestProposalsPurchaseContinuation;\n }\n | {\n outcome: 'rejected';\n proposals?: never;\n products?: never;\n incomplete?: never;\n reason: string;\n suggestions?: string[];\n purchase_continuation?: never;\n }\n | {\n /** Never overstates an empty or unsafe legacy response as a seller rejection. */\n outcome: 'legacy_unavailable';\n proposals?: never;\n products?: CompatibleProduct[];\n incomplete?: RequestProposalsIncomplete;\n reason?: never;\n suggestions?: never;\n purchase_continuation?: never;\n }\n );\n\ntype RequestProposalsIncomplete = NonNullable<Extract<RequestProposalsResponse, { outcome: 'proposed' }>['incomplete']>;\ntype RequestProposalsPurchaseContinuation = Extract<\n RequestProposalsResponse,\n { outcome: 'products_available' }\n>['purchase_continuation'];\n\nexport interface CompatibleRefineProposalsResponse extends CompatibleProposalResponseBase {\n operation: 'refine';\n /** Native result arms remain available in `results`; legacy projection is explicitly named. */\n outcome: 'native_results' | 'legacy_projected' | 'legacy_unavailable';\n results?: CompatibleRefinementResult[];\n reason?: string;\n suggestions?: string[];\n raw: RefineProposalsResponse | EstablishedProductsWireResponse;\n}\n\nexport interface CompatibleDeclineProposalsResponse extends CompatibleProposalResponseBase {\n operation: 'decline';\n outcome: 'native_results' | 'legacy_unconfirmed';\n results: (CompatibleDeclineResult | CompatibleProjectedDeclineResult)[];\n raw: DeclineProposalsResponse | EstablishedProductsWireResponse;\n}\n\nexport type CompatibleProposalResponse =\n | CompatibleRequestProposalsResponse\n | CompatibleRefineProposalsResponse\n | CompatibleDeclineProposalsResponse;\n\ntype TaskResultData<TResult> = TResult extends TaskResult<infer TData> ? TData : never;\n/** Canonical SDK source returned by established `get_products`, including projection diagnostics. */\nexport type EstablishedProductsWireResponse = TaskResultData<Awaited<ReturnType<AgentClient['getProducts']>>>;\n\n/** SDK-returned source data retained before a completed list response is projected. */\nexport type CompatibleProductsWireResponse =\n | TaskResultData<Awaited<ReturnType<AgentClient['listProducts']>>>\n | EstablishedProductsWireResponse;\n/** SDK-returned source data retained while a proposal request is non-terminal or failed. */\nexport type CompatibleRequestProposalsWireResponse =\n | TaskResultData<Awaited<ReturnType<AgentClient['requestProposals']>>>\n | EstablishedProductsWireResponse;\n/** SDK-returned source data retained while proposal refinement is non-terminal or failed. */\nexport type CompatibleRefineProposalsWireResponse =\n | TaskResultData<Awaited<ReturnType<AgentClient['refineProposals']>>>\n | EstablishedProductsWireResponse;\n/** SDK-returned source data retained while proposal decline is non-terminal or failed. */\nexport type CompatibleDeclineProposalsWireResponse =\n | TaskResultData<Awaited<ReturnType<AgentClient['declineProposals']>>>\n | EstablishedProductsWireResponse;\n\nexport interface MediaBuyLifecycleCoordinatorOptions {\n /** Prefer compact when advertised. Established is useful for a dual-surface test lane. */\n preferredLifecycle?: 'auto' | MediaBuyLifecycle;\n /** Named representational losses explicitly accepted for legacy mutations. */\n allowedLosses?: readonly MediaBuyCompatibilityLoss[];\n /**\n * Stable, non-secret, server-controlled identity for the authenticated\n * principal/tenant that owns this coordinator. Never derive it from buyer\n * request content. It salts proposal snapshots so multi-tenant runners\n * cannot reuse a snapshot across principals. Required for established\n * proposal acceptance; without it snapshots are not retained.\n */\n principalScope?: string;\n /**\n * Stable, non-secret identity for the authenticated seller/account session.\n * Persist and reuse it when a coordinator is rehydrated. It is required for\n * every established 2.5, 3.0, or 3.1 seller that provides no server context ID.\n */\n legacyPurchaseSellerSessionScope?: string;\n /** Durable storage for products-only legacy purchase continuations. */\n legacyPurchaseContinuationStore?: LegacyPurchaseContinuationStore;\n /** Lifetime of a projected continuation. Defaults to five minutes. */\n legacyPurchaseContinuationTtlMs?: number;\n /** Age after which an unresolved claim is reconciled instead of reported in-flight. */\n legacyPurchaseClaimTimeoutMs?: number;\n /** Bounded deterministic-replay window after the first claim. Defaults to 24 hours. */\n legacyPurchaseOperationTtlMs?: number;\n /** Application-owned authoritative reconciliation for ambiguous legacy creates. */\n reconcileLegacyPurchase?: ReconcileLegacyPurchase;\n}\n\nexport type LegacyPurchaseContinuationErrorCode =\n | 'not_found'\n | 'expired'\n | 'binding_mismatch'\n | 'selection_mismatch'\n | 'loss_mismatch'\n | 'request_invalid'\n | 'conflict'\n | 'in_flight'\n | 'ambiguous'\n | 'store_error';\n\n/** Fail-closed continuation error; ambiguous/store variants may be raised after seller dispatch. */\nexport class LegacyPurchaseContinuationError extends Error {\n readonly name = 'LegacyPurchaseContinuationError';\n\n constructor(\n readonly code: LegacyPurchaseContinuationErrorCode,\n message: string,\n readonly retryable = false,\n readonly recovery?: string,\n cause?: unknown\n ) {\n super(message, cause === undefined ? undefined : { cause });\n }\n}\n\n/**\n * Inputs the established create_media_buy proposal path requires but the\n * compact accept_proposal request intentionally does not repeat. Callers may\n * supply this on every compatibility-facade acceptance: compact sellers ignore\n * it, while established sellers use it without pretending it came from the\n * seller's proposal snapshot.\n */\nexport interface EstablishedProposalAcceptanceFallback {\n brand: CanonicalCreateMediaBuyRequest['brand'];\n start_time: CanonicalCreateMediaBuyRequest['start_time'];\n end_time: CanonicalCreateMediaBuyRequest['end_time'];\n}\n\n/**\n * Compatibility-facade acceptance input. A digest remains mandatory on the\n * native compact lane. It is optional only for an established lane whose\n * missing digest/snapshot guarantees have been explicitly accepted.\n */\nexport type CompatibleAcceptProposalRequest = Omit<AcceptProposalRequest, 'proposal_terms_digest'> & {\n proposal_terms_digest?: string;\n established_fallback?: EstablishedProposalAcceptanceFallback;\n};\n\nexport interface MediaBuyLifecycleCompatibilityErrorOptions {\n operation: string;\n negotiatedVersion: string;\n lifecycle: MediaBuyLifecycle;\n feature: string;\n message: string;\n losses?: readonly MediaBuyCompatibilityLoss[];\n recovery?: string;\n code?: 'UNSUPPORTED_FEATURE' | 'PROPOSAL_DIGEST_MISMATCH';\n}\n\n/** Structured preflight failure raised before an incompatible mutation is sent. */\nexport class MediaBuyLifecycleCompatibilityError extends Error {\n readonly name = 'MediaBuyLifecycleCompatibilityError';\n readonly code: 'UNSUPPORTED_FEATURE' | 'PROPOSAL_DIGEST_MISMATCH';\n readonly operation: string;\n readonly negotiatedVersion: string;\n readonly lifecycle: MediaBuyLifecycle;\n readonly feature: string;\n readonly losses: readonly MediaBuyCompatibilityLoss[];\n readonly recovery: string;\n\n constructor(options: MediaBuyLifecycleCompatibilityErrorOptions) {\n super(options.message);\n this.code = options.code ?? 'UNSUPPORTED_FEATURE';\n this.operation = options.operation;\n this.negotiatedVersion = options.negotiatedVersion;\n this.lifecycle = options.lifecycle;\n this.feature = options.feature;\n this.losses = options.losses ?? [];\n this.recovery =\n options.recovery ??\n 'Remove the unsupported compact guarantee, select a compact-capable seller, or explicitly allow the named loss.';\n }\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : {};\n}\n\nfunction safeDiagnostic(value: unknown, maxLength: number): string {\n const raw = String(value);\n const escaped = raw.replace(/[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]/gu, character => {\n const code = character.codePointAt(0) ?? 0;\n return `\\\\u${code.toString(16).padStart(4, '0')}`;\n });\n return escaped.length > maxLength ? `${escaped.slice(0, maxLength - 1)}…` : escaped;\n}\n\nfunction requestFingerprint(value: unknown): string {\n return createHash('sha256').update(canonicalize(value)).digest('base64url');\n}\n\nfunction retiredAcceptancePositions(key: string, salt: Uint8Array, bitCount: number): number[] {\n const digest = createHash('sha256').update(salt).update(key).digest();\n return [0, 4, 8, 12, 16, 20, 24, 28].map(offset => digest.readUInt32BE(offset) % bitCount);\n}\n\nfunction array(value: unknown): unknown[] {\n return Array.isArray(value) ? value : [];\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nconst CREDENTIAL_SHAPED_KEYS = new Set([\n 'authorization',\n 'credential',\n 'credentials',\n 'token',\n 'authtoken',\n 'apikey',\n 'password',\n 'secret',\n 'clientsecret',\n 'refreshtoken',\n 'accesstoken',\n 'bearer',\n 'sessiontoken',\n 'privatekey',\n 'signingkey',\n 'jwt',\n 'signature',\n 'signedpayload',\n 'cookie',\n 'setcookie',\n]);\n\nfunction isCredentialShapedKey(key: string): boolean {\n return CREDENTIAL_SHAPED_KEYS.has(key.replace(/[-_]/g, '').toLowerCase());\n}\n\nfunction containsCredentialShapedKey(value: unknown, seen = new WeakSet<object>()): boolean {\n if (value === null || typeof value !== 'object') return false;\n if (seen.has(value)) return false;\n seen.add(value);\n if (Array.isArray(value)) return value.some(item => containsCredentialShapedKey(item, seen));\n return Object.entries(value).some(\n ([key, nested]) => isCredentialShapedKey(key) || containsCredentialShapedKey(nested, seen)\n );\n}\n\nfunction containsPresignedUrl(value: unknown, seen = new WeakSet<object>()): boolean {\n if (typeof value === 'string') {\n try {\n const url = new URL(value, 'https://adcp-relative.invalid');\n const signedUrlAliases = new Set(['xamzcredential', 'xamzsignature', 'xgoogcredential', 'xgoogsignature', 'sig']);\n const isSensitiveUrlKey = (key: string): boolean => {\n const normalized = key.replace(/[-_]/g, '').toLowerCase();\n return isCredentialShapedKey(key) || signedUrlAliases.has(normalized);\n };\n const fragmentParams = new URLSearchParams(url.hash.startsWith('#') ? url.hash.slice(1) : url.hash);\n return (\n url.username.length > 0 ||\n url.password.length > 0 ||\n [...url.searchParams.keys()].some(isSensitiveUrlKey) ||\n [...fragmentParams.keys()].some(isSensitiveUrlKey)\n );\n } catch {\n return false;\n }\n }\n if (value === null || typeof value !== 'object') return false;\n if (seen.has(value)) return false;\n seen.add(value);\n return Object.values(value).some(nested => containsPresignedUrl(nested, seen));\n}\n\ninterface ParsedRelease {\n major: number;\n minor: number;\n patch: number;\n prerelease?: string;\n}\n\nfunction parseRelease(value: string): ParsedRelease | undefined {\n const match = /^v?(\\d+)\\.(\\d+)(?:\\.(\\d+))?(?:-([A-Za-z0-9.-]+))?(?:\\+[A-Za-z0-9.-]+)?$/.exec(value.trim());\n if (!match) return undefined;\n return {\n major: Number(match[1]),\n minor: Number(match[2]),\n patch: Number(match[3] ?? 0),\n ...(match[4] !== undefined && { prerelease: match[4] }),\n };\n}\n\nfunction comparePrerelease(left: string | undefined, right: string | undefined): number {\n if (left === right) return 0;\n if (left === undefined) return 1;\n if (right === undefined) return -1;\n const leftParts = left.split('.');\n const rightParts = right.split('.');\n for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {\n const a = leftParts[index];\n const b = rightParts[index];\n if (a === undefined) return -1;\n if (b === undefined) return 1;\n if (a === b) continue;\n const aNumeric = /^\\d+$/.test(a);\n const bNumeric = /^\\d+$/.test(b);\n if (aNumeric && bNumeric) return Number(a) - Number(b);\n if (aNumeric !== bNumeric) return aNumeric ? -1 : 1;\n return a.localeCompare(b);\n }\n return 0;\n}\n\nfunction compareRelease(left: string, right: string): number {\n const a = parseRelease(left);\n const b = parseRelease(right);\n if (!a || !b) return 0;\n return a.major - b.major || a.minor - b.minor || a.patch - b.patch || comparePrerelease(a.prerelease, b.prerelease);\n}\n\nfunction isCompactRelease(value: string): boolean {\n const release = parseRelease(value);\n return release !== undefined && (release.major > 3 || (release.major === 3 && release.minor >= 2));\n}\n\nfunction negotiatedVersion(capabilities: AdcpCapabilities, clientVersion: string): string {\n if (capabilities.version === 'v2') return '2.5';\n if (capabilities.servedVersion && parseRelease(capabilities.servedVersion)) {\n if (compareRelease(capabilities.servedVersion, clientVersion) > 0) {\n const displayedServedVersion = capabilities.servedVersion.slice(0, 64);\n throw new ConfigurationError(\n `The seller served AdCP ${displayedServedVersion}, which is newer than the client pin ${clientVersion}; the response cannot be interpreted safely.`\n );\n }\n return capabilities.servedVersion;\n }\n const advertisedVersions = capabilities.supportedVersions?.filter(version => parseRelease(version) !== undefined);\n const candidates = advertisedVersions?.filter(\n version => parseRelease(version) !== undefined && compareRelease(version, clientVersion) <= 0\n );\n if (candidates?.length) return [...candidates].sort(compareRelease).at(-1)!;\n if (advertisedVersions?.length) {\n throw new ConfigurationError(\n `The seller advertises only AdCP versions newer than the client pin ${clientVersion}; no compatible wire version can be negotiated.`\n );\n }\n if (capabilities._synthetic && capabilities.mediaBuyLifecycleTools?.length && isCompactRelease(clientVersion)) {\n // Compact tool names are authoritative wire evidence. A failed\n // capabilities call must not route a compact-only seller to aliases it\n // does not expose.\n return clientVersion;\n }\n // AdCP 3.0 predates release-precision capability metadata. A real v3\n // capability response with none of the fields above is therefore a 3.0\n // lane; reporting the client's newer pin would overstate the wire release.\n return '3.0';\n}\n\nconst MAX_PROPOSAL_TRAVERSAL_NODES = 4096;\nconst LEGACY_PROPOSAL_RAW = Symbol('legacyProposalRaw');\nconst COMPACT_REQUEST_PROPOSALS_RESPONSE_FIELDS = new Set([\n 'adcp_version',\n 'outcome',\n 'reason',\n 'suggestions',\n 'proposals',\n 'products',\n 'incomplete',\n 'purchase_continuation',\n 'targeting_resolution',\n 'status',\n 'task_id',\n 'message',\n 'errors',\n 'context',\n 'ext',\n 'replayed',\n]);\nconst COMPACT_DECLINE_PROPOSALS_RESPONSE_FIELDS = new Set([\n 'adcp_version',\n 'results',\n 'status',\n 'task_id',\n 'message',\n 'errors',\n 'context',\n 'ext',\n 'replayed',\n]);\n\nfunction projectProducts(data: unknown, lifecycle: MediaBuyLifecycle): CompatibleProductsResponse {\n const source = compactWirePayload(data);\n const feedVersion = optionalString(lifecycle === 'compact' ? source.feed_version : source.wholesale_feed_version);\n const pricingVersion = optionalString(source.pricing_version);\n const nextCursor = optionalString(lifecycle === 'compact' ? source.next_cursor : record(source.pagination).cursor);\n return {\n ...(Array.isArray(source.products) && { products: source.products as CompatibleProduct[] }),\n ...(Array.isArray(source.proposals) && { proposals: source.proposals as CompatibleProposal[] }),\n ...(feedVersion && { feed_version: feedVersion }),\n ...(pricingVersion && { pricing_version: pricingVersion }),\n ...((source.unchanged === true || source.outcome === 'unchanged') && { unchanged: true as const }),\n ...(nextCursor && { next_cursor: nextCursor }),\n ...(source.pagination !== undefined && { pagination: source.pagination as GetProductsResponse['pagination'] }),\n ...((source.cache_scope === 'public' || source.cache_scope === 'account') && {\n cache_scope: source.cache_scope,\n }),\n ...(Array.isArray(source.errors) && { errors: source.errors as CompatibleErrors }),\n ...(source.context !== undefined && { context: source.context as CompatibleContext }),\n raw: source as ListProductsResponse | EstablishedProductsWireResponse,\n };\n}\n\nfunction proposalRows(source: Record<string, unknown>): CompatibleProposal[] | undefined {\n const proposals: CompatibleProposal[] = [];\n let sawProposalContainer = false;\n const roots: unknown[] = [];\n if (source.proposals !== undefined) roots.push(source.proposals);\n if (source.proposal !== undefined) roots.push(source.proposal);\n const results = array(source.results);\n if (results.length > MAX_PROPOSAL_TRAVERSAL_NODES) {\n throw new TypeError('proposal response exceeded the bounded traversal limit.');\n }\n for (const result of results) {\n const row = record(result);\n if (row.proposals !== undefined) roots.push(row.proposals);\n if (row.proposal !== undefined) roots.push(row.proposal);\n }\n const stack = roots.reverse();\n const seen = new WeakSet<object>();\n let visited = 0;\n while (stack.length > 0) {\n const value = stack.pop();\n if (value === null || typeof value !== 'object' || seen.has(value)) continue;\n seen.add(value);\n visited += 1;\n if (visited > MAX_PROPOSAL_TRAVERSAL_NODES) {\n throw new TypeError('proposal response exceeded the bounded traversal limit.');\n }\n if (Array.isArray(value)) {\n sawProposalContainer = true;\n if (stack.length + value.length > MAX_PROPOSAL_TRAVERSAL_NODES) {\n throw new TypeError('proposal response exceeded the bounded traversal limit.');\n }\n for (let index = value.length - 1; index >= 0; index -= 1) stack.push(value[index]);\n continue;\n }\n const candidate = value as Record<string, unknown>;\n if (optionalString(candidate.proposal_id)) {\n sawProposalContainer = true;\n proposals.push(candidate as CompatibleProposal);\n }\n // Reverse push preserves the prior depth-first proposals-then-proposal order.\n if (candidate.proposal !== undefined) stack.push(candidate.proposal);\n if (candidate.proposals !== undefined) stack.push(candidate.proposals);\n }\n return sawProposalContainer ? proposals : undefined;\n}\n\nfunction proposalResponseBase(source: Record<string, unknown>): CompatibleProposalResponseBase {\n const proposals = proposalRows(source);\n return {\n ...(proposals !== undefined && { proposals }),\n ...(Array.isArray(source.products) && { products: source.products as CompatibleProduct[] }),\n ...(Array.isArray(source.errors) && { errors: source.errors as CompatibleErrors }),\n ...(source.context !== undefined && { context: source.context as CompatibleContext }),\n };\n}\n\n/**\n * Remove SDK-only response annotations before validating or exposing the\n * seller's wire payload. `_message` is synthesized by the response unwrapper\n * from MCP/A2A text parts after schema validation; it never crossed the AdCP\n * tool boundary and therefore must not be mistaken for an undeclared seller\n * field. Keep this allowlist deliberately narrow so seller-controlled\n * underscore fields still fail closed.\n */\nfunction compactWirePayload(data: unknown): Record<string, unknown> {\n const source = record(data);\n if (!Object.hasOwn(source, '_message')) return source;\n const { _message: _sdkMessage, ...wire } = source;\n return wire;\n}\n\nfunction assertCompactRequestProposalsCompletion(source: Record<string, unknown>, negotiatedVersion: string): void {\n const unsupportedFields = Object.keys(source).filter(field => !COMPACT_REQUEST_PROPOSALS_RESPONSE_FIELDS.has(field));\n if (unsupportedFields.length > 0) {\n throw new TypeError(\n `request_proposals returned a malformed compact completion: undeclared fields ${unsupportedFields.join(', ')}.`\n );\n }\n const normalized = source.status === undefined ? { ...source, status: 'completed' } : source;\n if (normalized.status !== 'completed' || Object.hasOwn(normalized, 'task_id')) {\n throw new TypeError(\n 'request_proposals returned a malformed compact completion: the completed sync arm must not contain submitted status or task_id.'\n );\n }\n if (source.outcome === 'products_available' || source.purchase_continuation !== undefined) {\n throw new TypeError(\n 'request_proposals returned the projection-only products_available outcome from a native compact seller.'\n );\n }\n const validation = validateResponse('request_proposals', normalized, negotiatedVersion);\n if (!validation.valid) {\n throw new TypeError(\n `request_proposals returned a malformed compact completion: ${formatIssues(validation.issues)}`\n );\n }\n}\n\nfunction projectRequestProposals(\n data: unknown,\n lifecycle: MediaBuyLifecycle,\n negotiatedVersion?: string\n): CompatibleRequestProposalsResponse {\n const source = compactWirePayload(data);\n if (lifecycle === 'compact') assertCompactRequestProposalsCompletion(source, negotiatedVersion ?? '3.2');\n const base = proposalResponseBase(source);\n const nativeOutcome = source.outcome === 'proposed' || source.outcome === 'rejected' ? source.outcome : undefined;\n const projectedProductsAvailable = lifecycle === 'established' && source.outcome === 'products_available';\n const outcome =\n nativeOutcome ??\n (projectedProductsAvailable ? 'products_available' : undefined) ??\n (lifecycle === 'established' && (base.proposals?.length ?? 0) > 0 ? 'proposed' : 'legacy_unavailable');\n return {\n ...base,\n operation: 'request',\n outcome,\n ...(typeof source.reason === 'string' && { reason: source.reason }),\n ...(Array.isArray(source.suggestions) && { suggestions: source.suggestions as string[] }),\n ...(Array.isArray(source.incomplete) && {\n incomplete: source.incomplete as RequestProposalsIncomplete,\n }),\n ...(source.purchase_continuation !== undefined && {\n purchase_continuation: source.purchase_continuation as RequestProposalsPurchaseContinuation,\n }),\n raw: ((source as Record<PropertyKey, unknown>)[LEGACY_PROPOSAL_RAW] ?? source) as\n | RequestProposalsResponse\n | EstablishedProductsWireResponse,\n } as CompatibleRequestProposalsResponse;\n}\n\nfunction projectRefineProposals(\n data: unknown,\n lifecycle: MediaBuyLifecycle,\n refinements: RefineProposalsInput['refinements']\n): CompatibleRefineProposalsResponse {\n const source = compactWirePayload(data);\n const proposalIds = refinements.map(refinement => refinement.proposal_id);\n if (lifecycle === 'compact') {\n // Verify the complete response root before following any seller-controlled\n // proposal container or result branch.\n assertRefineProposalsResponse({ refinements }, source);\n }\n const base = proposalResponseBase(source);\n const sourceResults = array(source.results);\n if (lifecycle === 'compact') {\n if (sourceResults.length !== proposalIds.length) {\n throw new TypeError('refine_proposals returned a different result count than the requested refinement count.');\n }\n sourceResults.forEach((value, index) => {\n const result = record(value);\n const requestedProposalId = proposalIds[index];\n const sourceProposalId = optionalString(result.source_proposal_id);\n if (requestedProposalId === undefined || sourceProposalId !== requestedProposalId) {\n throw new TypeError(\n `refine_proposals result ${index} did not identify the corresponding source proposal from the request.`\n );\n }\n const children = [...array(result.proposals), ...(result.proposal === undefined ? [] : [result.proposal])];\n if (result.outcome === 'revised' || result.outcome === 'partial' || result.outcome === 'finalized') {\n const shape = validateRefineProposalsResponseShape({ results: [result], products: [] });\n if (!shape.ok) {\n throw new TypeError(`refine_proposals result ${index} did not contain complete canonical proposal data.`);\n }\n const expectedStatus = result.outcome === 'finalized' ? 'committed' : 'draft';\n if (children.some(child => record(child).proposal_status !== expectedStatus)) {\n throw new TypeError(\n `refine_proposals result ${index} returned a proposal with an invalid status for its ${String(result.outcome)} outcome.`\n );\n }\n if (result.outcome === 'finalized' && children.some(child => !isStrictDateTime(record(child).expires_at))) {\n throw new TypeError(`refine_proposals result ${index} returned a finalized proposal without a valid expiry.`);\n }\n }\n children.forEach(child => {\n if (optionalString(record(child).parent_proposal_id) !== sourceProposalId) {\n throw new TypeError(\n `refine_proposals result ${index} returned a proposal with invalid parent_proposal_id lineage.`\n );\n }\n });\n });\n }\n const nativeResults = Array.isArray(source.results) ? (sourceResults as CompatibleRefinementResult[]) : undefined;\n const outcome =\n lifecycle === 'compact'\n ? 'native_results'\n : (base.proposals?.length ?? 0) > 0\n ? 'legacy_projected'\n : 'legacy_unavailable';\n return {\n ...base,\n operation: 'refine',\n outcome,\n ...(nativeResults !== undefined && { results: nativeResults }),\n ...(typeof source.reason === 'string' && { reason: source.reason }),\n ...(Array.isArray(source.suggestions) && { suggestions: source.suggestions as string[] }),\n raw: source as RefineProposalsResponse | EstablishedProductsWireResponse,\n };\n}\n\nfunction projectDeclineProposals(\n data: unknown,\n lifecycle: MediaBuyLifecycle,\n proposalIds: readonly string[],\n negotiatedVersion?: string\n): CompatibleDeclineProposalsResponse {\n const source = compactWirePayload(data);\n if (lifecycle === 'compact') {\n const unsupportedFields = Object.keys(source).filter(\n field => !COMPACT_DECLINE_PROPOSALS_RESPONSE_FIELDS.has(field)\n );\n if (unsupportedFields.length > 0) {\n throw new TypeError(\n `decline_proposals returned a malformed compact completion: undeclared fields ${unsupportedFields.join(', ')}.`\n );\n }\n const validation = validateResponse('decline_proposals', source, negotiatedVersion ?? '3.2');\n if (!validation.valid || validation.variant !== 'sync') {\n throw new TypeError(\n `decline_proposals returned a malformed compact completion: ${formatIssues(validation.issues)}`\n );\n }\n }\n const base = proposalResponseBase(source);\n const sourceResults = array(source.results);\n if (lifecycle === 'compact' && sourceResults.length !== proposalIds.length) {\n throw new TypeError('decline_proposals returned a different result count than the requested proposal count.');\n }\n const results =\n lifecycle === 'compact'\n ? sourceResults.map((result, index) => {\n const row = record(result);\n const requestedProposalId = proposalIds[index];\n const sellerProposalId = optionalString(row.proposal_id);\n if (requestedProposalId === undefined) {\n throw new TypeError('decline_proposals returned more result rows than requested proposals.');\n }\n if (Object.keys(row).some(key => !['proposal_id', 'outcome', 'reason'].includes(key))) {\n throw new TypeError(`decline_proposals result ${index} contained an undeclared field.`);\n }\n if (Object.hasOwn(row, 'proposal_id') && sellerProposalId === undefined) {\n throw new TypeError(`decline_proposals result ${index} contained an invalid proposal_id.`);\n }\n if (sellerProposalId !== undefined && sellerProposalId !== requestedProposalId) {\n throw new TypeError(\n `decline_proposals result ${index} identified a different proposal than the corresponding request.`\n );\n }\n if (row.outcome === 'declined') {\n if (Object.hasOwn(row, 'reason')) {\n throw new TypeError(`decline_proposals declined result ${index} must not contain a reason.`);\n }\n return { proposal_id: requestedProposalId, outcome: 'declined' as const };\n }\n if (row.outcome === 'unable') {\n const reason = optionalString(row.reason);\n if (!reason) {\n throw new TypeError(`decline_proposals unable result ${index} requires a non-empty reason.`);\n }\n return { proposal_id: requestedProposalId, outcome: 'unable' as const, reason };\n }\n throw new TypeError(`decline_proposals result ${index} contained an invalid outcome.`);\n })\n : proposalIds.map(proposal_id => ({ proposal_id, outcome: 'unconfirmed' as const }));\n return {\n ...base,\n operation: 'decline',\n outcome: lifecycle === 'compact' ? 'native_results' : 'legacy_unconfirmed',\n results,\n raw: source as DeclineProposalsResponse | EstablishedProductsWireResponse,\n };\n}\n\ninterface AcceptanceReservation {\n kind: 'native' | 'established';\n state: 'in-flight' | 'retryable' | 'retired';\n retryKind?: 'paused' | 'commit-uncertain';\n requestFingerprint: string;\n idempotencyKey?: string;\n skipIdempotencyAutoInject: boolean;\n readonly retryDeadlineMs?: number;\n taskId?: string;\n}\n\ninterface ProposalSnapshotEntry {\n proposal: Record<string, unknown>;\n bytes: number;\n principalScope: string;\n executable: boolean;\n accountScope?: string;\n canonicalTermsDigest?: string;\n acceptance?: AcceptanceReservation;\n /** Synthetic entry used only to share a native acceptance fence. */\n nativeAcceptanceOnly?: boolean;\n}\n\ninterface ProposalSnapshotStore {\n entries: Map<string, ProposalSnapshotEntry>;\n proposalAcceptances: Map<\n string,\n { snapshotKey: string; snapshot: ProposalSnapshotEntry; reservation: AcceptanceReservation }\n >;\n pendingDeclines: Set<PendingDeclineLease>;\n pendingDeclineProposalIdCount: number;\n pendingRefinements: Set<PendingRefinementLease>;\n pendingRefinementProposalIdCount: number;\n bytes: number;\n registry: ProposalSnapshotStoreRegistry;\n activeCoordinators: number;\n}\n\ninterface ProposalSnapshotStoreRegistry {\n stores: Map<string, ProposalSnapshotStore>;\n retiredAcceptanceSegments?: Map<number, Uint8Array>;\n retiredAcceptanceSalt?: Uint8Array;\n}\n\ninterface SafeProposalSnapshot {\n proposal: Record<string, unknown>;\n canonicalTermsDigest?: string;\n}\n\ntype ProposalMutationState = 'in-flight' | 'paused' | 'commit-uncertain' | 'retired';\n\ninterface ProposalMutationReservation {\n proposalIds: readonly string[];\n state: ProposalMutationState;\n requestFingerprint: string;\n idempotencyKey?: string;\n skipIdempotencyAutoInject: boolean;\n /** Fixed from the seller's advertised replay TTL at the first dispatch. */\n readonly retryDeadlineMs?: number;\n attemptEpoch: number;\n owner: object;\n timer?: ReturnType<typeof setTimeout>;\n}\n\ninterface PendingDeclineLease extends ProposalMutationReservation {\n operation: 'decline';\n}\n\ninterface PendingRefinementLease extends ProposalMutationReservation {\n operation: 'refine';\n sources: readonly { key: string; entry: ProposalSnapshotEntry }[];\n}\n\nconst SNAPSHOT_COMMERCIAL_TERM_FIELDS = [\n 'brand',\n 'start_time',\n 'end_time',\n 'total_budget',\n 'daily_budget_cap',\n 'budget_cap_timezone',\n 'purchase_order_ref',\n] as const;\n\nfunction safeProposalSnapshot(candidate: Record<string, unknown>): SafeProposalSnapshot | null {\n if (containsCredentialShapedKey(candidate) || containsPresignedUrl(candidate)) return null;\n const proposalId = optionalString(candidate.proposal_id);\n if (!proposalId || proposalId.length > 255) return null;\n const proposal: Record<string, unknown> = { proposal_id: proposalId };\n const proposalStatus = candidate.proposal_status;\n if (proposalStatus !== undefined) {\n if (typeof proposalStatus !== 'string' || !['draft', 'committed', 'accepted'].includes(proposalStatus)) return null;\n proposal.proposal_status = proposalStatus;\n }\n const proposalKind = candidate.proposal_kind;\n if (proposalKind !== undefined) {\n if (\n typeof proposalKind !== 'string' ||\n !['new_media_buy', 'media_buy_update', 'media_buy_cancellation'].includes(proposalKind)\n )\n return null;\n proposal.proposal_kind = proposalKind;\n }\n const termsDigest = candidate.terms_digest;\n if (termsDigest !== undefined) {\n if (typeof termsDigest !== 'string' || !/^sha256:[A-Za-z0-9_-]{43}$/.test(termsDigest)) return null;\n proposal.terms_digest = termsDigest;\n }\n const expiresAt = candidate.expires_at;\n if (expiresAt !== undefined) {\n if (typeof expiresAt !== 'string' || !isStrictDateTime(expiresAt)) return null;\n proposal.expires_at = expiresAt;\n }\n const sourceTerms = record(candidate.commercial_terms);\n let canonicalTermsDigest: string | undefined;\n if (Object.keys(sourceTerms).length > 0) {\n // Inspect the complete seller payload before reducing it to the execution\n // allow-list. A secret in an otherwise unused field must make the proposal\n // ineligible for caching rather than merely disappearing from the snapshot.\n try {\n canonicalTermsDigest = proposalTermsDigest(sourceTerms);\n } catch {\n return null;\n }\n const safeTerms: Record<string, unknown> = {};\n for (const field of SNAPSHOT_COMMERCIAL_TERM_FIELDS) {\n if (sourceTerms[field] !== undefined) safeTerms[field] = sourceTerms[field];\n }\n proposal.commercial_terms = safeTerms;\n }\n return { proposal, ...(canonicalTermsDigest && { canonicalTermsDigest }) };\n}\n\nconst proposalSnapshotStores = new WeakMap<AgentClient, ProposalSnapshotStoreRegistry>();\nconst acceptanceReservationOwners = new WeakMap<AcceptanceReservation, MediaBuyLifecycleCoordinator>();\nconst MAX_PRINCIPAL_STORES_PER_AGENT = 256;\nconst RETIRED_ACCEPTANCE_SEGMENT_COUNT = 256;\nconst RETIRED_ACCEPTANCE_SEGMENT_BYTES = 256 * 1024;\n\nfunction proposalSnapshotStoreFor(agent: AgentClient, principalScope?: string): ProposalSnapshotStore {\n let registry = proposalSnapshotStores.get(agent);\n if (!registry) {\n registry = { stores: new Map() };\n proposalSnapshotStores.set(agent, registry);\n }\n const key = principalScope === undefined ? '\\u0000unscoped' : `principal:${principalScope}`;\n const existing = registry.stores.get(key);\n if (existing) {\n existing.activeCoordinators += 1;\n return existing;\n }\n if (registry.stores.size >= MAX_PRINCIPAL_STORES_PER_AGENT) {\n for (const [candidateKey, candidate] of registry.stores) {\n if (\n candidate.activeCoordinators === 0 &&\n candidate.entries.size === 0 &&\n candidate.proposalAcceptances.size === 0 &&\n candidate.pendingDeclines.size === 0 &&\n candidate.pendingRefinements.size === 0\n ) {\n registry.stores.delete(candidateKey);\n break;\n }\n }\n }\n if (registry.stores.size >= MAX_PRINCIPAL_STORES_PER_AGENT) {\n throw new ConfigurationError(\n `Media-buy lifecycle principal partitions are limited to ${MAX_PRINCIPAL_STORES_PER_AGENT} per AgentClient. Dispose inactive coordinators or use a separate AgentClient.`,\n 'mediaBuy.principalScope'\n );\n }\n const created: ProposalSnapshotStore = {\n entries: new Map(),\n proposalAcceptances: new Map(),\n pendingDeclines: new Set(),\n pendingDeclineProposalIdCount: 0,\n pendingRefinements: new Set(),\n pendingRefinementProposalIdCount: 0,\n bytes: 0,\n registry,\n activeCoordinators: 1,\n };\n registry.stores.set(key, created);\n return created;\n}\n\n/**\n * Negotiated compact-first media-buy facade.\n *\n * Every established projection is assembled field-by-field. Tool selection\n * is final before dispatch, so ambiguous failures never trigger a second\n * mutation through the other lifecycle.\n */\nexport class MediaBuyLifecycleCoordinator {\n readonly negotiated_version: string;\n readonly lifecycle: MediaBuyLifecycle;\n readonly tools: ReadonlySet<string>;\n\n private readonly allowedLosses: ReadonlySet<MediaBuyCompatibilityLoss>;\n private readonly preferredLifecycle: 'auto' | MediaBuyLifecycle;\n private readonly principalScope?: string;\n private readonly configuredLegacyPurchaseSellerSessionScope?: string;\n private resolvedLegacyPurchaseSellerSessionScope?: string;\n private readonly legacyPurchaseContinuationStore: LegacyPurchaseContinuationStore;\n private readonly legacyPurchaseContinuationTtlMs: number;\n private readonly legacyPurchaseClaimTimeoutMs: number;\n private readonly legacyPurchaseOperationTtlMs: number;\n private readonly reconcileLegacyPurchase?: ReconcileLegacyPurchase;\n private readonly proposalSnapshotStore: ProposalSnapshotStore;\n private readonly pendingProposalTasks = new Map<\n string,\n {\n accountScope?: string;\n project?: (data: unknown) => unknown;\n retainProposals: boolean;\n onPause?: () => void;\n onAuthoritativeFailure?: () => void;\n authoritativeTaskNames?: ReadonlySet<string>;\n preserveAuthoritativeProposals?: boolean;\n onTerminalFailure?: () => void;\n }\n >();\n private readonly pendingProposalTaskTimers = new Map<string, ReturnType<typeof setTimeout>>();\n private proposalTaskUnsubscribe?: () => void;\n private readonly pendingAcceptanceTasks = new Map<\n string,\n { snapshotKey: string; snapshot: ProposalSnapshotEntry; reservation: AcceptanceReservation }\n >();\n private readonly ownedAcceptanceReservations = new Map<\n AcceptanceReservation,\n { snapshotKey: string; snapshot: ProposalSnapshotEntry }\n >();\n private readonly pendingAcceptanceTaskTimers = new Map<string, ReturnType<typeof setTimeout>>();\n private readonly acceptanceRetryExpiryTimers = new Map<AcceptanceReservation, ReturnType<typeof setTimeout>>();\n private readonly proposalDispatchUnsubscribes = new Set<() => void>();\n private readonly declineLeaseOwner = {};\n private readonly refinementLeaseOwner = {};\n private acceptanceTaskUnsubscribe?: () => void;\n private disposed = false;\n private readonly idempotencyReplayTtlMs?: number;\n private static readonly MAX_PROPOSAL_SNAPSHOTS = 256;\n private static readonly MAX_PROPOSAL_SNAPSHOT_BYTES = 256 * 1024;\n private static readonly MAX_PROPOSAL_SNAPSHOT_TOTAL_BYTES = 4 * 1024 * 1024;\n private static readonly MAX_PRINCIPAL_SCOPE_BYTES = 256;\n private static readonly MAX_PENDING_DECLINES = 256;\n private static readonly MAX_PENDING_DECLINE_PROPOSAL_IDS = 1024;\n private static readonly MAX_PENDING_REFINEMENTS = 256;\n private static readonly MAX_PENDING_REFINEMENT_PROPOSAL_IDS = 1024;\n private static readonly PROPOSAL_TASK_WATCH_TTL_MS = 5 * 60 * 1000;\n\n private constructor(\n private readonly agent: AgentClient,\n capabilities: AdcpCapabilities,\n options: MediaBuyLifecycleCoordinatorOptions\n ) {\n this.negotiated_version = negotiatedVersion(capabilities, agent.getAdcpVersion());\n this.tools = new Set([...(capabilities.mediaBuyLifecycleTools ?? []), ...(capabilities.discoveredTools ?? [])]);\n this.preferredLifecycle = options.preferredLifecycle ?? 'auto';\n this.allowedLosses = new Set(options.allowedLosses ?? []);\n const replayTtlSeconds = capabilities.idempotency?.replayTtlSeconds;\n if (replayTtlSeconds !== undefined) {\n assertValidIdempotencyReplayTtlSeconds(replayTtlSeconds);\n this.idempotencyReplayTtlMs = replayTtlSeconds * 1000;\n }\n if (options.principalScope !== undefined) {\n if (typeof options.principalScope !== 'string' || options.principalScope.trim().length === 0) {\n throw new TypeError('Media-buy lifecycle principalScope must be a non-empty string when provided.');\n }\n const normalizedScope = options.principalScope.trim();\n if (/[\\u0000-\\u001f\\u007f]/.test(normalizedScope)) {\n throw new TypeError('Media-buy lifecycle principalScope must not contain control characters.');\n }\n if (\n new TextEncoder().encode(normalizedScope).byteLength > MediaBuyLifecycleCoordinator.MAX_PRINCIPAL_SCOPE_BYTES\n ) {\n throw new TypeError(\n `Media-buy lifecycle principalScope must be at most ${MediaBuyLifecycleCoordinator.MAX_PRINCIPAL_SCOPE_BYTES} UTF-8 bytes.`\n );\n }\n }\n this.principalScope = options.principalScope?.trim();\n if (\n options.legacyPurchaseSellerSessionScope !== undefined &&\n (typeof options.legacyPurchaseSellerSessionScope !== 'string' ||\n options.legacyPurchaseSellerSessionScope.trim().length === 0)\n ) {\n throw new TypeError(\n 'Media-buy lifecycle legacyPurchaseSellerSessionScope must be a non-empty string when provided.'\n );\n }\n this.configuredLegacyPurchaseSellerSessionScope = options.legacyPurchaseSellerSessionScope?.trim();\n this.legacyPurchaseContinuationStore =\n options.legacyPurchaseContinuationStore ?? createInMemoryLegacyPurchaseContinuationStore();\n this.legacyPurchaseContinuationTtlMs = options.legacyPurchaseContinuationTtlMs ?? 5 * 60 * 1000;\n this.legacyPurchaseClaimTimeoutMs = options.legacyPurchaseClaimTimeoutMs ?? 30 * 1000;\n this.legacyPurchaseOperationTtlMs = options.legacyPurchaseOperationTtlMs ?? 24 * 60 * 60 * 1000;\n for (const [name, value] of [\n ['legacyPurchaseContinuationTtlMs', this.legacyPurchaseContinuationTtlMs],\n ['legacyPurchaseClaimTimeoutMs', this.legacyPurchaseClaimTimeoutMs],\n ['legacyPurchaseOperationTtlMs', this.legacyPurchaseOperationTtlMs],\n ] as const) {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new TypeError(`Media-buy lifecycle ${name} must be a positive safe integer.`);\n }\n }\n this.reconcileLegacyPurchase = options.reconcileLegacyPurchase;\n this.lifecycle = this.selectLifecycle('list_products');\n this.proposalSnapshotStore = proposalSnapshotStoreFor(agent, this.principalScope);\n }\n\n static async negotiate(\n agent: AgentClient,\n options: MediaBuyLifecycleCoordinatorOptions = {}\n ): Promise<MediaBuyLifecycleCoordinator> {\n return new MediaBuyLifecycleCoordinator(agent, await agent.getCapabilities(), options);\n }\n\n /** Initial negotiation report. Operation calls return their own exact tool report. */\n report(): MediaBuyCompatibilityReport {\n return this.makeReport(this.lifecycle, [], []);\n }\n\n private assertActive(operation: string): void {\n if (!this.disposed) return;\n throw new ConfigurationError(\n `Cannot call ${operation} after disposing the media-buy lifecycle coordinator. Negotiate a new coordinator.`,\n 'mediaBuy.lifecycleCoordinator'\n );\n }\n\n private pendingDeclineRetryCandidate(proposalIds: readonly string[]): PendingDeclineLease | undefined {\n const wanted = new Set(proposalIds);\n const overlapping = [...this.proposalSnapshotStore.pendingDeclines].filter(\n lease => lease.state !== 'retired' && lease.proposalIds.some(proposalId => wanted.has(proposalId))\n );\n const candidate = overlapping.length === 1 ? overlapping[0] : undefined;\n return candidate &&\n candidate.proposalIds.length === wanted.size &&\n candidate.proposalIds.every(proposalId => wanted.has(proposalId)) &&\n (candidate.state === 'paused' || candidate.state === 'commit-uncertain')\n ? candidate\n : undefined;\n }\n\n private pendingRefinementRetryCandidate(proposalIds: readonly string[]): PendingRefinementLease | undefined {\n const wanted = new Set(proposalIds);\n const overlapping = [...this.proposalSnapshotStore.pendingRefinements].filter(\n lease => lease.state !== 'retired' && lease.proposalIds.some(proposalId => wanted.has(proposalId))\n );\n const candidate = overlapping.length === 1 ? overlapping[0] : undefined;\n return candidate &&\n candidate.proposalIds.length === wanted.size &&\n candidate.proposalIds.every(proposalId => wanted.has(proposalId)) &&\n (candidate.state === 'paused' || candidate.state === 'commit-uncertain')\n ? candidate\n : undefined;\n }\n\n private mutationAttemptIsCurrent(\n reservation: PendingDeclineLease | PendingRefinementLease,\n attemptEpoch: number\n ): boolean {\n return reservation.state !== 'retired' && reservation.attemptEpoch === attemptEpoch;\n }\n\n private scheduleProposalMutationTimer(\n reservation: PendingDeclineLease | PendingRefinementLease,\n attemptEpoch: number\n ): void {\n if (reservation.timer) clearTimeout(reservation.timer);\n reservation.timer = undefined;\n if (!this.mutationAttemptIsCurrent(reservation, attemptEpoch)) return;\n const now = Date.now();\n const deadline = reservation.retryDeadlineMs;\n if (reservation.state !== 'in-flight' && (deadline === undefined || deadline <= now)) {\n this.retireAmbiguousProposalMutation(reservation, attemptEpoch);\n return;\n }\n const delay =\n reservation.state === 'in-flight'\n ? deadline === undefined\n ? MediaBuyLifecycleCoordinator.PROPOSAL_TASK_WATCH_TTL_MS\n : Math.min(MediaBuyLifecycleCoordinator.PROPOSAL_TASK_WATCH_TTL_MS, deadline - now)\n : deadline! - now;\n const timer = setTimeout(() => {\n if (!this.mutationAttemptIsCurrent(reservation, attemptEpoch) || reservation.timer !== timer) return;\n reservation.timer = undefined;\n if (reservation.state === 'in-flight' && deadline !== undefined && Date.now() < deadline) {\n reservation.state = 'commit-uncertain';\n this.scheduleProposalMutationTimer(reservation, attemptEpoch);\n return;\n }\n this.retireAmbiguousProposalMutation(reservation, attemptEpoch);\n }, delay);\n timer.unref?.();\n reservation.timer = timer;\n }\n\n private assertProposalMutationRetryWindow(\n reservation: PendingDeclineLease | PendingRefinementLease,\n operation: 'declineProposals' | 'refineProposals'\n ): void {\n if (reservation.idempotencyKey && reservation.retryDeadlineMs && reservation.retryDeadlineMs > Date.now()) return;\n this.retireAmbiguousProposalMutation(reservation, reservation.attemptEpoch);\n throw this.unsupported(\n operation,\n operation === 'declineProposals' ? 'proposal_decline_retry_window' : 'proposal_refinement_retry_window',\n 'The seller no longer guarantees idempotent replay of this proposal mutation. Reconcile its outcome before any different mutation.'\n );\n }\n\n private beginProposalMutationRetry<T extends PendingDeclineLease | PendingRefinementLease>(\n reservation: T,\n owner: object,\n operation: 'declineProposals' | 'refineProposals'\n ): T {\n this.assertProposalMutationRetryWindow(reservation, operation);\n if (reservation.timer) clearTimeout(reservation.timer);\n reservation.timer = undefined;\n reservation.attemptEpoch += 1;\n reservation.state = 'in-flight';\n reservation.owner = owner;\n this.scheduleProposalMutationTimer(reservation, reservation.attemptEpoch);\n return reservation;\n }\n\n private preserveAmbiguousProposalMutation(\n reservation: PendingDeclineLease | PendingRefinementLease,\n attemptEpoch: number,\n state: 'paused' | 'commit-uncertain' = 'commit-uncertain'\n ): void {\n if (!this.mutationAttemptIsCurrent(reservation, attemptEpoch)) return;\n if (!reservation.idempotencyKey || !reservation.retryDeadlineMs || reservation.retryDeadlineMs <= Date.now()) {\n this.retireAmbiguousProposalMutation(reservation, attemptEpoch);\n return;\n }\n // Once an attempt is commit-uncertain, a later local pause cannot weaken\n // the fence back to merely paused.\n if (reservation.state !== 'commit-uncertain') reservation.state = state;\n this.scheduleProposalMutationTimer(reservation, attemptEpoch);\n }\n\n private retireAmbiguousProposalMutation(\n reservation: PendingDeclineLease | PendingRefinementLease,\n attemptEpoch: number\n ): void {\n if (!this.mutationAttemptIsCurrent(reservation, attemptEpoch)) return;\n reservation.proposalIds.forEach(proposalId => this.markCommitUncertainProposalMutation(proposalId));\n if (reservation.operation === 'decline') this.retirePendingDecline(reservation, attemptEpoch);\n else this.retirePendingRefinement(reservation, attemptEpoch);\n }\n\n private proposalMutationIdempotency(\n callerValue: unknown,\n retry: PendingDeclineLease | PendingRefinementLease | undefined,\n skipIdempotencyAutoInject: boolean\n ): { idempotencyKey?: string; skipIdempotencyAutoInject: boolean } {\n const callerKey = optionalString(callerValue);\n const retrySkip = retry?.skipIdempotencyAutoInject;\n const effectiveSkip = retrySkip ?? skipIdempotencyAutoInject;\n const idempotencyKey =\n callerKey ?? retry?.idempotencyKey ?? (!effectiveSkip && !retry ? generateIdempotencyKey() : undefined);\n return {\n ...(idempotencyKey && { idempotencyKey }),\n skipIdempotencyAutoInject: effectiveSkip,\n };\n }\n\n private beginPendingDecline(\n proposalIds: readonly string[],\n requestFingerprintValue: string,\n idempotencyKey: string | undefined,\n skipIdempotencyAutoInject: boolean\n ): PendingDeclineLease {\n const retainedProposalIds = [...new Set(proposalIds)];\n const retry = this.pendingDeclineRetryCandidate(retainedProposalIds);\n const hasPendingDecline = retainedProposalIds.some(proposalId => this.isProposalDeclinePending(proposalId));\n if (hasPendingDecline) {\n if (retry) this.assertProposalMutationRetryWindow(retry, 'declineProposals');\n if (\n retry &&\n retry.idempotencyKey !== undefined &&\n retry.requestFingerprint === requestFingerprintValue &&\n retry.idempotencyKey === idempotencyKey &&\n retry.skipIdempotencyAutoInject === skipIdempotencyAutoInject\n ) {\n return this.beginProposalMutationRetry(retry, this.declineLeaseOwner, 'declineProposals');\n }\n throw this.unsupported(\n 'declineProposals',\n retry ? 'proposal_decline_retry' : 'proposal_decline_pending',\n retry\n ? 'A paused proposal decline may retry only the exact same request and idempotency key. No mutation was sent.'\n : 'A requested proposal already has an unresolved decline in this principal scope. Wait for it to finish before declining again.'\n );\n }\n if (retainedProposalIds.some(proposalId => this.isCommitUncertainProposalMutation(proposalId))) {\n throw this.unsupported(\n 'declineProposals',\n 'proposal_mutation_commit_uncertain',\n 'A prior mutation of a requested proposal has an unreconciled outcome. No decline was sent.'\n );\n }\n if (\n retainedProposalIds.some(proposalId => {\n const reservation = this.proposalSnapshotStore.proposalAcceptances.get(proposalId)?.reservation;\n return reservation?.state === 'retryable' && reservation.retryKind === 'commit-uncertain';\n })\n ) {\n throw this.unsupported(\n 'declineProposals',\n 'proposal_acceptance_commit_uncertain',\n 'A requested proposal has an acceptance whose commit outcome is unknown. Reconcile or exactly retry that acceptance before declining it.'\n );\n }\n if (\n retainedProposalIds.some(\n proposalId => this.proposalSnapshotStore.proposalAcceptances.get(proposalId)?.reservation.state === 'in-flight'\n )\n ) {\n throw this.unsupported(\n 'declineProposals',\n 'proposal_acceptance_pending',\n 'A requested proposal has an in-flight acceptance in this principal scope. Wait for it to finish before declining it.'\n );\n }\n if (retainedProposalIds.some(proposalId => this.isCommitUncertainProposal(proposalId))) {\n throw this.unsupported(\n 'declineProposals',\n 'proposal_acceptance_commit_uncertain',\n 'A requested proposal has an acceptance whose commit outcome is unknown. Reconcile the media buy by natural key before sending a different mutation.'\n );\n }\n if (retainedProposalIds.some(proposalId => this.isAcceptedProposal(proposalId))) {\n throw this.unsupported(\n 'declineProposals',\n 'proposal_terminal',\n 'A requested proposal has already been accepted in this principal scope. No decline was sent.'\n );\n }\n if (retainedProposalIds.some(proposalId => this.isProposalRefinementPending(proposalId))) {\n throw this.unsupported(\n 'declineProposals',\n 'proposal_refinement_pending',\n 'A requested proposal has an unresolved refinement in this principal scope. Wait for that refinement to finish before declining it.'\n );\n }\n if (\n this.proposalSnapshotStore.pendingDeclines.size >= MediaBuyLifecycleCoordinator.MAX_PENDING_DECLINES ||\n this.proposalSnapshotStore.pendingDeclineProposalIdCount + retainedProposalIds.length >\n MediaBuyLifecycleCoordinator.MAX_PENDING_DECLINE_PROPOSAL_IDS\n ) {\n throw new ConfigurationError(\n 'Too many media-buy proposal declines are still pending. Complete, cancel, or dispose outstanding decline tasks before dispatching another.',\n 'mediaBuy.pendingDeclines'\n );\n }\n const lease: PendingDeclineLease = {\n operation: 'decline',\n proposalIds: retainedProposalIds,\n state: 'in-flight',\n requestFingerprint: requestFingerprintValue,\n ...(idempotencyKey && { idempotencyKey }),\n skipIdempotencyAutoInject,\n attemptEpoch: 1,\n owner: this.declineLeaseOwner,\n };\n if (this.idempotencyReplayTtlMs !== undefined) {\n Object.defineProperty(lease, 'retryDeadlineMs', {\n value: Date.now() + this.idempotencyReplayTtlMs,\n enumerable: true,\n writable: false,\n configurable: false,\n });\n }\n this.proposalSnapshotStore.pendingDeclines.add(lease);\n this.proposalSnapshotStore.pendingDeclineProposalIdCount += retainedProposalIds.length;\n this.scheduleProposalMutationTimer(lease, lease.attemptEpoch);\n return lease;\n }\n\n private finishPendingDecline(lease: PendingDeclineLease, attemptEpoch = lease.attemptEpoch): void {\n if (!this.mutationAttemptIsCurrent(lease, attemptEpoch)) return;\n lease.state = 'retired';\n if (lease.timer) clearTimeout(lease.timer);\n lease.timer = undefined;\n this.proposalSnapshotStore.pendingDeclines.delete(lease);\n this.proposalSnapshotStore.pendingDeclineProposalIdCount -= lease.proposalIds.length;\n }\n\n private retirePendingDecline(lease: PendingDeclineLease, attemptEpoch = lease.attemptEpoch): void {\n if (!this.mutationAttemptIsCurrent(lease, attemptEpoch)) return;\n this.invalidateProposalSnapshots(lease.proposalIds, undefined, false, true);\n this.finishPendingDecline(lease, attemptEpoch);\n }\n\n private pausePendingDecline(lease: PendingDeclineLease, attemptEpoch = lease.attemptEpoch): void {\n this.preserveAmbiguousProposalMutation(lease, attemptEpoch, 'paused');\n }\n\n private preparePendingDeclineSettlement(\n lease: PendingDeclineLease,\n response: CompatibleDeclineProposalsResponse,\n attemptEpoch = lease.attemptEpoch\n ): () => void {\n const locallyTerminalIds = response.results\n .filter(result => result.outcome === 'declined' || result.outcome === 'unconfirmed')\n .map(result => result.proposal_id);\n return () => {\n if (!this.mutationAttemptIsCurrent(lease, attemptEpoch)) return;\n this.invalidateProposalSnapshots(locallyTerminalIds, undefined, false, true);\n this.finishPendingDecline(lease, attemptEpoch);\n };\n }\n\n private isProposalDeclinePending(proposalId: string): boolean {\n for (const lease of this.proposalSnapshotStore.pendingDeclines) {\n if (lease.state !== 'retired' && lease.proposalIds.includes(proposalId)) return true;\n }\n return false;\n }\n\n private beginPendingRefinement(\n proposalIds: readonly string[],\n rejectTerminalProposal: boolean,\n requestFingerprintValue: string,\n idempotencyKey: string | undefined,\n skipIdempotencyAutoInject: boolean\n ): PendingRefinementLease {\n const retainedProposalIds = [...new Set(proposalIds)];\n const retry = this.pendingRefinementRetryCandidate(retainedProposalIds);\n if (\n retainedProposalIds.some(\n proposalId => this.isProposalRefinementPending(proposalId) || this.isProposalDeclinePending(proposalId)\n )\n ) {\n if (retry) this.assertProposalMutationRetryWindow(retry, 'refineProposals');\n if (\n retry &&\n !retainedProposalIds.some(proposalId => this.isProposalDeclinePending(proposalId)) &&\n retry.idempotencyKey !== undefined &&\n retry.requestFingerprint === requestFingerprintValue &&\n retry.idempotencyKey === idempotencyKey &&\n retry.skipIdempotencyAutoInject === skipIdempotencyAutoInject\n ) {\n return this.beginProposalMutationRetry(retry, this.refinementLeaseOwner, 'refineProposals');\n }\n throw this.unsupported(\n 'refineProposals',\n retry ? 'proposal_refinement_retry' : 'proposal_mutation_pending',\n retry\n ? 'A paused proposal refinement may retry only the exact same request and idempotency key. No mutation was sent.'\n : 'A requested proposal already has an unresolved refinement or decline in this principal scope. Wait for it to finish before refining again.'\n );\n }\n if (retainedProposalIds.some(proposalId => this.isCommitUncertainProposalMutation(proposalId))) {\n throw this.unsupported(\n 'refineProposals',\n 'proposal_mutation_commit_uncertain',\n 'A prior mutation of a requested proposal has an unreconciled outcome. No refinement was sent.'\n );\n }\n if (\n retainedProposalIds.some(proposalId => {\n const reservation = this.proposalSnapshotStore.proposalAcceptances.get(proposalId)?.reservation;\n return reservation?.state === 'retryable' && reservation.retryKind === 'commit-uncertain';\n })\n ) {\n throw this.unsupported(\n 'refineProposals',\n 'proposal_acceptance_commit_uncertain',\n 'A requested proposal has an acceptance whose commit outcome is unknown. Reconcile or exactly retry that acceptance before refining it.'\n );\n }\n if (retainedProposalIds.some(proposalId => this.proposalSnapshotStore.proposalAcceptances.has(proposalId))) {\n throw this.unsupported(\n 'refineProposals',\n 'proposal_acceptance_pending',\n 'A requested proposal is already being accepted in this principal scope. No refinement was sent.'\n );\n }\n if (retainedProposalIds.some(proposalId => this.isCommitUncertainProposal(proposalId))) {\n throw this.unsupported(\n 'refineProposals',\n 'proposal_acceptance_commit_uncertain',\n 'A requested proposal has an acceptance whose commit outcome is unknown. Reconcile the media buy by natural key before refining it.'\n );\n }\n if (rejectTerminalProposal && retainedProposalIds.some(proposalId => this.isTerminalProposal(proposalId))) {\n throw this.unsupported(\n 'refineProposals',\n 'proposal_terminal',\n 'A requested proposal is terminal in this principal scope. Only a terminal decline remains safe; no refinement was sent.'\n );\n }\n const wanted = new Set(retainedProposalIds);\n const sources = [...this.proposalSnapshotStore.entries].flatMap(([key, entry]) =>\n entry.principalScope === this.principalScope && wanted.has(String(entry.proposal.proposal_id))\n ? [{ key, entry }]\n : []\n );\n if (sources.some(({ entry }) => entry.acceptance !== undefined)) {\n throw this.unsupported(\n 'refineProposals',\n 'proposal_acceptance_pending',\n 'A requested proposal is already being accepted in this principal scope. No refinement was sent.'\n );\n }\n if (\n this.proposalSnapshotStore.pendingRefinements.size >= MediaBuyLifecycleCoordinator.MAX_PENDING_REFINEMENTS ||\n this.proposalSnapshotStore.pendingRefinementProposalIdCount + retainedProposalIds.length >\n MediaBuyLifecycleCoordinator.MAX_PENDING_REFINEMENT_PROPOSAL_IDS\n ) {\n throw new ConfigurationError(\n 'Too many media-buy proposal refinements are still pending. Complete, cancel, or dispose outstanding refinement tasks before dispatching another.',\n 'mediaBuy.pendingRefinements'\n );\n }\n const lease: PendingRefinementLease = {\n operation: 'refine',\n proposalIds: retainedProposalIds,\n sources,\n state: 'in-flight',\n requestFingerprint: requestFingerprintValue,\n ...(idempotencyKey && { idempotencyKey }),\n skipIdempotencyAutoInject,\n attemptEpoch: 1,\n owner: this.refinementLeaseOwner,\n };\n if (this.idempotencyReplayTtlMs !== undefined) {\n Object.defineProperty(lease, 'retryDeadlineMs', {\n value: Date.now() + this.idempotencyReplayTtlMs,\n enumerable: true,\n writable: false,\n configurable: false,\n });\n }\n for (const { entry } of sources) entry.executable = false;\n this.proposalSnapshotStore.pendingRefinements.add(lease);\n this.proposalSnapshotStore.pendingRefinementProposalIdCount += retainedProposalIds.length;\n this.scheduleProposalMutationTimer(lease, lease.attemptEpoch);\n return lease;\n }\n\n private finishPendingRefinement(lease: PendingRefinementLease, attemptEpoch = lease.attemptEpoch): void {\n if (!this.mutationAttemptIsCurrent(lease, attemptEpoch)) return;\n lease.state = 'retired';\n if (lease.timer) clearTimeout(lease.timer);\n lease.timer = undefined;\n this.proposalSnapshotStore.pendingRefinements.delete(lease);\n this.proposalSnapshotStore.pendingRefinementProposalIdCount -= lease.proposalIds.length;\n }\n\n private restorePendingRefinement(lease: PendingRefinementLease, attemptEpoch = lease.attemptEpoch): void {\n if (!this.mutationAttemptIsCurrent(lease, attemptEpoch)) return;\n this.finishPendingRefinement(lease, attemptEpoch);\n for (const { key, entry } of lease.sources) {\n const proposalId = String(entry.proposal.proposal_id);\n if (\n this.proposalSnapshotStore.entries.get(key) === entry &&\n !this.isTerminalProposal(proposalId) &&\n !this.isCommitUncertainProposalMutation(proposalId)\n ) {\n entry.executable = true;\n }\n }\n }\n\n private retirePendingRefinement(lease: PendingRefinementLease, attemptEpoch = lease.attemptEpoch): void {\n if (!this.mutationAttemptIsCurrent(lease, attemptEpoch)) return;\n this.finishPendingRefinement(lease, attemptEpoch);\n this.invalidateProposalSnapshots(lease.proposalIds, undefined, false, true);\n }\n\n private pausePendingRefinement(lease: PendingRefinementLease, attemptEpoch = lease.attemptEpoch): void {\n this.preserveAmbiguousProposalMutation(lease, attemptEpoch, 'paused');\n }\n\n private settlePendingRefinement(\n lease: PendingRefinementLease,\n response: CompatibleRefineProposalsResponse,\n attemptEpoch = lease.attemptEpoch\n ): void {\n this.preparePendingRefinementSettlement(lease, response, attemptEpoch)();\n }\n\n private preparePendingRefinementSettlement(\n lease: PendingRefinementLease,\n response: CompatibleRefineProposalsResponse,\n attemptEpoch = lease.attemptEpoch\n ): () => void {\n const unableProposalIds = new Set(\n response.outcome === 'native_results'\n ? (response.results ?? [])\n .filter(result => result.outcome === 'unable')\n .map(result => result.source_proposal_id)\n : []\n );\n const replacementProposalIds = new Set(\n response.outcome === 'legacy_projected'\n ? (response.proposals ?? [])\n .map(proposal => optionalString(record(proposal).proposal_id))\n .filter((proposalId): proposalId is string => proposalId !== undefined)\n : []\n );\n return () => {\n if (!this.mutationAttemptIsCurrent(lease, attemptEpoch)) return;\n this.finishPendingRefinement(lease, attemptEpoch);\n const replacementSourceIds = lease.proposalIds.filter(proposalId => replacementProposalIds.has(proposalId));\n const terminalProposalIds = lease.proposalIds.filter(\n proposalId => !unableProposalIds.has(proposalId) && !replacementProposalIds.has(proposalId)\n );\n // A legacy exact replay after an ambiguous first attempt cannot prove\n // that a same-ID proposal row is a fresh immutable source rather than\n // the already-consumed pre-mutation snapshot. Keep that source retired;\n // distinct child proposal IDs returned by the replay are still cached.\n this.invalidateProposalSnapshots(replacementSourceIds, undefined, false, attemptEpoch > 1);\n this.invalidateProposalSnapshots(terminalProposalIds, undefined, false, true);\n for (const { key, entry } of lease.sources) {\n const proposalId = String(entry.proposal.proposal_id);\n if (\n unableProposalIds.has(proposalId) &&\n this.proposalSnapshotStore.entries.get(key) === entry &&\n !this.isTerminalProposal(proposalId)\n ) {\n entry.executable = true;\n }\n }\n };\n }\n\n private isProposalRefinementPending(proposalId: string): boolean {\n for (const lease of this.proposalSnapshotStore.pendingRefinements) {\n if (lease.state !== 'retired' && lease.proposalIds.includes(proposalId)) return true;\n }\n return false;\n }\n\n private selectLifecycle(compactTool: string): MediaBuyLifecycle {\n const establishedTool = ESTABLISHED_TOOL_FOR_COMPACT[compactTool as CompactLifecycleToolName];\n if (this.preferredLifecycle === 'established') {\n if (isCompactRelease(this.negotiated_version) && !this.tools.has(establishedTool)) {\n throw this.unsupported(\n compactTool,\n 'established_lifecycle_not_advertised',\n `The seller provides no discovery evidence that ${establishedTool} is callable. ` +\n 'The forced established diagnostic lane was not selected.',\n 'compact'\n );\n }\n return 'established';\n }\n if (isCompactRelease(this.negotiated_version) && this.tools.has(compactTool)) return 'compact';\n if (this.preferredLifecycle === 'compact') {\n throw this.unsupported(\n compactTool,\n compactTool,\n `The negotiated ${this.negotiated_version} lifecycle does not advertise ${compactTool}.`\n );\n }\n if (isCompactRelease(this.negotiated_version) && !this.tools.has(establishedTool)) {\n throw this.unsupported(\n compactTool,\n 'lifecycle_tool_not_advertised',\n `The seller advertises neither ${compactTool} nor its established counterpart ${establishedTool}. No request was sent.`,\n 'compact'\n );\n }\n return 'established';\n }\n\n private assertSharedToolAdvertised(tool: 'get_media_buys' | 'get_media_buy_delivery'): void {\n if (!isCompactRelease(this.negotiated_version) || this.tools.has(tool)) return;\n throw this.unsupported(\n tool,\n 'lifecycle_tool_not_advertised',\n `The negotiated ${this.negotiated_version} seller does not advertise ${tool}. No request was sent.`,\n this.lifecycle\n );\n }\n\n private makeReport(\n lifecycle: MediaBuyLifecycle,\n toolsUsed: string[],\n losses: MediaBuyCompatibilityLoss[],\n warnings: string[] = []\n ): MediaBuyCompatibilityReport {\n return {\n negotiated_version: this.negotiated_version,\n lifecycle,\n tools_used: toolsUsed,\n compatibility: lifecycle === 'compact' ? 'native' : losses.length ? 'lossy_projection' : 'lossless_projection',\n warnings,\n losses,\n };\n }\n\n private unsupported(\n operation: string,\n feature: string,\n message: string,\n lifecycle: MediaBuyLifecycle = 'established'\n ): MediaBuyLifecycleCompatibilityError {\n return new MediaBuyLifecycleCompatibilityError({\n operation,\n negotiatedVersion: this.negotiated_version,\n lifecycle,\n feature: safeDiagnostic(feature, 512),\n message: safeDiagnostic(message, 2048),\n });\n }\n\n private requireAllowed(operation: string, losses: MediaBuyCompatibilityLoss[]): void {\n const refused = losses.filter(loss => !this.allowedLosses.has(loss));\n if (!refused.length) return;\n throw new MediaBuyLifecycleCompatibilityError({\n operation,\n negotiatedVersion: this.negotiated_version,\n lifecycle: 'established',\n feature: refused.join(', '),\n losses: refused,\n message:\n `${operation} cannot preserve ${refused.join(', ')} on the established lifecycle. ` +\n `No mutation was sent. Opt in with allowedLosses only after accepting the named guarantee loss.`,\n });\n }\n\n private assertValidCompactRequest(\n tool: CompactLifecycleToolName,\n params: unknown,\n lifecycle: MediaBuyLifecycle,\n mutating = false\n ): void {\n const input = record(params);\n const candidate =\n mutating && !optionalString(input.idempotency_key)\n ? { ...input, idempotency_key: generateIdempotencyKey() }\n : input;\n const result = TOOL_REQUEST_SCHEMAS[tool]!.safeParse(candidate);\n if (result.success) return;\n const details = result.error.issues\n .slice(0, 5)\n .map(issue => `${issue.path.join('.') || '<root>'}: ${issue.message}`)\n .join('; ');\n throw this.unsupported(\n tool,\n 'compact_request_validation',\n `The compact ${tool} intent is invalid and was not projected: ${details}`,\n lifecycle\n );\n }\n\n private assertOnlyFields(operation: string, value: Record<string, unknown>, allowed: ReadonlySet<string>): void {\n const unsupportedFields = Object.keys(value).filter(key => !allowed.has(key));\n if (unsupportedFields.length === 0) return;\n throw this.unsupported(\n operation,\n unsupportedFields.join(','),\n `${operation} fields ${unsupportedFields.join(', ')} have no declared compatibility projection.`\n );\n }\n\n private assertCompactWireFieldsAbsent(\n operation: string,\n value: Record<string, unknown>,\n fields: readonly string[]\n ): void {\n if (isCompactRelease(this.negotiated_version)) return;\n const unsupportedFields = fields.filter(field => Object.hasOwn(value, field));\n if (unsupportedFields.length === 0) return;\n throw this.unsupported(\n operation,\n unsupportedFields.join(','),\n `The negotiated ${this.negotiated_version} established tool cannot represent compact fields ${unsupportedFields.join(\n ', '\n )}. No mutation was sent.`\n );\n }\n\n private assertLegacyReferenceShapes(operation: string, input: Record<string, unknown>): void {\n if (isCompactRelease(this.negotiated_version)) return;\n const rejectBrandCountries = (brand: unknown, path: string): void => {\n if (Object.hasOwn(record(brand), 'countries')) {\n throw this.unsupported(\n operation,\n `${path}.countries`,\n `The negotiated ${this.negotiated_version} BrandRef cannot represent compact country-qualified identity. No request was sent.`\n );\n }\n };\n if (input.brand !== undefined) rejectBrandCountries(input.brand, 'brand');\n if (input.account !== undefined) {\n const account = record(input.account);\n for (const field of ['operator_unit', 'currency', 'timezone']) {\n if (Object.hasOwn(account, field)) {\n throw this.unsupported(\n operation,\n `account.${field}`,\n `The negotiated ${this.negotiated_version} AccountRef cannot represent compact ${field} identity. No request was sent.`\n );\n }\n }\n if (account.brand !== undefined) rejectBrandCountries(account.brand, 'account.brand');\n }\n }\n\n private assertLegacyOfferFilterShapes(operation: string, offerFilters: Record<string, unknown>): void {\n if (isCompactRelease(this.negotiated_version)) return;\n if (offerFilters.is_fixed_price === false) {\n throw this.unsupported(\n operation,\n 'criteria.offer_filters.is_fixed_price',\n 'Legacy is_fixed_price=false also matches contingent pricing, while compact filtering excludes it. No request was sent.'\n );\n }\n for (const field of ['required_performance_standards', 'required_vendor_metrics']) {\n for (const [index, item] of array(offerFilters[field]).entries()) {\n if (Object.hasOwn(record(record(item).vendor), 'countries')) {\n throw this.unsupported(\n operation,\n `criteria.offer_filters.${field}[${index}].vendor.countries`,\n `The negotiated ${this.negotiated_version} vendor BrandRef cannot represent compact country-qualified identity. No request was sent.`\n );\n }\n }\n }\n }\n\n private assertLegacyTargetingOverlay(operation: string, value: unknown, path: string): void {\n if (value === undefined || isCompactRelease(this.negotiated_version)) return;\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw this.unsupported(operation, path, `${path} must be an object. No request was sent.`);\n }\n const targeting = value as Record<string, unknown>;\n if (compareRelease(this.negotiated_version, '3.0') < 0) {\n if (Object.keys(targeting).length > 0) {\n throw this.unsupported(\n operation,\n path,\n `The negotiated ${this.negotiated_version} targeting field names are not compatible with compact targeting_overlay. No request was sent.`\n );\n }\n return;\n }\n const allowed = compareRelease(this.negotiated_version, '3.1') >= 0 ? V31_TARGETING_FIELDS : V30_TARGETING_FIELDS;\n const unsupported = Object.keys(targeting).filter(field => !allowed.has(field));\n if (unsupported.length > 0) {\n throw this.unsupported(\n operation,\n `${path}.${unsupported.join(',')}`,\n `The negotiated ${this.negotiated_version} targeting schema cannot represent ${unsupported.join(\n ', '\n )}. No request was sent.`\n );\n }\n for (const [index, language] of array(targeting.language).entries()) {\n if (typeof language !== 'string' || !/^[a-z]{2}$/.test(language)) {\n throw this.unsupported(\n operation,\n `${path}.language[${index}]`,\n `The negotiated ${this.negotiated_version} targeting schema accepts only two-letter lowercase language codes. No request was sent.`\n );\n }\n }\n if (compareRelease(this.negotiated_version, '3.1') >= 0) return;\n for (const field of ['geo_postal_areas', 'geo_postal_areas_exclude']) {\n for (const [index, areaValue] of array(targeting[field]).entries()) {\n const area = record(areaValue);\n if (Object.hasOwn(area, 'country') || !V30_POSTAL_SYSTEMS.has(String(area.system))) {\n throw this.unsupported(\n operation,\n `${path}.${field}[${index}]`,\n `The negotiated ${this.negotiated_version} postal targeting supports only legacy country-fused postal systems. No request was sent.`\n );\n }\n }\n }\n }\n\n private assertLegacyMetrics(operation: string, value: unknown, path: string): void {\n if (value === undefined || isCompactRelease(this.negotiated_version)) return;\n const supported =\n compareRelease(this.negotiated_version, '3.1') >= 0\n ? V31_AVAILABLE_METRICS\n : compareRelease(this.negotiated_version, '3.0') >= 0\n ? V30_AVAILABLE_METRICS\n : V25_AVAILABLE_METRICS;\n const unsupported = array(value).filter(metric => typeof metric !== 'string' || !supported.has(metric));\n if (unsupported.length === 0) return;\n throw this.unsupported(\n operation,\n path,\n `The negotiated ${this.negotiated_version} metric enum cannot represent ${unsupported.map(String).join(', ')}. No request was sent.`\n );\n }\n\n private assertLegacyReportingWebhook(operation: string, value: unknown, path = 'reporting_webhook'): void {\n if (value === undefined || isCompactRelease(this.negotiated_version)) return;\n this.assertLegacyMetrics(operation, record(value).requested_metrics, `${path}.requested_metrics`);\n }\n\n private assertLegacyPushNotification(operation: string, value: unknown): void {\n if (value === undefined || isCompactRelease(this.negotiated_version)) return;\n const config = record(value);\n if (compareRelease(this.negotiated_version, '3.0') < 0 && config.authentication === undefined) {\n throw this.unsupported(\n operation,\n 'push_notification_config.authentication',\n `The negotiated ${this.negotiated_version} push notification schema requires explicit authentication. No request was sent.`\n );\n }\n if (compareRelease(this.negotiated_version, '3.1') < 0 && Object.hasOwn(config, 'operation_id')) {\n throw this.unsupported(\n operation,\n 'push_notification_config.operation_id',\n `The negotiated ${this.negotiated_version} push notification registration cannot preserve compact operation_id correlation. No request was sent.`\n );\n }\n }\n\n private assertLegacyProductFields(operation: string, value: unknown): void {\n if (value === undefined || isCompactRelease(this.negotiated_version)) return;\n const supported = compareRelease(this.negotiated_version, '3.1') >= 0 ? V31_PRODUCT_FIELDS : V30_PRODUCT_FIELDS;\n const unsupported = array(value).filter(field => typeof field !== 'string' || !supported.has(field));\n if (unsupported.length === 0) return;\n throw this.unsupported(\n operation,\n 'fields',\n `The negotiated ${this.negotiated_version} product field enum cannot represent ${unsupported\n .map(String)\n .join(', ')}. No request was sent.`\n );\n }\n\n private legacyPurchaseSourceVersion(): LegacyPurchaseSourceVersion {\n if (compareRelease(this.negotiated_version, '3.1') >= 0) return '3.1';\n if (compareRelease(this.negotiated_version, '3.0') >= 0) return '3.0';\n return '2.5';\n }\n\n private legacyPurchaseLosses(sourceVersion: LegacyPurchaseSourceVersion): LegacyPurchaseLoss[] {\n return [\n 'feed_version_not_atomic',\n 'pricing_version_not_atomic',\n ...(sourceVersion === '2.5' || this.idempotencyReplayTtlMs === undefined\n ? (['mutation_idempotency_not_guaranteed'] as const)\n : []),\n ];\n }\n\n private legacyPurchaseBinding(accountScope: string): LegacyPurchaseBinding {\n const agent = this.agent.getAgent();\n const contextId = this.agent.getContextId();\n if (this.resolvedLegacyPurchaseSellerSessionScope === undefined) {\n let sessionScope = this.configuredLegacyPurchaseSellerSessionScope ?? contextId;\n if (sessionScope === undefined) {\n throw new ConfigurationError(\n 'Products-only legacy purchase continuations require legacyPurchaseSellerSessionScope in negotiateMediaBuyLifecycle() when the seller provides no context ID.'\n );\n }\n this.resolvedLegacyPurchaseSellerSessionScope = sessionScope;\n }\n return {\n principalScope: this.principalScope!,\n accountScope,\n sellerScope: requestFingerprint({ id: agent.id, uri: agent.agent_uri, protocol: agent.protocol }),\n clientSessionScope: this.resolvedLegacyPurchaseSellerSessionScope,\n sourceAdcpVersion: this.legacyPurchaseSourceVersion(),\n ...(contextId !== undefined && { discoveryContextId: contextId }),\n };\n }\n\n private async projectLegacyProductsAvailable(\n data: unknown,\n accountScope: string | undefined,\n discoveryRequestFingerprint: string\n ): Promise<unknown> {\n const source = compactWirePayload(data);\n if ((proposalRows(source)?.length ?? 0) > 0 || !Array.isArray(source.products) || source.products.length === 0) {\n return data;\n }\n // The arm is a compatibility projection for pre-3.2 sellers only. A\n // dual-surface 3.2 seller forced through its established facade remains a\n // native 3.2 peer and cannot be relabelled as a 3.1 source.\n const negotiatedRelease = parseRelease(this.negotiated_version);\n if (\n negotiatedRelease &&\n (negotiatedRelease.major > 3 || (negotiatedRelease.major === 3 && negotiatedRelease.minor >= 2))\n )\n return data;\n if (!this.principalScope) {\n return data;\n }\n if (!accountScope) {\n return data;\n }\n if (containsCredentialShapedKey(source) || containsPresignedUrl(source)) {\n throw new LegacyPurchaseContinuationError(\n 'request_invalid',\n 'The legacy products-only response contains credential-shaped material and cannot be persisted.'\n );\n }\n const observedBytes = Buffer.byteLength(canonicalize(source), 'utf8');\n if (observedBytes > 256 * 1024) {\n throw new LegacyPurchaseContinuationError(\n 'store_error',\n 'The legacy products-only response exceeds the 256 KiB continuation snapshot limit.'\n );\n }\n const productIds = source.products.map(product => optionalString(record(product).product_id));\n if (productIds.some(productId => productId === undefined) || new Set(productIds).size !== productIds.length) {\n throw new TypeError('The legacy products-only response did not contain distinct non-empty product IDs.');\n }\n const hasBoundPricingOptions = source.products.every(product => {\n const pricingOptionIds = array(record(product).pricing_options).map(option =>\n optionalString(record(option).pricing_option_id)\n );\n return (\n pricingOptionIds.length > 0 &&\n pricingOptionIds.every(pricingOptionId => pricingOptionId !== undefined) &&\n new Set(pricingOptionIds).size === pricingOptionIds.length\n );\n });\n if (!hasBoundPricingOptions) return data;\n const binding = this.legacyPurchaseBinding(accountScope);\n const sourceAdcpVersion = binding.sourceAdcpVersion;\n const losses = this.legacyPurchaseLosses(sourceAdcpVersion);\n const expiresAt = new Date(Date.now() + this.legacyPurchaseContinuationTtlMs).toISOString();\n const issuanceFingerprint = requestFingerprint({\n ...binding,\n discoveryRequestFingerprint,\n observedResponse: source,\n });\n let storedRecord: LegacyPurchaseContinuationRecord | undefined;\n for (let attempt = 0; attempt < 4 && !storedRecord; attempt += 1) {\n const token = randomBytes(24).toString('base64url');\n const continuation: LegacyPurchaseContinuationRecord = {\n token,\n ...binding,\n expiresAt,\n issuanceFingerprint,\n discoveryRequestFingerprint,\n observedResponse: source,\n productIds: productIds as string[],\n losses,\n operation: { state: 'available' },\n };\n try {\n const created = await this.legacyPurchaseContinuationStore.create(continuation);\n if (created.outcome === 'capacity') {\n throw new LegacyPurchaseContinuationError(\n 'store_error',\n 'The legacy purchase continuation store is at capacity.',\n true\n );\n }\n storedRecord = created.record;\n } catch (error) {\n if (error instanceof LegacyPurchaseContinuationError) throw error;\n throw new LegacyPurchaseContinuationError(\n 'store_error',\n 'Could not persist the legacy purchase continuation.',\n true,\n undefined,\n error\n );\n }\n }\n if (!storedRecord) {\n throw new LegacyPurchaseContinuationError(\n 'store_error',\n 'Could not allocate a unique legacy purchase continuation token.',\n true\n );\n }\n const projected: Record<PropertyKey, unknown> = {\n outcome: 'products_available',\n products: source.products,\n ...(Array.isArray(source.incomplete) && { incomplete: source.incomplete }),\n ...(Array.isArray(source.errors) && { errors: source.errors }),\n ...(source.context !== undefined && { context: source.context }),\n purchase_continuation: {\n kind: 'legacy_create',\n continuation_token: storedRecord.token,\n continuation_expires_at: storedRecord.expiresAt,\n source_adcp_version: storedRecord.sourceAdcpVersion,\n product_ids: storedRecord.productIds,\n losses: storedRecord.losses,\n requires_explicit_acceptance: true,\n },\n };\n Object.defineProperty(projected, LEGACY_PROPOSAL_RAW, { value: source, enumerable: false });\n return projected;\n }\n\n private async prepareLegacyProposalResult<T>(\n result: TaskResult<T>,\n accountScope: string | undefined,\n discoveryRequestFingerprint: string\n ): Promise<TaskResult<T>> {\n const prepare = (value: unknown): Promise<unknown> =>\n this.projectLegacyProductsAvailable(value, accountScope, discoveryRequestFingerprint);\n if (\n result.success &&\n result.status === 'completed' &&\n isAdcpOperationSuccess(result.data, result.metadata.taskName)\n ) {\n (result as TaskResult<unknown>).data = await prepare(result.data);\n }\n if (result.submitted) {\n const submitted = result.submitted;\n (result as { submitted?: unknown }).submitted = {\n ...submitted,\n track: async (transport?: import('../protocols').TransportOptions) => {\n const task = await submitted.track(transport);\n if (\n task.status === 'completed' &&\n task.result !== undefined &&\n isAdcpOperationSuccess(task.result, task.taskType)\n ) {\n task.result = await prepare(task.result);\n }\n return task;\n },\n waitForCompletion: async (pollInterval?: number, signal?: AbortSignal) =>\n this.prepareLegacyProposalResult(\n await submitted.waitForCompletion(pollInterval, signal),\n accountScope,\n discoveryRequestFingerprint\n ),\n };\n }\n if (result.deferred) {\n const deferred = result.deferred;\n (result as { deferred?: unknown }).deferred = {\n ...deferred,\n resume: async (input: unknown) =>\n this.prepareLegacyProposalResult(await deferred.resume(input), accountScope, discoveryRequestFingerprint),\n };\n }\n return result;\n }\n\n private assertLegacyReportingDimensions(operation: string, value: unknown): void {\n if (value === undefined || isCompactRelease(this.negotiated_version)) return;\n const dimensions = record(value);\n const unsupported = Object.keys(dimensions).filter(field => !LEGACY_REPORTING_DIMENSIONS.has(field));\n if (unsupported.length > 0) {\n throw this.unsupported(\n operation,\n `reporting_dimensions.${unsupported.join(',')}`,\n `The negotiated ${this.negotiated_version} seller cannot represent reporting dimensions ${unsupported.join(\n ', '\n )}. No request was sent.`\n );\n }\n if (compareRelease(this.negotiated_version, '3.1') >= 0) return;\n const geo = record(dimensions.geo);\n const legacySystems =\n geo.geo_level === 'postal_area' ? V30_POSTAL_SYSTEMS : geo.geo_level === 'metro' ? V30_METRO_SYSTEMS : undefined;\n if (legacySystems && (Object.hasOwn(geo, 'country') || !legacySystems.has(String(geo.system)))) {\n throw this.unsupported(\n operation,\n 'reporting_dimensions.geo',\n `The negotiated ${this.negotiated_version} delivery breakdown requires a valid legacy country-fused metro or postal system. No request was sent.`\n );\n }\n }\n\n private assertProposalLifecycleAvailable(operation: string): void {\n if (compareRelease(this.negotiated_version, '3.0') >= 0) return;\n throw this.unsupported(\n operation,\n 'proposal_lifecycle',\n `The negotiated ${this.negotiated_version} seller has no proposal object or proposal-binding mutation. No request was sent.`\n );\n }\n\n private accountScope(account: unknown): string | undefined {\n const value = record(account);\n return Object.keys(value).length > 0 ? canonicalize(value) : undefined;\n }\n\n private snapshotKey(proposalId: string, accountScope: string | undefined): string {\n return `${this.principalScope ?? 'missing-principal-scope'}\\u0000${accountScope ?? 'unscoped'}\\u0000${proposalId}`;\n }\n\n private proposalScopes(proposalIds: readonly string[]): string[] {\n const wanted = new Set(proposalIds);\n const scopes = new Set<string>();\n for (const entry of this.proposalSnapshotStore.entries.values()) {\n if (\n entry.principalScope === this.principalScope &&\n entry.accountScope &&\n wanted.has(String(entry.proposal.proposal_id))\n ) {\n scopes.add(entry.accountScope);\n }\n }\n return [...scopes];\n }\n\n private removeProposalSnapshot(key: string): void {\n const existing = this.proposalSnapshotStore.entries.get(key);\n if (existing) {\n this.proposalSnapshotStore.bytes -= existing.bytes;\n }\n this.proposalSnapshotStore.entries.delete(key);\n }\n\n private retainProposalSnapshot(key: string, entry: ProposalSnapshotEntry): void {\n this.proposalSnapshotStore.entries.set(key, entry);\n this.proposalSnapshotStore.bytes += entry.bytes;\n }\n\n private isRetiredAcceptanceKey(key: string): boolean {\n const registry = this.proposalSnapshotStore.registry;\n const salt = registry.retiredAcceptanceSalt;\n if (!salt) return false;\n const segmentIndex =\n createHash('sha256')\n .update(salt)\n .update(this.principalScope ?? '\\u0000unscoped')\n .digest()\n .readUInt32BE(0) % RETIRED_ACCEPTANCE_SEGMENT_COUNT;\n const bits = registry.retiredAcceptanceSegments?.get(segmentIndex);\n if (!bits) return false;\n return retiredAcceptancePositions(key, salt, bits.length * 8).every(position => {\n const mask = 1 << (position & 7);\n return (bits[position >> 3]! & mask) !== 0;\n });\n }\n\n private markRetiredAcceptanceKey(key: string): void {\n const registry = this.proposalSnapshotStore.registry;\n const salt = (registry.retiredAcceptanceSalt ??= randomBytes(16));\n const segmentIndex =\n createHash('sha256')\n .update(salt)\n .update(this.principalScope ?? '\\u0000unscoped')\n .digest()\n .readUInt32BE(0) % RETIRED_ACCEPTANCE_SEGMENT_COUNT;\n const segments = (registry.retiredAcceptanceSegments ??= new Map());\n let bits = segments.get(segmentIndex);\n if (!bits) {\n bits = new Uint8Array(RETIRED_ACCEPTANCE_SEGMENT_BYTES);\n segments.set(segmentIndex, bits);\n }\n for (const position of retiredAcceptancePositions(key, salt, bits.length * 8)) {\n bits[position >> 3] = bits[position >> 3]! | (1 << (position & 7));\n }\n }\n\n private terminalProposalKey(proposalId: string): string {\n return `${this.principalScope ?? 'missing-principal-scope'}\\u0000terminal-proposal\\u0000${proposalId}`;\n }\n\n private isTerminalProposal(proposalId: string): boolean {\n return this.isRetiredAcceptanceKey(this.terminalProposalKey(proposalId));\n }\n\n private markTerminalProposal(proposalId: string): void {\n this.markRetiredAcceptanceKey(this.terminalProposalKey(proposalId));\n }\n\n private terminalAcceptanceProposalKey(proposalId: string): string {\n return `${this.principalScope ?? 'missing-principal-scope'}\\u0000terminal-acceptance-proposal\\u0000${proposalId}`;\n }\n\n private isTerminalAcceptanceProposal(proposalId: string): boolean {\n return this.isRetiredAcceptanceKey(this.terminalAcceptanceProposalKey(proposalId));\n }\n\n private markTerminalAcceptanceProposal(proposalId: string): void {\n this.markRetiredAcceptanceKey(this.terminalAcceptanceProposalKey(proposalId));\n }\n\n private acceptedProposalKey(proposalId: string): string {\n return `${this.principalScope ?? 'missing-principal-scope'}\\u0000accepted-proposal\\u0000${proposalId}`;\n }\n\n private isAcceptedProposal(proposalId: string): boolean {\n return this.isRetiredAcceptanceKey(this.acceptedProposalKey(proposalId));\n }\n\n private markAcceptedProposal(proposalId: string): void {\n this.markRetiredAcceptanceKey(this.acceptedProposalKey(proposalId));\n }\n\n private commitUncertainProposalKey(proposalId: string): string {\n return `${this.principalScope ?? 'missing-principal-scope'}\\u0000commit-uncertain-proposal\\u0000${proposalId}`;\n }\n\n private isCommitUncertainProposal(proposalId: string): boolean {\n return this.isRetiredAcceptanceKey(this.commitUncertainProposalKey(proposalId));\n }\n\n private markCommitUncertainProposal(proposalId: string): void {\n this.markRetiredAcceptanceKey(this.commitUncertainProposalKey(proposalId));\n }\n\n private commitUncertainProposalMutationKey(proposalId: string): string {\n return `${this.principalScope ?? 'missing-principal-scope'}\\u0000commit-uncertain-proposal-mutation\\u0000${proposalId}`;\n }\n\n private isCommitUncertainProposalMutation(proposalId: string): boolean {\n return this.isRetiredAcceptanceKey(this.commitUncertainProposalMutationKey(proposalId));\n }\n\n private markCommitUncertainProposalMutation(proposalId: string): void {\n this.markRetiredAcceptanceKey(this.commitUncertainProposalMutationKey(proposalId));\n }\n\n private enforceProposalSnapshotLimits(): void {\n while (\n this.proposalSnapshotStore.entries.size > MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOTS ||\n this.proposalSnapshotStore.bytes > MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOT_TOTAL_BYTES\n ) {\n const oldest = [...this.proposalSnapshotStore.entries].find(\n ([, entry]) =>\n entry.acceptance?.state !== 'in-flight' &&\n !this.isProposalRefinementPending(String(entry.proposal.proposal_id))\n );\n if (!oldest) break;\n const [key, entry] = oldest;\n if (entry.acceptance?.state === 'retryable') {\n this.retireAcceptance(key, entry, entry.acceptance);\n } else {\n this.removeProposalSnapshot(key);\n }\n }\n }\n\n private invalidateProposalSnapshots(\n proposalIds: readonly string[],\n accountScope?: string,\n preserveScope = false,\n retireAcceptances = false\n ): void {\n if (retireAcceptances) proposalIds.forEach(proposalId => this.markTerminalProposal(proposalId));\n const wanted = new Set(proposalIds);\n for (const [key, entry] of [...this.proposalSnapshotStore.entries]) {\n if (entry.principalScope !== this.principalScope) continue;\n if (!wanted.has(String(entry.proposal.proposal_id))) continue;\n if (accountScope !== undefined && entry.accountScope !== accountScope) continue;\n if (entry.acceptance) {\n if (retireAcceptances) this.retireAcceptance(key, entry, entry.acceptance);\n continue;\n }\n if (preserveScope && entry.accountScope) {\n this.removeProposalSnapshot(key);\n const proposal = { proposal_id: entry.proposal.proposal_id };\n const bytes = new TextEncoder().encode(`${key}${JSON.stringify(proposal)}`).byteLength;\n this.retainProposalSnapshot(key, {\n proposal,\n bytes,\n principalScope: entry.principalScope,\n executable: false,\n accountScope: entry.accountScope,\n });\n } else {\n this.removeProposalSnapshot(key);\n }\n }\n }\n\n private proposalIdsIn(data: unknown): string[] {\n const ids = new Set<string>();\n const seen = new WeakSet<object>();\n const stack = [data];\n let visited = 0;\n while (stack.length > 0) {\n const value = stack.pop();\n if (value === null || typeof value !== 'object' || seen.has(value)) continue;\n seen.add(value);\n visited += 1;\n if (visited > MAX_PROPOSAL_TRAVERSAL_NODES) return this.cachedProposalIds();\n if (Array.isArray(value)) {\n if (stack.length + value.length > MAX_PROPOSAL_TRAVERSAL_NODES) return this.cachedProposalIds();\n for (let index = value.length - 1; index >= 0; index -= 1) stack.push(value[index]);\n continue;\n }\n const candidate = value as Record<string, unknown>;\n const proposalId = optionalString(candidate.proposal_id);\n if (proposalId) ids.add(proposalId);\n if (candidate.results !== undefined) stack.push(candidate.results);\n if (candidate.proposal !== undefined) stack.push(candidate.proposal);\n if (candidate.proposals !== undefined) stack.push(candidate.proposals);\n }\n return [...ids];\n }\n\n private cachedProposalIds(accountScope?: string): string[] {\n if (!this.principalScope) return [];\n const ids = new Set<string>();\n for (const entry of this.proposalSnapshotStore.entries.values()) {\n if (entry.principalScope !== this.principalScope || entry.acceptance) continue;\n if (accountScope !== undefined && entry.accountScope !== accountScope) continue;\n ids.add(String(entry.proposal.proposal_id));\n }\n return [...ids];\n }\n\n private cachedProposalIdsIn(data: unknown, accountScope?: string): string[] {\n const wanted = new Set(this.cachedProposalIds(accountScope));\n if (wanted.size === 0) return [];\n const found: string[] = [];\n const seen = new WeakSet<object>();\n const stack = [data];\n let visited = 0;\n while (stack.length > 0 && wanted.size > 0) {\n const value = stack.pop();\n if (value === null || typeof value !== 'object' || seen.has(value)) continue;\n seen.add(value);\n visited += 1;\n if (visited > MAX_PROPOSAL_TRAVERSAL_NODES) return this.cachedProposalIds(accountScope);\n if (Array.isArray(value)) {\n if (stack.length + value.length > MAX_PROPOSAL_TRAVERSAL_NODES) {\n return this.cachedProposalIds(accountScope);\n }\n for (let index = value.length - 1; index >= 0; index -= 1) stack.push(value[index]);\n continue;\n }\n const candidate = value as Record<string, unknown>;\n const proposalId = optionalString(candidate.proposal_id);\n if (proposalId && wanted.delete(proposalId)) found.push(proposalId);\n if (candidate.results !== undefined) stack.push(candidate.results);\n if (candidate.proposal !== undefined) stack.push(candidate.proposal);\n if (candidate.proposals !== undefined) stack.push(candidate.proposals);\n }\n return found;\n }\n\n private safeProposalPayload(data: unknown): { snapshots: SafeProposalSnapshot[] } | undefined {\n const snapshots = new Map<string, { snapshot: SafeProposalSnapshot; bytes: number } | null>();\n const seen = new WeakSet<object>();\n let bytes = 0;\n let overflowed = false;\n const stack = [data];\n let visited = 0;\n try {\n while (stack.length > 0 && !overflowed) {\n const value = stack.pop();\n if (value === null || typeof value !== 'object' || seen.has(value)) continue;\n seen.add(value);\n visited += 1;\n if (visited > MAX_PROPOSAL_TRAVERSAL_NODES) {\n overflowed = true;\n break;\n }\n if (Array.isArray(value)) {\n if (stack.length + value.length > MAX_PROPOSAL_TRAVERSAL_NODES) {\n overflowed = true;\n break;\n }\n for (let index = value.length - 1; index >= 0; index -= 1) stack.push(value[index]);\n continue;\n }\n const candidate = value as Record<string, unknown>;\n const proposalId = optionalString(candidate.proposal_id);\n if (proposalId) {\n if (!snapshots.has(proposalId) && snapshots.size >= MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOTS) {\n overflowed = true;\n return;\n }\n const prior = snapshots.get(proposalId);\n if (prior) bytes -= prior.bytes;\n const safe = safeProposalSnapshot(candidate);\n if (safe) {\n // Detach while this listener still owns the checked representation.\n // Later task-update listeners may mutate the shared TaskInfo object.\n const detached = structuredClone(safe);\n const candidateBytes = new TextEncoder().encode(JSON.stringify(detached.proposal)).byteLength;\n if (\n candidateBytes > MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOT_BYTES ||\n bytes + candidateBytes > MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOT_TOTAL_BYTES\n ) {\n overflowed = true;\n return;\n }\n snapshots.set(proposalId, { snapshot: detached, bytes: candidateBytes });\n bytes += candidateBytes;\n } else {\n // Preserve last-observation semantics: a later unsafe duplicate must\n // revoke an earlier safe representation of the same proposal ID.\n snapshots.set(proposalId, null);\n }\n }\n if (candidate.results !== undefined) stack.push(candidate.results);\n if (candidate.proposal !== undefined) stack.push(candidate.proposal);\n if (candidate.proposals !== undefined) stack.push(candidate.proposals);\n }\n } catch {\n return undefined;\n }\n if (overflowed) return undefined;\n const retained = [...snapshots.values()].flatMap(snapshot => (snapshot ? [snapshot.snapshot] : []));\n return retained.length > 0 ? { snapshots: retained } : undefined;\n }\n\n private captureProposalDispatch<T, U>(\n accountScope: string | undefined,\n dispatch: () => Promise<TaskResult<T>>,\n adapt: (result: TaskResult<T>) => U | Promise<U>,\n projectCompletion?: (data: T) => unknown,\n onCompletionFailure?: () => void,\n retainCompletionProposals = true,\n prepareMatchedCompletion?: (projected: unknown) => () => void,\n onAuthoritativeFailure?: () => void\n ): Promise<U> {\n const captured = new Map<\n string,\n | {\n kind: 'success';\n proposalIds: string[];\n payload?: { snapshots: SafeProposalSnapshot[] };\n settle?: () => void;\n bytes: number;\n }\n | { kind: 'failure'; proposalIds: string[]; authoritative: boolean; bytes: number }\n >();\n let capturedPayloadBytes = 0;\n let captureOverflowed = false;\n const releaseTaskListener = this.agent.onTaskUpdate(task => {\n if (this.disposed) return;\n if (['pending', 'running', 'working', 'submitted'].includes(task.status)) return;\n const operationSucceeded =\n task.status === 'completed' && task.result !== undefined && isAdcpOperationSuccess(task.result, task.taskType);\n const authoritativeFailure =\n task.status === 'failed' ||\n task.status === 'governance-denied' ||\n (task.status === 'completed' &&\n task.result !== undefined &&\n !isAdcpOperationSuccess(task.result, task.taskType));\n let projectedResult = task.result;\n let projectionSucceeded = operationSucceeded;\n if (operationSucceeded && projectCompletion) {\n try {\n projectedResult = projectCompletion(task.result as T);\n } catch {\n projectionSucceeded = false;\n }\n }\n let settle: (() => void) | undefined;\n if (projectionSucceeded && prepareMatchedCompletion) {\n try {\n settle = prepareMatchedCompletion(projectedResult);\n } catch {\n projectionSucceeded = false;\n }\n }\n const safe =\n projectionSucceeded && retainCompletionProposals ? this.safeProposalPayload(projectedResult) : undefined;\n const proposalIds =\n retainCompletionProposals && projectedResult !== undefined\n ? this.cachedProposalIdsIn(projectedResult, accountScope)\n : [];\n const metadataBytes = new TextEncoder().encode(JSON.stringify(proposalIds)).byteLength;\n const safeBytes = safe ? new TextEncoder().encode(JSON.stringify(safe)).byteLength : 0;\n const retainSafe =\n safe !== undefined &&\n metadataBytes + safeBytes <= MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOT_TOTAL_BYTES;\n const bytes = retainSafe ? safeBytes : 0;\n const replaced = captured.get(task.taskId);\n if (replaced) capturedPayloadBytes -= replaced.bytes;\n captured.delete(task.taskId);\n captured.set(\n task.taskId,\n projectionSucceeded\n ? {\n kind: 'success',\n proposalIds,\n ...(retainSafe && { payload: safe }),\n ...(settle && { settle }),\n bytes,\n }\n : { kind: 'failure', proposalIds, authoritative: authoritativeFailure, bytes }\n );\n capturedPayloadBytes += bytes;\n while (capturedPayloadBytes > MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOT_TOTAL_BYTES) {\n const oldestWithPayload = [...captured].find(([, entry]) => entry.kind === 'success' && entry.payload);\n if (!oldestWithPayload) break;\n const [taskId, entry] = oldestWithPayload;\n if (entry.kind !== 'success') continue;\n capturedPayloadBytes -= entry.bytes;\n captured.set(taskId, {\n kind: 'success',\n proposalIds: entry.proposalIds,\n ...(entry.settle && { settle: entry.settle }),\n bytes: 0,\n });\n }\n while (captured.size > 32) {\n const oldest = captured.keys().next().value as string | undefined;\n if (oldest === undefined) break;\n capturedPayloadBytes -= captured.get(oldest)?.bytes ?? 0;\n captured.delete(oldest);\n captureOverflowed = true;\n }\n });\n let released = false;\n const unsubscribe = (): void => {\n if (released) return;\n released = true;\n releaseTaskListener();\n this.proposalDispatchUnsubscribes.delete(unsubscribe);\n };\n this.proposalDispatchUnsubscribes.add(unsubscribe);\n let dispatched: Promise<TaskResult<T>>;\n try {\n dispatched = dispatch();\n } catch (error) {\n unsubscribe();\n return Promise.reject(error);\n }\n return dispatched\n .then(\n async result => {\n this.assertActive('proposal dispatch completion');\n const racedCompletion = captured.get(result.metadata.taskId);\n if (racedCompletion?.kind === 'success') {\n racedCompletion.settle?.();\n this.invalidateProposalSnapshots(racedCompletion.proposalIds, accountScope);\n if (racedCompletion.payload) {\n for (const snapshot of racedCompletion.payload.snapshots) {\n this.rememberSafeProposalSnapshot(snapshot, accountScope);\n }\n }\n } else if (racedCompletion?.kind === 'failure') {\n if (racedCompletion.authoritative && onAuthoritativeFailure) {\n onAuthoritativeFailure();\n } else {\n this.invalidateProposalSnapshots(racedCompletion.proposalIds, accountScope);\n onCompletionFailure?.();\n }\n } else if (captureOverflowed) {\n // The dispatch task ID is not knowable until dispatch returns. If\n // unrelated terminal events overflow the bounded correlation map,\n // a missing match might be the evicted task. Retire every mutable\n // snapshot in scope rather than leave stale execution evidence.\n this.invalidateProposalSnapshots(this.cachedProposalIds(accountScope), accountScope);\n onCompletionFailure?.();\n }\n // adaptProjectedResult installs the long-lived watcher, when needed,\n // before this pre-dispatch listener is released.\n const output = await adapt(result);\n if (racedCompletion || captureOverflowed) this.forgetProposalTask(result.metadata.taskId);\n return output;\n },\n error => {\n if (this.disposed) throw error;\n // A terminal event can beat a transport failure. Without the\n // dispatch result there is no trustworthy task ID for correlation,\n // so any captured terminal evidence makes every mutable snapshot in\n // this scope unsafe to reuse.\n if (captured.size > 0 || captureOverflowed) {\n this.invalidateProposalSnapshots(this.cachedProposalIds(accountScope), accountScope);\n onCompletionFailure?.();\n }\n throw error;\n }\n )\n .finally(unsubscribe);\n }\n\n private watchProposalTask(\n taskId: string | undefined,\n accountScope: string | undefined,\n project: ((data: unknown) => unknown) | undefined,\n retainProposals: boolean,\n onPause?: () => void,\n onTerminalFailure?: () => void,\n onAuthoritativeFailure?: () => void,\n preserveAuthoritativeProposals = false,\n authoritativeTaskNames: ReadonlySet<string> = new Set()\n ): void {\n if (!taskId) return;\n this.pendingProposalTasks.delete(taskId);\n this.pendingProposalTasks.set(taskId, {\n accountScope,\n ...(project && { project }),\n retainProposals,\n ...(onPause && { onPause }),\n ...(onAuthoritativeFailure && { onAuthoritativeFailure }),\n authoritativeTaskNames,\n ...(preserveAuthoritativeProposals && { preserveAuthoritativeProposals }),\n ...(onTerminalFailure && { onTerminalFailure }),\n });\n const priorTimer = this.pendingProposalTaskTimers.get(taskId);\n if (priorTimer) clearTimeout(priorTimer);\n const timer = setTimeout(() => {\n const pending = this.pendingProposalTasks.get(taskId);\n if (!pending || this.pendingProposalTaskTimers.get(taskId) !== timer) return;\n pending.onTerminalFailure?.();\n this.forgetProposalTask(taskId);\n }, MediaBuyLifecycleCoordinator.PROPOSAL_TASK_WATCH_TTL_MS);\n timer.unref?.();\n this.pendingProposalTaskTimers.set(taskId, timer);\n while (this.pendingProposalTasks.size > MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOTS) {\n const oldest = this.pendingProposalTasks.keys().next().value as string | undefined;\n if (oldest === undefined) break;\n this.forgetProposalTask(oldest);\n }\n const handleUpdate = (task: import('../core/ConversationTypes').TaskInfo): void => {\n if (this.disposed) return;\n const pending = this.pendingProposalTasks.get(task.taskId);\n if (!pending) return;\n if (\n task.status === 'completed' &&\n task.result !== undefined &&\n pending.authoritativeTaskNames?.has(task.taskType) &&\n isAdcpOperationSuccess(task.result, task.taskType)\n ) {\n try {\n const projected = pending.project ? pending.project(task.result) : task.result;\n if (pending.retainProposals) this.rememberProposals(projected, pending.accountScope);\n } catch {\n this.invalidateProposalSnapshots(this.proposalIdsIn(task.result), pending.accountScope);\n pending.onTerminalFailure?.();\n }\n } else if (['pending', 'running', 'working', 'submitted'].includes(task.status)) {\n return;\n } else if (task.status === 'input-required' || task.status === 'auth-required') {\n pending.onPause?.();\n } else if (\n (task.status === 'failed' || task.status === 'governance-denied' || task.status === 'completed') &&\n pending.authoritativeTaskNames?.has(task.taskType)\n ) {\n if (task.result !== undefined && !pending.preserveAuthoritativeProposals) {\n this.invalidateProposalSnapshots(this.proposalIdsIn(task.result), pending.accountScope);\n }\n pending.onAuthoritativeFailure?.();\n } else {\n if (task.result !== undefined) {\n this.invalidateProposalSnapshots(this.proposalIdsIn(task.result), pending.accountScope);\n }\n pending.onTerminalFailure?.();\n }\n this.forgetProposalTask(task.taskId);\n };\n if (!this.proposalTaskUnsubscribe) {\n this.proposalTaskUnsubscribe = this.agent.onTaskUpdate(handleUpdate);\n }\n }\n\n private forgetProposalTask(taskId: string): void {\n this.pendingProposalTasks.delete(taskId);\n const timer = this.pendingProposalTaskTimers.get(taskId);\n if (timer) clearTimeout(timer);\n this.pendingProposalTaskTimers.delete(taskId);\n if (this.pendingProposalTasks.size === 0) {\n this.proposalTaskUnsubscribe?.();\n this.proposalTaskUnsubscribe = undefined;\n }\n }\n\n private ownsAcceptance(\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation\n ): boolean {\n const proposalId = String(snapshot.proposal.proposal_id);\n const global = this.proposalSnapshotStore.proposalAcceptances.get(proposalId);\n return (\n this.proposalSnapshotStore.entries.get(snapshotKey) === snapshot &&\n snapshot.acceptance === reservation &&\n global?.snapshotKey === snapshotKey &&\n global.snapshot === snapshot &&\n global.reservation === reservation\n );\n }\n\n private releaseAcceptanceOwnership(reservation: AcceptanceReservation): void {\n const owner = acceptanceReservationOwners.get(reservation);\n if (!owner) return;\n owner.ownedAcceptanceReservations.delete(reservation);\n if (reservation.taskId) owner.forgetAcceptanceTask(reservation.taskId, reservation);\n const retryExpiryTimer = owner.acceptanceRetryExpiryTimers.get(reservation);\n if (retryExpiryTimer) clearTimeout(retryExpiryTimer);\n owner.acceptanceRetryExpiryTimers.delete(reservation);\n acceptanceReservationOwners.delete(reservation);\n }\n\n private scheduleAcceptanceRetryExpiry(\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation\n ): void {\n const deadline = reservation.retryDeadlineMs;\n if (deadline === undefined || deadline <= Date.now()) {\n this.retireAcceptance(snapshotKey, snapshot, reservation);\n return;\n }\n const priorTimer = this.acceptanceRetryExpiryTimers.get(reservation);\n if (priorTimer) clearTimeout(priorTimer);\n const timer = setTimeout(() => {\n this.retireAcceptance(snapshotKey, snapshot, reservation);\n }, deadline - Date.now());\n timer.unref?.();\n this.acceptanceRetryExpiryTimers.set(reservation, timer);\n }\n\n private assertAcceptanceRetryWindow(\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation\n ): void {\n if (reservation.retryDeadlineMs !== undefined && reservation.retryDeadlineMs > Date.now()) return;\n this.retireAcceptance(snapshotKey, snapshot, reservation);\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_retry_window',\n 'The seller no longer guarantees idempotent replay of this paused acceptance. Reconcile by natural key before any new mutation.'\n );\n }\n\n private restoreAcceptance(\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation\n ): void {\n if (!this.ownsAcceptance(snapshotKey, snapshot, reservation) || reservation.state !== 'in-flight') return;\n this.proposalSnapshotStore.proposalAcceptances.delete(String(snapshot.proposal.proposal_id));\n this.releaseAcceptanceOwnership(reservation);\n delete snapshot.acceptance;\n if (snapshot.nativeAcceptanceOnly) this.removeProposalSnapshot(snapshotKey);\n else snapshot.executable = true;\n }\n\n private retireAcceptance(\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation,\n disposition: 'terminal' | 'accepted' | 'commit-uncertain' = reservation.retryKind === 'commit-uncertain'\n ? 'commit-uncertain'\n : 'terminal'\n ): void {\n if (!this.ownsAcceptance(snapshotKey, snapshot, reservation) || reservation.state === 'retired') return;\n const proposalId = String(snapshot.proposal.proposal_id);\n if (disposition === 'commit-uncertain') {\n this.markCommitUncertainProposal(proposalId);\n } else {\n this.markTerminalAcceptanceProposal(proposalId);\n if (disposition === 'accepted') this.markAcceptedProposal(proposalId);\n }\n reservation.state = 'retired';\n snapshot.executable = false;\n this.proposalSnapshotStore.proposalAcceptances.delete(proposalId);\n this.releaseAcceptanceOwnership(reservation);\n this.markTerminalProposal(proposalId);\n for (const [key, sibling] of [...this.proposalSnapshotStore.entries]) {\n if (sibling.principalScope !== this.principalScope || sibling.proposal.proposal_id !== proposalId) continue;\n if (sibling.acceptance && sibling.acceptance !== reservation) {\n sibling.acceptance.state = 'retired';\n this.releaseAcceptanceOwnership(sibling.acceptance);\n }\n sibling.executable = false;\n this.removeProposalSnapshot(key);\n this.markRetiredAcceptanceKey(key);\n }\n }\n\n private preserveAmbiguousAcceptance(\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation,\n taskId?: string,\n retryKind: 'paused' | 'commit-uncertain' = 'commit-uncertain'\n ): void {\n if (!this.ownsAcceptance(snapshotKey, snapshot, reservation) || reservation.state !== 'in-flight') return;\n reservation.retryKind = retryKind;\n if (!reservation.idempotencyKey || reservation.retryDeadlineMs === undefined) {\n this.retireAcceptance(snapshotKey, snapshot, reservation);\n return;\n }\n reservation.state = 'retryable';\n snapshot.executable = false;\n this.watchAcceptanceTask(\n taskId ?? `acceptance-retry:${generateIdempotencyKey()}`,\n snapshotKey,\n snapshot,\n reservation\n );\n this.scheduleAcceptanceRetryExpiry(snapshotKey, snapshot, reservation);\n }\n\n private transitionAcceptanceResult<T>(\n result: TaskResult<T>,\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation\n ): void {\n if (!this.ownsAcceptance(snapshotKey, snapshot, reservation) || reservation.state !== 'in-flight') return;\n if (result.status === 'input-required' || result.status === 'auth-required' || result.status === 'deferred') {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation, result.metadata.taskId, 'paused');\n return;\n }\n if (\n result.status === 'completed' &&\n result.data !== undefined &&\n !isAdcpOperationSuccess(result.data, result.metadata.taskName)\n ) {\n this.restoreAcceptance(snapshotKey, snapshot, reservation);\n this.forgetAcceptanceTask(result.metadata.taskId, reservation);\n return;\n }\n if (!result.success) {\n if (result.metadata.taskName === 'unknown') {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation, result.metadata.taskId);\n return;\n }\n this.restoreAcceptance(snapshotKey, snapshot, reservation);\n this.forgetAcceptanceTask(result.metadata.taskId, reservation);\n return;\n }\n if (result.status === 'working' || result.status === 'submitted') {\n this.watchAcceptanceTask(result.metadata.taskId, snapshotKey, snapshot, reservation);\n return;\n }\n this.retireAcceptance(snapshotKey, snapshot, reservation, 'accepted');\n this.forgetAcceptanceTask(result.metadata.taskId, reservation);\n }\n\n private transitionAcceptanceTask(\n task: import('../core/ConversationTypes').TaskInfo,\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation,\n watchedTaskId = task.taskId\n ): void {\n if (!this.ownsAcceptance(snapshotKey, snapshot, reservation) || reservation.state !== 'in-flight') return;\n if (['input-required', 'auth-required', 'needs_input', 'deferred'].includes(task.status)) {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation, watchedTaskId, 'paused');\n return;\n }\n if (['pending', 'running', 'working', 'submitted', 'deferred'].includes(task.status)) return;\n if (task.status === 'completed') {\n if (isAdcpOperationSuccess(task.result, task.taskType)) {\n this.retireAcceptance(snapshotKey, snapshot, reservation, 'accepted');\n } else {\n this.restoreAcceptance(snapshotKey, snapshot, reservation);\n }\n } else if (['failed', 'rejected', 'canceled', 'governance-denied'].includes(task.status)) {\n this.restoreAcceptance(snapshotKey, snapshot, reservation);\n } else {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation, watchedTaskId);\n return;\n }\n this.forgetAcceptanceTask(watchedTaskId, reservation);\n }\n\n private watchAcceptanceTask(\n taskId: string | undefined,\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation\n ): void {\n if (!taskId) return;\n if (reservation.taskId && reservation.taskId !== taskId) {\n this.forgetAcceptanceTask(reservation.taskId, reservation);\n }\n reservation.taskId = taskId;\n this.pendingAcceptanceTasks.set(taskId, { snapshotKey, snapshot, reservation });\n const priorTimer = this.pendingAcceptanceTaskTimers.get(taskId);\n if (priorTimer) clearTimeout(priorTimer);\n const timer = setTimeout(() => {\n if (reservation.state === 'in-flight') {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation, taskId, 'commit-uncertain');\n }\n this.forgetAcceptanceTask(taskId, reservation);\n }, MediaBuyLifecycleCoordinator.PROPOSAL_TASK_WATCH_TTL_MS);\n timer.unref?.();\n this.pendingAcceptanceTaskTimers.set(taskId, timer);\n const handleUpdate = (task: import('../core/ConversationTypes').TaskInfo): void => {\n if (this.disposed) return;\n const pending = this.pendingAcceptanceTasks.get(task.taskId);\n if (!pending) return;\n this.transitionAcceptanceTask(task, pending.snapshotKey, pending.snapshot, pending.reservation, task.taskId);\n };\n if (!this.acceptanceTaskUnsubscribe) {\n this.acceptanceTaskUnsubscribe = this.agent.onTaskUpdate(handleUpdate);\n }\n }\n\n private forgetAcceptanceTask(taskId: string, reservation?: AcceptanceReservation): void {\n const pending = this.pendingAcceptanceTasks.get(taskId);\n if (reservation && pending?.reservation !== reservation) return;\n this.pendingAcceptanceTasks.delete(taskId);\n const timer = this.pendingAcceptanceTaskTimers.get(taskId);\n if (timer) clearTimeout(timer);\n this.pendingAcceptanceTaskTimers.delete(taskId);\n if (this.pendingAcceptanceTasks.size === 0) {\n this.acceptanceTaskUnsubscribe?.();\n this.acceptanceTaskUnsubscribe = undefined;\n }\n }\n\n private attachAcceptanceTransitions<T>(\n result: TaskResult<T>,\n snapshotKey: string,\n snapshot: ProposalSnapshotEntry,\n reservation: AcceptanceReservation\n ): TaskResult<T> {\n this.assertActive('acceptance result projection');\n const localTaskId = result.metadata.taskId;\n this.transitionAcceptanceResult(result, snapshotKey, snapshot, reservation);\n if (result.submitted) {\n const submitted = result.submitted;\n (result as { submitted?: unknown }).submitted = {\n ...submitted,\n track: async (transport?: import('../protocols').TransportOptions) => {\n try {\n this.assertActive('acceptance track continuation');\n const task = await submitted.track(transport);\n this.assertActive('acceptance track continuation');\n this.transitionAcceptanceTask(task, snapshotKey, snapshot, reservation, localTaskId);\n return task;\n } catch (error) {\n if (!this.disposed) {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation, localTaskId);\n }\n throw error;\n }\n },\n waitForCompletion: async (pollInterval?: number, signal?: AbortSignal) => {\n try {\n this.assertActive('acceptance completion continuation');\n const completed = await submitted.waitForCompletion(pollInterval, signal);\n this.assertActive('acceptance completion continuation');\n this.transitionAcceptanceResult(completed, snapshotKey, snapshot, reservation);\n return completed;\n } catch (error) {\n if (!this.disposed) {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation, localTaskId);\n }\n throw error;\n }\n },\n };\n }\n if (result.deferred) {\n const deferred = result.deferred;\n (result as { deferred?: unknown }).deferred = {\n ...deferred,\n resume: async (input: unknown) => {\n try {\n this.assertActive('acceptance resume continuation');\n if (\n !this.ownsAcceptance(snapshotKey, snapshot, reservation) ||\n reservation.state !== 'retryable' ||\n reservation.retryKind !== 'paused'\n ) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_continuation_stale',\n 'This deferred acceptance continuation no longer owns the shared reservation. No continuation was sent.'\n );\n }\n const proposalId = String(snapshot.proposal.proposal_id);\n if (this.isProposalDeclinePending(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_decline_pending',\n 'The proposal has an unresolved decline in this principal scope. Wait for or reconcile that decline before resuming acceptance.'\n );\n }\n this.assertAcceptanceRetryWindow(snapshotKey, snapshot, reservation);\n if (reservation.taskId) this.forgetAcceptanceTask(reservation.taskId, reservation);\n const retryTimer = this.acceptanceRetryExpiryTimers.get(reservation);\n if (retryTimer) clearTimeout(retryTimer);\n this.acceptanceRetryExpiryTimers.delete(reservation);\n reservation.state = 'in-flight';\n delete reservation.retryKind;\n const resumed = await deferred.resume(input);\n this.assertActive('acceptance resume continuation');\n return this.attachAcceptanceTransitions(resumed, snapshotKey, snapshot, reservation);\n } catch (error) {\n if (!this.disposed) {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation, localTaskId);\n }\n throw error;\n }\n },\n };\n }\n return result;\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n for (const unsubscribe of [...this.proposalDispatchUnsubscribes]) unsubscribe();\n for (const decline of [...this.proposalSnapshotStore.pendingDeclines]) {\n if (decline.owner !== this.declineLeaseOwner) continue;\n this.preserveAmbiguousProposalMutation(decline, decline.attemptEpoch);\n }\n for (const refinement of [...this.proposalSnapshotStore.pendingRefinements]) {\n if (refinement.owner !== this.refinementLeaseOwner) continue;\n this.preserveAmbiguousProposalMutation(refinement, refinement.attemptEpoch);\n }\n for (const taskId of [...this.pendingProposalTasks.keys()]) this.forgetProposalTask(taskId);\n this.proposalTaskUnsubscribe?.();\n this.proposalTaskUnsubscribe = undefined;\n for (const [reservation, pending] of [...this.ownedAcceptanceReservations]) {\n if (reservation.state === 'in-flight') {\n this.preserveAmbiguousAcceptance(\n pending.snapshotKey,\n pending.snapshot,\n reservation,\n reservation.taskId,\n 'commit-uncertain'\n );\n }\n if (reservation.state === 'retryable' && reservation.retryKind === 'commit-uncertain') {\n if (reservation.taskId) this.forgetAcceptanceTask(reservation.taskId, reservation);\n continue;\n }\n this.retireAcceptance(pending.snapshotKey, pending.snapshot, reservation, 'terminal');\n this.releaseAcceptanceOwnership(reservation);\n }\n this.acceptanceTaskUnsubscribe?.();\n this.acceptanceTaskUnsubscribe = undefined;\n this.proposalSnapshotStore.activeCoordinators -= 1;\n }\n\n private rememberProposals(data: unknown, accountScope?: string): void {\n if (this.disposed || !this.principalScope) return;\n const seen = new WeakSet<object>();\n const stack = [data];\n let visited = 0;\n while (stack.length > 0) {\n const value = stack.pop();\n if (value === null || typeof value !== 'object' || seen.has(value)) continue;\n seen.add(value);\n visited += 1;\n if (visited > MAX_PROPOSAL_TRAVERSAL_NODES) {\n this.invalidateProposalSnapshots(this.cachedProposalIds(accountScope), accountScope);\n return;\n }\n if (Array.isArray(value)) {\n if (stack.length + value.length > MAX_PROPOSAL_TRAVERSAL_NODES) {\n this.invalidateProposalSnapshots(this.cachedProposalIds(accountScope), accountScope);\n return;\n }\n for (let index = value.length - 1; index >= 0; index -= 1) stack.push(value[index]);\n continue;\n }\n const candidate = value as Record<string, unknown>;\n const proposalId = optionalString(candidate.proposal_id);\n if (proposalId) {\n if (this.isProposalRefinementPending(proposalId)) continue;\n const key = this.snapshotKey(proposalId, accountScope);\n if (this.isTerminalProposal(proposalId) || this.isRetiredAcceptanceKey(key)) continue;\n if (this.proposalSnapshotStore.entries.get(key)?.acceptance) continue;\n // A newly observed seller representation supersedes the prior one.\n // Invalidate first so an unsafe, oversized, or unserializable\n // replacement cannot leave stale executable terms behind.\n this.removeProposalSnapshot(key);\n try {\n const safeSnapshot = safeProposalSnapshot(candidate);\n if (!safeSnapshot) continue;\n this.rememberSafeProposalSnapshot(safeSnapshot, accountScope);\n } catch {\n // Seller responses must be JSON. An unserializable proposal is not a\n // safe immutable acceptance snapshot, so leave it out of the cache.\n }\n }\n if (candidate.results !== undefined) stack.push(candidate.results);\n if (candidate.proposal !== undefined) stack.push(candidate.proposal);\n if (candidate.proposals !== undefined) stack.push(candidate.proposals);\n }\n }\n\n private rememberSafeProposalSnapshot(snapshot: SafeProposalSnapshot, accountScope?: string): void {\n if (this.disposed || !this.principalScope) return;\n const proposalId = optionalString(snapshot.proposal.proposal_id);\n if (!proposalId) return;\n if (this.isProposalRefinementPending(proposalId)) return;\n const key = this.snapshotKey(proposalId, accountScope);\n if (\n this.isTerminalProposal(proposalId) ||\n this.isRetiredAcceptanceKey(key) ||\n this.proposalSnapshotStore.entries.get(key)?.acceptance\n ) {\n return;\n }\n this.removeProposalSnapshot(key);\n const bytes = new TextEncoder().encode(`${key}${JSON.stringify(snapshot)}`).byteLength;\n if (bytes > MediaBuyLifecycleCoordinator.MAX_PROPOSAL_SNAPSHOT_BYTES) return;\n const retained = structuredClone(snapshot);\n this.retainProposalSnapshot(key, {\n proposal: retained.proposal,\n bytes,\n principalScope: this.principalScope,\n executable: true,\n ...(accountScope && { accountScope }),\n ...(retained.canonicalTermsDigest && { canonicalTermsDigest: retained.canonicalTermsDigest }),\n });\n this.enforceProposalSnapshotLimits();\n }\n\n private adaptProjectedResult<T, U>(\n result: TaskResult<T>,\n report: MediaBuyCompatibilityReport,\n project: (data: T) => U,\n accountScope?: string,\n retainProposals = false,\n pendingDecline?: PendingDeclineLease,\n pendingRefinement?: PendingRefinementLease,\n mutationAttemptEpoch?: number\n ): CompatibilityTaskResult<U, T> {\n const localTaskId = result.metadata.taskId;\n const mutationReservation = pendingDecline ?? pendingRefinement;\n const attemptEpoch = mutationAttemptEpoch ?? mutationReservation?.attemptEpoch;\n const mutationAttemptIsCurrent = (): boolean =>\n !mutationReservation ||\n (attemptEpoch !== undefined && this.mutationAttemptIsCurrent(mutationReservation, attemptEpoch));\n const adapt = (current: TaskResult<T>): CompatibilityTaskResult<U, T> => {\n this.assertActive('lifecycle result projection');\n const attemptWasCurrent = mutationAttemptIsCurrent();\n const currentTaskIsAuthoritative = report.tools_used.includes(current.metadata.taskName);\n const currentAuthoritativeFailure =\n currentTaskIsAuthoritative &&\n (current.status === 'failed' ||\n current.status === 'governance-denied' ||\n (current.status === 'completed' && !isAdcpOperationSuccess(current.data, current.metadata.taskName)));\n if (\n current.success &&\n current.status === 'completed' &&\n isAdcpOperationSuccess(current.data, current.metadata.taskName)\n ) {\n let projected: U;\n try {\n projected = project(current.data);\n } catch (error) {\n if (retainProposals && attemptWasCurrent) {\n // A malformed replacement is still authoritative evidence that\n // the seller re-used this proposal ID. Revoke any older executable\n // snapshot before surfacing the projection error.\n this.invalidateProposalSnapshots(this.proposalIdsIn(current.data), accountScope);\n }\n throw error;\n }\n if (retainProposals && attemptWasCurrent) this.rememberProposals(projected, accountScope);\n (current as TaskResult<unknown>).data = projected;\n } else if (\n retainProposals &&\n mutationAttemptIsCurrent() &&\n current.data !== undefined &&\n !(pendingRefinement && currentAuthoritativeFailure)\n ) {\n this.invalidateProposalSnapshots(this.proposalIdsIn(current.data), accountScope);\n }\n if (\n mutationAttemptIsCurrent() &&\n (retainProposals || pendingDecline || pendingRefinement) &&\n ['working', 'submitted'].includes(current.status)\n ) {\n this.watchProposalTask(\n localTaskId,\n accountScope,\n data => project(data as T),\n retainProposals,\n () => {\n if (attemptEpoch === undefined) return;\n if (pendingDecline && !this.disposed) this.pausePendingDecline(pendingDecline, attemptEpoch);\n if (pendingRefinement && !this.disposed) this.pausePendingRefinement(pendingRefinement, attemptEpoch);\n },\n () => {\n if (attemptEpoch === undefined) return;\n if (pendingDecline && !this.disposed) this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch);\n if (pendingRefinement && !this.disposed)\n this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n },\n () => {\n if (attemptEpoch === undefined) return;\n if (pendingDecline && !this.disposed) this.retirePendingDecline(pendingDecline, attemptEpoch);\n if (pendingRefinement && !this.disposed) this.restorePendingRefinement(pendingRefinement, attemptEpoch);\n },\n pendingRefinement !== undefined,\n new Set(report.tools_used)\n );\n } else if (mutationAttemptIsCurrent() && (retainProposals || pendingDecline || pendingRefinement)) {\n this.forgetProposalTask(localTaskId);\n }\n\n const output = current as unknown as TaskResult<U>;\n if (current.submitted) {\n const submitted = current.submitted;\n (output as { submitted?: unknown }).submitted = {\n ...submitted,\n track: async (transport?: import('../protocols').TransportOptions) => {\n try {\n this.assertActive('lifecycle track continuation');\n const task = await submitted.track(transport);\n this.assertActive('lifecycle track continuation');\n const completedSuccessfully =\n task.status === 'completed' &&\n task.result !== undefined &&\n report.tools_used.includes(task.taskType) &&\n isAdcpOperationSuccess(task.result, task.taskType);\n const authoritativeFailure =\n report.tools_used.includes(task.taskType) &&\n (task.status === 'failed' ||\n task.status === 'governance-denied' ||\n (task.status === 'completed' &&\n task.result !== undefined &&\n !isAdcpOperationSuccess(task.result, task.taskType)));\n if (completedSuccessfully) {\n const continuationWasCurrent = mutationAttemptIsCurrent();\n let projected: U;\n try {\n projected = project(task.result as T);\n } catch (error) {\n if (retainProposals && continuationWasCurrent) {\n this.invalidateProposalSnapshots(this.proposalIdsIn(task.result), accountScope);\n }\n throw error;\n }\n if (retainProposals && continuationWasCurrent) this.rememberProposals(projected, accountScope);\n task.result = projected;\n if (retainProposals && continuationWasCurrent) this.forgetProposalTask(localTaskId);\n } else if (\n retainProposals &&\n mutationAttemptIsCurrent() &&\n !(pendingRefinement && authoritativeFailure) &&\n !['pending', 'running', 'working', 'submitted'].includes(task.status)\n ) {\n if (task.result !== undefined) {\n this.invalidateProposalSnapshots(this.proposalIdsIn(task.result), accountScope);\n }\n if (mutationAttemptIsCurrent()) this.forgetProposalTask(localTaskId);\n }\n if (\n pendingDecline &&\n !['pending', 'running', 'working', 'submitted', 'input-required', 'auth-required', 'deferred'].includes(\n task.status\n )\n ) {\n if (attemptEpoch !== undefined) {\n if (completedSuccessfully) this.finishPendingDecline(pendingDecline, attemptEpoch);\n else this.retirePendingDecline(pendingDecline, attemptEpoch);\n }\n }\n if (\n pendingRefinement &&\n !completedSuccessfully &&\n !['pending', 'running', 'working', 'submitted', 'input-required', 'auth-required', 'deferred'].includes(\n task.status\n )\n ) {\n if (attemptEpoch !== undefined) {\n if (authoritativeFailure) this.restorePendingRefinement(pendingRefinement, attemptEpoch);\n else this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n }\n }\n if (task.status === 'input-required' || task.status === 'auth-required') {\n if (attemptEpoch !== undefined) {\n if (pendingDecline) this.pausePendingDecline(pendingDecline, attemptEpoch);\n if (pendingRefinement) this.pausePendingRefinement(pendingRefinement, attemptEpoch);\n }\n this.forgetProposalTask(localTaskId);\n }\n return task;\n } catch (error) {\n if (attemptEpoch !== undefined) {\n if (pendingDecline && !this.disposed)\n this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch);\n if (pendingRefinement && !this.disposed)\n this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n }\n throw error;\n }\n },\n waitForCompletion: async (pollInterval?: number, signal?: AbortSignal) => {\n try {\n this.assertActive('lifecycle completion continuation');\n return adapt(await submitted.waitForCompletion(pollInterval, signal));\n } catch (error) {\n if (attemptEpoch !== undefined) {\n if (pendingDecline && !this.disposed)\n this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch);\n if (pendingRefinement && !this.disposed)\n this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n }\n throw error;\n }\n },\n };\n }\n if (current.deferred) {\n const deferred = current.deferred;\n (output as { deferred?: unknown }).deferred = {\n ...deferred,\n resume: async (input: unknown) => {\n let resumedEpoch = attemptEpoch;\n try {\n this.assertActive('lifecycle resume continuation');\n if (mutationReservation) {\n if (\n attemptEpoch === undefined ||\n !this.mutationAttemptIsCurrent(mutationReservation, attemptEpoch) ||\n mutationReservation.state !== 'paused'\n ) {\n throw this.unsupported(\n pendingDecline ? 'declineProposals' : 'refineProposals',\n 'proposal_mutation_continuation_stale',\n 'This deferred proposal-mutation continuation no longer owns the shared reservation. No continuation was sent.'\n );\n }\n const operation = pendingDecline ? 'declineProposals' : 'refineProposals';\n const owner = pendingDecline ? this.declineLeaseOwner : this.refinementLeaseOwner;\n this.beginProposalMutationRetry(mutationReservation, owner, operation);\n resumedEpoch = mutationReservation.attemptEpoch;\n }\n const resumed = await deferred.resume(input);\n if (!mutationReservation) return adapt(resumed);\n return this.adaptProjectedResult(\n resumed,\n report,\n project,\n accountScope,\n retainProposals,\n pendingDecline,\n pendingRefinement,\n resumedEpoch\n );\n } catch (error) {\n if (resumedEpoch !== undefined) {\n if (pendingDecline && !this.disposed)\n this.preserveAmbiguousProposalMutation(pendingDecline, resumedEpoch);\n if (pendingRefinement && !this.disposed)\n this.preserveAmbiguousProposalMutation(pendingRefinement, resumedEpoch);\n }\n throw error;\n }\n },\n };\n }\n if (pendingDecline && current.status === 'completed') {\n if (attemptEpoch !== undefined) {\n if (isAdcpOperationSuccess(current.data, current.metadata.taskName))\n this.finishPendingDecline(pendingDecline, attemptEpoch);\n else this.retirePendingDecline(pendingDecline, attemptEpoch);\n }\n } else if (pendingDecline && (current.status === 'failed' || current.status === 'governance-denied')) {\n if (attemptEpoch !== undefined) this.retirePendingDecline(pendingDecline, attemptEpoch);\n }\n if (\n pendingRefinement &&\n ((current.status === 'completed' && !isAdcpOperationSuccess(current.data, current.metadata.taskName)) ||\n current.status === 'failed' ||\n current.status === 'governance-denied')\n ) {\n if (attemptEpoch !== undefined) {\n if (currentAuthoritativeFailure) this.restorePendingRefinement(pendingRefinement, attemptEpoch);\n else this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n }\n }\n if (current.status === 'input-required' || current.status === 'auth-required' || current.status === 'deferred') {\n if (attemptEpoch !== undefined) {\n if (pendingDecline) this.pausePendingDecline(pendingDecline, attemptEpoch);\n if (pendingRefinement) this.pausePendingRefinement(pendingRefinement, attemptEpoch);\n }\n }\n return Object.assign(output, { compatibility: report }) as unknown as CompatibilityTaskResult<U, T>;\n };\n return adapt(result);\n }\n\n async listProducts(\n params: ListProductsRequest,\n inputHandler?: InputHandler,\n options?: CanonicalProjectionTaskOptions\n ): Promise<CompatibilityTaskResult<CompatibleProductsResponse, CompatibleProductsWireResponse>> {\n this.assertActive('listProducts');\n const input = record(params);\n const lifecycle = this.selectLifecycle('list_products');\n this.assertLegacyReferenceShapes('listProducts', input);\n if (lifecycle === 'compact') {\n this.assertValidCompactRequest('list_products', params, lifecycle);\n const result = await this.agent.listProducts(params, inputHandler, options);\n return this.adaptProjectedResult(result, this.makeReport(lifecycle, ['list_products'], []), data =>\n projectProducts(data, lifecycle)\n );\n }\n\n this.assertOnlyFields('listProducts', input, LIST_PRODUCTS_FIELDS);\n if (\n compareRelease(this.negotiated_version, '3.0') < 0 &&\n ['cursor', 'max_results', 'fields'].some(field => Object.hasOwn(input, field))\n ) {\n throw this.unsupported(\n 'listProducts',\n 'cursor,max_results,fields',\n `The negotiated ${this.negotiated_version} get_products request has no pagination or response-field selection. No request was sent.`\n );\n }\n if (\n compareRelease(this.negotiated_version, '3.1') < 0 &&\n ['if_feed_version', 'if_pricing_version'].some(field => Object.hasOwn(input, field))\n ) {\n throw this.unsupported(\n 'listProducts',\n 'if_feed_version,if_pricing_version',\n `The negotiated ${this.negotiated_version} get_products request cannot condition on feed or pricing versions. No request was sent.`\n );\n }\n this.assertLegacyProductFields('listProducts', input.fields);\n if (input.criteria !== undefined || input.governance_context !== undefined || input.context_id !== undefined) {\n throw this.unsupported(\n 'listProducts',\n 'criteria/governance_context/context_id',\n 'Compact list_products criteria, governance context, and explicit context IDs have no general lossless established mapping.'\n );\n }\n if (input.push_notification_config !== undefined && compareRelease(this.negotiated_version, '3.1') < 0) {\n throw this.unsupported(\n 'listProducts',\n 'push_notification_config',\n `The negotiated ${this.negotiated_version} get_products request cannot carry push_notification_config.`\n );\n }\n const request: CanonicalGetProductsRequest = {\n buying_mode: 'wholesale',\n ...(input.idempotency_key !== undefined && { idempotency_key: input.idempotency_key as string }),\n ...(input.account !== undefined && { account: input.account as CanonicalGetProductsRequest['account'] }),\n ...(input.brand !== undefined && { brand: input.brand as CanonicalGetProductsRequest['brand'] }),\n ...(Array.isArray(input.fields) && { fields: input.fields as CanonicalGetProductsRequest['fields'] }),\n ...(compareRelease(this.negotiated_version, '3.0') >= 0 &&\n (input.cursor !== undefined || input.max_results !== undefined) && {\n pagination: {\n ...(input.cursor !== undefined && { cursor: input.cursor }),\n ...(input.max_results !== undefined && { max_results: input.max_results }),\n } as CanonicalGetProductsRequest['pagination'],\n }),\n ...(input.if_feed_version !== undefined && { if_wholesale_feed_version: input.if_feed_version as string }),\n ...(input.if_pricing_version !== undefined && { if_pricing_version: input.if_pricing_version as string }),\n ...(input.context !== undefined && { context: input.context as CanonicalGetProductsRequest['context'] }),\n ...(input.push_notification_config !== undefined && {\n push_notification_config:\n input.push_notification_config as CanonicalGetProductsRequest['push_notification_config'],\n }),\n };\n this.assertValidCompactRequest('list_products', params, lifecycle);\n const result = await this.agent.getProducts(request, inputHandler, options);\n return this.adaptProjectedResult(result, this.makeReport(lifecycle, ['get_products'], []), data =>\n projectProducts(data, lifecycle)\n );\n }\n\n async requestProposals(\n params: MutatingRequestInput<RequestProposalsRequest>,\n inputHandler?: InputHandler,\n options?: CanonicalProjectionTaskOptions\n ): Promise<CompatibilityTaskResult<CompatibleRequestProposalsResponse, CompatibleRequestProposalsWireResponse>> {\n this.assertActive('requestProposals');\n const input = record(params);\n const lifecycle = this.selectLifecycle('request_proposals');\n this.assertLegacyReferenceShapes('requestProposals', input);\n if (lifecycle === 'compact') {\n this.assertValidCompactRequest('request_proposals', params, lifecycle, true);\n const accountScope = this.accountScope(input.account);\n return this.captureProposalDispatch(\n accountScope,\n () => this.agent.requestProposals(params, inputHandler, options),\n result =>\n this.adaptProjectedResult(\n result,\n this.makeReport(lifecycle, ['request_proposals'], []),\n data => projectRequestProposals(data, lifecycle, this.negotiated_version),\n accountScope,\n true\n ),\n data => projectRequestProposals(data, lifecycle, this.negotiated_version)\n );\n }\n\n this.assertOnlyFields('requestProposals', input, REQUEST_PROPOSALS_FIELDS);\n const criteria = record(input.criteria);\n this.assertOnlyFields(\n 'requestProposals.criteria',\n criteria,\n new Set([\n 'product_ids',\n 'offer_filters',\n 'targeting_overlay',\n 'required_overlay_support',\n 'catalog',\n 'policy_ids',\n 'ext',\n ])\n );\n this.assertCompactWireFieldsAbsent('requestProposals.criteria', criteria, [\n 'targeting_overlay',\n 'required_overlay_support',\n ]);\n if (!optionalString(input.brief)) {\n throw this.unsupported('requestProposals', 'brief', 'Proposal requests require a non-empty brief.');\n }\n const accountScope = this.accountScope(input.account);\n if (\n criteria.ext !== undefined ||\n input.opportunity !== undefined ||\n input.governance_context !== undefined ||\n input.context_id !== undefined\n ) {\n throw this.unsupported(\n 'requestProposals',\n 'structured proposal context',\n 'The established proposal request cannot losslessly carry compact ext, opportunity, or governance context.'\n );\n }\n if (input.push_notification_config !== undefined && compareRelease(this.negotiated_version, '3.1') < 0) {\n throw this.unsupported(\n 'requestProposals',\n 'push_notification_config',\n `The negotiated ${this.negotiated_version} get_products request cannot carry push_notification_config.`\n );\n }\n const offerFilters = record(criteria.offer_filters);\n this.assertLegacyOfferFilterShapes('requestProposals', offerFilters);\n this.assertLegacyMetrics(\n 'requestProposals',\n offerFilters.required_metrics,\n 'criteria.offer_filters.required_metrics'\n );\n if (criteria.product_ids !== undefined) {\n throw this.unsupported(\n 'requestProposals',\n 'criteria.product_ids',\n 'Established get_products has no normative product-ID proposal filter.'\n );\n }\n if (criteria.catalog !== undefined) {\n throw this.unsupported(\n 'requestProposals',\n 'criteria.catalog',\n 'Compact catalog selection omits the full legacy catalog metadata required by get_products. No request was sent.'\n );\n }\n const legacyOfferFilterFields =\n compareRelease(this.negotiated_version, '3.1') >= 0\n ? V31_OFFER_FILTER_FIELDS\n : compareRelease(this.negotiated_version, '3.0') >= 0\n ? V30_OFFER_FILTER_FIELDS\n : V25_OFFER_FILTER_FIELDS;\n this.assertOnlyFields('requestProposals.criteria.offer_filters', offerFilters, legacyOfferFilterFields);\n const filters = Object.fromEntries(\n Object.entries(offerFilters).filter(([key]) => legacyOfferFilterFields.has(key))\n );\n const request: CanonicalGetProductsRequest = {\n buying_mode: 'brief',\n brief: input.brief as string,\n ...(optionalString(input.idempotency_key)\n ? { idempotency_key: optionalString(input.idempotency_key) }\n : !options?.skipIdempotencyAutoInject\n ? { idempotency_key: generateIdempotencyKey() }\n : {}),\n ...(input.account !== undefined && { account: input.account as CanonicalGetProductsRequest['account'] }),\n ...(input.brand !== undefined && { brand: input.brand as CanonicalGetProductsRequest['brand'] }),\n ...(Object.keys(filters).length > 0 && {\n filters: filters as CanonicalGetProductsRequest['filters'],\n }),\n ...(criteria.targeting_overlay !== undefined && {\n targeting_overlay: criteria.targeting_overlay as CanonicalGetProductsRequest['targeting_overlay'],\n }),\n ...(criteria.required_overlay_support !== undefined && {\n required_overlay_support:\n criteria.required_overlay_support as CanonicalGetProductsRequest['required_overlay_support'],\n }),\n ...(criteria.catalog !== undefined && { catalog: criteria.catalog as CanonicalGetProductsRequest['catalog'] }),\n ...(Array.isArray(criteria.policy_ids) && { required_policies: criteria.policy_ids as string[] }),\n ...(input.push_notification_config !== undefined && {\n push_notification_config:\n input.push_notification_config as CanonicalGetProductsRequest['push_notification_config'],\n }),\n ...(input.context !== undefined && { context: input.context as CanonicalGetProductsRequest['context'] }),\n };\n this.assertValidCompactRequest('request_proposals', params, lifecycle, true);\n return this.captureProposalDispatch(\n accountScope,\n () => this.agent.getProducts(request, inputHandler, options),\n async result => {\n const prepared = await this.prepareLegacyProposalResult(result, accountScope, requestFingerprint(request));\n return this.adaptProjectedResult(\n prepared,\n this.makeReport(lifecycle, ['get_products'], []),\n data => projectRequestProposals(data, lifecycle),\n accountScope,\n true\n );\n },\n data => projectRequestProposals(data, lifecycle)\n );\n }\n\n /**\n * Redeem a beta.4 `legacy_create` continuation. This is an SDK-local\n * coordinator operation; the input object itself is never sent on the wire.\n */\n async continueLegacyPurchase(\n input: CompatibilityPurchaseCoordinatorInput,\n inputHandler?: InputHandler,\n options?: TaskOptions\n ): Promise<TaskResult<CreateMediaBuyResponse>> {\n this.assertActive('continueLegacyPurchase');\n if (!this.principalScope) {\n throw new LegacyPurchaseContinuationError(\n 'binding_mismatch',\n 'Legacy purchase continuation redemption requires a stable principalScope.'\n );\n }\n const value = record(input);\n const allowedInputFields = new Set([\n 'idempotency_key',\n 'continuation_token',\n 'account',\n 'selected_product_ids',\n 'accepted_losses',\n 'legacy_create_request',\n ]);\n if (Object.keys(value).some(key => !allowedInputFields.has(key))) {\n throw new LegacyPurchaseContinuationError(\n 'request_invalid',\n 'Legacy purchase continuation input contains an unknown field.'\n );\n }\n const idempotencyKey = optionalString(value.idempotency_key);\n const token = optionalString(value.continuation_token);\n if (\n !idempotencyKey ||\n !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(idempotencyKey)\n ) {\n throw new LegacyPurchaseContinuationError('request_invalid', 'idempotency_key must be a UUID.');\n }\n if (!token || token.length < 16) {\n throw new LegacyPurchaseContinuationError(\n 'request_invalid',\n 'continuation_token must contain at least 16 characters.'\n );\n }\n const selectedProductIds = array(value.selected_product_ids);\n if (\n selectedProductIds.length === 0 ||\n selectedProductIds.some(productId => !optionalString(productId)) ||\n new Set(selectedProductIds).size !== selectedProductIds.length\n ) {\n throw new LegacyPurchaseContinuationError(\n 'selection_mismatch',\n 'selected_product_ids must be a non-empty set of distinct product IDs.'\n );\n }\n const acceptedLosses = array(value.accepted_losses);\n if (\n acceptedLosses.some(\n loss =>\n !['feed_version_not_atomic', 'pricing_version_not_atomic', 'mutation_idempotency_not_guaranteed'].includes(\n String(loss)\n )\n ) ||\n new Set(acceptedLosses).size !== acceptedLosses.length\n ) {\n throw new LegacyPurchaseContinuationError(\n 'loss_mismatch',\n 'accepted_losses contains an unknown or duplicate loss.'\n );\n }\n let continuation: LegacyPurchaseContinuationRecord | undefined;\n try {\n continuation = await this.legacyPurchaseContinuationStore.get(token);\n } catch (error) {\n throw new LegacyPurchaseContinuationError(\n 'store_error',\n 'Could not load the legacy purchase continuation.',\n true,\n undefined,\n error\n );\n }\n if (!continuation)\n throw new LegacyPurchaseContinuationError('not_found', 'Legacy purchase continuation not found.');\n const accountScope = this.accountScope(value.account);\n if (!accountScope) {\n throw new LegacyPurchaseContinuationError(\n 'binding_mismatch',\n 'Legacy purchase continuation redemption requires an explicit account.'\n );\n }\n const expectedBinding = this.legacyPurchaseBinding(accountScope);\n const stableBindingMatches =\n continuation.principalScope === expectedBinding.principalScope &&\n continuation.accountScope === expectedBinding.accountScope &&\n continuation.sellerScope === expectedBinding.sellerScope &&\n continuation.clientSessionScope === expectedBinding.clientSessionScope &&\n continuation.sourceAdcpVersion === expectedBinding.sourceAdcpVersion;\n const discoveryBindingMatches =\n continuation.operation.state !== 'available' ||\n continuation.discoveryContextId === expectedBinding.discoveryContextId;\n if (!stableBindingMatches || !discoveryBindingMatches) {\n throw new LegacyPurchaseContinuationError(\n 'binding_mismatch',\n 'Legacy purchase continuation does not belong to this principal, account, seller, or authenticated session.'\n );\n }\n const exactSet = (left: readonly unknown[], right: readonly unknown[]): boolean =>\n left.length === right.length && left.every(item => right.includes(item));\n if (!exactSet(acceptedLosses, continuation.losses)) {\n throw new LegacyPurchaseContinuationError(\n 'loss_mismatch',\n 'accepted_losses must exactly match the loss set returned with the continuation.'\n );\n }\n if (!selectedProductIds.every(productId => continuation!.productIds.includes(String(productId)))) {\n throw new LegacyPurchaseContinuationError(\n 'selection_mismatch',\n 'selected_product_ids contains a product not bound to this continuation.'\n );\n }\n const legacyRequest = record(value.legacy_create_request);\n if (Object.hasOwn(legacyRequest, 'proposal_id')) {\n throw new LegacyPurchaseContinuationError(\n 'request_invalid',\n 'legacy_create_request must use explicit packages and must not execute a proposal.'\n );\n }\n const packages = array(legacyRequest.packages);\n const packageProductIds = packages.map(pkg => optionalString(record(pkg).product_id));\n const distinctPackageProductIds = [...new Set(packageProductIds)];\n if (\n packages.length === 0 ||\n packageProductIds.some(productId => productId === undefined) ||\n !exactSet(distinctPackageProductIds, selectedProductIds)\n ) {\n throw new LegacyPurchaseContinuationError(\n 'selection_mismatch',\n 'The legacy_create_request package product ID set must exactly match selected_product_ids.'\n );\n }\n const observedPricingOptions = new Map<string, Set<string>>();\n for (const product of array(record(continuation.observedResponse).products)) {\n const productRecord = record(product);\n const productId = optionalString(productRecord.product_id);\n if (!productId) continue;\n observedPricingOptions.set(\n productId,\n new Set(\n array(productRecord.pricing_options)\n .map(option => optionalString(record(option).pricing_option_id))\n .filter((pricingOptionId): pricingOptionId is string => pricingOptionId !== undefined)\n )\n );\n }\n if (\n packages.some(pkg => {\n const packageRecord = record(pkg);\n const productId = optionalString(packageRecord.product_id);\n const pricingOptionId = optionalString(packageRecord.pricing_option_id);\n return !productId || !pricingOptionId || !observedPricingOptions.get(productId)?.has(pricingOptionId);\n })\n ) {\n throw new LegacyPurchaseContinuationError(\n 'selection_mismatch',\n 'Every legacy_create_request package pricing_option_id must match an option observed for its selected product.'\n );\n }\n if (continuation.sourceAdcpVersion !== '2.5' && this.accountScope(legacyRequest.account) !== accountScope) {\n throw new LegacyPurchaseContinuationError(\n 'binding_mismatch',\n 'legacy_create_request.account must match the continuation account.'\n );\n }\n const validation = validateRequest(\n 'create_media_buy',\n legacyRequest,\n continuation.sourceAdcpVersion === '2.5' ? 'v2.5' : continuation.sourceAdcpVersion\n );\n if (!validation.valid) {\n throw new LegacyPurchaseContinuationError(\n 'request_invalid',\n `legacy_create_request is invalid for AdCP ${continuation.sourceAdcpVersion}: ${formatIssues(validation.issues)}`\n );\n }\n let claim: LegacyPurchaseClaim = {\n idempotencyKey,\n inputFingerprint: requestFingerprint(input),\n operationKey: requestFingerprint({\n operation: 'continueLegacyPurchase',\n principalScope: expectedBinding.principalScope,\n accountScope: expectedBinding.accountScope,\n sellerScope: expectedBinding.sellerScope,\n clientSessionScope: expectedBinding.clientSessionScope,\n idempotencyKey,\n }),\n claimedAt: new Date().toISOString(),\n replayExpiresAt: new Date(Date.now() + this.legacyPurchaseOperationTtlMs).toISOString(),\n selectedProductIds: selectedProductIds.map(String),\n ...(optionalString(legacyRequest.idempotency_key ?? legacyRequest.buyer_ref) !== undefined && {\n sourceMutationKey: optionalString(legacyRequest.idempotency_key ?? legacyRequest.buyer_ref),\n }),\n };\n let claimedForDispatch = false;\n const claimBeforeDispatch = async (\n effectiveParams: unknown,\n context: BeforeProtocolDispatchContext\n ): Promise<BeforeProtocolDispatchHookResult<CreateMediaBuyResponse>> => {\n // Legacy continuation consent binds the complete pre-governance purchase.\n // Unlike native 3.2 proposal execution, it has no mechanism for the\n // caller to approve rewritten commercial terms, so fail closed before\n // claiming whenever governance changed the seller payload.\n if (context.governanceAdjusted) {\n throw new LegacyPurchaseContinuationError(\n 'request_invalid',\n 'Governance conditions cannot rewrite a legacy purchase continuation request.'\n );\n }\n const finalRequest = record(effectiveParams);\n const finalPackages = array(finalRequest.packages);\n const finalProductIds = finalPackages.map(pkg => optionalString(record(pkg).product_id));\n const distinctFinalProductIds = [...new Set(finalProductIds)];\n if (\n finalPackages.length === 0 ||\n finalProductIds.some(productId => productId === undefined) ||\n !exactSet(distinctFinalProductIds, selectedProductIds)\n ) {\n throw new LegacyPurchaseContinuationError(\n 'selection_mismatch',\n 'The final seller payload product IDs must exactly match the continuation selection.'\n );\n }\n if (\n finalPackages.some(pkg => {\n const packageRecord = record(pkg);\n const productId = optionalString(packageRecord.product_id);\n const pricingOptionId = optionalString(packageRecord.pricing_option_id);\n return !productId || !pricingOptionId || !observedPricingOptions.get(productId)?.has(pricingOptionId);\n })\n ) {\n throw new LegacyPurchaseContinuationError(\n 'selection_mismatch',\n 'The final seller payload pricing options must match the observed product snapshot.'\n );\n }\n if (continuation.sourceAdcpVersion !== '2.5' && this.accountScope(finalRequest.account) !== accountScope) {\n throw new LegacyPurchaseContinuationError(\n 'binding_mismatch',\n 'The final seller payload account must match the continuation account.'\n );\n }\n const finalMutationKey = optionalString(finalRequest.idempotency_key ?? finalRequest.buyer_ref);\n if (claim.sourceMutationKey !== undefined && finalMutationKey !== claim.sourceMutationKey) {\n throw new LegacyPurchaseContinuationError(\n 'binding_mismatch',\n 'The final seller payload mutation key must match the continuation request.'\n );\n }\n\n // Capture the mutation/replay clock at the durable CAS boundary, after\n // all awaited preflight and governance work. Earlier timestamps can\n // make a slow claim look abandoned or shorten its replay window before\n // the seller has even been dispatched.\n claim = {\n ...claim,\n claimedAt: new Date().toISOString(),\n replayExpiresAt: new Date(Date.now() + this.legacyPurchaseOperationTtlMs).toISOString(),\n };\n let claimed;\n try {\n claimed = await this.legacyPurchaseContinuationStore.claim(token, {\n claim,\n expected: expectedBinding,\n });\n } catch (error) {\n throw new LegacyPurchaseContinuationError(\n 'store_error',\n 'Could not atomically claim the legacy purchase continuation.',\n true,\n undefined,\n error\n );\n }\n if (claimed.outcome === 'missing') {\n throw new LegacyPurchaseContinuationError('not_found', 'Legacy purchase continuation not found.');\n }\n if (claimed.outcome === 'conflict') {\n throw new LegacyPurchaseContinuationError(\n 'conflict',\n 'Legacy purchase continuation was already claimed by a different coordinator operation.'\n );\n }\n if (claimed.outcome === 'expired') {\n throw new LegacyPurchaseContinuationError(\n 'expired',\n 'The legacy purchase continuation or its deterministic replay window has expired.'\n );\n }\n if (claimed.outcome === 'binding_mismatch') {\n throw new LegacyPurchaseContinuationError(\n 'binding_mismatch',\n 'Legacy purchase continuation does not belong to this principal, account, seller session, and source version.'\n );\n }\n if (claimed.outcome === 'replay') return { action: 'return', result: attachMatch(claimed.result) };\n if (claimed.outcome === 'in_flight' || claimed.outcome === 'ambiguous') {\n const age =\n Date.now() -\n Date.parse(\n claimed.record.operation.state === 'available' ? claim.claimedAt : claimed.record.operation.claimedAt\n );\n if (claimed.outcome === 'in_flight' && age < this.legacyPurchaseClaimTimeoutMs) {\n throw new LegacyPurchaseContinuationError(\n 'in_flight',\n 'The exact legacy purchase continuation operation is still in flight.',\n true\n );\n }\n if (this.reconcileLegacyPurchase) {\n let reconciled;\n try {\n reconciled = await this.reconcileLegacyPurchase(claimed.record, input);\n } catch (error) {\n throw this.legacyPurchaseAmbiguousError('Legacy create reconciliation failed without authority.', error);\n }\n if (reconciled.outcome === 'completed') {\n const terminal = this.assertLegacyPurchaseTerminalResult(reconciled.result, continuation.sourceAdcpVersion);\n return {\n action: 'return',\n result: attachMatch(await this.completeLegacyPurchase(token, claim, terminal)),\n };\n }\n }\n throw new LegacyPurchaseContinuationError(\n 'ambiguous',\n 'The legacy create outcome is not authoritative; reconcile it before any further mutation.',\n false,\n 'Configure reconcileLegacyPurchase to query the seller by an application-owned natural key.'\n );\n }\n claimedForDispatch = true;\n return {\n action: 'dispatch_committed',\n onResult: async result => {\n const settled = await this.trackLegacyPurchaseResult(\n token,\n claim,\n result,\n context.publishSettledTaskStatus,\n context.registerExternalTaskSettlement,\n options?.transport\n );\n settledInsideExecutor = true;\n return settled;\n },\n onError: async error => {\n settledInsideExecutor = true;\n if (error instanceof LegacyPurchaseContinuationError) {\n if (error.code === 'ambiguous') {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'create_media_buy_result_invalid');\n }\n throw error;\n }\n await this.markLegacyPurchaseAmbiguous(token, claim, 'create_media_buy_transport_uncertain');\n throw this.legacyPurchaseAmbiguousError(\n 'The legacy create transport failed after the token was claimed.',\n error\n );\n },\n };\n };\n\n let settledInsideExecutor = false;\n try {\n const result = await this.agent.createMediaBuyLegacyWithPreDispatch(\n legacyRequest as unknown as CreateMediaBuyRequest,\n claimBeforeDispatch,\n inputHandler,\n {\n ...options,\n skipAccountValidation: true,\n skipIdempotencyAutoInject: true,\n }\n );\n if (!claimedForDispatch) return result;\n if (settledInsideExecutor) return result;\n // Test doubles and older internal façades may invoke the pre-dispatch\n // hook without honoring its executor-owned settlement callbacks.\n return this.trackLegacyPurchaseResult(token, claim, result, undefined, undefined, options?.transport);\n } catch (error) {\n if (!claimedForDispatch) throw error;\n if (settledInsideExecutor) throw error;\n if (error instanceof LegacyPurchaseContinuationError) {\n if (error.code === 'ambiguous') {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'create_media_buy_result_invalid');\n }\n throw error;\n }\n await this.markLegacyPurchaseAmbiguous(token, claim, 'create_media_buy_transport_uncertain');\n throw this.legacyPurchaseAmbiguousError('The legacy create transport failed after the token was claimed.', error);\n }\n }\n\n private async completeLegacyPurchase(\n token: string,\n claim: LegacyPurchaseClaim,\n result: LegacyPurchaseTerminalResult\n ): Promise<LegacyPurchaseTerminalResult> {\n try {\n const completed = await this.legacyPurchaseContinuationStore.complete(token, claim, result);\n if (completed.outcome === 'completed') return completed.result;\n } catch (error) {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'completion_persistence_failed');\n throw new LegacyPurchaseContinuationError(\n 'store_error',\n 'Could not persist the legacy create result; the outcome is ambiguous.',\n false,\n 'Reconcile the seller mutation by its application-owned natural key.',\n error\n );\n }\n await this.markLegacyPurchaseAmbiguous(token, claim, 'completion_compare_and_set_failed');\n throw new LegacyPurchaseContinuationError(\n 'store_error',\n 'Could not atomically persist the legacy create result; the outcome is ambiguous.',\n false,\n 'Reconcile the seller mutation by its application-owned natural key.'\n );\n }\n\n private legacyPurchaseAmbiguousError(message: string, cause?: unknown): LegacyPurchaseContinuationError {\n return new LegacyPurchaseContinuationError(\n 'ambiguous',\n message,\n false,\n 'Configure reconcileLegacyPurchase to query the seller by the durable sourceMutationKey or sellerTaskId.',\n cause\n );\n }\n\n private assertLegacyPurchaseTerminalResult(\n candidate: unknown,\n sourceVersion: LegacyPurchaseSourceVersion\n ): LegacyPurchaseTerminalResult {\n const result = record(candidate) as Partial<TaskResult<CreateMediaBuyResponse>>;\n const metadata = record(result.metadata);\n if (metadata.taskName !== 'create_media_buy') {\n throw this.legacyPurchaseAmbiguousError('The legacy create terminal result has the wrong task identity.');\n }\n if (result.status === 'completed' && result.success === true) {\n if (result.data === undefined) {\n throw this.legacyPurchaseAmbiguousError('The seller reported completion without a create_media_buy result.');\n }\n const validation = validateResponse(\n 'create_media_buy',\n result.data,\n sourceVersion === '2.5' ? 'v2.5' : sourceVersion\n );\n if (!validation.valid) {\n throw this.legacyPurchaseAmbiguousError(\n `The seller returned an invalid terminal create_media_buy result: ${formatIssues(validation.issues)}`\n );\n }\n } else if (\n (result.status !== 'failed' && result.status !== 'governance-denied') ||\n result.success !== false ||\n typeof result.error !== 'string'\n ) {\n throw this.legacyPurchaseAmbiguousError('The legacy create result is not a valid terminal TaskResult.');\n }\n\n // Functions and typed Error prototypes are not portable durable-store\n // values. Structured AdCP error data remains available for replay.\n const {\n match: _match,\n errorInstance: _errorInstance,\n conversation: _conversation,\n debug_logs: _debugLogs,\n ...serializable\n } = result as TaskResult<CreateMediaBuyResponse>;\n void _match;\n void _errorInstance;\n void _conversation;\n void _debugLogs;\n if (containsCredentialShapedKey(serializable) || containsPresignedUrl(serializable)) {\n throw this.legacyPurchaseAmbiguousError(\n 'The legacy create terminal result contains credential-shaped material and cannot be persisted.'\n );\n }\n if (Buffer.byteLength(canonicalize(serializable), 'utf8') > 256 * 1024) {\n throw this.legacyPurchaseAmbiguousError(\n 'The legacy create terminal result exceeds the 256 KiB durable replay limit.'\n );\n }\n return serializable as LegacyPurchaseTerminalResult;\n }\n\n private async markLegacyPurchaseAmbiguous(token: string, claim: LegacyPurchaseClaim, reason: string): Promise<void> {\n try {\n await this.legacyPurchaseContinuationStore.markAmbiguous(token, claim, reason);\n } catch {\n // The original mutation/storage error remains more actionable. Stores\n // must make claim records durable before returning from claim().\n }\n }\n\n private async trackLegacyPurchaseResult(\n token: string,\n claim: LegacyPurchaseClaim,\n result: TaskResult<CreateMediaBuyResponse>,\n publishSettledTaskStatus?: BeforeProtocolDispatchContext['publishSettledTaskStatus'],\n registerExternalTaskSettlement?: BeforeProtocolDispatchContext['registerExternalTaskSettlement'],\n settlementTransport?: TaskOptions['transport']\n ): Promise<TaskResult<CreateMediaBuyResponse>> {\n if (result.status === 'completed' || result.status === 'failed' || result.status === 'governance-denied') {\n // TaskExecutor also uses status=failed for local response-schema and\n // unknown-envelope failures. Those do not prove that the seller\n // authoritatively rejected the mutation: it may have succeeded and\n // returned a malformed completion. Persist only structured AdCP\n // failures; otherwise fence the claimed operation as ambiguous.\n if (result.status === 'failed' && (result.adcpError === undefined || result.adcpError.synthetic === true)) {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'create_media_buy_failure_not_authoritative');\n throw this.legacyPurchaseAmbiguousError(\n 'The legacy create failure was not an authoritative structured AdCP error.'\n );\n }\n let terminal: LegacyPurchaseTerminalResult;\n try {\n terminal = this.assertLegacyPurchaseTerminalResult(result, this.legacyPurchaseSourceVersion());\n } catch (error) {\n if (error instanceof LegacyPurchaseContinuationError && error.code === 'ambiguous') {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'create_media_buy_result_invalid');\n }\n throw error;\n }\n return attachMatch(await this.completeLegacyPurchase(token, claim, terminal));\n }\n\n const settlementMetadata = {\n taskId: result.metadata.taskId,\n taskName: result.metadata.taskName,\n agent: { ...result.metadata.agent },\n responseTimeMs: result.metadata.responseTimeMs,\n timestamp: result.metadata.timestamp,\n clarificationRounds: result.metadata.clarificationRounds,\n status: result.metadata.status,\n ...(result.metadata.contextId !== undefined && { contextId: result.metadata.contextId }),\n ...((result.submitted?.taskId ?? result.metadata.serverTaskId ?? claim.sellerTaskId) !== undefined && {\n serverTaskId: result.submitted?.taskId ?? result.metadata.serverTaskId ?? claim.sellerTaskId,\n }),\n ...(result.metadata.idempotency_key !== undefined && { idempotency_key: result.metadata.idempotency_key }),\n ...(result.metadata.replayed !== undefined && { replayed: result.metadata.replayed }),\n ...(result.metadata.adcpVersion !== undefined && { adcpVersion: result.metadata.adcpVersion }),\n };\n const failureFieldsFromTask = (task: TaskInfo) => {\n const extracted = extractAdcpErrorInfo(task.result);\n const adcpError = extracted?.synthetic === true ? undefined : extracted;\n const correlationId = extractCorrelationId(task.result);\n return {\n // tasks/get and webhook free text are not durable-safe boundaries.\n // Preserve a structured AdCP message when present; otherwise replay a\n // generic error while retaining the seller payload for inspection.\n error: adcpError?.message ?? 'Legacy create failed.',\n ...(adcpError !== undefined && { adcpError }),\n ...(correlationId !== undefined && { correlationId }),\n };\n };\n const resultFromTask = (task: TaskInfo): TaskResult<CreateMediaBuyResponse> | undefined => {\n const metadata = {\n ...settlementMetadata,\n taskName: task.taskType,\n timestamp: new Date().toISOString(),\n };\n if (\n task.status === 'completed' &&\n task.result !== undefined &&\n isAdcpOperationSuccess(task.result, task.taskType)\n ) {\n return attachMatch({\n success: true,\n status: 'completed',\n data: task.result as CreateMediaBuyResponse,\n metadata: { ...metadata, status: 'completed' },\n });\n }\n if (task.status === 'unknown') {\n throw this.legacyPurchaseAmbiguousError(\n 'tasks/get returned an unrecognizable response for the submitted legacy purchase.'\n );\n }\n if (['completed', 'failed', 'rejected', 'canceled', 'governance-denied'].includes(task.status)) {\n const status = task.status === 'governance-denied' ? 'governance-denied' : 'failed';\n return attachMatch({\n success: false,\n status,\n ...failureFieldsFromTask(task),\n ...(task.result !== undefined && { data: task.result as CreateMediaBuyResponse }),\n metadata: { ...metadata, status },\n } as TaskResult<CreateMediaBuyResponse>);\n }\n if (task.status === 'input-required' || task.status === 'auth-required') {\n return attachMatch({\n success: true,\n status: task.status,\n ...(task.result !== undefined && { data: task.result as CreateMediaBuyResponse }),\n metadata: { ...metadata, status: task.status },\n } as TaskResult<CreateMediaBuyResponse>);\n }\n return undefined;\n };\n const bindSellerTask = async (sellerTaskId: string) => {\n try {\n const recorded = await this.legacyPurchaseContinuationStore.recordSubmittedTask(token, claim, sellerTaskId);\n if (!recorded) {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'submitted_task_persistence_failed');\n throw this.legacyPurchaseAmbiguousError('Could not durably bind the submitted seller task.');\n }\n } catch (error) {\n if (error instanceof LegacyPurchaseContinuationError) throw error;\n await this.markLegacyPurchaseAmbiguous(token, claim, 'submitted_task_persistence_failed');\n throw this.legacyPurchaseAmbiguousError('Could not durably bind the submitted seller task.', error);\n }\n\n // Register only after the seller task binding is durable. A webhook may\n // already be queued in TaskExecutor, but it must never complete the\n // operation before recordSubmittedTask commits the exact task identity.\n registerExternalTaskSettlement?.(async observation => {\n try {\n if (observation.serverTaskId !== sellerTaskId) {\n throw this.legacyPurchaseAmbiguousError(\n 'The pushed seller task ID does not match the durably recorded submitted task.'\n );\n }\n if (observation.taskType !== 'create_media_buy') {\n throw this.legacyPurchaseAmbiguousError('The pushed seller task has the wrong task identity.');\n }\n const task: TaskInfo = {\n taskId: sellerTaskId,\n taskType: observation.taskType,\n status: observation.status,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n ...(observation.result !== undefined && { result: observation.result }),\n };\n const observed = resultFromTask(task);\n if (!observed || !['completed', 'failed', 'governance-denied'].includes(observed.status)) {\n throw this.legacyPurchaseAmbiguousError(\n 'The pushed legacy create status was not an authoritative terminal result.'\n );\n }\n return await this.trackLegacyPurchaseResult(\n token,\n claim,\n observed,\n publishSettledTaskStatus,\n registerExternalTaskSettlement,\n settlementTransport\n );\n } catch (error) {\n if (error instanceof LegacyPurchaseContinuationError && error.code === 'ambiguous') {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'pushed_task_result_invalid');\n }\n throw error;\n }\n });\n };\n\n if (result.status === 'working' || result.status === 'input-required' || result.status === 'auth-required') {\n const sellerTaskId = result.metadata.serverTaskId;\n if (!sellerTaskId) {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'paused_task_identity_missing');\n throw this.legacyPurchaseAmbiguousError(\n 'The non-terminal legacy create response did not provide a durable seller task identity.'\n );\n }\n await bindSellerTask(sellerTaskId);\n if (result.status !== 'working') return attachMatch(result);\n const watchSignal = AbortSignal.timeout(Math.min(this.legacyPurchaseOperationTtlMs, 5 * 60 * 1000));\n const waitForWorkingPoll = () =>\n new Promise<void>((resolve, reject) => {\n if (watchSignal.aborted) {\n reject(createAbortError(watchSignal.reason));\n return;\n }\n const timer = setTimeout(finish, 60_000);\n const abort = () => finish(createAbortError(watchSignal.reason));\n watchSignal.addEventListener('abort', abort, { once: true });\n function finish(error?: Error) {\n clearTimeout(timer);\n watchSignal.removeEventListener('abort', abort);\n if (error) reject(error);\n else resolve();\n }\n });\n void new Promise<void>(resolve => setTimeout(resolve, 0))\n .then(async () => {\n while (!watchSignal.aborted) {\n const task = await this.agent.getTaskStatus(sellerTaskId, settlementTransport, watchSignal);\n if (task.taskId !== sellerTaskId || task.taskType !== 'create_media_buy') {\n throw this.legacyPurchaseAmbiguousError(\n 'The polled working seller task does not match the durably recorded create_media_buy task.'\n );\n }\n const observed = resultFromTask(task);\n if (observed) {\n return this.trackLegacyPurchaseResult(\n token,\n claim,\n observed,\n publishSettledTaskStatus,\n registerExternalTaskSettlement,\n settlementTransport\n );\n }\n await waitForWorkingPoll();\n }\n throw createAbortError(watchSignal.reason);\n })\n .then(completion => {\n publishSettledTaskStatus?.(completion.status, completion.data, completion.error);\n })\n .catch(async error => {\n if (watchSignal.aborted || isAbortOrTimeoutError(error)) return;\n await this.markLegacyPurchaseAmbiguous(token, claim, 'non_terminal_completion_watch_uncertain');\n void error;\n });\n return attachMatch(result);\n }\n\n if (result.submitted) {\n const submitted = result.submitted;\n await bindSellerTask(submitted.taskId);\n const observeTask = async (\n transport?: import('../protocols').TransportOptions,\n observationSignal?: AbortSignal\n ) => {\n try {\n const task = observationSignal\n ? await withAbortSignal([observationSignal], undefined, () => submitted.track(transport))\n : await submitted.track(transport);\n if (task.taskId !== submitted.taskId) {\n throw this.legacyPurchaseAmbiguousError(\n 'The tracked seller task ID does not match the durably recorded submitted task.'\n );\n }\n if (task.taskType !== 'create_media_buy') {\n throw this.legacyPurchaseAmbiguousError('The tracked seller task has the wrong task identity.');\n }\n if (['completed', 'failed', 'rejected', 'canceled', 'governance-denied'].includes(task.status)) {\n if (task.status === 'completed' && task.result === undefined) {\n throw this.legacyPurchaseAmbiguousError(\n 'The tracked seller task reported completion without a create_media_buy result.'\n );\n }\n const completedSuccessfully =\n task.status === 'completed' && isAdcpOperationSuccess(task.result, task.taskType);\n if (\n !completedSuccessfully &&\n task.status !== 'governance-denied' &&\n (() => {\n const adcpError = extractAdcpErrorInfo(task.result);\n return adcpError === undefined || adcpError.synthetic === true;\n })()\n ) {\n throw this.legacyPurchaseAmbiguousError(\n 'The tracked legacy create failure was not an authoritative structured AdCP error.'\n );\n }\n const terminal = this.assertLegacyPurchaseTerminalResult(\n {\n success: completedSuccessfully,\n status: completedSuccessfully\n ? 'completed'\n : task.status === 'governance-denied'\n ? 'governance-denied'\n : 'failed',\n ...(completedSuccessfully\n ? { data: task.result }\n : {\n ...failureFieldsFromTask(task),\n ...(task.result !== undefined && { data: task.result }),\n }),\n metadata: {\n ...settlementMetadata,\n status: completedSuccessfully\n ? 'completed'\n : task.status === 'governance-denied'\n ? 'governance-denied'\n : 'failed',\n timestamp: new Date().toISOString(),\n },\n },\n this.legacyPurchaseSourceVersion()\n );\n const canonical = await this.completeLegacyPurchase(token, claim, terminal);\n return {\n ...task,\n status: canonical.status,\n taskType: 'create_media_buy',\n ...(canonical.data !== undefined ? { result: canonical.data } : { result: undefined }),\n ...(canonical.status === 'completed'\n ? { error: undefined }\n : { error: canonical.error ?? 'Legacy create failed.' }),\n updatedAt: Date.now(),\n };\n }\n return task;\n } catch (error) {\n // A shared observer may disappear while its tasks/get request is in\n // flight. A late rejection belongs to that abandoned local observer;\n // it is not evidence that the seller mutation itself is ambiguous.\n if (observationSignal?.aborted) throw createAbortError(observationSignal.reason);\n if (error instanceof LegacyPurchaseContinuationError) {\n if (error.code === 'ambiguous') {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'tracked_task_result_invalid');\n }\n throw error;\n }\n await this.markLegacyPurchaseAmbiguous(token, claim, 'tasks_get_transport_uncertain');\n throw this.legacyPurchaseAmbiguousError('Legacy create task tracking failed after claim.', error);\n }\n };\n type SharedCompletion = {\n controller: AbortController;\n pollInterval: number;\n promise: Promise<TaskResult<CreateMediaBuyResponse>>;\n settled: boolean;\n subscriberIntervals: Map<symbol, number>;\n wake?: () => void;\n };\n const waitForNextPoll = (state: SharedCompletion, signal: AbortSignal) =>\n new Promise<void>((resolve, reject) => {\n if (signal.aborted) {\n reject(createAbortError(signal.reason));\n return;\n }\n const timer = setTimeout(finish, state.pollInterval);\n const abort = () => finish(createAbortError(signal.reason));\n const wake = () => finish();\n state.wake = wake;\n signal.addEventListener('abort', abort, { once: true });\n function finish(error?: Error) {\n clearTimeout(timer);\n signal.removeEventListener('abort', abort);\n if (state.wake === wake) state.wake = undefined;\n if (error) reject(error);\n else resolve();\n }\n });\n const pollTrackedCompletion = async (state: SharedCompletion, signal: AbortSignal) => {\n while (true) {\n if (signal.aborted) throw createAbortError(signal.reason);\n const task = await observeTask(settlementTransport, signal);\n const observed = resultFromTask(task);\n if (observed) {\n return this.trackLegacyPurchaseResult(\n token,\n claim,\n observed,\n publishSettledTaskStatus,\n registerExternalTaskSettlement,\n settlementTransport\n );\n }\n await waitForNextPoll(state, signal);\n }\n };\n let sharedCompletion: SharedCompletion | undefined;\n const waitForSharedCompletion = (requestedPollInterval = 60_000, signal?: AbortSignal) => {\n if (\n !Number.isFinite(requestedPollInterval) ||\n requestedPollInterval < 0 ||\n requestedPollInterval > MAX_TIMER_DELAY_MS\n ) {\n throw new RangeError(`pollInterval must be a finite non-negative number <= ${MAX_TIMER_DELAY_MS}`);\n }\n const pollInterval = requestedPollInterval;\n if (sharedCompletion === undefined) {\n const state: SharedCompletion = {\n controller: new AbortController(),\n pollInterval,\n promise: undefined as unknown as Promise<TaskResult<CreateMediaBuyResponse>>,\n settled: false,\n subscriberIntervals: new Map(),\n };\n state.promise = pollTrackedCompletion(state, state.controller.signal).then(\n completed => {\n state.settled = true;\n // A pause is authoritative for current observers but is not a\n // terminal result. A later wait must be able to start a fresh\n // tasks/get epoch after the caller supplies the required input.\n if (\n (completed.status === 'input-required' || completed.status === 'auth-required') &&\n sharedCompletion === state\n ) {\n sharedCompletion = undefined;\n }\n return completed;\n },\n error => {\n if (sharedCompletion === state) sharedCompletion = undefined;\n throw error;\n }\n );\n sharedCompletion = state;\n }\n const state = sharedCompletion;\n const subscription = Symbol('legacy-purchase-completion-subscriber');\n state.subscriberIntervals.set(subscription, pollInterval);\n const activeInterval = Math.min(...state.subscriberIntervals.values());\n if (activeInterval < state.pollInterval) {\n state.pollInterval = activeInterval;\n state.wake?.();\n } else {\n state.pollInterval = activeInterval;\n }\n return withAbortSignal([signal], undefined, () => state.promise).finally(() => {\n state.subscriberIntervals.delete(subscription);\n if (state.subscriberIntervals.size > 0) {\n state.pollInterval = Math.min(...state.subscriberIntervals.values());\n } else if (!state.settled && sharedCompletion === state) {\n sharedCompletion = undefined;\n // This controller only stops the SDK-owned track/sleep loop. It is\n // never forwarded to waitForCompletion, so an observation timeout\n // cannot become an A2A tasks/cancel request.\n state.controller.abort(createAbortError('No legacy purchase completion observers remain.'));\n }\n });\n };\n (result as { submitted?: unknown }).submitted = {\n ...submitted,\n track: (transport?: import('../protocols').TransportOptions) => observeTask(transport),\n waitForCompletion: async (pollInterval?: number, signal?: AbortSignal) => {\n // Validate caller input before entering the uncertainty boundary so\n // only this local RangeError bypasses durable ambiguity handling.\n if (\n pollInterval !== undefined &&\n (!Number.isFinite(pollInterval) || pollInterval < 0 || pollInterval > MAX_TIMER_DELAY_MS)\n ) {\n throw new RangeError(`pollInterval must be a finite non-negative number <= ${MAX_TIMER_DELAY_MS}`);\n }\n try {\n return await waitForSharedCompletion(pollInterval, signal);\n } catch (error) {\n // A caller stopping its own observation says nothing about the\n // seller mutation. The background observer retains ownership.\n if (isAbortOrTimeoutError(error)) throw error;\n if (error instanceof LegacyPurchaseContinuationError) {\n if (error.code === 'ambiguous') {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'completion_wait_result_invalid');\n }\n throw error;\n }\n await this.markLegacyPurchaseAmbiguous(token, claim, 'completion_wait_transport_uncertain');\n throw this.legacyPurchaseAmbiguousError('Legacy create completion waiting failed after claim.', error);\n }\n },\n };\n\n // Give the returned continuation's caller the first opportunity to set\n // its desired poll interval. If it does not, begin one bounded,\n // SDK-owned track loop on the next timer turn. The timeout races only\n // that observer subscription and never reaches the seller transport.\n const watchSignal = AbortSignal.timeout(Math.min(this.legacyPurchaseOperationTtlMs, 5 * 60 * 1000));\n void new Promise<void>(resolve => setTimeout(resolve, 0))\n .then(() => waitForSharedCompletion(undefined, watchSignal))\n .then(completion => {\n publishSettledTaskStatus?.(completion.status, completion.data, completion.error);\n })\n .catch(async error => {\n if (watchSignal.aborted || isAbortOrTimeoutError(error)) return;\n await this.markLegacyPurchaseAmbiguous(token, claim, 'background_completion_watch_uncertain');\n // The durable ambiguous state is the observable outcome. Avoid an\n // unhandled rejection from this best-effort background observer.\n void error;\n });\n }\n if (result.deferred) {\n const deferred = result.deferred;\n (result as { deferred?: unknown }).deferred = {\n ...deferred,\n resume: async (resumeInput: unknown) => {\n try {\n return await this.trackLegacyPurchaseResult(\n token,\n claim,\n await deferred.resume(resumeInput),\n publishSettledTaskStatus,\n registerExternalTaskSettlement,\n settlementTransport\n );\n } catch (error) {\n if (error instanceof LegacyPurchaseContinuationError) {\n if (error.code === 'ambiguous') {\n await this.markLegacyPurchaseAmbiguous(token, claim, 'deferred_resume_result_invalid');\n }\n throw error;\n }\n await this.markLegacyPurchaseAmbiguous(token, claim, 'deferred_resume_transport_uncertain');\n throw this.legacyPurchaseAmbiguousError('Legacy create deferred resume failed after claim.', error);\n }\n },\n };\n }\n return attachMatch(result);\n }\n\n async refineProposals(\n params: RefineProposalsInput,\n inputHandler?: InputHandler,\n options?: ProposalRefinementTaskOptions\n ): Promise<CompatibilityTaskResult<CompatibleRefineProposalsResponse, CompatibleRefineProposalsWireResponse>> {\n this.assertActive('refineProposals');\n const lifecycle = this.selectLifecycle('refine_proposals');\n this.assertValidCompactRequest('refine_proposals', params, lifecycle, true);\n if (lifecycle === 'compact') {\n const proposalIds = params.refinements.map(refinement => refinement.proposal_id);\n const retry = this.pendingRefinementRetryCandidate(proposalIds);\n const identity = this.proposalMutationIdempotency(\n params.idempotency_key,\n retry,\n Boolean(options?.skipIdempotencyAutoInject)\n );\n const request: RefineProposalsInput = identity.idempotencyKey\n ? { ...params, idempotency_key: identity.idempotencyKey }\n : params;\n const scopes = this.proposalScopes(proposalIds);\n const accountScope = scopes.length === 1 ? scopes[0] : undefined;\n const pendingRefinement = this.beginPendingRefinement(\n proposalIds,\n true,\n requestFingerprint(request),\n identity.idempotencyKey,\n identity.skipIdempotencyAutoInject\n );\n const attemptEpoch = pendingRefinement.attemptEpoch;\n const dispatchOptions = retry\n ? { ...options, skipIdempotencyAutoInject: retry.skipIdempotencyAutoInject }\n : options;\n const projectOnly = (data: CompatibleRefineProposalsWireResponse) =>\n projectRefineProposals(data, lifecycle, params.refinements);\n const projectAndSettle = (data: CompatibleRefineProposalsWireResponse) => {\n try {\n const projected = projectOnly(data);\n this.settlePendingRefinement(pendingRefinement, projected, attemptEpoch);\n return projected;\n } catch (error) {\n if (!this.disposed) this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n throw error;\n }\n };\n try {\n return await this.captureProposalDispatch(\n accountScope,\n () => this.agent.refineProposals(request, inputHandler, dispatchOptions),\n result =>\n this.adaptProjectedResult(\n result,\n this.makeReport(lifecycle, ['refine_proposals'], []),\n projectAndSettle,\n accountScope,\n true,\n undefined,\n pendingRefinement,\n attemptEpoch\n ),\n projectOnly,\n () => this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch),\n true,\n projected =>\n this.preparePendingRefinementSettlement(\n pendingRefinement,\n projected as CompatibleRefineProposalsResponse,\n attemptEpoch\n ),\n () => this.restorePendingRefinement(pendingRefinement, attemptEpoch)\n );\n } catch (error) {\n if (!this.disposed) this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n throw error;\n }\n }\n\n this.assertProposalLifecycleAvailable('refineProposals');\n\n this.assertOnlyFields('refineProposals', record(params), REFINE_PROPOSALS_FIELDS);\n const legacyRefine: Record<string, unknown>[] = [];\n if (params.refinements.length === 0) {\n throw this.unsupported('refineProposals', 'refinements', 'Proposal refinement requires at least one entry.');\n }\n if (params.governance_context !== undefined) {\n throw this.unsupported(\n 'refineProposals',\n 'governance_context',\n 'Established get_products refinement cannot carry compact governance_context.'\n );\n }\n if ((params as Record<string, unknown>).context_id !== undefined) {\n throw this.unsupported(\n 'refineProposals',\n 'context_id',\n 'Established get_products refinement cannot carry an explicit compact context_id.'\n );\n }\n if (params.push_notification_config !== undefined && compareRelease(this.negotiated_version, '3.1') < 0) {\n throw this.unsupported(\n 'refineProposals',\n 'push_notification_config',\n `The negotiated ${this.negotiated_version} get_products request cannot carry push_notification_config.`\n );\n }\n for (const refinement of params.refinements) {\n const refinementInput = record(refinement);\n if (!optionalString(refinementInput.proposal_id)) {\n throw this.unsupported(\n 'refineProposals',\n 'proposal_id',\n 'Every proposal refinement requires a real proposal_id.'\n );\n }\n if (refinement.action === 'finalize') {\n const unsupportedFields = Object.keys(refinementInput).filter(key => key !== 'proposal_id' && key !== 'action');\n if (unsupportedFields.length > 0) {\n throw this.unsupported(\n 'refineProposals',\n `finalize.${unsupportedFields.join(',')}`,\n `Legacy finalize cannot carry additional compact refinement fields: ${unsupportedFields.join(', ')}.`\n );\n }\n legacyRefine.push({ scope: 'proposal', proposal_id: refinement.proposal_id, action: 'finalize' });\n continue;\n }\n if (refinement.action !== 'revise') {\n throw this.unsupported(\n 'refineProposals',\n 'action',\n `Unsupported compact proposal refinement action: ${String(refinementInput.action)}.`\n );\n }\n const reviseFields = new Set([\n 'proposal_id',\n 'action',\n 'constraints',\n 'product_changes',\n 'alternatives',\n 'ask',\n 'criteria',\n 'change_kind',\n ]);\n const unknownFields = Object.keys(refinementInput).filter(key => !reviseFields.has(key));\n if (unknownFields.length > 0) {\n throw this.unsupported(\n 'refineProposals',\n `refinement.${unknownFields.join(',')}`,\n `Compact proposal refinement fields ${unknownFields.join(', ')} have no declared legacy projection.`\n );\n }\n if (refinement.constraints || refinement.alternatives || refinement.criteria || refinement.change_kind) {\n throw this.unsupported(\n 'refineProposals',\n 'structured proposal refinement',\n 'Hard constraints, alternatives, criteria, and amendment kinds cannot be guaranteed by legacy refinement.'\n );\n }\n legacyRefine.push({\n scope: 'proposal',\n proposal_id: refinement.proposal_id,\n ...(refinement.ask !== undefined && { ask: refinement.ask }),\n });\n for (const [productId, action] of Object.entries(refinement.product_changes ?? {})) {\n if (action !== 'include' && action !== 'omit') {\n throw this.unsupported(\n 'refineProposals',\n `product_changes.${productId}`,\n `Legacy product refinement supports only include or omit, not ${String(action)}.`\n );\n }\n legacyRefine.push({ scope: 'product', product_id: productId, action });\n }\n }\n const proposalIds = params.refinements.map(refinement => refinement.proposal_id);\n const retry = this.pendingRefinementRetryCandidate(proposalIds);\n const identity = this.proposalMutationIdempotency(\n params.idempotency_key,\n retry,\n Boolean(options?.skipIdempotencyAutoInject)\n );\n const request: CanonicalGetProductsRequest = {\n buying_mode: 'refine',\n refine: legacyRefine as CanonicalGetProductsRequest['refine'],\n ...(identity.idempotencyKey && { idempotency_key: identity.idempotencyKey }),\n ...(params.push_notification_config !== undefined && {\n push_notification_config:\n params.push_notification_config as unknown as CanonicalGetProductsRequest['push_notification_config'],\n }),\n ...(params.context !== undefined && { context: params.context as CanonicalGetProductsRequest['context'] }),\n };\n const scopes = this.proposalScopes(proposalIds);\n const accountScope = scopes.length === 1 ? scopes[0] : undefined;\n const pendingRefinement = this.beginPendingRefinement(\n proposalIds,\n true,\n requestFingerprint(request),\n identity.idempotencyKey,\n identity.skipIdempotencyAutoInject\n );\n const attemptEpoch = pendingRefinement.attemptEpoch;\n const dispatchOptions = retry\n ? { ...options, skipIdempotencyAutoInject: retry.skipIdempotencyAutoInject }\n : options;\n const projectOnly = (data: CompatibleRefineProposalsWireResponse) =>\n projectRefineProposals(data, lifecycle, params.refinements);\n const projectAndSettle = (data: CompatibleRefineProposalsWireResponse) => {\n try {\n const projected = projectOnly(data);\n this.settlePendingRefinement(pendingRefinement, projected, attemptEpoch);\n return projected;\n } catch (error) {\n if (!this.disposed) this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n throw error;\n }\n };\n try {\n return await this.captureProposalDispatch(\n accountScope,\n () => this.agent.getProducts(request, inputHandler, dispatchOptions),\n result =>\n this.adaptProjectedResult(\n result,\n this.makeReport(lifecycle, ['get_products'], []),\n projectAndSettle,\n accountScope,\n true,\n undefined,\n pendingRefinement,\n attemptEpoch\n ),\n projectOnly,\n () => this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch),\n true,\n projected =>\n this.preparePendingRefinementSettlement(\n pendingRefinement,\n projected as CompatibleRefineProposalsResponse,\n attemptEpoch\n ),\n () => this.restorePendingRefinement(pendingRefinement, attemptEpoch)\n );\n } catch (error) {\n if (!this.disposed) this.preserveAmbiguousProposalMutation(pendingRefinement, attemptEpoch);\n throw error;\n }\n }\n\n async declineProposals(\n params: MutatingRequestInput<DeclineProposalsRequest>,\n inputHandler?: InputHandler,\n options?: CanonicalProjectionTaskOptions\n ): Promise<CompatibilityTaskResult<CompatibleDeclineProposalsResponse, CompatibleDeclineProposalsWireResponse>> {\n this.assertActive('declineProposals');\n const input = record(params);\n const lifecycle = this.selectLifecycle('decline_proposals');\n const projectOnly = (data: unknown, proposalIds: readonly string[]) =>\n projectDeclineProposals(data, lifecycle, proposalIds, this.negotiated_version);\n if (lifecycle === 'compact') {\n this.assertValidCompactRequest('decline_proposals', params, lifecycle, true);\n const proposalIds = array(input.declines)\n .map(value => optionalString(record(value).proposal_id))\n .filter((value): value is string => value !== undefined);\n const retry = this.pendingDeclineRetryCandidate(proposalIds);\n const identity = this.proposalMutationIdempotency(\n input.idempotency_key,\n retry,\n Boolean(options?.skipIdempotencyAutoInject)\n );\n const request = identity.idempotencyKey ? { ...params, idempotency_key: identity.idempotencyKey } : params;\n const pendingDecline = this.beginPendingDecline(\n proposalIds,\n requestFingerprint(request),\n identity.idempotencyKey,\n identity.skipIdempotencyAutoInject\n );\n const attemptEpoch = pendingDecline.attemptEpoch;\n const dispatchOptions = retry\n ? { ...options, skipIdempotencyAutoInject: retry.skipIdempotencyAutoInject }\n : options;\n const projectAndSettle = (data: unknown) => {\n try {\n const projected = projectOnly(data, proposalIds);\n this.preparePendingDeclineSettlement(pendingDecline, projected, attemptEpoch)();\n return projected;\n } catch (error) {\n if (!this.disposed) this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch);\n throw error;\n }\n };\n try {\n return await this.captureProposalDispatch(\n undefined,\n () => this.agent.declineProposals(request, inputHandler, dispatchOptions),\n result =>\n this.adaptProjectedResult(\n result,\n this.makeReport(lifecycle, ['decline_proposals'], []),\n projectAndSettle,\n undefined,\n false,\n pendingDecline,\n undefined,\n attemptEpoch\n ),\n data => projectOnly(data, proposalIds),\n () => this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch),\n false,\n projected =>\n this.preparePendingDeclineSettlement(\n pendingDecline,\n projected as CompatibleDeclineProposalsResponse,\n attemptEpoch\n )\n );\n } catch (error) {\n if (!this.disposed) this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch);\n throw error;\n }\n }\n\n this.assertProposalLifecycleAvailable('declineProposals');\n\n this.assertOnlyFields('declineProposals', input, DECLINE_PROPOSALS_FIELDS);\n for (const [index, value] of array(input.declines).entries()) {\n this.assertOnlyFields(\n `declineProposals.declines[${index}]`,\n record(value),\n new Set(['proposal_id', 'reason', 'detail'])\n );\n }\n const losses: MediaBuyCompatibilityLoss[] = [\n 'proposal_decline_not_terminal',\n 'proposal_decline_reason_not_forwarded',\n ];\n this.requireAllowed('declineProposals', losses);\n if (input.opportunity !== undefined || input.governance_context !== undefined || input.context_id !== undefined) {\n throw this.unsupported(\n 'declineProposals',\n 'opportunity/governance_context/context_id',\n 'Established proposal omit cannot preserve compact opportunity, governance, or explicit context-ID semantics.'\n );\n }\n if (input.push_notification_config !== undefined && compareRelease(this.negotiated_version, '3.1') < 0) {\n throw this.unsupported(\n 'declineProposals',\n 'push_notification_config',\n `The negotiated ${this.negotiated_version} get_products request cannot carry push_notification_config.`\n );\n }\n const declines = array(input.declines).map(item => {\n const decline = record(item);\n return { scope: 'proposal', proposal_id: decline.proposal_id, action: 'omit' };\n });\n const proposalIds = declines.map(decline => String(decline.proposal_id));\n const retry = this.pendingDeclineRetryCandidate(proposalIds);\n const identity = this.proposalMutationIdempotency(\n input.idempotency_key,\n retry,\n Boolean(options?.skipIdempotencyAutoInject)\n );\n const request: CanonicalGetProductsRequest = {\n buying_mode: 'refine',\n refine: declines as CanonicalGetProductsRequest['refine'],\n ...(identity.idempotencyKey && { idempotency_key: identity.idempotencyKey }),\n ...(input.push_notification_config !== undefined && {\n push_notification_config:\n input.push_notification_config as CanonicalGetProductsRequest['push_notification_config'],\n }),\n ...(input.context !== undefined && { context: input.context as CanonicalGetProductsRequest['context'] }),\n };\n this.assertValidCompactRequest('decline_proposals', params, lifecycle, true);\n const pendingDecline = this.beginPendingDecline(\n proposalIds,\n requestFingerprint(request),\n identity.idempotencyKey,\n identity.skipIdempotencyAutoInject\n );\n const attemptEpoch = pendingDecline.attemptEpoch;\n const dispatchOptions = retry\n ? { ...options, skipIdempotencyAutoInject: retry.skipIdempotencyAutoInject }\n : options;\n const projectAndSettle = (data: unknown) => {\n try {\n const projected = projectOnly(data, proposalIds);\n this.preparePendingDeclineSettlement(pendingDecline, projected, attemptEpoch)();\n return projected;\n } catch (error) {\n if (!this.disposed) this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch);\n throw error;\n }\n };\n try {\n return await this.captureProposalDispatch(\n undefined,\n () => this.agent.getProducts(request, inputHandler, dispatchOptions),\n result =>\n this.adaptProjectedResult(\n result,\n this.makeReport(lifecycle, ['get_products'], losses, [\n 'Legacy proposal omit is not a seller-confirmed terminal decline.',\n 'Legacy proposal omit cannot forward the compact decline reason or detail.',\n ]),\n projectAndSettle,\n undefined,\n false,\n pendingDecline,\n undefined,\n attemptEpoch\n ),\n data => projectOnly(data, proposalIds),\n () => this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch),\n false,\n projected =>\n this.preparePendingDeclineSettlement(\n pendingDecline,\n projected as CompatibleDeclineProposalsResponse,\n attemptEpoch\n )\n );\n } catch (error) {\n if (!this.disposed) this.preserveAmbiguousProposalMutation(pendingDecline, attemptEpoch);\n throw error;\n }\n }\n\n async buyProducts(\n params: MutatingRequestInput<BuyProductsRequest>,\n inputHandler?: InputHandler,\n options?: TaskOptions\n ): Promise<CompatibilityTaskResult<BuyProductsResponse | CreateMediaBuyResponse>> {\n this.assertActive('buyProducts');\n const input = record(params);\n const lifecycle = this.selectLifecycle('buy_products');\n this.assertLegacyReferenceShapes('buyProducts', input);\n if (lifecycle === 'compact') {\n this.assertValidCompactRequest('buy_products', params, lifecycle, true);\n const result = await this.agent.buyProducts(params, inputHandler, options);\n return this.adaptProjectedResult(result, this.makeReport(lifecycle, ['buy_products'], []), data => data);\n }\n\n this.assertOnlyFields('buyProducts', input, BUY_PRODUCTS_FIELDS);\n this.assertLegacyReportingWebhook('buyProducts', input.reporting_webhook);\n this.assertCompactWireFieldsAbsent('buyProducts', input, [\n 'budget_allocation',\n 'daily_budget_cap',\n 'budget_cap_timezone',\n 'pacing',\n 'bidding',\n 'governance_context',\n 'opportunity',\n 'total_budget',\n ]);\n if (compareRelease(this.negotiated_version, '3.0') < 0) {\n this.assertCompactWireFieldsAbsent('buyProducts', input, [\n 'advertiser_industry',\n 'agency_estimate_number',\n 'invoice_recipient',\n 'push_notification_config',\n ]);\n }\n this.assertLegacyPushNotification('buyProducts', input.push_notification_config);\n if (Object.hasOwn(input, 'paused') && compareRelease(this.negotiated_version, '3.1') < 0) {\n throw this.unsupported(\n 'buyProducts',\n 'paused',\n `The negotiated ${this.negotiated_version} create_media_buy request cannot represent paused.`\n );\n }\n if (!optionalString(input.feed_version)) {\n throw this.unsupported('buyProducts', 'feed_version', 'Compact buy_products requires a real feed_version.');\n }\n if (input.pricing_version !== undefined && !optionalString(input.pricing_version)) {\n throw this.unsupported(\n 'buyProducts',\n 'pricing_version',\n 'When provided, compact pricing_version must be a non-empty seller version.'\n );\n }\n if (input.ext !== undefined) {\n throw this.unsupported('buyProducts', 'ext', 'Compact buy_products.ext has no declared legacy projection.');\n }\n const losses: MediaBuyCompatibilityLoss[] = ['feed_version_not_atomic'];\n if (input.pricing_version !== undefined) losses.push('pricing_version_not_atomic');\n this.requireAllowed('buyProducts', losses);\n for (const field of ['account', 'brand', 'start_time', 'end_time', 'purchases']) {\n if (input[field] === undefined) {\n throw this.unsupported('buyProducts', field, `Legacy create_media_buy requires ${field}.`);\n }\n }\n const purchases = array(input.purchases);\n if (purchases.length === 0) {\n throw this.unsupported('buyProducts', 'purchases', 'Legacy create_media_buy requires at least one purchase.');\n }\n const packageFields = isCompactRelease(this.negotiated_version)\n ? V32_PURCHASE_FIELDS\n : compareRelease(this.negotiated_version, '3.1') >= 0\n ? V31_PURCHASE_FIELDS\n : compareRelease(this.negotiated_version, '3.0') >= 0\n ? V30_PURCHASE_FIELDS\n : V25_PURCHASE_FIELDS;\n const packages = purchases.map((value, index) => {\n const purchase = record(value);\n const unsupportedFields = Object.keys(purchase).filter(key => !packageFields.has(key));\n if (unsupportedFields.length) {\n throw this.unsupported(\n 'buyProducts',\n `purchases[${index}].${unsupportedFields.join(',')}`,\n `Compact purchase fields ${unsupportedFields.join(', ')} have no declared legacy package projection.`\n );\n }\n if (!optionalString(purchase.product_id) || !optionalString(purchase.pricing_option_id)) {\n throw this.unsupported(\n 'buyProducts',\n `purchases[${index}]`,\n 'Every purchase requires real product_id and pricing_option_id values from seller discovery.'\n );\n }\n this.assertLegacyTargetingOverlay(\n 'buyProducts',\n purchase.targeting_overlay,\n `purchases[${index}].targeting_overlay`\n );\n return Object.fromEntries(Object.entries(purchase).filter(([key]) => packageFields.has(key)));\n });\n const request: MutatingRequestInput<CanonicalCreateMediaBuyRequest> = {\n account: input.account as CanonicalCreateMediaBuyRequest['account'],\n brand: input.brand as CanonicalCreateMediaBuyRequest['brand'],\n start_time: input.start_time as CanonicalCreateMediaBuyRequest['start_time'],\n end_time: input.end_time as CanonicalCreateMediaBuyRequest['end_time'],\n packages: packages as CanonicalCreateMediaBuyRequest['packages'],\n ...(input.idempotency_key !== undefined && { idempotency_key: input.idempotency_key as string }),\n ...(input.total_budget !== undefined && {\n total_budget: input.total_budget as CanonicalCreateMediaBuyRequest['total_budget'],\n }),\n ...(input.daily_budget_cap !== undefined && { daily_budget_cap: input.daily_budget_cap as number }),\n ...(input.budget_cap_timezone !== undefined && { budget_cap_timezone: input.budget_cap_timezone as string }),\n ...(input.budget_allocation !== undefined && {\n budget_allocation: input.budget_allocation as CanonicalCreateMediaBuyRequest['budget_allocation'],\n }),\n ...(input.pacing !== undefined && { pacing: input.pacing as CanonicalCreateMediaBuyRequest['pacing'] }),\n ...(input.bidding !== undefined && { bidding: input.bidding as CanonicalCreateMediaBuyRequest['bidding'] }),\n ...(input.paused !== undefined && { paused: input.paused as boolean }),\n ...(input.advertiser_industry !== undefined && {\n advertiser_industry: input.advertiser_industry as CanonicalCreateMediaBuyRequest['advertiser_industry'],\n }),\n ...(input.purchase_order_ref !== undefined && { po_number: input.purchase_order_ref as string }),\n ...(input.agency_estimate_number !== undefined && {\n agency_estimate_number: input.agency_estimate_number as string,\n }),\n ...(input.invoice_recipient !== undefined && {\n invoice_recipient: input.invoice_recipient as CanonicalCreateMediaBuyRequest['invoice_recipient'],\n }),\n ...(input.governance_context !== undefined && { governance_context: input.governance_context as string }),\n ...(input.opportunity !== undefined && {\n opportunity: input.opportunity as CanonicalCreateMediaBuyRequest['opportunity'],\n }),\n ...(input.reporting_webhook !== undefined && {\n reporting_webhook: input.reporting_webhook as CanonicalCreateMediaBuyRequest['reporting_webhook'],\n }),\n ...(input.push_notification_config !== undefined && {\n push_notification_config:\n input.push_notification_config as CanonicalCreateMediaBuyRequest['push_notification_config'],\n }),\n ...(input.context !== undefined && { context: input.context as CanonicalCreateMediaBuyRequest['context'] }),\n };\n this.assertValidCompactRequest('buy_products', params, lifecycle, true);\n const result = await this.agent.createMediaBuy(request, inputHandler, options);\n return this.adaptProjectedResult(\n result,\n this.makeReport(lifecycle, ['create_media_buy'], losses, [\n 'The established mutation cannot atomically fence the selected feed/pricing snapshot.',\n ]),\n data => data\n );\n }\n\n async acceptProposal(\n params: MutatingRequestInput<CompatibleAcceptProposalRequest>,\n inputHandler?: InputHandler,\n options?: TaskOptions\n ): Promise<CompatibilityTaskResult<AcceptProposalResponse | CreateMediaBuyResponse>> {\n this.assertActive('acceptProposal');\n const input = record(params);\n const lifecycle = this.selectLifecycle('accept_proposal');\n this.assertLegacyReferenceShapes('acceptProposal', input);\n if (lifecycle === 'compact') {\n const proposalId = optionalString(input.proposal_id);\n if (proposalId && this.isProposalDeclinePending(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_decline_pending',\n 'The proposal has an unresolved decline in this principal scope. Wait for or reconcile that decline before accepting it.'\n );\n }\n if (proposalId && this.isProposalRefinementPending(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_refinement_pending',\n 'The proposal has an unresolved refinement in this principal scope. Wait for or reconcile that refinement before accepting it.'\n );\n }\n if (proposalId && this.isCommitUncertainProposalMutation(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_mutation_commit_uncertain',\n 'The proposal has a decline or refinement whose commit outcome is unknown. Reconcile it before sending an acceptance.'\n );\n }\n if (proposalId && this.isCommitUncertainProposal(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_commit_uncertain',\n 'The proposal has an established acceptance whose commit outcome is unknown. Reconcile the media buy by natural key before sending another acceptance.'\n );\n }\n if (proposalId && this.isTerminalAcceptanceProposal(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_terminal',\n 'The proposal is terminal in this principal scope. No acceptance was sent.'\n );\n }\n if (proposalId && this.isTerminalProposal(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_terminal',\n 'The proposal was already consumed by a terminal lifecycle mutation in this principal scope. No acceptance was sent.'\n );\n }\n const { established_fallback: _fallback, ...compactInput } = input;\n this.assertValidCompactRequest('accept_proposal', compactInput, lifecycle, true);\n if (!proposalId) {\n throw this.unsupported('acceptProposal', 'proposal_id', 'Native proposal acceptance requires a proposal_id.');\n }\n const prior = this.proposalSnapshotStore.proposalAcceptances.get(proposalId);\n if (\n prior?.reservation.kind === 'established' &&\n prior.reservation.state === 'retryable' &&\n prior.reservation.retryKind === 'commit-uncertain'\n ) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_commit_uncertain',\n 'The proposal has an established acceptance whose commit outcome is unknown. Reconcile or exactly retry that established acceptance before sending a compact acceptance.'\n );\n }\n if (prior?.reservation.state === 'in-flight' || prior?.reservation.kind === 'established') {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_pending',\n 'The proposal already has an acceptance reservation in this principal scope. Wait for it to finish before retrying.'\n );\n }\n const retryable = prior?.reservation.state === 'retryable' ? prior.reservation : undefined;\n if (retryable) this.assertAcceptanceRetryWindow(prior!.snapshotKey, prior!.snapshot, retryable);\n const skipIdempotencyAutoInject =\n retryable?.skipIdempotencyAutoInject ?? Boolean(options?.skipIdempotencyAutoInject);\n const idempotencyKey =\n optionalString(compactInput.idempotency_key) ??\n retryable?.idempotencyKey ??\n (!skipIdempotencyAutoInject ? generateIdempotencyKey() : undefined);\n const request = {\n ...compactInput,\n ...(idempotencyKey && { idempotency_key: idempotencyKey }),\n } as MutatingRequestInput<AcceptProposalRequest>;\n const fingerprint = requestFingerprint(request);\n if (\n retryable &&\n (retryable.kind !== 'native' ||\n retryable.requestFingerprint !== fingerprint ||\n retryable.idempotencyKey !== idempotencyKey ||\n retryable.skipIdempotencyAutoInject !== skipIdempotencyAutoInject)\n ) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_retry',\n 'A paused or commit-uncertain native acceptance may retry only the exact same request and idempotency key. No mutation was sent.'\n );\n }\n if (retryable?.taskId) this.forgetAcceptanceTask(retryable.taskId, retryable);\n if (retryable) this.releaseAcceptanceOwnership(retryable);\n const accountScope = this.accountScope(compactInput.account);\n const snapshotKey = prior?.snapshotKey ?? `${this.snapshotKey(proposalId, accountScope)}\\u0000native-acceptance`;\n const snapshot =\n prior?.snapshot ??\n ({\n proposal: { proposal_id: proposalId },\n bytes: new TextEncoder().encode(snapshotKey).byteLength,\n principalScope: this.principalScope ?? '',\n executable: false,\n nativeAcceptanceOnly: true,\n ...(accountScope && { accountScope }),\n } satisfies ProposalSnapshotEntry);\n if (!prior) {\n this.retainProposalSnapshot(snapshotKey, snapshot);\n this.enforceProposalSnapshotLimits();\n if (this.proposalSnapshotStore.entries.get(snapshotKey) !== snapshot) {\n throw new ConfigurationError(\n 'The media-buy proposal snapshot limit could not retain a native acceptance fence.',\n 'mediaBuy.proposalSnapshots'\n );\n }\n }\n const retryDeadlineMs =\n retryable?.retryDeadlineMs ??\n (this.idempotencyReplayTtlMs !== undefined ? Date.now() + this.idempotencyReplayTtlMs : undefined);\n const reservation: AcceptanceReservation = {\n kind: 'native',\n state: 'in-flight',\n requestFingerprint: fingerprint,\n skipIdempotencyAutoInject,\n ...(idempotencyKey && { idempotencyKey }),\n };\n if (retryDeadlineMs !== undefined) {\n Object.defineProperty(reservation, 'retryDeadlineMs', {\n value: retryDeadlineMs,\n enumerable: true,\n writable: false,\n configurable: false,\n });\n }\n snapshot.executable = false;\n snapshot.acceptance = reservation;\n this.proposalSnapshotStore.proposalAcceptances.set(proposalId, { snapshotKey, snapshot, reservation });\n this.ownedAcceptanceReservations.set(reservation, { snapshotKey, snapshot });\n acceptanceReservationOwners.set(reservation, this);\n let result: TaskResult<AcceptProposalResponse>;\n try {\n result = await this.agent.acceptProposal(request, inputHandler, {\n ...options,\n skipIdempotencyAutoInject,\n });\n } catch (error) {\n this.preserveAmbiguousAcceptance(snapshotKey, snapshot, reservation);\n throw error;\n }\n const transitioned = this.attachAcceptanceTransitions(result, snapshotKey, snapshot, reservation);\n return this.adaptProjectedResult(transitioned, this.makeReport(lifecycle, ['accept_proposal'], []), data => data);\n }\n\n this.assertProposalLifecycleAvailable('acceptProposal');\n this.assertOnlyFields('acceptProposal', input, ACCEPT_PROPOSAL_FIELDS);\n this.assertLegacyReportingWebhook('acceptProposal', input.reporting_webhook);\n this.assertLegacyPushNotification('acceptProposal', input.push_notification_config);\n this.assertCompactWireFieldsAbsent('acceptProposal', input, [\n 'daily_budget_cap',\n 'budget_cap_timezone',\n 'governance_context',\n 'opportunity',\n ]);\n const suppliedDigest = optionalString(input.proposal_terms_digest);\n if (input.ext !== undefined) {\n throw this.unsupported('acceptProposal', 'ext', 'Compact accept_proposal.ext has no declared legacy projection.');\n }\n const proposalId = optionalString(input.proposal_id);\n if (!proposalId || input.account === undefined) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_id/account',\n 'Legacy proposal acceptance requires a real proposal_id and account.'\n );\n }\n if (!this.principalScope) {\n throw this.unsupported(\n 'acceptProposal',\n 'principal_scope',\n 'Established proposal acceptance requires a stable, non-secret principalScope when negotiating the coordinator. No mutation was sent.'\n );\n }\n if (this.isProposalDeclinePending(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_decline_pending',\n 'The proposal has an unresolved decline in this principal scope. Wait for that decline to finish before accepting it.'\n );\n }\n if (this.isProposalRefinementPending(proposalId)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_refinement_pending',\n 'The proposal has an unresolved refinement in this principal scope. Wait for that refinement to finish before accepting it.'\n );\n }\n const accountScope = this.accountScope(input.account);\n const snapshotKey = accountScope ? this.snapshotKey(proposalId, accountScope) : undefined;\n const globalAcceptance = this.proposalSnapshotStore.proposalAcceptances.get(proposalId);\n if (globalAcceptance && globalAcceptance.snapshotKey !== snapshotKey) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_pending',\n 'The proposal already has an acceptance reservation in this principal scope. Reuse the original account scope for an exact retry.'\n );\n }\n if (globalAcceptance?.reservation.state === 'in-flight') {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_pending',\n 'The proposal already has an in-flight acceptance in this principal scope. Wait for it to finish before retrying.'\n );\n }\n const snapshot = snapshotKey ? this.proposalSnapshotStore.entries.get(snapshotKey) : undefined;\n const retryableAcceptance =\n globalAcceptance?.reservation.state === 'retryable' ? globalAcceptance.reservation : undefined;\n if (!snapshot || (!snapshot.executable && !retryableAcceptance)) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_snapshot/account_scope',\n 'No proposal snapshot is available in the supplied principal and account scope. Request/finalize it through this coordinator first.'\n );\n }\n if (retryableAcceptance) this.assertAcceptanceRetryWindow(snapshotKey!, snapshot, retryableAcceptance);\n const proposal = snapshot.proposal;\n if (proposal.proposal_status !== undefined && proposal.proposal_status !== 'committed') {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_status',\n `Legacy create_media_buy projection cannot accept a proposal in ${String(proposal.proposal_status)} status.`\n );\n }\n if (proposal.proposal_kind !== undefined && proposal.proposal_kind !== 'new_media_buy') {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_kind',\n `Legacy create_media_buy projection supports only new_media_buy proposals, not ${String(proposal.proposal_kind)}.`\n );\n }\n\n const losses = ['proposal_terms_digest_not_enforced'] as MediaBuyCompatibilityLoss[];\n const expiresAt = proposal.expires_at;\n if (expiresAt === undefined) {\n losses.push('proposal_hold_not_verifiable');\n } else {\n if (!isStrictDateTime(expiresAt)) {\n throw this.unsupported(\n 'acceptProposal',\n 'expires_at',\n 'The proposal carries an invalid seller hold expiry. No mutation was sent.'\n );\n }\n const expiry = Date.parse(expiresAt);\n if (!retryableAcceptance && expiry <= Date.now()) {\n throw this.unsupported('acceptProposal', 'expires_at', 'The proposal is expired. No mutation was sent.');\n }\n }\n\n const sellerDigest = optionalString(proposal.terms_digest);\n const terms = record(proposal.commercial_terms);\n const digestBoundTerms = Boolean(sellerDigest && Object.keys(terms).length > 0);\n if (sellerDigest && snapshot.canonicalTermsDigest) {\n if (sellerDigest !== snapshot.canonicalTermsDigest) {\n throw new MediaBuyLifecycleCompatibilityError({\n operation: 'acceptProposal',\n negotiatedVersion: this.negotiated_version,\n lifecycle,\n feature: 'seller_proposal_terms_digest',\n code: 'PROPOSAL_DIGEST_MISMATCH',\n message: 'The seller digest is not bound to the cached commercial terms. No mutation was sent.',\n });\n }\n if (!suppliedDigest || suppliedDigest !== sellerDigest) {\n throw new MediaBuyLifecycleCompatibilityError({\n operation: 'acceptProposal',\n negotiatedVersion: this.negotiated_version,\n lifecycle,\n feature: 'proposal_terms_digest',\n code: 'PROPOSAL_DIGEST_MISMATCH',\n message: 'The proposal digest differs from the seller-provided snapshot. No mutation was sent.',\n });\n }\n } else {\n losses.push('proposal_terms_digest_unavailable', 'proposal_snapshot_not_immutable');\n }\n\n this.requireAllowed('acceptProposal', losses);\n const resolvedAcceptanceField = (field: string): unknown => {\n const termValue = terms[field];\n const inputValue = input[field];\n if (!digestBoundTerms || termValue === undefined) return inputValue;\n if (inputValue !== undefined) {\n let matches = false;\n try {\n matches = canonicalize(inputValue) === canonicalize(termValue);\n } catch {\n matches = false;\n }\n if (!matches) {\n throw new MediaBuyLifecycleCompatibilityError({\n operation: 'acceptProposal',\n negotiatedVersion: this.negotiated_version,\n lifecycle,\n feature: field,\n code: 'PROPOSAL_DIGEST_MISMATCH',\n message: `Acceptance field ${field} conflicts with the digest-bound seller terms. No mutation was sent.`,\n });\n }\n }\n return termValue;\n };\n const totalBudget = resolvedAcceptanceField('total_budget');\n const dailyBudgetCap = resolvedAcceptanceField('daily_budget_cap');\n const budgetCapTimezone = resolvedAcceptanceField('budget_cap_timezone');\n const purchaseOrderRef = resolvedAcceptanceField('purchase_order_ref');\n if (\n !isCompactRelease(this.negotiated_version) &&\n [dailyBudgetCap, budgetCapTimezone].some(value => value !== undefined)\n ) {\n throw this.unsupported(\n 'acceptProposal',\n 'commercial_terms.daily_budget_cap,budget_cap_timezone',\n `The negotiated ${this.negotiated_version} create_media_buy schema cannot represent compact budget-cap terms. No mutation was sent.`\n );\n }\n const fallback = record(input.established_fallback);\n const brand = terms.brand ?? fallback.brand;\n const startTime = terms.start_time ?? fallback.start_time;\n const endTime = terms.end_time ?? fallback.end_time;\n if (!brand || !startTime || !endTime) {\n throw this.unsupported(\n 'acceptProposal',\n 'established_fallback',\n 'The proposal does not carry compact commercial terms. Supply established_fallback with the original brand and flight.'\n );\n }\n this.assertLegacyReferenceShapes('acceptProposal', { brand });\n if (\n input.idempotency_key !== undefined &&\n (typeof input.idempotency_key !== 'string' || !isValidIdempotencyKey(input.idempotency_key))\n ) {\n throw this.unsupported(\n 'acceptProposal',\n 'idempotency_key',\n 'Established proposal acceptance requires a 16-255 character protocol idempotency key. No mutation was sent.'\n );\n }\n const callerIdempotencyKey = optionalString(input.idempotency_key);\n const acceptanceIdempotencyKey = retryableAcceptance\n ? (callerIdempotencyKey ?? retryableAcceptance.idempotencyKey)\n : (callerIdempotencyKey ?? (!options?.skipIdempotencyAutoInject ? generateIdempotencyKey() : undefined));\n const request: MutatingRequestInput<CanonicalCreateMediaBuyRequest> = {\n account: input.account as CanonicalCreateMediaBuyRequest['account'],\n brand: brand as CanonicalCreateMediaBuyRequest['brand'],\n start_time: startTime as CanonicalCreateMediaBuyRequest['start_time'],\n end_time: endTime as CanonicalCreateMediaBuyRequest['end_time'],\n proposal_id: proposalId,\n ...(acceptanceIdempotencyKey !== undefined && { idempotency_key: acceptanceIdempotencyKey }),\n ...(totalBudget !== undefined && {\n total_budget: totalBudget as CanonicalCreateMediaBuyRequest['total_budget'],\n }),\n ...(dailyBudgetCap !== undefined && { daily_budget_cap: dailyBudgetCap as number }),\n ...(budgetCapTimezone !== undefined && { budget_cap_timezone: budgetCapTimezone as string }),\n ...(purchaseOrderRef !== undefined && { po_number: purchaseOrderRef as string }),\n ...(input.io_acceptance !== undefined && {\n io_acceptance: input.io_acceptance as CanonicalCreateMediaBuyRequest['io_acceptance'],\n }),\n ...(input.governance_context !== undefined && { governance_context: input.governance_context as string }),\n ...(input.opportunity !== undefined && {\n opportunity: input.opportunity as CanonicalCreateMediaBuyRequest['opportunity'],\n }),\n ...(input.reporting_webhook !== undefined && {\n reporting_webhook: input.reporting_webhook as CanonicalCreateMediaBuyRequest['reporting_webhook'],\n }),\n ...(input.push_notification_config !== undefined && {\n push_notification_config:\n input.push_notification_config as CanonicalCreateMediaBuyRequest['push_notification_config'],\n }),\n ...(input.context !== undefined && { context: input.context as CanonicalCreateMediaBuyRequest['context'] }),\n };\n const fingerprint = requestFingerprint(request);\n if (retryableAcceptance && fingerprint !== retryableAcceptance.requestFingerprint) {\n throw this.unsupported(\n 'acceptProposal',\n 'proposal_acceptance_retry',\n 'A paused established acceptance must retry the exact same request and idempotency key. No mutation was sent.'\n );\n }\n if (retryableAcceptance) this.assertAcceptanceRetryWindow(snapshotKey!, snapshot, retryableAcceptance);\n if (retryableAcceptance?.taskId) {\n this.forgetAcceptanceTask(retryableAcceptance.taskId, retryableAcceptance);\n }\n if (retryableAcceptance) this.releaseAcceptanceOwnership(retryableAcceptance);\n const retryDeadlineMs =\n retryableAcceptance?.retryDeadlineMs ??\n (this.idempotencyReplayTtlMs !== undefined ? Date.now() + this.idempotencyReplayTtlMs : undefined);\n // Acceptance is one-shot even though the established seller has no\n // compact proposal state transition. The in-map reservation prevents\n // concurrent rediscovery from reauthorizing the proposal. Only an exact\n // paused retry can reuse it; ambiguous outcomes remain fail-closed.\n const reservation: AcceptanceReservation = {\n kind: 'established',\n state: 'in-flight',\n requestFingerprint: fingerprint,\n skipIdempotencyAutoInject:\n retryableAcceptance?.skipIdempotencyAutoInject ?? Boolean(options?.skipIdempotencyAutoInject),\n ...(acceptanceIdempotencyKey && { idempotencyKey: acceptanceIdempotencyKey }),\n };\n if (retryDeadlineMs !== undefined) {\n Object.defineProperty(reservation, 'retryDeadlineMs', {\n value: retryDeadlineMs,\n enumerable: true,\n writable: false,\n configurable: false,\n });\n }\n snapshot.executable = false;\n snapshot.acceptance = reservation;\n this.proposalSnapshotStore.proposalAcceptances.set(proposalId, {\n snapshotKey: snapshotKey!,\n snapshot,\n reservation,\n });\n this.ownedAcceptanceReservations.set(reservation, { snapshotKey: snapshotKey!, snapshot });\n acceptanceReservationOwners.set(reservation, this);\n const dispatchOptions = retryableAcceptance\n ? { ...options, skipIdempotencyAutoInject: retryableAcceptance.skipIdempotencyAutoInject }\n : options;\n let result: TaskResult<CreateMediaBuyResponse>;\n try {\n result = await this.agent.createMediaBuy(request, inputHandler, dispatchOptions);\n } catch (error) {\n this.preserveAmbiguousAcceptance(snapshotKey!, snapshot, reservation);\n throw error;\n }\n const transitioned = this.attachAcceptanceTransitions(result, snapshotKey!, snapshot, reservation);\n return this.adaptProjectedResult(\n transitioned,\n this.makeReport(lifecycle, ['create_media_buy'], losses, [\n 'The established seller accepted its ordinary proposal_id mutation without compact digest enforcement.',\n ...(losses.includes('proposal_terms_digest_unavailable')\n ? [\n 'The seller supplied no terms digest or immutable compact commercial-terms snapshot; none was synthesized.',\n ]\n : []),\n ]),\n data => data\n );\n }\n\n async controlMediaBuy(\n params: MutatingRequestInput<ControlMediaBuyRequest>,\n inputHandler?: InputHandler,\n options?: TaskOptions\n ): Promise<CompatibilityTaskResult<ControlMediaBuyResponse | UpdateMediaBuyResponse>> {\n this.assertActive('controlMediaBuy');\n const input = record(params);\n const lifecycle = this.selectLifecycle('control_media_buy');\n this.assertLegacyReferenceShapes('controlMediaBuy', input);\n const canceledControlConflicts = [\n 'name',\n 'paused',\n 'total_budget',\n 'daily_budget_cap',\n 'budget_cap_timezone',\n 'budget_allocation',\n 'pacing',\n 'bidding',\n 'packages',\n 'reporting_webhook',\n ];\n if (Object.hasOwn(input, 'canceled') && canceledControlConflicts.some(field => Object.hasOwn(input, field))) {\n throw this.unsupported(\n 'controlMediaBuy',\n 'canceled',\n 'Compact media-buy cancellation cannot be combined with other operational controls.'\n );\n }\n if (lifecycle === 'compact') {\n this.assertValidCompactRequest('control_media_buy', params, lifecycle, true);\n const result = await this.agent.controlMediaBuy(params, inputHandler, options);\n return this.adaptProjectedResult(result, this.makeReport(lifecycle, ['control_media_buy'], []), data => data);\n }\n\n this.assertOnlyFields('controlMediaBuy', input, CONTROL_MEDIA_BUY_FIELDS);\n this.assertLegacyReportingWebhook('controlMediaBuy', input.reporting_webhook);\n this.assertLegacyPushNotification('controlMediaBuy', input.push_notification_config);\n this.assertCompactWireFieldsAbsent('controlMediaBuy', input, [\n 'total_budget',\n 'daily_budget_cap',\n 'budget_cap_timezone',\n 'budget_allocation',\n 'pacing',\n 'bidding',\n 'governance_context',\n ]);\n if (!isCompactRelease(this.negotiated_version)) {\n this.assertCompactWireFieldsAbsent('controlMediaBuy', input, ['name']);\n }\n if (compareRelease(this.negotiated_version, '3.0') < 0) {\n this.assertCompactWireFieldsAbsent('controlMediaBuy', input, ['reporting_webhook']);\n }\n const losses: MediaBuyCompatibilityLoss[] = [];\n if (compareRelease(this.negotiated_version, '3.0') < 0) {\n if (Object.hasOwn(input, 'canceled') || Object.hasOwn(input, 'cancellation_reason')) {\n throw this.unsupported(\n 'controlMediaBuy',\n 'canceled,cancellation_reason',\n `The negotiated ${this.negotiated_version} update_media_buy request cannot represent cancellation.`\n );\n }\n losses.push('revision_not_atomic');\n this.requireAllowed('controlMediaBuy', losses);\n }\n if (\n input.account === undefined ||\n !optionalString(input.media_buy_id) ||\n !Number.isInteger(input.revision) ||\n (input.revision as number) < 1\n ) {\n throw this.unsupported(\n 'controlMediaBuy',\n 'account/media_buy_id/revision',\n 'Legacy media-buy control requires a real account, media_buy_id, and positive compact revision.'\n );\n }\n if (input.ext !== undefined) {\n throw this.unsupported(\n 'controlMediaBuy',\n 'ext',\n 'Compact control_media_buy.ext has no declared legacy projection.'\n );\n }\n let packages: CanonicalUpdateMediaBuyRequest['packages'] | undefined;\n if (input.packages !== undefined) {\n if (!Array.isArray(input.packages) || input.packages.length === 0) {\n throw this.unsupported(\n 'controlMediaBuy',\n 'packages',\n 'Compact package controls must be a non-empty array when provided.'\n );\n }\n const packageControlFields = new Set([\n 'package_id',\n 'bidding',\n 'budget',\n 'canceled',\n 'cancellation_reason',\n 'daily_budget_cap',\n 'impressions',\n 'keyword_targets_add',\n 'keyword_targets_remove',\n 'min_spend_target',\n 'negative_keywords_add',\n 'negative_keywords_remove',\n 'optimization_goals',\n 'pacing',\n 'paused',\n 'targeting_overlay',\n ]);\n packages = input.packages.map((value, index) => {\n const packageControl = record(value);\n this.assertCompactWireFieldsAbsent(`controlMediaBuy.packages[${index}]`, packageControl, [\n 'bidding',\n 'daily_budget_cap',\n 'min_spend_target',\n ]);\n if (compareRelease(this.negotiated_version, '3.0') < 0) {\n const v3OnlyFields = [\n 'canceled',\n 'cancellation_reason',\n 'keyword_targets_add',\n 'keyword_targets_remove',\n 'negative_keywords_add',\n 'negative_keywords_remove',\n 'optimization_goals',\n ].filter(field => Object.hasOwn(packageControl, field));\n if (v3OnlyFields.length > 0) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].${v3OnlyFields.join(',')}`,\n `The negotiated ${this.negotiated_version} package update cannot represent ${v3OnlyFields.join(\n ', '\n )}. No mutation was sent.`\n );\n }\n }\n if (!isCompactRelease(this.negotiated_version) && Object.hasOwn(packageControl, 'optimization_goals')) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].optimization_goals`,\n `The negotiated ${this.negotiated_version} optimization goal union cannot represent every compact vendor_metric goal. No mutation was sent.`\n );\n }\n if (!isCompactRelease(this.negotiated_version) && packageControl.budget === null) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].budget`,\n `The negotiated ${this.negotiated_version} package update cannot represent compact budget=null. No mutation was sent.`\n );\n }\n const unsupportedFields = Object.keys(packageControl).filter(key => !packageControlFields.has(key));\n if (unsupportedFields.length > 0) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].${unsupportedFields.join(',')}`,\n `Compact package control fields ${unsupportedFields.join(', ')} have no declared legacy projection.`\n );\n }\n if (!optionalString(packageControl.package_id)) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].package_id`,\n 'Every compact package control requires a real package_id.'\n );\n }\n this.assertLegacyTargetingOverlay(\n 'controlMediaBuy',\n packageControl.targeting_overlay,\n `packages[${index}].targeting_overlay`\n );\n if (packageControl.canceled !== undefined && packageControl.canceled !== true) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].canceled`,\n 'Compact package canceled may only be true when present.'\n );\n }\n if (Object.hasOwn(packageControl, 'cancellation_reason') && !Object.hasOwn(packageControl, 'canceled')) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].cancellation_reason`,\n 'Compact package cancellation_reason requires canceled=true.'\n );\n }\n const keywordDeltaFields = [\n 'keyword_targets_add',\n 'keyword_targets_remove',\n 'negative_keywords_add',\n 'negative_keywords_remove',\n ];\n if (!isCompactRelease(this.negotiated_version)) {\n for (const field of ['keyword_targets_remove', 'negative_keywords_add', 'negative_keywords_remove']) {\n for (const [itemIndex, item] of array(packageControl[field]).entries()) {\n if (Object.hasOwn(record(item), 'bid_price')) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].${field}[${itemIndex}].bid_price`,\n `The negotiated ${this.negotiated_version} ${field} item cannot represent compact bid_price. No mutation was sent.`\n );\n }\n }\n }\n }\n if (\n Object.hasOwn(packageControl, 'targeting_overlay') &&\n keywordDeltaFields.some(field => Object.hasOwn(packageControl, field))\n ) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].targeting_overlay`,\n 'Compact package targeting_overlay cannot be combined with keyword deltas.'\n );\n }\n const canceledPackageConflicts = [\n 'budget',\n 'daily_budget_cap',\n 'min_spend_target',\n 'impressions',\n 'pacing',\n 'bidding',\n 'paused',\n 'targeting_overlay',\n ...keywordDeltaFields,\n 'optimization_goals',\n ];\n if (\n Object.hasOwn(packageControl, 'canceled') &&\n canceledPackageConflicts.some(field => Object.hasOwn(packageControl, field))\n ) {\n throw this.unsupported(\n 'controlMediaBuy',\n `packages[${index}].canceled`,\n 'Compact package cancellation cannot be combined with other package controls.'\n );\n }\n return Object.fromEntries(\n Object.entries(packageControl).filter(([key]) => packageControlFields.has(key))\n ) as NonNullable<CanonicalUpdateMediaBuyRequest['packages']>[number];\n });\n }\n if (input.canceled !== undefined && input.canceled !== true) {\n throw this.unsupported(\n 'controlMediaBuy',\n 'canceled',\n 'Compact media-buy canceled may only be true when present.'\n );\n }\n if (Object.hasOwn(input, 'cancellation_reason') && !Object.hasOwn(input, 'canceled')) {\n throw this.unsupported(\n 'controlMediaBuy',\n 'cancellation_reason',\n 'Compact media-buy cancellation_reason requires canceled=true.'\n );\n }\n const request: MutatingRequestInput<CanonicalUpdateMediaBuyRequest> = {\n account: input.account as CanonicalUpdateMediaBuyRequest['account'],\n media_buy_id: input.media_buy_id as string,\n ...(input.idempotency_key !== undefined && { idempotency_key: input.idempotency_key as string }),\n revision: input.revision as number,\n ...(input.name !== undefined && { name: input.name as string }),\n ...(input.paused !== undefined && { paused: input.paused as boolean }),\n ...(input.canceled !== undefined && { canceled: input.canceled as true }),\n ...(input.cancellation_reason !== undefined && { cancellation_reason: input.cancellation_reason as string }),\n ...(input.governance_context !== undefined && { governance_context: input.governance_context as string }),\n ...(input.total_budget !== undefined && {\n total_budget: input.total_budget as CanonicalUpdateMediaBuyRequest['total_budget'],\n }),\n ...(input.daily_budget_cap !== undefined && {\n daily_budget_cap: input.daily_budget_cap as CanonicalUpdateMediaBuyRequest['daily_budget_cap'],\n }),\n ...(input.budget_cap_timezone !== undefined && {\n budget_cap_timezone: input.budget_cap_timezone as CanonicalUpdateMediaBuyRequest['budget_cap_timezone'],\n }),\n ...(input.budget_allocation !== undefined && {\n budget_allocation: input.budget_allocation as CanonicalUpdateMediaBuyRequest['budget_allocation'],\n }),\n ...(input.pacing !== undefined && { pacing: input.pacing as CanonicalUpdateMediaBuyRequest['pacing'] }),\n ...(input.bidding !== undefined && { bidding: input.bidding as CanonicalUpdateMediaBuyRequest['bidding'] }),\n ...(packages !== undefined && { packages }),\n ...(input.reporting_webhook !== undefined && {\n reporting_webhook: input.reporting_webhook as CanonicalUpdateMediaBuyRequest['reporting_webhook'],\n }),\n ...(input.push_notification_config !== undefined && {\n push_notification_config:\n input.push_notification_config as CanonicalUpdateMediaBuyRequest['push_notification_config'],\n }),\n ...(input.context !== undefined && { context: input.context as CanonicalUpdateMediaBuyRequest['context'] }),\n };\n this.assertValidCompactRequest('control_media_buy', params, lifecycle, true);\n const result = await this.agent.updateMediaBuy(request, inputHandler, options);\n return this.adaptProjectedResult(\n result,\n this.makeReport(\n lifecycle,\n ['update_media_buy'],\n losses,\n losses.length ? ['The v2.5 update cannot atomically enforce the compact revision token.'] : []\n ),\n data => data\n );\n }\n\n async getMediaBuys(\n params: GetMediaBuysRequest,\n inputHandler?: InputHandler,\n options?: TaskOptions\n ): Promise<CompatibilityTaskResult<GetMediaBuysResponse>> {\n this.assertActive('getMediaBuys');\n if (compareRelease(this.negotiated_version, '3.0') < 0) {\n throw this.unsupported(\n 'getMediaBuys',\n 'media_buy_readback',\n `The negotiated ${this.negotiated_version} seller has no get_media_buys tool.`\n );\n }\n this.assertSharedToolAdvertised('get_media_buys');\n const input = record(params);\n this.assertLegacyReferenceShapes('getMediaBuys', input);\n if (compareRelease(this.negotiated_version, '3.1') < 0) {\n this.assertCompactWireFieldsAbsent('getMediaBuys', input, ['include_webhook_activity', 'webhook_activity_limit']);\n }\n if (!isCompactRelease(this.negotiated_version)) {\n this.assertCompactWireFieldsAbsent('getMediaBuys', input, ['indicator_types']);\n }\n const result = await this.agent.getMediaBuys(params, inputHandler, options);\n return this.adaptProjectedResult(result, this.makeReport(this.lifecycle, ['get_media_buys'], []), data => data);\n }\n\n async getMediaBuyDelivery(\n params: GetMediaBuyDeliveryRequest,\n inputHandler?: InputHandler,\n options?: TaskOptions\n ): Promise<CompatibilityTaskResult<GetMediaBuyDeliveryResponse>> {\n this.assertActive('getMediaBuyDelivery');\n if (compareRelease(this.negotiated_version, '3.0') < 0) {\n throw this.unsupported(\n 'getMediaBuyDelivery',\n 'media_buy_delivery_readback',\n `The negotiated ${this.negotiated_version} delivery request cannot safely represent the compact account-scoped readback.`\n );\n }\n this.assertSharedToolAdvertised('get_media_buy_delivery');\n const input = record(params);\n if (compareRelease(this.negotiated_version, '3.1') < 0) {\n this.assertCompactWireFieldsAbsent('getMediaBuyDelivery', input, [\n 'include_window_breakdown',\n 'time_granularity',\n ]);\n } else if (\n !isCompactRelease(this.negotiated_version) &&\n input.time_granularity !== undefined &&\n !V31_TIME_GRANULARITIES.has(String(input.time_granularity))\n ) {\n throw this.unsupported(\n 'getMediaBuyDelivery',\n 'time_granularity',\n `The negotiated ${this.negotiated_version} delivery request cannot represent compact time granularity ${String(input.time_granularity)}. No request was sent.`\n );\n }\n this.assertLegacyReportingDimensions('getMediaBuyDelivery', input.reporting_dimensions);\n this.assertLegacyReferenceShapes('getMediaBuyDelivery', input);\n const result = await this.agent.getMediaBuyDelivery(params, inputHandler, options);\n return this.adaptProjectedResult(\n result,\n this.makeReport(this.lifecycle, ['get_media_buy_delivery'], []),\n data => data\n );\n }\n}\n\nexport function negotiateMediaBuyLifecycle(\n agent: AgentClient,\n options: MediaBuyLifecycleCoordinatorOptions = {}\n): Promise<MediaBuyLifecycleCoordinator> {\n return MediaBuyLifecycleCoordinator.negotiate(agent, options);\n}\n"],"mappings":"AAAA,SAAS,YAAY,mBAAmB;AAYxC,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB,6BAAwD;AACzF,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB,4BAA4B;AAC3D,SAAS,8CAAqE;AAC9E,SAAS,4BAA4B;AAmCrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,kBAAkB,uBAAuB,oBAAoB,uBAAuB;AAC7F,SAAS,cAAc,wBAAwB;AAC/C,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,OASK;AAaP,MAAM,uBAAuB,oBAAI,IAAI;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;A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;AAAA,QACT;AAAA,QACA;AAAA,QACA,kBAAkB,KAAK,kBAAkB;AAAA,MAC3C;AAAA,IACF;AACA,SAAK,2BAA2B,wBAAwB;AACxD,UAAM,QAAQ,OAAO,MAAM;AAC3B,QAAI,eAAe,KAAK,oBAAoB,KAAK,IAAI,GAAG;AACtD,WAAK,8BAA8B,uBAAuB,OAAO;AAAA,QAC/D;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH,WACE,CAAC,iBAAiB,KAAK,kBAAkB,KACzC,MAAM,qBAAqB,UAC3B,CAAC,uBAAuB,IAAI,OAAO,MAAM,gBAAgB,CAAC,GAC1D;AACA,YAAM,KAAK;AAAA,QACT;AAAA,QACA;AAAA,QACA,kBAAkB,KAAK,kBAAkB,+DAA+D,OAAO,MAAM,gBAAgB,CAAC;AAAA,MACxI;AAAA,IACF;AACA,SAAK,gCAAgC,uBAAuB,MAAM,oBAAoB;AACtF,SAAK,4BAA4B,uBAAuB,KAAK;AAC7D,UAAM,SAAS,MAAM,KAAK,MAAM,oBAAoB,QAAQ,cAAc,OAAO;AACjF,WAAO,KAAK;AAAA,MACV;AAAA,MACA,KAAK,WAAW,KAAK,WAAW,CAAC,wBAAwB,GAAG,CAAC,CAAC;AAAA,MAC9D,UAAQ;AAAA,IACV;AAAA,EACF;AACF;AAEO,SAAS,2BACd,OACA,UAA+C,CAAC,GACT;AACvC,SAAO,6BAA6B,UAAU,OAAO,OAAO;AAC9D;","names":["negotiatedVersion","entry","result","accountScope","state","proposalIds","retry","identity","request","scopes","pendingRefinement","attemptEpoch","dispatchOptions","projectOnly","projectAndSettle","pendingDecline","proposalId","fingerprint","snapshotKey","snapshot","retryDeadlineMs","reservation","transitioned"]}