From bdfcf63a35144ad2c95b1b49afbdf8890bf09d31 Mon Sep 17 00:00:00 2001 From: Brian O'Kelley Date: Mon, 14 Sep 2026 14:36:04 +0000 Subject: [PATCH 1/3] feat(protocol): adopt AdCP 3.2.0-rc.3 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bump ADCP_VERSION and the default wire pin to 3.2.0-rc.3, resync the signed schema and compliance bundles, and regenerate every derived surface (core/tools/enums/inline-enums/manifest/schemas, wire-spec fields, entity hydration, media-buy update fields, agent docs, TYPE-SUMMARY). The bundle swap is not purely mechanical in one place. The hand-written Zod parity block in scripts/generate-zod-from-ts.ts encodes the context-sensitive consumer-status constraints that the JSON Schema -> TS -> Zod projection drops, and it was written against rc.2. Left alone, the rc.3 pin would have produced a validator that rejects `mismatch_code` as an unrecognized key while accepting a `content_mismatch` statement with no code at all — exactly backwards. The block now covers the rc.3 arm: `content_mismatch` requires the obligation id, the revision id, the recomputed `observed_revision_content_sha256`, and `mismatch_code`, and forbids `failure_code`; the four pre-existing statuses additionally forbid `mismatch_code`. The differential test in test/generate-zod-consumer-status.test.js gains six cases pinning generated-Zod against the published schema for that arm. `ReportingLedgerConsumerStatementV1` gains `content_mismatch` and the closed `mismatch_code` so the ledger types can carry what the wire now accepts. The projection semantics (severity, grace window, escalation, obligation counts) are deliberately not in this commit. rc.3 also publishes core/media-buy-available-action-id.json, so the generated update dispatch table gains the structured-only `update_media_buy_frequency_cap` action and its `frequency_cap` binding. Media-buy preflight already resolved that binding from the generated table rather than hardcoding it, so the shared media-buy frequency cap becomes dispatchable with no adopter change. 3.2 prereleases stay exact pins: rc.3 replaces rc.2 in COMPATIBLE_ADCP_VERSIONS and only the current prerelease's bundle ships. `adcpVersion: '3.2-rc'` follows whichever release candidate a build carries; a superseded exact pin raises a configuration error at schema load rather than silently validating against a different contract. Co-Authored-By: Claude Opus 5 (1M context) --- .changeset/adopt-adcp-rc-three.md | 25 + ADCP_VERSION | 2 +- docs/TYPE-SUMMARY.md | 14 +- docs/development/WIRE-VERSION-COMPAT.md | 4 +- docs/guides/MEDIA-BUY-3.2-COMPATIBILITY.md | 6 +- docs/guides/REPORTING-LEDGER.md | 2 +- docs/llms.txt | 26 +- docs/migration-12-to-14.md | 2 +- docs/migration-13-to-14.md | 16 +- package.json | 2 +- scripts/check-package-size.mjs | 2 +- scripts/generate-agent-docs.ts | 2 +- scripts/verify-package.mjs | 6 +- src/lib/media-buy/update-fields.generated.ts | 10 +- .../runtime/entity-hydration.generated.ts | 2 +- src/lib/server/wire-spec-fields.generated.ts | 72 +- src/lib/types/core.generated.ts | 1695 +++-- src/lib/types/enums.generated.ts | 6 +- src/lib/types/inline-enums.generated.ts | 27 +- src/lib/types/manifest.generated.ts | 10 +- src/lib/types/schemas.generated.ts | 6579 +++++++++-------- src/lib/types/tools.generated.ts | 1646 ++++- src/lib/version.ts | 10 +- test/capabilities-overrides.test.js | 2 +- ...ello-seller-adapter-non-guaranteed.test.js | 14 +- .../consumer-status.json | 2 +- .../reporting-reconciliation/fixture.json | 2 +- test/generate-zod-consumer-status.test.js | 2 +- test/lib/adcp-major-version.test.js | 6 +- test/lib/beta6-reporting-version.test.js | 2 +- .../lib/capability-probe-operation-id.test.js | 4 +- test/lib/cli-storyboard-file-flag.test.js | 4 +- .../cli-test-kit-compliance-version.test.js | 4 +- test/lib/compact-commitment-cli.test.js | 4 +- ...ompact-lifecycle-storyboard-runner.test.js | 4 +- test/lib/conformance-arbitrary.test.js | 10 +- test/lib/conformance-seeder.test.js | 6 +- test/lib/functional-request-signing.test.js | 12 +- test/lib/get-signals-pre31-wholesale.test.js | 2 +- test/lib/mcp-modern-negotiation.test.js | 10 +- .../media-buy-lifecycle-compatibility.test.js | 38 +- .../media-buy-lifecycle-coordinator.test.js | 34 +- .../media-buy-lifecycle-release-gate.test.js | 20 +- test/lib/preview-creative-client.test.js | 2 +- test/lib/proposal-manager-e2e.test.js | 10 +- test/lib/proposal-negotiation-server.test.js | 18 +- .../proposal-negotiation-validation.test.js | 8 +- test/lib/proposal-negotiation.test.js | 8 +- ...reporting-consumer-status-fixtures.test.js | 2 +- test/lib/reporting-ledger.test.js | 24 +- test/lib/request-validation.test.js | 4 +- test/lib/schema-validation.test.js | 8 +- ...board-schema-invalid-negative-path.test.js | 4 +- test/lib/storyboard-security.test.js | 2 +- test/lib/storyboard-task-map-error.test.js | 4 +- .../lib/task-executor-operation-error.test.js | 2 +- test/lib/v2-getproducts-autowire.test.js | 4 +- test/lib/version-sync.test.js | 6 +- test/lib/versioned-tool-schemas.test.js | 6 +- test/server-a2a-adapter.test.js | 8 +- test/server-create-adcp-server.test.js | 60 +- test/server-decisioning-comply-gate.test.js | 2 +- test/server-decisioning-from-platform.test.js | 48 +- 63 files changed, 6334 insertions(+), 4244 deletions(-) create mode 100644 .changeset/adopt-adcp-rc-three.md diff --git a/.changeset/adopt-adcp-rc-three.md b/.changeset/adopt-adcp-rc-three.md new file mode 100644 index 000000000..4edee341e --- /dev/null +++ b/.changeset/adopt-adcp-rc-three.md @@ -0,0 +1,25 @@ +--- +'@adcp/sdk': minor +--- + +Adopt the signed AdCP 3.2.0-rc.3 schema and compliance bundles as the default wire release. + +Moving the pin activates the `content_mismatch` consumer status and its closed +`mismatch_code` across the published `ReportingConsumerStatusSchema` / +`SyncReportingStatusRequestSchema` exports and the seller ledger's consumer-status types. +The machinery that keeps those two in step with the bundle landed separately in #2911, +which derives both the ledger statement type and the Zod conditional arms from the pinned +schema; this pin is what supplies the rc.3 arms it reads. Verified: the regenerated +validator requires the obligation id, the revision id, the recomputed +`observed_revision_content_sha256`, and `mismatch_code` for `content_mismatch`, forbids +`failure_code` there, and forbids `mismatch_code` on the four pre-existing statuses. + +rc.3 also publishes `core/media-buy-available-action-id.json`, so the generated +`update_media_buy` dispatch table gains the structured-only +`update_media_buy_frequency_cap` action and its `frequency_cap` field binding. Media-buy +preflight already resolved that binding from the generated table, so the shared +media-buy frequency cap becomes dispatchable with no adopter change. + +3.2 prereleases remain exact pins: rc.3 replaces rc.2 in `COMPATIBLE_ADCP_VERSIONS` and +only the current prerelease's schema bundle ships. Pin `adcpVersion: '3.2-rc'` to follow +whichever 3.2 release candidate a given SDK build carries. diff --git a/ADCP_VERSION b/ADCP_VERSION index 7d2dc0792..31caa1c89 100644 --- a/ADCP_VERSION +++ b/ADCP_VERSION @@ -1 +1 @@ -3.2.0-rc.2 +3.2.0-rc.3 diff --git a/docs/TYPE-SUMMARY.md b/docs/TYPE-SUMMARY.md index 6e3ddb0c0..b633fd15c 100644 --- a/docs/TYPE-SUMMARY.md +++ b/docs/TYPE-SUMMARY.md @@ -754,9 +754,11 @@ _Request:_ preferred_delivery_types: Delivery Type[] filters: Product Filters targeting_overlay: Targeting + media_buy_frequency_cap: Media Buy Frequency Cap required_overlay_support: Targeting Overlay Requirements + required_media_buy_support: Media Buy Support Requirements property_list: Property List Ref - fields: ('product_id' | 'name' | 'description' | 'publisher_properties' | 'channels' | 'video_placement_types' | 'audio_distribution_types' | 'sponsored_placement_types' | 'social_placement_surfaces' | 'format_options' | 'placements' | 'delivery_type' | 'exclusivity' | 'pricing_options' | 'forecast' | 'reporting_capabilities' | 'measurement_terms' | 'performance_standards' | 'catalog_types' | 'signal_targeting_allowed' | 'signal_targeting_rules' | 'demographic_targeting' | 'audience_evidence' | 'audience_evidence_selections' | 'max_optimization_goals' | 'catalog_match' | 'list_applications' | 'brief_relevance' | 'acceptance_policy_profile_ids' | 'identity' | 'expires_at' | 'allowed_actions' | 'format_ids' | 'outcome_measurement' | 'delivery_measurement' | 'creative_policy' | 'metric_optimization' | 'conversion_tracking' | 'data_provider_signals' | 'included_signals' | 'signal_targeting_options' | 'overlay_support' | 'targeting_resolution' | 'collections' | 'collection_targeting_allowed' | 'installments' | 'is_custom' | 'product_card' | 'product_card_detailed' | 'enforced_policies' | 'trusted_match')[] + fields: ('product_id' | 'name' | 'description' | 'publisher_properties' | 'channels' | 'video_placement_types' | 'audio_distribution_types' | 'sponsored_placement_types' | 'social_placement_surfaces' | 'format_options' | 'placements' | 'delivery_type' | 'exclusivity' | 'pricing_options' | 'forecast' | 'reporting_capabilities' | 'measurement_terms' | 'performance_standards' | 'catalog_types' | 'signal_targeting_allowed' | 'signal_targeting_rules' | 'demographic_targeting' | 'overlay_support' | 'media_buy_support' | 'audience_evidence' | 'audience_evidence_selections' | 'max_optimization_goals' | 'catalog_match' | 'list_applications' | 'brief_relevance' | 'acceptance_policy_profile_ids' | 'identity' | 'expires_at' | 'allowed_actions' | 'format_ids' | 'outcome_measurement' | 'delivery_measurement' | 'creative_policy' | 'metric_optimization' | 'conversion_tracking' | 'data_provider_signals' | 'included_signals' | 'signal_targeting_options' | 'overlay_support' | 'media_buy_support' | 'targeting_resolution' | 'collections' | 'collection_targeting_allowed' | 'installments' | 'is_custom' | 'product_card' | 'product_card_detailed' | 'enforced_policies' | 'trusted_match')[] time_budget: Duration push_notification_config: Push Notification Config pagination: Pagination Request @@ -943,7 +945,7 @@ _Request:_ idempotency_key: string // required account: Canonical Account Ref // required feed_version: string // required - purchases: Product Purchase[] // required + purchases: Product Purchase Input[] // required start_time: Start Timing // required end_time: string // required adcp_version: string @@ -952,6 +954,7 @@ _Request:_ pricing_version: string total_budget: object daily_budget_cap: number + frequency_cap: Media Buy Frequency Cap budget_cap_timezone: string budget_allocation: Canonical Budget Allocation pacing: Pacing @@ -1013,6 +1016,7 @@ _Request:_ cancellation_reason: string total_budget: object daily_budget_cap: number,null + frequency_cap: Media Buy Frequency Cap | null budget_cap_timezone: string,null budget_allocation: Canonical Budget Allocation pacing: Pacing @@ -1104,6 +1108,7 @@ _Request:_ opportunity: Opportunity Context total_budget: object daily_budget_cap: number + frequency_cap: Media Buy Frequency Cap budget_cap_timezone: string budget_allocation: Budget Allocation packages: Package Request[] @@ -1139,6 +1144,7 @@ _Response (success branch):_ currency: string total_budget: number daily_budget_cap: number + frequency_cap: Media Buy Frequency Cap budget_cap_timezone: string budget_allocation: Budget Allocation pacing: Pacing @@ -1175,6 +1181,7 @@ _Request:_ end_time: string total_budget: object daily_budget_cap: number,null + frequency_cap: Media Buy Frequency Cap | null budget_cap_timezone: string,null budget_allocation: Budget Allocation pacing: Pacing @@ -1198,6 +1205,7 @@ _Response (success branch):_ currency: string total_budget: number daily_budget_cap: number + frequency_cap: Media Buy Frequency Cap budget_cap_timezone: string budget_allocation: Budget Allocation pacing: Pacing @@ -2787,7 +2795,7 @@ await producer.runWorker(); const getReportingStatus = createReportingStatusHandler(store); const getMediaBuyDelivery = createReportingDeliveryHandler(store); // exact reporting_revision_id reads -// AdCP 3.2.0-rc.2: identity comes from authenticated transport. +// AdCP 3.2.0-rc.3: identity comes from authenticated transport. const syncReportingStatus = createSyncReportingStatusHandler(store, { resolveConsumerId: context => context.agent.agent_url, }); diff --git a/docs/development/WIRE-VERSION-COMPAT.md b/docs/development/WIRE-VERSION-COMPAT.md index c08b82efd..86beb69f7 100644 --- a/docs/development/WIRE-VERSION-COMPAT.md +++ b/docs/development/WIRE-VERSION-COMPAT.md @@ -7,7 +7,7 @@ How `@adcp/sdk` keeps a buyer pinned to one AdCP major version while talking to ## The shape of the problem The SDK speaks one primary AdCP version on its public surface — `ADCP_VERSION` -in `src/lib/version.ts`. The SDK 14 prerelease pin is `3.2.0-rc.2`; maintained side +in `src/lib/version.ts`. The SDK 14 prerelease pin is `3.2.0-rc.3`; maintained side bundles cover `3.1.18`, `3.0.25`, and v2.5. Every buyer-facing type, helper, and example assumes the primary pin. @@ -27,7 +27,7 @@ There is exactly one active legacy compat layer at a time today: `legacy/v2-5/`. ``` schemas/cache/ -├── 3.2.0-rc.2/ # current SDK pin +├── 3.2.0-rc.3/ # current SDK pin ├── 3.1.18/ # maintained stable side bundle ├── 3.0.25/ # maintained stable side bundle ├── latest/ # symlink to the primary pin diff --git a/docs/guides/MEDIA-BUY-3.2-COMPATIBILITY.md b/docs/guides/MEDIA-BUY-3.2-COMPATIBILITY.md index 96820b167..f40675690 100644 --- a/docs/guides/MEDIA-BUY-3.2-COMPATIBILITY.md +++ b/docs/guides/MEDIA-BUY-3.2-COMPATIBILITY.md @@ -5,7 +5,7 @@ routes it can still **call**. A 3.2 seller should make the compact lifecycle the obvious path for new buyers without breaking a 3.0 or 3.1 buyer that already calls the established names. -The SDK is pinned to the signed `3.2.0-rc.2` bundle. It retains the converged +The SDK is pinned to the signed `3.2.0-rc.3` bundle. It retains the converged RC.0 product-identity, daypart-timezone, and flat-rate loop-position and slot-span surface, and adds the Reliable Reporting 1.0 core, managed-delivery, and reconciled-billing schema contracts. Beta.5 introduced the normative async identity, @@ -77,10 +77,10 @@ createAdcpServerFromPlatform(platform, { name: 'seller', version: '1.0.0', // `adcpVersion` is the newest release explicit callers may select. - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', // Keep callers that omit a version on the established 3.1 contract. defaultAdcpVersion: '3.1.18', - capabilities: { supported_versions: ['3.1.18', '3.2.0-rc.2'] }, + capabilities: { supported_versions: ['3.1.18', '3.2.0-rc.3'] }, }); ``` diff --git a/docs/guides/REPORTING-LEDGER.md b/docs/guides/REPORTING-LEDGER.md index 81e14da35..a497044a0 100644 --- a/docs/guides/REPORTING-LEDGER.md +++ b/docs/guides/REPORTING-LEDGER.md @@ -51,7 +51,7 @@ When `get_reporting_status` omits a period, the operational default horizon is t ## Consumer status ingest -The SDK is pinned to AdCP 3.2.0-rc.2 and exposes `sync_reporting_status` from the ledger subpath. Its request, response, consumer-status, obligation, issue, delivery-capabilities, and reporting-status types come from the published rc.2 schema bundle. +The SDK is pinned to AdCP 3.2.0-rc.3 and exposes `sync_reporting_status` from the ledger subpath. Its request, response, consumer-status, obligation, issue, delivery-capabilities, and reporting-status types come from the published rc.3 schema bundle. ```ts const syncReportingStatus = createSyncReportingStatusHandler(store, { diff --git a/docs/llms.txt b/docs/llms.txt index dca24913b..2fd6679f3 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -440,7 +440,7 @@ AdCP 3. **Request:** - Required: `buying_mode: 'brief' | 'wholesale' | 'refine'` -- Optional: `idempotency_key: string`, `brief: string`, `refine: object[]`, `brand: Brand Ref`, `acceptance_context: Acceptance Context`, `catalog: Catalog`, `account: Account Ref`, `preferred_delivery_types: Delivery Type[]`, +12 more +- Optional: `idempotency_key: string`, `brief: string`, `refine: object[]`, `brand: Brand Ref`, `acceptance_context: Acceptance Context`, `catalog: Catalog`, `account: Account Ref`, `preferred_delivery_types: Delivery Type[]`, +14 more **Response (success branch):** - Optional: `products: Product[]`, `targeting_resolution: Get Products Targeting Resolution`, `extensions: object`, `proposals: Proposal[]`, `errors: Error[]`, `reason: string`, `suggestions: string[]`, `property_list_applied: boolean`, +11 more @@ -501,8 +501,8 @@ Request parameters for terminally declining one or more proposals. Create a MediaBuy directly from canonical published product offers. **Request:** -- Required: `idempotency_key: string`, `account: Canonical Account Ref`, `feed_version: string`, `purchases: Product Purchase[]`, `start_time: Start Timing`, `end_time: string` -- Optional: `adcp_version: string`, `brand: Brand Key`, `advertiser_industry: Advertiser Industry`, `pricing_version: string`, `total_budget: object`, `daily_budget_cap: number`, `budget_cap_timezone: string`, `budget_allocation: Canonical Budget Allocation`, +11 more +- Required: `idempotency_key: string`, `account: Canonical Account Ref`, `feed_version: string`, `purchases: Product Purchase Input[]`, `start_time: Start Timing`, `end_time: string` +- Optional: `adcp_version: string`, `brand: Brand Key`, `advertiser_industry: Advertiser Industry`, `pricing_version: string`, `total_budget: object`, `daily_budget_cap: number`, `frequency_cap: Media Buy Frequency Cap`, `budget_cap_timezone: string`, +12 more #### `accept_proposal` @@ -518,7 +518,7 @@ Apply operational controls inside accepted commercial terms. **Request:** - Required: `idempotency_key: string`, `account: Canonical Account Ref`, `media_buy_id: string`, `revision: integer` -- Optional: `adcp_version: string`, `name: string`, `paused: boolean`, `canceled: 'true'`, `cancellation_reason: string`, `total_budget: object`, `daily_budget_cap: number,null`, `budget_cap_timezone: string,null`, +8 more +- Optional: `adcp_version: string`, `name: string`, `paused: boolean`, `canceled: 'true'`, `cancellation_reason: string`, `total_budget: object`, `daily_budget_cap: number,null`, `frequency_cap: Media Buy Frequency Cap | null`, +9 more **Response (success branch):** - Required: `status: 'completed'`, `media_buy_id: string`, `revision: integer` @@ -546,11 +546,11 @@ AdCP 3. **Request:** - Required: `idempotency_key: string`, `account: Account Ref`, `brand: Brand Ref`, `start_time: Start Timing`, `end_time: string` -- Optional: `governance_context: string`, `plan_id: string`, `proposal_id: string`, `opportunity: Opportunity Context`, `total_budget: object`, `daily_budget_cap: number`, `budget_cap_timezone: string`, `budget_allocation: Budget Allocation`, +14 more +- Optional: `governance_context: string`, `plan_id: string`, `proposal_id: string`, `opportunity: Opportunity Context`, `total_budget: object`, `daily_budget_cap: number`, `frequency_cap: Media Buy Frequency Cap`, `budget_cap_timezone: string`, +15 more **Response (success branch):** - Required: `media_buy_id: string`, `confirmed_at: string,null`, `revision: integer`, `packages: Package[]` -- Optional: `proposal_id: string`, `name: string`, `account: Account`, `invoice_recipient: Business Entity`, `media_buy_status: Media Buy Status`, `creative_deadline: string`, `currency: string`, `total_budget: number`, +11 more +- Optional: `proposal_id: string`, `name: string`, `account: Account`, `invoice_recipient: Business Entity`, `media_buy_status: Media Buy Status`, `creative_deadline: string`, `currency: string`, `total_budget: number`, +12 more **Watch out:** - Server handlers should return business lifecycle state as `media_buy_status`. The framework owns the task envelope `status`; do not return top-level `status` as the media-buy state. @@ -561,11 +561,11 @@ AdCP 3. **Request:** - Required: `account: Account Ref`, `media_buy_id: string`, `idempotency_key: string` -- Optional: `governance_context: string`, `name: string`, `revision: integer`, `paused: boolean`, `canceled: 'true'`, `cancellation_reason: string`, `start_time: Start Timing`, `end_time: string`, +12 more +- Optional: `governance_context: string`, `name: string`, `revision: integer`, `paused: boolean`, `canceled: 'true'`, `cancellation_reason: string`, `start_time: Start Timing`, `end_time: string`, +13 more **Response (success branch):** - Required: `media_buy_id: string`, `revision: integer` -- Optional: `name: string`, `media_buy_status: Media Buy Status`, `currency: string`, `total_budget: number`, `daily_budget_cap: number`, `budget_cap_timezone: string`, `budget_allocation: Budget Allocation`, `pacing: Pacing`, +9 more +- Optional: `name: string`, `media_buy_status: Media Buy Status`, `currency: string`, `total_budget: number`, `daily_budget_cap: number`, `frequency_cap: Media Buy Frequency Cap`, `budget_cap_timezone: string`, `budget_allocation: Budget Allocation`, +10 more **Watch out:** - Server handlers should return business lifecycle state as `media_buy_status`. The framework owns the task envelope `status`; do not return top-level `status` as the media-buy state. @@ -1420,6 +1420,9 @@ Flow: `comply_test_controller → request_proposals → refine_proposals → com **Seller binds an external audience source into a targetable audience** — Verifies dataset-source ingestion, discovery echo, media-buy targeting, unsupported-rail rejection, and transport immutability. Flow: `sync_audiences → create_media_buy → sync_audiences` +**Package frequency-cap capability and update boundaries** — Verifies constrained discovery with seller-wide unit inheritance, create-only rejection, out-of-range rejection, mutable update, package-qualified actions, and exact readback. +Flow: `sync_accounts → get_products → create_media_buy → get_media_buys → control_media_buy → get_media_buys` + **Seller honors a package-level frequency cap and reports observed frequency at-or-below the cap** — Verifies that a seller advertising frequency_capping accepts a package-level frequency_cap (max_impressions + per + window form) on create_media_buy and, after simulated delivery, reports observed reach and frequency on get_media_buy_delivery with the observed frequency at-or-below the requested cap. Runtime-enforcement scenario — no rejection arm. Sellers without frequency_capping grade not_applicable. Flow: `sync_accounts → get_products → create_media_buy → comply_test_controller → get_media_buy_delivery` @@ -1474,6 +1477,9 @@ Flow: `get_products → create_media_buy` **Seller rejects unworkable measurement_terms** — Buyer proposes measurement_terms the seller will not accept; seller returns TERMS_REJECTED without being required to accept a different configuration. Flow: `get_products → create_media_buy` +**Seller accepts and reads back a MediaBuy frequency cap** — Verifies participation-gated discovery, incompatible-mix rejection, exact acceptance, and readback of a root cap across a two-product buy. +Flow: `sync_accounts → get_products → create_media_buy → get_media_buys` + **Seller solves for budget from a structured outcome target** — Verifies criteria.outcome_target reverse forecasting: a metric or event goal plus desired volume answered with total_budget_guidance on proposals and a forecast whose points carry the goal's key in metrics. Flow: `sync_accounts → request_proposals` @@ -1735,7 +1741,7 @@ Flow: `get_adcp_capabilities → create_property_list → list_property_lists` Flow: `get_adcp_capabilities → get_products → list_accounts → list_creative_formats → list_creatives → get_adcp_capabilities` **Reliable Reporting: consumer-status loop** — Validates opt-in buyer-to-seller reporting status, missing-obligation identity, caller-scoped mismatch, and immutable supersession. -Flow: `comply_test_controller → sync_reporting_status → get_reporting_status → comply_test_controller → sync_reporting_status → comply_test_controller → get_reporting_status → get_media_buy_delivery → sync_reporting_status → get_reporting_status → comply_test_controller → get_reporting_status → sync_reporting_status → get_reporting_status` +Flow: `comply_test_controller → sync_reporting_status → get_reporting_status → comply_test_controller → sync_reporting_status → comply_test_controller → get_reporting_status → get_media_buy_delivery → sync_reporting_status → get_reporting_status → comply_test_controller → get_reporting_status → comply_test_controller → get_reporting_status → sync_reporting_status → get_reporting_status` **Reliable Reporting: Core declaration** — Validates the proper-name Reliable Reporting 1.0 declaration and its required Core tier without requiring optional tiers or a sandbox controller. Flow: `get_adcp_capabilities` @@ -1844,7 +1850,7 @@ Agents use the `recovery` classification to decide what to do: `transient` → r | `ACCOUNT_REQUIRED` | correctable | The service must resolve the commercial account before it can determine governance applicability, but the request and referenced resource do not identify one. | | `ACCOUNT_SETUP_REQUIRED` | correctable | Natural key resolved but the account needs setup before use. | | `ACCOUNT_SUSPENDED` | terminal | Account has been suspended. | -| `ACTION_NOT_ALLOWED` | correctable | The requested mutation maps to an action that is not currently available on this media buy. Sellers MUST populate `error.details` with `attempted_action` (the `media_buy_valid_action` value the request maps to), `reason` (an `action-not-allowed-reason` value: `wrong_status`, `not_supported_on_product`, `not_supported_on_buy`, `mode_mismatch`, or `condition_unresolved`), and `currently_available_actions` (echo of the buy's resolved `available_actions[]` so the buyer SDK can offer recovery without a separate get_media_buys round-trip). | +| `ACTION_NOT_ALLOWED` | correctable | The requested mutation maps to an action that is not currently available on this media buy. Sellers MUST populate `error.details` with `attempted_action` (the structured available-action identifier the request maps to), `reason` (an `action-not-allowed-reason` value: `wrong_status`, `not_supported_on_product`, `not_supported_on_buy`, `mode_mismatch`, or `condition_unresolved`), and `currently_available_actions` (echo of the buy's resolved `available_actions[]` so the buyer SDK can offer recovery without a separate get_media_buys round-trip). | | `AGENT_BLOCKED` | terminal | The calling buyer agent's commercial relationship with the seller is permanently denied — the agent is blocked. Sibling to `AGENT_SUSPENDED` on the agent-relationship axis but with no recovery path (a suspension may lift via re-onboarding; a block does not). The code itself is the discriminator — same posture as `AGENT_SUSPENDED`: no `error.details` payload, no per-agent commercial state, cross-tenant onboarding oracle clamp + channel-coverage requirements normative in error-handling.mdx Per-Agent Authorization Gate. | | `AGENT_SUSPENDED` | terminal | The calling buyer agent's commercial relationship with the seller is temporarily paused — the agent is onboarded but currently suspended. Sibling to `ACCOUNT_SUSPENDED` (account-wide) and `CAMPAIGN_SUSPENDED` (per-plan) but scoped to the agent-relationship axis (orthogonal to any specific account on that agent). The code itself is the discriminator — it does NOT carry an `error.details` payload (mirroring `BILLING_NOT_PERMITTED_FOR_AGENT`'s discriminator-by-code pattern), and MUST NOT carry per-agent commercial state (rate cards, payment terms, credit limit, billing entity, contact channels) since full disclosure of per-agent state in a single probe is a per-agent oracle. Cross-tenant onboarding oracle clamp + channel-coverage requirements (response shape, HTTP/A2A/MCP status, headers, side effects, observability, latency parity, retry-counter side channel) are normative in error-handling.mdx Per-Agent Authorization Gate; this description does not restate them to avoid drift. | | `AMBIGUOUS_BIDDING_POLICY` | correctable | The same effective package combines the canonical bidding block with legacy bid_price or monetary optimization-goal target fields, so two bidding interpretations are present. Sellers MUST reject rather than choosing a winner. | diff --git a/docs/migration-12-to-14.md b/docs/migration-12-to-14.md index 8381d86df..a5ffb579e 100644 --- a/docs/migration-12-to-14.md +++ b/docs/migration-12-to-14.md @@ -1,6 +1,6 @@ # Migrating from 12.x to the 14 prerelease -This is the direct upgrade path for applications skipping SDK 13. SDK 14 includes both SDK 13's canonical-creative and security boundary changes and the AdCP `3.2.0-rc.2` release-candidate surface. Treat it as two review checkpoints even if you deploy one package update. +This is the direct upgrade path for applications skipping SDK 13. SDK 14 includes both SDK 13's canonical-creative and security boundary changes and the AdCP `3.2.0-rc.3` release-candidate surface. Treat it as two review checkpoints even if you deploy one package update. AdCP prerelease pins are exact: beta.6 supersedes beta.5. Beta.2 added canonical compact proposal and direct-buy lifecycle storyboards through operational diff --git a/docs/migration-13-to-14.md b/docs/migration-13-to-14.md index 98c112b64..51fd70db0 100644 --- a/docs/migration-13-to-14.md +++ b/docs/migration-13-to-14.md @@ -1,6 +1,6 @@ # Migrating from 13.x to the 14 prerelease -SDK 14 adopts AdCP `3.2.0-rc.2` while preserving the canonical creative boundary introduced in SDK 13. Most SDK 13 applications can install the prerelease and continue using the established 3.x tools unchanged; adopt the compact 3.2 lifecycle only after the remote agent advertises it. +SDK 14 adopts AdCP `3.2.0-rc.3` while preserving the canonical creative boundary introduced in SDK 13. Most SDK 13 applications can install the prerelease and continue using the established 3.x tools unchanged; adopt the compact 3.2 lifecycle only after the remote agent advertises it. Legacy signal-discovery adapters may keep supplying `opts.signals.getSignals` (or `legacyHandlers.signals.getSignals`) while declaring the truthful @@ -10,9 +10,13 @@ now satisfies platform validation without requiring adopters to invent an AdCP 3.2 prereleases are exact protocol pins: beta.6 replaces beta.5 in the SDK's compatible-version list rather than extending a rolling 3.2-beta range. -Likewise, `3.2.0-rc.2` replaces `3.2.0-rc.1`; callers pinned to rc.1 must +Likewise, `3.2.0-rc.3` replaces `3.2.0-rc.2`; callers pinned to rc.2 must upgrade both peers together because the SDK does not advertise superseded 3.2 -prereleases as compatible wire releases. +prereleases as compatible wire releases and ships only the current +prerelease's schema bundle. Pinning `adcpVersion: '3.2-rc'` follows whichever +3.2 release candidate this SDK build carries; pinning a superseded exact +prerelease such as `'3.2.0-rc.2'` raises a configuration error at schema load +rather than silently validating against a different contract. Beta.1 restored `adcp_major_version` on `buy_products`, `accept_proposal`, and `control_media_buy`; the SDK now sends that field again for beta.1 and later while retaining its omission only for an explicitly @@ -31,9 +35,9 @@ unversioned callers off 3.1: ```ts const server = createAdcpServer({ - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', defaultAdcpVersion: '3.1.18', - capabilities: { supported_versions: ['3.1.18', '3.2.0-rc.2'] }, + capabilities: { supported_versions: ['3.1.18', '3.2.0-rc.3'] }, // handlers... }); ``` @@ -936,7 +940,7 @@ import { getToolInputSchema, getToolResponseSchema } from '@adcp/sdk/schemas'; const request = getToolInputSchema('create_media_buy', { adcpVersion: '3.0' }); const response = getToolResponseSchema('create_media_buy', { - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', variant: 'sync', }); diff --git a/package.json b/package.json index 75ab34d72..7f7bccee3 100644 --- a/package.json +++ b/package.json @@ -746,7 +746,7 @@ }, "minimatch": "^10.2.1" }, - "adcp_version": "3.2.0-rc.2", + "adcp_version": "3.2.0-rc.3", "sideEffects": [ "**/default-invariants.*" ] diff --git a/scripts/check-package-size.mjs b/scripts/check-package-size.mjs index 3d3e667b2..fde5d23de 100644 --- a/scripts/check-package-size.mjs +++ b/scripts/check-package-size.mjs @@ -19,7 +19,7 @@ import { fileURLToPath } from 'node:url'; const MAX_PACKED_TARBALL_BYTES = 20_000_000; const MAX_UNPACKED_PACKAGE_BYTES = 120 * 1024 * 1024; // AdCP 3.2.0-beta.10 adds the account-change schema family. The seller reporting -// ledger adds ten public module artifacts. AdCP 3.2.0-rc.2 replaces the preview +// ledger adds ten public module artifacts. AdCP 3.2.0-rc.2 replaced the preview // schemas with its generated task surface and current compliance artifacts; // superseded rc.1 fixtures are excluded from the published package. Its // sync_reporting_status tool slice adds four publishable runtime/declaration artifacts. diff --git a/scripts/generate-agent-docs.ts b/scripts/generate-agent-docs.ts index 58f716c0d..74b52199c 100644 --- a/scripts/generate-agent-docs.ts +++ b/scripts/generate-agent-docs.ts @@ -2052,7 +2052,7 @@ function generateTypeSummary(index: SchemaIndex, tools: ToolInfo[]): string { ln(`const getReportingStatus = createReportingStatusHandler(store);`); ln(`const getMediaBuyDelivery = createReportingDeliveryHandler(store); // exact reporting_revision_id reads`); ln(); - ln(`// AdCP 3.2.0-rc.2: identity comes from authenticated transport.`); + ln(`// AdCP 3.2.0-rc.3: identity comes from authenticated transport.`); ln(`const syncReportingStatus = createSyncReportingStatusHandler(store, {`); ln(` resolveConsumerId: context => context.agent.agent_url,`); ln(`});`); diff --git a/scripts/verify-package.mjs b/scripts/verify-package.mjs index f8901a922..814cebc7a 100644 --- a/scripts/verify-package.mjs +++ b/scripts/verify-package.mjs @@ -320,15 +320,15 @@ try { "const { validateRequest } = require('./node_modules/@adcp/sdk/dist/lib/validation/index.js');", "const { loadRequestSchema } = require('./node_modules/@adcp/sdk/dist/lib/conformance/schemaLoader.js');", "const { getToolsWithErrorArm } = require('./node_modules/@adcp/sdk/dist/lib/server/error-arm-tools.js');", - "const invalid = validateRequest('get_products', {}, '3.2.0-rc.2');", + "const invalid = validateRequest('get_products', {}, '3.2.0-rc.3');", "if (invalid.valid || !invalid.issues.some(issue => issue.pointer === '/buying_mode')) {", " throw new Error('runtime validator did not load the archived get_products schema');", '}', - "const schema = loadRequestSchema('get_products', { version: '3.2.0-rc.2' });", + "const schema = loadRequestSchema('get_products', { version: '3.2.0-rc.3' });", "if (!schema.$id?.includes('/bundled/media-buy/get-products-request.json')) {", ' throw new Error(`conformance loader returned the wrong archived schema ID: ${schema.$id}`);', '}', - "const errorArmTools = getToolsWithErrorArm('3.2.0-rc.2');", + "const errorArmTools = getToolsWithErrorArm('3.2.0-rc.3');", "if (!errorArmTools.has('create_media_buy')) {", " throw new Error('server error-arm discovery did not load the archived response schemas');", '}', diff --git a/src/lib/media-buy/update-fields.generated.ts b/src/lib/media-buy/update-fields.generated.ts index 26aa7ba28..c85b3008c 100644 --- a/src/lib/media-buy/update-fields.generated.ts +++ b/src/lib/media-buy/update-fields.generated.ts @@ -1,7 +1,7 @@ // Generated by scripts/generate-media-buy-update-fields.ts. // Sources (enumMetadata, merged; legacy block wins on shared keys): // schemas/cache//enums/media-buy-valid-action.json -// schemas/cache//core/media-buy-available-action-id.json (absent from this cache; legacy-only table) +// schemas/cache//core/media-buy-available-action-id.json // Do not hand-edit - regenerate after a schema bump. import type { MediaBuyValidAction } from './types'; @@ -12,7 +12,7 @@ import type { MediaBuyValidAction } from './types'; * field bindings come from `core/media-buy-available-action-id.json`. * Empty when the schema cache predates that file. */ -export const STRUCTURED_ONLY_MEDIA_BUY_ACTIONS = [] as const; +export const STRUCTURED_ONLY_MEDIA_BUY_ACTIONS = ["update_media_buy_frequency_cap"] as const; export type StructuredOnlyMediaBuyAction = (typeof STRUCTURED_ONLY_MEDIA_BUY_ACTIONS)[number]; @@ -154,6 +154,11 @@ export const UPDATE_FIELDS_BY_ACTION: Readonly< rollup: ["replace_creative", "update_creative_assignments", "remove_creative"] as const, deprecated: true, }, + "update_media_buy_frequency_cap": { + update_fields: ["frequency_cap"] as const, + rollup: null, + deprecated: false, + }, } as const; export const ACTIONS_BY_FIELD: Readonly< @@ -164,6 +169,7 @@ export const ACTIONS_BY_FIELD: Readonly< "canceled": ["cancel"] as const, "cancellation_reason": ["cancel"] as const, "end_time": ["extend_flight", "shorten_flight", "update_flight_dates"] as const, + "frequency_cap": ["update_media_buy_frequency_cap"] as const, "name": ["update_name"] as const, "new_packages": ["add_packages"] as const, "pacing": ["update_pacing"] as const, diff --git a/src/lib/server/decisioning/runtime/entity-hydration.generated.ts b/src/lib/server/decisioning/runtime/entity-hydration.generated.ts index fd4a0aef3..b9a80e602 100644 --- a/src/lib/server/decisioning/runtime/entity-hydration.generated.ts +++ b/src/lib/server/decisioning/runtime/entity-hydration.generated.ts @@ -1,6 +1,6 @@ // Generated entity-hydration field map — do NOT edit by hand // -// Source: `schemas/cache/3.2.0-rc.2/manifest.json` + per-tool request +// Source: `schemas/cache/3.2.0-rc.3/manifest.json` + per-tool request // schemas. Every top-level `x-entity`-tagged string field on a request // schema lands here. The runtime hydrator (`from-platform.ts` → // `hydrateForTool`) walks this map plus the hand-curated diff --git a/src/lib/server/wire-spec-fields.generated.ts b/src/lib/server/wire-spec-fields.generated.ts index 1988df6d0..9ec3a3a07 100644 --- a/src/lib/server/wire-spec-fields.generated.ts +++ b/src/lib/server/wire-spec-fields.generated.ts @@ -1,6 +1,6 @@ // AUTO-GENERATED by scripts/generate-wire-spec-fields.ts. DO NOT EDIT. -// Source: schemas/cache/3.2.0-rc.2/**/*-request.json -// Generated at: 2026-09-14T00:24:08.501Z +// Source: schemas/cache/3.2.0-rc.3/**/*-request.json +// Generated at: 2026-09-14T14:23:00.138Z import type { AcquireRightsRequest, @@ -56,162 +56,162 @@ import type { * pollution or shared-state mutation of the allowlist. */ export const WIRE_SPEC_FIELDS = Object.freeze({ - /** schemas/cache/3.2.0-rc.2/brand/acquire-rights-request.json */ + /** schemas/cache/3.2.0-rc.3/brand/acquire-rights-request.json */ AcquireRightsRequest: Object.freeze({ fields: Object.freeze(["account","adcp_major_version","adcp_version","buyer","campaign","context","ext","governance_context","idempotency_key","pricing_option_id","push_notification_config","revocation_webhook","rights_id"]) as readonly string[], __type: null as unknown as AcquireRightsRequest, }), - /** schemas/cache/3.2.0-rc.2/signals/activate-signal-request.json */ + /** schemas/cache/3.2.0-rc.3/signals/activate-signal-request.json */ ActivateSignalRequest: Object.freeze({ fields: Object.freeze(["account","action","adcp_major_version","adcp_version","context","destinations","ext","governance_context","idempotency_key","pricing_option_id","signal_agent_segment_id"]) as readonly string[], __type: null as unknown as ActivateSignalRequest, }), - /** schemas/cache/3.2.0-rc.2/media-buy/build-creative-request.json */ + /** schemas/cache/3.2.0-rc.3/media-buy/build-creative-request.json */ BuildCreativeRequest: Object.freeze({ fields: Object.freeze(["account","adcp_major_version","adcp_version","brand","concept_id","config","context","creative_id","creative_manifest","creative_representation_set","evaluator","ext","governance_context","idempotency_key","include_preview","item_limit","keep_mode","macro_values","max_creatives","max_spend","max_variants","media_buy_id","message","mode","package_id","preview_inputs","preview_output_format","preview_quality","push_notification_config","quality","refine_from_build_variant_id","representation_destination","representation_selection_strategy","selection_strategy","signal_conditions","target_capability_id","target_capability_ids","target_format_id","target_format_ids","transformer_id","variant_axis"]) as readonly string[], __type: null as unknown as BuildCreativeRequest, }), - /** schemas/cache/3.2.0-rc.2/content-standards/calibrate-content-request.json */ + /** schemas/cache/3.2.0-rc.3/content-standards/calibrate-content-request.json */ CalibrateContentRequest: Object.freeze({ fields: Object.freeze(["adcp_major_version","adcp_version","artifact","context","ext","idempotency_key","standards_id"]) as readonly string[], __type: null as unknown as CalibrateContentRequest, }), - /** schemas/cache/3.2.0-rc.2/collection/create-collection-list-request.json */ + /** schemas/cache/3.2.0-rc.3/collection/create-collection-list-request.json */ CreateCollectionListRequest: Object.freeze({ fields: Object.freeze(["account","adcp_major_version","adcp_version","base_collections","brand","context","description","ext","filters","idempotency_key","name"]) as readonly string[], __type: null as unknown as CreateCollectionListRequest, }), - /** schemas/cache/3.2.0-rc.2/content-standards/create-content-standards-request.json */ + /** schemas/cache/3.2.0-rc.3/content-standards/create-content-standards-request.json */ CreateContentStandardsRequest: Object.freeze({ fields: Object.freeze(["adcp_major_version","adcp_version","calibration_exemplars","context","ext","idempotency_key","policies","registry_policy_ids","scope"]) as readonly string[], __type: null as unknown as CreateContentStandardsRequest, }), - /** schemas/cache/3.2.0-rc.2/media-buy/create-media-buy-request.json */ + /** schemas/cache/3.2.0-rc.3/media-buy/create-media-buy-request.json */ CreateMediaBuyRequest: Object.freeze({ - fields: Object.freeze(["account","adcp_major_version","adcp_version","advertiser_industry","agency_estimate_number","artifact_webhook","bidding","brand","budget_allocation","budget_cap_timezone","context","daily_budget_cap","end_time","ext","governance_context","idempotency_key","invoice_recipient","io_acceptance","name","opportunity","pacing","packages","paused","plan_id","po_number","proposal_id","push_notification_config","reporting_webhook","start_time","total_budget"]) as readonly string[], + fields: Object.freeze(["account","adcp_major_version","adcp_version","advertiser_industry","agency_estimate_number","artifact_webhook","bidding","brand","budget_allocation","budget_cap_timezone","context","daily_budget_cap","end_time","ext","frequency_cap","governance_context","idempotency_key","invoice_recipient","io_acceptance","name","opportunity","pacing","packages","paused","plan_id","po_number","proposal_id","push_notification_config","reporting_webhook","start_time","total_budget"]) as readonly string[], __type: null as unknown as CreateMediaBuyRequest, }), - /** schemas/cache/3.2.0-rc.2/property/create-property-list-request.json */ + /** schemas/cache/3.2.0-rc.3/property/create-property-list-request.json */ CreatePropertyListRequest: Object.freeze({ fields: Object.freeze(["account","adcp_major_version","adcp_version","base_properties","brand","context","description","ext","filters","idempotency_key","name"]) as readonly string[], __type: null as unknown as CreatePropertyListRequest, }), - /** schemas/cache/3.2.0-rc.2/collection/delete-collection-list-request.json */ + /** schemas/cache/3.2.0-rc.3/collection/delete-collection-list-request.json */ DeleteCollectionListRequest: Object.freeze({ fields: Object.freeze(["account","adcp_major_version","adcp_version","context","ext","idempotency_key","list_id"]) as readonly string[], __type: null as unknown as DeleteCollectionListRequest, }), - /** schemas/cache/3.2.0-rc.2/property/delete-property-list-request.json */ + /** schemas/cache/3.2.0-rc.3/property/delete-property-list-request.json */ DeletePropertyListRequest: Object.freeze({ fields: Object.freeze(["account","adcp_major_version","adcp_version","context","ext","idempotency_key","list_id"]) as readonly string[], __type: null as unknown as DeletePropertyListRequest, }), - /** schemas/cache/3.2.0-rc.2/media-buy/get-media-buy-delivery-request.json */ + /** schemas/cache/3.2.0-rc.3/media-buy/get-media-buy-delivery-request.json */ GetMediaBuyDeliveryRequest: Object.freeze({ fields: Object.freeze(["account","adcp_major_version","adcp_version","attribution_window","context","end_date","ext","include_package_daily_breakdown","include_window_breakdown","media_buy_ids","pagination","reporting_dimensions","reporting_revision_id","requested_metrics","start_date","status_filter","time_granularity"]) as readonly string[], __type: null as unknown as GetMediaBuyDeliveryRequest, }), - /** schemas/cache/3.2.0-rc.2/media-buy/get-reporting-status-request.json */ + /** schemas/cache/3.2.0-rc.3/media-buy/get-reporting-status-request.json */ GetReportingStatusRequest: Object.freeze({ fields: Object.freeze(["account","adcp_major_version","adcp_version","changes_after","context","delivery_config_ids","ext","feed_purposes","finality","health","media_buy_ids","pagination","period","reporting_revision_id","view"]) as readonly string[], __type: null as unknown as GetReportingStatusRequest, }), - /** schemas/cache/3.2.0-rc.2/media-buy/log-event-request.json */ + /** schemas/cache/3.2.0-rc.3/media-buy/log-event-request.json */ LogEventRequest: Object.freeze({ fields: Object.freeze(["adcp_major_version","adcp_version","context","event_source_id","events","ext","idempotency_key","test_event_code"]) as readonly string[], __type: null as unknown as LogEventRequest, }), - /** schemas/cache/3.2.0-rc.2/media-buy/provide-performance-feedback-request.json */ + /** schemas/cache/3.2.0-rc.3/media-buy/provide-performance-feedback-request.json */ ProvidePerformanceFeedbackRequest: Object.freeze({ fields: Object.freeze(["adcp_major_version","adcp_version","as_of","baseline","context","creative_id","evidence","evidence_ref","ext","feedback_source","final","idempotency_key","measurement_period","media_buy_id","methodology","methodology_version","metric","metric_type","package_id","performance_index","producer","study_ref","supersedes_feedback_id","vendor"]) as readonly string[], __type: null as unknown as ProvidePerformanceFeedbackRequest, }), - /** schemas/cache/3.2.0-rc.2/governance/report-plan-outcome-request.json */ + /** schemas/cache/3.2.0-rc.3/governance/report-plan-outcome-request.json */ ReportPlanOutcomeRequest: Object.freeze({ fields: Object.freeze(["adcp_major_version","adcp_version","check_id","context","delivery","error","ext","governance_context","idempotency_key","outcome","plan_id","purchase_type","seller_response"]) as readonly string[], __type: null as unknown as ReportPlanOutcomeRequest, }), - /** schemas/cache/3.2.0-rc.2/account/report-usage-request.json */ + /** schemas/cache/3.2.0-rc.3/account/report-usage-request.json */ ReportUsageRequest: Object.freeze({ fields: Object.freeze(["adcp_major_version","adcp_version","context","ext","idempotency_key","reporting_period","usage"]) as readonly string[], __type: null as unknown as ReportUsageRequest, }), - /** schemas/cache/3.2.0-rc.2/sponsored-intelligence/si-initiate-session-request.json */ + /** schemas/cache/3.2.0-rc.3/sponsored-intelligence/si-initiate-session-request.json */ SIInitiateSessionRequest: Object.freeze({ fields: Object.freeze(["adcp_major_version","adcp_version","context","ext","idempotency_key","identity","intent","media_buy_id","offering_id","offering_token","placement","sponsored_context_receipt","supported_capabilities"]) as readonly string[], __type: null as unknown as SIInitiateSessionRequest, }), - /** schemas/cache/3.2.0-rc.2/sponsored-intelligence/si-send-message-request.json */ + /** schemas/cache/3.2.0-rc.3/sponsored-intelligence/si-send-message-request.json */ SISendMessageRequest: Object.freeze({ fields: Object.freeze(["action_response","adcp_major_version","adcp_version","context","ext","idempotency_key","message","session_id","sponsored_context_receipt"]) as readonly string[], __type: null as unknown as SISendMessageRequest, }), - /** schemas/cache/3.2.0-rc.2/account/sync-accounts-request.json */ + /** schemas/cache/3.2.0-rc.3/account/sync-accounts-request.json */ SyncAccountsRequest: Object.freeze({ fields: Object.freeze(["accounts","adcp_major_version","adcp_version","context","delete_missing","dry_run","ext","idempotency_key","push_notification_config"]) as readonly string[], __type: null as unknown as SyncAccountsRequest, }), - /** schemas/cache/3.2.0-rc.2/media-buy/sync-audiences-request.json */ + /** schemas/cache/3.2.0-rc.3/media-buy/sync-audiences-request.json */ SyncAudiencesRequest: Object.freeze({ fields: Object.freeze(["account","adcp_major_version","adcp_version","audiences","context","delete_missing","ext","idempotency_key"]) as readonly string[], __type: null as unknown as SyncAudiencesRequest, }), - /** schemas/cache/3.2.0-rc.2/media-buy/sync-catalogs-request.json */ + /** schemas/cache/3.2.0-rc.3/media-buy/sync-catalogs-request.json */ SyncCatalogsRequest: Object.freeze({ fields: Object.freeze(["account","adcp_major_version","adcp_version","catalog_ids","catalogs","context","delete_missing","dry_run","ext","idempotency_key","item_availability_queries","item_availability_updates","push_notification_config","validation_mode"]) as readonly string[], __type: null as unknown as SyncCatalogsRequest, }), - /** schemas/cache/3.2.0-rc.2/creative/sync-creatives-request.json */ + /** schemas/cache/3.2.0-rc.3/creative/sync-creatives-request.json */ SyncCreativesRequest: Object.freeze({ fields: Object.freeze(["account","adcp_major_version","adcp_version","assignment_operations","assignments","context","creative_ids","creatives","delete_missing","dry_run","ext","idempotency_key","push_notification_config","validation_mode"]) as readonly string[], __type: null as unknown as SyncCreativesRequest, }), - /** schemas/cache/3.2.0-rc.2/media-buy/sync-event-sources-request.json */ + /** schemas/cache/3.2.0-rc.3/media-buy/sync-event-sources-request.json */ SyncEventSourcesRequest: Object.freeze({ fields: Object.freeze(["account","adcp_major_version","adcp_version","context","delete_missing","event_sources","ext","idempotency_key"]) as readonly string[], __type: null as unknown as SyncEventSourcesRequest, }), - /** schemas/cache/3.2.0-rc.2/account/sync-governance-request.json */ + /** schemas/cache/3.2.0-rc.3/account/sync-governance-request.json */ SyncGovernanceRequest: Object.freeze({ fields: Object.freeze(["accounts","adcp_major_version","adcp_version","context","ext","idempotency_key"]) as readonly string[], __type: null as unknown as SyncGovernanceRequest, }), - /** schemas/cache/3.2.0-rc.2/governance/sync-plans-request.json */ + /** schemas/cache/3.2.0-rc.3/governance/sync-plans-request.json */ SyncPlansRequest: Object.freeze({ fields: Object.freeze(["adcp_major_version","adcp_version","context","ext","idempotency_key","plans"]) as readonly string[], __type: null as unknown as SyncPlansRequest, }), - /** schemas/cache/3.2.0-rc.2/media-buy/sync-reporting-receipts-request.json */ + /** schemas/cache/3.2.0-rc.3/media-buy/sync-reporting-receipts-request.json */ SyncReportingReceiptsRequest: Object.freeze({ fields: Object.freeze(["account","adcp_major_version","adcp_version","adjustment_receipts","context","ext","idempotency_key","receipts"]) as readonly string[], __type: null as unknown as SyncReportingReceiptsRequest, }), - /** schemas/cache/3.2.0-rc.2/media-buy/sync-reporting-status-request.json */ + /** schemas/cache/3.2.0-rc.3/media-buy/sync-reporting-status-request.json */ SyncReportingStatusRequest: Object.freeze({ fields: Object.freeze(["account","adcp_major_version","adcp_version","context","ext","idempotency_key","statuses"]) as readonly string[], __type: null as unknown as SyncReportingStatusRequest, }), - /** schemas/cache/3.2.0-rc.2/collection/update-collection-list-request.json */ + /** schemas/cache/3.2.0-rc.3/collection/update-collection-list-request.json */ UpdateCollectionListRequest: Object.freeze({ fields: Object.freeze(["account","adcp_major_version","adcp_version","base_collections","brand","context","description","ext","filters","idempotency_key","list_id","name","webhook_url"]) as readonly string[], __type: null as unknown as UpdateCollectionListRequest, }), - /** schemas/cache/3.2.0-rc.2/content-standards/update-content-standards-request.json */ + /** schemas/cache/3.2.0-rc.3/content-standards/update-content-standards-request.json */ UpdateContentStandardsRequest: Object.freeze({ fields: Object.freeze(["adcp_major_version","adcp_version","calibration_exemplars","context","ext","idempotency_key","policies","registry_policy_ids","scope","standards_id"]) as readonly string[], __type: null as unknown as UpdateContentStandardsRequest, }), - /** schemas/cache/3.2.0-rc.2/media-buy/update-media-buy-request.json */ + /** schemas/cache/3.2.0-rc.3/media-buy/update-media-buy-request.json */ UpdateMediaBuyRequest: Object.freeze({ - fields: Object.freeze(["account","adcp_major_version","adcp_version","bidding","budget_allocation","budget_cap_timezone","canceled","cancellation_reason","context","daily_budget_cap","end_time","ext","governance_context","idempotency_key","invoice_recipient","media_buy_id","name","new_packages","pacing","packages","paused","push_notification_config","reporting_webhook","revision","start_time","total_budget"]) as readonly string[], + fields: Object.freeze(["account","adcp_major_version","adcp_version","bidding","budget_allocation","budget_cap_timezone","canceled","cancellation_reason","context","daily_budget_cap","end_time","ext","frequency_cap","governance_context","idempotency_key","invoice_recipient","media_buy_id","name","new_packages","pacing","packages","paused","push_notification_config","reporting_webhook","revision","start_time","total_budget"]) as readonly string[], __type: null as unknown as UpdateMediaBuyRequest, }), - /** schemas/cache/3.2.0-rc.2/property/update-property-list-request.json */ + /** schemas/cache/3.2.0-rc.3/property/update-property-list-request.json */ UpdatePropertyListRequest: Object.freeze({ fields: Object.freeze(["account","adcp_major_version","adcp_version","base_properties","brand","context","description","ext","filters","idempotency_key","list_id","name","webhook_url"]) as readonly string[], __type: null as unknown as UpdatePropertyListRequest, }), - /** schemas/cache/3.2.0-rc.2/brand/update-rights-request.json */ + /** schemas/cache/3.2.0-rc.3/brand/update-rights-request.json */ UpdateRightsRequest: Object.freeze({ fields: Object.freeze(["account","adcp_major_version","adcp_version","context","end_date","ext","governance_context","idempotency_key","impression_cap","paused","pricing_option_id","push_notification_config","rights_id"]) as readonly string[], __type: null as unknown as UpdateRightsRequest, diff --git a/src/lib/types/core.generated.ts b/src/lib/types/core.generated.ts index a80373554..9bcae2c4a 100644 --- a/src/lib/types/core.generated.ts +++ b/src/lib/types/core.generated.ts @@ -1,5 +1,5 @@ -// Generated AdCP core types from official schemas v3.2.0-rc.2 -// Generated at: 2026-09-14T10:29:50.912Z +// Generated AdCP core types from official schemas v3.2.0-rc.3 +// Generated at: 2026-09-14T14:16:05.638Z // ACCOUNTCURRENCYMODE CANONICAL ENUM /** @@ -425,6 +425,7 @@ export type CanonicalMediaBuyActionName = | 'update_pacing' | 'update_bidding' | 'update_frequency_caps' + | 'update_media_buy_frequency_cap' | 'update_catalog_assignments' | 'update_keywords' | 'update_optimization_goals' @@ -1127,6 +1128,18 @@ export type FormatIDParameter = 'dimensions' | 'duration' | 'pixel_ratio'; */ export type FrameRateType = 'constant' | 'variable'; +// FREQUENCYCAPCONTROLMODE CANONICAL ENUM +/** + * A supported package frequency-cap control shape. + */ +export type FrequencyCapControlMode = 'max_impressions' | 'suppress' | 'max_impressions_and_suppress'; + +// FREQUENCYCAPMUTABLEFIELD CANONICAL ENUM +/** + * A logical frequency-cap field that a product implementation can change after creation. suppress covers the effective cooldown whether represented by suppress or the deprecated suppress_minutes alias. + */ +export type FrequencyCapMutableField = 'max_impressions' | 'per' | 'window' | 'suppress'; + // FREQUENCYCAPSCOPE CANONICAL ENUM /** * Scope for frequency cap application @@ -1406,6 +1419,12 @@ export type MatchType = 'broad' | 'phrase' | 'exact'; */ export type MediaBuyActionMode = 'self_serve' | 'conditional_self_serve' | 'seller_managed' | 'requires_approval'; +// MEDIABUYFREQUENCYCAPCONTROLMODE CANONICAL ENUM +/** + * The aggregate MediaBuy frequency-cap control shape supported in 3.2. + */ +export type MediaBuyFrequencyCapControlMode = 'max_impressions'; + // MEDIABUYHEALTH CANONICAL ENUM /** * Aggregate health of a media buy based on upstream dependency state. Orthogonal to media-buy-status — a buy can be paused-and-impaired, pending-and-impaired, or active-and-impaired. Always set; defaults to 'ok' when no open impairments exist. @@ -4233,6 +4252,119 @@ export type DaypartSupport = * Concrete timezone identifier in the implementation's supported IANA Time Zone Database, such as America/New_York, CET, or UTC. */ export type IANATimezoneIdentifier = string; +/** + * Structured frequency-cap constraints. Count and duration declarations are exact: each uses either an exhaustive preset list or an inclusive range, never a unit-only promise. At product scope, omitted fields inherit the applicable seller-wide capability and never broaden it. Product mutability describes implementation capability; MediaBuy.available_actions remains authoritative for a live buy. + */ +export type FrequencyCapConstraints = { +} & { + /** + * Logical cap fields that can change after creation. An empty array means create-only. For example, [max_impressions] permits changing the count while keeping per and window fixed. Omission means update support is undeclared and the legacy broad meaning applies. + */ + mutable_fields?: FrequencyCapMutableField[]; + /** + * FrequencyCap shapes accepted by the product. max_impressions_and_suppress means both controls may appear together and are enforced with AND semantics. + * + * @minItems 1 + */ + supported_control_modes?: [FrequencyCapControlMode, ...FrequencyCapControlMode[]]; + /** + * Entity granularities accepted by max_impressions caps. + * + * @minItems 1 + */ + supported_per_units?: [ReachUnit, ...ReachUnit[]]; + max_impressions_constraints?: FrequencyCapImpressionConstraints; + /** + * Exact supported max_impressions.window intervals, one entry per duration unit. + * + * @minItems 1 + */ + window_constraints?: [FrequencyCapIntervalConstraints, ...FrequencyCapIntervalConstraints[]]; + /** + * Exact supported suppress cooldown intervals, one entry per duration unit. + * + * @minItems 1 + */ + suppression_constraints?: [FrequencyCapIntervalConstraints, ...FrequencyCapIntervalConstraints[]]; + ext?: ExtensionObject; +}; +/** + * Exact supported max_impressions presets or range. + */ +export type FrequencyCapImpressionConstraints = { + minimum?: number; + maximum?: number; + /** + * @minItems 1 + */ + allowed_values?: [number, ...number[]]; + ext?: ExtensionObject; +} & { +}; +/** + * Exact supported intervals for one duration unit, declared as either an exhaustive preset list or an inclusive integer range. The two forms are mutually exclusive. + */ +export type FrequencyCapIntervalConstraints = { + unit: FrequencyCapDurationUnit; + minimum_interval?: number; + maximum_interval?: number; + /** + * @minItems 1 + */ + allowed_intervals?: [number, ...number[]]; + ext?: ExtensionObject; +} & ( + | { + } + | { + } +) & { + unit: FrequencyCapDurationUnit; + minimum_interval?: number; + maximum_interval?: number; + /** + * @minItems 1 + */ + allowed_intervals?: [number, ...number[]]; + ext?: ExtensionObject; + } & ( + | { + } + | { + } + ) & { + unit: FrequencyCapDurationUnit; + minimum_interval?: number; + maximum_interval?: number; + /** + * @minItems 1 + */ + allowed_intervals?: [number, ...number[]]; + ext?: ExtensionObject; + } & ( + | { + } + | { + } + ) & { + unit: FrequencyCapDurationUnit; + minimum_interval?: number; + maximum_interval?: number; + /** + * @minItems 1 + */ + allowed_intervals?: [number, ...number[]]; + ext?: ExtensionObject; + } & ( + | { + } + | { + } + ); +/** + * A duration unit supported for a frequency-cap window or suppression period. + */ +export type FrequencyCapDurationUnit = 'seconds' | 'minutes' | 'hours' | 'days' | 'campaign'; export type BrowserSupport = | Supported | { @@ -4246,7 +4378,7 @@ export type KeywordSupport = ext?: ExtensionObject; }; /** - * Product-scoped package targeting dimensions that may be supplied or changed after discovery. This is the seller response shape and may disclose seller limits such as max_values_per_package and max_packages. Product.overlay_support is the binding selectable-targeting contract: presence means the seller can apply protocol-valid values within the declared systems, countries, values, types, versions, and limits. Inherent product coverage alone does not satisfy a future-support requirement. Support does not guarantee inventory or a value-specific forecast before values are supplied; fixed prices and floors remain binding for supported selections. geo_regions and geo_regions_exclude are independent: structured support either exhaustively declares every value active in the seller's support snapshot for a country or lists the exact finite selectable subset. Buyer minimums use targeting-overlay-requirements.json. A requirement value of true matches true or any valid support object; an object requirement matches true or a containing support object. The daypart_targets boolean is the backward-compatible exception: true promises inventory_local only, and structured support opts into IANA zones. Every valid structured support object represents a positive capability; empty, extension-only, and false-only objects are invalid. Unrequested object fields and numeric seller limits do not participate in matching. + * Product-scoped package targeting dimensions that may be supplied or changed after discovery. This is the seller response shape and may disclose seller limits such as max_values_per_package and max_packages. Product.overlay_support is the binding selectable-targeting contract: presence means the seller can apply protocol-valid values within the declared systems, countries, values, types, versions, and limits. Inherent product coverage alone does not satisfy a future-support requirement. Support does not guarantee inventory or a value-specific forecast before values are supplied; fixed prices and floors remain binding for supported selections. geo_regions and geo_regions_exclude are independent: structured support either exhaustively declares every value active in the seller's support snapshot for a country or lists the exact finite selectable subset. Buyer minimums use targeting-overlay-requirements.json. A requirement value of true matches true or any valid support object; an object requirement matches true or a containing support object. The daypart_targets boolean is the backward-compatible exception: true promises inventory_local only, and structured support opts into IANA zones. Every valid structured support object represents a positive capability; empty, extension-only, and false-only objects are invalid. Unrequested object fields and numeric seller limits do not participate in matching. A product declares at most one of frequency_cap: true and frequency_cap_support. Legacy frequency_cap: true keeps its broad meaning within seller-wide limits, including update support. A constrained or create-only product instead advertises frequency_cap_support, so older buyers safely treat it as unsupported. */ export interface TargetingOverlaySupport { geo_countries?: CountrySupport; @@ -4285,6 +4417,10 @@ export interface TargetingOverlaySupport { ext?: ExtensionObject; }; frequency_cap?: Supported; + /** + * Independently positive constrained package-cap support. Mutually exclusive with legacy frequency_cap: a product declares one form or the other. + */ + frequency_cap_support?: FrequencyCapConstraints; property_list?: Supported; property_list_exclude?: Supported; collection_list?: Supported; @@ -4525,7 +4661,7 @@ export type KeywordRequirement = supported_match_types: MatchType[]; }; /** - * Buyer minimum requirements for targeting dimensions that will be selected on packages later. This request shape deliberately excludes seller limits such as max_values_per_package and max_packages. Matching is capability containment: where a field permits a boolean form, a requirement value of true matches product support true or any valid positive support object, and product support true satisfies every protocol-valid structured requirement except daypart_targets, where true promises inventory_local only. Otherwise, structured product support must contain the structured requirement. For geo_regions and geo_regions_exclude, every requested country must exist; requested all_values requires supported all_values; and requested values must be a subset of supported values unless support declares all_values. For geo_places and geo_places_exclude, every requested system and country key must exist and each requested place-type and system-version array must be a subset of the corresponding product array. Include and exclude fields match independently. Every valid structured requirement or support object represents a positive capability; empty, extension-only, and false-only objects are invalid. Object fields the buyer did not request do not participate. Missing or unknown required fields do not match. Numeric seller limits are disclosed only in Product.overlay_support and never participate in matching. + * Buyer minimum requirements for targeting dimensions that will be selected on packages later. This request shape deliberately excludes seller limits such as max_values_per_package and max_packages. Matching is capability containment: where a field permits a boolean form, a requirement value of true matches product support true or any valid positive support object, and product support true satisfies every protocol-valid structured requirement except daypart_targets, where true promises inventory_local only. Otherwise, structured product support must contain the structured requirement. For geo_regions and geo_regions_exclude, every requested country must exist; requested all_values requires supported all_values; and requested values must be a subset of supported values unless support declares all_values. For geo_places and geo_places_exclude, every requested system and country key must exist and each requested place-type and system-version array must be a subset of the corresponding product array. Include and exclude fields match independently. Every valid structured requirement or support object represents a positive capability; empty, extension-only, and false-only objects are invalid. Object fields the buyer did not request do not participate. Missing or unknown required fields do not match. Numeric seller limits are disclosed only in Product.overlay_support and never participate in matching. Legacy frequency_cap: true matches only the unchanged broad declaration. frequency_cap_support matches either legacy true or a containing structured declaration; an empty object requests either positive form. A requirement carries at most one of the two. */ export interface TargetingOverlayRequirements { geo_countries?: Required; @@ -4556,6 +4692,7 @@ export interface TargetingOverlayRequirements { age: Required; }; frequency_cap?: Required; + frequency_cap_support?: FrequencyCapRequirements; property_list?: Required; property_list_exclude?: Required; collection_list?: Required; @@ -4627,6 +4764,38 @@ export interface CatalogRequirement { */ system_versions?: [string, ...string[]]; } +/** + * Minimum structured package-cap support. Matches a broad legacy frequency_cap: true or a containing frequency_cap_support object. Mutually exclusive with a frequency_cap: true requirement, which would exclude every constrained product. + */ +export interface FrequencyCapRequirements { + /** + * Require each listed logical field to be mutable after creation. Matches a product whose mutable_fields contains every listed value, or a product that omits mutable_fields, or legacy frequency_cap: true. A product declaring mutable_fields: [] is create-only and never matches a non-empty list. + * + * @minItems 1 + */ + mutable_fields?: [FrequencyCapMutableField, ...FrequencyCapMutableField[]]; + /** + * @minItems 1 + */ + supported_control_modes?: [FrequencyCapControlMode, ...FrequencyCapControlMode[]]; + /** + * @minItems 1 + */ + supported_per_units?: [ReachUnit, ...ReachUnit[]]; + /** + * Require each listed unit to be a supported max_impressions.window unit after seller-wide inheritance. + * + * @minItems 1 + */ + supported_window_units?: [FrequencyCapDurationUnit, ...FrequencyCapDurationUnit[]]; + /** + * Require each listed unit to be a supported suppress unit after seller-wide inheritance. + * + * @minItems 1 + */ + supported_suppression_units?: [FrequencyCapDurationUnit, ...FrequencyCapDurationUnit[]]; +} +// CANONICALFORMATOPTION PRIORITY CANONICAL SCHEMA /** * One exact first-class manifest tracker selector in a seller production execution contract. AdCP 3.2 supports pixel_tracker, vast_tracker, and daast_tracker only; URL-slot selectors are not part of this union. */ @@ -5021,6 +5190,10 @@ export interface CancellationPolicy { }; } // MEDIABUYAVAILABLEACTION PRIORITY CANONICAL SCHEMA +/** + * The action identifier. + */ +export type MediaBuyAvailableActionID = MediaBuyValidAction | 'update_media_buy_frequency_cap'; /** * The accepted proposal change_terms[].term_id from which this current-state action projection was derived. */ @@ -5029,12 +5202,16 @@ export type MediaBuyChangeTermID = string; * Deprecated 3.1 opaque commercial-terms pointer. A 3.2 compatibility projection MAY echo change_term_id here for older buyers, but new buyers MUST prefer change_term_id and MUST NOT assume an arbitrary 3.1 value identifies an accepted change term. */ export type MediaBuyTermsReference = string; +/** + * A package identifier to which a package-scoped media-buy action currently applies. + */ +export type ApplicablePackageID = string; /** * An action currently available on a media buy, resolved against the buy's current status, accepted commercial_terms.change_terms, account authorization, and applicable governance delegation. Authoritative for current availability, but not a replacement for negotiated rights: when explicit change_terms exist, this projection may temporarily omit an action because state changed, but MUST NOT silently replace its negotiated service mode, SLA, constraints, conditions, or contract reference. The containing array is uniquely keyed by action. */ export interface MediaBuyAvailableAction { - action: MediaBuyValidAction; + action: MediaBuyAvailableActionID; mode: MediaBuyActionMode; /** * Compact-lifecycle task for this resolved action: operational control, commercial refinement, or creative lifecycle mutation. @@ -5043,6 +5220,10 @@ export interface MediaBuyAvailableAction { sla?: SLAWindow; change_term_id?: MediaBuyChangeTermID; terms_ref?: MediaBuyTermsReference; + /** + * For a package-scoped action, the exact packages currently eligible. Omission means every relevant package. Root actions omit this field. + */ + applicable_package_ids?: ApplicablePackageID[]; } /** * Optional SLA commitment for this action on this buy. Absence means no commitment, not zero commitment. @@ -5080,7 +5261,7 @@ export type EffectiveTimingConstraints = { * An action a seller declares as allowed on buys created against this product, scoped to the buy statuses where the action is permitted and the modes available. Advisory template only — the authoritative per-buy resolution lives in `available_actions[]` on the buy response (which may diverge from the product template based on negotiated terms, account tier, or buy-level overrides). The containing `allowed_actions[]` array is uniquely keyed by `action`; sellers MUST NOT emit two entries with the same `action` value. JSON Schema `uniqueItems` only catches structurally identical objects, so validators MUST enforce action-uniqueness separately. */ export interface ProductAllowedAction { - action: MediaBuyValidAction; + action: MediaBuyAvailableActionID; /** * Modes available for this action on this product. A product may declare multiple modes (for example `self_serve` within tolerances, escalating to `requires_approval` outside) — the buy-side `available_actions[].mode` resolves to the singular mode in effect at mutation time. SDKs that see multiple modes MUST NOT assume which one will fire; they must read the resolved `mode` on the buy. */ @@ -5640,330 +5821,115 @@ export type OptimizationGoal = priority?: number; }; /** - * Complete effective targeting overlay to apply to this package. On update, this replaces the package's current effective targeting, including values originally accepted through configured-product selection; omit the field to leave targeting unchanged. Every replacement must remain executable by the product. Sellers reject unsupported or partially applicable changes and use REQUOTE_REQUIRED when a change, including a broader inventory set, falls outside the priced envelope. placement_selection is purchased-inventory targeting; mode default restores the product default, and successful readback echoes the committed selected set when enumerable. If the replacement removes a placement referenced by an existing creative assignment, the seller MUST reject the update unless the same atomic package mutation supplies a compatible complete creative_assignments replacement. Sellers MUST NOT silently delete assignments or retain orphan placement refs. - */ -export type TargetingOverlay = { -} & { - /** - * Restrict delivery to specific countries. ISO 3166-1 alpha-2 codes (e.g., 'US', 'GB', 'DE'). - * - * @minItems 1 - */ - geo_countries?: [string, ...string[]]; - /** - * Exclude specific countries from delivery. ISO 3166-1 alpha-2 codes (e.g., 'US', 'GB', 'DE'). - * - * @minItems 1 - */ - geo_countries_exclude?: [string, ...string[]]; - /** - * Restrict delivery to exact canonical ISO 3166-2 subdivisions (states, provinces, regions, departments, or other subdivision categories). Unknown identifiers are invalid. At create or update, sellers MUST reject unsupported identifiers and MUST NOT silently widen, drop, or partially apply the list. During get_products, a seller may instead return a sparse, buyer-reviewable targeting_resolution modification for a valid but unsupported requested outcome. Exact internal translation preserves accepted identifiers in package readback. - * - * @minItems 1 - */ - geo_regions?: [string, ...string[]]; - /** - * Exclude exact canonical ISO 3166-2 subdivisions. Support is independent from geo_regions inclusion support. Unknown identifiers and values also present in geo_regions are invalid. At create or update, sellers MUST reject unsupported identifiers and partial application; during get_products, a seller may instead return a sparse, buyer-reviewable targeting_resolution modification for a valid but unsupported requested outcome. - * - * @minItems 1 - */ - geo_regions_exclude?: [string, ...string[]]; - /** - * Restrict delivery to specific metro areas. Each entry specifies the classification system and target values. Seller must declare supported systems in get_adcp_capabilities. - * - * @minItems 1 - */ - geo_metros?: [ - { - system: MetroAreaSystem; - /** - * Metro codes within the system (e.g., ['501', '602'] for Nielsen DMAs) - * - * @minItems 1 - */ - values: [string, ...string[]]; - }, - ...{ - system: MetroAreaSystem; - /** - * Metro codes within the system (e.g., ['501', '602'] for Nielsen DMAs) - * - * @minItems 1 - */ - values: [string, ...string[]]; - }[] - ]; - /** - * Exclude specific metro areas from delivery. Each entry specifies the classification system and excluded values. Seller must declare supported systems in get_adcp_capabilities. - * - * @minItems 1 - */ - geo_metros_exclude?: [ - { - system: MetroAreaSystem; - /** - * Metro codes to exclude within the system (e.g., ['501', '602'] for Nielsen DMAs) - * - * @minItems 1 - */ - values: [string, ...string[]]; - }, - ...{ - system: MetroAreaSystem; - /** - * Metro codes to exclude within the system (e.g., ['501', '602'] for Nielsen DMAs) - * - * @minItems 1 - */ - values: [string, ...string[]]; - }[] - ]; - /** - * Restrict delivery to specific postal areas. Prefer the native country + postal system form. The deprecated legacy country-fused postal-system tokens remain accepted for compatibility. Seller must declare supported systems in get_adcp_capabilities. - * - * @minItems 1 - */ - geo_postal_areas?: [PostalArea, ...PostalArea[]]; - /** - * Exclude specific postal areas from delivery. Prefer the native country + postal system form. The deprecated legacy country-fused postal-system tokens remain accepted for compatibility. Seller must declare supported systems in get_adcp_capabilities. - * - * @minItems 1 - */ - geo_postal_areas_exclude?: [PostalArea, ...PostalArea[]]; - /** - * Restrict delivery to catalog-backed named places. Values MUST be stable identifiers in the declared system, not display names. Sellers must declare supported systems, countries, and place types in get_adcp_capabilities and reject unsupported entries rather than silently dropping them. - * - * @minItems 1 - */ - geo_places?: [GeographicPlaceArea, ...GeographicPlaceArea[]]; - /** - * Exclude catalog-backed named places. Uses the same identifier-based shape as geo_places. Sellers MUST reject overlap with geo_places for the same country, system, place_type, and value. - * - * @minItems 1 - */ - geo_places_exclude?: [GeographicPlaceArea, ...GeographicPlaceArea[]]; - /** - * Restrict delivery to specific time windows. Each entry specifies days of week, an hour range, and an optional timezone that defaults to inventory_local. A concrete IANA zone uses one shared civil-time clock, while inventory_local evaluates each inventory unit in its seller-assigned local timezone. Entries are independent and MAY use different clocks. - * - * @minItems 1 - */ - daypart_targets?: [DaypartTarget, ...DaypartTarget[]]; - /** - * @deprecated - * Deprecated: Use TMP provider fields instead. AXE segment ID to include for targeting. - */ - axe_include_segment?: string; - /** - * @deprecated - * Deprecated: Use TMP provider fields instead. AXE segment ID to exclude from targeting. - */ - axe_exclude_segment?: string; - /** - * Restrict delivery to members of these first-party CRM audiences. Only users present in the uploaded lists are eligible. References audience_id values from sync_audiences on the same seller account — audience IDs are not portable across sellers. Not for lookalike expansion — express that intent in the campaign brief. Seller must declare support in get_adcp_capabilities. - * - * @minItems 1 - */ - audience_include?: [string, ...string[]]; - /** - * Suppress delivery to members of these first-party CRM audiences. Matched users are excluded regardless of other targeting. References audience_id values from sync_audiences on the same seller account — audience IDs are not portable across sellers. Seller must declare support in get_adcp_capabilities. - * - * @minItems 1 - */ - audience_exclude?: [string, ...string[]]; - signal_targeting_groups?: PackageSignalTargetingGroups; - /** - * @deprecated - * DEPRECATED. Use signal_targeting_groups for package-level signal targeting. Legacy flat signal_targeting remains accepted during the SignalRef migration window but cannot express grouped include/exclude composition or product-scoped pricing. - * - * @minItems 1 - */ - signal_targeting?: [SignalTargeting, ...SignalTargeting[]]; - demographics?: DemographicTargetingIntent; - frequency_cap?: FrequencyCap; - property_list?: PropertyListReference; - property_list_exclude?: PropertyListReference; - collection_list?: CollectionListReference; - collection_list_exclude?: CollectionListReference; - placement_selection?: PlacementSelection; - collection_selection?: CollectionSelection; - /** - * Age restriction for compliance. Use for legal requirements (alcohol, gambling), not audience targeting. - */ - age_restriction?: { + * Per-dimension targeting patch for this package. Omit targeting_overlay, or omit an individual dimension inside it, to leave the corresponding effective targeting unchanged. A non-null dimension replaces its current value; null clears it, including a value inherited from configured-product selection or a product default. Every resulting effective overlay must remain executable by the product. Sellers reject unsupported or partially applicable changes and use REQUOTE_REQUIRED when a change, including a broader inventory set, falls outside the priced envelope. placement_selection is purchased-inventory targeting; mode default restores the product default, null clears the dimension when the product permits it, and successful readback echoes the committed selected set when enumerable. If a patch removes a placement referenced by an existing creative assignment, the seller MUST reject the update unless the same atomic package mutation supplies a compatible complete creative_assignments replacement. Sellers MUST NOT silently delete assignments or retain orphan placement refs. + */ +export type TargetingOverlayInput = TargetingUnknownAgeEligibilityConstraint & + TargetingVerifiedAgeBasisConstraint & { + geo_countries?: GeoCountries | null; + geo_countries_exclude?: GeoCountriesExclude | null; + geo_regions?: GeoRegions | null; + geo_regions_exclude?: GeoRegionsExclude | null; + geo_metros?: TargetingGeoMetros; + geo_metros_exclude?: GeoMetrosExclude | null; + geo_postal_areas?: GeoPostalAreas | null; + geo_postal_areas_exclude?: GeoPostalAreasExclude | null; + geo_places?: GeoPlaces | null; + geo_places_exclude?: GeoPlacesExclude | null; + daypart_targets?: DaypartTargets | null; + axe_include_segment?: string | null; + axe_exclude_segment?: string | null; + audience_include?: AudienceInclude | null; + audience_exclude?: AudienceExclude | null; + signal_targeting_groups?: TargetingSignalGroups | null; /** - * Minimum age required + * @deprecated + * DEPRECATED. Use signal_targeting_groups for package-level signal targeting. Legacy flat signal_targeting remains accepted during the SignalRef migration window but cannot express grouped include/exclude composition or product-scoped pricing. + * + * @minItems 1 */ - min: number; + signal_targeting?: [SignalTargeting, ...SignalTargeting[]] | null; + demographics?: DemographicTargetingIntent | null; + frequency_cap?: TargetingFrequencyCap | null; + property_list?: TargetingPropertyList | null; + property_list_exclude?: PropertyListReference | null; + collection_list?: TargetingCollectionList | null; + collection_list_exclude?: CollectionListReference | null; + placement_selection?: PlacementSelection | null; + collection_selection?: TargetingCollectionSelection | null; + age_restriction?: AgeRestriction | null; + device_platform?: DevicePlatform | null; + device_platform_exclude?: DevicePlatformExclude | null; + device_type?: DeviceType | null; + device_type_exclude?: DeviceTypeExclude | null; + browser?: Browser | null; + browser_exclude?: BrowserExclude | null; + store_catchments?: StoreCatchments | null; + geo_proximity?: GeoProximity | null; + language?: TargetingLanguages; + keyword_targets?: TargetingKeywords; + negative_keywords?: TargetingNegativeKeywords; + }; +/** + * Restrict delivery to specific countries. ISO 3166-1 alpha-2 codes (e.g., 'US', 'GB', 'DE'). + * + * @minItems 1 + */ +export type GeoCountries = [string, ...string[]]; +/** + * Exclude specific countries from delivery. ISO 3166-1 alpha-2 codes (e.g., 'US', 'GB', 'DE'). + * + * @minItems 1 + */ +export type GeoCountriesExclude = [string, ...string[]]; +/** + * Restrict delivery to exact canonical ISO 3166-2 subdivisions (states, provinces, regions, departments, or other subdivision categories). Unknown identifiers are invalid. At create or update, sellers MUST reject unsupported identifiers and MUST NOT silently widen, drop, or partially apply the list. During get_products, a seller may instead return a sparse, buyer-reviewable targeting_resolution modification for a valid but unsupported requested outcome. Exact internal translation preserves accepted identifiers in package readback. + * + * @minItems 1 + */ +export type GeoRegions = [string, ...string[]]; +/** + * Exclude exact canonical ISO 3166-2 subdivisions. Support is independent from geo_regions inclusion support. Unknown identifiers and values also present in geo_regions are invalid. At create or update, sellers MUST reject unsupported identifiers and partial application; during get_products, a seller may instead return a sparse, buyer-reviewable targeting_resolution modification for a valid but unsupported requested outcome. + * + * @minItems 1 + */ +export type GeoRegionsExclude = [string, ...string[]]; +/** + * Restrict delivery to specific metro areas. Each entry specifies the classification system and target values. Seller must declare supported systems in get_adcp_capabilities. + * + * @minItems 1 + */ +export type TargetingGeoMetros = [GeoMetro, ...GeoMetro[]] | null; +/** + * Exclude specific metro areas from delivery. Each entry specifies the classification system and excluded values. Seller must declare supported systems in get_adcp_capabilities. + * + * @minItems 1 + */ +export type GeoMetrosExclude = [ + { + system: MetroAreaSystem; /** - * Whether verified age (not inferred) is required for compliance + * Metro codes to exclude within the system (e.g., ['501', '602'] for Nielsen DMAs) + * + * @minItems 1 */ - verification_required?: boolean; + values: [string, ...string[]]; + }, + ...{ + system: MetroAreaSystem; /** - * Accepted verification methods. If omitted, any method the platform supports is acceptable. + * Metro codes to exclude within the system (e.g., ['501', '602'] for Nielsen DMAs) * * @minItems 1 */ - accepted_methods?: [AgeVerificationMethod, ...AgeVerificationMethod[]]; - }; - /** - * Restrict to specific platforms. Use for technical compatibility (app only works on iOS). Values from Sec-CH-UA-Platform standard, extended for CTV. - * - * @minItems 1 - */ - device_platform?: [DevicePlatform, ...DevicePlatform[]]; - /** - * Exclude specific operating-system platforms from delivery. When a platform appears in both device_platform and device_platform_exclude, exclusion wins. Sellers MUST reject a request they cannot enforce rather than silently dropping the exclusion. - * - * @minItems 1 - */ - device_platform_exclude?: [DevicePlatform, ...DevicePlatform[]]; - /** - * Restrict to specific device form factors. Use for campaigns targeting hardware categories rather than operating systems (e.g., mobile-only promotions, CTV campaigns). - * - * @minItems 1 - */ - device_type?: [DeviceType, ...DeviceType[]]; - /** - * Exclude specific device form factors from delivery (e.g., exclude CTV for app-install campaigns). - * - * @minItems 1 - */ - device_type_exclude?: [DeviceType, ...DeviceType[]]; - /** - * Restrict delivery to specific canonical browser families in the impression delivery and rendering environment, not the post-click landing-page browser. Values MUST NOT be inferred solely from operating system, device, web/mobile-web inventory, or placement. Values in this array use OR semantics. When browser is supplied, families not listed are ineligible: other includes a seller-recognized family that is not explicitly enumerated, while unknown includes a browser the seller cannot classify into a recognized family. When the same family appears in browser and browser_exclude, exclusion wins. Browser and device constraints intersect; a seller that cannot enforce the exact combination MUST exclude or explicitly reconfigure the product during discovery and MUST reject it at create or update rather than silently widening delivery. Browser versions and seller-native IDs are intentionally unsupported. - * - * @minItems 1 - */ - browser?: [BrowserFamily, ...BrowserFamily[]]; - /** - * Exclude specific canonical browser families from delivery. other excludes seller-recognized families that are not explicitly enumerated; unknown excludes browsers the seller cannot classify into a recognized family. When the same family appears in browser and browser_exclude, exclusion wins. Sellers MUST reject a request they cannot enforce rather than silently dropping the exclusion. - * - * @minItems 1 - */ - browser_exclude?: [BrowserFamily, ...BrowserFamily[]]; - /** - * Target users within store catchment areas from a synced store catalog. Each entry references a store-type catalog and optionally narrows to specific stores or catchment zones. - * - * @minItems 1 - */ - store_catchments?: [ - { - /** - * Synced store-type catalog ID from sync_catalogs. - */ - catalog_id: string; - /** - * Filter to specific stores within the catalog. Omit to target all stores. - * - * @minItems 1 - */ - store_ids?: [string, ...string[]]; - /** - * Catchment zone IDs to target (e.g., 'walk', 'drive'). Omit to target all catchment zones. - * - * @minItems 1 - */ - catchment_ids?: [string, ...string[]]; - }, - ...{ - /** - * Synced store-type catalog ID from sync_catalogs. - */ - catalog_id: string; - /** - * Filter to specific stores within the catalog. Omit to target all stores. - * - * @minItems 1 - */ - store_ids?: [string, ...string[]]; - /** - * Catchment zone IDs to target (e.g., 'walk', 'drive'). Omit to target all catchment zones. - * - * @minItems 1 - */ - catchment_ids?: [string, ...string[]]; - }[] - ]; - /** - * Target users within travel time, distance, or a custom boundary around arbitrary geographic points. Multiple entries use OR semantics — a user within range of any listed point is eligible. For campaigns targeting 10+ locations, consider using store_catchments with a location catalog instead. Seller must declare support in get_adcp_capabilities. - * - * @minItems 1 - */ - geo_proximity?: [ - ( - | { - } - | { - } - | { - } - ), - ...( - | { - } - | { - } - | { - } - )[] - ]; - /** - * Restrict to users with specific language preferences using canonical BCP 47 language ranges. Each buyer range is evaluated against a user's language-preference tag with RFC 4647 section 3.3.1 Basic Filtering: 'fr' matches 'fr', 'fr-CA', and 'fr-FR', while 'fr-CA' matches 'fr-CA' and more-specific descendants but not 'fr' or 'fr-FR'. Values use OR logic. - * - * @minItems 1 - */ - language?: [LanguageTag, ...LanguageTag[]]; - /** - * Keyword targeting for search and retail media platforms. Restricts delivery to queries matching the specified keywords. Each keyword is identified by the tuple (keyword, match_type) — the same keyword string with different match types are distinct targets. Sellers SHOULD reject duplicate (keyword, match_type) pairs within a single request. Seller must declare support in get_adcp_capabilities. - * - * @minItems 1 - */ - keyword_targets?: [ - { - /** - * The keyword to target - */ - keyword: string; - match_type: MatchType; - /** - * Per-keyword bid price, denominated in the same currency as the package's pricing option. Overrides the package-level bid_price for this keyword. Inherits the max_bid interpretation from the pricing option: when max_bid is true, this is the keyword's bid ceiling; when false, this is the exact bid. If omitted, the package bid_price applies. - */ - bid_price?: number; - }, - ...{ - /** - * The keyword to target - */ - keyword: string; - match_type: MatchType; - /** - * Per-keyword bid price, denominated in the same currency as the package's pricing option. Overrides the package-level bid_price for this keyword. Inherits the max_bid interpretation from the pricing option: when max_bid is true, this is the keyword's bid ceiling; when false, this is the exact bid. If omitted, the package bid_price applies. - */ - bid_price?: number; - }[] - ]; - /** - * Keywords to exclude from delivery. Queries matching these keywords will not trigger the ad. Each negative keyword is identified by the tuple (keyword, match_type). Seller must declare support in get_adcp_capabilities. - * - * @minItems 1 - */ - negative_keywords?: [ - { - /** - * The keyword to exclude - */ - keyword: string; - match_type: MatchType; - }, - ...{ - /** - * The keyword to exclude - */ - keyword: string; - match_type: MatchType; - }[] - ]; -}; + values: [string, ...string[]]; + }[] +]; +/** + * Restrict delivery to specific postal areas. Prefer the native country + postal system form. The deprecated legacy country-fused postal-system tokens remain accepted for compatibility. Seller must declare supported systems in get_adcp_capabilities. + * + * @minItems 1 + */ +export type GeoPostalAreas = [PostalArea, ...PostalArea[]]; /** * Postal area values. Prefer the native country + postal system form. Deprecated legacy country-fused postal-system tokens remain accepted for compatibility. */ @@ -6029,6 +5995,18 @@ export type PostalCountrySystem = ( country: string; system: PostalCodeSystem; }; +/** + * Exclude specific postal areas from delivery. Prefer the native country + postal system form. The deprecated legacy country-fused postal-system tokens remain accepted for compatibility. Seller must declare supported systems in get_adcp_capabilities. + * + * @minItems 1 + */ +export type GeoPostalAreasExclude = [PostalArea, ...PostalArea[]]; +/** + * Restrict delivery to catalog-backed named places. Values MUST be stable identifiers in the declared system, not display names. Sellers must declare supported systems, countries, and place types in get_adcp_capabilities and reject unsupported entries rather than silently dropping them. + * + * @minItems 1 + */ +export type GeoPlaces = [GeographicPlaceArea, ...GeographicPlaceArea[]]; /** * A catalog-backed named place target. Values are stable identifiers in the declared system. Entries within geo_places form a union; different geographic inclusion dimensions intersect. value_labels are diagnostic only and MUST NOT be used to resolve targeting. */ @@ -6086,6 +6064,30 @@ export type GeographicPlaceArea = { * Collision-safe identifier namespace for geographic places. Registered tokens have protocol-defined semantics. Unregistered systems MUST use an absolute HTTPS URI controlled by the catalog owner; consumers compare URI systems as exact opaque strings. */ export type GeographicPlaceIdentifierSystem = ('geonames' | 'google_ads' | 'microsoft_ads') | string; +/** + * Exclude catalog-backed named places. Uses the same identifier-based shape as geo_places. Sellers MUST reject overlap with geo_places for the same country, system, place_type, and value. + * + * @minItems 1 + */ +export type GeoPlacesExclude = [GeographicPlaceArea, ...GeographicPlaceArea[]]; +/** + * Restrict delivery to specific time windows. Each entry specifies days of week, an hour range, and an optional timezone that defaults to inventory_local. A concrete IANA zone uses one shared civil-time clock, while inventory_local evaluates each inventory unit in its seller-assigned local timezone. Entries are independent and MAY use different clocks. + * + * @minItems 1 + */ +export type DaypartTargets = [DaypartTarget, ...DaypartTarget[]]; +/** + * Restrict delivery to members of these first-party CRM audiences. Only users present in the uploaded lists are eligible. References audience_id values from sync_audiences on the same seller account — audience IDs are not portable across sellers. Not for lookalike expansion — express that intent in the campaign brief. Seller must declare support in get_adcp_capabilities. + * + * @minItems 1 + */ +export type AudienceInclude = [string, ...string[]]; +/** + * Suppress delivery to members of these first-party CRM audiences. Matched users are excluded regardless of other targeting. References audience_id values from sync_audiences on the same seller account — audience IDs are not portable across sellers. Seller must declare support in get_adcp_capabilities. + * + * @minItems 1 + */ +export type AudienceExclude = [string, ...string[]]; /** * Buy-time selection of one seller-offered signal inside a package signal targeting group. The signal_ref uses scope 'product' for a product-local signal option, scope 'data_provider' for a signal defined in a data provider's published adagents.json signals[], or scope 'signal_source' for a source-native signal that is not published in adagents.json signals[]. The selected product's inline Product.signal_targeting_options, get_signals feed when inline options are omitted, and signal_targeting_rules define buy-time eligibility. Inclusion and exclusion are controlled by the parent group operator: use operator 'any' to include users matching the signal expression and operator 'none' to exclude users matching the signal expression. For binary signals, value MUST be true; do not use value=false for exclusion inside signal_targeting_groups. Use audience_include/audience_exclude only for buyer-managed first-party audiences registered through sync_audiences. */ @@ -6179,9 +6181,9 @@ export type DemographicAgeRange = { include_unknown: boolean; }; /** - * Frequency capping settings for package-level application. Two types of frequency control can be used independently or together: suppress enforces a cooldown between consecutive exposures; max_impressions + per + window caps total exposures per entity in a time window. When both suppress and max_impressions are set, an impression is delivered only if both constraints permit it (AND semantics). At least one of suppress, suppress_minutes, or max_impressions must be set. + * Frequency capping settings for package-level application. Two types of frequency control can be used independently or together: suppress enforces a cooldown between consecutive exposures; max_impressions + per + window caps total exposures per entity in a time window. When both suppress and max_impressions are set, an impression is delivered only if both constraints permit it (AND semantics). At least one of suppress, suppress_minutes, or max_impressions must be set. Field location determines scope; this value has no scope discriminator. The MediaBuy root uses the narrower media-buy-frequency-cap schema, which permits maximum impressions only in 3.2. */ -export type FrequencyCap = { +export type TargetingFrequencyCap = { } & { /** * Cooldown period between consecutive exposures to the same entity. Prevents back-to-back ad delivery (e.g. {"interval": 60, "unit": "minutes"} for a 1-hour cooldown). Preferred over suppress_minutes. @@ -6193,7 +6195,7 @@ export type FrequencyCap = { */ suppress_minutes?: number; /** - * Maximum number of impressions per entity per window. For duration windows, implementations typically use a rolling window; 'campaign' applies a fixed cap across the full flight. + * Maximum number of impressions per entity per window. For duration windows, implementations typically use a rolling window. campaign applies across the owning field's full flight: the package flight for a targeting overlay, or the MediaBuy flight for a root cap. */ max_impressions?: number; /** @@ -6206,7 +6208,7 @@ export type FrequencyCap = { window?: Duration; }; /** - * Purchased placement selection within the product. This constrains package inventory; it is distinct from creative_assignments[].placement_refs, which only route individual creatives within the purchased set. On create, mode selected supplies the complete selected set and mode default uses the product default. On update, the surrounding targeting_overlay replacement semantics apply. + * Purchased placement selection within the product. This constrains package inventory; it is distinct from creative_assignments[].placement_refs, which only route individual creatives within the purchased set. On create, mode selected supplies the complete selected set and mode default uses the product default. In request-side Targeting Input, a non-null value replaces this dimension, omission preserves or inherits it, and null clears it when the product permits that broader inventory set. */ export type PlacementSelection = SelectedPlacements | ProductDefaultPlacements; /** @@ -6214,9 +6216,142 @@ export type PlacementSelection = SelectedPlacements | ProductDefaultPlacements; */ export type PlacementIdentity = PublisherCatalogPlacementIdentity | SellerInlinePlacementIdentity; /** - * Purchased collection selection within the product. On create, mode selected supplies the complete selected set and mode default uses the product's full bundle. On package readback this is the committed selection sellers MUST echo as concrete selectors, materializing any collection_list composition; collection_list fields remain the buyer-managed list mechanism. On update, the surrounding targeting_overlay replacement semantics apply. + * Purchased collection selection within the product. On create, mode selected supplies the complete selected set and mode default uses the product's full bundle. On package readback this is the committed selection sellers MUST echo as concrete selectors, materializing any collection_list composition; collection_list fields remain the buyer-managed list mechanism. In request-side Targeting Input, a non-null value replaces this dimension, omission preserves or inherits it, and null clears it when the product permits that broader inventory set. */ -export type CollectionSelection = SelectedCollections | ProductDefaultCollections; +export type TargetingCollectionSelection = SelectedCollections | ProductDefaultCollections; +/** + * Exclude specific operating-system platforms from delivery. When a platform appears in both device_platform and device_platform_exclude, exclusion wins. Sellers MUST reject a request they cannot enforce rather than silently dropping the exclusion. + * + * @minItems 1 + */ +export type DevicePlatformExclude = [DevicePlatform, ...DevicePlatform[]]; +/** + * Exclude specific device form factors from delivery (e.g., exclude CTV for app-install campaigns). + * + * @minItems 1 + */ +export type DeviceTypeExclude = [DeviceType, ...DeviceType[]]; +/** + * Restrict delivery to specific canonical browser families in the impression delivery and rendering environment, not the post-click landing-page browser. Values MUST NOT be inferred solely from operating system, device, web/mobile-web inventory, or placement. Values in this array use OR semantics. When browser is supplied, families not listed are ineligible: other includes a seller-recognized family that is not explicitly enumerated, while unknown includes a browser the seller cannot classify into a recognized family. When the same family appears in browser and browser_exclude, exclusion wins. Browser and device constraints intersect; a seller that cannot enforce the exact combination MUST exclude or explicitly reconfigure the product during discovery and MUST reject it at create or update rather than silently widening delivery. Browser versions and seller-native IDs are intentionally unsupported. + * + * @minItems 1 + */ +export type Browser = [BrowserFamily, ...BrowserFamily[]]; +/** + * Exclude specific canonical browser families from delivery. other excludes seller-recognized families that are not explicitly enumerated; unknown excludes browsers the seller cannot classify into a recognized family. When the same family appears in browser and browser_exclude, exclusion wins. Sellers MUST reject a request they cannot enforce rather than silently dropping the exclusion. + * + * @minItems 1 + */ +export type BrowserExclude = [BrowserFamily, ...BrowserFamily[]]; +/** + * Target users within store catchment areas from a synced store catalog. Each entry references a store-type catalog and optionally narrows to specific stores or catchment zones. + * + * @minItems 1 + */ +export type StoreCatchments = [ + { + /** + * Synced store-type catalog ID from sync_catalogs. + */ + catalog_id: string; + /** + * Filter to specific stores within the catalog. Omit to target all stores. + * + * @minItems 1 + */ + store_ids?: [string, ...string[]]; + /** + * Catchment zone IDs to target (e.g., 'walk', 'drive'). Omit to target all catchment zones. + * + * @minItems 1 + */ + catchment_ids?: [string, ...string[]]; + }, + ...{ + /** + * Synced store-type catalog ID from sync_catalogs. + */ + catalog_id: string; + /** + * Filter to specific stores within the catalog. Omit to target all stores. + * + * @minItems 1 + */ + store_ids?: [string, ...string[]]; + /** + * Catchment zone IDs to target (e.g., 'walk', 'drive'). Omit to target all catchment zones. + * + * @minItems 1 + */ + catchment_ids?: [string, ...string[]]; + }[] +]; +/** + * Target users within travel time, distance, or a custom boundary around arbitrary geographic points. Multiple entries use OR semantics — a user within range of any listed point is eligible. For campaigns targeting 10+ locations, consider using store_catchments with a location catalog instead. Seller must declare support in get_adcp_capabilities. + * + * @minItems 1 + */ +export type GeoProximity = [ + ( + | { + } + | { + } + | { + } + ), + ...( + | { + } + | { + } + | { + } + )[] +]; +/** + * Restrict to users with specific language preferences using canonical BCP 47 language ranges. Each buyer range is evaluated against a user's language-preference tag with RFC 4647 section 3.3.1 Basic Filtering: 'fr' matches 'fr', 'fr-CA', and 'fr-FR', while 'fr-CA' matches 'fr-CA' and more-specific descendants but not 'fr' or 'fr-FR'. Values use OR logic. + * + * @minItems 1 + */ +export type TargetingLanguages = [LanguageTag, ...LanguageTag[]] | null; +/** + * Keyword targeting for search and retail media platforms. Restricts delivery to queries matching the specified keywords. Each keyword is identified by the tuple (keyword, match_type) — the same keyword string with different match types are distinct targets. Sellers SHOULD reject duplicate (keyword, match_type) pairs within a single request. Seller must declare support in get_adcp_capabilities. + * + * @minItems 1 + */ +export type TargetingKeywords = + | [ + { + /** + * The keyword to target + */ + keyword: string; + match_type: MatchType; + /** + * Per-keyword bid price, denominated in the same currency as the package's pricing option. Overrides the package-level bid_price for this keyword. Inherits the max_bid interpretation from the pricing option: when max_bid is true, this is the keyword's bid ceiling; when false, this is the exact bid. If omitted, the package bid_price applies. + */ + bid_price?: number; + }, + ...{ + /** + * The keyword to target + */ + keyword: string; + match_type: MatchType; + /** + * Per-keyword bid price, denominated in the same currency as the package's pricing option. Overrides the package-level bid_price for this keyword. Inherits the max_bid interpretation from the pricing option: when max_bid is true, this is the keyword's bid ceiling; when false, this is the exact bid. If omitted, the package bid_price applies. + */ + bid_price?: number; + }[] + ] + | null; +/** + * Keywords to exclude from delivery. Queries matching these keywords will not trigger the ad. Each negative keyword is identified by the tuple (keyword, match_type). Seller must declare support in get_adcp_capabilities. + * + * @minItems 1 + */ +export type TargetingNegativeKeywords = [NegativeKeyword, ...NegativeKeyword[]] | null; /** * Assignment of a creative asset to a package with optional rotation and placement routing. Used in create_media_buy and update_media_buy requests. Buyers identify the stored creative with `creative_id` only. A generic `id` alias, if present due to adapter-internal payload reuse, is not an AdCP identifier and sellers MUST ignore it on input. Note: sync_creatives does not support package rotation, placement_refs, or placement_ids - use create/update_media_buy for package-level trafficking controls. */ @@ -7757,7 +7892,7 @@ export interface PackageUpdate { * Replace all optimization goals for this package. Uses replacement semantics — omit to leave goals unchanged. */ optimization_goals?: OptimizationGoal[]; - targeting_overlay?: TargetingOverlay; + targeting_overlay?: TargetingOverlayInput; /** * Keyword targets to add or update on this package. Upserts by (keyword, match_type) identity: if the pair already exists, its bid_price is updated; if not, a new keyword target is added. Use targeting_overlay.keyword_targets in create_media_buy to set the initial list. */ @@ -7808,7 +7943,7 @@ export interface PackageUpdate { match_type: MatchType; }[]; /** - * Replace creative assignments for this package with optional rotation, grouping, weights, and placement routing. Uses replacement semantics - omit to leave assignments unchanged. rotation_mode is package-scoped: omission resolves to weighted, and every assignment MUST resolve to the same effective mode. In sequential mode, sequence_position MUST be unique within each package-local group. Sellers reject conflicts with VALIDATION_ERROR before mutation. When the same mutation narrows targeting_overlay.placement_selection, this complete replacement MUST remove or reroute every assignment reference that would otherwise be orphaned; the seller validates both changes atomically. + * Replace creative assignments for this package with optional rotation, grouping, weights, and placement routing. Uses replacement semantics - omit to leave assignments unchanged. rotation_mode is package-scoped: omission resolves to weighted, and every assignment MUST resolve to the same effective mode. In sequential mode, sequence_position MUST be unique within each package-local group. Sellers reject conflicts with VALIDATION_ERROR before mutation. When the same mutation narrows or clears targeting_overlay.placement_selection, this complete replacement MUST remove or reroute every assignment reference that would otherwise be orphaned; the seller validates both changes atomically. */ creative_assignments?: CreativeAssignment[]; /** @@ -7898,6 +8033,28 @@ export interface AttributionWindow { post_view?: Duration; model?: AttributionModel; } +/** + * Unknown-age delivery cannot satisfy a minimum-age eligibility policy. When demographic audience targeting and age_restriction are both present, include_unknown must be false. + */ +export interface TargetingUnknownAgeEligibilityConstraint { +} +/** + * A legal verification requirement always narrows demographic targeting. When the buyer supplies accepted_bases and age_restriction requires verification, verified must be accepted; otherwise the constraints have an empty intersection and the request is invalid. + */ +export interface TargetingVerifiedAgeBasisConstraint { +} +/** + * A targeted metro area. + */ +export interface GeoMetro { + system: MetroAreaSystem; + /** + * Metro codes within the system (e.g., ['501', '602'] for Nielsen DMAs) + * + * @minItems 1 + */ + values: [string, ...string[]]; +} /** * @deprecated */ @@ -7940,7 +8097,7 @@ export interface DaypartTarget { /** * Basic Boolean grouping for seller-offered signals. v1 supports a required top-level operator 'all' and child groups with operator 'any' for include groups or 'none' for exclusion groups. Example semantics: group 1 any(A, B) plus group 2 none(C, D) means (A OR B) AND NOT (C OR D). Signal entries reference named signal definitions with signal_ref scope 'product' for product-local signal options or scope 'data_provider' for external signals published in adagents.json signals[]. For simple include-only targeting, send one child group with operator 'any'. Sellers SHOULD reject entries that are not available for the product through inline signal_targeting_options or get_signals, are not active for the account, or exceed the product's signal_targeting_allowed/signal_targeting_rules/product terms. Signal targeting limits are product-scoped, not declared in get_adcp_capabilities, because products may be backed by different ad servers. Sellers MUST echo applied signal_targeting_groups on the resulting package state, including fixed/default selections. Sellers MAY return REQUOTE_REQUIRED when a targeting mutation changes commercial terms. */ -export interface PackageSignalTargetingGroups { +export interface TargetingSignalGroups { /** * Groups-level operator. Required even though v1 only supports 'all': every child group must be satisfied. */ @@ -7977,6 +8134,23 @@ export interface DemographicTargetingIntent { /** * Reference to a property list for targeting specific properties within this product. The package runs on the intersection of the product's publisher_properties and this list. Sellers SHOULD return a validation error if the product has property_targeting_allowed: false. */ +export interface TargetingPropertyList { + /** + * URL of the agent managing the property list + */ + agent_url: string; + /** + * Identifier for the property list within the agent + */ + list_id: string; + /** + * JWT or other authorization token for accessing the list. Optional if the list is public or caller has implicit access. + */ + auth_token?: string; +} +/** + * Reference to a property list whose properties must not carry the buyer's ads. Matched properties are removed from delivery. Use for brand-safety do-not-run lists (apps, sites). Exclude wins on overlap with property_list, and applies regardless of the product's property_targeting_allowed flag. Seller must declare support in get_adcp_capabilities. + */ export interface PropertyListReference { /** * URL of the agent managing the property list @@ -7994,6 +8168,23 @@ export interface PropertyListReference { /** * Reference to a collection list for including specific collections (programs, publications, channels) within this product. The package runs on the intersection of matched collections and this list. Use for inclusion-based collection targeting. Seller must declare support in get_adcp_capabilities. */ +export interface TargetingCollectionList { + /** + * URL of the agent managing the collection list + */ + agent_url: string; + /** + * Identifier for the collection list within the agent + */ + list_id: string; + /** + * JWT or other authorization token for accessing the list. Optional if the list is public or caller has implicit access. + */ + auth_token?: string; +} +/** + * Reference to a collection list for excluding specific collections (programs, publications, channels) from this product. Matched collections must not carry the buyer's ads. Use for brand safety do-not-air lists. Seller must declare support in get_adcp_capabilities. + */ export interface CollectionListReference { /** * URL of the agent managing the collection list @@ -8096,6 +8287,35 @@ export interface ProductDefaultCollections { mode: 'default'; ext?: ExtensionObject; } +/** + * Age restriction for compliance. Use for legal requirements (alcohol, gambling), not audience targeting. + */ +export interface AgeRestriction { + /** + * Minimum age required + */ + min: number; + /** + * Whether verified age (not inferred) is required for compliance + */ + verification_required?: boolean; + /** + * Accepted verification methods. If omitted, any method the platform supports is acceptable. + * + * @minItems 1 + */ + accepted_methods?: [AgeVerificationMethod, ...AgeVerificationMethod[]]; +} +/** + * An excluded keyword. + */ +export interface NegativeKeyword { + /** + * The keyword to exclude + */ + keyword: string; + match_type: MatchType; +} /** * @deprecated * **DEPRECATED in 3.2.** Legacy named-format path retained for older 3.x peers. New creative assets use `format_kind` and optional `format_option_ref`. @@ -15902,6 +16122,10 @@ export type ReportingDeliveryConfiguration = { coverage_requirement: 'full' | 'allow_partial'; required_finality: ReportingFinality; reconciliation_mode: ReportingReconciliationMode; + /** + * Reserved: which party's count of this feed is authoritative. seller (the default, and the only value any 3.2 seller accepts) means the seller produces every revision and the consumer may only attest to what it consumed. consumer is reserved for the buyer-deposited billing revision task scoped to a later minor; until that task exists sellers MUST reject it with UNSUPPORTED_FEATURE. Reserving the field now keeps a future buyer-basis billing feed additive instead of breaking the billing-feed constraints. See https://github.com/adcontextprotocol/adcp/issues/7440. + */ + authoritative_party?: 'seller' | 'consumer'; schedule: ReportingSchedule; method?: ReportingDeliveryMethod; /** @@ -15915,7 +16139,7 @@ export type ReportingDeliveryConfiguration = { export type ReportingFeedPurpose = 'pacing' | 'analytics' | 'billing'; export type ReportingMediaBuyID = string; /** - * Whether producer-side delivery evidence is sufficient or the selected consumer must submit an authenticated matching receipt. Billing MUST use consumer_receipt. + * Whether producer-side delivery evidence is sufficient or the selected consumer must submit an authenticated matching receipt. A seller-authoritative billing feed MUST use consumer_receipt. */ export type ReportingReconciliationMode = 'delivery_only' | 'consumer_receipt'; /** @@ -15952,7 +16176,176 @@ export type ReportingDeliveryConfigurationLifecycleState = | 'action_required' | 'inactive'; export type ReportingPackageID = string; +/** + * Structured reporting condition that explains delayed or action_required health without exposing credentials, provider response bodies, or internal stack traces. + */ +export type ReportingStatusIssue = { +} & { + /** + * Seller-issued stable identifier for this logical issue: re-emissions and later polls of the same unresolved condition reuse it, and resolution retires it, so consumers can project AdCP reporting issues into durable work items. A recurrence after resolution receives a new id. + */ + issue_id: string; + code: + | 'REPORT_OVERDUE' + | 'PRODUCTION_FAILED' + | 'DELIVERY_FAILED' + | 'ACCESS_REQUIRED' + | 'CONFIGURATION_REQUIRED' + | 'REPORTING_COVERAGE_INCOMPLETE' + | 'RESOURCE_EXPIRED' + | 'READER_INCOMPATIBLE' + | 'HISTORY_UNAVAILABLE' + | 'RECEIPT_REQUIRED' + | 'RECEIPT_REJECTED' + | 'ADJUSTMENT_RECEIPT_REQUIRED' + | 'ADJUSTMENT_RECEIPT_REJECTED' + | 'CONSUMER_STATUS_MISMATCH'; + severity: ReportingStatusSeverity; + /** + * When the seller first observed this logical condition, carried unchanged across every re-emission until the issue is retired. It anchors the escalation clock advertised as consumer_mismatch_escalation_seconds and lets a consumer age an issue without keeping its own first-seen table. Required when code is CONSUMER_STATUS_MISMATCH. + */ + opened_at?: string; + /** + * Optional seller-maintained lifecycle for this issue_id. open is the default when omitted. acknowledged means a human on responsible_party has taken it up but the condition persists. resolved means the underlying condition no longer holds; a recurrence uses a new issue_id. waived means the parties agreed off-protocol to stop acting on it. Only open and acknowledged issues appear in issues[]; retiring an issue removes it from the projection rather than publishing it at resolved or waived, so a reader that treats a nonempty issues[] as degradation stays correct. Retiring is never a way to discharge a condition that still holds: for CONSUMER_STATUS_MISMATCH see the consumer_mismatch_lifecycle rule. + */ + issue_state?: 'open' | 'acknowledged' | 'resolved' | 'waived'; + /** + * Optional opaque, non-secret correlation string for the party's own tracker — a ticket key, incident ID, or case number. Untrusted display text only. The character class excludes whitespace and the solidus, so the value cannot express a URL or a sentence; receivers compare, store, and display it as inert text and never dereference, resolve, or execute it. It confers no authorization and MUST NOT be used to look up state across accounts or callers. + */ + external_ref?: string; + responsible_party: 'buyer' | 'seller' | 'provider'; + recommended_action: + | 'wait_for_retry' + | 'contact_buyer' + | 'contact_seller' + | 'contact_provider' + | 'repair_access' + | 'update_configuration' + | 'change_reporting_scope' + | 'use_supported_reader'; + /** + * Untrusted display text only. SDKs and agents dispatch exclusively on closed code/recommended_action values and never execute embedded links or instructions. + */ + message?: string; + reporting_obligation_id?: string; + /** + * Current authenticated consumer status statement that caused this mismatch. + */ + reporting_status_id?: string; + delivery_config_id?: string; + delivery_config_version?: number; + feed_purpose?: ReportingFeedPurpose; + /** + * @minItems 1 + */ + media_buy_ids?: [ReportingMediaBuyID, ...ReportingMediaBuyID[]]; + /** + * @minItems 1 + */ + package_ids?: [ReportingPackageID, ...ReportingPackageID[]]; + period_start?: string; + period_end?: string; + expected_at?: string; +} & { + /** + * Seller-issued stable identifier for this logical issue: re-emissions and later polls of the same unresolved condition reuse it, and resolution retires it, so consumers can project AdCP reporting issues into durable work items. A recurrence after resolution receives a new id. + */ + issue_id: string; + code: + | 'REPORT_OVERDUE' + | 'PRODUCTION_FAILED' + | 'DELIVERY_FAILED' + | 'ACCESS_REQUIRED' + | 'CONFIGURATION_REQUIRED' + | 'REPORTING_COVERAGE_INCOMPLETE' + | 'RESOURCE_EXPIRED' + | 'READER_INCOMPATIBLE' + | 'HISTORY_UNAVAILABLE' + | 'RECEIPT_REQUIRED' + | 'RECEIPT_REJECTED' + | 'ADJUSTMENT_RECEIPT_REQUIRED' + | 'ADJUSTMENT_RECEIPT_REJECTED' + | 'CONSUMER_STATUS_MISMATCH'; + severity: ReportingStatusSeverity; + /** + * When the seller first observed this logical condition, carried unchanged across every re-emission until the issue is retired. It anchors the escalation clock advertised as consumer_mismatch_escalation_seconds and lets a consumer age an issue without keeping its own first-seen table. Required when code is CONSUMER_STATUS_MISMATCH. + */ + opened_at?: string; + /** + * Optional seller-maintained lifecycle for this issue_id. open is the default when omitted. acknowledged means a human on responsible_party has taken it up but the condition persists. resolved means the underlying condition no longer holds; a recurrence uses a new issue_id. waived means the parties agreed off-protocol to stop acting on it. Only open and acknowledged issues appear in issues[]; retiring an issue removes it from the projection rather than publishing it at resolved or waived, so a reader that treats a nonempty issues[] as degradation stays correct. Retiring is never a way to discharge a condition that still holds: for CONSUMER_STATUS_MISMATCH see the consumer_mismatch_lifecycle rule. + */ + issue_state?: 'open' | 'acknowledged' | 'resolved' | 'waived'; + /** + * Optional opaque, non-secret correlation string for the party's own tracker — a ticket key, incident ID, or case number. Untrusted display text only. The character class excludes whitespace and the solidus, so the value cannot express a URL or a sentence; receivers compare, store, and display it as inert text and never dereference, resolve, or execute it. It confers no authorization and MUST NOT be used to look up state across accounts or callers. + */ + external_ref?: string; + responsible_party: 'buyer' | 'seller' | 'provider'; + recommended_action: + | 'wait_for_retry' + | 'contact_buyer' + | 'contact_seller' + | 'contact_provider' + | 'repair_access' + | 'update_configuration' + | 'change_reporting_scope' + | 'use_supported_reader'; + /** + * Untrusted display text only. SDKs and agents dispatch exclusively on closed code/recommended_action values and never execute embedded links or instructions. + */ + message?: string; + reporting_obligation_id?: string; + /** + * Current authenticated consumer status statement that caused this mismatch. + */ + reporting_status_id?: string; + delivery_config_id?: string; + delivery_config_version?: number; + feed_purpose?: ReportingFeedPurpose; + /** + * @minItems 1 + */ + media_buy_ids?: [ReportingMediaBuyID, ...ReportingMediaBuyID[]]; + /** + * @minItems 1 + */ + package_ids?: [ReportingPackageID, ...ReportingPackageID[]]; + period_start?: string; + period_end?: string; + expected_at?: string; +}; export type ReportingStatusSeverity = 'delayed' | 'action_required'; +/** + * Current hard MediaBuy-level cap. Sellers MUST echo it whenever set. Its counter aggregates exposures across all participating packages; each package targeting_overlay.frequency_cap remains independently binding. + */ +export type MediaBuyFrequencyCap = FrequencyCap & { +}; +/** + * Frequency capping settings for package-level application. Two types of frequency control can be used independently or together: suppress enforces a cooldown between consecutive exposures; max_impressions + per + window caps total exposures per entity in a time window. When both suppress and max_impressions are set, an impression is delivered only if both constraints permit it (AND semantics). At least one of suppress, suppress_minutes, or max_impressions must be set. Field location determines scope; this value has no scope discriminator. The MediaBuy root uses the narrower media-buy-frequency-cap schema, which permits maximum impressions only in 3.2. + */ +export type FrequencyCap = { +} & { + /** + * Cooldown period between consecutive exposures to the same entity. Prevents back-to-back ad delivery (e.g. {"interval": 60, "unit": "minutes"} for a 1-hour cooldown). Preferred over suppress_minutes. + */ + suppress?: Duration; + /** + * @deprecated + * Deprecated — use suppress instead. Cooldown period in minutes between consecutive exposures to the same entity (e.g. 60 for a 1-hour cooldown). + */ + suppress_minutes?: number; + /** + * Maximum number of impressions per entity per window. For duration windows, implementations typically use a rolling window. campaign applies across the owning field's full flight: the package flight for a targeting overlay, or the MediaBuy flight for a root cap. + */ + max_impressions?: number; + /** + * Entity granularity for impression counting. Required when max_impressions is set. + */ + per?: ReachUnit; + /** + * Time window for the max_impressions cap (e.g. {"interval": 7, "unit": "days"} or {"interval": 1, "unit": "campaign"} for the full flight). Required when max_impressions is set. + */ + window?: Duration; +}; /** * How a media buy's total budget is allocated across its packages. Fixed allocation preserves independent package budgets. Seller-optimized allocation delegates continuous cross-package allocation to the seller within the media-buy total, package caps, minimum-spend targets, flight windows, and pacing controls. When a seller-optimized media-buy BiddingPolicy carries cost_per or roas, that control binds to this allocation block's primary optimization goal rather than independently to each package goal. */ @@ -16341,6 +16734,254 @@ export type AttestationEvaluation = { }; ext?: ExtensionObject; }; +/** + * Complete effective targeting accepted for this package, including targeting bound through configured product selection plus package-specific targeting. Sellers MUST echo an applied package frequency_cap independently from any MediaBuy root cap. Sellers MUST also echo placement, property, and collection selection so buyers can audit purchased inventory: placements via placement_selection, collections via collection_selection (the committed concrete selectors, materialized even when the selection was produced through collection_list references). + */ +export type TargetingOverlay = TargetingUnknownAgeEligibilityConstraint & + TargetingVerifiedAgeBasisConstraint & { + /** + * Restrict delivery to specific countries. ISO 3166-1 alpha-2 codes (e.g., 'US', 'GB', 'DE'). + * + * @minItems 1 + */ + geo_countries?: [string, ...string[]]; + /** + * Exclude specific countries from delivery. ISO 3166-1 alpha-2 codes (e.g., 'US', 'GB', 'DE'). + * + * @minItems 1 + */ + geo_countries_exclude?: [string, ...string[]]; + /** + * Restrict delivery to exact canonical ISO 3166-2 subdivisions (states, provinces, regions, departments, or other subdivision categories). Unknown identifiers are invalid. At create or update, sellers MUST reject unsupported identifiers and MUST NOT silently widen, drop, or partially apply the list. During get_products, a seller may instead return a sparse, buyer-reviewable targeting_resolution modification for a valid but unsupported requested outcome. Exact internal translation preserves accepted identifiers in package readback. + * + * @minItems 1 + */ + geo_regions?: [string, ...string[]]; + /** + * Exclude exact canonical ISO 3166-2 subdivisions. Support is independent from geo_regions inclusion support. Unknown identifiers and values also present in geo_regions are invalid. At create or update, sellers MUST reject unsupported identifiers and partial application; during get_products, a seller may instead return a sparse, buyer-reviewable targeting_resolution modification for a valid but unsupported requested outcome. + * + * @minItems 1 + */ + geo_regions_exclude?: [string, ...string[]]; + geo_metros?: TargetingGeoMetros; + /** + * Exclude specific metro areas from delivery. Each entry specifies the classification system and excluded values. Seller must declare supported systems in get_adcp_capabilities. + * + * @minItems 1 + */ + geo_metros_exclude?: [ + { + system: MetroAreaSystem; + /** + * Metro codes to exclude within the system (e.g., ['501', '602'] for Nielsen DMAs) + * + * @minItems 1 + */ + values: [string, ...string[]]; + }, + ...{ + system: MetroAreaSystem; + /** + * Metro codes to exclude within the system (e.g., ['501', '602'] for Nielsen DMAs) + * + * @minItems 1 + */ + values: [string, ...string[]]; + }[] + ]; + /** + * Restrict delivery to specific postal areas. Prefer the native country + postal system form. The deprecated legacy country-fused postal-system tokens remain accepted for compatibility. Seller must declare supported systems in get_adcp_capabilities. + * + * @minItems 1 + */ + geo_postal_areas?: [PostalArea, ...PostalArea[]]; + /** + * Exclude specific postal areas from delivery. Prefer the native country + postal system form. The deprecated legacy country-fused postal-system tokens remain accepted for compatibility. Seller must declare supported systems in get_adcp_capabilities. + * + * @minItems 1 + */ + geo_postal_areas_exclude?: [PostalArea, ...PostalArea[]]; + /** + * Restrict delivery to catalog-backed named places. Values MUST be stable identifiers in the declared system, not display names. Sellers must declare supported systems, countries, and place types in get_adcp_capabilities and reject unsupported entries rather than silently dropping them. + * + * @minItems 1 + */ + geo_places?: [GeographicPlaceArea, ...GeographicPlaceArea[]]; + /** + * Exclude catalog-backed named places. Uses the same identifier-based shape as geo_places. Sellers MUST reject overlap with geo_places for the same country, system, place_type, and value. + * + * @minItems 1 + */ + geo_places_exclude?: [GeographicPlaceArea, ...GeographicPlaceArea[]]; + /** + * Restrict delivery to specific time windows. Each entry specifies days of week, an hour range, and an optional timezone that defaults to inventory_local. A concrete IANA zone uses one shared civil-time clock, while inventory_local evaluates each inventory unit in its seller-assigned local timezone. Entries are independent and MAY use different clocks. + * + * @minItems 1 + */ + daypart_targets?: [DaypartTarget, ...DaypartTarget[]]; + /** + * @deprecated + * Deprecated: Use TMP provider fields instead. AXE segment ID to include for targeting. + */ + axe_include_segment?: string; + /** + * @deprecated + * Deprecated: Use TMP provider fields instead. AXE segment ID to exclude from targeting. + */ + axe_exclude_segment?: string; + /** + * Restrict delivery to members of these first-party CRM audiences. Only users present in the uploaded lists are eligible. References audience_id values from sync_audiences on the same seller account — audience IDs are not portable across sellers. Not for lookalike expansion — express that intent in the campaign brief. Seller must declare support in get_adcp_capabilities. + * + * @minItems 1 + */ + audience_include?: [string, ...string[]]; + /** + * Suppress delivery to members of these first-party CRM audiences. Matched users are excluded regardless of other targeting. References audience_id values from sync_audiences on the same seller account — audience IDs are not portable across sellers. Seller must declare support in get_adcp_capabilities. + * + * @minItems 1 + */ + audience_exclude?: [string, ...string[]]; + signal_targeting_groups?: TargetingSignalGroups; + /** + * @deprecated + * DEPRECATED. Use signal_targeting_groups for package-level signal targeting. Legacy flat signal_targeting remains accepted during the SignalRef migration window but cannot express grouped include/exclude composition or product-scoped pricing. + * + * @minItems 1 + */ + signal_targeting?: [SignalTargeting, ...SignalTargeting[]]; + demographics?: DemographicTargetingIntent; + frequency_cap?: FrequencyCap; + property_list?: TargetingPropertyList; + property_list_exclude?: PropertyListReference; + collection_list?: TargetingCollectionList; + collection_list_exclude?: CollectionListReference; + placement_selection?: PlacementSelection; + collection_selection?: TargetingCollectionSelection; + /** + * Age restriction for compliance. Use for legal requirements (alcohol, gambling), not audience targeting. + */ + age_restriction?: { + /** + * Minimum age required + */ + min: number; + /** + * Whether verified age (not inferred) is required for compliance + */ + verification_required?: boolean; + /** + * Accepted verification methods. If omitted, any method the platform supports is acceptable. + * + * @minItems 1 + */ + accepted_methods?: [AgeVerificationMethod, ...AgeVerificationMethod[]]; + }; + /** + * Restrict to specific platforms. Use for technical compatibility (app only works on iOS). Values from Sec-CH-UA-Platform standard, extended for CTV. + * + * @minItems 1 + */ + device_platform?: [DevicePlatform, ...DevicePlatform[]]; + /** + * Exclude specific operating-system platforms from delivery. When a platform appears in both device_platform and device_platform_exclude, exclusion wins. Sellers MUST reject a request they cannot enforce rather than silently dropping the exclusion. + * + * @minItems 1 + */ + device_platform_exclude?: [DevicePlatform, ...DevicePlatform[]]; + /** + * Restrict to specific device form factors. Use for campaigns targeting hardware categories rather than operating systems (e.g., mobile-only promotions, CTV campaigns). + * + * @minItems 1 + */ + device_type?: [DeviceType, ...DeviceType[]]; + /** + * Exclude specific device form factors from delivery (e.g., exclude CTV for app-install campaigns). + * + * @minItems 1 + */ + device_type_exclude?: [DeviceType, ...DeviceType[]]; + /** + * Restrict delivery to specific canonical browser families in the impression delivery and rendering environment, not the post-click landing-page browser. Values MUST NOT be inferred solely from operating system, device, web/mobile-web inventory, or placement. Values in this array use OR semantics. When browser is supplied, families not listed are ineligible: other includes a seller-recognized family that is not explicitly enumerated, while unknown includes a browser the seller cannot classify into a recognized family. When the same family appears in browser and browser_exclude, exclusion wins. Browser and device constraints intersect; a seller that cannot enforce the exact combination MUST exclude or explicitly reconfigure the product during discovery and MUST reject it at create or update rather than silently widening delivery. Browser versions and seller-native IDs are intentionally unsupported. + * + * @minItems 1 + */ + browser?: [BrowserFamily, ...BrowserFamily[]]; + /** + * Exclude specific canonical browser families from delivery. other excludes seller-recognized families that are not explicitly enumerated; unknown excludes browsers the seller cannot classify into a recognized family. When the same family appears in browser and browser_exclude, exclusion wins. Sellers MUST reject a request they cannot enforce rather than silently dropping the exclusion. + * + * @minItems 1 + */ + browser_exclude?: [BrowserFamily, ...BrowserFamily[]]; + /** + * Target users within store catchment areas from a synced store catalog. Each entry references a store-type catalog and optionally narrows to specific stores or catchment zones. + * + * @minItems 1 + */ + store_catchments?: [ + { + /** + * Synced store-type catalog ID from sync_catalogs. + */ + catalog_id: string; + /** + * Filter to specific stores within the catalog. Omit to target all stores. + * + * @minItems 1 + */ + store_ids?: [string, ...string[]]; + /** + * Catchment zone IDs to target (e.g., 'walk', 'drive'). Omit to target all catchment zones. + * + * @minItems 1 + */ + catchment_ids?: [string, ...string[]]; + }, + ...{ + /** + * Synced store-type catalog ID from sync_catalogs. + */ + catalog_id: string; + /** + * Filter to specific stores within the catalog. Omit to target all stores. + * + * @minItems 1 + */ + store_ids?: [string, ...string[]]; + /** + * Catchment zone IDs to target (e.g., 'walk', 'drive'). Omit to target all catchment zones. + * + * @minItems 1 + */ + catchment_ids?: [string, ...string[]]; + }[] + ]; + /** + * Target users within travel time, distance, or a custom boundary around arbitrary geographic points. Multiple entries use OR semantics — a user within range of any listed point is eligible. For campaigns targeting 10+ locations, consider using store_catchments with a location catalog instead. Seller must declare support in get_adcp_capabilities. + * + * @minItems 1 + */ + geo_proximity?: [ + ( + | { + } + | { + } + | { + } + ), + ...( + | { + } + | { + } + | { + } + )[] + ]; + language?: TargetingLanguages; + keyword_targets?: TargetingKeywords; + negative_keywords?: TargetingNegativeKeywords; + }; /** * Canonical demographic predicate and exact seller execution details. Include whenever demographic targeting was requested or applied. */ @@ -16648,6 +17289,7 @@ export interface MediaBuy { * @minimum 0 */ daily_budget_cap?: number; + frequency_cap?: MediaBuyFrequencyCap; /** * IANA timezone defining the shared calendar-day boundary for every aggregate and package daily cap on this media buy. Sellers MUST echo it whenever any daily cap is set. */ @@ -16920,64 +17562,6 @@ export interface ReportingCoverage { package_ids?: [ReportingPackageID, ...ReportingPackageID[]]; }[]; } -/** - * Structured reporting condition that explains delayed or action_required health without exposing credentials, provider response bodies, or internal stack traces. - */ -export interface ReportingStatusIssue { - /** - * Seller-issued stable identifier for this logical issue: re-emissions and later polls of the same unresolved condition reuse it, and resolution retires it, so consumers can project AdCP reporting issues into durable work items. A recurrence after resolution receives a new id. - */ - issue_id: string; - code: - | 'REPORT_OVERDUE' - | 'PRODUCTION_FAILED' - | 'DELIVERY_FAILED' - | 'ACCESS_REQUIRED' - | 'CONFIGURATION_REQUIRED' - | 'REPORTING_COVERAGE_INCOMPLETE' - | 'RESOURCE_EXPIRED' - | 'READER_INCOMPATIBLE' - | 'HISTORY_UNAVAILABLE' - | 'RECEIPT_REQUIRED' - | 'RECEIPT_REJECTED' - | 'ADJUSTMENT_RECEIPT_REQUIRED' - | 'ADJUSTMENT_RECEIPT_REJECTED' - | 'CONSUMER_STATUS_MISMATCH'; - severity: ReportingStatusSeverity; - responsible_party: 'buyer' | 'seller' | 'provider'; - recommended_action: - | 'wait_for_retry' - | 'contact_buyer' - | 'contact_seller' - | 'contact_provider' - | 'repair_access' - | 'update_configuration' - | 'change_reporting_scope' - | 'use_supported_reader'; - /** - * Untrusted display text only. SDKs and agents dispatch exclusively on closed code/recommended_action values and never execute embedded links or instructions. - */ - message?: string; - reporting_obligation_id?: string; - /** - * Current authenticated consumer status statement that caused this mismatch. - */ - reporting_status_id?: string; - delivery_config_id?: string; - delivery_config_version?: number; - feed_purpose?: ReportingFeedPurpose; - /** - * @minItems 1 - */ - media_buy_ids?: [ReportingMediaBuyID, ...ReportingMediaBuyID[]]; - /** - * @minItems 1 - */ - package_ids?: [ReportingPackageID, ...ReportingPackageID[]]; - period_start?: string; - period_end?: string; - expected_at?: string; -} /** * Single webhook delivery attempt surfaced to a calling principal as a buyer-side debug aid. Represents one HTTP attempt of a logical webhook fire from the seller to the buyer's registered endpoint — retries of the same logical fire share `idempotency_key` and differ by `attempt`. This is the canonical record shape for any AdCP resource that exposes a `webhook_activity[]` log on its read API; see snapshot-and-log.mdx § Webhook activity log pattern for the full normative contract (scoping, retention, three-state presence, request-field conventions). */ @@ -17425,6 +18009,7 @@ export type Product = { signal_targeting_allowed?: boolean; demographic_targeting?: DemographicTargetingCapability; overlay_support?: TargetingOverlaySupport; + media_buy_support?: ProductMediaBuySupport; identity?: ProductIdentity; targeting_resolution?: ProductTargetingResolution; /** @@ -18061,6 +18646,15 @@ export type VendorPricingOption = { * Pricing model for a vendor service. Discriminated by model: 'cpm' (fixed CPM), 'percent_of_media' (percentage of spend with optional CPM cap), 'flat_fee' (fixed charge per reporting period), 'per_unit' (fixed price per unit of work), or 'custom' (escape hatch for models not covered by the enumerated forms — requires a description and structured metadata). */ export type VendorPricing = CpmPricing | PercentOfMediaPricing | FlatFeePricing | PerUnitPricing | CustomPricing; +/** + * Optional product support detail for aggregate MediaBuy frequency caps. Aggregate support in 3.2 is max-impressions only. + */ +export type MediaBuyFrequencyCapSupport = FrequencyCapConstraints & { + /** + * @minItems 1 + */ + supported_control_modes?: [MediaBuyFrequencyCapControlMode, ...MediaBuyFrequencyCapControlMode[]]; +}; /** * Sparse, buyer-reviewable change from targeting requested in get_products to targeting bound to a returned configured product. Entries are applied in array order to the original targeting_overlay; after every entry, the complete result MUST validate against targeting.json. A seller MUST NOT emit two replace operations for the same path or combine replace and remove_values on the same path. Selecting the configured product_id accepts the ordered result. */ @@ -19027,7 +19621,18 @@ export interface DemographicTargetingCapability { }; } /** - * Experimental product-scoped identity and reach-measurement facts. Absence is undeclared, not a claim that the product has persistent identifiers. Sellers implementing this surface MUST list media_buy.product_identity in experimental_features on get_adcp_capabilities. When persistent_identifier is false, the product MUST NOT declare overlay_support.frequency_cap; create and update reject that overlay under the ordinary exact-apply-or-reject rule. Delivery for the product MUST NOT report devices, accounts, or cookies as reach_unit. Individuals and households remain valid for panel-based or place-based modeled measurement. When delivery reports reach or frequency with reach_unit custom, reach_methodology is required and explains that unit. + * Binding product participation in shared MediaBuy-level controls. This is separate from overlay_support because a root frequency cap aggregates exposures across packages rather than targeting one package. Returned products MUST cover every field requested through required_media_buy_support. + */ +export interface ProductMediaBuySupport { + /** + * This product can participate in the seller's shared counter for a root MediaBuy.frequency_cap. A buy mixing this product with one that lacks this declaration, or whose resolved supported_per_units omits the root cap's per value, is rejected atomically. + */ + frequency_cap?: true; + frequency_cap_constraints?: MediaBuyFrequencyCapSupport; + ext?: ExtensionObject; +} +/** + * Experimental product-scoped identity and reach-measurement facts. Absence is undeclared, not a claim that the product has persistent identifiers. Sellers implementing this surface MUST list media_buy.product_identity in experimental_features on get_adcp_capabilities. When persistent_identifier is false, the product MUST NOT declare overlay_support.frequency_cap, overlay_support.frequency_cap_support, or media_buy_support.frequency_cap; create and update reject those caps under the ordinary exact-apply-or-reject rule. Delivery for the product MUST NOT report devices, accounts, or cookies as reach_unit. Individuals and households remain valid for panel-based or place-based modeled measurement. When delivery reports reach or frequency with reach_unit custom, reach_methodology is required and explains that unit. */ export interface ProductIdentity { /** @@ -19533,7 +20138,7 @@ export type GetProductsResponse = AdCPVersionEnvelope & extensions?: { }; /** - * Optional array of proposed media plans with budget allocations across products. Publishers include proposals when they can provide strategic guidance based on the brief. Proposals are actionable - buyers can refine them via follow-up get_products calls within the same session, or execute them directly via create_media_buy. + * Optional legacy proposed media plans. When the request carries media_buy_frequency_cap, every returned proposal echoes the bound value as proposal.frequency_cap. Buyers may refine or execute a committed proposal by ID. */ proposals?: Proposal[]; /** @@ -19685,7 +20290,7 @@ export type GetProductsResponse = AdCPVersionEnvelope & }; pagination?: PaginationResponse; /** - * Opaque token representing the version of the wholesale product feed state used to compose this response. Sellers that implement conditional-fetch (if_wholesale_feed_version) MUST return this on every wholesale-mode response so buyers can cache and probe later. Buyers MUST treat the value as opaque — no format, no ordering, no inspection. The token is scope-keyed: it describes a version for the cache_scope declared on this response, NOT a global agent version. A buyer caches `(cache_scope, wholesale_feed_version)` pairs and presents the matching token on the next request. Scoping dimensions: (agent, buying_mode, filters, targeting_overlay, required_overlay_support, deprecated property_list, catalog) for cache_scope: 'public'; that tuple plus account_id for cache_scope: 'account'. pagination.cursor is NOT part of the scoping tuple. See specs/wholesale-feed-webhooks.md for the full cache layering model. + * Opaque token representing the version of the wholesale product feed state used to compose this response. Sellers that implement conditional-fetch (if_wholesale_feed_version) MUST return this on every wholesale-mode response so buyers can cache and probe later. Buyers MUST treat the value as opaque — no format, no ordering, no inspection. The token is scope-keyed: it describes a version for the cache_scope declared on this response, NOT a global agent version. A buyer caches `(cache_scope, wholesale_feed_version)` pairs and presents the matching token on the next request. Scoping dimensions: (agent, buying_mode, filters, targeting_overlay, media_buy_frequency_cap, required_overlay_support, required_media_buy_support, deprecated property_list, catalog) for cache_scope: 'public'; that tuple plus account_id for cache_scope: 'account'. pagination.cursor is NOT part of the scoping tuple. See specs/wholesale-feed-webhooks.md for the full cache layering model. */ wholesale_feed_version?: string; /** @@ -19693,7 +20298,7 @@ export type GetProductsResponse = AdCPVersionEnvelope & */ pricing_version?: string; /** - * Declares whether the wholesale_feed_version and pricing_version on this response describe a universal layer or an account-specific overlay. REQUIRED on every 3.1+ response (the 3.1 schema enforces this — the safety property of the two-layer cache model depends on it). 'public': this response describes the seller's published rate card; the buyer MAY dedupe under (agent, buying_mode, filters, targeting_overlay, required_overlay_support, deprecated property_list, catalog) without scoping by account. 'account': this response includes account-specific overrides; the buyer MUST cache the version under (agent, buying_mode, filters, targeting_overlay, required_overlay_support, deprecated property_list, catalog, account_id). When the request did NOT include `account`, the seller MUST return `cache_scope: 'public'`. When the request included `account`, the seller MUST return either: 'public' (this account prices off the public rate card — buyer dedupes) or 'account' (account-specific overrides exist — buyer caches under the account key). Sellers MAY return 'public' on an account-scoped request that previously had overrides — buyers SHOULD interpret this as a downgrade and drop their account-overlay for the (agent, filters, targeting, support, mode) tuple. Without schema-required cache_scope, a seller silently omitting the field on an account-scoped response would cause buyers to mis-key the cache and serve account-overlay payloads to other accounts — the canonical safety invariant of the entire cache layering model. **Backward-compatibility note for 3.1 validators:** SDKs that validate strictly against the 3.1 schema MUST select the validator based on the server-declared `adcp_version` (release-precision version negotiation, 3.1). For responses with `adcp_version` starting `3.0`, the 3.1 cache_scope-required constraint MUST be relaxed — pre-3.1 sellers correctly emit no cache_scope and remain conformant to their declared version. This is a tightening within 3.1, not a 3.0 break. + * Declares whether the wholesale_feed_version and pricing_version on this response describe a universal layer or an account-specific overlay. REQUIRED on every 3.1+ response (the 3.1 schema enforces this — the safety property of the two-layer cache model depends on it). 'public': this response describes the seller's published rate card; the buyer MAY dedupe under (agent, buying_mode, filters, targeting_overlay, media_buy_frequency_cap, required_overlay_support, required_media_buy_support, deprecated property_list, catalog) without scoping by account. 'account': this response includes account-specific overrides; the buyer MUST cache the version under that tuple plus account_id. When the request did NOT include `account`, the seller MUST return `cache_scope: 'public'`. When the request included `account`, the seller MUST return either: 'public' (this account prices off the public rate card — buyer dedupes) or 'account' (account-specific overrides exist — buyer caches under the account key). Sellers MAY return 'public' on an account-scoped request that previously had overrides — buyers SHOULD interpret this as a downgrade and drop their account-overlay. Without schema-required cache_scope, a seller silently omitting the field on an account-scoped response would cause buyers to mis-key the cache and serve account-overlay payloads to other accounts. **Backward-compatibility note for 3.1 validators:** SDKs that validate strictly against the 3.1 schema MUST select the validator based on the server-declared `adcp_version` (release-precision version negotiation, 3.1). For responses with `adcp_version` starting `3.0`, the 3.1 cache_scope-required constraint MUST be relaxed. */ cache_scope?: 'public' | 'account'; /** @@ -19735,6 +20340,7 @@ export type Proposal = { */ budget_allocation?: BudgetAllocation; pacing?: Pacing; + frequency_cap?: MediaBuyFrequencyCap; proposal_status?: ProposalStatus; /** * When this proposal expires and can no longer be executed. For draft proposals, indicates when indicative pricing becomes stale. For committed proposals, indicates when the inventory hold lapses — the buyer must call create_media_buy before this time. @@ -19819,6 +20425,7 @@ export type CanonicalPricingOption = { commission_rate?: number; commission_basis_description?: string; }; +export type ProductPurchaseImpressions = number; /** * Canonical 3.2 optimization objective. Monetary execution policy belongs in BiddingPolicy; legacy monetary targets and unbound attention metrics are excluded. */ @@ -19888,7 +20495,7 @@ export type CanonicalOptimizationGoal = /** * Buyer evidence-admissibility policy carried into the accepted purchase snapshot. */ -export type ProductAudienceEvidenceRequirements = { +export type ProductPurchaseAudienceEvidenceRequirements = { } & { requirement_mode: 'required' | 'preferred'; evidence_presence: 'required' | 'when_available'; @@ -20082,6 +20689,7 @@ export type CanonicalProduct = { signal_targeting_rules?: SignalTargetingRules; demographic_targeting?: DemographicTargetingCapability; overlay_support?: TargetingOverlaySupport1; + media_buy_support?: ProductMediaBuySupport; identity?: ProductIdentity; /** * @minItems 1 @@ -21612,6 +22220,7 @@ export interface CommercialTerms { * Hard aggregate daily spend ceiling accepted as part of these terms. It bounds total spend without creating purchase allocations. */ daily_budget_cap?: number; + frequency_cap?: MediaBuyFrequencyCap; /** * Shared IANA calendar-day boundary for aggregate and purchase daily caps in these terms. */ @@ -21675,7 +22284,7 @@ export interface BrandKey { countries?: [string, ...string[]]; } /** - * One canonical product selection shared by buy_products inputs and compact proposal snapshots. Direct purchases accept published terms as-is; sellers resolve omitted inherited flight, measurement, and performance terms into the accepted commercial snapshot. Changes to those terms belong in the proposal lifecycle. Creative content and creative assignments are intentionally absent. + * One resolved canonical product selection in a compact proposal or accepted commercial snapshot. Request-side buy_products selections use product-purchase-input.json. This strict snapshot shape contains effective non-null targeting and resolved inherited terms. Creative content and creative assignments are intentionally absent. */ export interface ProductPurchase { product_id: string; @@ -21705,7 +22314,7 @@ export interface ProductPurchase { * Soft lifetime spend target for seller-optimized allocation. */ min_spend_target?: number; - impressions?: number; + impressions?: ProductPurchaseImpressions; /** * Resolved package flight start. On direct-purchase input, omission inherits the MediaBuy start; accepted proposal snapshots carry the resolved timestamp. */ @@ -21721,7 +22330,7 @@ export interface ProductPurchase { * @minItems 1 */ optimization_goals?: [CanonicalOptimizationGoal, ...CanonicalOptimizationGoal[]]; - audience_evidence_requirements?: ProductAudienceEvidenceRequirements; + audience_evidence_requirements?: ProductPurchaseAudienceEvidenceRequirements; /** * Exact immutable audience-evidence snapshots selected for package construction. * @@ -21734,7 +22343,7 @@ export interface ProductPurchase { agency_estimate_number?: string; context?: ContextObject; ext?: ExtensionObject; - measurement_terms?: CanonicalMeasurementTerms; + measurement_terms?: ProductPurchaseMeasurementTerms; /** * Published or negotiated metric thresholds and measurement vendors. Direct buyers may omit this to inherit the product defaults; accepted proposal snapshots preserve every applicable standard. * @@ -21755,7 +22364,7 @@ export interface AudienceEvidencePin { /** * Published or negotiated billing-measurement and makegood terms for this purchase. Direct buyers may omit this to inherit the product default; accepted proposal snapshots preserve the resolved terms. */ -export interface CanonicalMeasurementTerms { +export interface ProductPurchaseMeasurementTerms { billing_measurement?: { vendor: BrandKey; max_variance_percent?: number; @@ -21937,6 +22546,23 @@ export interface CanonicalReportingCapabilities { */ measurement_windows?: [MeasurementWindow, ...MeasurementWindow[]]; } +/** + * Default billing measurement and makegood terms inherited by a direct purchase unless a negotiated proposal replaces them. + */ +export interface CanonicalMeasurementTerms { + billing_measurement?: { + vendor: BrandKey; + max_variance_percent?: number; + measurement_window?: string; + finalization_deadline_hours?: number; + }; + makegood_policy?: { + /** + * @minItems 1 + */ + available_remedies: [MakegoodRemedy, ...MakegoodRemedy[]]; + }; +} /** * Re-export of `TargetingOverlaySupport` under the legacy codegen artifact name. * @@ -22040,6 +22666,12 @@ export interface CanonicalMediaBuyActionFields { sla?: SLAWindow; change_term_id?: MediaBuyChangeTermID; terms_ref?: MediaBuyTermsReference; + /** + * Exact eligible packages for a package-scoped action; omission means all relevant packages. + * + * @minItems 1 + */ + applicable_package_ids?: [ApplicablePackageID, ...ApplicablePackageID[]]; } export interface CommitmentError { status: 'failed'; @@ -22301,6 +22933,7 @@ export interface UpdateMediaBuySuccess { * Post-update hard aggregate daily spend ceiling. Echoed when the update sets or changes the aggregate daily cap; omitted after the cap is removed. */ daily_budget_cap?: number; + frequency_cap?: MediaBuyFrequencyCap; /** * Post-update IANA timezone shared by every aggregate and package daily cap. Echoed whenever the update affects daily caps or their timezone. */ @@ -25762,7 +26395,7 @@ export type GetProductsCompletion = AdCPVersionEnvelope & extensions?: { }; /** - * Optional array of proposed media plans with budget allocations across products. Publishers include proposals when they can provide strategic guidance based on the brief. Proposals are actionable - buyers can refine them via follow-up get_products calls within the same session, or execute them directly via create_media_buy. + * Optional legacy proposed media plans. When the request carries media_buy_frequency_cap, every returned proposal echoes the bound value as proposal.frequency_cap. Buyers may refine or execute a committed proposal by ID. */ proposals?: Proposal[]; /** @@ -25914,7 +26547,7 @@ export type GetProductsCompletion = AdCPVersionEnvelope & }; pagination?: PaginationResponse; /** - * Opaque token representing the version of the wholesale product feed state used to compose this response. Sellers that implement conditional-fetch (if_wholesale_feed_version) MUST return this on every wholesale-mode response so buyers can cache and probe later. Buyers MUST treat the value as opaque — no format, no ordering, no inspection. The token is scope-keyed: it describes a version for the cache_scope declared on this response, NOT a global agent version. A buyer caches `(cache_scope, wholesale_feed_version)` pairs and presents the matching token on the next request. Scoping dimensions: (agent, buying_mode, filters, targeting_overlay, required_overlay_support, deprecated property_list, catalog) for cache_scope: 'public'; that tuple plus account_id for cache_scope: 'account'. pagination.cursor is NOT part of the scoping tuple. See specs/wholesale-feed-webhooks.md for the full cache layering model. + * Opaque token representing the version of the wholesale product feed state used to compose this response. Sellers that implement conditional-fetch (if_wholesale_feed_version) MUST return this on every wholesale-mode response so buyers can cache and probe later. Buyers MUST treat the value as opaque — no format, no ordering, no inspection. The token is scope-keyed: it describes a version for the cache_scope declared on this response, NOT a global agent version. A buyer caches `(cache_scope, wholesale_feed_version)` pairs and presents the matching token on the next request. Scoping dimensions: (agent, buying_mode, filters, targeting_overlay, media_buy_frequency_cap, required_overlay_support, required_media_buy_support, deprecated property_list, catalog) for cache_scope: 'public'; that tuple plus account_id for cache_scope: 'account'. pagination.cursor is NOT part of the scoping tuple. See specs/wholesale-feed-webhooks.md for the full cache layering model. */ wholesale_feed_version?: string; /** @@ -25922,7 +26555,7 @@ export type GetProductsCompletion = AdCPVersionEnvelope & */ pricing_version?: string; /** - * Declares whether the wholesale_feed_version and pricing_version on this response describe a universal layer or an account-specific overlay. REQUIRED on every 3.1+ response (the 3.1 schema enforces this — the safety property of the two-layer cache model depends on it). 'public': this response describes the seller's published rate card; the buyer MAY dedupe under (agent, buying_mode, filters, targeting_overlay, required_overlay_support, deprecated property_list, catalog) without scoping by account. 'account': this response includes account-specific overrides; the buyer MUST cache the version under (agent, buying_mode, filters, targeting_overlay, required_overlay_support, deprecated property_list, catalog, account_id). When the request did NOT include `account`, the seller MUST return `cache_scope: 'public'`. When the request included `account`, the seller MUST return either: 'public' (this account prices off the public rate card — buyer dedupes) or 'account' (account-specific overrides exist — buyer caches under the account key). Sellers MAY return 'public' on an account-scoped request that previously had overrides — buyers SHOULD interpret this as a downgrade and drop their account-overlay for the (agent, filters, targeting, support, mode) tuple. Without schema-required cache_scope, a seller silently omitting the field on an account-scoped response would cause buyers to mis-key the cache and serve account-overlay payloads to other accounts — the canonical safety invariant of the entire cache layering model. **Backward-compatibility note for 3.1 validators:** SDKs that validate strictly against the 3.1 schema MUST select the validator based on the server-declared `adcp_version` (release-precision version negotiation, 3.1). For responses with `adcp_version` starting `3.0`, the 3.1 cache_scope-required constraint MUST be relaxed — pre-3.1 sellers correctly emit no cache_scope and remain conformant to their declared version. This is a tightening within 3.1, not a 3.0 break. + * Declares whether the wholesale_feed_version and pricing_version on this response describe a universal layer or an account-specific overlay. REQUIRED on every 3.1+ response (the 3.1 schema enforces this — the safety property of the two-layer cache model depends on it). 'public': this response describes the seller's published rate card; the buyer MAY dedupe under (agent, buying_mode, filters, targeting_overlay, media_buy_frequency_cap, required_overlay_support, required_media_buy_support, deprecated property_list, catalog) without scoping by account. 'account': this response includes account-specific overrides; the buyer MUST cache the version under that tuple plus account_id. When the request did NOT include `account`, the seller MUST return `cache_scope: 'public'`. When the request included `account`, the seller MUST return either: 'public' (this account prices off the public rate card — buyer dedupes) or 'account' (account-specific overrides exist — buyer caches under the account key). Sellers MAY return 'public' on an account-scoped request that previously had overrides — buyers SHOULD interpret this as a downgrade and drop their account-overlay. Without schema-required cache_scope, a seller silently omitting the field on an account-scoped response would cause buyers to mis-key the cache and serve account-overlay payloads to other accounts. **Backward-compatibility note for 3.1 validators:** SDKs that validate strictly against the 3.1 schema MUST select the validator based on the server-declared `adcp_version` (release-precision version negotiation, 3.1). For responses with `adcp_version` starting `3.0`, the 3.1 cache_scope-required constraint MUST be relaxed. */ cache_scope?: 'public' | 'account'; /** @@ -28686,6 +29319,13 @@ export interface PropertyReference { } +// core/collection-selection.json +/** + * Complete purchased collection set within a product. Mode selected names the complete required set (partial selection requires product collection_targeting_allowed: true; exactly restating the full bundle is an inherent match); mode default accepts the product's full bundle. Package readback MUST echo the committed selection here as concrete selectors, materializing any collection_list composition; a purchase made with mode default therefore reads back as mode selected naming the product's complete bundle. Rejection of a schema-valid selector that references an unknown collection_id or publisher_domain uses REFERENCE_NOT_FOUND per the error-code registry (INVALID_REQUEST applies only to schema-invalid shapes such as a selected-mode item omitting collection_ids). Sellers reject unknown, duplicate, or partially applicable selectors rather than silently changing the selection. + */ +export type CollectionSelection = SelectedCollections | ProductDefaultCollections; + + // core/collection.json /** * A recurring inventory container — a named program, publication, event series, rotation, or programmed channel that produces bookable installments on a defined cadence. The kind field indicates how to interpret this collection: 'series' for TV/podcast programs, 'publication' for print/newsletter titles, 'event_series' for live events, 'rotation' for DOOH scheduling, and 'channel' for continuously programmed audio or video streams regardless of carriage or monetization model. Declared in the publisher's adagents.json and referenced by products via collection selectors. @@ -31402,6 +32042,34 @@ export interface MediaBuyFeatures { [k: string]: boolean | BiddingPolicyCapability | undefined; } +// core/media-buy-frequency-cap-capability.json +/** + * Complete seller-wide executable domain for aggregate MediaBuy frequency caps. Unlike product detail, this root capability cannot inherit omitted values: it declares the supported max-impression mode, entity units, impression limits, and exact window intervals. Product constraints may only narrow this domain. + */ +export type MediaBuyFrequencyCapCapability = FrequencyCapConstraints & { + supported_control_modes: MediaBuyFrequencyCapControlMode[]; +}; + +// core/media-buy-frequency-cap-requirement.json +/** + * Buyer minimum product-support detail for an aggregate MediaBuy frequency cap. Aggregate support in 3.2 is max-impressions only. + */ +export type MediaBuyFrequencyCapRequirement = FrequencyCapRequirements & { + supported_control_modes?: MediaBuyFrequencyCapControlMode[]; +}; + +// core/media-buy-support-requirements.json +/** + * Buyer minimums for product participation in shared MediaBuy-level execution. Missing or unknown required capabilities exclude the product. + */ +export interface ProductMediaBuySupportRequirements { + /** + * Require product participation in one shared MediaBuy frequency-cap counter. + */ + frequency_cap?: true; + frequency_cap_constraints?: MediaBuyFrequencyCapRequirement; +} + // core/missing-metric.json /** * One metric the binding reporting contract declared but that is not populated in a delivery report. Symmetric with `committed_metrics` and discriminated by `scope`. @@ -31633,6 +32301,21 @@ export type PackageDeliveryMetricValue = ({ }; }; +// core/package-signal-targeting-groups.json +/** + * Top-level basic Boolean composition for package signal targeting. The groups-level operator is required; v1 supports operator 'all', meaning every child group must be satisfied. This represents the portable baseline: (any of include group 1) AND (any of include group 2) AND NOT (any of exclude group N). + */ +export interface PackageSignalTargetingGroups { + /** + * Groups-level operator. Required even though v1 only supports 'all': every child group must be satisfied. + */ + operator: 'all'; + /** + * Signal targeting groups to evaluate. Use operator 'any' for include groups and 'none' for exclusion groups. + */ + groups: PackageSignalTargetingGroup[]; +} + // core/performance-feedback-assertion.json /** * Metric this assertion describes. Omit only for holistic feedback that is not attributable to one metric. @@ -32575,6 +33258,57 @@ export interface PrincipalState { }[]; } +// core/product-audience-evidence-requirements.json +/** + * Buyer-authored evidence policy for compact product discovery. Organization selectors are stable keys and never carry brand assets or content provenance. + */ +export interface ProductAudienceEvidenceRequirements { + requirement_mode: 'required' | 'preferred'; + evidence_presence: 'required' | 'when_available'; + accepted_methodologies?: AudienceEvidenceMethodology[]; + excluded_methodologies?: AudienceEvidenceMethodology[]; + accepted_evidence_types?: ('measured' | 'forecast' | 'seller_declared')[]; + accepted_providers?: BrandKey[]; + excluded_providers?: BrandKey[]; + accepted_subject_types?: AudienceSubjectType[]; + accepted_resolution_methods?: AudienceResolutionMethod[]; + /** + * @minimum 0 + * @maximum 1 + */ + minimum_confidence?: number; + maximum_age?: Duration & { + unit?: 'seconds' | 'minutes' | 'hours' | 'days'; + }; + methodology_documentation_required?: boolean; + independent_attestation_required?: boolean; + accepted_attestation_issuers?: ( + | { + type: 'brand'; + brand: BrandKey; + ext?: ExtensionObject; + } + | { + type: 'agent'; + /** + * @pattern ^https:\/\/[^\/?#@]+(?:\/[^?#]*)?(?:\?[^#]*)?$ + */ + agent_url: string; + ext?: ExtensionObject; + } + | { + type: 'origin'; + /** + * @pattern ^https:\/\/[^\/?#@]+$ + */ + origin: string; + ext?: ExtensionObject; + } + )[]; + accepted_attestation_claim_types?: string[]; + ext?: ExtensionObject; +} + // core/product-change-map.json /** * Product IDs mapped to deterministic membership actions. Object keys are product identifiers, so contradictory actions for one product cannot be represented. @@ -32927,29 +33661,6 @@ export interface ProductFilters { } // core/product-offer-filters.json -/** - * Inventory coverage in the specified proximity boundaries: OR within this field, AND across offer filters. Does not add delivery targeting, require targeting support, or rescope pricing or forecasts. - * - * @minItems 1 - */ -export type GeoProximity = [ - ( - | { - } - | { - } - | { - } - ), - ...( - | { - } - | { - } - | { - } - )[] -]; /** * Offer, commercial-fit, availability, and reporting filters for product discovery. This compact schema is independent of the legacy delivery-targeting filter graph. Brand and issuer selectors are stable keys; callers do not send brand assets or content provenance. */ @@ -34124,19 +34835,29 @@ export interface ReportingConsumerStatus { */ reporting_revision_id?: string; /** - * revision_content_sha256 independently recomputed from the exact consumed Core revision binding. Required only for received; unlike a Reconciled Billing receipt it carries no materialization evidence, row totals, canonical digest, or billing acceptance. + * revision_content_sha256 independently recomputed from the exact consumed Core revision binding. Required for received and content_mismatch, where it proves which exact revision content the consumer read; unlike a Reconciled Billing receipt it carries no materialization evidence, row totals, canonical digest, or billing acceptance. * @pattern ^[A-Fa-f0-9]{64}$ */ observed_revision_content_sha256?: string; /** - * received means the exact revision content was successfully consumed; obligation_missing means the independently expected period was absent from the seller ledger; revision_missing means the obligation existed but no required revision was available after expected_at; unreadable means a named revision was advertised but its exact content could not be consumed. None of these values reconciles billing evidence. + * received means the exact revision content was successfully consumed; obligation_missing means the independently expected period was absent from the seller ledger; revision_missing means the obligation existed but no required revision was available after expected_at; unreadable means a named revision was advertised but its exact content could not be consumed; content_mismatch means the exact revision content was read but contradicts a fact the accepted configuration generation already fixed, named by the closed mismatch_code. None of these values reconciles billing evidence, and content_mismatch in particular is not a measurement dispute. */ - consumer_status: 'received' | 'obligation_missing' | 'revision_missing' | 'unreadable'; + consumer_status: 'received' | 'obligation_missing' | 'revision_missing' | 'unreadable' | 'content_mismatch'; /** * When the consumer established this status. For received, this is when the named revision first became consumable to this consumer; sellers use it as buyer-attributed arrival evidence rather than silently substituting publication time. * @format date-time */ status_as_of: string; + /** + * Closed reason the consumed revision contradicts the accepted configuration generation. Each value is decidable from the obligation, the pinned report definition, and the revision itself, with no reference to either party's own measurement. scope_media_buy_missing: a media buy frozen in the obligation's media_buy_ids denominator is absent from the revision and is not represented by an explicit zero row, so the revision cannot distinguish zero delivery from an omitted buy. coverage_short: the revision covers fewer packages than the obligation's frozen coverage.covered_package_ids claims. metric_missing: a metric named in the pinned report definition's metrics[].name is absent from the revision. schema_nonconformant: rows do not validate against the reporting profile's pinned schema_uri and schema_sha256. currency_mismatch: a value's unit disagrees with the unit the pinned report definition fixed for that metric, or a control total's unit disagrees with the profile-defined unit for that name. period_mismatch: the revision carries a time dimension declared by the pinned grain whose values fall outside the obligation's half-open period. Precedence when more than one applies: schema_nonconformant is used only when the failure is structural validation against the pinned schema; a metric that is simply absent uses metric_missing even when the pinned schema declares it required. Each names a contract fact already fixed by the accepted generation, never a difference of opinion about counts. Agents dispatch on this value, not on prose. + */ + mismatch_code?: + | 'scope_media_buy_missing' + | 'coverage_short' + | 'metric_missing' + | 'schema_nonconformant' + | 'currency_mismatch' + | 'period_mismatch'; /** * Typed reason a named revision was unreadable. Agents dispatch on this value, not prose or provider response bodies. */ @@ -34368,6 +35089,29 @@ export interface ReportingDeliveryCapabilities { * @format int */ status_retention_days: number; + /** + * Maximum interval after a CONSUMER_STATUS_MISMATCH issue's opened_at during which the seller may keep that issue at a non-escalated recommended_action. After it, the issue MUST be action_required with a contact_ recommended_action naming the diagnosed responsible_party. Declaring it requires operations_contact so the escalation has a destination. Absence means the seller publishes no escalation commitment; it never means an unbounded one. + * @minimum 0 + * @format int + */ + consumer_mismatch_escalation_seconds?: number; + /** + * Optional non-secret human escalation path for reporting issues the protocol cannot resolve. It is display metadata for an operator, not an AdCP endpoint: agents MUST NOT dereference, probe, or send protocol traffic to these values, and they carry no authorization. Required when consumer_mismatch_escalation_seconds is advertised. + */ + operations_contact?: { + /** + * HTTPS page a human uses to open or track a reporting issue, such as a support portal or status page. Same hardened origin shape as the offering document URIs: never an IP literal, userinfo URL, loopback host, AdCP task endpoint, webhook target, or credentialed link. + * @maxLength 2048 + * @pattern ^https:\/\/(?![^\/]*@)(?!localhost(?:[:\/]|$))(?!\[)(?!\d+(?:\.\d+){3}(?::|\/|$))(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,}(?::\d+)?(?:\/|$) + */ + url?: string; + /** + * Monitored operations mailbox for reporting escalations. A role address, not an individual. + * @maxLength 254 + * @format email + */ + email?: string; + }; /** * Optional evidence-scoped observed performance for advertised offerings. offering_id values MUST be unique and name offerings in this capability block. */ @@ -38309,7 +39053,7 @@ export interface AccountSetupRequiredDetails { * Details payload for ACTION_NOT_ALLOWED errors. Lets buyer SDKs offer a structured recovery path without a separate get_media_buys round-trip. */ export interface ActionNotAllowedDetails { - attempted_action: MediaBuyValidAction; + attempted_action: MediaBuyAvailableActionID; reason: ActionNotAllowedReason; /** * Echo of the buy's resolved `available_actions[]` at rejection time. Buyer SDKs render this to the caller as the recovery option set. @@ -39437,7 +40181,7 @@ export interface OutcomeTarget { // media-buy/package-control.json /** - * Operational controls for an existing package that remain inside its accepted commercial envelope. targeting_overlay is a complete replacement; keyword add/remove arrays are incremental, and the same keyword MUST NOT appear in both directions. Creative mutation, flight changes, new products, pricing changes, and billing-term changes require their dedicated lifecycle or a refined proposal. + * Operational controls for an existing package that remain inside its accepted commercial envelope. targeting_overlay is a per-dimension patch; keyword add/remove arrays are incremental, and the same keyword MUST NOT appear in both directions. Creative mutation, flight changes, new products, pricing changes, and billing-term changes require their dedicated lifecycle or a refined proposal. */ export interface PackageControl { /** @@ -39473,7 +40217,7 @@ export interface PackageControl { * @maxLength 500 */ cancellation_reason?: string; - targeting_overlay?: TargetingOverlay; + targeting_overlay?: TargetingOverlayInput; /** * Replace the package's promoted catalogs with references previously managed through sync_catalogs. */ @@ -39487,7 +40231,7 @@ export interface PackageControl { // media-buy/product-discovery-criteria.json /** - * Structured criteria shared by product listing and proposal requests. Offer filters decide which commercial offers may be returned; targeting_overlay constrains deliverable inventory; required_overlay_support requires package-level targeting capability for values the buyer will supply later; acceptance_context supplies facts for advisory seller-policy preflight. + * Structured criteria shared by product listing and proposal requests. Offer filters decide which commercial offers may be returned; targeting_overlay constrains deliverable inventory; required_overlay_support requires package-level targeting capability; required_media_buy_support requires participation in shared MediaBuy controls; acceptance_context supplies facts for advisory seller-policy preflight. */ export interface ProductDiscoveryCriteria { /** @@ -39496,7 +40240,9 @@ export interface ProductDiscoveryCriteria { product_ids?: string[]; offer_filters?: ProductOfferFilters; targeting_overlay?: TargetingOverlay; + media_buy_frequency_cap?: MediaBuyFrequencyCap; required_overlay_support?: TargetingOverlayRequirements; + required_media_buy_support?: ProductMediaBuySupportRequirements; outcome_target?: OutcomeTarget; acceptance_context?: AcceptanceContext; catalog?: CatalogSelection; @@ -39529,6 +40275,8 @@ export type ProductResponseFields = ( | 'signal_targeting_allowed' | 'signal_targeting_rules' | 'demographic_targeting' + | 'overlay_support' + | 'media_buy_support' | 'audience_evidence' | 'audience_evidence_selections' | 'max_optimization_goals' @@ -39542,6 +40290,81 @@ export type ProductResponseFields = ( )[]; +// media-buy/product-purchase-input.json +/** + * Canonical format options selected from the published product offer. Legacy named-format identifiers are not accepted. + * + * @minItems 1 + */ +export type FormatOptionRefs = [FormatOptionReference, ...FormatOptionReference[]]; +/** + * Previously synchronized account catalog IDs promoted by this selection. Callers manage catalog bodies through sync_catalogs rather than inlining them here. + * + * @minItems 1 + */ +export type CatalogIds = [string, ...string[]]; +/** + * @minItems 1 + */ +export type OptimizationGoals = [CanonicalOptimizationGoal, ...CanonicalOptimizationGoal[]]; +/** + * Exact immutable audience-evidence snapshots selected for package construction. + * + * @minItems 1 + */ +export type AudienceEvidencePins = [AudienceEvidencePin, ...AudienceEvidencePin[]]; +/** + * Published or negotiated metric thresholds and measurement vendors. Direct buyers may omit this to inherit the product defaults; accepted proposal snapshots preserve every applicable standard. + * + * @minItems 1 + */ +export type PerformanceStandards = [CanonicalPerformanceStandard, ...CanonicalPerformanceStandard[]]; +/** + * Request-only canonical product selection for buy_products. It shares the strict Product Purchase field shapes but uses Targeting Input so a buyer can distinguish inheritance, replacement, and explicit clearing. Accepted commercial snapshots use product-purchase.json and contain only resolved, non-null effective targeting. + */ +export interface ProductPurchaseInput { + product_id: string; + pricing_option_id: string; + pricing?: CanonicalPricingOption; + format_option_refs?: FormatOptionRefs; + catalog_ids?: CatalogIds; + /** + * Hard spend cap for this selection in the media-buy currency. + */ + budget?: number; + /** + * Optional hard daily spend ceiling for this purchase. It is subordinate to the media-buy aggregate daily cap and is not a reserved daily allocation. Its day boundary is the media buy's budget_cap_timezone. + */ + daily_budget_cap?: number; + /** + * Soft lifetime spend target for seller-optimized allocation. + */ + min_spend_target?: number; + impressions?: ProductPurchaseImpressions; + /** + * Resolved package flight start. On direct-purchase input, omission inherits the MediaBuy start; accepted proposal snapshots carry the resolved timestamp. + */ + start_time?: string; + /** + * Resolved package flight end. On direct-purchase input, omission inherits the MediaBuy end; accepted proposal snapshots carry the resolved timestamp. + */ + end_time?: string; + pacing?: Pacing; + bidding?: BiddingPolicy; + targeting_overlay?: TargetingOverlayInput; + optimization_goals?: OptimizationGoals; + audience_evidence_requirements?: ProductPurchaseAudienceEvidenceRequirements; + audience_evidence_pins?: AudienceEvidencePins; + /** + * Package-level agency estimate or authorization reference. + */ + agency_estimate_number?: string; + context?: ContextObject; + ext?: ExtensionObject; + measurement_terms?: ProductPurchaseMeasurementTerms; + performance_standards?: PerformanceStandards; +} + // media-buy/product-refinement.json /** * Change requests for iterating on product discovery results and proposals. @@ -39644,7 +40467,7 @@ export interface ProposalDecline { // media-buy/proposal-refinement.json /** - * Fork an immutable proposal or finalize a draft into a held committed snapshot. Revising with structured criteria, typed boundaries, product changes, requested alternatives, and/or a semantic ask creates one or more new drafts; finalizing changes no terms. Refining an accepted proposal creates a draft amendment or cancellation proposal against its MediaBuy; the source remains accepted and unchanged. + * Fork an immutable proposal or finalize a draft into a held committed snapshot. Revising with structured criteria, typed boundaries, product changes, requested alternatives, and/or a semantic ask creates one or more new drafts; finalizing changes no terms. Refining an accepted proposal creates a draft amendment or cancellation proposal against its MediaBuy; the source remains accepted and unchanged. A revised product mix must support the resulting root frequency cap; because omitted criteria inherit, clearing the cap is explicit through remove_media_buy_frequency_cap. */ export type ProposalRefinement = { /** @@ -39713,6 +40536,10 @@ export type ProposalRefinement = { */ ask?: string; criteria?: ProductDiscoveryCriteria; + /** + * Request a revised draft whose commercial terms omit the existing MediaBuy frequency cap. Omission inherits it. To replace it, provide criteria.media_buy_frequency_cap instead. + */ + remove_media_buy_frequency_cap?: true; } & ( | { action: 'finalize'; diff --git a/src/lib/types/enums.generated.ts b/src/lib/types/enums.generated.ts index 0af225722..641b19b74 100644 --- a/src/lib/types/enums.generated.ts +++ b/src/lib/types/enums.generated.ts @@ -47,7 +47,7 @@ export const C2PAWatermarkActionValues = ["c2pa.watermarked.bound", "c2pa.waterm export const CanceledByValues = ["buyer", "seller"] as const; export const CanonicalFormatKindValues = ["image", "html5", "display_tag", "image_carousel", "video_hosted", "video_vast", "audio_hosted", "audio_vast", "audio_daast", "sponsored_placement", "native_in_feed", "responsive_creative", "agent_placement", "seller_rendered_stateful_display", "coordinated_placements", "custom"] as const; export const CanonicalMediaBuyActionModeValues = ["self_serve", "conditional_self_serve", "seller_managed", "requires_approval"] as const; -export const CanonicalMediaBuyActionNameValues = ["pause", "resume", "cancel", "extend_flight", "shorten_flight", "update_flight_dates", "increase_budget", "decrease_budget", "reallocate_budget", "update_budget_allocation", "update_targeting", "update_pacing", "update_bidding", "update_frequency_caps", "update_catalog_assignments", "update_keywords", "update_optimization_goals", "update_impression_goal", "update_spend_target", "update_reporting_webhook", "replace_creative", "update_creative_assignments", "remove_creative", "add_packages", "remove_packages"] as const; +export const CanonicalMediaBuyActionNameValues = ["pause", "resume", "cancel", "extend_flight", "shorten_flight", "update_flight_dates", "increase_budget", "decrease_budget", "reallocate_budget", "update_budget_allocation", "update_targeting", "update_pacing", "update_bidding", "update_frequency_caps", "update_media_buy_frequency_cap", "update_catalog_assignments", "update_keywords", "update_optimization_goals", "update_impression_goal", "update_spend_target", "update_reporting_webhook", "replace_creative", "update_creative_assignments", "remove_creative", "add_packages", "remove_packages"] as const; export const CatalogActionValues = ["created", "updated", "unchanged", "failed", "deleted"] as const; export const CatalogItemStatusValues = ["approved", "pending", "rejected", "warning", "withdrawn"] as const; export const CatalogTypeValues = ["offering", "product", "inventory", "store", "promotion", "hotel", "flight", "job", "vehicle", "real_estate", "education", "destination", "app"] as const; @@ -109,6 +109,9 @@ export const ForecastMethodValues = ["estimate", "modeled", "guaranteed"] as con export const ForecastRangeUnitValues = ["spend", "availability", "reach_freq", "weekly", "daily", "clicks", "conversions", "package"] as const; export const FormatIDParameterValues = ["dimensions", "duration", "pixel_ratio"] as const; export const FrameRateTypeValues = ["constant", "variable"] as const; +export const FrequencyCapControlModeValues = ["max_impressions", "suppress", "max_impressions_and_suppress"] as const; +export const FrequencyCapDurationUnitValues = ["seconds", "minutes", "hours", "days", "campaign"] as const; +export const FrequencyCapMutableFieldValues = ["max_impressions", "per", "window", "suppress"] as const; export const FrequencyCapScopeValues = ["package"] as const; export const GenreTaxonomyValues = ["iab_content_3.0", "iab_content_2.2", "gracenote", "eidr", "apple_genres", "google_genres", "roku", "amazon_genres", "custom"] as const; export const GeographicTargetingLevelValues = ["country", "region", "metro", "postal_area"] as const; @@ -139,6 +142,7 @@ export const MarkdownFlavorValues = ["commonmark", "gfm"] as const; export const MatchIDTypeValues = ["hashed_email", "hashed_phone", "rampid", "id5", "uid2", "euid", "pairid", "maid", "other"] as const; export const MatchTypeValues = ["broad", "phrase", "exact"] as const; export const MediaBuyActionModeValues = ["self_serve", "conditional_self_serve", "seller_managed", "requires_approval"] as const; +export const MediaBuyFrequencyCapControlModeValues = ["max_impressions"] as const; export const MediaBuyHealthValues = ["ok", "impaired"] as const; export const MediaBuyStatusValues = ["pending_creatives", "pending_start", "active", "paused", "completed", "rejected", "canceled"] as const; export const MediaBuyValidActionValues = ["pause", "resume", "cancel", "update_name", "extend_flight", "shorten_flight", "update_flight_dates", "increase_budget", "decrease_budget", "reallocate_budget", "update_budget_allocation", "update_targeting", "update_pacing", "update_bidding", "update_frequency_caps", "replace_creative", "update_creative_assignments", "remove_creative", "add_packages", "remove_packages", "update_budget", "update_dates", "update_packages", "sync_creatives"] as const; diff --git a/src/lib/types/inline-enums.generated.ts b/src/lib/types/inline-enums.generated.ts index d6c48a7e5..67ab0ef17 100644 --- a/src/lib/types/inline-enums.generated.ts +++ b/src/lib/types/inline-enums.generated.ts @@ -761,11 +761,6 @@ export const DownstreamConnectionRequirement_ScopeValues = ["account", "identity /** single | DownstreamConnectionRequirement.status */ export const DownstreamConnectionRequirement_StatusValues = ["connected", "missing", "pending", "expired", "revoked", "not_required", "unknown"] as const; -// ====== Duration ====== - -/** single | Duration.unit */ -export const Duration_UnitValues = ["seconds", "minutes", "hours", "days", "campaign"] as const; - // ====== EducationItem ====== /** single | EducationItem.degree_type */ @@ -885,7 +880,7 @@ export const GetProductsCompletion_CacheScopeValues = ["public", "account"] as c /** single | GetProductsRequest.buying_mode */ export const GetProductsRequest_BuyingModeValues = ["brief", "wholesale", "refine"] as const; /** array of | GetProductsRequest.fields */ -export const GetProductsRequest_FieldsValues = ["product_id", "name", "description", "publisher_properties", "channels", "video_placement_types", "audio_distribution_types", "sponsored_placement_types", "social_placement_surfaces", "format_options", "placements", "delivery_type", "exclusivity", "pricing_options", "forecast", "reporting_capabilities", "measurement_terms", "performance_standards", "catalog_types", "signal_targeting_allowed", "signal_targeting_rules", "demographic_targeting", "audience_evidence", "audience_evidence_selections", "max_optimization_goals", "catalog_match", "list_applications", "brief_relevance", "acceptance_policy_profile_ids", "identity", "expires_at", "allowed_actions", "format_ids", "outcome_measurement", "delivery_measurement", "creative_policy", "metric_optimization", "conversion_tracking", "data_provider_signals", "included_signals", "signal_targeting_options", "overlay_support", "targeting_resolution", "collections", "collection_targeting_allowed", "installments", "is_custom", "product_card", "product_card_detailed", "enforced_policies", "trusted_match"] as const; +export const GetProductsRequest_FieldsValues = ["product_id", "name", "description", "publisher_properties", "channels", "video_placement_types", "audio_distribution_types", "sponsored_placement_types", "social_placement_surfaces", "format_options", "placements", "delivery_type", "exclusivity", "pricing_options", "forecast", "reporting_capabilities", "measurement_terms", "performance_standards", "catalog_types", "signal_targeting_allowed", "signal_targeting_rules", "demographic_targeting", "overlay_support", "media_buy_support", "audience_evidence", "audience_evidence_selections", "max_optimization_goals", "catalog_match", "list_applications", "brief_relevance", "acceptance_policy_profile_ids", "identity", "expires_at", "allowed_actions", "format_ids", "outcome_measurement", "delivery_measurement", "creative_policy", "metric_optimization", "conversion_tracking", "data_provider_signals", "included_signals", "signal_targeting_options", "targeting_resolution", "collections", "collection_targeting_allowed", "installments", "is_custom", "product_card", "product_card_detailed", "enforced_policies", "trusted_match"] as const; // ====== GetSignalsRequest ====== @@ -1052,7 +1047,7 @@ export const ListCreativesRequest_FieldsValues = ["creative_id", "name", "format // ====== ListProductsRequest ====== /** array of | ListProductsRequest.fields */ -export const ListProductsRequest_FieldsValues = ["product_id", "name", "description", "publisher_properties", "channels", "video_placement_types", "audio_distribution_types", "sponsored_placement_types", "social_placement_surfaces", "format_options", "placements", "delivery_type", "exclusivity", "pricing_options", "forecast", "reporting_capabilities", "measurement_terms", "performance_standards", "catalog_types", "signal_targeting_allowed", "signal_targeting_rules", "demographic_targeting", "audience_evidence", "audience_evidence_selections", "max_optimization_goals", "catalog_match", "list_applications", "brief_relevance", "acceptance_policy_profile_ids", "identity", "expires_at", "allowed_actions"] as const; +export const ListProductsRequest_FieldsValues = ["product_id", "name", "description", "publisher_properties", "channels", "video_placement_types", "audio_distribution_types", "sponsored_placement_types", "social_placement_surfaces", "format_options", "placements", "delivery_type", "exclusivity", "pricing_options", "forecast", "reporting_capabilities", "measurement_terms", "performance_standards", "catalog_types", "signal_targeting_allowed", "signal_targeting_rules", "demographic_targeting", "overlay_support", "media_buy_support", "audience_evidence", "audience_evidence_selections", "max_optimization_goals", "catalog_match", "list_applications", "brief_relevance", "acceptance_policy_profile_ids", "identity", "expires_at", "allowed_actions"] as const; // ====== MacroDeclaration ====== @@ -1457,9 +1452,11 @@ export const ReportingCanonicalizationContract_MediaTypeValues = ["application/v // ====== ReportingConsumerStatus ====== /** single | ReportingConsumerStatus.consumer_status */ -export const ReportingConsumerStatus_ConsumerStatusValues = ["received", "obligation_missing", "revision_missing", "unreadable"] as const; +export const ReportingConsumerStatus_ConsumerStatusValues = ["received", "obligation_missing", "revision_missing", "unreadable", "content_mismatch"] as const; /** single | ReportingConsumerStatus.failure_code */ export const ReportingConsumerStatus_FailureCodeValues = ["access_denied", "resource_not_found", "integrity_mismatch", "reader_incompatible", "transport_failed"] as const; +/** single | ReportingConsumerStatus.mismatch_code */ +export const ReportingConsumerStatus_MismatchCodeValues = ["scope_media_buy_missing", "coverage_short", "metric_missing", "schema_nonconformant", "currency_mismatch", "period_mismatch"] as const; // ====== ReportingCoverage ====== @@ -1485,6 +1482,8 @@ export const ReportingDeliveryCapabilities_StatusTaskValues = ["get_reporting_st // ====== ReportingDeliveryConfiguration ====== +/** single | ReportingDeliveryConfiguration.authoritative_party */ +export const ReportingDeliveryConfiguration_AuthoritativePartyValues = ["seller", "consumer"] as const; /** single | ReportingDeliveryConfiguration.coverage_requirement */ export const ReportingDeliveryConfiguration_CoverageRequirementValues = ["full", "allow_partial"] as const; @@ -1546,6 +1545,8 @@ export const ReportingScheduleOffering_PeriodTimezonePolicyValues = ["fixed", "a /** single | ReportingStatusIssue.code */ export const ReportingStatusIssue_CodeValues = ["REPORT_OVERDUE", "PRODUCTION_FAILED", "DELIVERY_FAILED", "ACCESS_REQUIRED", "CONFIGURATION_REQUIRED", "REPORTING_COVERAGE_INCOMPLETE", "RESOURCE_EXPIRED", "READER_INCOMPATIBLE", "HISTORY_UNAVAILABLE", "RECEIPT_REQUIRED", "RECEIPT_REJECTED", "ADJUSTMENT_RECEIPT_REQUIRED", "ADJUSTMENT_RECEIPT_REJECTED", "CONSUMER_STATUS_MISMATCH"] as const; +/** single | ReportingStatusIssue.issue_state */ +export const ReportingStatusIssue_IssueStateValues = ["open", "acknowledged", "resolved", "waived"] as const; /** single | ReportingStatusIssue.recommended_action */ export const ReportingStatusIssue_RecommendedActionValues = ["wait_for_retry", "contact_buyer", "contact_seller", "contact_provider", "repair_access", "update_configuration", "change_reporting_scope", "use_supported_reader"] as const; /** single | ReportingStatusIssue.responsible_party */ @@ -2348,6 +2349,13 @@ export const ProductAudienceEvidenceRequirements_RequirementModeValues = Audienc // --- ProductDefaultPlacements --- /** @deprecated use `ProductDefaultCollections_ModeValues` — same literal set, ProductDefaultPlacements.mode duplicates the canonical export. */ export const ProductDefaultPlacements_ModeValues = ProductDefaultCollections_ModeValues; +// --- ProductPurchaseAudienceEvidenceRequirements --- +/** @deprecated use `AudienceEvidence_EvidenceTypeValues` — same literal set, ProductPurchaseAudienceEvidenceRequirements.accepted_evidence_types duplicates the canonical export. */ +export const ProductPurchaseAudienceEvidenceRequirements_AcceptedEvidenceTypesValues = AudienceEvidence_EvidenceTypeValues; +/** @deprecated use `AudienceEvidenceRequirements_EvidencePresenceValues` — same literal set, ProductPurchaseAudienceEvidenceRequirements.evidence_presence duplicates the canonical export. */ +export const ProductPurchaseAudienceEvidenceRequirements_EvidencePresenceValues = AudienceEvidenceRequirements_EvidencePresenceValues; +/** @deprecated use `AudienceEvidenceRequirements_RequirementModeValues` — same literal set, ProductPurchaseAudienceEvidenceRequirements.requirement_mode duplicates the canonical export. */ +export const ProductPurchaseAudienceEvidenceRequirements_RequirementModeValues = AudienceEvidenceRequirements_RequirementModeValues; // --- ProductTarget --- /** @deprecated use `ProductLocalFormatOptionReference_ScopeValues` — same literal set, ProductTarget.kind duplicates the canonical export. */ export const ProductTarget_KindValues = ProductLocalFormatOptionReference_ScopeValues; @@ -2481,6 +2489,9 @@ export const SyncCreativesSubmitted_StatusValues = BuildCreativeAsyncSubmitted_S // --- TagURL --- /** @deprecated use `DisplayTagFormatDeclaration_FormatKindValues` — same literal set, TagURL.asset_type duplicates the canonical export. */ export const TagURL_AssetTypeValues = DisplayTagFormatDeclaration_FormatKindValues; +// --- TargetingSignalGroups --- +/** @deprecated use `PackageSignalTargetingGroups_OperatorValues` — same literal set, TargetingSignalGroups.operator duplicates the canonical export. */ +export const TargetingSignalGroups_OperatorValues = PackageSignalTargetingGroups_OperatorValues; // --- TextAsset --- /** @deprecated use `GroupTextAsset_AssetTypeValues` — same literal set, TextAsset.asset_type duplicates the canonical export. */ export const TextAsset_AssetTypeValues = GroupTextAsset_AssetTypeValues; diff --git a/src/lib/types/manifest.generated.ts b/src/lib/types/manifest.generated.ts index 3eb730c2b..bdd0e3252 100644 --- a/src/lib/types/manifest.generated.ts +++ b/src/lib/types/manifest.generated.ts @@ -1,8 +1,8 @@ -// AUTO-GENERATED FROM schemas/cache/3.2.0-rc.2/manifest.json — DO NOT EDIT. +// AUTO-GENERATED FROM schemas/cache/3.2.0-rc.3/manifest.json — DO NOT EDIT. // Run `npm run generate-manifest-derived` to regenerate. /** - * Manifest-derived constants for AdCP 3.2.0-rc.2. + * Manifest-derived constants for AdCP 3.2.0-rc.3. * * Single source of truth for tool↔protocol grouping, error-code metadata * (description + recovery + suggestion), and specialism→required-tools @@ -12,8 +12,8 @@ * previously lived in `src/lib/utils/capabilities.ts` and * `src/lib/types/error-codes.ts`. * - * Source: `schemas/cache/3.2.0-rc.2/manifest.json` (adcp_version: 3.2.0-rc.2, generated_at: - * 2026-09-13T18:15:31.349Z). Re-run `npm run sync-schemas` then + * Source: `schemas/cache/3.2.0-rc.3/manifest.json` (adcp_version: 3.2.0-rc.3, generated_at: + * 2026-09-14T11:59:57.201Z). Re-run `npm run sync-schemas` then * `npm run generate-manifest-derived` to refresh after a spec bump. */ @@ -84,7 +84,7 @@ export const STANDARD_ERROR_CODES_FROM_MANIFEST = { suggestion: "contact seller to resolve suspension" }, "ACTION_NOT_ALLOWED": { - description: "The requested mutation maps to an action that is not currently available on this media buy. Sellers MUST populate `error.details` with `attempted_action` (the `media_buy_valid_action` value the request maps to), `reason` (an `action-not-allowed-reason` value: `wrong_status`, `not_supported_on_product`, `not_supported_on_buy`, `mode_mismatch`, or `condition_unresolved`), and `currently_available_actions` (echo of the buy's resolved `available_actions[]` so the buyer SDK can offer recovery without a separate get_media_buys round-trip).", + description: "The requested mutation maps to an action that is not currently available on this media buy. Sellers MUST populate `error.details` with `attempted_action` (the structured available-action identifier the request maps to), `reason` (an `action-not-allowed-reason` value: `wrong_status`, `not_supported_on_product`, `not_supported_on_buy`, `mode_mismatch`, or `condition_unresolved`), and `currently_available_actions` (echo of the buy's resolved `available_actions[]` so the buyer SDK can offer recovery without a separate get_media_buys round-trip).", recovery: "correctable", suggestion: "branch on error.details.reason: for wrong_status, wait for or transition to a status listed under the action's allowed_statuses; for mode_mismatch, this is a flow switch (not a retry against update_media_buy) — follow the mode named in available_actions[].mode; for condition_unresolved, wait until the seller advertises the action after resolving its opaque condition; for not_supported_on_product or not_supported_on_buy, do not retry — the action is unavailable on this buy and buyer must select a different product or renegotiate" }, diff --git a/src/lib/types/schemas.generated.ts b/src/lib/types/schemas.generated.ts index 52fb120d8..c0712b866 100644 --- a/src/lib/types/schemas.generated.ts +++ b/src/lib/types/schemas.generated.ts @@ -1,5 +1,5 @@ // Generated Zod v4 schemas from TypeScript types -// Generated at: 2026-09-14T15:12:42.507Z +// Generated at: 2026-09-14T17:49:02.914Z // Sources: // - core.generated.ts (core types) // - tools.generated.ts (tool types) @@ -105,7 +105,7 @@ export const CanceledBySchema = z.union([z.literal("buyer"), z.literal("seller") export const CanonicalMediaBuyActionModeSchema = z.union([z.literal("self_serve"), z.literal("conditional_self_serve"), z.literal("seller_managed"), z.literal("requires_approval")]); -export const CanonicalMediaBuyActionNameSchema = z.union([z.literal("pause"), z.literal("resume"), z.literal("cancel"), z.literal("extend_flight"), z.literal("shorten_flight"), z.literal("update_flight_dates"), z.literal("increase_budget"), z.literal("decrease_budget"), z.literal("reallocate_budget"), z.literal("update_budget_allocation"), z.literal("update_targeting"), z.literal("update_pacing"), z.literal("update_bidding"), z.literal("update_frequency_caps"), z.literal("update_catalog_assignments"), z.literal("update_keywords"), z.literal("update_optimization_goals"), z.literal("update_impression_goal"), z.literal("update_spend_target"), z.literal("update_reporting_webhook"), z.literal("replace_creative"), z.literal("update_creative_assignments"), z.literal("remove_creative"), z.literal("add_packages"), z.literal("remove_packages")]); +export const CanonicalMediaBuyActionNameSchema = z.union([z.literal("pause"), z.literal("resume"), z.literal("cancel"), z.literal("extend_flight"), z.literal("shorten_flight"), z.literal("update_flight_dates"), z.literal("increase_budget"), z.literal("decrease_budget"), z.literal("reallocate_budget"), z.literal("update_budget_allocation"), z.literal("update_targeting"), z.literal("update_pacing"), z.literal("update_bidding"), z.literal("update_frequency_caps"), z.literal("update_media_buy_frequency_cap"), z.literal("update_catalog_assignments"), z.literal("update_keywords"), z.literal("update_optimization_goals"), z.literal("update_impression_goal"), z.literal("update_spend_target"), z.literal("update_reporting_webhook"), z.literal("replace_creative"), z.literal("update_creative_assignments"), z.literal("remove_creative"), z.literal("add_packages"), z.literal("remove_packages")]); export const CatalogActionSchema = z.union([z.literal("created"), z.literal("updated"), z.literal("unchanged"), z.literal("failed"), z.literal("deleted")]); @@ -221,6 +221,10 @@ export const FormatIDParameterSchema = z.union([z.literal("dimensions"), z.liter export const FrameRateTypeSchema = z.union([z.literal("constant"), z.literal("variable")]); +export const FrequencyCapControlModeSchema = z.union([z.literal("max_impressions"), z.literal("suppress"), z.literal("max_impressions_and_suppress")]); + +export const FrequencyCapMutableFieldSchema = z.union([z.literal("max_impressions"), z.literal("per"), z.literal("window"), z.literal("suppress")]); + export const FrequencyCapScopeSchema = z.literal("package"); export const GenreTaxonomySchema = z.union([z.literal("iab_content_3.0"), z.literal("iab_content_2.2"), z.literal("gracenote"), z.literal("eidr"), z.literal("apple_genres"), z.literal("google_genres"), z.literal("roku"), z.literal("amazon_genres"), z.literal("custom")]); @@ -283,6 +287,8 @@ export const MatchTypeSchema = z.union([z.literal("broad"), z.literal("phrase"), export const MediaBuyActionModeSchema = z.union([z.literal("self_serve"), z.literal("conditional_self_serve"), z.literal("seller_managed"), z.literal("requires_approval")]); +export const MediaBuyFrequencyCapControlModeSchema = z.literal("max_impressions"); + export const MediaBuyHealthSchema = z.union([z.literal("ok"), z.literal("impaired")]); export const MediaBuyStatusSchema = z.union([z.literal("pending_creatives"), z.literal("pending_start"), z.literal("active"), z.literal("paused"), z.literal("completed"), z.literal("rejected"), z.literal("canceled")]); @@ -741,6 +747,15 @@ export const PostalAreaSupportSchema = z.object({ export const IANATimezoneIdentifierSchema = z.string().min(1).max(255).regex(new RegExp("^[A-Za-z0-9._+-]+(?:/[A-Za-z0-9._+-]+)*$")); +export const FrequencyCapImpressionConstraintsSchema = z.object({ + minimum: z.number().int().gte(1).optional(), + maximum: z.number().int().gte(1).optional(), + allowed_values: z.array(z.number()).optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough().merge(z.object({}).passthrough()); + +export const FrequencyCapDurationUnitSchema = z.union([z.literal("seconds"), z.literal("minutes"), z.literal("hours"), z.literal("days"), z.literal("campaign")]); + export const BrowserSupportSchema = z.union([SupportedSchema, z.object({ families: z.array(BrowserFamilySchema), ext: ExtensionObjectSchema.optional() @@ -823,6 +838,14 @@ export const GeographicRegionRequirementSchema = z.object({ }).passthrough()])) }).passthrough(); +export const FrequencyCapRequirementsSchema = z.object({ + mutable_fields: z.array(FrequencyCapMutableFieldSchema).optional(), + supported_control_modes: z.array(FrequencyCapControlModeSchema).optional(), + supported_per_units: z.array(ReachUnitSchema).optional(), + supported_window_units: z.array(FrequencyCapDurationUnitSchema).optional(), + supported_suppression_units: z.array(FrequencyCapDurationUnitSchema).optional() +}).passthrough(); + export const CatalogRequirementSchema = z.object({ countries: z.record(z.string(), z.array(GeographicPlaceTypeSchema)), system_versions: z.array(z.string()).optional() @@ -912,10 +935,14 @@ export const CancellationPolicySchema = z.object({ }).passthrough()]) }).passthrough(); +export const MediaBuyAvailableActionIDSchema = z.union([MediaBuyValidActionSchema, z.literal("update_media_buy_frequency_cap")]); + export const MediaBuyChangeTermIDSchema = z.string().regex(new RegExp("^[A-Za-z0-9_.:-]+$")); export const MediaBuyTermsReferenceSchema = z.string(); +export const ApplicablePackageIDSchema = z.string().min(1); + export const SLAWindowSchema = z.object({ response_max: z.string().regex(new RegExp("^P(?!$)(\\d+Y)?(\\d+M)?(\\d+D)?(T(\\d+H)?(\\d+M)?(\\d+S)?)?$")).optional(), completion_max: z.string().regex(new RegExp("^P(?!$)(\\d+Y)?(\\d+M)?(\\d+D)?(T(\\d+H)?(\\d+M)?(\\d+S)?)?$")).optional() @@ -1030,36 +1057,96 @@ export const AttributionWindowSchema = z.object({ model: AttributionModelSchema.optional() }).passthrough(); -export const DaypartTargetSchema = z.object({ - days: z.array(DayOfWeekSchema), - start_hour: z.number().int().gte(0).lte(23), - end_hour: z.number().int().gte(1).lte(24), - timezone: z.union([z.literal("inventory_local"), IANATimezoneIdentifierSchema]).optional(), - label: z.string().optional() -}).passthrough(); +export const TargetingUnknownAgeEligibilityConstraintSchema = z.object({}).passthrough(); + +export const TargetingVerifiedAgeBasisConstraintSchema = z.object({}).passthrough(); + +export const GeoCountriesSchema = z.array(z.string()); + +export const GeoCountriesExcludeSchema = z.array(z.string()); + +export const GeoRegionsSchema = z.array(z.string()); + +export const GeoRegionsExcludeSchema = z.array(z.string()); + +export const GeoMetrosExcludeSchema = z.array(z.object({ + system: MetroAreaSystemSchema, + values: z.array(z.string()) +}).passthrough()); + +export const AudienceIncludeSchema = z.array(z.string()); + +export const AudienceExcludeSchema = z.array(z.string()); export const SignalTargetingSchema = z.union([z.union([z.object({}).passthrough(), z.object({}).passthrough()]), z.union([z.object({}).passthrough(), z.object({}).passthrough()]), z.union([z.object({}).passthrough(), z.object({}).passthrough()])]); -export const FrequencyCapSchema = z.object({}).passthrough().merge(z.object({ +export const TargetingFrequencyCapSchema = z.object({}).passthrough().merge(z.object({ suppress: DurationSchema.optional(), - suppress_minutes: z.number().gte(0).optional(), - max_impressions: z.number().int().gte(1).optional(), + suppress_minutes: z.number().optional(), + max_impressions: z.number().optional(), per: ReachUnitSchema.optional(), window: DurationSchema.optional() }).passthrough()); +export const TargetingPropertyListSchema = z.object({ + agent_url: z.string(), + list_id: z.string(), + auth_token: z.string().optional() +}).passthrough(); + export const PropertyListReferenceSchema = z.object({ agent_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI"), list_id: z.string().min(1), auth_token: z.string().optional() }).passthrough(); +export const TargetingCollectionListSchema = z.object({ + agent_url: z.string(), + list_id: z.string(), + auth_token: z.string().optional() +}).passthrough(); + export const CollectionListReferenceSchema = z.object({ agent_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI"), list_id: z.string().min(1), auth_token: z.string().optional() }).passthrough(); +export const AgeRestrictionSchema = z.object({ + min: z.number(), + verification_required: z.boolean().optional(), + accepted_methods: z.array(AgeVerificationMethodSchema).optional() +}).passthrough(); + +export const DevicePlatformExcludeSchema = z.array(DevicePlatformSchema); + +export const DeviceTypeExcludeSchema = z.array(DeviceTypeSchema); + +export const BrowserSchema = z.array(BrowserFamilySchema); + +export const BrowserExcludeSchema = z.array(BrowserFamilySchema); + +export const StoreCatchmentsSchema = z.array(z.object({ + catalog_id: z.string(), + store_ids: z.array(z.string()).optional(), + catchment_ids: z.array(z.string()).optional() +}).passthrough()); + +export const GeoProximitySchema = z.array(z.union([z.object({}).passthrough(), z.object({}).passthrough(), z.object({}).passthrough()])); + +export const TargetingLanguagesSchema = z.array(LanguageTagSchema); + +export const TargetingKeywordsSchema = z.array(z.object({ + keyword: z.string(), + match_type: MatchTypeSchema, + bid_price: z.number().optional() +}).passthrough()); + +export const GeoMetroSchema = z.object({ + system: MetroAreaSystemSchema, + values: z.array(z.string()) +}).passthrough(); + export const PostalAreaWithFusedSystemSchema = z.object({ system: CountryFusedPostalCodeSystemSchema, values: z.array(z.string()) @@ -1106,6 +1193,32 @@ export const PostalCountryAreaSchema = PostalCountrySystemSchema.and(z.object({ export const GeographicPlaceIdentifierSystemSchema = z.union([z.union([z.literal("geonames"), z.literal("google_ads"), z.literal("microsoft_ads")]), z.string()]); +export const GeographicPlaceAreaSchema = z.object({}).passthrough().merge(z.object({ + country: z.string().regex(new RegExp("^[A-Z]{2}$")), + system: GeographicPlaceIdentifierSystemSchema, + system_version: z.string().min(1).optional(), + place_type: GeographicPlaceTypeSchema, + values: z.array(z.string()), + value_labels: z.record(z.string(), z.string()).optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough()).merge(z.object({ + country: z.string().regex(new RegExp("^[A-Z]{2}$")), + system: GeographicPlaceIdentifierSystemSchema, + system_version: z.string().min(1).optional(), + place_type: GeographicPlaceTypeSchema, + values: z.array(z.string()), + value_labels: z.record(z.string(), z.string()).optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough()); + +export const DaypartTargetSchema = z.object({ + days: z.array(DayOfWeekSchema), + start_hour: z.number().int().gte(0).lte(23), + end_hour: z.number().int().gte(1).lte(24), + timezone: z.union([z.literal("inventory_local"), IANATimezoneIdentifierSchema]).optional(), + label: z.string().optional() +}).passthrough(); + export const ActivationKeySchema = z.union([z.object({ type: z.literal("segment_id"), segment_id: z.string() @@ -1137,6 +1250,11 @@ export const ProductDefaultCollectionsSchema = z.object({ ext: ExtensionObjectSchema.optional() }).passthrough(); +export const NegativeKeywordSchema = z.object({ + keyword: z.string().min(1), + match_type: MatchTypeSchema +}).passthrough(); + export const CreativeAssignmentSchema = z.object({}).passthrough().merge(z.object({}).passthrough()).merge(z.object({}).passthrough()).merge(z.object({ creative_id: z.string(), weight: z.number().gte(0).lte(100).optional(), @@ -2734,6 +2852,14 @@ export const ReportingPackageIDSchema = z.string(); export const ReportingStatusSeveritySchema = z.union([z.literal("delayed"), z.literal("action_required")]); +export const FrequencyCapSchema = z.object({}).passthrough().merge(z.object({ + suppress: DurationSchema.optional(), + suppress_minutes: z.number().gte(0).optional(), + max_impressions: z.number().int().gte(1).optional(), + per: ReachUnitSchema.optional(), + window: DurationSchema.optional() +}).passthrough()); + export const OptimizationGoalSchema = z.union([z.object({ kind: z.literal("metric"), metric: z.union([z.literal("clicks"), z.literal("views"), z.literal("completed_views"), z.literal("viewed_seconds"), z.literal("attention_seconds"), z.literal("attention_score"), z.literal("engagements"), z.literal("follows"), z.literal("saves"), z.literal("profile_visits"), z.literal("reach")]), @@ -2880,6 +3006,10 @@ export const AttestationEvaluationSchema = z.object({}).passthrough().merge(z.ob ext: ExtensionObjectSchema.optional() }).passthrough()); +export const TargetingGeoMetrosSchema = z.array(GeoMetroSchema); + +export const TargetingNegativeKeywordsSchema = z.array(NegativeKeywordSchema); + export const DemographicPredicateSchema = z.object({ age: DemographicAgeRangeSchema }).passthrough(); @@ -2976,6 +3106,8 @@ export const ImpairmentSchema = z.object({ remediation: z.string().max(500).optional() }).passthrough(); +export const MediaBuyFrequencyCapSchema = FrequencyCapSchema.and(z.object({}).passthrough()); + export const BudgetAllocationSchema = z.union([z.object({ mode: z.literal("fixed") }).passthrough(), z.object({ @@ -3034,25 +3166,6 @@ export const ReportingCoverageSchema = z.object({ }).strict()) }).strict(); -export const ReportingStatusIssueSchema = z.object({ - issue_id: z.string().min(1).max(255).regex(new RegExp("^[A-Za-z0-9_.:-]{1,255}$")), - code: z.union([z.literal("REPORT_OVERDUE"), z.literal("PRODUCTION_FAILED"), z.literal("DELIVERY_FAILED"), z.literal("ACCESS_REQUIRED"), z.literal("CONFIGURATION_REQUIRED"), z.literal("REPORTING_COVERAGE_INCOMPLETE"), z.literal("RESOURCE_EXPIRED"), z.literal("READER_INCOMPATIBLE"), z.literal("HISTORY_UNAVAILABLE"), z.literal("RECEIPT_REQUIRED"), z.literal("RECEIPT_REJECTED"), z.literal("ADJUSTMENT_RECEIPT_REQUIRED"), z.literal("ADJUSTMENT_RECEIPT_REJECTED"), z.literal("CONSUMER_STATUS_MISMATCH")]), - severity: ReportingStatusSeveritySchema, - responsible_party: z.union([z.literal("buyer"), z.literal("seller"), z.literal("provider")]), - recommended_action: z.union([z.literal("wait_for_retry"), z.literal("contact_buyer"), z.literal("contact_seller"), z.literal("contact_provider"), z.literal("repair_access"), z.literal("update_configuration"), z.literal("change_reporting_scope"), z.literal("use_supported_reader")]), - message: z.string().max(500).optional(), - reporting_obligation_id: z.string().min(1).max(255).regex(new RegExp("^[A-Za-z0-9_.:-]{1,255}$")).optional(), - reporting_status_id: z.string().min(16).max(255).regex(new RegExp("^[A-Za-z0-9_.:-]{16,255}$")).optional(), - delivery_config_id: z.string().min(1).max(64).regex(new RegExp("^[A-Za-z0-9_.:-]{1,64}$")).optional(), - delivery_config_version: z.number().int().gte(1).optional(), - feed_purpose: ReportingFeedPurposeSchema.optional(), - media_buy_ids: z.array(ReportingMediaBuyIDSchema).optional(), - package_ids: z.array(ReportingPackageIDSchema).optional(), - period_start: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - period_end: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - expected_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() -}).strict(); - export const PriceAdjustmentSchema = z.object({ kind: PriceAdjustmentKindSchema, name: z.string(), @@ -3202,7 +3315,7 @@ export const OutcomeMeasurementSchema = z.object({ export const BrandReference1Schema = BrandReferenceSchema; export const ProductAllowedActionSchema = z.object({ - action: MediaBuyValidActionSchema, + action: MediaBuyAvailableActionIDSchema, modes: z.array(MediaBuyActionModeSchema), allowed_statuses: z.array(MediaBuyStatusSchema).optional(), sla: SLAWindowSchema.optional(), @@ -3874,13 +3987,15 @@ export const CanonicalPricingOptionSchema = z.object({}).passthrough().merge(z.o commission_basis_description: z.string().min(1).max(1000).optional() }).passthrough()); +export const ProductPurchaseImpressionsSchema = z.number(); + export const BrandKeySchema = z.object({ domain: z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")), brand_id: BrandIDSchema.optional(), countries: z.array(z.string()).optional() }).passthrough(); -export const ProductAudienceEvidenceRequirementsSchema = z.object({}).passthrough().merge(z.object({ +export const ProductPurchaseAudienceEvidenceRequirementsSchema = z.object({}).passthrough().merge(z.object({ requirement_mode: z.union([z.literal("required"), z.literal("preferred")]), evidence_presence: z.union([z.literal("required"), z.literal("when_available")]), accepted_methodologies: z.array(AudienceEvidenceMethodologySchema).optional(), @@ -3890,7 +4005,7 @@ export const ProductAudienceEvidenceRequirementsSchema = z.object({}).passthroug excluded_providers: z.array(BrandKeySchema).optional(), accepted_subject_types: z.array(AudienceSubjectTypeSchema).optional(), accepted_resolution_methods: z.array(AudienceResolutionMethodSchema).optional(), - minimum_confidence: z.number().gte(0).lte(1).optional(), + minimum_confidence: z.number().optional(), maximum_age: DurationSchema.and(z.object({ unit: z.union([z.literal("seconds"), z.literal("minutes"), z.literal("hours"), z.literal("days")]).optional() }).passthrough()).optional(), @@ -4162,7 +4277,8 @@ export const CanonicalMediaBuyActionFieldsSchema = z.object({ mode: CanonicalMediaBuyActionModeSchema, sla: SLAWindowSchema.optional(), change_term_id: MediaBuyChangeTermIDSchema.optional(), - terms_ref: MediaBuyTermsReferenceSchema.optional() + terms_ref: MediaBuyTermsReferenceSchema.optional(), + applicable_package_ids: z.array(ApplicablePackageIDSchema).optional() }).passthrough(); export const WarningSchema = z.object({}).passthrough().merge(z.object({}).passthrough()).merge(z.object({ @@ -4361,6 +4477,18 @@ export const AudienceEvidencePinSchema = z.object({ ext: ExtensionObjectSchema.optional() }).passthrough(); +export const ProductPurchaseMeasurementTermsSchema = z.object({ + billing_measurement: z.object({ + vendor: BrandKeySchema, + max_variance_percent: z.number().optional(), + measurement_window: z.string().optional(), + finalization_deadline_hours: z.number().optional() + }).passthrough().optional(), + makegood_policy: z.object({ + available_remedies: z.array(MakegoodRemedySchema) + }).passthrough().optional() +}).passthrough(); + export const CanonicalForecastVendorMetricValueSchema = z.object({ vendor: BrandKeySchema, metric_id: VendorMetricIDSchema, @@ -4396,12 +4524,13 @@ export const ControlAppliedSchema = z.object({ export const CreateMediaBuyAsyncSubmittedSchema = CreateMediaBuySubmittedSchema; export const MediaBuyAvailableActionSchema = z.object({ - action: MediaBuyValidActionSchema, + action: MediaBuyAvailableActionIDSchema, mode: MediaBuyActionModeSchema, task: z.union([z.literal("control_media_buy"), z.literal("refine_proposals"), z.literal("sync_creatives")]).optional(), sla: SLAWindowSchema.optional(), change_term_id: MediaBuyChangeTermIDSchema.optional(), - terms_ref: MediaBuyTermsReferenceSchema.optional() + terms_ref: MediaBuyTermsReferenceSchema.optional(), + applicable_package_ids: z.array(ApplicablePackageIDSchema).optional() }).passthrough(); export const MeasurementTerms1Schema = MeasurementTermsSchema; @@ -5741,6 +5870,12 @@ export const PropertyReferenceSchema = z.object({ property_id: PropertyIDSchema }).passthrough(); +export const SelectedCollectionsSchema = z.object({ + mode: z.literal("selected"), + collections: z.array(CollectionSelectorSchema.merge(z.object({}).passthrough())), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + export const LimitedSeriesSchema = z.object({ total_installments: z.number().int().gte(1), starts: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), @@ -6212,6 +6347,15 @@ export const KeywordTargetSchema = z.object({ bid_price: z.number().gte(0).optional() }).passthrough(); +export const MediaBuyFrequencyCapRequirementSchema = FrequencyCapRequirementsSchema.and(z.object({ + supported_control_modes: z.array(MediaBuyFrequencyCapControlModeSchema).optional() +}).passthrough()); + +export const ProductMediaBuySupportRequirementsSchema = z.object({ + frequency_cap: z.literal(true).optional(), + frequency_cap_constraints: MediaBuyFrequencyCapRequirementSchema.optional() +}).passthrough(); + export const MissingMetricSchema = z.union([z.object({ scope: z.literal("standard"), metric_id: AvailableMetricSchema, @@ -6263,6 +6407,11 @@ export const PackageDeliveryMetricValueSchema = z.object({}).passthrough().merge qualifier: z.object({}).passthrough() }).passthrough()); +export const PackageSignalTargetingGroupSchema = z.object({ + operator: z.union([z.literal("any"), z.literal("none")]), + signals: z.array(PackageSignalTargetingSchema) +}).passthrough(); + export const PerformanceFeedbackMetricSchema = z.union([z.object({ scope: z.literal("standard"), metric_id: AvailableMetricSchema, @@ -6468,12 +6617,43 @@ export const PrincipalDeclarationsStateSchema = z.object({ }).passthrough()).max(64).optional() }).passthrough(); +export const ProductAudienceEvidenceRequirementsSchema = z.object({}).passthrough().merge(z.object({ + requirement_mode: z.union([z.literal("required"), z.literal("preferred")]), + evidence_presence: z.union([z.literal("required"), z.literal("when_available")]), + accepted_methodologies: z.array(AudienceEvidenceMethodologySchema).optional(), + excluded_methodologies: z.array(AudienceEvidenceMethodologySchema).optional(), + accepted_evidence_types: z.array(z.union([z.literal("measured"), z.literal("forecast"), z.literal("seller_declared")])).optional(), + accepted_providers: z.array(BrandKeySchema).optional(), + excluded_providers: z.array(BrandKeySchema).optional(), + accepted_subject_types: z.array(AudienceSubjectTypeSchema).optional(), + accepted_resolution_methods: z.array(AudienceResolutionMethodSchema).optional(), + minimum_confidence: z.number().gte(0).lte(1).optional(), + maximum_age: DurationSchema.and(z.object({ + unit: z.union([z.literal("seconds"), z.literal("minutes"), z.literal("hours"), z.literal("days")]).optional() + }).passthrough()).optional(), + methodology_documentation_required: z.boolean().optional(), + independent_attestation_required: z.boolean().optional(), + accepted_attestation_issuers: z.array(z.union([z.object({ + type: z.literal("brand"), + brand: BrandKeySchema, + ext: ExtensionObjectSchema.optional() + }).passthrough(), z.object({ + type: z.literal("agent"), + agent_url: z.string(), + ext: ExtensionObjectSchema.optional() + }).passthrough(), z.object({ + type: z.literal("origin"), + origin: z.string(), + ext: ExtensionObjectSchema.optional() + }).passthrough()])).optional(), + accepted_attestation_claim_types: z.array(z.string()).optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough()); + export const ProductChangeMapSchema = z.record(z.string(), z.union([z.literal("include"), z.literal("omit")])); export const BrandReference3Schema = BrandReferenceSchema; -export const GeoProximitySchema = z.array(z.union([z.object({}).passthrough(), z.object({}).passthrough(), z.object({}).passthrough()])); - export const ReferenceRendererSchema = z.object({ runtime: z.literal("browser-esm"), package: z.string().regex(/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/), @@ -6678,8 +6858,9 @@ export const ReportingConsumerStatusSchema = (() => { reporting_obligation_id: z.string().min(1).max(255).regex(new RegExp("^[A-Za-z0-9_.:-]{1,255}$")).optional(), reporting_revision_id: z.string().min(1).max(255).regex(new RegExp("^[A-Za-z0-9_.:-]{1,255}$")).optional(), observed_revision_content_sha256: z.string().regex(new RegExp("^[A-Fa-f0-9]{64}$")).optional(), - consumer_status: z.union([z.literal("received"), z.literal("obligation_missing"), z.literal("revision_missing"), z.literal("unreadable")]), + consumer_status: z.union([z.literal("received"), z.literal("obligation_missing"), z.literal("revision_missing"), z.literal("unreadable"), z.literal("content_mismatch")]), status_as_of: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time"), + mismatch_code: z.union([z.literal("scope_media_buy_missing"), z.literal("coverage_short"), z.literal("metric_missing"), z.literal("schema_nonconformant"), z.literal("currency_mismatch"), z.literal("period_mismatch")]).optional(), failure_code: z.union([z.literal("access_denied"), z.literal("resource_not_found"), z.literal("integrity_mismatch"), z.literal("reader_incompatible"), z.literal("transport_failed")]).optional(), consumer_commit_ref: z.string().min(1).max(512).regex(new RegExp("^[A-Za-z0-9_.:-]{1,512}$")).optional(), seller_ledger_snapshot_id: z.string().min(1).max(255).optional(), @@ -6698,7 +6879,7 @@ export const ReportingConsumerStatusSchema = (() => { ctx.addIssue({ code: "custom", path: [field], message: field + " is forbidden" }); } }; - const allowed = new Set(["reporting_status_id","supersedes_reporting_status_id","delivery_config_id","delivery_config_version","report_definition_id","period","reporting_obligation_id","reporting_revision_id","observed_revision_content_sha256","consumer_status","status_as_of","failure_code","consumer_commit_ref","seller_ledger_snapshot_id","seller_ledger_as_of","recorded_at"]); + const allowed = new Set(["reporting_status_id","supersedes_reporting_status_id","delivery_config_id","delivery_config_version","report_definition_id","period","reporting_obligation_id","reporting_revision_id","observed_revision_content_sha256","consumer_status","status_as_of","mismatch_code","failure_code","consumer_commit_ref","seller_ledger_snapshot_id","seller_ledger_as_of","recorded_at"]); for (const field of Object.keys(value as Record)) { if (!allowed.has(field)) ctx.addIssue({ code: "custom", path: [field], message: "Unrecognized key" }); } @@ -6710,7 +6891,7 @@ export const ReportingConsumerStatusSchema = (() => { } } } - const rules: Record = {"received":{"required":["reporting_obligation_id","reporting_revision_id","observed_revision_content_sha256"],"forbidden":["failure_code"]},"obligation_missing":{"required":[],"forbidden":["reporting_obligation_id","reporting_revision_id","observed_revision_content_sha256","failure_code"]},"revision_missing":{"required":["reporting_obligation_id"],"forbidden":["reporting_revision_id","observed_revision_content_sha256","failure_code"]},"unreadable":{"required":["reporting_obligation_id","reporting_revision_id","failure_code"],"forbidden":["observed_revision_content_sha256"]}}; + const rules: Record = {"received":{"required":["reporting_obligation_id","reporting_revision_id","observed_revision_content_sha256"],"forbidden":["failure_code","mismatch_code"]},"obligation_missing":{"required":[],"forbidden":["reporting_obligation_id","reporting_revision_id","observed_revision_content_sha256","failure_code","mismatch_code"]},"revision_missing":{"required":["reporting_obligation_id"],"forbidden":["reporting_revision_id","observed_revision_content_sha256","failure_code","mismatch_code"]},"unreadable":{"required":["reporting_obligation_id","reporting_revision_id","failure_code"],"forbidden":["observed_revision_content_sha256","mismatch_code"]},"content_mismatch":{"required":["reporting_obligation_id","reporting_revision_id","observed_revision_content_sha256","mismatch_code"],"forbidden":["failure_code"]}}; const rule = Object.hasOwn(rules, value.consumer_status) ? rules[value.consumer_status] : undefined; if (!rule) { ctx.addIssue({ code: "custom", path: ["consumer_status"], message: "Unsupported consumer status" }); @@ -6942,6 +7123,48 @@ export const ReportingScheduleSchema = z.object({}).strict().merge(z.object({ delivery_sla: z.string().regex(new RegExp("^P(?=\\d|T)(?=.*\\d)(?:\\d+Y)?(?:\\d+M)?(?:\\d+D)?(?:T(?=\\d)(?:\\d+H)?(?:\\d+M)?(?:\\d+S)?)?$")) }).strict()); +export const ReportingStatusIssueSchema = z.object({}).strict().merge(z.object({ + issue_id: z.string().min(1).max(255).regex(new RegExp("^[A-Za-z0-9_.:-]{1,255}$")), + code: z.union([z.literal("REPORT_OVERDUE"), z.literal("PRODUCTION_FAILED"), z.literal("DELIVERY_FAILED"), z.literal("ACCESS_REQUIRED"), z.literal("CONFIGURATION_REQUIRED"), z.literal("REPORTING_COVERAGE_INCOMPLETE"), z.literal("RESOURCE_EXPIRED"), z.literal("READER_INCOMPATIBLE"), z.literal("HISTORY_UNAVAILABLE"), z.literal("RECEIPT_REQUIRED"), z.literal("RECEIPT_REJECTED"), z.literal("ADJUSTMENT_RECEIPT_REQUIRED"), z.literal("ADJUSTMENT_RECEIPT_REJECTED"), z.literal("CONSUMER_STATUS_MISMATCH")]), + severity: ReportingStatusSeveritySchema, + opened_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + issue_state: z.union([z.literal("open"), z.literal("acknowledged"), z.literal("resolved"), z.literal("waived")]).optional(), + external_ref: z.string().min(1).max(128).regex(new RegExp("^[A-Za-z0-9_.:-]{1,128}$")).optional(), + responsible_party: z.union([z.literal("buyer"), z.literal("seller"), z.literal("provider")]), + recommended_action: z.union([z.literal("wait_for_retry"), z.literal("contact_buyer"), z.literal("contact_seller"), z.literal("contact_provider"), z.literal("repair_access"), z.literal("update_configuration"), z.literal("change_reporting_scope"), z.literal("use_supported_reader")]), + message: z.string().max(500).optional(), + reporting_obligation_id: z.string().min(1).max(255).regex(new RegExp("^[A-Za-z0-9_.:-]{1,255}$")).optional(), + reporting_status_id: z.string().min(16).max(255).regex(new RegExp("^[A-Za-z0-9_.:-]{16,255}$")).optional(), + delivery_config_id: z.string().min(1).max(64).regex(new RegExp("^[A-Za-z0-9_.:-]{1,64}$")).optional(), + delivery_config_version: z.number().int().gte(1).optional(), + feed_purpose: ReportingFeedPurposeSchema.optional(), + media_buy_ids: z.array(ReportingMediaBuyIDSchema).optional(), + package_ids: z.array(ReportingPackageIDSchema).optional(), + period_start: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + period_end: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + expected_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() +}).strict()).merge(z.object({ + issue_id: z.string().min(1).max(255).regex(new RegExp("^[A-Za-z0-9_.:-]{1,255}$")), + code: z.union([z.literal("REPORT_OVERDUE"), z.literal("PRODUCTION_FAILED"), z.literal("DELIVERY_FAILED"), z.literal("ACCESS_REQUIRED"), z.literal("CONFIGURATION_REQUIRED"), z.literal("REPORTING_COVERAGE_INCOMPLETE"), z.literal("RESOURCE_EXPIRED"), z.literal("READER_INCOMPATIBLE"), z.literal("HISTORY_UNAVAILABLE"), z.literal("RECEIPT_REQUIRED"), z.literal("RECEIPT_REJECTED"), z.literal("ADJUSTMENT_RECEIPT_REQUIRED"), z.literal("ADJUSTMENT_RECEIPT_REJECTED"), z.literal("CONSUMER_STATUS_MISMATCH")]), + severity: ReportingStatusSeveritySchema, + opened_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + issue_state: z.union([z.literal("open"), z.literal("acknowledged"), z.literal("resolved"), z.literal("waived")]).optional(), + external_ref: z.string().min(1).max(128).regex(new RegExp("^[A-Za-z0-9_.:-]{1,128}$")).optional(), + responsible_party: z.union([z.literal("buyer"), z.literal("seller"), z.literal("provider")]), + recommended_action: z.union([z.literal("wait_for_retry"), z.literal("contact_buyer"), z.literal("contact_seller"), z.literal("contact_provider"), z.literal("repair_access"), z.literal("update_configuration"), z.literal("change_reporting_scope"), z.literal("use_supported_reader")]), + message: z.string().max(500).optional(), + reporting_obligation_id: z.string().min(1).max(255).regex(new RegExp("^[A-Za-z0-9_.:-]{1,255}$")).optional(), + reporting_status_id: z.string().min(16).max(255).regex(new RegExp("^[A-Za-z0-9_.:-]{16,255}$")).optional(), + delivery_config_id: z.string().min(1).max(64).regex(new RegExp("^[A-Za-z0-9_.:-]{1,64}$")).optional(), + delivery_config_version: z.number().int().gte(1).optional(), + feed_purpose: ReportingFeedPurposeSchema.optional(), + media_buy_ids: z.array(ReportingMediaBuyIDSchema).optional(), + package_ids: z.array(ReportingPackageIDSchema).optional(), + period_start: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + period_end: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + expected_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() +}).strict()); + export const ReportingReceiptSchema = z.object({}).strict().merge(z.object({ reporting_receipt_id: z.string().min(16).max(255).regex(new RegExp("^[A-Za-z0-9_.:-]{16,255}$")), reporting_obligation_id: z.string().min(1).max(255).regex(new RegExp("^[A-Za-z0-9_.:-]{1,255}$")), @@ -7562,7 +7785,7 @@ export const AccountSetupRequiredDetailsSchema = z.object({ }).passthrough(); export const ActionNotAllowedDetailsSchema = z.object({ - attempted_action: MediaBuyValidActionSchema, + attempted_action: MediaBuyAvailableActionIDSchema, reason: ActionNotAllowedReasonSchema, currently_available_actions: z.array(MediaBuyAvailableActionSchema).optional() }).passthrough(); @@ -7880,7 +8103,17 @@ export const OutcomeTargetSchema = z.object({ } }); -export const ProductResponseFieldsSchema = z.array(z.union([z.literal("product_id"), z.literal("name"), z.literal("description"), z.literal("publisher_properties"), z.literal("channels"), z.literal("video_placement_types"), z.literal("audio_distribution_types"), z.literal("sponsored_placement_types"), z.literal("social_placement_surfaces"), z.literal("format_options"), z.literal("placements"), z.literal("delivery_type"), z.literal("exclusivity"), z.literal("pricing_options"), z.literal("forecast"), z.literal("reporting_capabilities"), z.literal("measurement_terms"), z.literal("performance_standards"), z.literal("catalog_types"), z.literal("signal_targeting_allowed"), z.literal("signal_targeting_rules"), z.literal("demographic_targeting"), z.literal("audience_evidence"), z.literal("audience_evidence_selections"), z.literal("max_optimization_goals"), z.literal("catalog_match"), z.literal("list_applications"), z.literal("brief_relevance"), z.literal("acceptance_policy_profile_ids"), z.literal("identity"), z.literal("expires_at"), z.literal("allowed_actions")])); +export const ProductResponseFieldsSchema = z.array(z.union([z.literal("product_id"), z.literal("name"), z.literal("description"), z.literal("publisher_properties"), z.literal("channels"), z.literal("video_placement_types"), z.literal("audio_distribution_types"), z.literal("sponsored_placement_types"), z.literal("social_placement_surfaces"), z.literal("format_options"), z.literal("placements"), z.literal("delivery_type"), z.literal("exclusivity"), z.literal("pricing_options"), z.literal("forecast"), z.literal("reporting_capabilities"), z.literal("measurement_terms"), z.literal("performance_standards"), z.literal("catalog_types"), z.literal("signal_targeting_allowed"), z.literal("signal_targeting_rules"), z.literal("demographic_targeting"), z.literal("overlay_support"), z.literal("media_buy_support"), z.literal("audience_evidence"), z.literal("audience_evidence_selections"), z.literal("max_optimization_goals"), z.literal("catalog_match"), z.literal("list_applications"), z.literal("brief_relevance"), z.literal("acceptance_policy_profile_ids"), z.literal("identity"), z.literal("expires_at"), z.literal("allowed_actions")])); + +export const FormatOptionRefsSchema = z.array(FormatOptionReferenceSchema); + +export const CatalogIdsSchema = z.array(z.string()); + +export const OptimizationGoalsSchema = z.array(CanonicalOptimizationGoalSchema); + +export const AudienceEvidencePinsSchema = z.array(AudienceEvidencePinSchema); + +export const PerformanceStandardsSchema = z.array(CanonicalPerformanceStandardSchema); export const ProductRefinementRequestsSchema = z.array(z.union([z.object({ scope: z.literal("request"), @@ -8410,23 +8643,12 @@ export const PostalAreaSchema = z.union([PostalArea1Schema, PostalAreaWithFusedS } }); -export const GeographicPlaceAreaSchema = z.object({}).passthrough().merge(z.object({ - country: z.string().regex(new RegExp("^[A-Z]{2}$")), - system: GeographicPlaceIdentifierSystemSchema, - system_version: z.string().min(1).optional(), - place_type: GeographicPlaceTypeSchema, - values: z.array(z.string()), - value_labels: z.record(z.string(), z.string()).optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough()).merge(z.object({ - country: z.string().regex(new RegExp("^[A-Z]{2}$")), - system: GeographicPlaceIdentifierSystemSchema, - system_version: z.string().min(1).optional(), - place_type: GeographicPlaceTypeSchema, - values: z.array(z.string()), - value_labels: z.record(z.string(), z.string()).optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough()); +export const TargetingSignalGroupsSchema = z.object({ + operator: z.literal("all"), + groups: z.array(PackageSignalTargetingGroupSchema) +}).passthrough(); + +export const TargetingCollectionSelectionSchema = z.union([SelectedCollectionsSchema, ProductDefaultCollectionsSchema]); export const SellerInlinePlacementIdentitySchema = z.object({ kind: z.literal("seller_inline"), @@ -8434,22 +8656,11 @@ export const SellerInlinePlacementIdentitySchema = z.object({ placement_id: z.string() }).passthrough(); -export const SelectedCollectionsSchema = z.object({ - mode: z.literal("selected"), - collections: z.array(CollectionSelectorSchema.merge(z.object({}).passthrough())), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - export const ScopeCapabilitySchema = z.object({ fixed: PolicyProfileSchema.optional(), seller_optimized: PolicyProfileSchema.optional() }).passthrough(); -export const PackageSignalTargetingGroupSchema = z.object({ - operator: z.union([z.literal("any"), z.literal("none")]), - signals: z.array(PackageSignalTargetingSchema) -}).passthrough(); - export const PlacementIdentitySchema = z.union([PublisherCatalogPlacementIdentitySchema, SellerInlinePlacementIdentitySchema]); export const GeographicPlaceRequirementSchema = z.object({ @@ -8576,11 +8787,47 @@ export const PlacementForecastDimensionSchema = z.object({ placement_name: z.string().optional() }).passthrough(); -export const AttestationIssuerSchema = z.union([AttestationBrandIssuerSchema, AttestationAgentIssuerSchema, AttestationOriginIssuerSchema]); - -export const AttestationBrandSubjectSchema = z.object({ - type: z.literal("brand"), - brand: BrandReferenceSchema, +export const FrequencyCapIntervalConstraintsSchema = z.object({ + unit: FrequencyCapDurationUnitSchema, + minimum_interval: z.number().optional(), + maximum_interval: z.number().optional(), + allowed_intervals: z.array(z.number()).optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough().and(z.union([z.object({}).passthrough(), z.object({}).passthrough()])).and(z.object({ + unit: FrequencyCapDurationUnitSchema, + minimum_interval: z.number().optional(), + maximum_interval: z.number().optional(), + allowed_intervals: z.array(z.number()).optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough()).and(z.union([z.object({}).passthrough(), z.object({}).passthrough()])).and(z.object({ + unit: FrequencyCapDurationUnitSchema, + minimum_interval: z.number().optional(), + maximum_interval: z.number().optional(), + allowed_intervals: z.array(z.number()).optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough()).and(z.union([z.object({}).passthrough(), z.object({}).passthrough()])).and(z.object({ + unit: FrequencyCapDurationUnitSchema, + minimum_interval: z.number().optional(), + maximum_interval: z.number().optional(), + allowed_intervals: z.array(z.number()).optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough()).and(z.union([z.object({}).passthrough(), z.object({}).passthrough()])); + +export const FrequencyCapConstraintsSchema = z.object({}).passthrough().merge(z.object({ + mutable_fields: z.array(FrequencyCapMutableFieldSchema).optional(), + supported_control_modes: z.array(FrequencyCapControlModeSchema).optional(), + supported_per_units: z.array(ReachUnitSchema).optional(), + max_impressions_constraints: FrequencyCapImpressionConstraintsSchema.optional(), + window_constraints: z.array(FrequencyCapIntervalConstraintsSchema).optional(), + suppression_constraints: z.array(FrequencyCapIntervalConstraintsSchema).optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough()); + +export const AttestationIssuerSchema = z.union([AttestationBrandIssuerSchema, AttestationAgentIssuerSchema, AttestationOriginIssuerSchema]); + +export const AttestationBrandSubjectSchema = z.object({ + type: z.literal("brand"), + brand: BrandReferenceSchema, ext: ExtensionObjectSchema.optional() }).passthrough(); @@ -8633,6 +8880,10 @@ export const PlaceSupportSchema = z.object({ ext: ExtensionObjectSchema.optional() }).passthrough(); +export const MediaBuyFrequencyCapSupportSchema = FrequencyCapConstraintsSchema.and(z.object({ + supported_control_modes: z.array(MediaBuyFrequencyCapControlModeSchema).optional() +}).passthrough()); + export const InstallmentDeadlinesSchema = z.object({ booking_deadline: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), cancellation_deadline: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), @@ -8664,6 +8915,7 @@ export const TargetingOverlayRequirementsSchema = z.object({ age: RequiredSchema }).passthrough()]).optional(), frequency_cap: RequiredSchema.optional(), + frequency_cap_support: FrequencyCapRequirementsSchema.optional(), property_list: RequiredSchema.optional(), property_list_exclude: RequiredSchema.optional(), collection_list: RequiredSchema.optional(), @@ -8716,6 +8968,7 @@ export const TargetingOverlaySupportSchema = z.object({ ext: ExtensionObjectSchema.optional() }).passthrough()]).optional(), frequency_cap: SupportedSchema.optional(), + frequency_cap_support: FrequencyCapConstraintsSchema.optional(), property_list: SupportedSchema.optional(), property_list_exclude: SupportedSchema.optional(), collection_list: SupportedSchema.optional(), @@ -8739,6 +8992,12 @@ export const TargetingOverlaySupportSchema = z.object({ ext: ExtensionObjectSchema.optional() }).passthrough(); +export const ProductMediaBuySupportSchema = z.object({ + frequency_cap: z.literal(true).optional(), + frequency_cap_constraints: MediaBuyFrequencyCapSupportSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + export const CanonicalDOOHPlacementAttributesSchema = z.object({ slot_duration_seconds: z.number().optional(), loop_duration_seconds: z.number().optional(), @@ -8760,6 +9019,16 @@ export const DeclineProposalsRequestSchema = z.object({ opportunity: OpportunityContextSchema.optional() }).passthrough(); +export const GeoPostalAreasSchema = z.array(PostalAreaSchema); + +export const GeoPostalAreasExcludeSchema = z.array(PostalAreaSchema); + +export const GeoPlacesSchema = z.array(GeographicPlaceAreaSchema); + +export const GeoPlacesExcludeSchema = z.array(GeographicPlaceAreaSchema); + +export const DaypartTargetsSchema = z.array(DaypartTargetSchema); + export const AcceptProposalRequestSchema = z.object({ adcp_version: z.string().optional(), adcp_major_version: z.number().optional(), @@ -11424,12 +11693,21 @@ export const ReportingDeliveryCapabilitiesSchema = z.object({}).passthrough().me offerings: z.array(ReportingDeliveryOfferingSchema), automated_recovery_window_seconds: z.number().int().gte(0), status_retention_days: z.number().int().gte(1), + consumer_mismatch_escalation_seconds: z.number().int().gte(0).optional(), + operations_contact: z.object({ + url: z.string().max(2048).regex(new RegExp("^https://(?![^/]*@)(?!localhost(?:[:/]|$))(?!\\[)(?!\\d+(?:\\.\\d+){3}(?::|/|$))(?:[A-Za-z0-9-]+\\.)+[A-Za-z]{2,}(?::\\d+)?(?:/|$)")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), + email: z.string().max(254).optional() + }).passthrough().optional(), reliability_statistics: z.array(ReportingReliabilityStatisticsSchema).optional(), resource_retention_days: z.number().int().gte(1).optional(), supports_webhook_activity: z.boolean().optional(), authorization_revocation_seconds: z.number().int().gte(0).optional() }).passthrough()); +export const MediaBuyFrequencyCapCapabilitySchema = FrequencyCapConstraintsSchema.and(z.object({ + supported_control_modes: z.array(MediaBuyFrequencyCapControlModeSchema) +}).passthrough()); + export const BudgetCappingTimezoneBasisSchema = z.union([z.literal("account"), z.literal("fixed")]); export const IdempotencySupportedSchema = z.object({ @@ -12210,13 +12488,6 @@ export const ReportingFileTransferSchema = z.object({ format: z.union([z.literal("jsonl"), z.literal("csv"), z.literal("parquet"), z.literal("avro"), z.literal("orc")]) }).passthrough(); -export const PackageSignalTargetingGroupsSchema = z.object({ - operator: z.literal("all"), - groups: z.array(PackageSignalTargetingGroupSchema) -}).passthrough(); - -export const CollectionSelectionSchema = z.union([SelectedCollectionsSchema, ProductDefaultCollectionsSchema]); - export const SelectedPlacementsSchema = z.object({ mode: z.literal("selected"), placement_refs: z.array(z.union([PlacementReferenceSchema.merge(z.object({}).passthrough()), PlacementIdentitySchema])), @@ -12385,6 +12656,8 @@ export const AttestationReferenceSchema = z.object({ ext: ExtensionObjectSchema.optional() }).passthrough()); +export const PlacementSelectionSchema = z.union([SelectedPlacementsSchema, ProductDefaultPlacementsSchema]); + // @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. export const ProductFormatDeclarationSchema: z.ZodObject<{ [K in keyof ProductFormatDeclaration]-?: undefined extends ProductFormatDeclaration[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, ProductFormatDeclaration & Record> = z.object({}).passthrough().merge(z.object({}).passthrough()).merge(z.object({}).passthrough()).merge(z.object({}).passthrough()).merge(z.object({}).passthrough()).merge(z.object({}).passthrough()).merge(z.object({ format_option_id: z.string().optional(), @@ -12708,6 +12981,7 @@ export const ProductSchema: ProductSchemaObject & z.ZodType< signal_targeting_allowed: z.boolean().optional(), demographic_targeting: DemographicTargetingCapabilitySchema.optional(), overlay_support: TargetingOverlaySupportSchema.optional(), + media_buy_support: ProductMediaBuySupportSchema.optional(), identity: ProductIdentitySchema.optional(), targeting_resolution: ProductTargetingResolutionSchema.optional(), audience_evidence: z.array(AudienceEvidenceSchema).optional(), @@ -12923,6 +13197,57 @@ export const RightsConstraintSchema = z.object({}).passthrough().merge(z.object( ext: ExtensionObjectSchema.optional() }).passthrough()); +export const TargetingOverlaySchema = TargetingUnknownAgeEligibilityConstraintSchema.merge(TargetingVerifiedAgeBasisConstraintSchema).merge(z.object({ + geo_countries: z.array(z.string()).optional(), + geo_countries_exclude: z.array(z.string()).optional(), + geo_regions: z.array(z.string()).optional(), + geo_regions_exclude: z.array(z.string()).optional(), + geo_metros: TargetingGeoMetrosSchema.optional(), + geo_metros_exclude: z.array(z.object({ + system: MetroAreaSystemSchema, + values: z.array(z.string()) + }).passthrough()).optional(), + geo_postal_areas: z.array(PostalAreaSchema).optional(), + geo_postal_areas_exclude: z.array(PostalAreaSchema).optional(), + geo_places: z.array(GeographicPlaceAreaSchema).optional(), + geo_places_exclude: z.array(GeographicPlaceAreaSchema).optional(), + daypart_targets: z.array(DaypartTargetSchema).optional(), + axe_include_segment: z.string().optional(), + axe_exclude_segment: z.string().optional(), + audience_include: z.array(z.string()).optional(), + audience_exclude: z.array(z.string()).optional(), + signal_targeting_groups: TargetingSignalGroupsSchema.optional(), + signal_targeting: z.array(SignalTargetingSchema).optional(), + demographics: DemographicTargetingIntentSchema.optional(), + frequency_cap: TargetingFrequencyCapSchema.optional(), + property_list: TargetingPropertyListSchema.optional(), + property_list_exclude: PropertyListReferenceSchema.optional(), + collection_list: TargetingCollectionListSchema.optional(), + collection_list_exclude: CollectionListReferenceSchema.optional(), + placement_selection: PlacementSelectionSchema.optional(), + collection_selection: TargetingCollectionSelectionSchema.optional(), + age_restriction: z.object({ + min: z.number().int().gte(13).lte(99), + verification_required: z.boolean().optional(), + accepted_methods: z.array(AgeVerificationMethodSchema).optional() + }).passthrough().optional(), + device_platform: z.array(DevicePlatformSchema).optional(), + device_platform_exclude: z.array(DevicePlatformSchema).optional(), + device_type: z.array(DeviceTypeSchema).optional(), + device_type_exclude: z.array(DeviceTypeSchema).optional(), + browser: z.array(BrowserFamilySchema).optional(), + browser_exclude: z.array(BrowserFamilySchema).optional(), + store_catchments: z.array(z.object({ + catalog_id: z.string(), + store_ids: z.array(z.string()).optional(), + catchment_ids: z.array(z.string()).optional() + }).passthrough()).optional(), + geo_proximity: z.array(z.union([z.object({}).passthrough(), z.object({}).passthrough(), z.object({}).passthrough()])).optional(), + language: TargetingLanguagesSchema.optional(), + keyword_targets: TargetingKeywordsSchema.optional(), + negative_keywords: TargetingNegativeKeywordsSchema.optional() +}).passthrough()); + export const DeliveryForecast1Schema = DeliveryForecastSchema; export const GetProductsAsyncInputRequiredSchema: z.ZodType = z.object({ @@ -12933,6 +13258,31 @@ export const GetProductsAsyncInputRequiredSchema: z.ZodType = z.object({ ext: ExtensionObjectSchema.optional() }).passthrough(); +export const ProductPurchaseSchema = z.object({ + product_id: z.string().min(1), + pricing_option_id: z.string().min(1), + pricing: CanonicalPricingOptionSchema.optional(), + format_option_refs: z.array(FormatOptionReferenceSchema).optional(), + catalog_ids: z.array(z.string()).optional(), + budget: z.number().gte(0).optional(), + daily_budget_cap: z.number().gte(0).optional(), + min_spend_target: z.number().gte(0).optional(), + impressions: ProductPurchaseImpressionsSchema.optional(), + start_time: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + end_time: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + pacing: PacingSchema.optional(), + bidding: BiddingPolicySchema.optional(), + targeting_overlay: TargetingOverlaySchema.optional(), + optimization_goals: z.array(CanonicalOptimizationGoalSchema).optional(), + audience_evidence_requirements: ProductPurchaseAudienceEvidenceRequirementsSchema.optional(), + audience_evidence_pins: z.array(AudienceEvidencePinSchema).optional(), + agency_estimate_number: z.string().max(100).optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional(), + measurement_terms: ProductPurchaseMeasurementTermsSchema.optional(), + performance_standards: z.array(CanonicalPerformanceStandardSchema).optional() +}).passthrough(); + export const CanonicalForecastPointSchema = z.object({ label: z.string().max(128).optional(), budget: z.number().gte(0).optional(), @@ -13224,6 +13574,11 @@ export const VerifyBrandClaimsSuccessSchema = z.object({ ext: ExtensionObjectSchema.optional() }).passthrough(); +export const ProductDiscoveryTargetingResolutionSchema = z.object({ + brief_targeting: TargetingOverlaySchema, + ext: ExtensionObjectSchema.optional() +}).passthrough(); + export const ProposalSchema = z.object({}).passthrough().merge(z.object({ proposal_id: z.string().max(255), name: z.string().max(500), @@ -13231,6 +13586,7 @@ export const ProposalSchema = z.object({}).passthrough().merge(z.object({ allocations: z.array(ProductAllocationSchema), budget_allocation: BudgetAllocationSchema.optional(), pacing: PacingSchema.optional(), + frequency_cap: MediaBuyFrequencyCapSchema.optional(), proposal_status: ProposalStatusSchema.optional(), expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), insertion_order: InsertionOrderSchema.optional(), @@ -13313,6 +13669,8 @@ export const CollectionPropertyDeliveryMetricsSchema = DeliveryMetricsSchema.mer property_name: z.string().optional() }).passthrough()); +export const CollectionSelectionSchema = z.union([SelectedCollectionsSchema, ProductDefaultCollectionsSchema]); + export const CreativeDeliveryMetricsSchema = DeliveryMetricsSchema.merge(z.object({ creative_id: z.string(), creative_name: z.string().optional(), @@ -13621,6 +13979,11 @@ export const OfferingSchema = z.object({ ext: ExtensionObjectSchema.optional() }).passthrough(); +export const PackageSignalTargetingGroupsSchema = z.object({ + operator: z.literal("all"), + groups: z.array(PackageSignalTargetingGroupSchema) +}).passthrough(); + export const InlineDeclarationSchema = z.object({}).passthrough().merge(z.object({ format_option_id: z.string().optional(), publisher_domain: z.string().optional(), @@ -14187,6 +14550,113 @@ export const AcceptancePolicyCatalogSchema = z.object({ ext: ExtensionObjectSchema.optional() }).passthrough(); +export const TargetingOverlayInputSchema = TargetingUnknownAgeEligibilityConstraintSchema.merge(TargetingVerifiedAgeBasisConstraintSchema).merge(z.object({ + geo_countries: GeoCountriesSchema.optional().nullable(), + geo_countries_exclude: GeoCountriesExcludeSchema.optional().nullable(), + geo_regions: GeoRegionsSchema.optional().nullable(), + geo_regions_exclude: GeoRegionsExcludeSchema.optional().nullable(), + geo_metros: TargetingGeoMetrosSchema.optional(), + geo_metros_exclude: GeoMetrosExcludeSchema.optional().nullable(), + geo_postal_areas: GeoPostalAreasSchema.optional().nullable(), + geo_postal_areas_exclude: GeoPostalAreasExcludeSchema.optional().nullable(), + geo_places: GeoPlacesSchema.optional().nullable(), + geo_places_exclude: GeoPlacesExcludeSchema.optional().nullable(), + daypart_targets: DaypartTargetsSchema.optional().nullable(), + axe_include_segment: z.string().optional().nullable(), + axe_exclude_segment: z.string().optional().nullable(), + audience_include: AudienceIncludeSchema.optional().nullable(), + audience_exclude: AudienceExcludeSchema.optional().nullable(), + signal_targeting_groups: TargetingSignalGroupsSchema.optional().nullable(), + signal_targeting: z.array(SignalTargetingSchema).optional().nullable(), + demographics: DemographicTargetingIntentSchema.optional().nullable(), + frequency_cap: TargetingFrequencyCapSchema.optional().nullable(), + property_list: TargetingPropertyListSchema.optional().nullable(), + property_list_exclude: PropertyListReferenceSchema.optional().nullable(), + collection_list: TargetingCollectionListSchema.optional().nullable(), + collection_list_exclude: CollectionListReferenceSchema.optional().nullable(), + placement_selection: PlacementSelectionSchema.optional().nullable(), + collection_selection: TargetingCollectionSelectionSchema.optional().nullable(), + age_restriction: AgeRestrictionSchema.optional().nullable(), + device_platform: z.array(DevicePlatformSchema).optional().nullable(), + device_platform_exclude: DevicePlatformExcludeSchema.optional().nullable(), + device_type: z.array(DeviceTypeSchema).optional().nullable(), + device_type_exclude: DeviceTypeExcludeSchema.optional().nullable(), + browser: BrowserSchema.optional().nullable(), + browser_exclude: BrowserExcludeSchema.optional().nullable(), + store_catchments: StoreCatchmentsSchema.optional().nullable(), + geo_proximity: GeoProximitySchema.optional().nullable(), + language: TargetingLanguagesSchema.optional(), + keyword_targets: TargetingKeywordsSchema.optional(), + negative_keywords: TargetingNegativeKeywordsSchema.optional() +}).passthrough()); + +export const ProductDiscoveryCriteriaSchema = z.object({ + product_ids: z.array(z.string()).optional(), + offer_filters: ProductOfferFiltersSchema.optional(), + targeting_overlay: TargetingOverlaySchema.optional(), + media_buy_frequency_cap: MediaBuyFrequencyCapSchema.optional(), + required_overlay_support: TargetingOverlayRequirementsSchema.optional(), + required_media_buy_support: ProductMediaBuySupportRequirementsSchema.optional(), + outcome_target: OutcomeTargetSchema.optional(), + acceptance_context: AcceptanceContextSchema.optional(), + catalog: CatalogSelectionSchema.optional(), + policy_ids: z.array(z.string()).optional(), + ext: z.object({}).passthrough().optional() +}).passthrough(); + +export const ProductPurchaseInputSchema = z.object({ + product_id: z.string(), + pricing_option_id: z.string(), + pricing: CanonicalPricingOptionSchema.optional(), + format_option_refs: FormatOptionRefsSchema.optional(), + catalog_ids: CatalogIdsSchema.optional(), + budget: z.number().optional(), + daily_budget_cap: z.number().optional(), + min_spend_target: z.number().optional(), + impressions: ProductPurchaseImpressionsSchema.optional(), + start_time: z.string().optional(), + end_time: z.string().optional(), + pacing: PacingSchema.optional(), + bidding: BiddingPolicySchema.optional(), + targeting_overlay: TargetingOverlayInputSchema.optional(), + optimization_goals: OptimizationGoalsSchema.optional(), + audience_evidence_requirements: ProductPurchaseAudienceEvidenceRequirementsSchema.optional(), + audience_evidence_pins: AudienceEvidencePinsSchema.optional(), + agency_estimate_number: z.string().optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional(), + measurement_terms: ProductPurchaseMeasurementTermsSchema.optional(), + performance_standards: PerformanceStandardsSchema.optional() +}).passthrough(); + +export const ProposalRefinementSchema = z.object({ + proposal_id: z.string().min(1), + action: z.union([z.literal("revise"), z.literal("finalize")]).optional(), + change_kind: z.union([z.literal("amendment"), z.literal("cancellation")]).optional(), + constraints: z.object({ + total_budget: ProposalBudgetConstraintSchema.optional(), + cpm: z.object({ + max: z.number().gt(0), + currency: z.string().regex(new RegExp("^[A-Z]{3}$")) + }).passthrough().optional(), + impressions: z.object({ + min: z.number().gt(0) + }).passthrough().optional(), + flight: z.object({}).passthrough().optional() + }).passthrough().optional(), + product_changes: ProductChangeMapSchema.optional(), + alternatives: z.object({ + count: z.number().int().gte(2).lte(10) + }).passthrough().optional(), + ask: z.string().min(1).optional(), + criteria: ProductDiscoveryCriteriaSchema.optional(), + remove_media_buy_frequency_cap: z.literal(true).optional() +}).passthrough().and(z.union([z.object({ + action: z.literal("finalize") + }).passthrough(), z.union([z.object({}).passthrough(), z.object({ + change_kind: z.literal("cancellation") + }).passthrough()])])); + export const PropertyFeatureResultSchema = z.object({ property: PropertyIDSchema, features: z.record(z.string(), PropertyFeatureValueSchema).optional(), @@ -14268,84 +14738,132 @@ export const ContextMatchResponseRouterPublisherSchema = z.object({ export const FormatAssetSlotSchema = z.union([IndividualAssetSlotSchema, RepeatableGroupAssetSchema]); -export const PlacementSelectionSchema = z.union([SelectedPlacementsSchema, ProductDefaultPlacementsSchema]); - -export const TargetingOverlaySchema = z.object({}).passthrough().merge(z.object({ - geo_countries: z.array(z.string()).optional(), - geo_countries_exclude: z.array(z.string()).optional(), - geo_regions: z.array(z.string()).optional(), - geo_regions_exclude: z.array(z.string()).optional(), - geo_metros: z.array(z.object({ - system: MetroAreaSystemSchema, - values: z.array(z.string()) - }).passthrough()).optional(), - geo_metros_exclude: z.array(z.object({ - system: MetroAreaSystemSchema, - values: z.array(z.string()) - }).passthrough()).optional(), - geo_postal_areas: z.array(PostalAreaSchema).optional(), - geo_postal_areas_exclude: z.array(PostalAreaSchema).optional(), - geo_places: z.array(GeographicPlaceAreaSchema).optional(), - geo_places_exclude: z.array(GeographicPlaceAreaSchema).optional(), - daypart_targets: z.array(DaypartTargetSchema).optional(), - axe_include_segment: z.string().optional(), - axe_exclude_segment: z.string().optional(), - audience_include: z.array(z.string()).optional(), - audience_exclude: z.array(z.string()).optional(), - signal_targeting_groups: PackageSignalTargetingGroupsSchema.optional(), - signal_targeting: z.array(SignalTargetingSchema).optional(), - demographics: DemographicTargetingIntentSchema.optional(), - frequency_cap: FrequencyCapSchema.optional(), +// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. +export const GetProductsRequestSchema: z.ZodObject<{ [K in keyof GetProductsRequest]-?: undefined extends GetProductsRequest[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, GetProductsRequest & Record> = z.object({ + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/).optional(), + buying_mode: z.union([z.literal("brief"), z.literal("wholesale"), z.literal("refine")]), + brief: z.string().optional(), + refine: z.array(z.union([z.object({ + scope: z.literal("request"), + ask: z.string().min(1) + }).passthrough(), z.object({ + scope: z.literal("product"), + product_id: z.string().min(1), + action: z.union([z.literal("include"), z.literal("omit"), z.literal("more_like_this")]).optional(), + ask: z.string().min(1).optional() + }).passthrough(), z.object({ + scope: z.literal("proposal"), + proposal_id: z.string().min(1), + action: z.union([z.literal("include"), z.literal("omit"), z.literal("finalize")]).optional(), + ask: z.string().min(1).optional() + }).passthrough()])).optional(), + brand: BrandReferenceSchema.optional(), + acceptance_context: AcceptanceContextSchema.optional(), + catalog: CatalogSchema.optional(), + account: AccountReferenceSchema.optional(), + preferred_delivery_types: z.array(DeliveryTypeSchema).optional(), + filters: ProductFiltersSchema.optional(), + targeting_overlay: TargetingOverlaySchema.optional(), + media_buy_frequency_cap: MediaBuyFrequencyCapSchema.optional(), + required_overlay_support: TargetingOverlayRequirementsSchema.optional(), + required_media_buy_support: ProductMediaBuySupportRequirementsSchema.optional(), property_list: PropertyListReferenceSchema.optional(), - property_list_exclude: PropertyListReferenceSchema.optional(), - collection_list: CollectionListReferenceSchema.optional(), - collection_list_exclude: CollectionListReferenceSchema.optional(), - placement_selection: PlacementSelectionSchema.optional(), - collection_selection: CollectionSelectionSchema.optional(), - age_restriction: z.object({ - min: z.number().int().gte(13).lte(99), - verification_required: z.boolean().optional(), - accepted_methods: z.array(AgeVerificationMethodSchema).optional() - }).passthrough().optional(), - device_platform: z.array(DevicePlatformSchema).optional(), - device_platform_exclude: z.array(DevicePlatformSchema).optional(), - device_type: z.array(DeviceTypeSchema).optional(), - device_type_exclude: z.array(DeviceTypeSchema).optional(), - browser: z.array(BrowserFamilySchema).optional(), - browser_exclude: z.array(BrowserFamilySchema).optional(), - store_catchments: z.array(z.object({ - catalog_id: z.string(), - store_ids: z.array(z.string()).optional(), - catchment_ids: z.array(z.string()).optional() - }).passthrough()).optional(), - geo_proximity: z.array(z.union([z.object({}).passthrough(), z.object({}).passthrough(), z.object({}).passthrough()])).optional(), - language: z.array(LanguageTagSchema).optional(), - keyword_targets: z.array(z.object({ - keyword: z.string().min(1), - match_type: MatchTypeSchema, - bid_price: z.number().gte(0).optional() - }).passthrough()).optional(), - negative_keywords: z.array(z.object({ - keyword: z.string().min(1), - match_type: MatchTypeSchema - }).passthrough()).optional() -}).passthrough()); - -export const ProductDiscoveryTargetingResolutionSchema = z.object({ - brief_targeting: TargetingOverlaySchema, + fields: z.array(z.union([z.union([z.literal("product_id"), z.literal("name"), z.literal("description"), z.literal("publisher_properties"), z.literal("channels"), z.literal("video_placement_types"), z.literal("audio_distribution_types"), z.literal("sponsored_placement_types"), z.literal("social_placement_surfaces"), z.literal("format_options"), z.literal("placements"), z.literal("delivery_type"), z.literal("exclusivity"), z.literal("pricing_options"), z.literal("forecast"), z.literal("reporting_capabilities"), z.literal("measurement_terms"), z.literal("performance_standards"), z.literal("catalog_types"), z.literal("signal_targeting_allowed"), z.literal("signal_targeting_rules"), z.literal("demographic_targeting"), z.literal("overlay_support"), z.literal("media_buy_support"), z.literal("audience_evidence"), z.literal("audience_evidence_selections"), z.literal("max_optimization_goals"), z.literal("catalog_match"), z.literal("list_applications"), z.literal("brief_relevance"), z.literal("acceptance_policy_profile_ids"), z.literal("identity"), z.literal("expires_at"), z.literal("allowed_actions")]), z.union([z.literal("format_ids"), z.literal("outcome_measurement"), z.literal("delivery_measurement"), z.literal("creative_policy"), z.literal("metric_optimization"), z.literal("conversion_tracking"), z.literal("data_provider_signals"), z.literal("included_signals"), z.literal("signal_targeting_options"), z.literal("overlay_support"), z.literal("media_buy_support"), z.literal("targeting_resolution"), z.literal("collections"), z.literal("collection_targeting_allowed"), z.literal("installments"), z.literal("is_custom"), z.literal("product_card"), z.literal("product_card_detailed"), z.literal("enforced_policies"), z.literal("trusted_match")])])).optional(), + time_budget: DurationSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + pagination: PaginationRequestSchema.optional(), + if_wholesale_feed_version: z.string().optional(), + if_pricing_version: z.string().optional(), + context: ContextObjectSchema.optional(), + required_policies: z.array(z.string()).optional(), ext: ExtensionObjectSchema.optional() }).passthrough(); -export const ProductDiscoveryCriteriaSchema = z.object({ - product_ids: z.array(z.string()).optional(), - offer_filters: ProductOfferFiltersSchema.optional(), - targeting_overlay: TargetingOverlaySchema.optional(), - required_overlay_support: TargetingOverlayRequirementsSchema.optional(), - outcome_target: OutcomeTargetSchema.optional(), - acceptance_context: AcceptanceContextSchema.optional(), - catalog: CatalogSelectionSchema.optional(), - policy_ids: z.array(z.string()).optional(), - ext: z.object({}).passthrough().optional() +// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. +export const GetProductsResponseSchema: z.ZodObject<{ [K in keyof GetProductsResponse]-?: undefined extends GetProductsResponse[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, GetProductsResponse & Record> = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + products: z.array(ProductSchema).optional(), + targeting_resolution: ProductDiscoveryTargetingResolutionSchema.optional(), + extensions: z.record(z.string(), z.object({ + extends: z.string(), + fields: z.object({}).passthrough(), + version: z.string().optional(), + description: z.string().optional() + }).passthrough()).optional(), + proposals: z.array(ProposalSchema).optional(), + errors: z.array(ErrorSchema).optional(), + reason: z.string().min(1).max(2000).optional(), + suggestions: z.array(z.string()).max(20).optional(), + property_list_applied: z.boolean().optional(), + catalog_applied: z.boolean().optional(), + refinement_applied: z.array(z.union([z.object({ + scope: z.literal("request"), + status: z.union([z.literal("applied"), z.literal("partial"), z.literal("unable")]), + notes: z.string().optional() + }).passthrough(), z.object({ + scope: z.literal("product"), + product_id: z.string(), + status: z.union([z.literal("applied"), z.literal("partial"), z.literal("unable")]), + notes: z.string().optional() + }).passthrough(), z.object({ + scope: z.literal("proposal"), + proposal_id: z.string().max(255), + status: z.union([z.literal("applied"), z.literal("partial"), z.literal("unable")]), + notes: z.string().optional() + }).passthrough()])).optional(), + incomplete: z.array(z.object({ + scope: z.union([z.literal("products"), z.literal("pricing"), z.literal("forecast"), z.literal("proposals"), z.literal("wholesale_feed")]), + description: z.string(), + estimated_wait: DurationSchema.optional() + }).passthrough()).optional(), + filter_diagnostics: z.object({ + semantics: z.union([z.literal("only"), z.literal("any"), z.literal("approximate")]).optional(), + total_candidates: z.int().min(0).optional(), + excluded_by: z.record(z.string(), z.object({ + count: z.int().min(0), + values: z.array(z.union([z.string(), z.object({}).passthrough()])).optional(), + notes: z.string().optional() + }).passthrough()).optional() + }).passthrough().optional(), + pagination: PaginationResponseSchema.optional(), + wholesale_feed_version: z.string().optional(), + pricing_version: z.string().optional(), + cache_scope: z.union([z.literal("public"), z.literal("account")]).optional(), + unchanged: z.literal(true).optional(), + sandbox: z.boolean().optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const ListProductsRequestSchema = z.object({ + adcp_version: z.string().optional(), + adcp_major_version: z.number().optional(), + idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/).optional(), + context_id: z.string().min(1).optional(), + context: ContextObjectSchema.optional(), + governance_context: z.string().min(1).max(4096).optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + account: CanonicalAccountReferenceSchema.optional(), + brand: BrandKeySchema.optional(), + criteria: ProductDiscoveryCriteriaSchema.optional(), + fields: ProductResponseFieldsSchema.optional(), + cursor: z.string().min(1).optional(), + max_results: z.int().min(1).max(100).optional(), + if_feed_version: z.string().optional(), + if_pricing_version: z.string().optional() }).passthrough(); export const CanonicalDeliveryForecastSchema = z.object({ @@ -14379,57 +14897,41 @@ export const RequestProposalsRequestSchema = z.object({ }).passthrough()).optional() }).passthrough(); -export const ProductPurchaseSchema = z.object({ - product_id: z.string().min(1), - pricing_option_id: z.string().min(1), - pricing: CanonicalPricingOptionSchema.optional(), - format_option_refs: z.array(FormatOptionReferenceSchema).optional(), - catalog_ids: z.array(z.string()).optional(), - budget: z.number().gte(0).optional(), +export const CommercialTermsSchema = z.object({ + source_feed_version: z.string().min(1).optional(), + source_pricing_version: z.string().min(1).optional(), + brand: BrandKeySchema, + advertiser_industry: AdvertiserIndustrySchema.optional(), + purchases: z.array(ProductPurchaseSchema.merge(z.object({}).passthrough())), + start_time: StartTimingSchema, + end_time: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time"), + total_budget: z.object({ + amount: z.number().gte(0), + currency: z.string().regex(new RegExp("^[A-Z]{3}$")) + }).passthrough().optional(), daily_budget_cap: z.number().gte(0).optional(), - min_spend_target: z.number().gte(0).optional(), - impressions: z.number().gte(0).optional(), - start_time: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - end_time: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + frequency_cap: MediaBuyFrequencyCapSchema.optional(), + budget_cap_timezone: z.string().min(1).optional(), + budget_allocation: CanonicalBudgetAllocationSchema.optional(), pacing: PacingSchema.optional(), bidding: BiddingPolicySchema.optional(), - targeting_overlay: TargetingOverlaySchema.optional(), - optimization_goals: z.array(CanonicalOptimizationGoalSchema).optional(), - audience_evidence_requirements: ProductAudienceEvidenceRequirementsSchema.optional(), - audience_evidence_pins: z.array(AudienceEvidencePinSchema).optional(), + invoice_recipient: BusinessEntitySchema.optional(), + purchase_order_ref: z.string().min(1).max(255).optional(), agency_estimate_number: z.string().max(100).optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional(), - measurement_terms: CanonicalMeasurementTermsSchema.optional(), - performance_standards: z.array(CanonicalPerformanceStandardSchema).optional() -}).passthrough(); - -export const ProposalRefinementSchema = z.object({ - proposal_id: z.string().min(1), - action: z.union([z.literal("revise"), z.literal("finalize")]).optional(), - change_kind: z.union([z.literal("amendment"), z.literal("cancellation")]).optional(), - constraints: z.object({ - total_budget: ProposalBudgetConstraintSchema.optional(), - cpm: z.object({ - max: z.number().gt(0), + reporting_commitments: z.array(z.object({ + purchase_index: z.number().int().gte(0), + metrics: z.array(CanonicalReportingCommitmentSchema) + }).passthrough()).optional(), + cancellation_terms: z.object({ + effective_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time"), + fee: z.object({ + amount: z.number().gte(0), currency: z.string().regex(new RegExp("^[A-Z]{3}$")) }).passthrough().optional(), - impressions: z.object({ - min: z.number().gt(0) - }).passthrough().optional(), - flight: z.object({}).passthrough().optional() - }).passthrough().optional(), - product_changes: ProductChangeMapSchema.optional(), - alternatives: z.object({ - count: z.number().int().gte(2).lte(10) + reason: z.string().min(1).max(500).optional() }).passthrough().optional(), - ask: z.string().min(1).optional(), - criteria: ProductDiscoveryCriteriaSchema.optional() -}).passthrough().and(z.union([z.object({ - action: z.literal("finalize") - }).passthrough(), z.union([z.object({}).passthrough(), z.object({ - change_kind: z.literal("cancellation") - }).passthrough()])])); + change_terms: z.array(MediaBuyChangeTermSchema).optional() +}).passthrough(); export const RefineProposalsRequestSchema = z.object({ adcp_version: z.string().optional(), @@ -14442,2617 +14944,74 @@ export const RefineProposalsRequestSchema = z.object({ refinements: z.array(ProposalRefinementSchema).max(25) }).passthrough(); -export const CanonicalProductSchema = z.object({}).passthrough().merge(z.object({ - product_id: z.string().min(1), - name: z.string().min(1), - description: z.string().optional(), - publisher_properties: z.array(PublisherPropertySelectorSchema.and(z.object({}).passthrough())).optional(), - channels: z.array(MediaChannelSchema).optional(), - video_placement_types: z.array(VideoPlacementTypeSchema).optional(), - audio_distribution_types: z.array(AudioDistributionTypeSchema).optional(), - sponsored_placement_types: z.array(SponsoredPlacementTypeSchema).optional(), - social_placement_surfaces: z.array(SocialPlacementSurfaceSchema).optional(), - format_options: z.array(CanonicalFormatOptionSchema).optional(), - placements: z.array(CanonicalProductPlacementSchema).optional(), - delivery_type: DeliveryTypeSchema.optional(), - exclusivity: ExclusivitySchema.optional(), - pricing_options: z.array(CanonicalPricingOptionSchema).optional(), - forecast: CanonicalDeliveryForecastSchema.optional(), - reporting_capabilities: CanonicalReportingCapabilitiesSchema.optional(), - measurement_terms: CanonicalMeasurementTermsSchema.optional(), - performance_standards: z.array(CanonicalPerformanceStandardSchema).optional(), - catalog_types: z.array(CatalogTypeSchema).optional(), - signal_targeting_allowed: z.boolean().optional(), - signal_targeting_rules: SignalTargetingRulesSchema.optional(), - demographic_targeting: DemographicTargetingCapabilitySchema.optional(), - overlay_support: TargetingOverlaySupportSchema.optional(), - identity: ProductIdentitySchema.optional(), - audience_evidence: z.array(CanonicalAudienceEvidenceSchema).optional(), - audience_evidence_selections: z.array(CanonicalAudienceEvidenceSelectionSchema).optional(), - max_optimization_goals: z.number().int().gte(0).optional(), - catalog_match: z.object({ - matched_gtins: z.array(z.string()).optional(), - matched_ids: z.array(z.string()).optional(), - matched_count: z.number().int().gte(0).optional(), - submitted_count: z.number().int().gte(0) - }).passthrough().optional(), - list_applications: z.array(InventoryListApplicationSchema).optional(), - brief_relevance: z.string().optional(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - allowed_actions: z.array(CanonicalProductActionSchema).optional(), - acceptance_policy_profile_ids: AcceptancePolicyProfileIDsSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough()); - -export const BuyProductsRequestSchema = z.object({ - adcp_version: z.string().optional(), - adcp_major_version: z.number().optional(), - idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/), - account: CanonicalAccountReferenceSchema, - brand: BrandKeySchema.optional(), - advertiser_industry: AdvertiserIndustrySchema.optional(), - feed_version: z.string().min(1), - pricing_version: z.string().min(1).optional(), - purchases: z.array(ProductPurchaseSchema), - total_budget: z.object({ - amount: z.number().min(0), - currency: z.string().regex(/^[A-Z]{3}$/) - }).passthrough().optional(), - daily_budget_cap: z.number().min(0).optional(), - budget_cap_timezone: z.string().min(1).optional(), - budget_allocation: CanonicalBudgetAllocationSchema.optional(), - start_time: StartTimingSchema, - end_time: z.iso.datetime(), - pacing: PacingSchema.optional(), - bidding: BiddingPolicySchema.optional(), - paused: z.boolean().optional(), - purchase_order_ref: z.string().min(1).max(255).optional(), - agency_estimate_number: z.string().max(100).optional(), - invoice_recipient: BusinessEntitySchema.optional(), - governance_context: z.string().min(1).max(4096).optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - reporting_webhook: ReportingWebhookSchema.optional(), - opportunity: OpportunityContextSchema.and(z.object({ - status: z.literal("closed").optional() - }).passthrough()).optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const PackageControlSchema = z.object({}).passthrough().merge(z.object({ - package_id: z.string().min(1), - budget: z.number().gte(0).optional().nullable(), - daily_budget_cap: z.number().gte(0).optional().nullable(), - min_spend_target: z.number().gte(0).optional().nullable(), - impressions: z.number().gte(0).optional(), - pacing: PacingSchema.optional(), - bidding: BiddingPolicySchema.optional().nullable(), - paused: z.boolean().optional(), - canceled: z.literal(true).optional(), - cancellation_reason: z.string().min(1).max(500).optional(), - targeting_overlay: TargetingOverlaySchema.optional(), - catalog_ids: z.array(z.string()).optional(), - keyword_targets_add: z.array(KeywordTargetSchema).optional(), - keyword_targets_remove: z.array(KeywordTargetSchema).optional(), - negative_keywords_add: z.array(KeywordTargetSchema).optional(), - negative_keywords_remove: z.array(KeywordTargetSchema).optional(), - optimization_goals: z.array(CanonicalOptimizationGoalSchema).optional() -}).passthrough()); - -export const ControlMediaBuyRequestSchema = z.object({ - adcp_version: z.string().optional(), - adcp_major_version: z.number().optional(), - idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/), - account: CanonicalAccountReferenceSchema, - media_buy_id: z.string().min(1), - revision: z.int().min(1), - name: z.string().min(1).max(255).regex(/\S/).optional(), - paused: z.boolean().optional(), - canceled: z.literal(true).optional(), - cancellation_reason: z.string().min(1).max(500).optional(), - total_budget: z.object({ - amount: z.number().min(0), - currency: z.string().regex(/^[A-Z]{3}$/) - }).passthrough().optional(), - daily_budget_cap: z.number().min(0).optional().nullable(), - budget_cap_timezone: z.string().min(1).optional().nullable(), - budget_allocation: CanonicalBudgetAllocationSchema.optional(), - pacing: PacingSchema.optional(), - bidding: BiddingPolicySchema.optional().nullable(), - packages: z.array(PackageControlSchema).optional(), - reporting_webhook: ReportingWebhookSchema.optional(), - governance_context: z.string().min(1).max(4096).optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - // @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. -export const ListCreativeFormatsResponseSchema: z.ZodObject<{ [K in keyof ListCreativeFormatsResponse]-?: undefined extends ListCreativeFormatsResponse[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, ListCreativeFormatsResponse & Record> = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - formats: z.array(FormatSchema), - source: z.union([z.literal("publisher"), z.literal("aao_mirror"), z.literal("agent_derived")]).optional(), - creative_agents: z.array(z.object({ - agent_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI"), - agent_name: z.string().optional(), - capabilities: z.array(CreativeAgentCapabilitySchema).optional() - }).passthrough()).optional(), - errors: z.array(ErrorSchema).optional(), - pagination: PaginationResponseSchema.optional(), - sandbox: z.boolean().optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const CreativeAssetSchema = z.object({}).passthrough().merge(z.object({ - creative_id: z.string(), - name: z.string(), - format_id: FormatReferenceStructuredObjectSchema.optional(), - format_kind: CanonicalFormatKindSchema.optional(), - format_option_ref: FormatOptionReferenceSchema.optional(), - representation_selection: RepresentationSelectionSchema.optional(), - assets: CreativeAssetsRuntimeSchema, - component_assets: z.record(z.string(), CreativeAssetsSchema).optional(), - inputs: z.array(z.object({ - name: z.string(), - macros: z.record(z.string(), z.string()).optional(), - context_description: z.string().optional() - }).passthrough()).optional(), - tags: z.array(z.string()).optional(), - status: CreativeStatusSchema.optional(), - weight: z.number().gte(0).lte(100).optional(), - placement_refs: z.array(PlacementReferenceSchema).optional(), - placement_ids: z.array(z.string()).optional(), - industry_identifiers: z.array(IndustryIdentifierSchema).optional(), - provenance: ProvenanceSchema.optional(), - rights: z.array(RightsConstraintSchema).optional() -}).passthrough()).superRefine((value, ctx) => { - const hasFormatId = value.format_id !== undefined; - const hasFormatKind = value.format_kind !== undefined; - if (hasFormatId === hasFormatKind) { - ctx.addIssue({ - code: "custom", - path: [], - message: "creative identity requires exactly one of format_id or format_kind" - }); +export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposal]-?: undefined extends CanonicalProposal[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, CanonicalProposal & Record> = (() => { + const objectSchema = z.object({ "proposal_id": z.string().min(1).max(255), "proposal_kind": z.enum(["new_media_buy","media_buy_update","media_buy_cancellation"]), "parent_proposal_id": z.string().min(1).max(255).describe("Immediate predecessor this snapshot was forked from. Every proposal produced by refine_proposals carries it, equal to the request's source proposal_id, so negotiation lineage is reconstructible from proposals alone.").optional(), "media_buy_id": z.string().min(1).optional(), "opportunity_id": z.string().regex(new RegExp("^[A-Za-z0-9_.:-]{1,255}$")).min(1).max(255).describe("Buyer planning cycle associated with this proposal. Revisions inherit it; it does not participate in proposal identity.").optional(), "base_media_buy_revision": z.number().int().gte(1).optional(), "proposal_status": z.enum(["draft","committed","accepted"]).describe("draft is indicative and unreserved; committed has firm terms with inventory reserved until expires_at; accepted is the historical snapshot attached to a MediaBuy."), "accepted_at": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "expires_at": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "name": z.string().min(1).max(500), "description": z.string().max(2000).optional(), "brief_alignment": z.string().max(2000).optional(), "commercial_terms": z.object({ "source_feed_version": z.string().min(1).describe("Wholesale product feed version against which direct published offers were accepted. Omitted when the seller authored terms outside a wholesale snapshot.").optional(), "source_pricing_version": z.string().min(1).describe("Pricing-layer version against which published rates were accepted.").optional(), "brand": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery."), "advertiser_industry": z.enum(["automotive","automotive.electric_vehicles","automotive.parts_accessories","automotive.luxury","beauty_cosmetics","beauty_cosmetics.skincare","beauty_cosmetics.fragrance","beauty_cosmetics.haircare","cannabis","cpg","cpg.personal_care","cpg.household","dating","education","education.higher_education","education.online_learning","education.k12","energy_utilities","energy_utilities.renewable","fashion_apparel","fashion_apparel.luxury","fashion_apparel.sportswear","finance","finance.banking","finance.insurance","finance.investment","finance.cryptocurrency","food_beverage","food_beverage.alcohol","food_beverage.restaurants","food_beverage.packaged_goods","gambling_betting","gambling_betting.sports_betting","gambling_betting.casino","gaming","gaming.mobile","gaming.console_pc","gaming.esports","government_nonprofit","government_nonprofit.political","government_nonprofit.charity","healthcare","healthcare.pharmaceutical","healthcare.medical_devices","healthcare.wellness","home_garden","home_garden.furniture","home_garden.home_improvement","media_entertainment","media_entertainment.podcasts","media_entertainment.music","media_entertainment.film_tv","media_entertainment.publishing","media_entertainment.live_events","pets","professional_services","professional_services.legal","professional_services.consulting","real_estate","real_estate.residential","real_estate.commercial","recruitment_hr","retail","retail.ecommerce","retail.department_stores","sports_fitness","sports_fitness.equipment","sports_fitness.teams_leagues","technology","technology.software","technology.hardware","technology.ai_ml","telecom","telecom.mobile_carriers","telecom.internet_providers","transportation_logistics","travel_hospitality","travel_hospitality.airlines","travel_hospitality.hotels","travel_hospitality.cruise","travel_hospitality.tourism"]).describe("Standardized advertiser industry classification. Top-level categories classify the advertiser's primary business. Dot-notation subcategories (e.g., 'media_entertainment.podcasts') provide platform-specific precision where needed. Sellers map these to platform-native codes (Spotify ADV categories, LinkedIn industry IDs, IAB Content Taxonomy, etc.). Sellers MUST accept unknown values gracefully — treat unrecognized values as the parent category (strip the subcategory) or as uncategorized. This ensures forward compatibility as the taxonomy evolves.").optional(), "purchases": z.array(z.intersection(z.object({ "product_id": z.string().min(1), "pricing_option_id": z.string().min(1), "pricing": z.object({ "pricing_option_id": z.string().min(1), "pricing_model": z.enum(["cpm","vcpm","cpc","cpcv","cpv","cpp","cpa","revenue_share","flat_rate","time"]), "currency": z.string().regex(new RegExp("^[A-Z]{3}$")), "fixed_price": z.number().gte(0).optional(), "floor_price": z.number().gte(0).optional(), "price_guidance": z.object({ "p25": z.number().gte(0).describe("25th percentile of recent winning bids").optional(), "p50": z.number().gte(0).describe("Median of recent winning bids").optional(), "p75": z.number().gte(0).describe("75th percentile of recent winning bids").optional(), "p90": z.number().gte(0).describe("90th percentile of recent winning bids").optional() }).catchall(z.any()).describe("Pricing guidance for auction-based bidding. Helps buyers calibrate bids with historical percentiles.").optional(), "min_spend_per_package": z.number().gte(0).optional(), "price_breakdown": z.object({ "list_price": z.number().gt(0).describe("Rate card or base price before any adjustments. The starting point from which fixed_price is derived by applying fee and discount adjustments sequentially."), "adjustments": z.array(z.object({ "kind": z.enum(["fee","discount","commission","settlement"]).describe("Categorizes how a price adjustment affects the transaction"), "name": z.string().max(64).describe("Specific adjustment name. Use well-known values where applicable for interoperability."), "rate": z.number().gt(0).lt(1).describe("Adjustment as a decimal proportion (e.g., 0.15 for 15%). Always positive — kind determines the economic effect. Mutually exclusive with amount.").optional(), "amount": z.number().gt(0).describe("Adjustment as a fixed monetary amount in the pricing option's currency. Always positive — kind determines the economic effect. Mutually exclusive with rate.").optional(), "description": z.string().max(256).describe("Human-readable description of this adjustment (e.g., 'Malstaffel 12x', '2% Skonto 10 Tage')").optional(), "beneficiary": z.string().max(256).describe("Identifies who receives this adjustment's value. For commissions, the intermediary (e.g., a sellers.json domain, an AdCP account ID, or a human-readable party name). Optional but recommended for multi-intermediary transparency.").optional() }).catchall(z.any()).and(z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "rate": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "amount": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]; + const { errors, failed } = schemas.reduce<{ + errors: z.core.$ZodIssue[]; + failed: number; + }>( + ({ errors, failed }, schema) => + ((result) => + result.error + ? { + errors: [...errors, ...result.error.issues], + failed: failed + 1, + } + : { errors, failed })( + schema.safeParse(x), + ), + { errors: [], failed: 0 }, + ); + const passed = schemas.length - failed; + if (passed !== 1) { + ctx.addIssue(errors.length ? { + path: [], + code: "invalid_union", + errors: [errors], + message: "Invalid input: Should pass single schema. Passed " + passed, + } : { + path: [], + code: "custom", + errors: [errors], + message: "Invalid input: Should pass single schema. Passed " + passed, + }); } - if ("capability_id" in value || "capability_ref" in value) { - ctx.addIssue({ - code: "custom", - path: [], - message: "creative identity does not allow capability_id or capability_ref" - }); + }))).min(1).max(20).describe("Ordered list of price adjustments. Fee and discount adjustments walk list_price to fixed_price — fees increase the running price, discounts reduce it. Commission and settlement adjustments are disclosed for transparency but do not affect the buyer's committed price.") }).catchall(z.any()).describe("Breaks down the composition of fixed_price from a list (rate card) price through adjustments. Adjustments fall into four kinds: fees (increase buyer price), discounts (reduce buyer price), commissions (revenue splits that don't affect buyer price), and settlement terms (applied at invoicing). The invariant is: list_price with all fee and discount adjustments applied sequentially equals fixed_price. Fees increase the running price; discounts reduce it. This invariant applies only when fixed_price is present on the parent object; on auction-based packages the breakdown is informational only. All monetary values are rounded to currency precision at each step. Budgets are always denominated at the fixed_price level, inclusive of commissions.").optional(), "eligible_adjustments": z.array(z.enum(["fee","discount","commission","settlement"]).describe("Categorizes how a price adjustment affects the transaction")).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").optional(), "parameters": z.record(z.string(), z.any()).optional(), "event_type": z.enum(["page_view","view_content","select_content","select_item","search","share","add_to_cart","remove_from_cart","viewed_cart","add_to_wishlist","initiate_checkout","add_payment_info","purchase","refund","lead","qualify_lead","close_convert_lead","disqualify_lead","complete_registration","subscribe","follow","content_view","watch_milestone","start_trial","app_install","app_launch","contact","schedule","donate","submit_application","custom"]).describe("Standard marketing event types for event logging, aligned with IAB ECAPI").optional(), "custom_event_name": z.string().min(1).optional(), "event_source_id": z.string().min(1).optional(), "commission_rate": z.number().gt(0).lte(1).optional(), "commission_basis_description": z.string().min(1).max(1000).optional() }).passthrough().and(z.intersection(z.intersection(z.any().refine((value) => !z.object({ "fixed_price": z.any().refine((value) => value !== undefined, "Required"), "floor_price": z.any().refine((value) => value !== undefined, "Required") }).passthrough().safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.union([z.any().refine((value) => !z.object({ "pricing_model": z.literal("cpa") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "pricing_model": z.literal("cpa") }), z.object({ "event_type": z.any().refine((value) => value !== undefined, "Required"), "fixed_price": z.any().refine((value) => value !== undefined, "Required") }).passthrough())])), z.intersection(z.union([z.any().refine((value) => !z.object({ "pricing_model": z.literal("revenue_share") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "pricing_model": z.literal("revenue_share") }), z.object({ "event_type": z.any().refine((value) => value !== undefined, "Required"), "event_source_id": z.any().refine((value) => value !== undefined, "Required"), "commission_rate": z.any().refine((value) => value !== undefined, "Required"), "commission_basis_description": z.any().refine((value) => value !== undefined, "Required") }).passthrough())]), z.intersection(z.union([z.any().refine((value) => !z.object({ "pricing_model": z.enum(["cpv","cpp","time"]) }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "pricing_model": z.enum(["cpv","cpp","time"]) }), z.object({ "parameters": z.any().refine((value) => value !== undefined, "Required") }).passthrough())]), z.union([z.any().refine((value) => !z.object({ "event_type": z.literal("custom") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "event_type": z.literal("custom") }), z.object({ "custom_event_name": z.any().refine((value) => value !== undefined, "Required") }).passthrough())]))))).describe("Resolved selected pricing terms. Optional on buy_products input, where pricing_option_id plus the versioned feed identifies the offer; required inside accepted commercial_terms. Its pricing_option_id MUST match the sibling field.").optional(), "format_option_refs": z.array(z.record(z.string(), z.any()).and(z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "scope": z.literal("publisher").describe("Reference resolves against the named publisher's adagents.json top-level `formats[]` catalog."), "publisher_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Publisher domain where the adagents.json declaring this format option is hosted."), "format_option_id": z.string().describe("Stable format option ID from the publisher's adagents.json top-level `formats[]`, matching a publisher-catalog-backed entry in the target product's `format_options[]`.") }).catchall(z.any()).describe("Selects a publisher-catalog-backed product format option by publisher domain and format option ID."), z.object({ "scope": z.literal("product").describe("Reference resolves only against the target product's inline `format_options[]`."), "format_option_id": z.string().describe("Stable format option ID from the target product's inline `format_options[]`."), "publisher_domain": z.never().optional() }).catchall(z.any()).describe("Selects a product-local format option by ID within the enclosing package/product context. This branch deliberately forbids `publisher_domain` (`publisher_domain: false` in the schema) because product-local references are namespaced by the enclosing product only; include `scope: \"publisher\"` when the selector must cross into a publisher catalog.")]; + const { errors, failed } = schemas.reduce<{ + errors: z.core.$ZodIssue[]; + failed: number; + }>( + ({ errors, failed }, schema) => + ((result) => + result.error + ? { + errors: [...errors, ...result.error.issues], + failed: failed + 1, + } + : { errors, failed })( + schema.safeParse(x), + ), + { errors: [], failed: 0 }, + ); + const passed = schemas.length - failed; + if (passed !== 1) { + ctx.addIssue(errors.length ? { + path: [], + code: "invalid_union", + errors: [errors], + message: "Invalid input: Should pass single schema. Passed " + passed, + } : { + path: [], + code: "custom", + errors: [errors], + message: "Invalid input: Should pass single schema. Passed " + passed, + }); } -}); - -// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. -export const PackageRequestSchema: z.ZodObject<{ [K in keyof PackageRequest]-?: undefined extends PackageRequest[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, PackageRequest & Record> = AdCPVersionEnvelopeSchema.merge(z.object({}).passthrough()).merge(z.object({ - product_id: z.string(), - format_ids: z.array(FormatReferenceStructuredObjectSchema).optional(), - format_option_refs: z.array(FormatOptionReferenceSchema).optional(), - format_kind: CanonicalFormatKindSchema.optional(), - params: z.object({}).passthrough().optional(), - budget: z.number().gte(0).optional(), - min_spend_target: z.number().gte(0).optional(), - pacing: PacingSchema.optional(), - pricing_option_id: z.string(), - bid_price: z.number().gte(0).optional(), - bidding: BiddingPolicySchema.optional(), - impressions: z.number().gte(0).optional(), - daily_budget_cap: z.number().gte(0).optional(), - start_time: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - end_time: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - paused: z.boolean().optional(), - catalogs: z.array(CatalogSchema).optional(), - optimization_goals: z.array(OptimizationGoalSchema).optional(), - targeting_overlay: TargetingOverlaySchema.optional(), - audience_evidence_requirements: AudienceEvidenceRequirementsSchema.optional(), - audience_evidence_pins: z.array(AudienceEvidencePinSchema).optional(), - measurement_terms: MeasurementTermsSchema.optional(), - performance_standards: z.array(PerformanceStandardSchema).optional(), - committed_metrics: z.array(z.union([z.object({ - scope: z.literal("standard"), - metric_id: AvailableMetricSchema, - qualifier: z.object({ - viewability_standard: ViewabilityStandardSchema.optional(), - completion_source: CompletionSourceSchema.optional(), - attribution_methodology: AttributionMethodologySchema.optional(), - attribution_window: DurationSchema.optional(), - lift_dimension: LiftDimensionSchema.optional() - }).passthrough().optional() - }).passthrough(), z.object({ - scope: z.literal("vendor"), - vendor: BrandReferenceSchema, - metric_id: VendorMetricIDSchema, - methodology_version: z.string().optional(), - qualifier: z.object({ - viewability_standard: ViewabilityStandardSchema.optional(), - completion_source: CompletionSourceSchema.optional(), - attribution_methodology: AttributionMethodologySchema.optional(), - attribution_window: DurationSchema.optional(), - lift_dimension: LiftDimensionSchema.optional() - }).passthrough().optional() - }).passthrough()])).optional(), - creative_assignments: z.array(CreativeAssignmentSchema).optional(), - creatives: z.array(CreativeAssetSchema.and(z.object({}).passthrough())).max(100).optional(), - agency_estimate_number: z.string().max(100).optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough()); - -export const ReportingDeliveryConfigurationSchema = z.object({}).passthrough().merge(z.object({}).passthrough()).merge(z.object({}).passthrough()).merge(z.object({ - delivery_config_id: z.string().min(1).max(64).regex(new RegExp("^[A-Za-z0-9_.:-]{1,64}$")), - delivery_config_version: z.number().int().gte(1), - offering_id: z.string().min(1).max(128).regex(new RegExp("^[A-Za-z0-9_.:-]{1,128}$")), - active: z.boolean(), - feed_purpose: ReportingFeedPurposeSchema, - report_definition_id: z.string().min(1).max(255).regex(new RegExp("^[A-Za-z0-9_.:-]{1,255}$")), - reporting_profile: z.string().min(1).max(128).regex(new RegExp("^[A-Za-z0-9_.:-]{1,128}$")), - scope: z.object({ - all_media_buys: z.literal(true).optional(), - media_buy_ids: z.array(ReportingMediaBuyIDSchema).optional() - }).passthrough(), - coverage_requirement: z.union([z.literal("full"), z.literal("allow_partial")]), - required_finality: ReportingFinalitySchema, - reconciliation_mode: ReportingReconciliationModeSchema, - schedule: ReportingScheduleSchema, - method: ReportingDeliveryMethodSchema.optional(), - revocation_effective_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() -}).passthrough()); - -// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. -export const PackageSchema: z.ZodObject<{ [K in keyof Package]-?: undefined extends Package[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, Package & Record> = z.object({}).passthrough().merge(z.object({ - package_id: z.string(), - product_id: z.string().optional(), - audience_evidence_selections: z.array(AudienceEvidenceSelectionSchema).optional(), - budget: z.number().gte(0).optional(), - min_spend_target: z.number().gte(0).optional(), - daily_budget_cap: z.number().gte(0).optional(), - pacing: PacingSchema.optional(), - pricing_option_id: z.string().optional(), - bid_price: z.number().gte(0).optional(), - bidding: BiddingPolicySchema.optional(), - price_breakdown: PriceBreakdownSchema.optional(), - impressions: z.number().gte(0).optional(), - catalogs: z.array(CatalogSchema).optional(), - format_ids: z.array(FormatReferenceStructuredObjectSchema).optional(), - format_option_refs: z.array(FormatOptionReferenceSchema).optional(), - format_kind: CanonicalFormatKindSchema.optional(), - params: z.object({}).passthrough().optional(), - targeting_overlay: TargetingOverlaySchema.optional(), - targeting_resolution: PackageTargetingResolutionSchema.optional(), - measurement_terms: MeasurementTermsSchema.optional(), - performance_standards: z.array(PerformanceStandardSchema).optional(), - committed_metrics: z.array(CommittedMetricSchema).optional(), - creative_assignments: z.array(CreativeAssignmentSchema).optional(), - formats_to_provide: z.array(PackageFormatSnapshotSchema).optional(), - formats_pending: z.array(PackageFormatSnapshotSchema).optional(), - format_ids_to_provide: z.array(FormatReferenceStructuredObjectSchema).optional(), - format_ids_pending: z.array(FormatReferenceStructuredObjectSchema).optional(), - optimization_goals: z.array(OptimizationGoalSchema).optional(), - start_time: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - end_time: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - paused: z.boolean().optional(), - canceled: z.boolean().optional(), - cancellation: z.object({ - canceled_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time"), - canceled_by: CanceledBySchema, - reason: z.string().max(500).optional(), - acknowledged_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - agency_estimate_number: z.string().max(100).optional(), - creative_deadline: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough()); - -export const ReportingDeliveryConfigurationStateSchema = z.object({}).passthrough().merge(z.object({}).passthrough()).merge(z.object({}).passthrough()).merge(z.object({ - configuration: ReportingDeliveryConfigurationSchema, - state: ReportingDeliveryConfigurationLifecycleStateSchema, - destination_ref: z.string().min(1).max(255).optional(), - validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - current_coverage: ReportingCoverageSchema.optional(), - setup: z.object({ - action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), - message: z.string().min(1).max(2000), - url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - issues: z.array(ReportingStatusIssueSchema).optional() -}).passthrough()).merge(z.object({ - configuration: ReportingDeliveryConfigurationSchema, - state: ReportingDeliveryConfigurationLifecycleStateSchema, - destination_ref: z.string().min(1).max(255).optional(), - validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - current_coverage: ReportingCoverageSchema.optional(), - setup: z.object({ - action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), - message: z.string().min(1).max(2000), - url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - issues: z.array(ReportingStatusIssueSchema).optional() -}).passthrough()).merge(z.object({ - configuration: ReportingDeliveryConfigurationSchema, - state: ReportingDeliveryConfigurationLifecycleStateSchema, - destination_ref: z.string().min(1).max(255).optional(), - validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - current_coverage: ReportingCoverageSchema.optional(), - setup: z.object({ - action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), - message: z.string().min(1).max(2000), - url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - issues: z.array(ReportingStatusIssueSchema).optional() -}).passthrough()).merge(z.object({ - configuration: ReportingDeliveryConfigurationSchema, - state: ReportingDeliveryConfigurationLifecycleStateSchema, - destination_ref: z.string().min(1).max(255).optional(), - validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - current_coverage: ReportingCoverageSchema.optional(), - setup: z.object({ - action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), - message: z.string().min(1).max(2000), - url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - issues: z.array(ReportingStatusIssueSchema).optional() -}).passthrough()).merge(z.object({ - configuration: ReportingDeliveryConfigurationSchema, - state: ReportingDeliveryConfigurationLifecycleStateSchema, - destination_ref: z.string().min(1).max(255).optional(), - validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - current_coverage: ReportingCoverageSchema.optional(), - setup: z.object({ - action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), - message: z.string().min(1).max(2000), - url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - issues: z.array(ReportingStatusIssueSchema).optional() -}).passthrough()).merge(z.object({ - configuration: ReportingDeliveryConfigurationSchema, - state: ReportingDeliveryConfigurationLifecycleStateSchema, - destination_ref: z.string().min(1).max(255).optional(), - validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - current_coverage: ReportingCoverageSchema.optional(), - setup: z.object({ - action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), - message: z.string().min(1).max(2000), - url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - issues: z.array(ReportingStatusIssueSchema).optional() -}).passthrough()).merge(z.object({ - configuration: ReportingDeliveryConfigurationSchema, - state: ReportingDeliveryConfigurationLifecycleStateSchema, - destination_ref: z.string().min(1).max(255).optional(), - validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - current_coverage: ReportingCoverageSchema.optional(), - setup: z.object({ - action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), - message: z.string().min(1).max(2000), - url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - issues: z.array(ReportingStatusIssueSchema).optional() -}).passthrough()).merge(z.object({ - configuration: ReportingDeliveryConfigurationSchema, - state: ReportingDeliveryConfigurationLifecycleStateSchema, - destination_ref: z.string().min(1).max(255).optional(), - validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - current_coverage: ReportingCoverageSchema.optional(), - setup: z.object({ - action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), - message: z.string().min(1).max(2000), - url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - issues: z.array(ReportingStatusIssueSchema).optional() -}).passthrough()).merge(z.object({ - configuration: ReportingDeliveryConfigurationSchema, - state: ReportingDeliveryConfigurationLifecycleStateSchema, - destination_ref: z.string().min(1).max(255).optional(), - validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - current_coverage: ReportingCoverageSchema.optional(), - setup: z.object({ - action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), - message: z.string().min(1).max(2000), - url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - issues: z.array(ReportingStatusIssueSchema).optional() -}).passthrough()).merge(z.object({ - configuration: ReportingDeliveryConfigurationSchema, - state: ReportingDeliveryConfigurationLifecycleStateSchema, - destination_ref: z.string().min(1).max(255).optional(), - validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - current_coverage: ReportingCoverageSchema.optional(), - setup: z.object({ - action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), - message: z.string().min(1).max(2000), - url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - issues: z.array(ReportingStatusIssueSchema).optional() -}).passthrough()).merge(z.object({ - configuration: ReportingDeliveryConfigurationSchema, - state: ReportingDeliveryConfigurationLifecycleStateSchema, - destination_ref: z.string().min(1).max(255).optional(), - validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - current_coverage: ReportingCoverageSchema.optional(), - setup: z.object({ - action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), - message: z.string().min(1).max(2000), - url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - issues: z.array(ReportingStatusIssueSchema).optional() -}).passthrough()).merge(z.object({ - configuration: ReportingDeliveryConfigurationSchema, - state: ReportingDeliveryConfigurationLifecycleStateSchema, - destination_ref: z.string().min(1).max(255).optional(), - validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - current_coverage: ReportingCoverageSchema.optional(), - setup: z.object({ - action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), - message: z.string().min(1).max(2000), - url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - issues: z.array(ReportingStatusIssueSchema).optional() -}).passthrough()).merge(z.object({ - configuration: ReportingDeliveryConfigurationSchema, - state: ReportingDeliveryConfigurationLifecycleStateSchema, - destination_ref: z.string().min(1).max(255).optional(), - validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - current_coverage: ReportingCoverageSchema.optional(), - setup: z.object({ - action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), - message: z.string().min(1).max(2000), - url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - issues: z.array(ReportingStatusIssueSchema).optional() -}).passthrough()).merge(z.object({ - configuration: ReportingDeliveryConfigurationSchema, - state: ReportingDeliveryConfigurationLifecycleStateSchema, - destination_ref: z.string().min(1).max(255).optional(), - validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - current_coverage: ReportingCoverageSchema.optional(), - setup: z.object({ - action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), - message: z.string().min(1).max(2000), - url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - issues: z.array(ReportingStatusIssueSchema).optional() -}).passthrough()).merge(z.object({ - configuration: ReportingDeliveryConfigurationSchema, - state: ReportingDeliveryConfigurationLifecycleStateSchema, - destination_ref: z.string().min(1).max(255).optional(), - validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - current_coverage: ReportingCoverageSchema.optional(), - setup: z.object({ - action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), - message: z.string().min(1).max(2000), - url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - issues: z.array(ReportingStatusIssueSchema).optional() -}).passthrough()).merge(z.object({ - configuration: ReportingDeliveryConfigurationSchema, - state: ReportingDeliveryConfigurationLifecycleStateSchema, - destination_ref: z.string().min(1).max(255).optional(), - validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - current_coverage: ReportingCoverageSchema.optional(), - setup: z.object({ - action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), - message: z.string().min(1).max(2000), - url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - issues: z.array(ReportingStatusIssueSchema).optional() -}).passthrough()); - -// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. -export const PackageUpdateSchema: z.ZodObject<{ [K in keyof PackageUpdate]-?: undefined extends PackageUpdate[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, PackageUpdate & Record> = z.object({ - package_id: z.string(), - budget: z.number().min(0).optional().nullable(), - min_spend_target: z.number().min(0).optional().nullable(), - pacing: PacingSchema.optional(), - bid_price: z.number().min(0).optional(), - bidding: BiddingPolicySchema.optional().nullable(), - impressions: z.number().min(0).optional(), - daily_budget_cap: z.number().min(0).optional().nullable(), - start_time: z.iso.datetime().optional(), - end_time: z.iso.datetime().optional(), - paused: z.boolean().optional(), - canceled: z.literal(true).optional(), - cancellation_reason: z.string().max(500).optional(), - catalogs: z.array(CatalogSchema).optional(), - optimization_goals: z.array(OptimizationGoalSchema).optional(), - targeting_overlay: TargetingOverlaySchema.optional(), - keyword_targets_add: z.array(z.object({ - keyword: z.string().min(1), - match_type: MatchTypeSchema, - bid_price: z.number().min(0).optional() - }).passthrough()).optional(), - keyword_targets_remove: z.array(z.object({ - keyword: z.string().min(1), - match_type: MatchTypeSchema - }).passthrough()).optional(), - negative_keywords_add: z.array(z.object({ - keyword: z.string().min(1), - match_type: MatchTypeSchema - }).passthrough()).optional(), - negative_keywords_remove: z.array(z.object({ - keyword: z.string().min(1), - match_type: MatchTypeSchema - }).passthrough()).optional(), - creative_assignments: z.array(CreativeAssignmentSchema).optional(), - creatives: z.array(CreativeAssetSchema).max(100).optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const UpdateMediaBuySuccessSchema: z.ZodType = z.object({ - media_buy_id: z.string(), - name: z.string().min(1).max(255).regex(/\S/).optional(), - media_buy_status: MediaBuyStatusSchema.optional(), - revision: z.int().min(1).optional(), - currency: z.string().regex(/^[A-Z]{3}$/).optional(), - total_budget: z.number().min(0).optional(), - daily_budget_cap: z.number().min(0).optional(), - budget_cap_timezone: z.string().optional(), - budget_allocation: BudgetAllocationSchema.optional(), - pacing: PacingSchema.optional(), - bidding: BiddingPolicySchema.optional(), - implementation_date: z.iso.datetime().optional().nullable(), - invoice_recipient: BusinessEntitySchema.optional(), - affected_packages: z.array(PackageSchema).optional(), - valid_actions: z.array(MediaBuyValidActionSchema).optional(), - available_actions: z.array(MediaBuyAvailableActionSchema).optional(), - warnings: z.array(WarningSchema).optional(), - sandbox: z.boolean().optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const AccountSchema = z.object({ - account_id: z.string(), - name: z.string(), - advertiser: z.string().optional(), - billing_proxy: z.string().optional(), - status: AccountStatusSchema, - brand: BrandReferenceSchema.optional(), - operator: z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).optional(), - operator_unit: OperatorUnitSchema.optional(), - revision: z.number().int().gte(1).optional(), - identity_change: AccountIdentityChangeSchema.optional(), - currency: z.string().regex(new RegExp("^[A-Z]{3}$")).optional(), - timezone: z.string().min(1).optional(), - billing: BillingPartySchema.optional(), - billing_entity: BusinessEntitySchema.optional(), - destination_billing_entity: z.object({}).passthrough().optional(), - rate_card: z.string().optional(), - payment_terms: PaymentTermsSchema.optional(), - credit_limit: z.object({ - amount: z.number().gte(0), - currency: z.string().regex(new RegExp("^[A-Z]{3}$")) - }).passthrough().optional(), - setup: z.object({ - url: z.string().optional(), - message: z.string(), - expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() - }).passthrough().optional(), - account_scope: AccountScopeSchema.optional(), - governance_agents: z.tuple([z.object({ - url: z.string() - }).passthrough()]).optional(), - reporting_bucket: z.object({ - protocol: CloudStorageProtocolSchema, - bucket: z.string().min(3).max(63).regex(new RegExp("^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$")), - prefix: z.string().max(512).regex(new RegExp("^[a-zA-Z0-9/_.-]+$")).optional(), - region: z.string().max(64).regex(new RegExp("^[a-z0-9-]+$")).optional(), - format: z.union([z.literal("jsonl"), z.literal("csv"), z.literal("parquet"), z.literal("avro"), z.literal("orc")]).optional(), - compression: z.union([z.literal("gzip"), z.literal("none")]).optional(), - file_retention_days: z.number().int().gte(1), - setup_instructions: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional() - }).passthrough().optional(), - sandbox: z.boolean().optional(), - notification_configs: z.array(NotificationConfigSchema).max(16).optional(), - reporting_delivery_configs: z.array(ReportingDeliveryConfigurationStateSchema).max(16).optional(), - webhook_activity: z.array(WebhookActivityRecordSchema).max(200).optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. -export const PackageStatusSchema: z.ZodObject<{ [K in keyof PackageStatus]-?: undefined extends PackageStatus[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, PackageStatus & Record> = z.object({ - package_id: z.string(), - product_id: z.string().optional(), - budget: z.number().min(0).optional(), - min_spend_target: z.number().min(0).optional(), - daily_budget_cap: z.number().min(0).optional(), - currency: z.string().regex(/^[A-Z]{3}$/).optional(), - bid_price: z.number().min(0).optional(), - bidding: BiddingPolicySchema.optional(), - optimization_goals: z.array(OptimizationGoalSchema).optional(), - format_ids: z.array(FormatReferenceStructuredObjectSchema).optional(), - format_option_refs: z.array(FormatOptionReferenceSchema).optional(), - format_kind: CanonicalFormatKindSchema.optional(), - params: z.object({}).passthrough().optional(), - impressions: z.number().min(0).optional(), - pacing: PacingSchema.optional(), - targeting_overlay: TargetingOverlaySchema.optional(), - targeting_resolution: PackageTargetingResolutionSchema.optional(), - start_time: z.iso.datetime().optional(), - end_time: z.iso.datetime().optional(), - paused: z.boolean().optional(), - canceled: z.boolean().optional(), - cancellation: z.object({ - canceled_at: z.iso.datetime(), - canceled_by: CanceledBySchema, - reason: z.string().max(500).optional() - }).passthrough().optional(), - creative_deadline: z.iso.datetime().optional(), - context: ContextObjectSchema.optional(), - creative_approvals: z.array(z.object({ - creative_id: z.string(), - approval_status: CreativeApprovalStatusSchema.optional(), - rejection_reason: z.string().optional(), - approval_scopes: z.array(ScopedCreativeApprovalSchema).optional(), - indicators: z.array(IndicatorSchema.and(z.object({ - type: z.union([z.literal("creative_fatigue"), z.literal("creative_quality_opportunity")]).optional() - }).passthrough())).optional(), - indicator_types_evaluated: z.array(IndicatorTypeSchema.and(z.union([z.literal("creative_fatigue"), z.literal("creative_quality_opportunity")]))).optional(), - indicators_as_of: z.iso.datetime().optional(), - indicators_evaluated_scope: z.array(IndicatorScopeSchema).optional() - }).passthrough()).optional(), - formats_to_provide: z.array(PackageFormatSnapshotSchema).optional(), - formats_pending: z.array(PackageFormatSnapshotSchema).optional(), - format_ids_to_provide: z.array(FormatReferenceStructuredObjectSchema).optional(), - format_ids_pending: z.array(FormatReferenceStructuredObjectSchema).optional(), - snapshot_unavailable_reason: SnapshotUnavailableReasonSchema.optional(), - snapshot: z.object({ - as_of: z.iso.datetime(), - staleness_seconds: z.int().min(0), - impressions: z.number().min(0), - spend: z.number().min(0), - currency: z.string().regex(/^[A-Z]{3}$/).optional(), - clicks: z.number().min(0).optional(), - pacing_index: z.number().min(0).optional(), - delivery_status: DeliveryStatusSchema.optional(), - ext: ExtensionObjectSchema.optional() - }).passthrough().optional(), - ext: ExtensionObjectSchema.optional(), - indicator_types_evaluated: z.array(z.union([z.literal("creative_diversity_low"), z.literal("audience_saturation"), z.literal("inventory_shortfall_forecast"), z.literal("pacing_risk"), z.literal("budget_constrained")])).optional(), - indicators: z.array(z.object({ - type: z.union([z.literal("creative_diversity_low"), z.literal("audience_saturation"), z.literal("inventory_shortfall_forecast"), z.literal("pacing_risk"), z.literal("budget_constrained")]).optional() - }).passthrough()).optional() -}).passthrough(); - -export const GetMediaBuyDeliveryCatalogItemMetricsSchema = DeliveryMetricsSchema.merge(z.object({ - content_id: z.string().optional(), - content_id_type: ContentIDTypeSchema.optional() -}).passthrough()); - -export const GetMediaBuyDeliveryKeywordMetricsSchema = DeliveryMetricsSchema.merge(z.object({ - keyword: z.string().optional(), - match_type: MatchTypeSchema.optional() -}).passthrough()); - -export const GetMediaBuyDeliveryGeoMetricsSchema = DeliveryMetricsSchema.merge(z.object({ - geo_level: GeographicTargetingLevelSchema.optional(), - system: z.string().optional(), - country: z.string().regex(/^[A-Z]{2}$/).optional(), - geo_code: z.string().optional(), - geo_name: z.string().optional() -}).passthrough()); - -export const GetMediaBuyDeliveryDeviceTypeMetricsSchema = DeliveryMetricsSchema.merge(z.object({ - device_type: DeviceTypeSchema.optional() -}).passthrough()); - -export const GetMediaBuyDeliveryDevicePlatformMetricsSchema = DeliveryMetricsSchema.merge(z.object({ - device_platform: DevicePlatformSchema.optional() -}).passthrough()); - -export const GetMediaBuyDeliveryAudienceMetricsSchema = DeliveryMetricsSchema.merge(z.object({ - audience_id: z.string().optional(), - audience_source: AudienceSourceSchema.optional(), - audience_name: z.string().optional() -}).passthrough()); - -export const GetMediaBuyDeliveryPlacementMetricsSchema = DeliveryMetricsSchema.merge(z.object({ - placement_identity: PlacementIdentitySchema.optional(), - placement_name: z.string().optional(), - placement_id: z.string().optional(), - publisher_domain: z.string().regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/).optional() -}).passthrough()); - -export const GetMediaBuyDeliveryResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - notification_type: z.union([z.literal("scheduled"), z.literal("final"), z.literal("delayed"), z.literal("adjusted"), z.literal("window_update")]).optional(), - partial_data: z.boolean().optional(), - unavailable_count: z.int().min(0).optional(), - sequence_number: z.int().min(1).optional(), - next_expected_at: z.iso.datetime().optional(), - reporting_period: z.object({ - start: z.iso.datetime(), - end: z.iso.datetime() - }).passthrough(), - reporting_revision_binding: z.object({ - reporting_revision_id: z.string().min(1).max(255), - row_count: z.int().min(0), - control_totals: z.array(ReportingControlTotalSchema), - content_sha256: z.string().regex(/^[A-Fa-f0-9]{64}$/) - }).passthrough().optional(), - reporting_revision: ReportingRevisionSchema.optional(), - reporting_rows: z.array(z.object({}).passthrough()).optional(), - pagination: PaginationResponseSchema.optional(), - currency: z.string().regex(/^[A-Z]{3}$/).optional(), - attribution_window: AttributionWindowSchema.optional(), - aggregated_totals: z.object({ - impressions: z.number().min(0), - spend: z.number().min(0), - clicks: z.number().min(0).optional(), - completed_views: z.number().min(0).optional(), - views: z.number().min(0).optional(), - conversions: z.number().min(0).optional(), - conversion_value: z.number().min(0).optional(), - commissionable_value: z.number().min(0).optional(), - roas: z.number().min(0).optional(), - new_to_brand_rate: z.number().min(0).max(1).optional(), - cost_per_acquisition: z.number().min(0).optional(), - completion_rate: z.number().min(0).max(1).optional().nullable(), - reach: z.number().min(0).optional(), - reach_aggregation: ReachAggregationSchema.optional(), - reach_unit: ReachUnitSchema.optional(), - frequency: z.number().min(0).optional(), - media_buy_count: z.int().min(0), - metric_aggregates: z.array(DeliveryMetricAggregateSchema).optional() - }).passthrough().optional(), - media_buy_deliveries: z.array(z.object({ - media_buy_id: z.string(), - currency: z.string().regex(/^[A-Z]{3}$/).optional(), - status: z.union([z.literal("pending_creatives"), z.literal("pending_start"), z.literal("pending"), z.literal("active"), z.literal("paused"), z.literal("completed"), z.literal("rejected"), z.literal("canceled"), z.literal("failed"), z.literal("reporting_delayed")]), - expected_availability: z.iso.datetime().optional(), - is_adjusted: z.boolean().optional(), - is_final: z.boolean().optional(), - finalized_at: z.iso.datetime().optional(), - pricing_model: PricingModelSchema.optional(), - pacing_index: z.number().min(0).optional(), - totals: DeliveryMetricsSchema.merge(z.object({ - effective_rate: z.number().min(0).optional() - }).passthrough()), - by_package: z.array(DeliveryMetricsSchema.merge(z.object({ - package_id: z.string(), - pacing_index: z.number().min(0).optional(), - pricing_model: PricingModelSchema.optional(), - rate: z.number().min(0).optional(), - currency: z.string().regex(/^[A-Z]{3}$/).optional(), - delivery_status: DeliveryStatusSchema.optional(), - paused: z.boolean().optional(), - is_final: z.boolean().optional(), - finalized_at: z.iso.datetime().optional(), - measurement_window: z.string().max(50).optional(), - supersedes_window: z.string().max(50).optional(), - missing_metrics: z.array(MissingMetricSchema).optional(), - metric_values: z.array(PackageDeliveryMetricValueSchema).optional(), - by_catalog_item: z.array(GetMediaBuyDeliveryCatalogItemMetricsSchema).optional(), - by_catalog_item_truncated: z.boolean().optional(), - by_catalog_item_sorted_by: SortMetricSchema.optional(), - by_catalog_item_sort_direction: SortDirectionSchema.optional(), - by_creative: z.array(CreativeDeliveryMetricsSchema).optional(), - by_format: z.array(DeliveryMetricsSchema.merge(z.object({ - format_kind: CanonicalFormatKindSchema - }).passthrough())).optional(), - by_format_truncated: z.boolean().optional(), - by_format_sorted_by: SortMetricSchema.optional(), - by_format_sort_direction: SortDirectionSchema.optional(), - by_creative_truncated: z.boolean().optional(), - by_creative_sorted_by: SortMetricSchema.optional(), - by_creative_sort_direction: SortDirectionSchema.optional(), - by_keyword: z.array(GetMediaBuyDeliveryKeywordMetricsSchema).optional(), - by_keyword_truncated: z.boolean().optional(), - by_keyword_sorted_by: SortMetricSchema.optional(), - by_keyword_sort_direction: SortDirectionSchema.optional(), - by_geo: z.array(GetMediaBuyDeliveryGeoMetricsSchema).optional(), - by_geo_truncated: z.boolean().optional(), - by_geo_sorted_by: SortMetricSchema.optional(), - by_geo_sort_direction: SortDirectionSchema.optional(), - by_device_type: z.array(GetMediaBuyDeliveryDeviceTypeMetricsSchema).optional(), - by_device_type_truncated: z.boolean().optional(), - by_device_type_sorted_by: SortMetricSchema.optional(), - by_device_type_sort_direction: SortDirectionSchema.optional(), - by_device_type_pagination: PaginationResponseSchema.optional(), - by_device_platform: z.array(GetMediaBuyDeliveryDevicePlatformMetricsSchema).optional(), - by_device_platform_truncated: z.boolean().optional(), - by_device_platform_sorted_by: SortMetricSchema.optional(), - by_device_platform_sort_direction: SortDirectionSchema.optional(), - by_device_platform_pagination: PaginationResponseSchema.optional(), - by_audience: z.array(GetMediaBuyDeliveryAudienceMetricsSchema).optional(), - by_audience_truncated: z.boolean().optional(), - by_audience_sorted_by: SortMetricSchema.optional(), - by_audience_sort_direction: SortDirectionSchema.optional(), - by_audience_pagination: PaginationResponseSchema.optional(), - by_demographic: z.array(DeliveryMetricsSchema.merge(z.object({ - demographic: z.string().min(1).regex(/\S/), - demographic_system: DemographicSystemSchema, - age: DemographicAgeRangeSchema.optional() - }).passthrough())).optional(), - by_demographic_truncated: z.boolean().optional(), - by_demographic_sorted_by: SortMetricSchema.optional(), - by_demographic_sort_direction: SortDirectionSchema.optional(), - by_demographic_suppressed: z.boolean().optional(), - by_placement: z.array(GetMediaBuyDeliveryPlacementMetricsSchema).optional(), - by_placement_truncated: z.boolean().optional(), - by_placement_sorted_by: SortMetricSchema.optional(), - by_placement_sort_direction: SortDirectionSchema.optional(), - by_placement_pagination: PaginationResponseSchema.optional(), - by_property: z.array(PropertyDeliveryMetricsSchema).optional(), - by_property_truncated: z.boolean().optional(), - by_property_suppressed: z.boolean().optional(), - by_property_sorted_by: SortMetricSchema.optional(), - by_property_sort_direction: SortDirectionSchema.optional(), - by_collection: z.array(CollectionDeliveryMetricsSchema).optional(), - by_collection_truncated: z.boolean().optional(), - by_collection_sorted_by: SortMetricSchema.optional(), - by_collection_sort_direction: SortDirectionSchema.optional(), - by_installment: z.array(InstallmentDeliveryMetricsSchema).optional(), - by_installment_truncated: z.boolean().optional(), - by_installment_sorted_by: SortMetricSchema.optional(), - by_installment_sort_direction: SortDirectionSchema.optional(), - by_collection_property: z.array(CollectionPropertyDeliveryMetricsSchema).optional(), - by_collection_property_truncated: z.boolean().optional(), - by_collection_property_suppressed: z.boolean().optional(), - by_collection_property_sorted_by: SortMetricSchema.optional(), - by_collection_property_sort_direction: SortDirectionSchema.optional(), - by_installment_property: z.array(InstallmentPropertyDeliveryMetricsSchema).optional(), - by_installment_property_truncated: z.boolean().optional(), - by_installment_property_suppressed: z.boolean().optional(), - by_installment_property_sorted_by: SortMetricSchema.optional(), - by_installment_property_sort_direction: SortDirectionSchema.optional(), - by_placement_property: z.array(PlacementPropertyDeliveryMetricsSchema).optional(), - by_placement_property_truncated: z.boolean().optional(), - by_placement_property_suppressed: z.boolean().optional(), - by_placement_property_sorted_by: SortMetricSchema.optional(), - by_placement_property_sort_direction: SortDirectionSchema.optional(), - by_spot: z.array(DeliveryMetricsSchema.merge(z.object({ - spot_id: z.string().min(1), - creative_id: z.string().min(1).optional(), - aired_at: z.iso.datetime(), - network: z.string().min(1).optional(), - station: z.string().min(1).optional(), - daypart: z.string().min(1).optional() - }).passthrough())).optional(), - by_spot_truncated: z.boolean().optional(), - daily_breakdown: z.array(z.object({ - date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), - impressions: z.number().min(0), - spend: z.number().min(0), - conversions: z.number().min(0).optional(), - conversion_value: z.number().min(0).optional(), - commissionable_value: z.number().min(0).optional(), - roas: z.number().min(0).optional(), - new_to_brand_rate: z.number().min(0).max(1).optional() - }).passthrough()).optional() - }).passthrough())), - windows: z.array(z.object({ - window_start: z.iso.datetime(), - window_end: z.iso.datetime(), - totals: DeliveryMetricsSchema, - by_package: z.array(DeliveryMetricsSchema.merge(z.object({ - package_id: z.string(), - currency: z.string().regex(/^[A-Z]{3}$/).optional() - }).passthrough())).optional(), - is_final: z.boolean().optional(), - measurement_window: z.string().max(50).optional() - }).passthrough()).optional(), - daily_breakdown: z.array(z.object({ - date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), - impressions: z.number().min(0), - spend: z.number().min(0), - conversions: z.number().min(0).optional(), - conversion_value: z.number().min(0).optional(), - commissionable_value: z.number().min(0).optional(), - roas: z.number().min(0).optional(), - new_to_brand_rate: z.number().min(0).max(1).optional() - }).passthrough()).optional() - }).passthrough()), - errors: z.array(ErrorSchema).optional(), - sandbox: z.boolean().optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const SuccessfulLookupSchema = z.union([SummaryViewSchema, PeriodsViewSchema, RevisionViewSchema]); - -export const FailedLookupSchema = z.union([UnavailableLookupSchema, OperationalFailureSchema]); - -export const SyncReportingStatusResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - results: z.array(z.union([RecordedReportingConsumerStatusSchema, UnchangedReportingConsumerStatusSchema, FailedReportingConsumerStatusSchema])).max(100), - ext: ExtensionObjectSchema.optional() -}).passthrough().superRefine((value, ctx) => { - // reporting consumer status canonical parity - if (value.status === "completed" && value.results.length < 1) { - ctx.addIssue({ code: "custom", path: ["results"], message: "Array must contain at least 1 element(s)" }); - } - if (value.status !== "completed") return; - value.results.forEach((entry, index) => { - if (entry.result === "failed") { - if (entry.errors.length < 1) ctx.addIssue({ code: "custom", path: ["results", index, "errors"], message: "Array must contain at least 1 element(s)" }); - return; - } - const status = entry.consumer_status as Record; - if (status.recorded_at === undefined) { - ctx.addIssue({ code: "custom", path: ["results", index, "consumer_status", "recorded_at"], message: "recorded_at is required" }); - } - }); - }); - -export const SyncReportingReceiptsResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - results: z.array(z.union([RecordedReportingReceiptSchema, UnchangedReportingReceiptSchema, RecordedReportingAdjustmentReceiptSchema, UnchangedReportingAdjustmentReceiptSchema, FailedReportingReceiptSchema])).max(100), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const ProvidePerformanceFeedbackResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional() -}).passthrough().and(z.union([ProvidePerformanceFeedbackSuccessSchema, ProvidePerformanceFeedbackErrorSchema])); - -// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. -export const SyncEventSourcesResponseSchema: z.ZodType, SyncEventSourcesResponse & Record> = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional() -}).passthrough().and(z.union([SyncEventSourcesSuccessSchema, SyncEventSourcesErrorSchema])); - -export const LogEventResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional() -}).passthrough().and(z.union([LogEventSuccessSchema, LogEventErrorSchema])); - -export const SyncAudiencesResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional() -}).passthrough().and(z.union([SyncAudiencesSuccessSchema, SyncAudiencesErrorSchema, SyncAudiencesSubmittedSchema])); - -export const BuildCreativeRequestSchema = z.object({ - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - governance_context: z.string().min(1).max(4096).regex(/^[\x20-\x7E]+$/).optional(), - message: z.string().optional(), - creative_manifest: CreativeManifestSchema.optional(), - creative_representation_set: CreativeRepresentationSetSchema.optional(), - representation_destination: RepresentationDestinationSchema.optional(), - representation_selection_strategy: RepresentationSelectionStrategySchema.optional(), - creative_id: z.string().optional(), - concept_id: z.string().optional(), - media_buy_id: z.string().optional(), - package_id: z.string().optional(), - target_format_id: FormatReferenceStructuredObjectSchema.optional(), - target_format_ids: z.array(FormatReferenceStructuredObjectSchema).max(50).optional(), - target_capability_id: z.string().regex(/^[a-zA-Z0-9_-]+$/).optional(), - target_capability_ids: z.array(z.string()).max(50).optional(), - transformer_id: z.string().optional(), - config: z.object({}).passthrough().optional(), - refine_from_build_variant_id: z.string().optional(), - mode: z.union([z.literal("execute"), z.literal("estimate")]).optional(), - max_spend: z.object({ - amount: z.number().min(0), - currency: z.string().regex(/^[A-Z]{3}$/) - }).passthrough().optional(), - max_creatives: z.int().min(1).optional(), - signal_conditions: z.array(SignalTargetingSchema.and(z.object({ - signal_agent_segment_id: z.string().optional() - }).passthrough())).optional(), - max_variants: z.int().min(1).optional(), - variant_axis: z.object({ - dimension: z.union([z.literal("voice"), z.literal("theme"), z.literal("best_of_n"), z.literal("transformer_config"), z.literal("custom")]), - field: z.string().optional(), - values: z.array(z.unknown()).optional(), - label: z.string().optional() - }).passthrough().optional(), - keep_mode: z.union([z.literal("keep_all"), z.literal("keep_one"), z.literal("keep_some")]).optional(), - selection_strategy: CreativeSelectionStrategySchema.optional(), - account: AccountReferenceSchema.optional(), - brand: BrandReferenceSchema.optional(), - quality: CreativeQualitySchema.optional(), - evaluator: EvaluatorSpecSchema.optional(), - item_limit: z.int().min(1).optional(), - include_preview: z.boolean().optional(), - preview_inputs: z.array(z.object({ - name: z.string(), - macros: z.record(z.string(), z.string()).optional(), - context_description: z.string().optional() - }).passthrough()).optional(), - preview_quality: CreativeQualitySchema.optional(), - preview_output_format: PreviewOutputFormatSchema.optional(), - macro_values: z.record(z.string(), z.string()).optional(), - idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/), - push_notification_config: PushNotificationConfigSchema.optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const BuildCreativeSuccessSchema = z.object({ - creative_manifest: CreativeManifestSchema, - build_variant_id: z.string().optional(), - recipe_hash: z.string().optional(), - sandbox: z.boolean().optional(), - expires_at: z.iso.datetime().optional(), - preview: z.object({ - previews: z.array(z.object({ - preview_id: z.string(), - renders: z.array(PreviewRenderSchema), - input: z.object({ - name: z.string(), - macros: z.record(z.string(), z.string()).optional(), - context_description: z.string().optional() - }).passthrough() - }).passthrough()), - interactive_url: z.string().optional(), - expires_at: z.iso.datetime() - }).passthrough().optional(), - preview_error: ErrorSchema.optional(), - pricing_option_id: z.string().optional(), - vendor_cost: z.number().min(0).optional(), - currency: z.string().regex(/^[A-Z]{3}$/).optional(), - consumption: CreativeConsumptionSchema.optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. -export const PreviewCreativeRequestSchema: z.ZodObject<{ request_type: z.ZodType } & Record, z.core.$loose> & z.ZodType, PreviewCreativeRequest & Record> = z.object({}).passthrough().merge(z.object({ - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - request_type: z.union([z.literal("single"), z.literal("batch"), z.literal("variant")]), - creative_manifest: CreativeManifestSchema.optional(), - target_capability_id: z.string().regex(/^[a-zA-Z0-9_-]+$/).optional(), - format_id: FormatReferenceStructuredObjectSchema.optional(), - inputs: z.array(z.object({ - name: z.string(), - macros: z.record(z.string(), z.string()).optional(), - context_description: z.string().optional() - }).passthrough()).optional(), - template_id: z.string().optional(), - quality: CreativeQualitySchema.optional(), - output_format: PreviewOutputFormatSchema.optional(), - item_limit: z.int().min(1).optional(), - requests: z.array(z.object({ - target_capability_id: z.string().regex(/^[a-zA-Z0-9_-]+$/).optional(), - format_id: FormatReferenceStructuredObjectSchema.optional(), - creative_manifest: CreativeManifestSchema.optional(), - creative_id: z.string().optional(), - inputs: z.array(z.object({ - name: z.string(), - macros: z.record(z.string(), z.string()).optional(), - context_description: z.string().optional() - }).passthrough()).optional(), - template_id: z.string().optional(), - quality: CreativeQualitySchema.optional(), - output_format: PreviewOutputFormatSchema.optional(), - item_limit: z.int().min(1).optional() - }).passthrough()).max(50).optional(), - variant_id: z.string().optional(), - creative_id: z.string().optional(), - allow_async: z.boolean().optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough()).superRefine((value, ctx) => { - const defined = (field: string): boolean => value[field as keyof typeof value] !== undefined; - const rejectPair = (left: string, right: string): void => { - if (defined(left) && defined(right)) { - ctx.addIssue({ code: "custom", path: [right], message: "the paired fields are mutually exclusive" }); - } - }; - rejectPair("target_capability_id", "format_id"); - rejectPair("creative_manifest", "creative_id"); - if (value.requests !== undefined) { - if (value.requests.length < 1 || value.requests.length > 50) { - ctx.addIssue({ code: "custom", path: ["requests"], message: "preview requests must contain 1 to 50 items" }); - } - const canonicalRouting = defined("target_capability_id") || value.requests.some(item => item.target_capability_id !== undefined); - const legacyRouting = defined("format_id") || value.requests.some(item => item.format_id !== undefined); - if (canonicalRouting && legacyRouting) { - ctx.addIssue({ code: "custom", path: ["requests"], message: "preview requests cannot mix canonical and legacy routing selectors" }); - } - for (const [index, item] of value.requests.entries()) { - const hasManifest = item.creative_manifest !== undefined; - const hasCreativeId = item.creative_id !== undefined; - if (hasManifest === hasCreativeId) { - ctx.addIssue({ code: "custom", path: ["requests", index, "creative_manifest"], message: "each preview request requires exactly one of creative_manifest or creative_id" }); - } - } - } - if (value.request_type === "single") { - const hasManifest = defined("creative_manifest"); - const hasCreativeId = defined("creative_id"); - if (hasManifest === hasCreativeId) { - ctx.addIssue({ code: "custom", path: ["creative_manifest"], message: "single preview requires exactly one of creative_manifest or creative_id" }); - } - } else if (value.request_type === "batch") { - if (value.requests === undefined) { - ctx.addIssue({ code: "custom", path: ["requests"], message: "batch preview requires 1 to 50 requests" }); - } - } else if (value.request_type === "variant" && !defined("variant_id")) { - ctx.addIssue({ code: "custom", path: ["variant_id"], message: "variant_id is required for variant preview" }); - } -}); - -export const PreviewCreativeResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional() -}).passthrough().and(z.union([PreviewCreativeSingleResponseSchema, PreviewCreativeBatchResponseSchema, PreviewCreativeVariantResponseSchema, PreviewCreativeSubmittedSchema])); - -// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. -export const ListTransformersResponseCreativeAgentSchema: z.ZodObject<{ [K in keyof ListTransformersResponseCreativeAgent]-?: undefined extends ListTransformersResponseCreativeAgent[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, ListTransformersResponseCreativeAgent & Record> = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - transformers: z.array(TransformerSchema), - errors: z.array(ErrorSchema).optional(), - pagination: PaginationResponseSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const GetCreativeDeliveryResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - account_id: z.string().optional(), - media_buy_id: z.string().optional(), - currency: z.string().regex(/^[A-Z]{3}$/), - reporting_period: z.object({ - start: z.iso.datetime(), - end: z.iso.datetime(), - timezone: z.string().optional() - }).passthrough(), - creatives: z.array(z.object({ - creative_id: z.string(), - media_buy_id: z.string().optional(), - format_id: FormatReferenceStructuredObjectSchema.optional(), - format_kind: CanonicalFormatKindSchema.optional(), - format_option_ref: FormatOptionReferenceSchema.optional(), - totals: DeliveryMetricsSchema.optional(), - variant_count: z.int().min(0).optional(), - variants: z.array(CreativeVariantSchema) - }).passthrough()), - pagination: z.object({ - limit: z.int().min(1), - offset: z.int().min(0), - has_more: z.boolean(), - total_count: z.int().min(0).optional(), - total: z.int().min(0).optional() - }).passthrough().optional(), - errors: z.array(ErrorSchema).optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const SourceLocalizationReadbackSchema = z.object({ - locale_variant_id: z.string(), - locale: LanguageTagSchema, - role: z.literal("source"), - assets: ResolvedAssetsSchema -}).passthrough(); - -export const CreativeLocalizationReadbackSchema: z.ZodType = z.object({ - default_locale_variant_id: z.string().min(1).max(255), - unmatched_locale_action: z.union([z.literal("serve_default"), z.literal("do_not_serve")]), - locale_matching: z.literal("rfc4647_lookup"), - locale_fallbacks: z.array(z.object({ - language_range: LanguageTagSchema, - locale_variant_id: z.string().min(1).max(255) - }).passthrough()).max(50).optional(), - variants: z.array(z.union([SourceLocalizationReadbackSchema, TargetLocalizationReadbackSchema])).max(51) -}).passthrough(); - -// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. -export const SyncCreativesRequestSchema: z.ZodObject<{ [K in keyof SyncCreativesRequest]-?: undefined extends SyncCreativesRequest[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, SyncCreativesRequest & Record> = z.object({ - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - account: AccountReferenceSchema, - creatives: z.array(CreativeAssetSchema.and(z.object({ - revision_id: CreativeRevisionIDSchema.optional(), - localization: CreativeLocalizationSchema.optional().nullable() - }).passthrough())).max(100).optional(), - creative_ids: z.array(z.string()).max(100).optional(), - assignments: z.array(z.object({ - creative_id: z.string(), - package_id: z.string(), - weight: z.number().min(0).max(100).optional(), - placement_ids: z.array(z.string()).optional() - }).passthrough()).optional(), - assignment_operations: z.array(z.union([AssignOrUpdateSchema, UnassignSchema, ReplaceAssignmentSchema])).max(500).optional(), - idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/), - delete_missing: z.boolean().optional(), - dry_run: z.boolean().optional(), - validation_mode: ValidationModeSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const SyncCreativesSuccessSchema: z.ZodType = z.object({ - dry_run: z.boolean().optional(), - creatives: z.array(z.object({ - creative_id: z.string(), - revision_id: CreativeRevisionIDSchema.optional(), - account: AccountSchema.optional(), - action: CreativeActionSchema, - status: CreativeStatusSchema.optional(), - platform_id: z.string().optional(), - localization: CreativeLocalizationReadbackSchema.optional(), - changes: z.array(z.string()).optional(), - errors: z.array(ErrorSchema).optional(), - warnings: z.array(z.string()).optional(), - macro_resolution_results: z.array(MacroResolutionResultSchema).optional(), - preview_url: z.string().optional(), - expires_at: z.iso.datetime().optional(), - assigned_to: z.array(z.string()).optional(), - assignment_errors: z.record(z.string(), z.string()).optional() - }).passthrough()), - sandbox: z.boolean().optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const ValidateInputRequestSchema = z.object({ - account: AccountReferenceSchema.optional(), - brand: BrandReferenceSchema.optional(), - manifest: CreativeManifestSchema, - targets: z.array(z.union([CanonicalFormatTargetSchema, ProductTargetSchema, ThirdPartyFormatTargetSchema, CreativeCapabilityTargetSchema])).max(50).optional() -}).passthrough(); - -export const ActivateSignalResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional() -}).passthrough().and(z.union([ActivateSignalSuccessSchema, ActivateSignalErrorSchema])); - -export const CreatePropertyListResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - list: PropertyListSchema, - auth_token: z.string(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const CreateCollectionListResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - list: CollectionListSchema, - auth_token: z.string(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const ListContentStandardsResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional() -}).passthrough().and(z.union([z.object({ - standards: z.array(ContentStandardsSchema), - pagination: PaginationResponseSchema.optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() - }).passthrough(), z.object({ - errors: z.array(ErrorSchema), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() - }).passthrough()])); - -export const GetContentStandardsResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional() -}).passthrough().and(z.union([z.object({ - standards_id: z.string(), - name: z.string().optional(), - countries_all: z.array(z.string()).optional(), - channels_any: z.array(MediaChannelSchema).optional(), - languages_any: z.array(z.string()).optional(), - policies: z.array(PolicyEntrySchema).optional(), - calibration_exemplars: z.object({ - pass: z.array(ArtifactSchema).optional(), - fail: z.array(ArtifactSchema).optional() - }).passthrough().optional(), - pricing_options: z.array(VendorPricingOptionSchema).optional(), - ext: ExtensionObjectSchema.optional(), - context: ContextObjectSchema.optional() - }).passthrough(), z.object({ - errors: z.array(ErrorSchema), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() - }).passthrough()])); - -export const CreateContentStandardsRequestSchema = z.object({ - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - scope: z.object({ - countries_all: z.array(z.string()).optional(), - channels_any: z.array(MediaChannelSchema).optional(), - languages_any: z.array(z.string()), - description: z.string().optional() - }).passthrough(), - registry_policy_ids: z.array(z.string()).optional(), - policies: z.array(PolicyEntrySchema).optional(), - calibration_exemplars: z.object({ - pass: z.array(z.union([z.object({ - type: z.literal("url"), - value: z.string(), - language: z.string().optional() - }).passthrough(), ArtifactSchema])).optional(), - fail: z.array(z.union([z.object({ - type: z.literal("url"), - value: z.string(), - language: z.string().optional() - }).passthrough(), Artifact1Schema])).optional() - }).passthrough().optional(), - idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const UpdateContentStandardsResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional() -}).passthrough().and(z.union([UpdateContentStandardsSuccessSchema, UpdateContentStandardsErrorSchema])); - -export const GetCreativeFeaturesRequestSchema = z.object({ - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - creative_manifest: CreativeManifestSchema, - feature_ids: z.array(z.string()).optional(), - account: AccountReferenceSchema.optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const ReportPlanOutcomeRequestSchema = z.object({ - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - plan_id: z.string(), - check_id: z.string().optional(), - idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/), - purchase_type: PurchaseTypeSchema.optional(), - outcome: OutcomeTypeSchema, - seller_response: z.object({ - seller_reference: z.string().max(255).optional(), - committed_budget: z.number().min(0).optional(), - packages: z.array(z.object({ - budget: z.number().min(0).optional() - }).passthrough()).optional(), - planned_delivery: PlannedDeliverySchema.optional(), - creative_deadline: z.iso.datetime().optional() - }).passthrough().optional(), - delivery: z.union([z.object({ - observation_id: z.string().min(1).max(255), - source: z.literal("seller_statement_copy"), - observed_at: z.iso.datetime(), - seller_statement_id: z.string(), - seller_statement_digest: z.string().regex(/^sha256:[a-f0-9]{64}$/), - reporting_period: z.object({ - start: z.iso.datetime(), - end: z.iso.datetime() - }).passthrough(), - cumulative_spend: z.number().min(0), - currency: z.string().regex(/^[A-Z]{3}$/), - period_closed: z.boolean().optional(), - impressions: z.int().min(0).optional() - }).passthrough(), z.object({ - observation_id: z.string().min(1).max(255), - source: z.literal("buyer_measurement"), - observed_at: z.iso.datetime(), - seller_statement_id: z.string().optional(), - seller_statement_digest: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional(), - reporting_period: z.object({ - start: z.iso.datetime(), - end: z.iso.datetime() - }).passthrough(), - cumulative_spend: z.number().min(0), - currency: z.string().regex(/^[A-Z]{3}$/), - period_closed: z.boolean().optional(), - impressions: z.int().min(0).optional() - }).passthrough()]).optional(), - error: ReportedOutcomeErrorSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(/^[\x20-\x7E]+$/).optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const GetPlanAuditLogsResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - plans: z.array(z.object({ - plan_id: z.string(), - plan_version: z.int(), - status: z.union([z.literal("active"), z.literal("suspended"), z.literal("completed")]), - budget: z.object({ - authorized: z.number().optional(), - accounting_mode: z.union([z.literal("gross_commitment"), z.literal("verified_net_cost")]).optional(), - committed: z.number().optional(), - gross_committed: z.number().optional(), - adjustments_reported: z.number().optional(), - adjustments_verified: z.number().optional(), - net_cost: z.number().optional(), - headroom_restored: z.number().optional(), - net_committed: z.number().optional(), - ledger_committed: z.number().optional(), - remaining: z.number().optional(), - utilization_pct: z.number().optional() - }).passthrough(), - channel_allocation: z.record(z.string(), z.object({ - committed: z.number().optional(), - pct: z.number().optional() - }).passthrough()).optional(), - summary: z.object({ - checks_performed: z.int().optional(), - outcomes_reported: z.int().optional(), - adjustments_reported: z.int().optional(), - adjustments_verified: z.int().optional(), - statuses: z.object({ - approved: z.int().optional(), - denied: z.int().optional(), - conditions: z.int().optional(), - human_reviewed: z.int().optional() - }).passthrough().optional(), - findings_count: z.int().optional(), - escalations: z.array(z.object({ - check_id: z.string(), - reason: z.string(), - resolution: z.string().optional(), - resolved_at: z.iso.datetime().optional() - }).passthrough()).optional(), - drift_metrics: z.object({ - escalation_rate: z.number().min(0).max(1).optional(), - escalation_rate_trend: z.union([z.literal("increasing"), z.literal("stable"), z.literal("declining")]).optional(), - auto_approval_rate: z.number().min(0).max(1).optional(), - human_override_rate: z.number().min(0).max(1).optional(), - mean_confidence: z.number().min(0).max(1).optional(), - thresholds: z.object({ - escalation_rate_max: z.number().min(0).max(1).optional(), - escalation_rate_min: z.number().min(0).max(1).optional(), - auto_approval_rate_max: z.number().min(0).max(1).optional(), - human_override_rate_max: z.number().min(0).max(1).optional() - }).passthrough().optional() - }).passthrough().optional() - }).passthrough(), - entries: z.array(z.object({ - id: z.string(), - type: z.union([z.literal("check"), z.literal("outcome"), z.literal("adjustment")]), - timestamp: z.iso.datetime(), - plan_id: z.string().optional(), - caller: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional(), - tool: z.string().optional(), - verdict: GovernanceDecisionSchema.optional(), - check_type: z.union([z.literal("intent"), z.literal("execution")]).optional(), - mode: GovernanceModeSchema.optional(), - explanation: z.string().optional(), - policies_evaluated: z.array(z.string()).optional(), - categories_evaluated: z.array(z.string()).optional(), - findings: z.array(z.object({ - category_id: z.string(), - policy_id: z.string().optional(), - source_plan_id: z.string().optional(), - severity: EscalationSeveritySchema, - explanation: z.string(), - details: z.object({}).passthrough().optional(), - confidence: z.number().min(0).max(1).optional(), - uncertainty_reason: z.string().optional(), - attestation_reference_digest: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional() - }).passthrough()).optional(), - delivery_statement: z.object({ - statement_id: z.string(), - statement_digest: z.string().regex(/^sha256:[a-f0-9]{64}$/), - sequence: z.int().min(1), - issued_at: z.iso.datetime(), - seller_reference: z.string(), - cumulative_spend: z.number().min(0), - currency: z.string().regex(/^[A-Z]{3}$/), - reporting_period: z.object({ - start: z.iso.datetime(), - end: z.iso.datetime() - }).passthrough(), - canonical_payload: z.object({ - seller_reference: z.string(), - delivery_metrics: z.object({}).passthrough() - }).passthrough() - }).passthrough().optional(), - outcome: OutcomeTypeSchema.optional(), - error: ReportedOutcomeErrorSchema.optional(), - outcome_id: z.string().optional(), - seller_adjustment_id: z.string().optional(), - adjustment_type: z.union([z.literal("decommitment"), z.literal("refund"), z.literal("credit"), z.literal("makegood")]).optional(), - amount: z.object({ - amount: z.number(), - currency: z.string().regex(/^[A-Z]{3}$/) - }).passthrough().optional(), - headroom_restored: z.number().min(0).optional(), - reason: z.string().optional(), - effective_at: z.iso.datetime().optional(), - committed_budget: z.number().optional(), - reported_committed_budget: z.number().min(0).optional(), - seller_reference: z.string().optional(), - delivery: z.object({ - observation_id: z.string().min(1).max(255).optional(), - source: z.union([z.literal("seller_statement_copy"), z.literal("buyer_measurement")]).optional(), - observed_at: z.iso.datetime().optional(), - seller_statement_id: z.string().optional(), - seller_statement_digest: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional(), - reporting_period: z.object({ - start: z.iso.datetime(), - end: z.iso.datetime() - }).passthrough().optional(), - cumulative_spend: z.number().min(0).optional(), - currency: z.string().regex(/^[A-Z]{3}$/).optional(), - period_closed: z.boolean().optional(), - impressions: z.int().min(0).optional() - }).passthrough().optional(), - governance_context: z.string().optional(), - plan_hash: z.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(), - runtime_attestations: z.array(z.object({ - reference: AttestationReferenceSchema, - evaluation: AttestationEvaluationSchema - }).passthrough()).max(10).optional(), - runtime_attestation_binding_digest: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional(), - purchase_type: PurchaseTypeSchema.optional(), - outcome_status: z.string().optional(), - delivery_reconciliation_status: z.union([z.literal("consistent"), z.literal("measurement_variance"), z.literal("disputed"), z.literal("unmatched"), z.literal("closed_unresolved")]).optional(), - delivery_period_state: z.union([z.literal("open"), z.literal("closed")]).optional(), - adjustment_state: z.union([z.literal("reported"), z.literal("verified"), z.literal("disputed")]).optional(), - verified_amount: z.number().min(0).optional(), - evidence: z.object({ - evidence_id: z.string(), - evidence_type: z.union([z.literal("decommitment_agreement"), z.literal("refund_settlement"), z.literal("credit_note"), z.literal("makegood_agreement")]), - digest: z.string().regex(/^sha256:[a-f0-9]{64}$/), - issued_at: z.iso.datetime() - }).passthrough().optional(), - reviewed_by: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional(), - reviewed_at: z.iso.datetime().optional(), - review_reason: z.string().optional() - }).passthrough()).optional(), - governed_actions: z.array(z.object({ - governance_context: z.string(), - purchase_type: PurchaseTypeSchema, - status: z.union([z.literal("active"), z.literal("suspended"), z.literal("completed")]), - committed: z.number(), - adjustments_reported: z.number().optional(), - adjustments_verified: z.number().optional(), - net_cost: z.number().optional(), - headroom_restored: z.number().optional(), - net_committed: z.number().optional(), - seller_reported_spend: z.number().min(0).optional(), - buyer_observed_spend: z.number().min(0).optional(), - delivery_reporting_period: z.object({ - start: z.iso.datetime(), - end: z.iso.datetime() - }).passthrough().optional(), - conservative_exposure: z.number().min(0).optional(), - delivery_reconciliation_status: z.union([z.literal("consistent"), z.literal("measurement_variance"), z.literal("disputed"), z.literal("unmatched"), z.literal("closed_unresolved")]).optional(), - delivery_period_state: z.union([z.literal("open"), z.literal("closed")]).optional(), - check_count: z.int(), - seller_reference: z.string().optional() - }).passthrough()) - }).passthrough()), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. -export const GetAdCPCapabilitiesResponseSchema: z.ZodObject<{ [K in keyof GetAdCPCapabilitiesResponse]-?: undefined extends GetAdCPCapabilitiesResponse[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, GetAdCPCapabilitiesResponse & Record> = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - adcp: z.object({ - major_versions: z.array(z.number()), - supported_versions: z.array(z.string()).optional(), - build_version: z.string().regex(/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$/).optional(), - idempotency: z.union([IdempotencySupportedSchema, IdempotencyUnsupportedSchema]), - principal: z.object({ - supported: z.literal(true), - sync_task: z.literal("sync_principal"), - read_task: z.literal("get_principal"), - supported_sections: z.array(z.union([z.literal("notification_configs"), z.literal("reporting_destinations"), z.literal("declarations")])), - max_reporting_destinations: z.int().min(1).max(64).optional(), - reporting_destination_offerings: z.array(z.object({ - pattern: z.union([z.literal("file_transfer"), z.literal("warehouse_materialization"), z.literal("dataset_share")]), - transports: z.array(z.string()), - formats: z.array(z.union([z.literal("jsonl"), z.literal("csv"), z.literal("parquet"), z.literal("avro"), z.literal("orc")])).optional(), - access_modes: z.array(z.string()).optional(), - verification_profiles: ReportingVerificationProfileSetSchema - }).passthrough()).max(3).optional(), - suspension_interval_seconds: z.int().min(1).max(86400).optional(), - caller_event_types: z.array(NotificationTypeSchema).optional(), - optimistic_concurrency: z.boolean() - }).passthrough().optional(), - capability_changes: z.object({ - capabilities_version: z.string().min(1).max(255).optional(), - last_modified: z.iso.datetime().optional(), - cache_ttl_seconds: z.int().min(60).max(604800).optional(), - notifications: z.union([CapabilityChangeNotificationsSupportedSchema, CapabilityChangeNotificationsUnsupportedSchema]).optional() - }).passthrough().optional(), - governance_enforcement: z.object({ - tasks: z.array(z.union([z.object({ - task: z.literal("create_media_buy"), - modes: z.array(z.union([z.literal("signed_context"), z.literal("online_execution_check")])).max(1) - }).passthrough(), z.object({ - task: z.literal("update_media_buy"), - modes: z.array(z.union([z.literal("signed_context"), z.literal("online_execution_check")])).max(1) - }).passthrough(), z.object({ - task: z.literal("buy_products"), - modes: z.array(z.union([z.literal("signed_context"), z.literal("online_execution_check")])).max(1) - }).passthrough(), z.object({ - task: z.literal("accept_proposal"), - modes: z.array(z.union([z.literal("signed_context"), z.literal("online_execution_check")])).max(1) - }).passthrough(), z.object({ - task: z.literal("control_media_buy"), - modes: z.array(z.union([z.literal("signed_context"), z.literal("online_execution_check")])).max(1) - }).passthrough(), z.object({ - task: z.literal("build_creative"), - modes: z.array(z.literal("signed_context")).max(1) - }).passthrough(), z.object({ - task: z.literal("activate_signal"), - modes: z.array(z.literal("signed_context")).max(1) - }).passthrough(), z.object({ - task: z.literal("acquire_rights"), - modes: z.array(z.literal("signed_context")).max(1) - }).passthrough(), z.object({ - task: z.literal("update_rights"), - modes: z.array(z.literal("signed_context")).max(1) - }).passthrough()])), - accepted_governance_agents: AcceptedGovernanceAgentsSchema.optional() - }).passthrough().optional(), - attestations: AttestationCapabilitiesSchema.optional() - }).passthrough(), - supported_protocols: z.array(z.union([z.literal("media_buy"), z.literal("signals"), z.literal("governance"), z.literal("sponsored_intelligence"), z.literal("creative"), z.literal("brand"), z.literal("measurement")])), - account: z.object({ - require_operator_auth: z.boolean().optional(), - authorization_endpoint: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional(), - supported_billing: z.array(BillingPartySchema), - supported_account_currency_modes: z.array(AccountCurrencyModeSchema).optional(), - timezone: AccountTimezoneCapabilitySchema.optional(), - required_for_products: z.boolean().optional(), - account_financials: z.boolean().optional(), - notifications: z.union([AccountNotificationsSupportedSchema, AccountNotificationsUnsupportedSchema]).optional(), - change_feed: z.union([AccountChangeFeedSupportedSchema, AccountChangeFeedUnsupportedSchema]).optional(), - identity_updates: z.union([AccountIdentityUpdatesSupportedSchema, AccountIdentityUpdatesUnsupportedSchema]).optional(), - sandbox: z.boolean().optional() - }).passthrough().optional(), - media_buy: z.object({ - acceptance_policy_discovery: z.object({ - catalog_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI").regex(/^https:\/\//), - catalog_digest: z.string().regex(/^sha256:[a-f0-9]{64}$/), - default_profile_ids: z.array(z.string()).optional() - }).passthrough().optional(), - supported_pricing_models: z.array(PricingModelSchema).optional(), - buying_modes: z.array(z.union([z.literal("brief"), z.literal("wholesale"), z.literal("refine")])).optional(), - measurement_terms_acceptance: z.boolean().optional(), - availability_horizon: z.boolean().optional(), - lifecycle_tools: z.array(z.union([z.literal("list_products"), z.literal("request_proposals"), z.literal("refine_proposals"), z.literal("decline_proposals"), z.literal("buy_products"), z.literal("accept_proposal"), z.literal("control_media_buy")])).optional(), - proposal_refinement: z.object({ - supported_dimensions: z.array(z.union([z.literal("total_budget"), z.literal("cpm"), z.literal("impressions"), z.literal("flight"), z.literal("product_changes"), z.literal("alternatives"), z.literal("criteria")])), - max_alternatives: z.int().min(2).max(10).optional() - }).passthrough().optional(), - reporting_delivery_methods: z.array(CapabilityReportingDeliveryMethodSchema).optional(), - performance_feedback: z.object({ - reports_application_status: z.boolean().optional() - }).passthrough().optional(), - offline_delivery_protocols: z.array(CloudStorageProtocolSchema).optional(), - reporting_delivery: ReportingDeliveryCapabilitiesSchema.optional(), - supports_proposals: z.boolean().optional(), - outcome_target: z.boolean().optional(), - governance_aware: z.boolean().optional(), - propagation_surfaces: z.array(z.union([z.literal("snapshot"), z.literal("webhook"), z.literal("out_of_band")])).optional(), - creative_approval_mode: z.union([z.literal("auto_approve"), z.literal("require_human")]).optional(), - supported_indicator_types: z.array(IndicatorTypeSchema).optional(), - relationship_notifications: z.object({ - supported: z.literal(true), - registration_task: z.literal("sync_accounts"), - event_types: z.array(z.union([z.literal("indicators.changed"), z.literal("creative.assignment_changed")])).max(2), - repair_tasks: z.array(z.literal("get_media_buys")).max(1), - projection_tasks: z.array(z.literal("list_creatives")).max(1).optional(), - supports_webhook_activity: z.boolean().optional() - }).passthrough().optional(), - features: MediaBuyFeaturesSchema.optional(), - execution: z.object({ - trusted_match: z.object({ - surfaces: z.array(PropertyTypeSchema).optional() - }).passthrough().optional(), - axe_integrations: z.array(z.string()).optional(), - creative_specs: z.object({ - vast_versions: z.array(VASTVersionSchema).optional(), - macro_resolution_capabilities: z.array(MacroProcessingCapabilitySchema).optional(), - mraid_versions: z.array(z.string()).optional(), - vpaid: z.boolean().optional(), - simid: z.boolean().optional(), - vast_validation: z.union([z.literal("structural"), z.literal("document"), z.literal("wrapper")]).optional() - }).passthrough().optional(), - targeting: z.object({ - geo_countries: z.boolean().optional(), - geo_regions: z.union([z.boolean(), GeographicRegionSupportSchema]).optional(), - geo_regions_exclude: z.union([z.boolean(), GeographicRegionSupportSchema]).optional(), - geo_metros: z.object({ - nielsen_dma: z.boolean().optional(), - uk_itl1: z.boolean().optional(), - uk_itl2: z.boolean().optional(), - eurostat_nuts2: z.boolean().optional() - }).passthrough().optional(), - geo_postal_areas: PostalAreaSupportSchema.optional(), - geo_places: z.record(z.string(), GeographicPlaceSystemSupportSchema).optional(), - age_restriction: z.object({ - supported: z.boolean().optional(), - verification_methods: z.array(AgeVerificationMethodSchema).optional() - }).passthrough().optional(), - demographics: z.object({ - supported: z.boolean() - }).passthrough().optional(), - language: z.union([z.boolean(), z.object({ - supported: z.boolean().optional(), - supported_languages: z.array(LanguageTagSchema).optional() - }).passthrough()]).optional(), - keyword_targets: z.object({ - supported_match_types: z.array(MatchTypeSchema) - }).passthrough().optional(), - negative_keywords: z.object({ - supported_match_types: z.array(MatchTypeSchema) - }).passthrough().optional(), - placement_selection: z.boolean().optional(), - property_list: z.boolean().optional(), - property_list_exclude: z.boolean().optional(), - collection_list: z.boolean().optional(), - collection_list_exclude: z.boolean().optional(), - geo_proximity: z.object({ - radius: z.boolean().optional(), - travel_time: z.boolean().optional(), - geometry: z.boolean().optional(), - transport_modes: z.array(TransportModeSchema).optional() - }).passthrough().optional() - }).passthrough().optional() - }).passthrough().optional(), - audience_evidence: z.object({ - supported_requirement_modes: z.array(z.union([z.literal("required"), z.literal("preferred")])), - supported_presence_modes: z.array(z.union([z.literal("required"), z.literal("when_available")])), - supports_attestation_evaluation: z.boolean() - }).passthrough().optional(), - rights_attestations: z.object({ - requirement: z.union([z.literal("optional"), z.literal("required")]) - }).passthrough().optional(), - audience_targeting: z.object({ - supported_identifier_types: z.array(z.union([z.literal("hashed_email"), z.literal("hashed_phone")])), - supports_platform_customer_id: z.boolean().optional(), - supported_uid_types: z.array(UIDTypeSchema).optional(), - minimum_audience_size: z.int().min(1), - supported_activation_methods: z.array(AudienceActivationMethodSchema).optional(), - matching_latency_hours: z.object({ - min: z.int().min(0).optional(), - max: z.int().min(0).optional() - }).passthrough().optional() - }).passthrough().optional(), - supported_optimization_metrics: z.array(z.union([z.literal("clicks"), z.literal("views"), z.literal("completed_views"), z.literal("viewed_seconds"), z.literal("attention_seconds"), z.literal("attention_score"), z.literal("engagements"), z.literal("follows"), z.literal("saves"), z.literal("profile_visits"), z.literal("reach")])).optional(), - vendor_metric_optimization: z.object({ - supported_targets: z.array(z.union([z.literal("cost_per"), z.literal("threshold_rate")])).optional() - }).passthrough().optional(), - conversion_tracking: z.object({ - multi_source_event_dedup: z.boolean().optional(), - per_creative_attribution: z.boolean().optional(), - supported_event_types: z.array(EventTypeSchema).optional(), - supported_targets: z.array(z.union([z.literal("cost_per"), z.literal("per_ad_spend"), z.literal("maximize_value")])).optional(), - supported_uid_types: z.array(UIDTypeSchema).optional(), - supported_hashed_identifiers: z.array(z.union([z.literal("hashed_email"), z.literal("hashed_phone")])).optional(), - supported_action_sources: z.array(ActionSourceSchema).optional(), - attribution_windows: z.array(z.object({ - event_type: EventTypeSchema.optional(), - post_click: z.array(DurationSchema), - post_view: z.array(DurationSchema).optional() - }).passthrough()).optional() - }).passthrough().optional(), - frequency_capping: z.object({ - supported_per_units: z.array(ReachUnitSchema).optional(), - supported_window_units: z.array(z.string()).optional() - }).passthrough().optional(), - budget_capping: z.object({ - supported_scopes: z.array(z.union([z.literal("media_buy"), z.literal("package")])), - supported_periods: z.array(z.literal("day")), - timezone_basis: BudgetCappingTimezoneBasisSchema, - fixed_timezone: z.string().min(1).optional(), - buyer_timezone_override: z.boolean().optional() - }).passthrough().optional(), - content_standards: z.object({ - supports_local_evaluation: z.boolean().optional(), - supported_channels: z.array(MediaChannelSchema).optional(), - supports_webhook_delivery: z.boolean().optional() - }).passthrough().optional(), - portfolio: z.object({ - publisher_domains: z.array(z.string()), - primary_channels: z.array(MediaChannelSchema).optional(), - primary_countries: z.array(z.string()).optional(), - description: z.string().max(5000).optional(), - advertising_policies: z.string().max(10000).optional() - }).passthrough().optional() - }).passthrough().optional(), - signals: z.object({ - data_provider_domains: z.array(z.string()).optional(), - discovery_modes: z.array(z.union([z.literal("brief"), z.literal("wholesale")])).optional(), - features: z.object({ - catalog_signals: z.boolean().optional() - }).passthrough().catchall(z.boolean()).optional() - }).passthrough().optional(), - governance: z.object({ - runtime_attestations: z.object({ - signal_activation: z.object({ - requirement: z.union([z.literal("optional"), z.literal("required")]), - claim_types: z.array(z.string()) - }).passthrough() - }).passthrough().optional(), - aggregation_window_days: z.int().min(1).max(365).optional(), - property_features: z.array(z.object({ - feature_id: z.string(), - type: z.union([z.literal("binary"), z.literal("quantitative"), z.literal("categorical")]), - range: z.object({ - min: z.number(), - max: z.number() - }).passthrough().optional(), - categories: z.array(z.string()).optional(), - description: z.string().optional(), - methodology_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional() - }).passthrough()).optional(), - creative_features: z.array(z.object({ - feature_id: z.string(), - type: z.union([z.literal("binary"), z.literal("quantitative"), z.literal("categorical")]), - range: z.object({ - min: z.number(), - max: z.number() - }).passthrough().optional(), - categories: z.array(z.string()).optional(), - description: z.string().optional(), - methodology_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional() - }).passthrough()).optional() - }).passthrough().optional(), - sponsored_intelligence: z.object({ - endpoint: z.object({ - transports: z.array(z.object({ - type: z.union([z.literal("mcp"), z.literal("a2a")]), - url: z.string().refine(adcpJsonSchemaUri, "Invalid URI") - }).passthrough()), - preferred: z.union([z.literal("mcp"), z.literal("a2a")]).optional() - }).passthrough(), - capabilities: SICapabilitiesSchema, - brand_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional() - }).passthrough().optional(), - brand: z.object({ - rights: z.boolean().optional(), - right_types: z.array(RightTypeSchema).optional(), - available_uses: z.array(RightUseSchema).optional(), - generation_providers: z.array(z.string()).optional(), - description: z.string().max(5000).optional() - }).passthrough().optional(), - creative: z.object({ - supports_compliance: z.boolean().optional(), - has_creative_library: z.boolean().optional(), - supports_revisions: z.boolean().optional(), - supports_generation: z.boolean().optional(), - supports_transformation: z.boolean().optional(), - representation_resolution: z.object({ - supported: z.literal(true), - strategies: z.array(RepresentationSelectionStrategySchema) - }).passthrough().optional(), - supports_transformers: z.boolean().optional(), - supports_refinement: z.boolean().optional(), - supports_spend_controls: z.boolean().optional(), - supports_evaluator: z.boolean().optional(), - refinable_retention_seconds: z.int().min(0).optional(), - multiplicity: z.object({ - supports_catalog_fanout: z.boolean().optional(), - max_creatives_limit: z.int().min(1).optional(), - supports_signal_fanout: z.boolean().optional(), - max_signal_conditions_limit: z.int().min(1).optional(), - supports_variants: z.boolean().optional(), - max_variants_limit: z.int().min(1).optional(), - variant_dimensions: z.array(z.union([z.literal("voice"), z.literal("theme"), z.literal("best_of_n"), z.literal("transformer_config"), z.literal("custom")])).optional(), - selection_strategies: z.array(CreativeSelectionStrategySchema).optional() - }).passthrough().optional(), - supported_formats: z.array(z.object({ - capability_id: z.string().regex(/^[a-zA-Z0-9_-]+$/).optional(), - format: CreativeOperationFormatDeclarationSchema, - operations: z.array(z.union([z.literal("build"), z.literal("validate"), z.literal("preview")])).optional() - }).passthrough()).optional(), - preview: z.object({ - routes: z.array(z.object({ - capability_id: z.string().regex(/^[a-zA-Z0-9_-]+$/), - rendering_origin: z.union([z.literal("platform_native"), z.literal("agent_approximation")]) - }).passthrough()) - }).passthrough().optional(), - localization: z.object({ - max_target_variants: z.int().min(0).max(50).optional(), - locale_matching: z.literal("rfc4647_lookup") - }).passthrough().optional(), - bills_through_adcp: z.boolean().optional(), - canonical_catalog_version: z.string().regex(/^\d+\.\d+(\.\d+)?$/).optional() - }).passthrough().optional(), - oauth: z.object({ - supported: z.boolean() - }).passthrough().optional(), - request_signing: z.object({ - supported: z.boolean(), - covers_content_digest: z.union([z.literal("required"), z.literal("forbidden"), z.literal("either")]).optional(), - required_for: z.array(z.string()).optional(), - warn_for: z.array(z.string()).optional(), - supported_for: z.array(z.string()).optional(), - protocol_methods_supported_for: z.array(z.string()).optional(), - protocol_methods_warn_for: z.array(z.string()).optional(), - protocol_methods_required_for: z.array(z.string()).optional() - }).passthrough().optional(), - webhook_signing: z.object({ - supported: z.boolean(), - profile: z.literal("adcp/webhook-signing/v1").optional(), - algorithms: z.array(z.union([z.literal("ed25519"), z.literal("ecdsa-p256-sha256")])).optional(), - legacy_hmac_fallback: z.boolean().optional(), - delivery_retry_horizon_seconds: z.int().min(86400).max(604800).optional() - }).passthrough().optional(), - identity: z.object({ - brand_json_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI").regex(/^https:\/\//).optional(), - per_principal_key_isolation: z.boolean().optional(), - key_origins: z.object({ - governance_signing: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional(), - request_signing: z.string().optional(), - webhook_signing: z.string().optional(), - tmp_signing: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional() - }).passthrough().optional(), - compromise_notification: z.object({ - emits: z.boolean().optional(), - accepts: z.boolean().optional() - }).passthrough().optional() - }).passthrough().optional(), - measurement_gateway: z.object({ - delivery_task: z.literal("get_media_buy_delivery"), - feedback_task: z.literal("provide_performance_feedback") - }).passthrough().optional(), - measurement: z.object({ - produces_performance_feedback: z.boolean().optional(), - metrics: z.array(z.object({ - metric_id: VendorMetricIDSchema, - standard_reference: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional(), - accreditations: z.array(z.object({ - accrediting_body: z.string(), - certification_id: z.string().optional(), - valid_until: z.iso.date().optional(), - evidence_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional() - }).passthrough()).optional(), - unit: z.string().optional(), - description: z.string().optional(), - methodology_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional(), - methodology_version: z.string().optional(), - ext: ExtensionObjectSchema.optional() - }).passthrough()) - }).passthrough().optional(), - compliance_testing: z.object({ - scenarios: z.array(z.string()) - }).passthrough().optional(), - specialisms: z.array(AdCPSpecialismSchema).optional(), - extensions_supported: z.array(z.string()).optional(), - experimental_features: z.array(ExperimentalFeatureIDSchema).optional(), - wholesale_feed_versioning: z.object({ - supported: z.boolean(), - pricing_version_separate: z.boolean().optional(), - cache_scope_account: z.boolean().optional() - }).passthrough().optional(), - last_updated: z.iso.datetime().optional(), - errors: z.array(ErrorSchema).optional(), - ext: ExtensionObjectSchema.optional(), - wholesale_feed_webhooks: z.object({ - supported: z.boolean(), - event_types: z.array(z.union([z.literal("product.created"), z.literal("product.updated"), z.literal("product.priced"), z.literal("product.removed"), z.literal("signal.created"), z.literal("signal.updated"), z.literal("signal.priced"), z.literal("signal.removed"), z.literal("wholesale_feed.bulk_change")])).optional() - }).passthrough().optional() -}).passthrough(); - -export const SyncPrincipalRequestSchema = z.object({ - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/), - expected_configuration_version: z.string().min(1).max(255).optional(), - expected_principal_kind: PrincipalKindSchema.optional(), - configuration: z.object({ - notification_configs: z.array(AgentNotificationConfigSchema).max(16).optional(), - reporting_destinations: z.array(AgentReportingDestinationSchema).max(64).optional(), - declarations: AgentDeclarationsSchema.optional() - }).passthrough(), - dry_run: z.boolean().optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const AppliedPrincipalConfigurationSchema = z.object({ - kind: z.literal("applied"), - action: z.union([z.literal("updated"), z.literal("unchanged"), z.literal("cleared")]), - dry_run: z.literal(false), - principal_id: z.string().min(1).max(255), - principal_kind: PrincipalKindSchema, - configuration_version: z.string().min(1).max(255), - configuration: PrincipalStateSchema, - warnings: z.array(ErrorSchema).max(16).optional() -}).passthrough(); - -export const GetPrincipalResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - result: z.union([CurrentPrincipalConfigurationSchema, RecognizedPrincipalWithoutStandingConfigurationSchema, UnconfiguredPrincipalSchema, FailedPrincipalReadSchema]), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const AccountWithAuthorizationSchema = AccountSchema.merge(z.object({ - authorization: AccountAuthorizationSchema.optional() -}).passthrough()); - -export const ListAccountsResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - accounts: z.array(AccountWithAuthorizationSchema), - errors: z.array(ErrorSchema).optional(), - pagination: PaginationResponseSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const ProvisioningModeSchema = z.object({ - brand: BrandReferenceSchema, - operator: z.string().regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/), - operator_unit: OperatorUnitSchema.optional(), - currency: z.string().regex(/^[A-Z]{3}$/).optional(), - timezone: z.string().min(1).optional(), - billing: BillingPartySchema, - billing_entity: BusinessEntitySchema.optional(), - payment_terms: PaymentTermsSchema.optional(), - sandbox: z.boolean().optional(), - preferred_reporting_protocol: CloudStorageProtocolSchema.optional(), - reporting_delivery_configs: z.array(ReportingDeliveryConfigurationSchema).max(16).optional(), - notification_configs: z.array(NotificationConfigSchema).max(16).optional() -}).passthrough(); - -export const SettingsUpdateModeSchema = z.object({ - account: AccountReferenceSchema, - revision: z.int().min(1).optional(), - operator_identity: OperatorIdentitySchema.optional(), - destination_billing_entity: BusinessEntitySchema.optional(), - billing_entity: BusinessEntitySchema.optional(), - payment_terms: PaymentTermsSchema.optional(), - sandbox: z.boolean().optional(), - preferred_reporting_protocol: CloudStorageProtocolSchema.optional(), - reporting_delivery_configs: z.array(ReportingDeliveryConfigurationSchema).max(16).optional(), - notification_configs: z.array(NotificationConfigSchema).max(16).optional() -}).passthrough(); - -export const SyncAccountsSuccessSchema = z.object({ - dry_run: z.boolean().optional(), - accounts: z.array(z.object({ - account_id: z.string().optional(), - brand: BrandReferenceSchema, - operator: z.string(), - operator_unit: OperatorUnitSchema.optional(), - revision: z.int().min(1).optional(), - identity_change: AccountIdentityChangeSchema.optional(), - identity_change_preview: AccountIdentityChangePreviewSchema.optional(), - currency: z.string().regex(/^[A-Z]{3}$/).optional(), - timezone: z.string().min(1).optional(), - name: z.string().optional(), - action: z.union([z.literal("created"), z.literal("updated"), z.literal("unchanged"), z.literal("failed")]), - status: z.union([z.literal("active"), z.literal("pending_approval"), z.literal("rejected"), z.literal("payment_required"), z.literal("suspended"), z.literal("closed")]), - billing: BillingPartySchema.optional(), - billing_entity: BusinessEntitySchema.optional(), - destination_billing_entity: z.object({}).passthrough().optional(), - account_scope: AccountScopeSchema.optional(), - setup: z.object({ - url: z.string().optional(), - message: z.string(), - expires_at: z.iso.datetime().optional() - }).passthrough().optional(), - rate_card: z.string().optional(), - payment_terms: PaymentTermsSchema.optional(), - credit_limit: z.object({ - amount: z.number().min(0), - currency: z.string().regex(/^[A-Z]{3}$/) - }).passthrough().optional(), - errors: z.array(ErrorSchema).optional(), - warnings: z.array(z.string()).optional(), - sandbox: z.boolean().optional(), - notification_configs: z.array(NotificationConfigSchema).max(16).optional(), - reporting_delivery_configs: z.array(ReportingDeliveryConfigurationStateSchema).max(16).optional(), - authorization: AccountAuthorizationSchema.optional() - }).passthrough()), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const SyncGovernanceResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional() -}).passthrough().and(z.union([SyncGovernanceSuccessSchema, SyncGovernanceErrorSchema])); - -export const GetAccountFinancialsResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional() -}).passthrough().and(z.union([GetAccountFinancialsSuccessSchema, GetAccountFinancialsErrorSchema])); - -export const GetProductsCompletionSchema: z.ZodType = AdCPVersionEnvelopeSchema.merge(ProtocolEnvelopeSchema).merge(z.object({}).passthrough()).merge(z.object({ - products: z.array(ProductSchema).optional(), - targeting_resolution: ProductDiscoveryTargetingResolutionSchema.optional(), - extensions: z.object({}).passthrough().optional(), - proposals: z.array(ProposalSchema).optional(), - errors: z.array(ErrorSchema).optional(), - reason: z.string().optional(), - suggestions: z.array(z.string()).max(20).optional(), - property_list_applied: z.boolean().optional(), - catalog_applied: z.boolean().optional(), - refinement_applied: z.array(z.union([z.object({ - scope: z.literal("request"), - status: z.union([z.literal("applied"), z.literal("partial"), z.literal("unable")]), - notes: z.string().optional() - }).passthrough(), z.object({ - scope: z.literal("product"), - product_id: z.string(), - status: z.union([z.literal("applied"), z.literal("partial"), z.literal("unable")]), - notes: z.string().optional() - }).passthrough(), z.object({ - scope: z.literal("proposal"), - proposal_id: z.string(), - status: z.union([z.literal("applied"), z.literal("partial"), z.literal("unable")]), - notes: z.string().optional() - }).passthrough()])).optional(), - incomplete: z.array(z.object({ - scope: z.union([z.literal("products"), z.literal("pricing"), z.literal("forecast"), z.literal("proposals"), z.literal("wholesale_feed")]), - description: z.string(), - estimated_wait: DurationSchema.optional() - }).passthrough()).optional(), - filter_diagnostics: z.object({ - semantics: z.union([z.literal("only"), z.literal("any"), z.literal("approximate")]).optional(), - total_candidates: z.number().optional(), - excluded_by: z.record(z.string(), z.object({ - count: z.number(), - values: z.array(z.union([z.string(), z.object({}).passthrough()])).optional(), - notes: z.string().optional() - }).passthrough()).optional() - }).passthrough().optional(), - pagination: PaginationResponseSchema.optional(), - wholesale_feed_version: z.string().optional(), - pricing_version: z.string().optional(), - cache_scope: z.union([z.literal("public"), z.literal("account")]).optional(), - unchanged: z.literal(true).optional(), - sandbox: z.boolean().optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough()); - -export const ComplianceTaskCompletionDataSchema: z.ZodType = z.union([GetProductsCompletionSchema, GetSignalsCompletionSchema, CreateMediaBuyCompletionSchema]); - -export const UpstreamTrafficSuccessSchema = z.object({ - success: z.literal(true), - recorded_calls: z.array(z.union([RawAttestationSchema, DigestAttestationSchema])), - total_count: z.int().min(0), - truncated: z.boolean().optional(), - since_timestamp: z.iso.datetime(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. -export const ListTransformersResponseSchema: z.ZodObject<{ [K in keyof ListTransformersResponse]-?: undefined extends ListTransformersResponse[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, ListTransformersResponse & Record> = ListTransformersResponseCreativeAgentSchema; - -export const ValidatePropertyDeliveryRequestSchema = z.object({ - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - list_id: z.string(), - account: AccountReferenceSchema.optional(), - records: z.array(DeliveryRecordSchema).max(10000), - include_compliant: z.boolean().optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const ValidatePropertyDeliveryResponseSchema = z.object({ - context_id: z.string().optional(), - context: ContextObjectSchema.optional(), - task_id: z.string().optional(), - status: TaskStatusSchema, - message: z.string().optional(), - timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), - replayed: z.boolean().optional(), - adcp_error: ErrorSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), - payload: z.object({}).passthrough().optional(), - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - compliant: z.boolean().optional(), - list_id: z.string(), - summary: z.object({ - total_records: z.int(), - total_impressions: z.int(), - compliant_records: z.int(), - compliant_impressions: z.int(), - non_compliant_records: z.int(), - non_compliant_impressions: z.int(), - not_covered_records: z.int(), - not_covered_impressions: z.int(), - unidentified_records: z.int(), - unidentified_impressions: z.int() - }).passthrough(), - aggregate: z.object({ - score: z.number().optional(), - grade: z.string().optional(), - label: z.string().optional(), - methodology_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional() - }).passthrough().optional(), - authorization_summary: z.object({ - records_checked: z.int(), - impressions_checked: z.int(), - authorized_records: z.int(), - authorized_impressions: z.int(), - unauthorized_records: z.int(), - unauthorized_impressions: z.int(), - unknown_records: z.int(), - unknown_impressions: z.int() - }).passthrough().optional(), - results: z.array(ValidationResultSchema), - validated_at: z.iso.datetime(), - list_resolved_at: z.iso.datetime().optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const CommercialTermsSchema = z.object({ - source_feed_version: z.string().min(1).optional(), - source_pricing_version: z.string().min(1).optional(), - brand: BrandKeySchema, - advertiser_industry: AdvertiserIndustrySchema.optional(), - purchases: z.array(ProductPurchaseSchema.merge(z.object({}).passthrough())), - start_time: StartTimingSchema, - end_time: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time"), - total_budget: z.object({ - amount: z.number().gte(0), - currency: z.string().regex(new RegExp("^[A-Z]{3}$")) - }).passthrough().optional(), - daily_budget_cap: z.number().gte(0).optional(), - budget_cap_timezone: z.string().min(1).optional(), - budget_allocation: CanonicalBudgetAllocationSchema.optional(), - pacing: PacingSchema.optional(), - bidding: BiddingPolicySchema.optional(), - invoice_recipient: BusinessEntitySchema.optional(), - purchase_order_ref: z.string().min(1).max(255).optional(), - agency_estimate_number: z.string().max(100).optional(), - reporting_commitments: z.array(z.object({ - purchase_index: z.number().int().gte(0), - metrics: z.array(CanonicalReportingCommitmentSchema) - }).passthrough()).optional(), - cancellation_terms: z.object({ - effective_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time"), - fee: z.object({ - amount: z.number().gte(0), - currency: z.string().regex(new RegExp("^[A-Z]{3}$")) - }).passthrough().optional(), - reason: z.string().min(1).max(500).optional() - }).passthrough().optional(), - change_terms: z.array(MediaBuyChangeTermSchema).optional() -}).passthrough(); - -// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. -export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposal]-?: undefined extends CanonicalProposal[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, CanonicalProposal & Record> = (() => { - const objectSchema = z.object({ "proposal_id": z.string().min(1).max(255), "proposal_kind": z.enum(["new_media_buy","media_buy_update","media_buy_cancellation"]), "parent_proposal_id": z.string().min(1).max(255).describe("Immediate predecessor this snapshot was forked from. Every proposal produced by refine_proposals carries it, equal to the request's source proposal_id, so negotiation lineage is reconstructible from proposals alone.").optional(), "media_buy_id": z.string().min(1).optional(), "opportunity_id": z.string().regex(new RegExp("^[A-Za-z0-9_.:-]{1,255}$")).min(1).max(255).describe("Buyer planning cycle associated with this proposal. Revisions inherit it; it does not participate in proposal identity.").optional(), "base_media_buy_revision": z.number().int().gte(1).optional(), "proposal_status": z.enum(["draft","committed","accepted"]).describe("draft is indicative and unreserved; committed has firm terms with inventory reserved until expires_at; accepted is the historical snapshot attached to a MediaBuy."), "accepted_at": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "expires_at": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "name": z.string().min(1).max(500), "description": z.string().max(2000).optional(), "brief_alignment": z.string().max(2000).optional(), "commercial_terms": z.object({ "source_feed_version": z.string().min(1).describe("Wholesale product feed version against which direct published offers were accepted. Omitted when the seller authored terms outside a wholesale snapshot.").optional(), "source_pricing_version": z.string().min(1).describe("Pricing-layer version against which published rates were accepted.").optional(), "brand": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery."), "advertiser_industry": z.enum(["automotive","automotive.electric_vehicles","automotive.parts_accessories","automotive.luxury","beauty_cosmetics","beauty_cosmetics.skincare","beauty_cosmetics.fragrance","beauty_cosmetics.haircare","cannabis","cpg","cpg.personal_care","cpg.household","dating","education","education.higher_education","education.online_learning","education.k12","energy_utilities","energy_utilities.renewable","fashion_apparel","fashion_apparel.luxury","fashion_apparel.sportswear","finance","finance.banking","finance.insurance","finance.investment","finance.cryptocurrency","food_beverage","food_beverage.alcohol","food_beverage.restaurants","food_beverage.packaged_goods","gambling_betting","gambling_betting.sports_betting","gambling_betting.casino","gaming","gaming.mobile","gaming.console_pc","gaming.esports","government_nonprofit","government_nonprofit.political","government_nonprofit.charity","healthcare","healthcare.pharmaceutical","healthcare.medical_devices","healthcare.wellness","home_garden","home_garden.furniture","home_garden.home_improvement","media_entertainment","media_entertainment.podcasts","media_entertainment.music","media_entertainment.film_tv","media_entertainment.publishing","media_entertainment.live_events","pets","professional_services","professional_services.legal","professional_services.consulting","real_estate","real_estate.residential","real_estate.commercial","recruitment_hr","retail","retail.ecommerce","retail.department_stores","sports_fitness","sports_fitness.equipment","sports_fitness.teams_leagues","technology","technology.software","technology.hardware","technology.ai_ml","telecom","telecom.mobile_carriers","telecom.internet_providers","transportation_logistics","travel_hospitality","travel_hospitality.airlines","travel_hospitality.hotels","travel_hospitality.cruise","travel_hospitality.tourism"]).describe("Standardized advertiser industry classification. Top-level categories classify the advertiser's primary business. Dot-notation subcategories (e.g., 'media_entertainment.podcasts') provide platform-specific precision where needed. Sellers map these to platform-native codes (Spotify ADV categories, LinkedIn industry IDs, IAB Content Taxonomy, etc.). Sellers MUST accept unknown values gracefully — treat unrecognized values as the parent category (strip the subcategory) or as uncategorized. This ensures forward compatibility as the taxonomy evolves.").optional(), "purchases": z.array(z.intersection(z.object({ "product_id": z.string().min(1), "pricing_option_id": z.string().min(1), "pricing": z.object({ "pricing_option_id": z.string().min(1), "pricing_model": z.enum(["cpm","vcpm","cpc","cpcv","cpv","cpp","cpa","revenue_share","flat_rate","time"]), "currency": z.string().regex(new RegExp("^[A-Z]{3}$")), "fixed_price": z.number().gte(0).optional(), "floor_price": z.number().gte(0).optional(), "price_guidance": z.object({ "p25": z.number().gte(0).describe("25th percentile of recent winning bids").optional(), "p50": z.number().gte(0).describe("Median of recent winning bids").optional(), "p75": z.number().gte(0).describe("75th percentile of recent winning bids").optional(), "p90": z.number().gte(0).describe("90th percentile of recent winning bids").optional() }).catchall(z.any()).describe("Pricing guidance for auction-based bidding. Helps buyers calibrate bids with historical percentiles.").optional(), "min_spend_per_package": z.number().gte(0).optional(), "price_breakdown": z.object({ "list_price": z.number().gt(0).describe("Rate card or base price before any adjustments. The starting point from which fixed_price is derived by applying fee and discount adjustments sequentially."), "adjustments": z.array(z.object({ "kind": z.enum(["fee","discount","commission","settlement"]).describe("Categorizes how a price adjustment affects the transaction"), "name": z.string().max(64).describe("Specific adjustment name. Use well-known values where applicable for interoperability."), "rate": z.number().gt(0).lt(1).describe("Adjustment as a decimal proportion (e.g., 0.15 for 15%). Always positive — kind determines the economic effect. Mutually exclusive with amount.").optional(), "amount": z.number().gt(0).describe("Adjustment as a fixed monetary amount in the pricing option's currency. Always positive — kind determines the economic effect. Mutually exclusive with rate.").optional(), "description": z.string().max(256).describe("Human-readable description of this adjustment (e.g., 'Malstaffel 12x', '2% Skonto 10 Tage')").optional(), "beneficiary": z.string().max(256).describe("Identifies who receives this adjustment's value. For commissions, the intermediary (e.g., a sellers.json domain, an AdCP account ID, or a human-readable party name). Optional but recommended for multi-intermediary transparency.").optional() }).catchall(z.any()).and(z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "rate": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "amount": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]; + })).describe("Discriminated reference to a product format option. The global canonical shape is still named by `format_kind`; this reference selects one concrete product `format_options[]` entry. `scope: \"publisher\"` identifies a publisher-declared catalog option by `{ publisher_domain, format_option_id }`. `scope: \"product\"` identifies a product-local option by `format_option_id`; the enclosing package/product context supplies the namespace.")).min(1).describe("Canonical format options selected from the published product offer. Legacy named-format identifiers are not accepted.").optional(), "catalog_ids": z.array(z.string().min(1)).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Previously synchronized account catalog IDs promoted by this selection. Callers manage catalog bodies through sync_catalogs rather than inlining them here.").optional(), "budget": z.number().gte(0).describe("Hard spend cap for this selection in the media-buy currency.").optional(), "daily_budget_cap": z.number().gte(0).describe("Optional hard daily spend ceiling for this purchase. It is subordinate to the media-buy aggregate daily cap and is not a reserved daily allocation. Its day boundary is the media buy's budget_cap_timezone.").optional(), "min_spend_target": z.number().gte(0).describe("Soft lifetime spend target for seller-optimized allocation.").optional(), "impressions": z.number().gte(0).optional(), "start_time": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "end_time": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "pacing": z.enum(["even","asap","front_loaded"]).describe("Budget pacing strategy").optional(), "bidding": z.object({ "automatic": z.literal(true).describe("Explicitly use seller/provider automatic bidding at this authored scope. At package scope this is a complete override of a media-buy policy, not inheritance. It MUST be the only field in the block and MUST be preserved on readback.").optional(), "bid_amount": z.number().gt(0).describe("Manual auction bid denominated in the media-buy currency and expressed per the selected pricing option's auction unit. For example, a CPM option interprets the amount per thousand impressions. This is the amount submitted to the auction, not a promise that the clearing price equals it. Requires an auction-priced pricing option whose currency equals the media-buy currency.").optional(), "max_bid": z.number().gt(0).describe("Hard per-auction ceiling denominated in the media-buy currency and expressed per the selected pricing option's auction unit. This is the only canonical hard auction ceiling and MUST NOT be translated into an average outcome-cost control. Requires an auction-priced pricing option whose currency equals the media-buy currency. May stand alone or supplement cost_per/roas only when the relevant scope capability advertises that combination.").optional(), "cost_per": z.object({ "amount": z.number().gt(0).describe("Average cost amount per scope-bound primary-goal result, denominated in the media-buy currency."), "strength": z.enum(["cap","target"]).describe("`cap` optimizes for an average at or below the amount and accepts underdelivery when necessary; `target` optimizes around the amount while balancing volume and spend. Neither is a per-result or per-auction guarantee.") }).passthrough().describe("Average cost control per result of the scope-bound primary optimization goal. At seller-optimized media-buy scope it binds to budget_allocation.optimization_goals; at package scope it binds to that package's optimization_goals; at fixed media-buy scope it binds independently to each inheriting package and is valid only when their primary-goal result units are compatible. Metric goals are compatible only when metric and every result-defining qualifier match; vendor_metric goals only when vendor and metric_id match; event goals only when the event_type/custom_event_name set and resolved attribution_window match. Primary is the earliest array entry among goals tied for the lowest explicit numeric priority; unprioritized goals follow explicitly prioritized goals; when all priorities are absent, the first entry is primary.").optional(), "roas": z.object({ "value": z.number().gt(0).describe("Return per unit of ad spend; 4 means 4 units of value per 1 unit spent."), "strength": z.enum(["floor","target"]).describe("`floor` prefers underdelivery to knowingly optimizing below the requested return; `target` optimizes around the requested return. Neither guarantees realized return.") }).passthrough().describe("Dimensionless return-on-ad-spend control bound to the same scope-specific primary goal rules as cost_per. The bound goal must be value-bearing; a fixed media-buy default requires a value-bearing primary goal on every inheriting package. Every referenced value-bearing event source MUST declare value_currencies containing the media-buy currency. The seller validates this at buy creation; each buy consumes only exact-currency records, while other declared currencies remain available to other buys. Sellers MUST NOT perform currency conversion.").optional() }).passthrough().and(z.any().refine((value) => !z.union([z.object({ "automatic": z.any().refine((value) => value !== undefined, "Required"), "bid_amount": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "automatic": z.any().refine((value) => value !== undefined, "Required"), "max_bid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "automatic": z.any().refine((value) => value !== undefined, "Required"), "cost_per": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "automatic": z.any().refine((value) => value !== undefined, "Required"), "roas": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "bid_amount": z.any().refine((value) => value !== undefined, "Required"), "max_bid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "bid_amount": z.any().refine((value) => value !== undefined, "Required"), "cost_per": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "bid_amount": z.any().refine((value) => value !== undefined, "Required"), "roas": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "cost_per": z.any().refine((value) => value !== undefined, "Required"), "roas": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]).safeParse(value).success, "Invalid input: Should NOT be valid against schema")).describe("Buyer-authored execution policy for automatic delivery, auction bidding, average outcome cost, or return on ad spend. The containing object determines authored scope: media-buy `bidding` is a complete inherited default and package `bidding` is a complete package override. Sellers MUST preserve authored scope on readback and MUST NOT copy an inherited media-buy policy into package `bidding`. Every monetary field in this block is denominated in the media-buy currency; the selected pricing option supplies the auction unit, never another denomination. Auction-unit identity is the pricing_model plus every canonical billing-event qualifier after defaults are applied: for example CPV view threshold, CPP demographic system/demographic, CPA event tuple, time time_unit, and flat-rate/DOOH parameters. An extension qualifier participates only when its registered extension specification explicitly defines how it contributes to auction-unit identity. A media-buy bid_amount or max_bid is valid only when every inheriting package resolves the same auction-unit identity. Every affected pricing option MUST use the media-buy currency; split currency-mismatched packages into separate buys. Seller-optimized media-buy cost_per/roas bind to the primary budget_allocation.optimization_goals goal. Package-authored cost_per/roas bind to the package primary optimization goal. The primary goal is the earliest array entry among goals with the lowest explicit numeric priority; unprioritized goals follow explicitly prioritized goals; when all priorities are absent, the first entry is primary. In fixed allocation, an inherited media-buy cost_per is valid only when all inheriting packages have compatible primary-goal result units; inherited roas requires value-bearing primary goals on every inheriting package. Canonical ROAS requires each value-bearing event source to declare the media-buy currency in value_currencies; each buy consumes only exact-currency records and sellers MUST NOT convert them. Absence invokes inheritance or provider automatic delivery; `{automatic:true}` is an explicit authored policy that overrides inheritance. Sellers MUST reject unsupported modes, combinations, units, currency, goal bindings, or native placements before any provider mutation and MUST NOT silently translate semantics.").refine((value) => Object.keys(value).length >= 1, "Object must contain at least 1 property").optional(), "targeting_overlay": z.object({ "geo_countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).describe("Restrict delivery to specific countries. ISO 3166-1 alpha-2 codes (e.g., 'US', 'GB', 'DE').").optional(), "geo_countries_exclude": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).describe("Exclude specific countries from delivery. ISO 3166-1 alpha-2 codes (e.g., 'US', 'GB', 'DE').").optional(), "geo_regions": z.array(z.string().regex(new RegExp("^[A-Z]{2}-[A-Z0-9]{1,3}$"))).min(1).describe("Restrict delivery to exact canonical ISO 3166-2 subdivisions (states, provinces, regions, departments, or other subdivision categories). Unknown identifiers are invalid. At create or update, sellers MUST reject unsupported identifiers and MUST NOT silently widen, drop, or partially apply the list. During get_products, a seller may instead return a sparse, buyer-reviewable targeting_resolution modification for a valid but unsupported requested outcome. Exact internal translation preserves accepted identifiers in package readback.").optional(), "geo_regions_exclude": z.array(z.string().regex(new RegExp("^[A-Z]{2}-[A-Z0-9]{1,3}$"))).min(1).describe("Exclude exact canonical ISO 3166-2 subdivisions. Support is independent from geo_regions inclusion support. Unknown identifiers and values also present in geo_regions are invalid. At create or update, sellers MUST reject unsupported identifiers and partial application; during get_products, a seller may instead return a sparse, buyer-reviewable targeting_resolution modification for a valid but unsupported requested outcome.").optional(), "geo_metros": z.array(z.object({ "system": z.enum(["nielsen_dma","uk_itl1","uk_itl2","eurostat_nuts2","custom"]).describe("Metro area classification system (e.g., 'nielsen_dma', 'uk_itl2')"), "values": z.array(z.string()).min(1).describe("Metro codes within the system (e.g., ['501', '602'] for Nielsen DMAs)") }).passthrough().describe("A targeted metro area.")).min(1).describe("Restrict delivery to specific metro areas. Each entry specifies the classification system and target values. Seller must declare supported systems in get_adcp_capabilities.").optional(), "geo_metros_exclude": z.array(z.object({ "system": z.enum(["nielsen_dma","uk_itl1","uk_itl2","eurostat_nuts2","custom"]).describe("Metro area classification system (e.g., 'nielsen_dma', 'uk_itl2')"), "values": z.array(z.string()).min(1).describe("Metro codes to exclude within the system (e.g., ['501', '602'] for Nielsen DMAs)") }).passthrough()).min(1).describe("Exclude specific metro areas from delivery. Each entry specifies the classification system and excluded values. Seller must declare supported systems in get_adcp_capabilities.").optional(), "geo_postal_areas": z.array(z.union([z.object({ "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code for the postal values."), "system": z.enum(["postal_code","zip","zip_plus_four","outward","full","fsa","plz","code_postal","postcode","cep","pin","custom","us_zip","us_zip_plus_four","gb_outward","gb_full","ca_fsa","ca_full","de_plz","fr_code_postal","au_postcode","ch_plz","at_plz"]).describe("Country-local postal code system."), "values": z.array(z.string()).min(1).describe("Postal codes within the country and system.") }).passthrough().and(z.object({ "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code."), "system": z.enum(["postal_code","zip","zip_plus_four","outward","full","fsa","plz","code_postal","postcode","cep","pin","custom","us_zip","us_zip_plus_four","gb_outward","gb_full","ca_fsa","ca_full","de_plz","fr_code_postal","au_postcode","ch_plz","at_plz"]).describe("Country-local postal code system.") }).and(z.union([z.object({ "country": z.literal("US").optional(), "system": z.enum(["zip","zip_plus_four"]).optional() }), z.object({ "country": z.literal("GB").optional(), "system": z.enum(["outward","full"]).optional() }), z.object({ "country": z.literal("CA").optional(), "system": z.enum(["fsa","full"]).optional() }), z.object({ "country": z.enum(["DE","CH","AT"]).optional(), "system": z.literal("plz").optional() }), z.object({ "country": z.literal("FR").optional(), "system": z.literal("code_postal").optional() }), z.object({ "country": z.literal("AU").optional(), "system": z.literal("postcode").optional() }), z.object({ "country": z.literal("BR").optional(), "system": z.literal("cep").optional() }), z.object({ "country": z.literal("IN").optional(), "system": z.literal("pin").optional() }), z.object({ "country": z.literal("ZA").optional(), "system": z.literal("postal_code").optional() }), z.object({ "country": z.any().refine((value) => !z.enum(["US","GB","CA","DE","CH","AT","FR","AU","BR","IN","ZA"]).safeParse(value).success, "Invalid input: Should NOT be valid against schema").optional(), "system": z.enum(["postal_code","custom"]).optional() })])).describe("Valid country-local postal system pairing. Registered countries only accept their registered local systems; countries without a registered local system use postal_code or custom.")), z.object({ "system": z.enum(["us_zip","us_zip_plus_four","gb_outward","gb_full","ca_fsa","ca_full","de_plz","fr_code_postal","au_postcode","ch_plz","at_plz"]).describe("Deprecated country-fused postal code system (e.g., 'us_zip', 'gb_outward'). Prefer country + postal-system."), "values": z.array(z.string()).min(1).describe("Postal codes within the legacy system.") }).passthrough()]).describe("Postal area values. Prefer the native country + postal system form. Deprecated legacy country-fused postal-system tokens remain accepted for compatibility.")).min(1).describe("Restrict delivery to specific postal areas. Prefer the native country + postal system form. The deprecated legacy country-fused postal-system tokens remain accepted for compatibility. Seller must declare supported systems in get_adcp_capabilities.").optional(), "geo_postal_areas_exclude": z.array(z.union([z.object({ "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code for the postal values."), "system": z.enum(["postal_code","zip","zip_plus_four","outward","full","fsa","plz","code_postal","postcode","cep","pin","custom","us_zip","us_zip_plus_four","gb_outward","gb_full","ca_fsa","ca_full","de_plz","fr_code_postal","au_postcode","ch_plz","at_plz"]).describe("Country-local postal code system."), "values": z.array(z.string()).min(1).describe("Postal codes within the country and system.") }).passthrough().and(z.object({ "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code."), "system": z.enum(["postal_code","zip","zip_plus_four","outward","full","fsa","plz","code_postal","postcode","cep","pin","custom","us_zip","us_zip_plus_four","gb_outward","gb_full","ca_fsa","ca_full","de_plz","fr_code_postal","au_postcode","ch_plz","at_plz"]).describe("Country-local postal code system.") }).and(z.union([z.object({ "country": z.literal("US").optional(), "system": z.enum(["zip","zip_plus_four"]).optional() }), z.object({ "country": z.literal("GB").optional(), "system": z.enum(["outward","full"]).optional() }), z.object({ "country": z.literal("CA").optional(), "system": z.enum(["fsa","full"]).optional() }), z.object({ "country": z.enum(["DE","CH","AT"]).optional(), "system": z.literal("plz").optional() }), z.object({ "country": z.literal("FR").optional(), "system": z.literal("code_postal").optional() }), z.object({ "country": z.literal("AU").optional(), "system": z.literal("postcode").optional() }), z.object({ "country": z.literal("BR").optional(), "system": z.literal("cep").optional() }), z.object({ "country": z.literal("IN").optional(), "system": z.literal("pin").optional() }), z.object({ "country": z.literal("ZA").optional(), "system": z.literal("postal_code").optional() }), z.object({ "country": z.any().refine((value) => !z.enum(["US","GB","CA","DE","CH","AT","FR","AU","BR","IN","ZA"]).safeParse(value).success, "Invalid input: Should NOT be valid against schema").optional(), "system": z.enum(["postal_code","custom"]).optional() })])).describe("Valid country-local postal system pairing. Registered countries only accept their registered local systems; countries without a registered local system use postal_code or custom.")), z.object({ "system": z.enum(["us_zip","us_zip_plus_four","gb_outward","gb_full","ca_fsa","ca_full","de_plz","fr_code_postal","au_postcode","ch_plz","at_plz"]).describe("Deprecated country-fused postal code system (e.g., 'us_zip', 'gb_outward'). Prefer country + postal-system."), "values": z.array(z.string()).min(1).describe("Postal codes within the legacy system.") }).passthrough()]).describe("Postal area values. Prefer the native country + postal system form. Deprecated legacy country-fused postal-system tokens remain accepted for compatibility.")).min(1).describe("Exclude specific postal areas from delivery. Prefer the native country + postal system form. The deprecated legacy country-fused postal-system tokens remain accepted for compatibility. Seller must declare supported systems in get_adcp_capabilities.").optional(), "geo_places": z.array(z.object({ "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code containing the place."), "system": z.union([z.enum(["geonames","google_ads","microsoft_ads"]), z.string().refine(adcpJsonSchemaUri, "Invalid URI").regex(new RegExp("^https://"))]).describe("Collision-safe identifier namespace for geographic places. Registered tokens have protocol-defined semantics. Unregistered systems MUST use an absolute HTTPS URI controlled by the catalog owner; consumers compare URI systems as exact opaque strings."), "system_version": z.string().min(1).describe("Optional exact catalog version from the seller's declared supported_versions. When omitted, the seller applies catalog.current_version and MUST echo that version on persisted package state.").optional(), "place_type": z.union([z.enum(["airport","borough","city","city_region","commune","county","district","municipality","neighborhood","post_town","prefecture","province","quarter","state","territory","ward"]), z.string().refine(adcpJsonSchemaUri, "Invalid URI").regex(new RegExp("^https://"))]).describe("Canonical place classification. Registered tokens have protocol-defined meanings. Catalog-specific classifications without a registered mapping MUST use an absolute HTTPS URI controlled by the vocabulary owner; consumers compare URI types as exact opaque strings."), "values": z.array(z.string().min(1)).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Stable place identifiers in the declared system. Display names are not valid targeting values."), "value_labels": z.record(z.string(), z.string().min(1)).describe("Optional human-readable diagnostic labels keyed by identifiers present in values. Extra keys are a conformance error. Labels are non-authoritative and MUST NOT be used to resolve or apply targeting.").optional(), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough().and(z.union([z.any().refine((value) => !z.object({ "system": z.enum(["geonames","google_ads","microsoft_ads"]) }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "system": z.enum(["geonames","google_ads","microsoft_ads"]) }), z.object({ "values": z.any().optional() }))])).describe("A catalog-backed named place target. Values are stable identifiers in the declared system. Entries within geo_places form a union; different geographic inclusion dimensions intersect. value_labels are diagnostic only and MUST NOT be used to resolve targeting.")).min(1).describe("Restrict delivery to catalog-backed named places. Values MUST be stable identifiers in the declared system, not display names. Sellers must declare supported systems, countries, and place types in get_adcp_capabilities and reject unsupported entries rather than silently dropping them.").optional(), "geo_places_exclude": z.array(z.object({ "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code containing the place."), "system": z.union([z.enum(["geonames","google_ads","microsoft_ads"]), z.string().refine(adcpJsonSchemaUri, "Invalid URI").regex(new RegExp("^https://"))]).describe("Collision-safe identifier namespace for geographic places. Registered tokens have protocol-defined semantics. Unregistered systems MUST use an absolute HTTPS URI controlled by the catalog owner; consumers compare URI systems as exact opaque strings."), "system_version": z.string().min(1).describe("Optional exact catalog version from the seller's declared supported_versions. When omitted, the seller applies catalog.current_version and MUST echo that version on persisted package state.").optional(), "place_type": z.union([z.enum(["airport","borough","city","city_region","commune","county","district","municipality","neighborhood","post_town","prefecture","province","quarter","state","territory","ward"]), z.string().refine(adcpJsonSchemaUri, "Invalid URI").regex(new RegExp("^https://"))]).describe("Canonical place classification. Registered tokens have protocol-defined meanings. Catalog-specific classifications without a registered mapping MUST use an absolute HTTPS URI controlled by the vocabulary owner; consumers compare URI types as exact opaque strings."), "values": z.array(z.string().min(1)).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Stable place identifiers in the declared system. Display names are not valid targeting values."), "value_labels": z.record(z.string(), z.string().min(1)).describe("Optional human-readable diagnostic labels keyed by identifiers present in values. Extra keys are a conformance error. Labels are non-authoritative and MUST NOT be used to resolve or apply targeting.").optional(), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough().and(z.union([z.any().refine((value) => !z.object({ "system": z.enum(["geonames","google_ads","microsoft_ads"]) }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "system": z.enum(["geonames","google_ads","microsoft_ads"]) }), z.object({ "values": z.any().optional() }))])).describe("A catalog-backed named place target. Values are stable identifiers in the declared system. Entries within geo_places form a union; different geographic inclusion dimensions intersect. value_labels are diagnostic only and MUST NOT be used to resolve targeting.")).min(1).describe("Exclude catalog-backed named places. Uses the same identifier-based shape as geo_places. Sellers MUST reject overlap with geo_places for the same country, system, place_type, and value.").optional(), "daypart_targets": z.array(z.object({ "days": z.array(z.enum(["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]).describe("Days of the week for daypart targeting")).min(1).describe("Days of week this window applies to. Use multiple days for compact targeting (e.g., monday-friday in one object)."), "start_hour": z.number().int().gte(0).lte(23).describe("Start hour (inclusive), 0-23 in 24-hour format. 0 = midnight, 6 = 6:00am, 18 = 6:00pm."), "end_hour": z.number().int().gte(1).lte(24).describe("End hour (exclusive), 1-24 in 24-hour format. 10 = 10:00am, 24 = midnight. Must be greater than start_hour."), "timezone": z.union([z.literal("inventory_local"), z.any().refine((value) => !z.literal("inventory_local").safeParse(value).success, "Invalid input: Should NOT be valid against schema").describe("Concrete timezone identifier in the implementation's supported IANA Time Zone Database, such as America/New_York, CET, or UTC.")]).describe("Civil-time clock used to evaluate this window. 'inventory_local' evaluates the hours in the seller-assigned local timezone of each inventory unit that can deliver the impression, such as a screen, venue, station, or publisher property; it never means the buyer, account, or server timezone. A concrete IANA timezone identifier (for example, 'America/New_York', 'CET', or 'UTC') evaluates one shared civil-time clock across the targeted inventory. Omission defaults to 'inventory_local'. Buyers that begin with a user or account preference MUST resolve it to a concrete IANA identifier before sending the daypart; 'user_timezone' and 'account_timezone' are not wire values. For each candidate delivery instant, convert the instant into this clock and compare its resulting local day and hour with the half-open window: a skipped DST hour has no matching instants, while both occurrences of a repeated hour match. This delivery clock is independent of reporting_capabilities.timezone.").default("inventory_local"), "label": z.string().describe("Optional human-readable name for this time window (e.g., 'Morning Drive', 'Prime Time')").optional() }).passthrough().describe("A time window for daypart targeting. Specifies days of week, an hour range, and the civil-time clock used to evaluate it. start_hour is inclusive, end_hour is exclusive (e.g., 6-10 = 6:00am to 10:00am). Follows the Google Ads AdScheduleInfo / DV360 DayPartTargeting pattern.")).min(1).describe("Restrict delivery to specific time windows. Each entry specifies days of week, an hour range, and an optional timezone that defaults to inventory_local. A concrete IANA zone uses one shared civil-time clock, while inventory_local evaluates each inventory unit in its seller-assigned local timezone. Entries are independent and MAY use different clocks.").optional(), "axe_include_segment": z.string().describe("Deprecated: Use TMP provider fields instead. AXE segment ID to include for targeting.").optional(), "axe_exclude_segment": z.string().describe("Deprecated: Use TMP provider fields instead. AXE segment ID to exclude from targeting.").optional(), "audience_include": z.array(z.string()).min(1).describe("Restrict delivery to members of these first-party CRM audiences. Only users present in the uploaded lists are eligible. References audience_id values from sync_audiences on the same seller account — audience IDs are not portable across sellers. Not for lookalike expansion — express that intent in the campaign brief. Seller must declare support in get_adcp_capabilities.").optional(), "audience_exclude": z.array(z.string()).min(1).describe("Suppress delivery to members of these first-party CRM audiences. Matched users are excluded regardless of other targeting. References audience_id values from sync_audiences on the same seller account — audience IDs are not portable across sellers. Seller must declare support in get_adcp_capabilities.").optional(), "signal_targeting_groups": z.object({ "operator": z.literal("all").describe("Groups-level operator. Required even though v1 only supports 'all': every child group must be satisfied."), "groups": z.array(z.object({ "operator": z.enum(["any","none"]).describe("How to evaluate the signals in this group. 'any' is an OR include group. 'none' is an exclusion group equivalent to NOT (A OR B OR C)."), "signals": z.array(z.object({ "pricing_option_id": z.string().describe("Pricing option selected for this signal. Use the pricing_option_id from the product's signal_targeting_options entry when product-scoped pricing is present; otherwise use the seller get_signals pricing only when the product option does not override it. Required when the selected signal has pricing_options; omit only when the signal is bundled into the product price or has no incremental cost.").optional(), "signal_agent_segment_id": z.string().describe("Optional opaque resolved-segment or seller execution handle for this signal. Omit when signal_ref plus the value expression is sufficient for the seller to resolve the signal. Include when the product option exposes a separate runtime or activation handle, and pass it verbatim. Buyers SHOULD prefer an exposed segment handle over reconstructing condition identity from categorical values because the handle can carry provider namespace and methodology distinctions.").optional(), "activation_key": z.record(z.string(), z.any()).and(z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "type": z.literal("segment_id").describe("Segment ID based targeting"), "segment_id": z.string().describe("The platform-specific segment identifier to use in campaign targeting") }).catchall(z.any()), z.object({ "type": z.literal("key_value").describe("Key-value pair based targeting"), "key": z.string().describe("The targeting parameter key"), "value": z.string().describe("The targeting parameter value") }).catchall(z.any())]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17083,8 +15042,9 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - }))).min(1).max(20).describe("Ordered list of price adjustments. Fee and discount adjustments walk list_price to fixed_price — fees increase the running price, discounts reduce it. Commission and settlement adjustments are disclosed for transparency but do not affect the buyer's committed price.") }).catchall(z.any()).describe("Breaks down the composition of fixed_price from a list (rate card) price through adjustments. Adjustments fall into four kinds: fees (increase buyer price), discounts (reduce buyer price), commissions (revenue splits that don't affect buyer price), and settlement terms (applied at invoicing). The invariant is: list_price with all fee and discount adjustments applied sequentially equals fixed_price. Fees increase the running price; discounts reduce it. This invariant applies only when fixed_price is present on the parent object; on auction-based packages the breakdown is informational only. All monetary values are rounded to currency precision at each step. Budgets are always denominated at the fixed_price level, inclusive of commissions.").optional(), "eligible_adjustments": z.array(z.enum(["fee","discount","commission","settlement"]).describe("Categorizes how a price adjustment affects the transaction")).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").optional(), "parameters": z.record(z.string(), z.any()).optional(), "event_type": z.enum(["page_view","view_content","select_content","select_item","search","share","add_to_cart","remove_from_cart","viewed_cart","add_to_wishlist","initiate_checkout","add_payment_info","purchase","refund","lead","qualify_lead","close_convert_lead","disqualify_lead","complete_registration","subscribe","follow","content_view","watch_milestone","start_trial","app_install","app_launch","contact","schedule","donate","submit_application","custom"]).describe("Standard marketing event types for event logging, aligned with IAB ECAPI").optional(), "custom_event_name": z.string().min(1).optional(), "event_source_id": z.string().min(1).optional(), "commission_rate": z.number().gt(0).lte(1).optional(), "commission_basis_description": z.string().min(1).max(1000).optional() }).passthrough().and(z.intersection(z.intersection(z.any().refine((value) => !z.object({ "fixed_price": z.any().refine((value) => value !== undefined, "Required"), "floor_price": z.any().refine((value) => value !== undefined, "Required") }).passthrough().safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.union([z.any().refine((value) => !z.object({ "pricing_model": z.literal("cpa") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "pricing_model": z.literal("cpa") }), z.object({ "event_type": z.any().refine((value) => value !== undefined, "Required"), "fixed_price": z.any().refine((value) => value !== undefined, "Required") }).passthrough())])), z.intersection(z.union([z.any().refine((value) => !z.object({ "pricing_model": z.literal("revenue_share") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "pricing_model": z.literal("revenue_share") }), z.object({ "event_type": z.any().refine((value) => value !== undefined, "Required"), "event_source_id": z.any().refine((value) => value !== undefined, "Required"), "commission_rate": z.any().refine((value) => value !== undefined, "Required"), "commission_basis_description": z.any().refine((value) => value !== undefined, "Required") }).passthrough())]), z.intersection(z.union([z.any().refine((value) => !z.object({ "pricing_model": z.enum(["cpv","cpp","time"]) }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "pricing_model": z.enum(["cpv","cpp","time"]) }), z.object({ "parameters": z.any().refine((value) => value !== undefined, "Required") }).passthrough())]), z.union([z.any().refine((value) => !z.object({ "event_type": z.literal("custom") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "event_type": z.literal("custom") }), z.object({ "custom_event_name": z.any().refine((value) => value !== undefined, "Required") }).passthrough())]))))).describe("Resolved selected pricing terms. Optional on buy_products input, where pricing_option_id plus the versioned feed identifies the offer; required inside accepted commercial_terms. Its pricing_option_id MUST match the sibling field.").optional(), "format_option_refs": z.array(z.record(z.string(), z.any()).and(z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "scope": z.literal("publisher").describe("Reference resolves against the named publisher's adagents.json top-level `formats[]` catalog."), "publisher_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Publisher domain where the adagents.json declaring this format option is hosted."), "format_option_id": z.string().describe("Stable format option ID from the publisher's adagents.json top-level `formats[]`, matching a publisher-catalog-backed entry in the target product's `format_options[]`.") }).catchall(z.any()).describe("Selects a publisher-catalog-backed product format option by publisher domain and format option ID."), z.object({ "scope": z.literal("product").describe("Reference resolves only against the target product's inline `format_options[]`."), "format_option_id": z.string().describe("Stable format option ID from the target product's inline `format_options[]`."), "publisher_domain": z.never().optional() }).catchall(z.any()).describe("Selects a product-local format option by ID within the enclosing package/product context. This branch deliberately forbids `publisher_domain` (`publisher_domain: false` in the schema) because product-local references are namespaced by the enclosing product only; include `scope: \"publisher\"` when the selector must cross into a publisher catalog.")]; + })).describe("Destination-specific activation key returned by get_signals or activate_signal. Usually omitted for seller-offered signals selected directly through the same seller; include only when the selected signal was separately activated and the seller requires the activation key to correlate the package selection.").optional() }).catchall(z.any()).and(z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "signal_ref": z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "scope": z.literal("product").describe("Discriminator indicating the signal resolves through the selected product's included_signals or signal_targeting_options."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Product-local signal identifier. For local signals exposed on both get_signals and get_products, this MUST match get_signals.signals[].signal_ref.signal_id for the same signal.") }).catchall(z.any()).describe("Product-scoped signal. The signal_id is meaningful only within the selected product/package context and MUST match a Product.included_signals[].signal_ref.signal_id or Product.signal_targeting_options[].signal_ref.signal_id for that product, depending on whether the signal is descriptive or selectable."), z.object({ "scope": z.literal("data_provider").describe("Discriminator indicating the signal resolves through a data provider's published adagents.json signals[]."), "data_provider_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that publishes the signal definition in its adagents.json signals[]."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the data provider's published adagents.json signals[].") }).catchall(z.any()).describe("Data-provider-scoped signal. The signal_id resolves through the data provider's published adagents.json signals[] and can be authorization-verified there."), z.object({ "scope": z.literal("signal_source").describe("Discriminator indicating the signal resolves through the issuing signal source."), "signal_source_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the signal source that issues this source-native signal."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the issuing signal source's signal set.") }).catchall(z.any()).describe("Signal-source-scoped signal. Use this for source-native signals that are not published in upstream adagents.json signals[]. The buyer trusts the issuing signal source for this identity; use scope 'data_provider' instead when the signal is published in adagents.json signals[], even if the publisher is also the seller or signal source.")]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17115,8 +15075,8 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - })).describe("Discriminated reference to a product format option. The global canonical shape is still named by `format_kind`; this reference selects one concrete product `format_options[]` entry. `scope: \"publisher\"` identifies a publisher-declared catalog option by `{ publisher_domain, format_option_id }`. `scope: \"product\"` identifies a product-local option by `format_option_id`; the enclosing package/product context supplies the namespace.")).min(1).describe("Canonical format options selected from the published product offer. Legacy named-format identifiers are not accepted.").optional(), "catalog_ids": z.array(z.string().min(1)).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Previously synchronized account catalog IDs promoted by this selection. Callers manage catalog bodies through sync_catalogs rather than inlining them here.").optional(), "budget": z.number().gte(0).describe("Hard spend cap for this selection in the media-buy currency.").optional(), "daily_budget_cap": z.number().gte(0).describe("Optional hard daily spend ceiling for this purchase. It is subordinate to the media-buy aggregate daily cap and is not a reserved daily allocation. Its day boundary is the media buy's budget_cap_timezone.").optional(), "min_spend_target": z.number().gte(0).describe("Soft lifetime spend target for seller-optimized allocation.").optional(), "impressions": z.number().gte(0).optional(), "start_time": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "end_time": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "pacing": z.enum(["even","asap","front_loaded"]).describe("Budget pacing strategy").optional(), "bidding": z.object({ "automatic": z.literal(true).describe("Explicitly use seller/provider automatic bidding at this authored scope. At package scope this is a complete override of a media-buy policy, not inheritance. It MUST be the only field in the block and MUST be preserved on readback.").optional(), "bid_amount": z.number().gt(0).describe("Manual auction bid denominated in the media-buy currency and expressed per the selected pricing option's auction unit. For example, a CPM option interprets the amount per thousand impressions. This is the amount submitted to the auction, not a promise that the clearing price equals it. Requires an auction-priced pricing option whose currency equals the media-buy currency.").optional(), "max_bid": z.number().gt(0).describe("Hard per-auction ceiling denominated in the media-buy currency and expressed per the selected pricing option's auction unit. This is the only canonical hard auction ceiling and MUST NOT be translated into an average outcome-cost control. Requires an auction-priced pricing option whose currency equals the media-buy currency. May stand alone or supplement cost_per/roas only when the relevant scope capability advertises that combination.").optional(), "cost_per": z.object({ "amount": z.number().gt(0).describe("Average cost amount per scope-bound primary-goal result, denominated in the media-buy currency."), "strength": z.enum(["cap","target"]).describe("`cap` optimizes for an average at or below the amount and accepts underdelivery when necessary; `target` optimizes around the amount while balancing volume and spend. Neither is a per-result or per-auction guarantee.") }).passthrough().describe("Average cost control per result of the scope-bound primary optimization goal. At seller-optimized media-buy scope it binds to budget_allocation.optimization_goals; at package scope it binds to that package's optimization_goals; at fixed media-buy scope it binds independently to each inheriting package and is valid only when their primary-goal result units are compatible. Metric goals are compatible only when metric and every result-defining qualifier match; vendor_metric goals only when vendor and metric_id match; event goals only when the event_type/custom_event_name set and resolved attribution_window match. Primary is the earliest array entry among goals tied for the lowest explicit numeric priority; unprioritized goals follow explicitly prioritized goals; when all priorities are absent, the first entry is primary.").optional(), "roas": z.object({ "value": z.number().gt(0).describe("Return per unit of ad spend; 4 means 4 units of value per 1 unit spent."), "strength": z.enum(["floor","target"]).describe("`floor` prefers underdelivery to knowingly optimizing below the requested return; `target` optimizes around the requested return. Neither guarantees realized return.") }).passthrough().describe("Dimensionless return-on-ad-spend control bound to the same scope-specific primary goal rules as cost_per. The bound goal must be value-bearing; a fixed media-buy default requires a value-bearing primary goal on every inheriting package. Every referenced value-bearing event source MUST declare value_currencies containing the media-buy currency. The seller validates this at buy creation; each buy consumes only exact-currency records, while other declared currencies remain available to other buys. Sellers MUST NOT perform currency conversion.").optional() }).passthrough().and(z.any().refine((value) => !z.union([z.object({ "automatic": z.any().refine((value) => value !== undefined, "Required"), "bid_amount": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "automatic": z.any().refine((value) => value !== undefined, "Required"), "max_bid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "automatic": z.any().refine((value) => value !== undefined, "Required"), "cost_per": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "automatic": z.any().refine((value) => value !== undefined, "Required"), "roas": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "bid_amount": z.any().refine((value) => value !== undefined, "Required"), "max_bid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "bid_amount": z.any().refine((value) => value !== undefined, "Required"), "cost_per": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "bid_amount": z.any().refine((value) => value !== undefined, "Required"), "roas": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "cost_per": z.any().refine((value) => value !== undefined, "Required"), "roas": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]).safeParse(value).success, "Invalid input: Should NOT be valid against schema")).describe("Buyer-authored execution policy for automatic delivery, auction bidding, average outcome cost, or return on ad spend. The containing object determines authored scope: media-buy `bidding` is a complete inherited default and package `bidding` is a complete package override. Sellers MUST preserve authored scope on readback and MUST NOT copy an inherited media-buy policy into package `bidding`. Every monetary field in this block is denominated in the media-buy currency; the selected pricing option supplies the auction unit, never another denomination. Auction-unit identity is the pricing_model plus every canonical billing-event qualifier after defaults are applied: for example CPV view threshold, CPP demographic system/demographic, CPA event tuple, time time_unit, and flat-rate/DOOH parameters. An extension qualifier participates only when its registered extension specification explicitly defines how it contributes to auction-unit identity. A media-buy bid_amount or max_bid is valid only when every inheriting package resolves the same auction-unit identity. Every affected pricing option MUST use the media-buy currency; split currency-mismatched packages into separate buys. Seller-optimized media-buy cost_per/roas bind to the primary budget_allocation.optimization_goals goal. Package-authored cost_per/roas bind to the package primary optimization goal. The primary goal is the earliest array entry among goals with the lowest explicit numeric priority; unprioritized goals follow explicitly prioritized goals; when all priorities are absent, the first entry is primary. In fixed allocation, an inherited media-buy cost_per is valid only when all inheriting packages have compatible primary-goal result units; inherited roas requires value-bearing primary goals on every inheriting package. Canonical ROAS requires each value-bearing event source to declare the media-buy currency in value_currencies; each buy consumes only exact-currency records and sellers MUST NOT convert them. Absence invokes inheritance or provider automatic delivery; `{automatic:true}` is an explicit authored policy that overrides inheritance. Sellers MUST reject unsupported modes, combinations, units, currency, goal bindings, or native placements before any provider mutation and MUST NOT silently translate semantics.").refine((value) => Object.keys(value).length >= 1, "Object must contain at least 1 property").optional(), "targeting_overlay": z.object({ "geo_countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).describe("Restrict delivery to specific countries. ISO 3166-1 alpha-2 codes (e.g., 'US', 'GB', 'DE').").optional(), "geo_countries_exclude": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).describe("Exclude specific countries from delivery. ISO 3166-1 alpha-2 codes (e.g., 'US', 'GB', 'DE').").optional(), "geo_regions": z.array(z.string().regex(new RegExp("^[A-Z]{2}-[A-Z0-9]{1,3}$"))).min(1).describe("Restrict delivery to exact canonical ISO 3166-2 subdivisions (states, provinces, regions, departments, or other subdivision categories). Unknown identifiers are invalid. At create or update, sellers MUST reject unsupported identifiers and MUST NOT silently widen, drop, or partially apply the list. During get_products, a seller may instead return a sparse, buyer-reviewable targeting_resolution modification for a valid but unsupported requested outcome. Exact internal translation preserves accepted identifiers in package readback.").optional(), "geo_regions_exclude": z.array(z.string().regex(new RegExp("^[A-Z]{2}-[A-Z0-9]{1,3}$"))).min(1).describe("Exclude exact canonical ISO 3166-2 subdivisions. Support is independent from geo_regions inclusion support. Unknown identifiers and values also present in geo_regions are invalid. At create or update, sellers MUST reject unsupported identifiers and partial application; during get_products, a seller may instead return a sparse, buyer-reviewable targeting_resolution modification for a valid but unsupported requested outcome.").optional(), "geo_metros": z.array(z.object({ "system": z.enum(["nielsen_dma","uk_itl1","uk_itl2","eurostat_nuts2","custom"]).describe("Metro area classification system (e.g., 'nielsen_dma', 'uk_itl2')"), "values": z.array(z.string()).min(1).describe("Metro codes within the system (e.g., ['501', '602'] for Nielsen DMAs)") }).passthrough()).min(1).describe("Restrict delivery to specific metro areas. Each entry specifies the classification system and target values. Seller must declare supported systems in get_adcp_capabilities.").optional(), "geo_metros_exclude": z.array(z.object({ "system": z.enum(["nielsen_dma","uk_itl1","uk_itl2","eurostat_nuts2","custom"]).describe("Metro area classification system (e.g., 'nielsen_dma', 'uk_itl2')"), "values": z.array(z.string()).min(1).describe("Metro codes to exclude within the system (e.g., ['501', '602'] for Nielsen DMAs)") }).passthrough()).min(1).describe("Exclude specific metro areas from delivery. Each entry specifies the classification system and excluded values. Seller must declare supported systems in get_adcp_capabilities.").optional(), "geo_postal_areas": z.array(z.union([z.object({ "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code for the postal values."), "system": z.enum(["postal_code","zip","zip_plus_four","outward","full","fsa","plz","code_postal","postcode","cep","pin","custom","us_zip","us_zip_plus_four","gb_outward","gb_full","ca_fsa","ca_full","de_plz","fr_code_postal","au_postcode","ch_plz","at_plz"]).describe("Country-local postal code system."), "values": z.array(z.string()).min(1).describe("Postal codes within the country and system.") }).passthrough().and(z.object({ "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code."), "system": z.enum(["postal_code","zip","zip_plus_four","outward","full","fsa","plz","code_postal","postcode","cep","pin","custom","us_zip","us_zip_plus_four","gb_outward","gb_full","ca_fsa","ca_full","de_plz","fr_code_postal","au_postcode","ch_plz","at_plz"]).describe("Country-local postal code system.") }).and(z.union([z.object({ "country": z.literal("US").optional(), "system": z.enum(["zip","zip_plus_four"]).optional() }), z.object({ "country": z.literal("GB").optional(), "system": z.enum(["outward","full"]).optional() }), z.object({ "country": z.literal("CA").optional(), "system": z.enum(["fsa","full"]).optional() }), z.object({ "country": z.enum(["DE","CH","AT"]).optional(), "system": z.literal("plz").optional() }), z.object({ "country": z.literal("FR").optional(), "system": z.literal("code_postal").optional() }), z.object({ "country": z.literal("AU").optional(), "system": z.literal("postcode").optional() }), z.object({ "country": z.literal("BR").optional(), "system": z.literal("cep").optional() }), z.object({ "country": z.literal("IN").optional(), "system": z.literal("pin").optional() }), z.object({ "country": z.literal("ZA").optional(), "system": z.literal("postal_code").optional() }), z.object({ "country": z.any().refine((value) => !z.enum(["US","GB","CA","DE","CH","AT","FR","AU","BR","IN","ZA"]).safeParse(value).success, "Invalid input: Should NOT be valid against schema").optional(), "system": z.enum(["postal_code","custom"]).optional() })])).describe("Valid country-local postal system pairing. Registered countries only accept their registered local systems; countries without a registered local system use postal_code or custom.")), z.object({ "system": z.enum(["us_zip","us_zip_plus_four","gb_outward","gb_full","ca_fsa","ca_full","de_plz","fr_code_postal","au_postcode","ch_plz","at_plz"]).describe("Deprecated country-fused postal code system (e.g., 'us_zip', 'gb_outward'). Prefer country + postal-system."), "values": z.array(z.string()).min(1).describe("Postal codes within the legacy system.") }).passthrough()]).describe("Postal area values. Prefer the native country + postal system form. Deprecated legacy country-fused postal-system tokens remain accepted for compatibility.")).min(1).describe("Restrict delivery to specific postal areas. Prefer the native country + postal system form. The deprecated legacy country-fused postal-system tokens remain accepted for compatibility. Seller must declare supported systems in get_adcp_capabilities.").optional(), "geo_postal_areas_exclude": z.array(z.union([z.object({ "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code for the postal values."), "system": z.enum(["postal_code","zip","zip_plus_four","outward","full","fsa","plz","code_postal","postcode","cep","pin","custom","us_zip","us_zip_plus_four","gb_outward","gb_full","ca_fsa","ca_full","de_plz","fr_code_postal","au_postcode","ch_plz","at_plz"]).describe("Country-local postal code system."), "values": z.array(z.string()).min(1).describe("Postal codes within the country and system.") }).passthrough().and(z.object({ "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code."), "system": z.enum(["postal_code","zip","zip_plus_four","outward","full","fsa","plz","code_postal","postcode","cep","pin","custom","us_zip","us_zip_plus_four","gb_outward","gb_full","ca_fsa","ca_full","de_plz","fr_code_postal","au_postcode","ch_plz","at_plz"]).describe("Country-local postal code system.") }).and(z.union([z.object({ "country": z.literal("US").optional(), "system": z.enum(["zip","zip_plus_four"]).optional() }), z.object({ "country": z.literal("GB").optional(), "system": z.enum(["outward","full"]).optional() }), z.object({ "country": z.literal("CA").optional(), "system": z.enum(["fsa","full"]).optional() }), z.object({ "country": z.enum(["DE","CH","AT"]).optional(), "system": z.literal("plz").optional() }), z.object({ "country": z.literal("FR").optional(), "system": z.literal("code_postal").optional() }), z.object({ "country": z.literal("AU").optional(), "system": z.literal("postcode").optional() }), z.object({ "country": z.literal("BR").optional(), "system": z.literal("cep").optional() }), z.object({ "country": z.literal("IN").optional(), "system": z.literal("pin").optional() }), z.object({ "country": z.literal("ZA").optional(), "system": z.literal("postal_code").optional() }), z.object({ "country": z.any().refine((value) => !z.enum(["US","GB","CA","DE","CH","AT","FR","AU","BR","IN","ZA"]).safeParse(value).success, "Invalid input: Should NOT be valid against schema").optional(), "system": z.enum(["postal_code","custom"]).optional() })])).describe("Valid country-local postal system pairing. Registered countries only accept their registered local systems; countries without a registered local system use postal_code or custom.")), z.object({ "system": z.enum(["us_zip","us_zip_plus_four","gb_outward","gb_full","ca_fsa","ca_full","de_plz","fr_code_postal","au_postcode","ch_plz","at_plz"]).describe("Deprecated country-fused postal code system (e.g., 'us_zip', 'gb_outward'). Prefer country + postal-system."), "values": z.array(z.string()).min(1).describe("Postal codes within the legacy system.") }).passthrough()]).describe("Postal area values. Prefer the native country + postal system form. Deprecated legacy country-fused postal-system tokens remain accepted for compatibility.")).min(1).describe("Exclude specific postal areas from delivery. Prefer the native country + postal system form. The deprecated legacy country-fused postal-system tokens remain accepted for compatibility. Seller must declare supported systems in get_adcp_capabilities.").optional(), "geo_places": z.array(z.object({ "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code containing the place."), "system": z.union([z.enum(["geonames","google_ads","microsoft_ads"]), z.string().refine(adcpJsonSchemaUri, "Invalid URI").regex(new RegExp("^https://"))]).describe("Collision-safe identifier namespace for geographic places. Registered tokens have protocol-defined semantics. Unregistered systems MUST use an absolute HTTPS URI controlled by the catalog owner; consumers compare URI systems as exact opaque strings."), "system_version": z.string().min(1).describe("Optional exact catalog version from the seller's declared supported_versions. When omitted, the seller applies catalog.current_version and MUST echo that version on persisted package state.").optional(), "place_type": z.union([z.enum(["airport","borough","city","city_region","commune","county","district","municipality","neighborhood","post_town","prefecture","province","quarter","state","territory","ward"]), z.string().refine(adcpJsonSchemaUri, "Invalid URI").regex(new RegExp("^https://"))]).describe("Canonical place classification. Registered tokens have protocol-defined meanings. Catalog-specific classifications without a registered mapping MUST use an absolute HTTPS URI controlled by the vocabulary owner; consumers compare URI types as exact opaque strings."), "values": z.array(z.string().min(1)).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Stable place identifiers in the declared system. Display names are not valid targeting values."), "value_labels": z.record(z.string(), z.string().min(1)).describe("Optional human-readable diagnostic labels keyed by identifiers present in values. Extra keys are a conformance error. Labels are non-authoritative and MUST NOT be used to resolve or apply targeting.").optional(), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough().and(z.union([z.any().refine((value) => !z.object({ "system": z.enum(["geonames","google_ads","microsoft_ads"]) }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "system": z.enum(["geonames","google_ads","microsoft_ads"]) }), z.object({ "values": z.any().optional() }))])).describe("A catalog-backed named place target. Values are stable identifiers in the declared system. Entries within geo_places form a union; different geographic inclusion dimensions intersect. value_labels are diagnostic only and MUST NOT be used to resolve targeting.")).min(1).describe("Restrict delivery to catalog-backed named places. Values MUST be stable identifiers in the declared system, not display names. Sellers must declare supported systems, countries, and place types in get_adcp_capabilities and reject unsupported entries rather than silently dropping them.").optional(), "geo_places_exclude": z.array(z.object({ "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code containing the place."), "system": z.union([z.enum(["geonames","google_ads","microsoft_ads"]), z.string().refine(adcpJsonSchemaUri, "Invalid URI").regex(new RegExp("^https://"))]).describe("Collision-safe identifier namespace for geographic places. Registered tokens have protocol-defined semantics. Unregistered systems MUST use an absolute HTTPS URI controlled by the catalog owner; consumers compare URI systems as exact opaque strings."), "system_version": z.string().min(1).describe("Optional exact catalog version from the seller's declared supported_versions. When omitted, the seller applies catalog.current_version and MUST echo that version on persisted package state.").optional(), "place_type": z.union([z.enum(["airport","borough","city","city_region","commune","county","district","municipality","neighborhood","post_town","prefecture","province","quarter","state","territory","ward"]), z.string().refine(adcpJsonSchemaUri, "Invalid URI").regex(new RegExp("^https://"))]).describe("Canonical place classification. Registered tokens have protocol-defined meanings. Catalog-specific classifications without a registered mapping MUST use an absolute HTTPS URI controlled by the vocabulary owner; consumers compare URI types as exact opaque strings."), "values": z.array(z.string().min(1)).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Stable place identifiers in the declared system. Display names are not valid targeting values."), "value_labels": z.record(z.string(), z.string().min(1)).describe("Optional human-readable diagnostic labels keyed by identifiers present in values. Extra keys are a conformance error. Labels are non-authoritative and MUST NOT be used to resolve or apply targeting.").optional(), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough().and(z.union([z.any().refine((value) => !z.object({ "system": z.enum(["geonames","google_ads","microsoft_ads"]) }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "system": z.enum(["geonames","google_ads","microsoft_ads"]) }), z.object({ "values": z.any().optional() }))])).describe("A catalog-backed named place target. Values are stable identifiers in the declared system. Entries within geo_places form a union; different geographic inclusion dimensions intersect. value_labels are diagnostic only and MUST NOT be used to resolve targeting.")).min(1).describe("Exclude catalog-backed named places. Uses the same identifier-based shape as geo_places. Sellers MUST reject overlap with geo_places for the same country, system, place_type, and value.").optional(), "daypart_targets": z.array(z.object({ "days": z.array(z.enum(["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]).describe("Days of the week for daypart targeting")).min(1).describe("Days of week this window applies to. Use multiple days for compact targeting (e.g., monday-friday in one object)."), "start_hour": z.number().int().gte(0).lte(23).describe("Start hour (inclusive), 0-23 in 24-hour format. 0 = midnight, 6 = 6:00am, 18 = 6:00pm."), "end_hour": z.number().int().gte(1).lte(24).describe("End hour (exclusive), 1-24 in 24-hour format. 10 = 10:00am, 24 = midnight. Must be greater than start_hour."), "timezone": z.union([z.literal("inventory_local"), z.any().refine((value) => !z.literal("inventory_local").safeParse(value).success, "Invalid input: Should NOT be valid against schema").describe("Concrete timezone identifier in the implementation's supported IANA Time Zone Database, such as America/New_York, CET, or UTC.")]).describe("Civil-time clock used to evaluate this window. 'inventory_local' evaluates the hours in the seller-assigned local timezone of each inventory unit that can deliver the impression, such as a screen, venue, station, or publisher property; it never means the buyer, account, or server timezone. A concrete IANA timezone identifier (for example, 'America/New_York', 'CET', or 'UTC') evaluates one shared civil-time clock across the targeted inventory. Omission defaults to 'inventory_local'. Buyers that begin with a user or account preference MUST resolve it to a concrete IANA identifier before sending the daypart; 'user_timezone' and 'account_timezone' are not wire values. For each candidate delivery instant, convert the instant into this clock and compare its resulting local day and hour with the half-open window: a skipped DST hour has no matching instants, while both occurrences of a repeated hour match. This delivery clock is independent of reporting_capabilities.timezone.").default("inventory_local"), "label": z.string().describe("Optional human-readable name for this time window (e.g., 'Morning Drive', 'Prime Time')").optional() }).passthrough().describe("A time window for daypart targeting. Specifies days of week, an hour range, and the civil-time clock used to evaluate it. start_hour is inclusive, end_hour is exclusive (e.g., 6-10 = 6:00am to 10:00am). Follows the Google Ads AdScheduleInfo / DV360 DayPartTargeting pattern.")).min(1).describe("Restrict delivery to specific time windows. Each entry specifies days of week, an hour range, and an optional timezone that defaults to inventory_local. A concrete IANA zone uses one shared civil-time clock, while inventory_local evaluates each inventory unit in its seller-assigned local timezone. Entries are independent and MAY use different clocks.").optional(), "axe_include_segment": z.string().describe("Deprecated: Use TMP provider fields instead. AXE segment ID to include for targeting.").optional(), "axe_exclude_segment": z.string().describe("Deprecated: Use TMP provider fields instead. AXE segment ID to exclude from targeting.").optional(), "audience_include": z.array(z.string()).min(1).describe("Restrict delivery to members of these first-party CRM audiences. Only users present in the uploaded lists are eligible. References audience_id values from sync_audiences on the same seller account — audience IDs are not portable across sellers. Not for lookalike expansion — express that intent in the campaign brief. Seller must declare support in get_adcp_capabilities.").optional(), "audience_exclude": z.array(z.string()).min(1).describe("Suppress delivery to members of these first-party CRM audiences. Matched users are excluded regardless of other targeting. References audience_id values from sync_audiences on the same seller account — audience IDs are not portable across sellers. Seller must declare support in get_adcp_capabilities.").optional(), "signal_targeting_groups": z.object({ "operator": z.literal("all").describe("Groups-level operator. Required even though v1 only supports 'all': every child group must be satisfied."), "groups": z.array(z.object({ "operator": z.enum(["any","none"]).describe("How to evaluate the signals in this group. 'any' is an OR include group. 'none' is an exclusion group equivalent to NOT (A OR B OR C)."), "signals": z.array(z.object({ "pricing_option_id": z.string().describe("Pricing option selected for this signal. Use the pricing_option_id from the product's signal_targeting_options entry when product-scoped pricing is present; otherwise use the seller get_signals pricing only when the product option does not override it. Required when the selected signal has pricing_options; omit only when the signal is bundled into the product price or has no incremental cost.").optional(), "signal_agent_segment_id": z.string().describe("Optional opaque resolved-segment or seller execution handle for this signal. Omit when signal_ref plus the value expression is sufficient for the seller to resolve the signal. Include when the product option exposes a separate runtime or activation handle, and pass it verbatim. Buyers SHOULD prefer an exposed segment handle over reconstructing condition identity from categorical values because the handle can carry provider namespace and methodology distinctions.").optional(), "activation_key": z.record(z.string(), z.any()).and(z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "type": z.literal("segment_id").describe("Segment ID based targeting"), "segment_id": z.string().describe("The platform-specific segment identifier to use in campaign targeting") }).catchall(z.any()), z.object({ "type": z.literal("key_value").describe("Key-value pair based targeting"), "key": z.string().describe("The targeting parameter key"), "value": z.string().describe("The targeting parameter value") }).catchall(z.any())]; + }).describe("Named signal being targeted."), "value_type": z.literal("binary").describe("Discriminator for binary signals."), "value": z.literal(true).describe("Binary package signal entries match users for whom the signal is true. Use the parent group operator for include/exclude.") }).catchall(z.any()).describe("Binary signal expression. In grouped package targeting, value is always true; use a parent group with operator 'none' for exclusion."), z.object({ "signal_ref": z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "scope": z.literal("product").describe("Discriminator indicating the signal resolves through the selected product's included_signals or signal_targeting_options."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Product-local signal identifier. For local signals exposed on both get_signals and get_products, this MUST match get_signals.signals[].signal_ref.signal_id for the same signal.") }).catchall(z.any()).describe("Product-scoped signal. The signal_id is meaningful only within the selected product/package context and MUST match a Product.included_signals[].signal_ref.signal_id or Product.signal_targeting_options[].signal_ref.signal_id for that product, depending on whether the signal is descriptive or selectable."), z.object({ "scope": z.literal("data_provider").describe("Discriminator indicating the signal resolves through a data provider's published adagents.json signals[]."), "data_provider_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that publishes the signal definition in its adagents.json signals[]."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the data provider's published adagents.json signals[].") }).catchall(z.any()).describe("Data-provider-scoped signal. The signal_id resolves through the data provider's published adagents.json signals[] and can be authorization-verified there."), z.object({ "scope": z.literal("signal_source").describe("Discriminator indicating the signal resolves through the issuing signal source."), "signal_source_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the signal source that issues this source-native signal."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the issuing signal source's signal set.") }).catchall(z.any()).describe("Signal-source-scoped signal. Use this for source-native signals that are not published in upstream adagents.json signals[]. The buyer trusts the issuing signal source for this identity; use scope 'data_provider' instead when the signal is published in adagents.json signals[], even if the publisher is also the seller or signal source.")]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17147,8 +15107,7 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - })).describe("Destination-specific activation key returned by get_signals or activate_signal. Usually omitted for seller-offered signals selected directly through the same seller; include only when the selected signal was separately activated and the seller requires the activation key to correlate the package selection.").optional() }).catchall(z.any()).and(z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "signal_ref": z.any().superRefine((x, ctx) => { + }).describe("Named signal being targeted."), "value_type": z.literal("categorical").describe("Discriminator for categorical signals."), "values": z.array(z.string()).min(1).describe("Values to target. Users with any of these values match the expression.") }).catchall(z.any()).describe("Categorical signal expression - target users with one of the listed values."), z.object({ "signal_ref": z.any().superRefine((x, ctx) => { const schemas = [z.object({ "scope": z.literal("product").describe("Discriminator indicating the signal resolves through the selected product's included_signals or signal_targeting_options."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Product-local signal identifier. For local signals exposed on both get_signals and get_products, this MUST match get_signals.signals[].signal_ref.signal_id for the same signal.") }).catchall(z.any()).describe("Product-scoped signal. The signal_id is meaningful only within the selected product/package context and MUST match a Product.included_signals[].signal_ref.signal_id or Product.signal_targeting_options[].signal_ref.signal_id for that product, depending on whether the signal is descriptive or selectable."), z.object({ "scope": z.literal("data_provider").describe("Discriminator indicating the signal resolves through a data provider's published adagents.json signals[]."), "data_provider_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that publishes the signal definition in its adagents.json signals[]."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the data provider's published adagents.json signals[].") }).catchall(z.any()).describe("Data-provider-scoped signal. The signal_id resolves through the data provider's published adagents.json signals[] and can be authorization-verified there."), z.object({ "scope": z.literal("signal_source").describe("Discriminator indicating the signal resolves through the issuing signal source."), "signal_source_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the signal source that issues this source-native signal."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the issuing signal source's signal set.") }).catchall(z.any()).describe("Signal-source-scoped signal. Use this for source-native signals that are not published in upstream adagents.json signals[]. The buyer trusts the issuing signal source for this identity; use scope 'data_provider' instead when the signal is published in adagents.json signals[], even if the publisher is also the seller or signal source.")]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; @@ -17180,8 +15139,7 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - }).describe("Named signal being targeted."), "value_type": z.literal("binary").describe("Discriminator for binary signals."), "value": z.literal(true).describe("Binary package signal entries match users for whom the signal is true. Use the parent group operator for include/exclude.") }).catchall(z.any()).describe("Binary signal expression. In grouped package targeting, value is always true; use a parent group with operator 'none' for exclusion."), z.object({ "signal_ref": z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "scope": z.literal("product").describe("Discriminator indicating the signal resolves through the selected product's included_signals or signal_targeting_options."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Product-local signal identifier. For local signals exposed on both get_signals and get_products, this MUST match get_signals.signals[].signal_ref.signal_id for the same signal.") }).catchall(z.any()).describe("Product-scoped signal. The signal_id is meaningful only within the selected product/package context and MUST match a Product.included_signals[].signal_ref.signal_id or Product.signal_targeting_options[].signal_ref.signal_id for that product, depending on whether the signal is descriptive or selectable."), z.object({ "scope": z.literal("data_provider").describe("Discriminator indicating the signal resolves through a data provider's published adagents.json signals[]."), "data_provider_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that publishes the signal definition in its adagents.json signals[]."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the data provider's published adagents.json signals[].") }).catchall(z.any()).describe("Data-provider-scoped signal. The signal_id resolves through the data provider's published adagents.json signals[] and can be authorization-verified there."), z.object({ "scope": z.literal("signal_source").describe("Discriminator indicating the signal resolves through the issuing signal source."), "signal_source_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the signal source that issues this source-native signal."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the issuing signal source's signal set.") }).catchall(z.any()).describe("Signal-source-scoped signal. Use this for source-native signals that are not published in upstream adagents.json signals[]. The buyer trusts the issuing signal source for this identity; use scope 'data_provider' instead when the signal is published in adagents.json signals[], even if the publisher is also the seller or signal source.")]; + }).describe("Named signal being targeted."), "value_type": z.literal("numeric").describe("Discriminator for numeric signals."), "min_value": z.number().describe("Minimum value, inclusive. Omit for no minimum. Should be within the signal definition's range when declared.").optional(), "max_value": z.number().describe("Maximum value, inclusive. Omit for no maximum. Should be within the signal definition's range when declared.").optional() }).catchall(z.any()).and(z.union([z.object({ "min_value": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max_value": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("Numeric signal expression - target users within a value range. At least one of min_value or max_value is required. If both min_value and max_value are provided, min_value MUST be <= max_value.")]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17212,7 +15170,8 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - }).describe("Named signal being targeted."), "value_type": z.literal("categorical").describe("Discriminator for categorical signals."), "values": z.array(z.string()).min(1).describe("Values to target. Users with any of these values match the expression.") }).catchall(z.any()).describe("Categorical signal expression - target users with one of the listed values."), z.object({ "signal_ref": z.any().superRefine((x, ctx) => { + }).describe("Predicate over a named signal definition. Signals are typed dimensions, similar to feature values: binary signals match true, categorical signals match one of a set of values, and numeric signals match a range. In package signal targeting groups, include/exclude semantics are controlled by the parent group operator, not by negating the expression.")).describe("Buy-time selection of one seller-offered signal inside a package signal targeting group. The signal_ref uses scope 'product' for a product-local signal option, scope 'data_provider' for a signal defined in a data provider's published adagents.json signals[], or scope 'signal_source' for a source-native signal that is not published in adagents.json signals[]. The selected product's inline Product.signal_targeting_options, get_signals feed when inline options are omitted, and signal_targeting_rules define buy-time eligibility. Inclusion and exclusion are controlled by the parent group operator: use operator 'any' to include users matching the signal expression and operator 'none' to exclude users matching the signal expression. For binary signals, value MUST be true; do not use value=false for exclusion inside signal_targeting_groups. Use audience_include/audience_exclude only for buyer-managed first-party audiences registered through sync_audiences.")).min(1).describe("Signal targeting entries evaluated by this group. Each entry uses the package signal targeting shape, including signal_ref, value expression, and optional pricing, execution-handle, or activation fields.") }).catchall(z.any()).describe("A basic Boolean group of package-level signal targeting entries. 'any' means the user must match at least one signal in the group. 'none' means the user must match none of the signals in the group. Use groups for portable include/exclude composition such as (A OR B) AND NOT (C OR D).")).min(1).describe("Signal targeting groups to evaluate. Use operator 'any' for include groups and 'none' for exclusion groups.") }).catchall(z.any()).describe("Basic Boolean grouping for seller-offered signals. v1 supports a required top-level operator 'all' and child groups with operator 'any' for include groups or 'none' for exclusion groups. Example semantics: group 1 any(A, B) plus group 2 none(C, D) means (A OR B) AND NOT (C OR D). Signal entries reference named signal definitions with signal_ref scope 'product' for product-local signal options or scope 'data_provider' for external signals published in adagents.json signals[]. For simple include-only targeting, send one child group with operator 'any'. Sellers SHOULD reject entries that are not available for the product through inline signal_targeting_options or get_signals, are not active for the account, or exceed the product's signal_targeting_allowed/signal_targeting_rules/product terms. Signal targeting limits are product-scoped, not declared in get_adcp_capabilities, because products may be backed by different ad servers. Sellers MUST echo applied signal_targeting_groups on the resulting package state, including fixed/default selections. Sellers MAY return REQUOTE_REQUIRED when a targeting mutation changes commercial terms.").optional(), "signal_targeting": z.array(z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "signal_ref": z.any().superRefine((x, ctx) => { const schemas = [z.object({ "scope": z.literal("product").describe("Discriminator indicating the signal resolves through the selected product's included_signals or signal_targeting_options."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Product-local signal identifier. For local signals exposed on both get_signals and get_products, this MUST match get_signals.signals[].signal_ref.signal_id for the same signal.") }).catchall(z.any()).describe("Product-scoped signal. The signal_id is meaningful only within the selected product/package context and MUST match a Product.included_signals[].signal_ref.signal_id or Product.signal_targeting_options[].signal_ref.signal_id for that product, depending on whether the signal is descriptive or selectable."), z.object({ "scope": z.literal("data_provider").describe("Discriminator indicating the signal resolves through a data provider's published adagents.json signals[]."), "data_provider_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that publishes the signal definition in its adagents.json signals[]."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the data provider's published adagents.json signals[].") }).catchall(z.any()).describe("Data-provider-scoped signal. The signal_id resolves through the data provider's published adagents.json signals[] and can be authorization-verified there."), z.object({ "scope": z.literal("signal_source").describe("Discriminator indicating the signal resolves through the issuing signal source."), "signal_source_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the signal source that issues this source-native signal."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the issuing signal source's signal set.") }).catchall(z.any()).describe("Signal-source-scoped signal. Use this for source-native signals that are not published in upstream adagents.json signals[]. The buyer trusts the issuing signal source for this identity; use scope 'data_provider' instead when the signal is published in adagents.json signals[], even if the publisher is also the seller or signal source.")]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; @@ -17244,7 +15203,8 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - }).describe("Named signal being targeted."), "value_type": z.literal("numeric").describe("Discriminator for numeric signals."), "min_value": z.number().describe("Minimum value, inclusive. Omit for no minimum. Should be within the signal definition's range when declared.").optional(), "max_value": z.number().describe("Maximum value, inclusive. Omit for no maximum. Should be within the signal definition's range when declared.").optional() }).catchall(z.any()).and(z.union([z.object({ "min_value": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max_value": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("Numeric signal expression - target users within a value range. At least one of min_value or max_value is required. If both min_value and max_value are provided, min_value MUST be <= max_value.")]; + }).describe("The signal to target. New targeting constraints SHOULD use signal_ref.").optional(), "signal_id": z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "source": z.literal("catalog").describe("Discriminator indicating this signal is from a data provider's published adagents.json signals[]"), "data_provider_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain of the data provider that owns this signal (e.g., 'pinnacle-data.example'). The signal definition is published at this domain's /.well-known/adagents.json"), "id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the data provider's catalog (e.g., 'likely_ev_buyers', 'income_100k_plus')") }).catchall(z.any()).describe("Data-provider signal - references a signal from a data provider's published adagents.json signals[]. Buyers can verify authorization by checking the data provider's adagents.json."), z.object({ "source": z.literal("agent").describe("Discriminator indicating this signal is native to the signal source identified by agent_url, not from a data provider's published signal definitions."), "agent_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the signal source that provides this signal (e.g., 'https://signals.example/.well-known/adcp/signals')"), "id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the agent's signal set (e.g., 'custom_auto_intenders')") }).catchall(z.any()).describe("Agent signal - references a signal native to a signal source identified by agent_url. Not externally verifiable through an upstream catalog; buyer trusts the issuing signal source's claim about the signal.")]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17275,8 +15235,7 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - }).describe("Predicate over a named signal definition. Signals are typed dimensions, similar to feature values: binary signals match true, categorical signals match one of a set of values, and numeric signals match a range. In package signal targeting groups, include/exclude semantics are controlled by the parent group operator, not by negating the expression.")).describe("Buy-time selection of one seller-offered signal inside a package signal targeting group. The signal_ref uses scope 'product' for a product-local signal option, scope 'data_provider' for a signal defined in a data provider's published adagents.json signals[], or scope 'signal_source' for a source-native signal that is not published in adagents.json signals[]. The selected product's inline Product.signal_targeting_options, get_signals feed when inline options are omitted, and signal_targeting_rules define buy-time eligibility. Inclusion and exclusion are controlled by the parent group operator: use operator 'any' to include users matching the signal expression and operator 'none' to exclude users matching the signal expression. For binary signals, value MUST be true; do not use value=false for exclusion inside signal_targeting_groups. Use audience_include/audience_exclude only for buyer-managed first-party audiences registered through sync_audiences.")).min(1).describe("Signal targeting entries evaluated by this group. Each entry uses the package signal targeting shape, including signal_ref, value expression, and optional pricing, execution-handle, or activation fields.") }).catchall(z.any()).describe("A basic Boolean group of package-level signal targeting entries. 'any' means the user must match at least one signal in the group. 'none' means the user must match none of the signals in the group. Use groups for portable include/exclude composition such as (A OR B) AND NOT (C OR D).")).min(1).describe("Signal targeting groups to evaluate. Use operator 'any' for include groups and 'none' for exclusion groups.") }).catchall(z.any()).describe("Basic Boolean grouping for seller-offered signals. v1 supports a required top-level operator 'all' and child groups with operator 'any' for include groups or 'none' for exclusion groups. Example semantics: group 1 any(A, B) plus group 2 none(C, D) means (A OR B) AND NOT (C OR D). Signal entries reference named signal definitions with signal_ref scope 'product' for product-local signal options or scope 'data_provider' for external signals published in adagents.json signals[]. For simple include-only targeting, send one child group with operator 'any'. Sellers SHOULD reject entries that are not available for the product through inline signal_targeting_options or get_signals, are not active for the account, or exceed the product's signal_targeting_allowed/signal_targeting_rules/product terms. Signal targeting limits are product-scoped, not declared in get_adcp_capabilities, because products may be backed by different ad servers. Sellers MUST echo applied signal_targeting_groups on the resulting package state, including fixed/default selections. Sellers MAY return REQUOTE_REQUIRED when a targeting mutation changes commercial terms.").optional(), "signal_targeting": z.array(z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "signal_ref": z.any().superRefine((x, ctx) => { + }).describe("DEPRECATED. Use signal_ref instead. Legacy SignalId retained for compatibility with older clients.").optional(), "value_type": z.literal("binary").describe("Discriminator for binary signals"), "value": z.boolean().describe("Whether to include (true) or exclude (false) users matching this signal") }).catchall(z.any()).and(z.union([z.object({ "signal_ref": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "signal_id": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("Binary signal targeting - user either matches or doesn't"), z.object({ "signal_ref": z.any().superRefine((x, ctx) => { const schemas = [z.object({ "scope": z.literal("product").describe("Discriminator indicating the signal resolves through the selected product's included_signals or signal_targeting_options."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Product-local signal identifier. For local signals exposed on both get_signals and get_products, this MUST match get_signals.signals[].signal_ref.signal_id for the same signal.") }).catchall(z.any()).describe("Product-scoped signal. The signal_id is meaningful only within the selected product/package context and MUST match a Product.included_signals[].signal_ref.signal_id or Product.signal_targeting_options[].signal_ref.signal_id for that product, depending on whether the signal is descriptive or selectable."), z.object({ "scope": z.literal("data_provider").describe("Discriminator indicating the signal resolves through a data provider's published adagents.json signals[]."), "data_provider_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that publishes the signal definition in its adagents.json signals[]."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the data provider's published adagents.json signals[].") }).catchall(z.any()).describe("Data-provider-scoped signal. The signal_id resolves through the data provider's published adagents.json signals[] and can be authorization-verified there."), z.object({ "scope": z.literal("signal_source").describe("Discriminator indicating the signal resolves through the issuing signal source."), "signal_source_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the signal source that issues this source-native signal."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the issuing signal source's signal set.") }).catchall(z.any()).describe("Signal-source-scoped signal. Use this for source-native signals that are not published in upstream adagents.json signals[]. The buyer trusts the issuing signal source for this identity; use scope 'data_provider' instead when the signal is published in adagents.json signals[], even if the publisher is also the seller or signal source.")]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; @@ -17340,7 +15299,7 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - }).describe("DEPRECATED. Use signal_ref instead. Legacy SignalId retained for compatibility with older clients.").optional(), "value_type": z.literal("binary").describe("Discriminator for binary signals"), "value": z.boolean().describe("Whether to include (true) or exclude (false) users matching this signal") }).catchall(z.any()).and(z.union([z.object({ "signal_ref": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "signal_id": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("Binary signal targeting - user either matches or doesn't"), z.object({ "signal_ref": z.any().superRefine((x, ctx) => { + }).describe("DEPRECATED. Use signal_ref instead. Legacy SignalId retained for compatibility with older clients.").optional(), "value_type": z.literal("categorical").describe("Discriminator for categorical signals"), "values": z.array(z.string()).min(1).describe("Values to target. Users with any of these values will be included.") }).catchall(z.any()).and(z.union([z.object({ "signal_ref": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "signal_id": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("Categorical signal targeting - target users with specific values"), z.object({ "signal_ref": z.any().superRefine((x, ctx) => { const schemas = [z.object({ "scope": z.literal("product").describe("Discriminator indicating the signal resolves through the selected product's included_signals or signal_targeting_options."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Product-local signal identifier. For local signals exposed on both get_signals and get_products, this MUST match get_signals.signals[].signal_ref.signal_id for the same signal.") }).catchall(z.any()).describe("Product-scoped signal. The signal_id is meaningful only within the selected product/package context and MUST match a Product.included_signals[].signal_ref.signal_id or Product.signal_targeting_options[].signal_ref.signal_id for that product, depending on whether the signal is descriptive or selectable."), z.object({ "scope": z.literal("data_provider").describe("Discriminator indicating the signal resolves through a data provider's published adagents.json signals[]."), "data_provider_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that publishes the signal definition in its adagents.json signals[]."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the data provider's published adagents.json signals[].") }).catchall(z.any()).describe("Data-provider-scoped signal. The signal_id resolves through the data provider's published adagents.json signals[] and can be authorization-verified there."), z.object({ "scope": z.literal("signal_source").describe("Discriminator indicating the signal resolves through the issuing signal source."), "signal_source_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the signal source that issues this source-native signal."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the issuing signal source's signal set.") }).catchall(z.any()).describe("Signal-source-scoped signal. Use this for source-native signals that are not published in upstream adagents.json signals[]. The buyer trusts the issuing signal source for this identity; use scope 'data_provider' instead when the signal is published in adagents.json signals[], even if the publisher is also the seller or signal source.")]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; @@ -17404,8 +15363,7 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - }).describe("DEPRECATED. Use signal_ref instead. Legacy SignalId retained for compatibility with older clients.").optional(), "value_type": z.literal("categorical").describe("Discriminator for categorical signals"), "values": z.array(z.string()).min(1).describe("Values to target. Users with any of these values will be included.") }).catchall(z.any()).and(z.union([z.object({ "signal_ref": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "signal_id": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("Categorical signal targeting - target users with specific values"), z.object({ "signal_ref": z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "scope": z.literal("product").describe("Discriminator indicating the signal resolves through the selected product's included_signals or signal_targeting_options."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Product-local signal identifier. For local signals exposed on both get_signals and get_products, this MUST match get_signals.signals[].signal_ref.signal_id for the same signal.") }).catchall(z.any()).describe("Product-scoped signal. The signal_id is meaningful only within the selected product/package context and MUST match a Product.included_signals[].signal_ref.signal_id or Product.signal_targeting_options[].signal_ref.signal_id for that product, depending on whether the signal is descriptive or selectable."), z.object({ "scope": z.literal("data_provider").describe("Discriminator indicating the signal resolves through a data provider's published adagents.json signals[]."), "data_provider_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that publishes the signal definition in its adagents.json signals[]."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the data provider's published adagents.json signals[].") }).catchall(z.any()).describe("Data-provider-scoped signal. The signal_id resolves through the data provider's published adagents.json signals[] and can be authorization-verified there."), z.object({ "scope": z.literal("signal_source").describe("Discriminator indicating the signal resolves through the issuing signal source."), "signal_source_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the signal source that issues this source-native signal."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the issuing signal source's signal set.") }).catchall(z.any()).describe("Signal-source-scoped signal. Use this for source-native signals that are not published in upstream adagents.json signals[]. The buyer trusts the issuing signal source for this identity; use scope 'data_provider' instead when the signal is published in adagents.json signals[], even if the publisher is also the seller or signal source.")]; + }).describe("DEPRECATED. Use signal_ref instead. Legacy SignalId retained for compatibility with older clients.").optional(), "value_type": z.literal("numeric").describe("Discriminator for numeric signals"), "min_value": z.number().describe("Minimum value (inclusive). Omit for no minimum. Must be <= max_value when both are provided. Should be >= signal's range.min if defined.").optional(), "max_value": z.number().describe("Maximum value (inclusive). Omit for no maximum. Must be >= min_value when both are provided. Should be <= signal's range.max if defined.").optional() }).catchall(z.any()).and(z.union([z.object({ "signal_ref": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "signal_id": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("Numeric signal targeting - target users within a value range. If min_value is provided, it must be <= max_value. Values should be within the signal's defined range (see signal definition).")]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17436,8 +15394,9 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - }).describe("The signal to target. New targeting constraints SHOULD use signal_ref.").optional(), "signal_id": z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "source": z.literal("catalog").describe("Discriminator indicating this signal is from a data provider's published adagents.json signals[]"), "data_provider_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain of the data provider that owns this signal (e.g., 'pinnacle-data.example'). The signal definition is published at this domain's /.well-known/adagents.json"), "id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the data provider's catalog (e.g., 'likely_ev_buyers', 'income_100k_plus')") }).catchall(z.any()).describe("Data-provider signal - references a signal from a data provider's published adagents.json signals[]. Buyers can verify authorization by checking the data provider's adagents.json."), z.object({ "source": z.literal("agent").describe("Discriminator indicating this signal is native to the signal source identified by agent_url, not from a data provider's published signal definitions."), "agent_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the signal source that provides this signal (e.g., 'https://signals.example/.well-known/adcp/signals')"), "id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the agent's signal set (e.g., 'custom_auto_intenders')") }).catchall(z.any()).describe("Agent signal - references a signal native to a signal source identified by agent_url. Not externally verifiable through an upstream catalog; buyer trusts the issuing signal source's claim about the signal.")]; + }).describe("Targeting constraint for a specific signal. Uses value_type as discriminator to determine the targeting expression format.")).min(1).describe("DEPRECATED. Use signal_targeting_groups for package-level signal targeting. Legacy flat signal_targeting remains accepted during the SignalRef migration window but cannot express grouped include/exclude composition or product-scoped pricing.").optional(), "demographics": z.object({ "age": z.intersection(z.object({ "min": z.number().int().gte(0).lte(150).describe("Inclusive minimum age in completed years. Omit for an open lower bound.").optional(), "max": z.number().int().gte(0).lte(150).describe("Inclusive maximum age in completed years. Omit for an open upper bound.").optional(), "include_unknown": z.boolean().describe("Whether delivery to people whose age is unavailable is part of this predicate. This field has no default and MUST be supplied.") }).catchall(z.any()).and(z.union([z.object({ "min": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A canonical audience-age predicate in completed integer years. min and max are inclusive; omitting one bound means no restriction in that direction. At least one bound is required. include_unknown is always explicit because people whose age is unavailable are not members of any numeric interval. Implementations MUST reject min greater than max; JSON Schema draft-07 cannot compare sibling numeric values."), z.object({ "accepted_bases": z.array(z.enum(["verified","declared","inferred"]).describe("User-level bases that may resolve age for demographic targeting execution. Population estimates are deliberately absent because aggregate composition cannot establish an individual impression's age.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("User-level age determination bases the buyer permits for this predicate. Sellers MUST use only these bases or reject the request; they MUST NOT silently fall back to another basis. When omitted, the buyer imposes no determination-basis constraint beyond product capability and any age_restriction. population_estimate is structurally unavailable because aggregate evidence cannot identify an eligible user.").optional(), "accepted_verification_methods": z.array(z.enum(["facial_age_estimation","id_document","digital_id","credit_card","world_id"]).describe("Methods for verifying user age for compliance. Does not include 'inferred' as it is not accepted for regulatory compliance.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Verification methods acceptable when verified is an accepted basis. This field narrows verified demographic execution; age_restriction.accepted_methods independently governs legal eligibility and the two sets are intersected when both are present.").optional() }).catchall(z.any()).and(z.union([z.any().refine((value) => !z.object({ "accepted_verification_methods": z.any().refine((value) => value !== undefined, "Required") }).passthrough().safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "accepted_verification_methods": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "accepted_bases": z.any().refine((value) => !z.array(z.any().refine((value) => !z.literal("verified").safeParse(value).success, "Invalid input: Should NOT be valid against schema")).safeParse(value).success, "Invalid input: Should NOT be valid against schema") }))]))) }).catchall(z.any()).describe("Canonical demographic audience targeting intent with optional constraints on how age may be determined. This is distinct from age_restriction: demographics selects an audience, while age_restriction expresses a legal eligibility or verification floor. Fresh create/update targeting MUST compile exactly or be rejected. During get_products, a seller may offer a different configured predicate only through sparse targeting_resolution modifications on a distinguishable product_id; selecting that product accepts the alternative. Sellers never silently broaden, narrow, default, drop, or substitute the basis.").optional(), "frequency_cap": z.object({ "suppress": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").describe("Cooldown period between consecutive exposures to the same entity. Prevents back-to-back ad delivery (e.g. {\"interval\": 60, \"unit\": \"minutes\"} for a 1-hour cooldown). Preferred over suppress_minutes.").optional(), "suppress_minutes": z.number().gte(0).describe("Deprecated — use suppress instead. Cooldown period in minutes between consecutive exposures to the same entity (e.g. 60 for a 1-hour cooldown).").optional(), "max_impressions": z.number().int().gte(1).describe("Maximum number of impressions per entity per window. For duration windows, implementations typically use a rolling window. campaign applies across the owning field's full flight: the package flight for a targeting overlay, or the MediaBuy flight for a root cap.").optional(), "per": z.enum(["individuals","households","devices","accounts","cookies","custom"]).describe("Unit of measurement for reach and audience size metrics. Different channels and measurement providers count reach in fundamentally different units, making cross-channel comparison impossible without declaring the unit.").describe("Entity granularity for impression counting. Required when max_impressions is set.").optional(), "window": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").describe("Time window for the max_impressions cap (e.g. {\"interval\": 7, \"unit\": \"days\"} or {\"interval\": 1, \"unit\": \"campaign\"} for the full flight). Required when max_impressions is set.").optional() }).catchall(z.any()).and(z.union([z.object({ "suppress": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "suppress_minutes": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max_impressions": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).and(z.intersection(z.union([z.any().refine((value) => !z.object({ "max_impressions": z.any().refine((value) => value !== undefined, "Required") }).passthrough().safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.object({ "max_impressions": z.any().refine((value) => value !== undefined, "Required"), "per": z.any().refine((value) => value !== undefined, "Required"), "window": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]), z.intersection(z.union([z.any().refine((value) => !z.object({ "per": z.any().refine((value) => value !== undefined, "Required") }).passthrough().safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.object({ "per": z.any().refine((value) => value !== undefined, "Required"), "max_impressions": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]), z.union([z.any().refine((value) => !z.object({ "window": z.any().refine((value) => value !== undefined, "Required") }).passthrough().safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.object({ "window": z.any().refine((value) => value !== undefined, "Required"), "max_impressions": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])))).describe("Frequency capping settings for package-level application. Two types of frequency control can be used independently or together: suppress enforces a cooldown between consecutive exposures; max_impressions + per + window caps total exposures per entity in a time window. When both suppress and max_impressions are set, an impression is delivered only if both constraints permit it (AND semantics). At least one of suppress, suppress_minutes, or max_impressions must be set. Field location determines scope; this value has no scope discriminator. The MediaBuy root uses the narrower media-buy-frequency-cap schema, which permits maximum impressions only in 3.2.").optional(), "property_list": z.object({ "agent_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the agent managing the property list"), "list_id": z.string().min(1).describe("Identifier for the property list within the agent"), "auth_token": z.string().describe("JWT or other authorization token for accessing the list. Optional if the list is public or caller has implicit access.").optional() }).passthrough().describe("Reference to a property list for targeting specific properties within this product. The package runs on the intersection of the product's publisher_properties and this list. Sellers SHOULD return a validation error if the product has property_targeting_allowed: false.").optional(), "property_list_exclude": z.object({ "agent_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the agent managing the property list"), "list_id": z.string().min(1).describe("Identifier for the property list within the agent"), "auth_token": z.string().describe("JWT or other authorization token for accessing the list. Optional if the list is public or caller has implicit access.").optional() }).passthrough().describe("Reference to a property list whose properties must not carry the buyer's ads. Matched properties are removed from delivery. Use for brand-safety do-not-run lists (apps, sites). Exclude wins on overlap with property_list, and applies regardless of the product's property_targeting_allowed flag. Seller must declare support in get_adcp_capabilities.").optional(), "collection_list": z.object({ "agent_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the agent managing the collection list"), "list_id": z.string().min(1).describe("Identifier for the collection list within the agent"), "auth_token": z.string().describe("JWT or other authorization token for accessing the list. Optional if the list is public or caller has implicit access.").optional() }).passthrough().describe("Reference to a collection list for including specific collections (programs, publications, channels) within this product. The package runs on the intersection of matched collections and this list. Use for inclusion-based collection targeting. Seller must declare support in get_adcp_capabilities.").optional(), "collection_list_exclude": z.object({ "agent_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the agent managing the collection list"), "list_id": z.string().min(1).describe("Identifier for the collection list within the agent"), "auth_token": z.string().describe("JWT or other authorization token for accessing the list. Optional if the list is public or caller has implicit access.").optional() }).passthrough().describe("Reference to a collection list for excluding specific collections (programs, publications, channels) from this product. Matched collections must not carry the buyer's ads. Use for brand safety do-not-air lists. Seller must declare support in get_adcp_capabilities.").optional(), "placement_selection": z.record(z.string(), z.any()).and(z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "mode": z.literal("selected"), "placement_refs": z.array(z.union([z.intersection(z.object({ "publisher_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain where the adagents.json declaring a publisher-catalog placement is hosted, or the inventory publisher associated with an inline placement. Omitted only for legacy single-publisher product-context references.").optional(), "placement_id": z.string().describe("Placement ID from the publisher's adagents.json placement catalog, or an inline seller-defined placement ID interpreted within the enclosing seller and product context.") }).catchall(z.any()).describe("Legacy-compatible product-context reference to a placement. For publisher-catalog placements, publisher_domain plus placement_id resolves the declaration in that publisher's adagents.json. For seller-inline placements, the enclosing seller and product supply scope. When publisher_domain is omitted on legacy inputs, receivers MAY interpret the ID relative to the enclosing single-publisher product. Use placement-identity.json when a self-contained cross-document identity is required."), z.object({ "publisher_domain": z.any().refine((value) => value !== undefined, "Required") }).passthrough()), z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "kind": z.literal("publisher_ref"), "publisher_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain whose adagents.json declares placement_id."), "placement_id": z.string().min(1) }).passthrough(), z.object({ "kind": z.literal("seller_inline"), "seller_agent": z.object({ "agent_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("The seller agent's API endpoint URL as declared in the property publisher's adagents.json `authorized_agents[].url`. MUST use the `https://` scheme. Receivers compare this URL against the `authorized_agents` list using the AdCP URL canonicalization rules — not byte-equality — and reject mismatches with `seller_not_authorized`. See docs/reference/url-canonicalization."), "id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).min(1).describe("Reserved for a future registry-assigned stable seller identifier. Not used today — senders MUST NOT populate this field until a registry is defined. When a future release populates both `agent_url` and `id`, `agent_url` remains authoritative and `id` is advisory.").optional() }).passthrough().describe("Sales agent that defines and maintains the inline placement namespace."), "placement_id": z.string().min(1).describe("Stable placement ID within the defining sales agent's namespace. The agent MUST NOT reuse it for a different semantic placement.") }).passthrough()]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17468,7 +15427,7 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - }).describe("DEPRECATED. Use signal_ref instead. Legacy SignalId retained for compatibility with older clients.").optional(), "value_type": z.literal("numeric").describe("Discriminator for numeric signals"), "min_value": z.number().describe("Minimum value (inclusive). Omit for no minimum. Must be <= max_value when both are provided. Should be >= signal's range.min if defined.").optional(), "max_value": z.number().describe("Maximum value (inclusive). Omit for no maximum. Must be >= min_value when both are provided. Should be <= signal's range.max if defined.").optional() }).catchall(z.any()).and(z.union([z.object({ "signal_ref": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "signal_id": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("Numeric signal targeting - target users within a value range. If min_value is provided, it must be <= max_value. Values should be within the signal's defined range (see signal definition).")]; + }).describe("Self-contained identity for either a publisher-catalog placement or a sales-agent-defined inline placement. The discriminator names which authority owns placement_id.")])).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Complete required placement set. A reference normally identifies a mode targetable placement. It MAY identify a mode included placement only when the set exactly equals the product's complete fixed included set, which is an inherent match rather than independent selection. Legacy publisher refs use {publisher_domain, placement_id}; authority-discriminated 3.2 identities use placement-identity.json so seller-inline inventory is selected by {seller_agent, placement_id}. An item that exactly matches placement-identity uses that canonical identity; otherwise a released-compatible item with publisher_domain and placement_id uses legacy product-context matching, and tolerated product metadata such as kind, name, or mode has no selection effect."), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough(), z.object({ "mode": z.literal("default"), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough()]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17499,9 +15458,8 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - }).describe("Targeting constraint for a specific signal. Uses value_type as discriminator to determine the targeting expression format.")).min(1).describe("DEPRECATED. Use signal_targeting_groups for package-level signal targeting. Legacy flat signal_targeting remains accepted during the SignalRef migration window but cannot express grouped include/exclude composition or product-scoped pricing.").optional(), "demographics": z.object({ "age": z.intersection(z.object({ "min": z.number().int().gte(0).lte(150).describe("Inclusive minimum age in completed years. Omit for an open lower bound.").optional(), "max": z.number().int().gte(0).lte(150).describe("Inclusive maximum age in completed years. Omit for an open upper bound.").optional(), "include_unknown": z.boolean().describe("Whether delivery to people whose age is unavailable is part of this predicate. This field has no default and MUST be supplied.") }).catchall(z.any()).and(z.union([z.object({ "min": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A canonical audience-age predicate in completed integer years. min and max are inclusive; omitting one bound means no restriction in that direction. At least one bound is required. include_unknown is always explicit because people whose age is unavailable are not members of any numeric interval. Implementations MUST reject min greater than max; JSON Schema draft-07 cannot compare sibling numeric values."), z.object({ "accepted_bases": z.array(z.enum(["verified","declared","inferred"]).describe("User-level bases that may resolve age for demographic targeting execution. Population estimates are deliberately absent because aggregate composition cannot establish an individual impression's age.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("User-level age determination bases the buyer permits for this predicate. Sellers MUST use only these bases or reject the request; they MUST NOT silently fall back to another basis. When omitted, the buyer imposes no determination-basis constraint beyond product capability and any age_restriction. population_estimate is structurally unavailable because aggregate evidence cannot identify an eligible user.").optional(), "accepted_verification_methods": z.array(z.enum(["facial_age_estimation","id_document","digital_id","credit_card","world_id"]).describe("Methods for verifying user age for compliance. Does not include 'inferred' as it is not accepted for regulatory compliance.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Verification methods acceptable when verified is an accepted basis. This field narrows verified demographic execution; age_restriction.accepted_methods independently governs legal eligibility and the two sets are intersected when both are present.").optional() }).catchall(z.any()).and(z.union([z.any().refine((value) => !z.object({ "accepted_verification_methods": z.any().refine((value) => value !== undefined, "Required") }).passthrough().safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "accepted_verification_methods": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "accepted_bases": z.any().refine((value) => !z.array(z.any().refine((value) => !z.literal("verified").safeParse(value).success, "Invalid input: Should NOT be valid against schema")).safeParse(value).success, "Invalid input: Should NOT be valid against schema") }))]))) }).catchall(z.any()).describe("Canonical demographic audience targeting intent with optional constraints on how age may be determined. This is distinct from age_restriction: demographics selects an audience, while age_restriction expresses a legal eligibility or verification floor. Fresh create/update targeting MUST compile exactly or be rejected. During get_products, a seller may offer a different configured predicate only through sparse targeting_resolution modifications on a distinguishable product_id; selecting that product accepts the alternative. Sellers never silently broaden, narrow, default, drop, or substitute the basis.").optional(), "frequency_cap": z.object({ "suppress": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").describe("Cooldown period between consecutive exposures to the same entity. Prevents back-to-back ad delivery (e.g. {\"interval\": 60, \"unit\": \"minutes\"} for a 1-hour cooldown). Preferred over suppress_minutes.").optional(), "suppress_minutes": z.number().gte(0).describe("Deprecated — use suppress instead. Cooldown period in minutes between consecutive exposures to the same entity (e.g. 60 for a 1-hour cooldown).").optional(), "max_impressions": z.number().int().gte(1).describe("Maximum number of impressions per entity per window. For duration windows, implementations typically use a rolling window; 'campaign' applies a fixed cap across the full flight.").optional(), "per": z.enum(["individuals","households","devices","accounts","cookies","custom"]).describe("Unit of measurement for reach and audience size metrics. Different channels and measurement providers count reach in fundamentally different units, making cross-channel comparison impossible without declaring the unit.").describe("Entity granularity for impression counting. Required when max_impressions is set.").optional(), "window": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").describe("Time window for the max_impressions cap (e.g. {\"interval\": 7, \"unit\": \"days\"} or {\"interval\": 1, \"unit\": \"campaign\"} for the full flight). Required when max_impressions is set.").optional() }).catchall(z.any()).and(z.union([z.object({ "suppress": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "suppress_minutes": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max_impressions": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).and(z.intersection(z.union([z.any().refine((value) => !z.object({ "max_impressions": z.any().refine((value) => value !== undefined, "Required") }).passthrough().safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.object({ "max_impressions": z.any().refine((value) => value !== undefined, "Required"), "per": z.any().refine((value) => value !== undefined, "Required"), "window": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]), z.intersection(z.union([z.any().refine((value) => !z.object({ "per": z.any().refine((value) => value !== undefined, "Required") }).passthrough().safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.object({ "per": z.any().refine((value) => value !== undefined, "Required"), "max_impressions": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]), z.union([z.any().refine((value) => !z.object({ "window": z.any().refine((value) => value !== undefined, "Required") }).passthrough().safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.object({ "window": z.any().refine((value) => value !== undefined, "Required"), "max_impressions": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])))).describe("Frequency capping settings for package-level application. Two types of frequency control can be used independently or together: suppress enforces a cooldown between consecutive exposures; max_impressions + per + window caps total exposures per entity in a time window. When both suppress and max_impressions are set, an impression is delivered only if both constraints permit it (AND semantics). At least one of suppress, suppress_minutes, or max_impressions must be set.").optional(), "property_list": z.object({ "agent_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the agent managing the property list"), "list_id": z.string().min(1).describe("Identifier for the property list within the agent"), "auth_token": z.string().describe("JWT or other authorization token for accessing the list. Optional if the list is public or caller has implicit access.").optional() }).passthrough().describe("Reference to a property list for targeting specific properties within this product. The package runs on the intersection of the product's publisher_properties and this list. Sellers SHOULD return a validation error if the product has property_targeting_allowed: false.").optional(), "property_list_exclude": z.object({ "agent_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the agent managing the property list"), "list_id": z.string().min(1).describe("Identifier for the property list within the agent"), "auth_token": z.string().describe("JWT or other authorization token for accessing the list. Optional if the list is public or caller has implicit access.").optional() }).passthrough().describe("Reference to a property list whose properties must not carry the buyer's ads. Matched properties are removed from delivery. Use for brand-safety do-not-run lists (apps, sites). Exclude wins on overlap with property_list, and applies regardless of the product's property_targeting_allowed flag. Seller must declare support in get_adcp_capabilities.").optional(), "collection_list": z.object({ "agent_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the agent managing the collection list"), "list_id": z.string().min(1).describe("Identifier for the collection list within the agent"), "auth_token": z.string().describe("JWT or other authorization token for accessing the list. Optional if the list is public or caller has implicit access.").optional() }).passthrough().describe("Reference to a collection list for including specific collections (programs, publications, channels) within this product. The package runs on the intersection of matched collections and this list. Use for inclusion-based collection targeting. Seller must declare support in get_adcp_capabilities.").optional(), "collection_list_exclude": z.object({ "agent_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the agent managing the collection list"), "list_id": z.string().min(1).describe("Identifier for the collection list within the agent"), "auth_token": z.string().describe("JWT or other authorization token for accessing the list. Optional if the list is public or caller has implicit access.").optional() }).passthrough().describe("Reference to a collection list for excluding specific collections (programs, publications, channels) from this product. Matched collections must not carry the buyer's ads. Use for brand safety do-not-air lists. Seller must declare support in get_adcp_capabilities.").optional(), "placement_selection": z.record(z.string(), z.any()).and(z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "mode": z.literal("selected"), "placement_refs": z.array(z.union([z.intersection(z.object({ "publisher_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain where the adagents.json declaring a publisher-catalog placement is hosted, or the inventory publisher associated with an inline placement. Omitted only for legacy single-publisher product-context references.").optional(), "placement_id": z.string().describe("Placement ID from the publisher's adagents.json placement catalog, or an inline seller-defined placement ID interpreted within the enclosing seller and product context.") }).catchall(z.any()).describe("Legacy-compatible product-context reference to a placement. For publisher-catalog placements, publisher_domain plus placement_id resolves the declaration in that publisher's adagents.json. For seller-inline placements, the enclosing seller and product supply scope. When publisher_domain is omitted on legacy inputs, receivers MAY interpret the ID relative to the enclosing single-publisher product. Use placement-identity.json when a self-contained cross-document identity is required."), z.object({ "publisher_domain": z.any().refine((value) => value !== undefined, "Required") }).passthrough()), z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "kind": z.literal("publisher_ref"), "publisher_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain whose adagents.json declares placement_id."), "placement_id": z.string().min(1) }).passthrough(), z.object({ "kind": z.literal("seller_inline"), "seller_agent": z.object({ "agent_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("The seller agent's API endpoint URL as declared in the property publisher's adagents.json `authorized_agents[].url`. MUST use the `https://` scheme. Receivers compare this URL against the `authorized_agents` list using the AdCP URL canonicalization rules — not byte-equality — and reject mismatches with `seller_not_authorized`. See docs/reference/url-canonicalization."), "id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).min(1).describe("Reserved for a future registry-assigned stable seller identifier. Not used today — senders MUST NOT populate this field until a registry is defined. When a future release populates both `agent_url` and `id`, `agent_url` remains authoritative and `id` is advisory.").optional() }).passthrough().describe("Sales agent that defines and maintains the inline placement namespace."), "placement_id": z.string().min(1).describe("Stable placement ID within the defining sales agent's namespace. The agent MUST NOT reuse it for a different semantic placement.") }).passthrough()]; + })).describe("Purchased placement selection within the product. This constrains package inventory; it is distinct from creative_assignments[].placement_refs, which only route individual creatives within the purchased set. On create, mode selected supplies the complete selected set and mode default uses the product default. In request-side Targeting Input, a non-null value replaces this dimension, omission preserves or inherits it, and null clears it when the product permits that broader inventory set.").optional(), "collection_selection": z.record(z.string(), z.any()).and(z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "mode": z.literal("selected"), "collections": z.array(z.intersection(z.object({ "publisher_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain where the adagents.json declaring these collections is hosted (e.g., 'mrbeast.com'). The collections array in that file contains the authoritative collection definitions."), "collection_ids": z.array(z.string()).min(1).describe("Collection IDs from the adagents.json collections array. Each ID must match a collection_id declared in that file. Omit to reference all collections declared in that file.").optional() }).catchall(z.any()).describe("References collections declared in an adagents.json. Buyers resolve full collection objects by fetching the adagents.json at the given domain and matching collection_ids against its collections array. When collection_ids is omitted, the selector references every collection declared in that adagents.json — the bulk-grant form for authorization scoping (e.g., a host authorizing a channel owner's sales agent for all of the owner's collections without tracking owner-assigned IDs)."), z.object({ "collection_ids": z.any().refine((value) => value !== undefined, "Required") }).passthrough())).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Complete required collection set as domain-qualified selectors with explicit collection_ids; the domain-only bulk-grant form is authorization scoping, not selection. publisher_domain may be an external channel owner's domain."), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough(), z.object({ "mode": z.literal("default"), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough()]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17532,7 +15490,8 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - }).describe("Self-contained identity for either a publisher-catalog placement or a sales-agent-defined inline placement. The discriminator names which authority owns placement_id.")])).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Complete required placement set. A reference normally identifies a mode targetable placement. It MAY identify a mode included placement only when the set exactly equals the product's complete fixed included set, which is an inherent match rather than independent selection. Legacy publisher refs use {publisher_domain, placement_id}; authority-discriminated 3.2 identities use placement-identity.json so seller-inline inventory is selected by {seller_agent, placement_id}. An item that exactly matches placement-identity uses that canonical identity; otherwise a released-compatible item with publisher_domain and placement_id uses legacy product-context matching, and tolerated product metadata such as kind, name, or mode has no selection effect."), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough(), z.object({ "mode": z.literal("default"), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough()]; + })).describe("Purchased collection selection within the product. On create, mode selected supplies the complete selected set and mode default uses the product's full bundle. On package readback this is the committed selection sellers MUST echo as concrete selectors, materializing any collection_list composition; collection_list fields remain the buyer-managed list mechanism. In request-side Targeting Input, a non-null value replaces this dimension, omission preserves or inherits it, and null clears it when the product permits that broader inventory set.").optional(), "age_restriction": z.object({ "min": z.number().int().gte(13).lte(99).describe("Minimum age required"), "verification_required": z.boolean().describe("Whether verified age (not inferred) is required for compliance").default(false), "accepted_methods": z.array(z.enum(["facial_age_estimation","id_document","digital_id","credit_card","world_id"]).describe("Methods for verifying user age for compliance. Does not include 'inferred' as it is not accepted for regulatory compliance.")).min(1).describe("Accepted verification methods. If omitted, any method the platform supports is acceptable.").optional() }).passthrough().describe("Age restriction for compliance. Use for legal requirements (alcohol, gambling), not audience targeting.").optional(), "device_platform": z.array(z.enum(["ios","android","windows","macos","linux","chromeos","tvos","tizen","webos","fire_os","roku_os","unknown"]).describe("Operating system platforms for device targeting. Browser values from Sec-CH-UA-Platform standard, extended for CTV.")).min(1).describe("Restrict to specific platforms. Use for technical compatibility (app only works on iOS). Values from Sec-CH-UA-Platform standard, extended for CTV.").optional(), "device_platform_exclude": z.array(z.enum(["ios","android","windows","macos","linux","chromeos","tvos","tizen","webos","fire_os","roku_os","unknown"]).describe("Operating system platforms for device targeting. Browser values from Sec-CH-UA-Platform standard, extended for CTV.")).min(1).describe("Exclude specific operating-system platforms from delivery. When a platform appears in both device_platform and device_platform_exclude, exclusion wins. Sellers MUST reject a request they cannot enforce rather than silently dropping the exclusion.").optional(), "device_type": z.array(z.enum(["desktop","mobile","tablet","ctv","dooh","unknown"]).describe("Device form factor categories for targeting and reporting. Complements device-platform (operating system) with hardware classification. OpenRTB mapping: 1 (Mobile/Tablet General) → mobile, 2 (PC) → desktop, 4 (Phone) → mobile, 5 (Tablet) → tablet, 6 (Connected Device) → ctv, 7 (Set Top Box) → ctv. DOOH inventory uses dooh.")).min(1).describe("Restrict to specific device form factors. Use for campaigns targeting hardware categories rather than operating systems (e.g., mobile-only promotions, CTV campaigns).").optional(), "device_type_exclude": z.array(z.enum(["desktop","mobile","tablet","ctv","dooh","unknown"]).describe("Device form factor categories for targeting and reporting. Complements device-platform (operating system) with hardware classification. OpenRTB mapping: 1 (Mobile/Tablet General) → mobile, 2 (PC) → desktop, 4 (Phone) → mobile, 5 (Tablet) → tablet, 6 (Connected Device) → ctv, 7 (Set Top Box) → ctv. DOOH inventory uses dooh.")).min(1).describe("Exclude specific device form factors from delivery (e.g., exclude CTV for app-install campaigns).").optional(), "browser": z.array(z.enum(["chrome","safari","firefox","edge","opera","samsung_internet","android_webview","other","unknown"]).describe("Portable browser families for targeting the impression delivery and rendering environment, not a post-click landing-page browser. Values identify browser families, not versions or seller-native browser IDs, and MUST NOT be inferred solely from operating system, device, web/mobile-web inventory, or placement. android_webview means an impression reliably classified as rendering in Android WebView. other means a seller-recognized browser family that is not explicitly enumerated; unknown means the seller cannot classify the browser into a recognized family.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Restrict delivery to specific canonical browser families in the impression delivery and rendering environment, not the post-click landing-page browser. Values MUST NOT be inferred solely from operating system, device, web/mobile-web inventory, or placement. Values in this array use OR semantics. When browser is supplied, families not listed are ineligible: other includes a seller-recognized family that is not explicitly enumerated, while unknown includes a browser the seller cannot classify into a recognized family. When the same family appears in browser and browser_exclude, exclusion wins. Browser and device constraints intersect; a seller that cannot enforce the exact combination MUST exclude or explicitly reconfigure the product during discovery and MUST reject it at create or update rather than silently widening delivery. Browser versions and seller-native IDs are intentionally unsupported.").optional(), "browser_exclude": z.array(z.enum(["chrome","safari","firefox","edge","opera","samsung_internet","android_webview","other","unknown"]).describe("Portable browser families for targeting the impression delivery and rendering environment, not a post-click landing-page browser. Values identify browser families, not versions or seller-native browser IDs, and MUST NOT be inferred solely from operating system, device, web/mobile-web inventory, or placement. android_webview means an impression reliably classified as rendering in Android WebView. other means a seller-recognized browser family that is not explicitly enumerated; unknown means the seller cannot classify the browser into a recognized family.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Exclude specific canonical browser families from delivery. other excludes seller-recognized families that are not explicitly enumerated; unknown excludes browsers the seller cannot classify into a recognized family. When the same family appears in browser and browser_exclude, exclusion wins. Sellers MUST reject a request they cannot enforce rather than silently dropping the exclusion.").optional(), "store_catchments": z.array(z.object({ "catalog_id": z.string().describe("Synced store-type catalog ID from sync_catalogs."), "store_ids": z.array(z.string()).min(1).describe("Filter to specific stores within the catalog. Omit to target all stores.").optional(), "catchment_ids": z.array(z.string()).min(1).describe("Catchment zone IDs to target (e.g., 'walk', 'drive'). Omit to target all catchment zones.").optional() }).catchall(z.any())).min(1).describe("Target users within store catchment areas from a synced store catalog. Each entry references a store-type catalog and optionally narrows to specific stores or catchment zones.").optional(), "geo_proximity": z.array(z.object({ "lat": z.number().gte(-90).lte(90).describe("Latitude in decimal degrees (WGS 84). Required for travel_time and radius methods.").optional(), "lng": z.number().gte(-180).lte(180).describe("Longitude in decimal degrees (WGS 84). Required for travel_time and radius methods.").optional(), "label": z.string().describe("Human-readable label for this entry (e.g., 'Düsseldorf', 'Heathrow Airport', 'Primary trade area').").optional(), "travel_time": z.object({ "value": z.number().gte(1).describe("Travel time limit."), "unit": z.enum(["min","hr"]).describe("Time unit for isochrone (travel-time catchment) calculations.") }).passthrough().describe("Travel time limit for isochrone calculation. The platform resolves this to a geographic boundary based on actual transportation networks.").optional(), "transport_mode": z.enum(["walking","cycling","driving","public_transport"]).describe("Transportation mode for isochrone calculation. Required when travel_time is provided.").optional(), "radius": z.object({ "value": z.number().gt(0).describe("Radius distance."), "unit": z.enum(["km","mi","m"]).describe("Distance unit.") }).passthrough().describe("Simple radius from the point. The platform draws a circle of this distance around the coordinates.").optional(), "geometry": z.object({ "type": z.enum(["Polygon","MultiPolygon"]).describe("GeoJSON geometry type."), "coordinates": z.array(z.any()).describe("GeoJSON coordinates array. For Polygon: array of linear rings. For MultiPolygon: array of polygons.") }).passthrough().describe("Pre-computed GeoJSON geometry defining the proximity boundary. Use when the buyer has already calculated isochrones (via TravelTime, Mapbox, etc.) or has custom boundaries. When geometry is provided, lat/lng are not required.").optional(), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).catchall(z.any()).and(z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "lat": z.any().refine((value) => value !== undefined, "Required"), "lng": z.any().refine((value) => value !== undefined, "Required"), "travel_time": z.any().refine((value) => value !== undefined, "Required"), "transport_mode": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "lat": z.any().refine((value) => value !== undefined, "Required"), "lng": z.any().refine((value) => value !== undefined, "Required"), "radius": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "geometry": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17563,8 +15522,8 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - })).describe("Purchased placement selection within the product. This constrains package inventory; it is distinct from creative_assignments[].placement_refs, which only route individual creatives within the purchased set. On create, mode selected supplies the complete selected set and mode default uses the product default. On update, the surrounding targeting_overlay replacement semantics apply.").optional(), "collection_selection": z.record(z.string(), z.any()).and(z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "mode": z.literal("selected"), "collections": z.array(z.intersection(z.object({ "publisher_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain where the adagents.json declaring these collections is hosted (e.g., 'mrbeast.com'). The collections array in that file contains the authoritative collection definitions."), "collection_ids": z.array(z.string()).min(1).describe("Collection IDs from the adagents.json collections array. Each ID must match a collection_id declared in that file. Omit to reference all collections declared in that file.").optional() }).catchall(z.any()).describe("References collections declared in an adagents.json. Buyers resolve full collection objects by fetching the adagents.json at the given domain and matching collection_ids against its collections array. When collection_ids is omitted, the selector references every collection declared in that adagents.json — the bulk-grant form for authorization scoping (e.g., a host authorizing a channel owner's sales agent for all of the owner's collections without tracking owner-assigned IDs)."), z.object({ "collection_ids": z.any().refine((value) => value !== undefined, "Required") }).passthrough())).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Complete required collection set as domain-qualified selectors with explicit collection_ids; the domain-only bulk-grant form is authorization scoping, not selection. publisher_domain may be an external channel owner's domain."), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough(), z.object({ "mode": z.literal("default"), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough()]; + }))).min(1).describe("Target users within travel time, distance, or a custom boundary around arbitrary geographic points. Multiple entries use OR semantics — a user within range of any listed point is eligible. For campaigns targeting 10+ locations, consider using store_catchments with a location catalog instead. Seller must declare support in get_adcp_capabilities.").optional(), "language": z.array(z.string().regex(new RegExp("^(?:[a-z]{2,8}(?:-[A-Z][a-z]{3})?(?:-(?:[A-Z]{2}|[0-9]{3}))?(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*(?:-x(?:-[a-z0-9]{1,8})+)?|x(?:-[a-z0-9]{1,8})+)$")).min(2).max(63).describe("A well-formed BCP 47 language tag used by AdCP only as language identity. Script and region may refine that identity; other valid BCP 47 subtags remain part of tag matching but do not make this a general locale-settings object. It does not determine currency, time zone, number/date formatting, market, or legal jurisdiction. The AdCP canonical wire profile requires lower-case language and variants, title-case script, and upper-case region (for example `en-US`, `zh-Hant-TW`, or `x-private`). RFC 5646 comparisons are case-insensitive and its case regularization is optional; AdCP intentionally requires this stricter single wire spelling and receivers MUST reject differently cased tags rather than silently normalizing them. The schema pattern enforces the AdCP casing profile and extension structure for commonly used tags; conforming receivers additionally validate the complete RFC 5646 grammar and registry rules. Every new AdCP field carrying BCP 47 language identity or a concrete language range MUST reference this schema instead of declaring independent string constraints.")).min(1).describe("Restrict to users with specific language preferences using canonical BCP 47 language ranges. Each buyer range is evaluated against a user's language-preference tag with RFC 4647 section 3.3.1 Basic Filtering: 'fr' matches 'fr', 'fr-CA', and 'fr-FR', while 'fr-CA' matches 'fr-CA' and more-specific descendants but not 'fr' or 'fr-FR'. Values use OR logic.").optional(), "keyword_targets": z.array(z.object({ "keyword": z.string().min(1).describe("The keyword to target"), "match_type": z.enum(["broad","phrase","exact"]).describe("Keyword targeting match type. broad: ads may serve on queries semantically related to the keyword. phrase: ads serve when the query contains the keyword phrase. exact: ads serve only when the query matches the keyword exactly."), "bid_price": z.number().gte(0).describe("Per-keyword bid price, denominated in the same currency as the package's pricing option. Overrides the package-level bid_price for this keyword. Inherits the max_bid interpretation from the pricing option: when max_bid is true, this is the keyword's bid ceiling; when false, this is the exact bid. If omitted, the package bid_price applies.").optional() }).passthrough()).min(1).describe("Keyword targeting for search and retail media platforms. Restricts delivery to queries matching the specified keywords. Each keyword is identified by the tuple (keyword, match_type) — the same keyword string with different match types are distinct targets. Sellers SHOULD reject duplicate (keyword, match_type) pairs within a single request. Seller must declare support in get_adcp_capabilities.").optional(), "negative_keywords": z.array(z.object({ "keyword": z.string().min(1).describe("The keyword to exclude"), "match_type": z.enum(["broad","phrase","exact"]).describe("Keyword targeting match type. broad: ads may serve on queries semantically related to the keyword. phrase: ads serve when the query contains the keyword phrase. exact: ads serve only when the query matches the keyword exactly.") }).passthrough().describe("An excluded keyword.")).min(1).describe("Keywords to exclude from delivery. Queries matching these keywords will not trigger the ad. Each negative keyword is identified by the tuple (keyword, match_type). Seller must declare support in get_adcp_capabilities.").optional() }).catchall(z.any()).and(z.intersection(z.union([z.any().refine((value) => !z.object({ "demographics": z.any().refine((value) => value !== undefined, "Required"), "age_restriction": z.any().refine((value) => value !== undefined, "Required") }).passthrough().safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "demographics": z.any().refine((value) => value !== undefined, "Required"), "age_restriction": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "demographics": z.object({ "age": z.object({ "include_unknown": z.literal(false).optional() }).optional() }).optional() }))]).describe("Unknown-age delivery cannot satisfy a minimum-age eligibility policy. When demographic audience targeting and age_restriction are both present, include_unknown must be false."), z.union([z.any().refine((value) => !z.object({ "age_restriction": z.object({ "verification_required": z.literal(true) }), "demographics": z.object({ "age": z.object({ "accepted_bases": z.any().refine((value) => value !== undefined, "Required") }).passthrough() }) }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "age_restriction": z.object({ "verification_required": z.literal(true) }), "demographics": z.object({ "age": z.object({ "accepted_bases": z.any().refine((value) => value !== undefined, "Required") }).passthrough() }) }), z.object({ "demographics": z.object({ "age": z.object({ "accepted_bases": z.any().refine((value) => !z.array(z.any().refine((value) => !z.literal("verified").safeParse(value).success, "Invalid input: Should NOT be valid against schema")).safeParse(value).success, "Invalid input: Should NOT be valid against schema").optional() }).optional() }).optional() }))]).describe("A legal verification requirement always narrows demographic targeting. When the buyer supplies accepted_bases and age_restriction requires verification, verified must be accepted; otherwise the constraints have an empty intersection and the request is invalid."))).describe("Resolved effective buyer-selected targeting, including compatible wholesale signal selections, applied within the product's published targeting contract. Cleared dimensions are omitted; null is invalid in an accepted snapshot.").optional(), "optimization_goals": z.array(z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "kind": z.literal("metric"), "metric": z.enum(["clicks","views","completed_views","viewed_seconds","engagements","follows","saves","profile_visits","reach"]), "reach_unit": z.enum(["individuals","households","devices","accounts","cookies","custom"]).describe("Unit of measurement for reach and audience size metrics. Different channels and measurement providers count reach in fundamentally different units, making cross-channel comparison impossible without declaring the unit.").optional(), "target_frequency": z.object({ "min": z.number().int().gte(1).optional(), "max": z.number().int().gte(1).optional(), "window": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.") }).passthrough().and(z.union([z.object({ "min": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).optional(), "view_duration_seconds": z.number().gt(0).optional(), "target": z.object({ "kind": z.literal("threshold_rate"), "value": z.number().gt(0) }).passthrough().optional(), "priority": z.number().int().gte(1).optional() }).passthrough(), z.object({ "kind": z.literal("event"), "event_sources": z.array(z.object({ "event_source_id": z.string().min(1), "event_type": z.enum(["page_view","view_content","select_content","select_item","search","share","add_to_cart","remove_from_cart","viewed_cart","add_to_wishlist","initiate_checkout","add_payment_info","purchase","refund","lead","qualify_lead","close_convert_lead","disqualify_lead","complete_registration","subscribe","follow","content_view","watch_milestone","start_trial","app_install","app_launch","contact","schedule","donate","submit_application","custom"]).describe("Standard marketing event types for event logging, aligned with IAB ECAPI"), "custom_event_name": z.string().min(1).optional(), "value_field": z.string().min(1).optional(), "value_factor": z.number().default(1) }).passthrough()).min(1), "target": z.object({ "kind": z.literal("maximize_value") }).passthrough().optional(), "attribution_window": z.object({ "post_click": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").describe("Post-click attribution window. Conversions occurring within this duration after a click are attributed to the ad.").optional(), "post_view": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").describe("Post-view attribution window. Conversions occurring within this duration after an ad impression (without click) are attributed to the ad.").optional(), "model": z.enum(["last_touch","first_touch","linear","time_decay","data_driven"]).describe("Attribution model used to assign credit when multiple touchpoints exist. SHOULD be populated when committing to a specific model; when absent, the seller's default applies.").optional() }).catchall(z.any()).describe("Describes the attribution methodology and lookback windows used for conversion measurement. Enables cross-platform comparison by making attribution methodology transparent. Used as a `$ref` from `optimization-goal.json` (buyer's optimization-time attribution choice), `get-media-buy-delivery-response.json` (seller-declared attribution methodology in delivery reports), and similar surfaces. All fields are optional individually but at least one of `post_click`, `post_view`, or `model` SHOULD be populated; absence of `model` means the seller's default attribution model applies (typically `last_touch` per industry convention) — sellers SHOULD populate `model` explicitly when committing to a specific methodology.").optional(), "priority": z.number().int().gte(1).optional() }).passthrough(), z.object({ "kind": z.literal("vendor_metric"), "vendor": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery."), "metric_id": z.string().regex(new RegExp("^[a-z][a-z0-9_]*$")).min(1).max(64).describe("Identifier for a vendor-defined metric within the vendor's vocabulary. Stable lookup key; the vendor publishes the canonical list (with category, methodology, and standard alignment) in `brand.json` `agents[type='measurement']`. Lowercase with underscores so a future enum promotion into `available-metric.json` is a literal string lift. Identifier is namespaced by the vendor — the same `metric_id` may mean different things in different vendors' vocabularies."), "target": z.object({ "kind": z.literal("threshold_rate"), "value": z.number().gt(0) }).passthrough().optional(), "priority": z.number().int().gte(1).optional() }).passthrough()]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17595,8 +15554,8 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - })).describe("Purchased collection selection within the product. On create, mode selected supplies the complete selected set and mode default uses the product's full bundle. On package readback this is the committed selection sellers MUST echo as concrete selectors, materializing any collection_list composition; collection_list fields remain the buyer-managed list mechanism. On update, the surrounding targeting_overlay replacement semantics apply.").optional(), "age_restriction": z.object({ "min": z.number().int().gte(13).lte(99).describe("Minimum age required"), "verification_required": z.boolean().describe("Whether verified age (not inferred) is required for compliance").default(false), "accepted_methods": z.array(z.enum(["facial_age_estimation","id_document","digital_id","credit_card","world_id"]).describe("Methods for verifying user age for compliance. Does not include 'inferred' as it is not accepted for regulatory compliance.")).min(1).describe("Accepted verification methods. If omitted, any method the platform supports is acceptable.").optional() }).passthrough().describe("Age restriction for compliance. Use for legal requirements (alcohol, gambling), not audience targeting.").optional(), "device_platform": z.array(z.enum(["ios","android","windows","macos","linux","chromeos","tvos","tizen","webos","fire_os","roku_os","unknown"]).describe("Operating system platforms for device targeting. Browser values from Sec-CH-UA-Platform standard, extended for CTV.")).min(1).describe("Restrict to specific platforms. Use for technical compatibility (app only works on iOS). Values from Sec-CH-UA-Platform standard, extended for CTV.").optional(), "device_platform_exclude": z.array(z.enum(["ios","android","windows","macos","linux","chromeos","tvos","tizen","webos","fire_os","roku_os","unknown"]).describe("Operating system platforms for device targeting. Browser values from Sec-CH-UA-Platform standard, extended for CTV.")).min(1).describe("Exclude specific operating-system platforms from delivery. When a platform appears in both device_platform and device_platform_exclude, exclusion wins. Sellers MUST reject a request they cannot enforce rather than silently dropping the exclusion.").optional(), "device_type": z.array(z.enum(["desktop","mobile","tablet","ctv","dooh","unknown"]).describe("Device form factor categories for targeting and reporting. Complements device-platform (operating system) with hardware classification. OpenRTB mapping: 1 (Mobile/Tablet General) → mobile, 2 (PC) → desktop, 4 (Phone) → mobile, 5 (Tablet) → tablet, 6 (Connected Device) → ctv, 7 (Set Top Box) → ctv. DOOH inventory uses dooh.")).min(1).describe("Restrict to specific device form factors. Use for campaigns targeting hardware categories rather than operating systems (e.g., mobile-only promotions, CTV campaigns).").optional(), "device_type_exclude": z.array(z.enum(["desktop","mobile","tablet","ctv","dooh","unknown"]).describe("Device form factor categories for targeting and reporting. Complements device-platform (operating system) with hardware classification. OpenRTB mapping: 1 (Mobile/Tablet General) → mobile, 2 (PC) → desktop, 4 (Phone) → mobile, 5 (Tablet) → tablet, 6 (Connected Device) → ctv, 7 (Set Top Box) → ctv. DOOH inventory uses dooh.")).min(1).describe("Exclude specific device form factors from delivery (e.g., exclude CTV for app-install campaigns).").optional(), "browser": z.array(z.enum(["chrome","safari","firefox","edge","opera","samsung_internet","android_webview","other","unknown"]).describe("Portable browser families for targeting the impression delivery and rendering environment, not a post-click landing-page browser. Values identify browser families, not versions or seller-native browser IDs, and MUST NOT be inferred solely from operating system, device, web/mobile-web inventory, or placement. android_webview means an impression reliably classified as rendering in Android WebView. other means a seller-recognized browser family that is not explicitly enumerated; unknown means the seller cannot classify the browser into a recognized family.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Restrict delivery to specific canonical browser families in the impression delivery and rendering environment, not the post-click landing-page browser. Values MUST NOT be inferred solely from operating system, device, web/mobile-web inventory, or placement. Values in this array use OR semantics. When browser is supplied, families not listed are ineligible: other includes a seller-recognized family that is not explicitly enumerated, while unknown includes a browser the seller cannot classify into a recognized family. When the same family appears in browser and browser_exclude, exclusion wins. Browser and device constraints intersect; a seller that cannot enforce the exact combination MUST exclude or explicitly reconfigure the product during discovery and MUST reject it at create or update rather than silently widening delivery. Browser versions and seller-native IDs are intentionally unsupported.").optional(), "browser_exclude": z.array(z.enum(["chrome","safari","firefox","edge","opera","samsung_internet","android_webview","other","unknown"]).describe("Portable browser families for targeting the impression delivery and rendering environment, not a post-click landing-page browser. Values identify browser families, not versions or seller-native browser IDs, and MUST NOT be inferred solely from operating system, device, web/mobile-web inventory, or placement. android_webview means an impression reliably classified as rendering in Android WebView. other means a seller-recognized browser family that is not explicitly enumerated; unknown means the seller cannot classify the browser into a recognized family.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Exclude specific canonical browser families from delivery. other excludes seller-recognized families that are not explicitly enumerated; unknown excludes browsers the seller cannot classify into a recognized family. When the same family appears in browser and browser_exclude, exclusion wins. Sellers MUST reject a request they cannot enforce rather than silently dropping the exclusion.").optional(), "store_catchments": z.array(z.object({ "catalog_id": z.string().describe("Synced store-type catalog ID from sync_catalogs."), "store_ids": z.array(z.string()).min(1).describe("Filter to specific stores within the catalog. Omit to target all stores.").optional(), "catchment_ids": z.array(z.string()).min(1).describe("Catchment zone IDs to target (e.g., 'walk', 'drive'). Omit to target all catchment zones.").optional() }).catchall(z.any())).min(1).describe("Target users within store catchment areas from a synced store catalog. Each entry references a store-type catalog and optionally narrows to specific stores or catchment zones.").optional(), "geo_proximity": z.array(z.object({ "lat": z.number().gte(-90).lte(90).describe("Latitude in decimal degrees (WGS 84). Required for travel_time and radius methods.").optional(), "lng": z.number().gte(-180).lte(180).describe("Longitude in decimal degrees (WGS 84). Required for travel_time and radius methods.").optional(), "label": z.string().describe("Human-readable label for this entry (e.g., 'Düsseldorf', 'Heathrow Airport', 'Primary trade area').").optional(), "travel_time": z.object({ "value": z.number().gte(1).describe("Travel time limit."), "unit": z.enum(["min","hr"]).describe("Time unit for isochrone (travel-time catchment) calculations.") }).passthrough().describe("Travel time limit for isochrone calculation. The platform resolves this to a geographic boundary based on actual transportation networks.").optional(), "transport_mode": z.enum(["walking","cycling","driving","public_transport"]).describe("Transportation mode for isochrone calculation. Required when travel_time is provided.").optional(), "radius": z.object({ "value": z.number().gt(0).describe("Radius distance."), "unit": z.enum(["km","mi","m"]).describe("Distance unit.") }).passthrough().describe("Simple radius from the point. The platform draws a circle of this distance around the coordinates.").optional(), "geometry": z.object({ "type": z.enum(["Polygon","MultiPolygon"]).describe("GeoJSON geometry type."), "coordinates": z.array(z.any()).describe("GeoJSON coordinates array. For Polygon: array of linear rings. For MultiPolygon: array of polygons.") }).passthrough().describe("Pre-computed GeoJSON geometry defining the proximity boundary. Use when the buyer has already calculated isochrones (via TravelTime, Mapbox, etc.) or has custom boundaries. When geometry is provided, lat/lng are not required.").optional(), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).catchall(z.any()).and(z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "lat": z.any().refine((value) => value !== undefined, "Required"), "lng": z.any().refine((value) => value !== undefined, "Required"), "travel_time": z.any().refine((value) => value !== undefined, "Required"), "transport_mode": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "lat": z.any().refine((value) => value !== undefined, "Required"), "lng": z.any().refine((value) => value !== undefined, "Required"), "radius": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "geometry": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]; + }).describe("Canonical 3.2 optimization objective. Monetary execution policy belongs in BiddingPolicy; legacy monetary targets and unbound attention metrics are excluded.")).min(1).optional(), "audience_evidence_requirements": z.object({ "requirement_mode": z.enum(["required","preferred"]), "evidence_presence": z.enum(["required","when_available"]), "accepted_methodologies": z.array(z.enum(["observed","declared","derived","inferred","modeled","projected"]).describe("How a population-level audience-evidence estimate was produced. This vocabulary is intentionally separate from signal-definition methodology: `projected` describes expansion of a sample or panel to a reference population and does not become a user-level signal-membership method.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").optional(), "excluded_methodologies": z.array(z.enum(["observed","declared","derived","inferred","modeled","projected"]).describe("How a population-level audience-evidence estimate was produced. This vocabulary is intentionally separate from signal-definition methodology: `projected` describes expansion of a sample or panel to a reference population and does not become a user-level signal-membership method.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").optional(), "accepted_evidence_types": z.array(z.enum(["measured","forecast","seller_declared"])).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").optional(), "accepted_providers": z.array(z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery.")).min(1).optional(), "excluded_providers": z.array(z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery.")).min(1).optional(), "accepted_subject_types": z.array(z.enum(["individual","household","business","contextual","none"]).describe("The kind of subject characterized by audience data or population-level evidence.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").optional(), "accepted_resolution_methods": z.array(z.enum(["deterministic_id","probabilistic_device","browser","geographic","content_signal","mixed"]).describe("How subjects were resolved when producing a signal or population-level evidence estimate.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").optional(), "minimum_confidence": z.number().gte(0).lte(1).optional(), "maximum_age": z.intersection(z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight."), z.object({ "unit": z.enum(["seconds","minutes","hours","days"]).optional() })).optional(), "methodology_documentation_required": z.boolean().default(false), "independent_attestation_required": z.boolean().default(false), "accepted_attestation_issuers": z.array(z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "type": z.literal("brand"), "brand": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery."), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough(), z.object({ "type": z.literal("agent"), "agent_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").regex(new RegExp("^https://[^/?#@]+(?:/[^?#]*)?(?:\\?[^#]*)?$")), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough(), z.object({ "type": z.literal("origin"), "origin": z.string().refine(adcpJsonSchemaUri, "Invalid URI").regex(new RegExp("^https://[^/?#@]+$")), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough()]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17627,8 +15586,8 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - }))).min(1).describe("Target users within travel time, distance, or a custom boundary around arbitrary geographic points. Multiple entries use OR semantics — a user within range of any listed point is eligible. For campaigns targeting 10+ locations, consider using store_catchments with a location catalog instead. Seller must declare support in get_adcp_capabilities.").optional(), "language": z.array(z.string().regex(new RegExp("^(?:[a-z]{2,8}(?:-[A-Z][a-z]{3})?(?:-(?:[A-Z]{2}|[0-9]{3}))?(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*(?:-x(?:-[a-z0-9]{1,8})+)?|x(?:-[a-z0-9]{1,8})+)$")).min(2).max(63).describe("A well-formed BCP 47 language tag used by AdCP only as language identity. Script and region may refine that identity; other valid BCP 47 subtags remain part of tag matching but do not make this a general locale-settings object. It does not determine currency, time zone, number/date formatting, market, or legal jurisdiction. The AdCP canonical wire profile requires lower-case language and variants, title-case script, and upper-case region (for example `en-US`, `zh-Hant-TW`, or `x-private`). RFC 5646 comparisons are case-insensitive and its case regularization is optional; AdCP intentionally requires this stricter single wire spelling and receivers MUST reject differently cased tags rather than silently normalizing them. The schema pattern enforces the AdCP casing profile and extension structure for commonly used tags; conforming receivers additionally validate the complete RFC 5646 grammar and registry rules. Every new AdCP field carrying BCP 47 language identity or a concrete language range MUST reference this schema instead of declaring independent string constraints.")).min(1).describe("Restrict to users with specific language preferences using canonical BCP 47 language ranges. Each buyer range is evaluated against a user's language-preference tag with RFC 4647 section 3.3.1 Basic Filtering: 'fr' matches 'fr', 'fr-CA', and 'fr-FR', while 'fr-CA' matches 'fr-CA' and more-specific descendants but not 'fr' or 'fr-FR'. Values use OR logic.").optional(), "keyword_targets": z.array(z.object({ "keyword": z.string().min(1).describe("The keyword to target"), "match_type": z.enum(["broad","phrase","exact"]).describe("Keyword targeting match type. broad: ads may serve on queries semantically related to the keyword. phrase: ads serve when the query contains the keyword phrase. exact: ads serve only when the query matches the keyword exactly."), "bid_price": z.number().gte(0).describe("Per-keyword bid price, denominated in the same currency as the package's pricing option. Overrides the package-level bid_price for this keyword. Inherits the max_bid interpretation from the pricing option: when max_bid is true, this is the keyword's bid ceiling; when false, this is the exact bid. If omitted, the package bid_price applies.").optional() }).passthrough()).min(1).describe("Keyword targeting for search and retail media platforms. Restricts delivery to queries matching the specified keywords. Each keyword is identified by the tuple (keyword, match_type) — the same keyword string with different match types are distinct targets. Sellers SHOULD reject duplicate (keyword, match_type) pairs within a single request. Seller must declare support in get_adcp_capabilities.").optional(), "negative_keywords": z.array(z.object({ "keyword": z.string().min(1).describe("The keyword to exclude"), "match_type": z.enum(["broad","phrase","exact"]).describe("Keyword targeting match type. broad: ads may serve on queries semantically related to the keyword. phrase: ads serve when the query contains the keyword phrase. exact: ads serve only when the query matches the keyword exactly.") }).passthrough()).min(1).describe("Keywords to exclude from delivery. Queries matching these keywords will not trigger the ad. Each negative keyword is identified by the tuple (keyword, match_type). Seller must declare support in get_adcp_capabilities.").optional() }).catchall(z.any()).and(z.intersection(z.union([z.any().refine((value) => !z.object({ "demographics": z.any().refine((value) => value !== undefined, "Required"), "age_restriction": z.any().refine((value) => value !== undefined, "Required") }).passthrough().safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "demographics": z.any().refine((value) => value !== undefined, "Required"), "age_restriction": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "demographics": z.object({ "age": z.object({ "include_unknown": z.literal(false).optional() }).optional() }).optional() }))]).describe("Unknown-age delivery cannot satisfy a minimum-age eligibility policy. When demographic audience targeting and age_restriction are both present, include_unknown must be false."), z.union([z.any().refine((value) => !z.object({ "age_restriction": z.object({ "verification_required": z.literal(true) }), "demographics": z.object({ "age": z.object({ "accepted_bases": z.any().refine((value) => value !== undefined, "Required") }).passthrough() }) }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "age_restriction": z.object({ "verification_required": z.literal(true) }), "demographics": z.object({ "age": z.object({ "accepted_bases": z.any().refine((value) => value !== undefined, "Required") }).passthrough() }) }), z.object({ "demographics": z.object({ "age": z.object({ "accepted_bases": z.any().refine((value) => !z.array(z.any().refine((value) => !z.literal("verified").safeParse(value).success, "Invalid input: Should NOT be valid against schema")).safeParse(value).success, "Invalid input: Should NOT be valid against schema").optional() }).optional() }).optional() }))]).describe("A legal verification requirement always narrows demographic targeting. When the buyer supplies accepted_bases and age_restriction requires verification, verified must be accepted; otherwise the constraints have an empty intersection and the request is invalid."))).describe("Buyer-selected targeting, including compatible wholesale signal selections, applied within the product's published targeting contract.").optional(), "optimization_goals": z.array(z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "kind": z.literal("metric"), "metric": z.enum(["clicks","views","completed_views","viewed_seconds","engagements","follows","saves","profile_visits","reach"]), "reach_unit": z.enum(["individuals","households","devices","accounts","cookies","custom"]).describe("Unit of measurement for reach and audience size metrics. Different channels and measurement providers count reach in fundamentally different units, making cross-channel comparison impossible without declaring the unit.").optional(), "target_frequency": z.object({ "min": z.number().int().gte(1).optional(), "max": z.number().int().gte(1).optional(), "window": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.") }).passthrough().and(z.union([z.object({ "min": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).optional(), "view_duration_seconds": z.number().gt(0).optional(), "target": z.object({ "kind": z.literal("threshold_rate"), "value": z.number().gt(0) }).passthrough().optional(), "priority": z.number().int().gte(1).optional() }).passthrough(), z.object({ "kind": z.literal("event"), "event_sources": z.array(z.object({ "event_source_id": z.string().min(1), "event_type": z.enum(["page_view","view_content","select_content","select_item","search","share","add_to_cart","remove_from_cart","viewed_cart","add_to_wishlist","initiate_checkout","add_payment_info","purchase","refund","lead","qualify_lead","close_convert_lead","disqualify_lead","complete_registration","subscribe","follow","content_view","watch_milestone","start_trial","app_install","app_launch","contact","schedule","donate","submit_application","custom"]).describe("Standard marketing event types for event logging, aligned with IAB ECAPI"), "custom_event_name": z.string().min(1).optional(), "value_field": z.string().min(1).optional(), "value_factor": z.number().default(1) }).passthrough()).min(1), "target": z.object({ "kind": z.literal("maximize_value") }).passthrough().optional(), "attribution_window": z.object({ "post_click": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").describe("Post-click attribution window. Conversions occurring within this duration after a click are attributed to the ad.").optional(), "post_view": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").describe("Post-view attribution window. Conversions occurring within this duration after an ad impression (without click) are attributed to the ad.").optional(), "model": z.enum(["last_touch","first_touch","linear","time_decay","data_driven"]).describe("Attribution model used to assign credit when multiple touchpoints exist. SHOULD be populated when committing to a specific model; when absent, the seller's default applies.").optional() }).catchall(z.any()).describe("Describes the attribution methodology and lookback windows used for conversion measurement. Enables cross-platform comparison by making attribution methodology transparent. Used as a `$ref` from `optimization-goal.json` (buyer's optimization-time attribution choice), `get-media-buy-delivery-response.json` (seller-declared attribution methodology in delivery reports), and similar surfaces. All fields are optional individually but at least one of `post_click`, `post_view`, or `model` SHOULD be populated; absence of `model` means the seller's default attribution model applies (typically `last_touch` per industry convention) — sellers SHOULD populate `model` explicitly when committing to a specific methodology.").optional(), "priority": z.number().int().gte(1).optional() }).passthrough(), z.object({ "kind": z.literal("vendor_metric"), "vendor": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery."), "metric_id": z.string().regex(new RegExp("^[a-z][a-z0-9_]*$")).min(1).max(64).describe("Identifier for a vendor-defined metric within the vendor's vocabulary. Stable lookup key; the vendor publishes the canonical list (with category, methodology, and standard alignment) in `brand.json` `agents[type='measurement']`. Lowercase with underscores so a future enum promotion into `available-metric.json` is a literal string lift. Identifier is namespaced by the vendor — the same `metric_id` may mean different things in different vendors' vocabularies."), "target": z.object({ "kind": z.literal("threshold_rate"), "value": z.number().gt(0) }).passthrough().optional(), "priority": z.number().int().gte(1).optional() }).passthrough()]; + })).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").optional(), "accepted_attestation_claim_types": z.array(z.string().refine(adcpJsonSchemaUri, "Invalid URI")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").optional(), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough().and(z.union([z.any().refine((value) => !z.object({ "independent_attestation_required": z.literal(true) }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "independent_attestation_required": z.literal(true) }), z.object({ "accepted_attestation_issuers": z.any().refine((value) => value !== undefined, "Required") }).passthrough())])).describe("Buyer evidence-admissibility policy carried into the accepted purchase snapshot.").optional(), "audience_evidence_pins": z.array(z.object({ "evidence_id": z.string().min(1), "snapshot_id": z.string().min(1), "version": z.string().min(1), "content_digest": z.string().regex(new RegExp("^sha256:[a-f0-9]{64}$")), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough().describe("Buyer-authored pin to one exact immutable audience-evidence snapshot selected during discovery. Sellers MUST match all four fields against a single published snapshot; they MUST reject the package rather than substitute a newer version or reuse snapshot_id with changed content. A confirmed package MUST return the same identity in audience_evidence_selections with decision_use package_construction.")).min(1).describe("Exact immutable audience-evidence snapshots selected for package construction.").optional(), "agency_estimate_number": z.string().max(100).describe("Package-level agency estimate or authorization reference.").optional(), "context": z.record(z.string(), z.any()).describe("Opaque buyer package correlation preserved in the accepted snapshot and readback.").optional(), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional(), "measurement_terms": z.object({ "billing_measurement": z.object({ "vendor": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery."), "max_variance_percent": z.number().gte(0).lt(100).optional(), "measurement_window": z.string().min(1).optional(), "finalization_deadline_hours": z.number().int().gte(0).optional() }).passthrough().optional(), "makegood_policy": z.object({ "available_remedies": z.array(z.enum(["additional_delivery","credit","invoice_adjustment"]).describe("Remedy types available when a performance standard or billing measurement threshold is breached.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!") }).passthrough().optional() }).passthrough().describe("Published or negotiated billing-measurement and makegood terms for this purchase. Direct buyers may omit this to inherit the product default; accepted proposal snapshots preserve the resolved terms.").optional(), "performance_standards": z.array(z.object({ "metric": z.enum(["viewability","ivt","completion_rate","brand_safety","attention_score"]).describe("Performance metrics that support rate thresholds on media buys — the verification subset of the broader metric vocabulary. Each metric specifies whether its threshold is a floor (must exceed) or ceiling (must not exceed). Shared values with `available-metric.json` mirror the delivery vocabulary (`viewability` → `viewable_rate` family, `completion_rate` → same name); verification-only values (`ivt`, `brand_safety`, `attention_score`) are typically vendor-attested and do not appear in `available-metric.json` because they're not seller-reportable scalars — they flow through `vendor_metric_values` or vendor-scope `committed_metrics` entries with the matching `performance_standard.vendor` BrandRef anchoring identity."), "threshold": z.number().gte(0).lte(1), "standard": z.enum(["mrc","groupm"]).describe("Viewability measurement standard applied to determine whether an impression qualifies as viewable. These are materially different thresholds and should not be compared across standards.").optional(), "vendor": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery.") }).passthrough().describe("Compact committed metric threshold with resolvable vendor identity and no creative or brand-asset graph.")).min(1).describe("Published or negotiated metric thresholds and measurement vendors. Direct buyers may omit this to inherit the product defaults; accepted proposal snapshots preserve every applicable standard.").optional() }).passthrough().describe("One resolved canonical product selection in a compact proposal or accepted commercial snapshot. Request-side buy_products selections use product-purchase-input.json. This strict snapshot shape contains effective non-null targeting and resolved inherited terms. Creative content and creative assignments are intentionally absent."), z.object({ "product_id": z.any().refine((value) => value !== undefined, "Required"), "pricing_option_id": z.any().refine((value) => value !== undefined, "Required"), "pricing": z.any().refine((value) => value !== undefined, "Required"), "start_time": z.any().refine((value) => value !== undefined, "Required"), "end_time": z.any().refine((value) => value !== undefined, "Required") }).passthrough())).min(1).describe("Exact canonical product, pricing, format, catalog, budget, targeting, bidding, optimization, resolved flight, measurement, and performance terms in the commercial envelope."), "start_time": z.any().superRefine((x, ctx) => { + const schemas = [z.literal("asap").describe("Start campaign as soon as possible"), z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time")]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17659,8 +15618,9 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - }).describe("Canonical 3.2 optimization objective. Monetary execution policy belongs in BiddingPolicy; legacy monetary targets and unbound attention metrics are excluded.")).min(1).optional(), "audience_evidence_requirements": z.object({ "requirement_mode": z.enum(["required","preferred"]), "evidence_presence": z.enum(["required","when_available"]), "accepted_methodologies": z.array(z.enum(["observed","declared","derived","inferred","modeled","projected"]).describe("How a population-level audience-evidence estimate was produced. This vocabulary is intentionally separate from signal-definition methodology: `projected` describes expansion of a sample or panel to a reference population and does not become a user-level signal-membership method.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").optional(), "excluded_methodologies": z.array(z.enum(["observed","declared","derived","inferred","modeled","projected"]).describe("How a population-level audience-evidence estimate was produced. This vocabulary is intentionally separate from signal-definition methodology: `projected` describes expansion of a sample or panel to a reference population and does not become a user-level signal-membership method.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").optional(), "accepted_evidence_types": z.array(z.enum(["measured","forecast","seller_declared"])).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").optional(), "accepted_providers": z.array(z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery.")).min(1).optional(), "excluded_providers": z.array(z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery.")).min(1).optional(), "accepted_subject_types": z.array(z.enum(["individual","household","business","contextual","none"]).describe("The kind of subject characterized by audience data or population-level evidence.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").optional(), "accepted_resolution_methods": z.array(z.enum(["deterministic_id","probabilistic_device","browser","geographic","content_signal","mixed"]).describe("How subjects were resolved when producing a signal or population-level evidence estimate.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").optional(), "minimum_confidence": z.number().gte(0).lte(1).optional(), "maximum_age": z.intersection(z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight."), z.object({ "unit": z.enum(["seconds","minutes","hours","days"]).optional() })).optional(), "methodology_documentation_required": z.boolean().default(false), "independent_attestation_required": z.boolean().default(false), "accepted_attestation_issuers": z.array(z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "type": z.literal("brand"), "brand": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery."), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough(), z.object({ "type": z.literal("agent"), "agent_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").regex(new RegExp("^https://[^/?#@]+(?:/[^?#]*)?(?:\\?[^#]*)?$")), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough(), z.object({ "type": z.literal("origin"), "origin": z.string().refine(adcpJsonSchemaUri, "Invalid URI").regex(new RegExp("^https://[^/?#@]+$")), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough()]; + }).describe("Campaign start timing: 'asap' or ISO 8601 date-time"), "end_time": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time"), "total_budget": z.object({ "amount": z.number().gte(0), "currency": z.string().regex(new RegExp("^[A-Z]{3}$")) }).passthrough().optional(), "daily_budget_cap": z.number().gte(0).describe("Hard aggregate daily spend ceiling accepted as part of these terms. It bounds total spend without creating purchase allocations.").optional(), "frequency_cap": z.intersection(z.object({ "suppress": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").describe("Cooldown period between consecutive exposures to the same entity. Prevents back-to-back ad delivery (e.g. {\"interval\": 60, \"unit\": \"minutes\"} for a 1-hour cooldown). Preferred over suppress_minutes.").optional(), "suppress_minutes": z.number().gte(0).describe("Deprecated — use suppress instead. Cooldown period in minutes between consecutive exposures to the same entity (e.g. 60 for a 1-hour cooldown).").optional(), "max_impressions": z.number().int().gte(1).describe("Maximum number of impressions per entity per window. For duration windows, implementations typically use a rolling window. campaign applies across the owning field's full flight: the package flight for a targeting overlay, or the MediaBuy flight for a root cap.").optional(), "per": z.enum(["individuals","households","devices","accounts","cookies","custom"]).describe("Unit of measurement for reach and audience size metrics. Different channels and measurement providers count reach in fundamentally different units, making cross-channel comparison impossible without declaring the unit.").describe("Entity granularity for impression counting. Required when max_impressions is set.").optional(), "window": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").describe("Time window for the max_impressions cap (e.g. {\"interval\": 7, \"unit\": \"days\"} or {\"interval\": 1, \"unit\": \"campaign\"} for the full flight). Required when max_impressions is set.").optional() }).catchall(z.any()).and(z.union([z.object({ "suppress": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "suppress_minutes": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max_impressions": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).and(z.intersection(z.union([z.any().refine((value) => !z.object({ "max_impressions": z.any().refine((value) => value !== undefined, "Required") }).passthrough().safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.object({ "max_impressions": z.any().refine((value) => value !== undefined, "Required"), "per": z.any().refine((value) => value !== undefined, "Required"), "window": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]), z.intersection(z.union([z.any().refine((value) => !z.object({ "per": z.any().refine((value) => value !== undefined, "Required") }).passthrough().safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.object({ "per": z.any().refine((value) => value !== undefined, "Required"), "max_impressions": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]), z.union([z.any().refine((value) => !z.object({ "window": z.any().refine((value) => value !== undefined, "Required") }).passthrough().safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.object({ "window": z.any().refine((value) => value !== undefined, "Required"), "max_impressions": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])))).describe("Frequency capping settings for package-level application. Two types of frequency control can be used independently or together: suppress enforces a cooldown between consecutive exposures; max_impressions + per + window caps total exposures per entity in a time window. When both suppress and max_impressions are set, an impression is delivered only if both constraints permit it (AND semantics). At least one of suppress, suppress_minutes, or max_impressions must be set. Field location determines scope; this value has no scope discriminator. The MediaBuy root uses the narrower media-buy-frequency-cap schema, which permits maximum impressions only in 3.2."), z.object({ "max_impressions": z.any().refine((value) => value !== undefined, "Required") }).passthrough()).describe("Hard MediaBuy-level cap accepted as part of these terms. One counter aggregates exposures across every purchase; purchase targeting caps remain independently binding.").optional(), "budget_cap_timezone": z.string().min(1).describe("Shared IANA calendar-day boundary for aggregate and purchase daily caps in these terms.").optional(), "budget_allocation": z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "mode": z.literal("fixed") }).passthrough(), z.object({ "mode": z.literal("seller_optimized"), "optimization_goals": z.array(z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "kind": z.literal("metric"), "metric": z.enum(["clicks","views","completed_views","viewed_seconds","engagements","follows","saves","profile_visits","reach"]), "reach_unit": z.enum(["individuals","households","devices","accounts","cookies","custom"]).describe("Unit of measurement for reach and audience size metrics. Different channels and measurement providers count reach in fundamentally different units, making cross-channel comparison impossible without declaring the unit.").optional(), "target_frequency": z.object({ "min": z.number().int().gte(1).optional(), "max": z.number().int().gte(1).optional(), "window": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.") }).passthrough().and(z.union([z.object({ "min": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).optional(), "view_duration_seconds": z.number().gt(0).optional(), "target": z.object({ "kind": z.literal("threshold_rate"), "value": z.number().gt(0) }).passthrough().optional(), "priority": z.number().int().gte(1).optional() }).passthrough(), z.object({ "kind": z.literal("event"), "event_sources": z.array(z.object({ "event_source_id": z.string().min(1), "event_type": z.enum(["page_view","view_content","select_content","select_item","search","share","add_to_cart","remove_from_cart","viewed_cart","add_to_wishlist","initiate_checkout","add_payment_info","purchase","refund","lead","qualify_lead","close_convert_lead","disqualify_lead","complete_registration","subscribe","follow","content_view","watch_milestone","start_trial","app_install","app_launch","contact","schedule","donate","submit_application","custom"]).describe("Standard marketing event types for event logging, aligned with IAB ECAPI"), "custom_event_name": z.string().min(1).optional(), "value_field": z.string().min(1).optional(), "value_factor": z.number().default(1) }).passthrough()).min(1), "target": z.object({ "kind": z.literal("maximize_value") }).passthrough().optional(), "attribution_window": z.object({ "post_click": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").describe("Post-click attribution window. Conversions occurring within this duration after a click are attributed to the ad.").optional(), "post_view": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").describe("Post-view attribution window. Conversions occurring within this duration after an ad impression (without click) are attributed to the ad.").optional(), "model": z.enum(["last_touch","first_touch","linear","time_decay","data_driven"]).describe("Attribution model used to assign credit when multiple touchpoints exist. SHOULD be populated when committing to a specific model; when absent, the seller's default applies.").optional() }).catchall(z.any()).describe("Describes the attribution methodology and lookback windows used for conversion measurement. Enables cross-platform comparison by making attribution methodology transparent. Used as a `$ref` from `optimization-goal.json` (buyer's optimization-time attribution choice), `get-media-buy-delivery-response.json` (seller-declared attribution methodology in delivery reports), and similar surfaces. All fields are optional individually but at least one of `post_click`, `post_view`, or `model` SHOULD be populated; absence of `model` means the seller's default attribution model applies (typically `last_touch` per industry convention) — sellers SHOULD populate `model` explicitly when committing to a specific methodology.").optional(), "priority": z.number().int().gte(1).optional() }).passthrough(), z.object({ "kind": z.literal("vendor_metric"), "vendor": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery."), "metric_id": z.string().regex(new RegExp("^[a-z][a-z0-9_]*$")).min(1).max(64).describe("Identifier for a vendor-defined metric within the vendor's vocabulary. Stable lookup key; the vendor publishes the canonical list (with category, methodology, and standard alignment) in `brand.json` `agents[type='measurement']`. Lowercase with underscores so a future enum promotion into `available-metric.json` is a literal string lift. Identifier is namespaced by the vendor — the same `metric_id` may mean different things in different vendors' vocabularies."), "target": z.object({ "kind": z.literal("threshold_rate"), "value": z.number().gt(0) }).passthrough().optional(), "priority": z.number().int().gte(1).optional() }).passthrough()]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17691,8 +15651,7 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - })).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").optional(), "accepted_attestation_claim_types": z.array(z.string().refine(adcpJsonSchemaUri, "Invalid URI")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").optional(), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough().and(z.union([z.any().refine((value) => !z.object({ "independent_attestation_required": z.literal(true) }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "independent_attestation_required": z.literal(true) }), z.object({ "accepted_attestation_issuers": z.any().refine((value) => value !== undefined, "Required") }).passthrough())])).describe("Buyer evidence-admissibility policy carried into the accepted purchase snapshot.").optional(), "audience_evidence_pins": z.array(z.object({ "evidence_id": z.string().min(1), "snapshot_id": z.string().min(1), "version": z.string().min(1), "content_digest": z.string().regex(new RegExp("^sha256:[a-f0-9]{64}$")), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough().describe("Buyer-authored pin to one exact immutable audience-evidence snapshot selected during discovery. Sellers MUST match all four fields against a single published snapshot; they MUST reject the package rather than substitute a newer version or reuse snapshot_id with changed content. A confirmed package MUST return the same identity in audience_evidence_selections with decision_use package_construction.")).min(1).describe("Exact immutable audience-evidence snapshots selected for package construction.").optional(), "agency_estimate_number": z.string().max(100).describe("Package-level agency estimate or authorization reference.").optional(), "context": z.record(z.string(), z.any()).describe("Opaque buyer package correlation preserved in the accepted snapshot and readback.").optional(), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional(), "measurement_terms": z.object({ "billing_measurement": z.object({ "vendor": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery."), "max_variance_percent": z.number().gte(0).lt(100).optional(), "measurement_window": z.string().min(1).optional(), "finalization_deadline_hours": z.number().int().gte(0).optional() }).passthrough().optional(), "makegood_policy": z.object({ "available_remedies": z.array(z.enum(["additional_delivery","credit","invoice_adjustment"]).describe("Remedy types available when a performance standard or billing measurement threshold is breached.")).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!") }).passthrough().optional() }).passthrough().describe("Published or negotiated billing-measurement and makegood terms for this purchase. Direct buyers may omit this to inherit the product default; accepted proposal snapshots preserve the resolved terms.").optional(), "performance_standards": z.array(z.object({ "metric": z.enum(["viewability","ivt","completion_rate","brand_safety","attention_score"]).describe("Performance metrics that support rate thresholds on media buys — the verification subset of the broader metric vocabulary. Each metric specifies whether its threshold is a floor (must exceed) or ceiling (must not exceed). Shared values with `available-metric.json` mirror the delivery vocabulary (`viewability` → `viewable_rate` family, `completion_rate` → same name); verification-only values (`ivt`, `brand_safety`, `attention_score`) are typically vendor-attested and do not appear in `available-metric.json` because they're not seller-reportable scalars — they flow through `vendor_metric_values` or vendor-scope `committed_metrics` entries with the matching `performance_standard.vendor` BrandRef anchoring identity."), "threshold": z.number().gte(0).lte(1), "standard": z.enum(["mrc","groupm"]).describe("Viewability measurement standard applied to determine whether an impression qualifies as viewable. These are materially different thresholds and should not be compared across standards.").optional(), "vendor": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery.") }).passthrough().describe("Compact committed metric threshold with resolvable vendor identity and no creative or brand-asset graph.")).min(1).describe("Published or negotiated metric thresholds and measurement vendors. Direct buyers may omit this to inherit the product defaults; accepted proposal snapshots preserve every applicable standard.").optional() }).passthrough().describe("One canonical product selection shared by buy_products inputs and compact proposal snapshots. Direct purchases accept published terms as-is; sellers resolve omitted inherited flight, measurement, and performance terms into the accepted commercial snapshot. Changes to those terms belong in the proposal lifecycle. Creative content and creative assignments are intentionally absent."), z.object({ "product_id": z.any().refine((value) => value !== undefined, "Required"), "pricing_option_id": z.any().refine((value) => value !== undefined, "Required"), "pricing": z.any().refine((value) => value !== undefined, "Required"), "start_time": z.any().refine((value) => value !== undefined, "Required"), "end_time": z.any().refine((value) => value !== undefined, "Required") }).passthrough())).min(1).describe("Exact canonical product, pricing, format, catalog, budget, targeting, bidding, optimization, resolved flight, measurement, and performance terms in the commercial envelope."), "start_time": z.any().superRefine((x, ctx) => { - const schemas = [z.literal("asap").describe("Start campaign as soon as possible"), z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time")]; + }).describe("Canonical 3.2 optimization objective. Monetary execution policy belongs in BiddingPolicy; legacy monetary targets and unbound attention metrics are excluded.")).min(1) }).passthrough()]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17723,9 +15682,8 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - }).describe("Campaign start timing: 'asap' or ISO 8601 date-time"), "end_time": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time"), "total_budget": z.object({ "amount": z.number().gte(0), "currency": z.string().regex(new RegExp("^[A-Z]{3}$")) }).passthrough().optional(), "daily_budget_cap": z.number().gte(0).describe("Hard aggregate daily spend ceiling accepted as part of these terms. It bounds total spend without creating purchase allocations.").optional(), "budget_cap_timezone": z.string().min(1).describe("Shared IANA calendar-day boundary for aggregate and purchase daily caps in these terms.").optional(), "budget_allocation": z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "mode": z.literal("fixed") }).passthrough(), z.object({ "mode": z.literal("seller_optimized"), "optimization_goals": z.array(z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "kind": z.literal("metric"), "metric": z.enum(["clicks","views","completed_views","viewed_seconds","engagements","follows","saves","profile_visits","reach"]), "reach_unit": z.enum(["individuals","households","devices","accounts","cookies","custom"]).describe("Unit of measurement for reach and audience size metrics. Different channels and measurement providers count reach in fundamentally different units, making cross-channel comparison impossible without declaring the unit.").optional(), "target_frequency": z.object({ "min": z.number().int().gte(1).optional(), "max": z.number().int().gte(1).optional(), "window": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.") }).passthrough().and(z.union([z.object({ "min": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).optional(), "view_duration_seconds": z.number().gt(0).optional(), "target": z.object({ "kind": z.literal("threshold_rate"), "value": z.number().gt(0) }).passthrough().optional(), "priority": z.number().int().gte(1).optional() }).passthrough(), z.object({ "kind": z.literal("event"), "event_sources": z.array(z.object({ "event_source_id": z.string().min(1), "event_type": z.enum(["page_view","view_content","select_content","select_item","search","share","add_to_cart","remove_from_cart","viewed_cart","add_to_wishlist","initiate_checkout","add_payment_info","purchase","refund","lead","qualify_lead","close_convert_lead","disqualify_lead","complete_registration","subscribe","follow","content_view","watch_milestone","start_trial","app_install","app_launch","contact","schedule","donate","submit_application","custom"]).describe("Standard marketing event types for event logging, aligned with IAB ECAPI"), "custom_event_name": z.string().min(1).optional(), "value_field": z.string().min(1).optional(), "value_factor": z.number().default(1) }).passthrough()).min(1), "target": z.object({ "kind": z.literal("maximize_value") }).passthrough().optional(), "attribution_window": z.object({ "post_click": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").describe("Post-click attribution window. Conversions occurring within this duration after a click are attributed to the ad.").optional(), "post_view": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").describe("Post-view attribution window. Conversions occurring within this duration after an ad impression (without click) are attributed to the ad.").optional(), "model": z.enum(["last_touch","first_touch","linear","time_decay","data_driven"]).describe("Attribution model used to assign credit when multiple touchpoints exist. SHOULD be populated when committing to a specific model; when absent, the seller's default applies.").optional() }).catchall(z.any()).describe("Describes the attribution methodology and lookback windows used for conversion measurement. Enables cross-platform comparison by making attribution methodology transparent. Used as a `$ref` from `optimization-goal.json` (buyer's optimization-time attribution choice), `get-media-buy-delivery-response.json` (seller-declared attribution methodology in delivery reports), and similar surfaces. All fields are optional individually but at least one of `post_click`, `post_view`, or `model` SHOULD be populated; absence of `model` means the seller's default attribution model applies (typically `last_touch` per industry convention) — sellers SHOULD populate `model` explicitly when committing to a specific methodology.").optional(), "priority": z.number().int().gte(1).optional() }).passthrough(), z.object({ "kind": z.literal("vendor_metric"), "vendor": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery."), "metric_id": z.string().regex(new RegExp("^[a-z][a-z0-9_]*$")).min(1).max(64).describe("Identifier for a vendor-defined metric within the vendor's vocabulary. Stable lookup key; the vendor publishes the canonical list (with category, methodology, and standard alignment) in `brand.json` `agents[type='measurement']`. Lowercase with underscores so a future enum promotion into `available-metric.json` is a literal string lift. Identifier is namespaced by the vendor — the same `metric_id` may mean different things in different vendors' vocabularies."), "target": z.object({ "kind": z.literal("threshold_rate"), "value": z.number().gt(0) }).passthrough().optional(), "priority": z.number().int().gte(1).optional() }).passthrough()]; + }).describe("Canonical fixed or seller-optimized allocation using only canonical optimization goals.").optional(), "pacing": z.enum(["even","asap","front_loaded"]).describe("Budget pacing strategy").optional(), "bidding": z.object({ "automatic": z.literal(true).describe("Explicitly use seller/provider automatic bidding at this authored scope. At package scope this is a complete override of a media-buy policy, not inheritance. It MUST be the only field in the block and MUST be preserved on readback.").optional(), "bid_amount": z.number().gt(0).describe("Manual auction bid denominated in the media-buy currency and expressed per the selected pricing option's auction unit. For example, a CPM option interprets the amount per thousand impressions. This is the amount submitted to the auction, not a promise that the clearing price equals it. Requires an auction-priced pricing option whose currency equals the media-buy currency.").optional(), "max_bid": z.number().gt(0).describe("Hard per-auction ceiling denominated in the media-buy currency and expressed per the selected pricing option's auction unit. This is the only canonical hard auction ceiling and MUST NOT be translated into an average outcome-cost control. Requires an auction-priced pricing option whose currency equals the media-buy currency. May stand alone or supplement cost_per/roas only when the relevant scope capability advertises that combination.").optional(), "cost_per": z.object({ "amount": z.number().gt(0).describe("Average cost amount per scope-bound primary-goal result, denominated in the media-buy currency."), "strength": z.enum(["cap","target"]).describe("`cap` optimizes for an average at or below the amount and accepts underdelivery when necessary; `target` optimizes around the amount while balancing volume and spend. Neither is a per-result or per-auction guarantee.") }).passthrough().describe("Average cost control per result of the scope-bound primary optimization goal. At seller-optimized media-buy scope it binds to budget_allocation.optimization_goals; at package scope it binds to that package's optimization_goals; at fixed media-buy scope it binds independently to each inheriting package and is valid only when their primary-goal result units are compatible. Metric goals are compatible only when metric and every result-defining qualifier match; vendor_metric goals only when vendor and metric_id match; event goals only when the event_type/custom_event_name set and resolved attribution_window match. Primary is the earliest array entry among goals tied for the lowest explicit numeric priority; unprioritized goals follow explicitly prioritized goals; when all priorities are absent, the first entry is primary.").optional(), "roas": z.object({ "value": z.number().gt(0).describe("Return per unit of ad spend; 4 means 4 units of value per 1 unit spent."), "strength": z.enum(["floor","target"]).describe("`floor` prefers underdelivery to knowingly optimizing below the requested return; `target` optimizes around the requested return. Neither guarantees realized return.") }).passthrough().describe("Dimensionless return-on-ad-spend control bound to the same scope-specific primary goal rules as cost_per. The bound goal must be value-bearing; a fixed media-buy default requires a value-bearing primary goal on every inheriting package. Every referenced value-bearing event source MUST declare value_currencies containing the media-buy currency. The seller validates this at buy creation; each buy consumes only exact-currency records, while other declared currencies remain available to other buys. Sellers MUST NOT perform currency conversion.").optional() }).passthrough().and(z.any().refine((value) => !z.union([z.object({ "automatic": z.any().refine((value) => value !== undefined, "Required"), "bid_amount": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "automatic": z.any().refine((value) => value !== undefined, "Required"), "max_bid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "automatic": z.any().refine((value) => value !== undefined, "Required"), "cost_per": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "automatic": z.any().refine((value) => value !== undefined, "Required"), "roas": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "bid_amount": z.any().refine((value) => value !== undefined, "Required"), "max_bid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "bid_amount": z.any().refine((value) => value !== undefined, "Required"), "cost_per": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "bid_amount": z.any().refine((value) => value !== undefined, "Required"), "roas": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "cost_per": z.any().refine((value) => value !== undefined, "Required"), "roas": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]).safeParse(value).success, "Invalid input: Should NOT be valid against schema")).describe("Buyer-authored execution policy for automatic delivery, auction bidding, average outcome cost, or return on ad spend. The containing object determines authored scope: media-buy `bidding` is a complete inherited default and package `bidding` is a complete package override. Sellers MUST preserve authored scope on readback and MUST NOT copy an inherited media-buy policy into package `bidding`. Every monetary field in this block is denominated in the media-buy currency; the selected pricing option supplies the auction unit, never another denomination. Auction-unit identity is the pricing_model plus every canonical billing-event qualifier after defaults are applied: for example CPV view threshold, CPP demographic system/demographic, CPA event tuple, time time_unit, and flat-rate/DOOH parameters. An extension qualifier participates only when its registered extension specification explicitly defines how it contributes to auction-unit identity. A media-buy bid_amount or max_bid is valid only when every inheriting package resolves the same auction-unit identity. Every affected pricing option MUST use the media-buy currency; split currency-mismatched packages into separate buys. Seller-optimized media-buy cost_per/roas bind to the primary budget_allocation.optimization_goals goal. Package-authored cost_per/roas bind to the package primary optimization goal. The primary goal is the earliest array entry among goals with the lowest explicit numeric priority; unprioritized goals follow explicitly prioritized goals; when all priorities are absent, the first entry is primary. In fixed allocation, an inherited media-buy cost_per is valid only when all inheriting packages have compatible primary-goal result units; inherited roas requires value-bearing primary goals on every inheriting package. Canonical ROAS requires each value-bearing event source to declare the media-buy currency in value_currencies; each buy consumes only exact-currency records and sellers MUST NOT convert them. Absence invokes inheritance or provider automatic delivery; `{automatic:true}` is an explicit authored policy that overrides inheritance. Sellers MUST reject unsupported modes, combinations, units, currency, goal bindings, or native placements before any provider mutation and MUST NOT silently translate semantics.").refine((value) => Object.keys(value).length >= 1, "Object must contain at least 1 property").optional(), "invoice_recipient": z.object({ "legal_name": z.string().max(200).describe("Registered legal name of the business entity"), "vat_id": z.string().regex(new RegExp("^[A-Z]{2}[A-Z0-9]{2,13}$")).describe("VAT identification number (e.g., DE123456789 for Germany, FR12345678901 for France). Required for B2B invoicing in the EU. Must be normalized: no spaces, dots, or dashes.").optional(), "tax_id": z.string().max(30).describe("Tax identification number for jurisdictions that do not use VAT (e.g., US EIN)").optional(), "registration_number": z.string().max(50).describe("Company registration number (e.g., HRB 12345 for German Handelsregister)").optional(), "address": z.object({ "street": z.string().max(200).describe("Street address including building number"), "city": z.string().max(100), "postal_code": z.string().max(20), "region": z.string().max(100).describe("State, province, or region").optional(), "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code") }).passthrough().describe("Postal address for invoicing and legal correspondence").optional(), "contacts": z.array(z.object({ "role": z.enum(["billing","legal","creative","general"]).describe("Contact's functional role in the business relationship"), "name": z.string().max(200).describe("Full name of the contact").optional(), "email": z.string().email().max(254).optional(), "phone": z.string().max(30).optional() }).passthrough()).max(10).describe("Contacts for billing, legal, and operational matters. Contains personal data subject to GDPR and equivalent regulations. Implementations MUST use this data only for invoicing and account management.").optional(), "bank": z.object({ "account_holder": z.string().max(200).describe("Name on the bank account"), "iban": z.string().regex(new RegExp("^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,30}$")).describe("International Bank Account Number (SEPA markets)").optional(), "bic": z.string().regex(new RegExp("^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$")).describe("Bank Identifier Code / SWIFT code (SEPA markets)").optional(), "routing_number": z.string().max(30).describe("Bank routing number for non-SEPA markets (e.g., US ABA routing number, Canadian transit/institution number)").optional(), "account_number": z.string().max(30).describe("Bank account number for non-SEPA markets").optional() }).passthrough().describe("Bank account details for payment processing. Write-only: included in requests to provide payment coordinates, but MUST NOT be echoed in responses. Sellers store these details and confirm receipt without returning them.").optional(), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough().describe("Structured business identity for B2B invoicing and contracts. Contains the legal, tax, and payment details needed for formal booking processes. Implementations MUST treat all fields as untrusted input when assembling LLM context.").optional(), "purchase_order_ref": z.string().min(1).max(255).optional(), "agency_estimate_number": z.string().max(100).optional(), "reporting_commitments": z.array(z.object({ "purchase_index": z.number().int().gte(0), "metrics": z.array(z.record(z.string(), z.any()).and(z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "scope": z.literal("standard"), "metric_id": z.enum(["impressions","spend","clicks","ctr","views","completed_views","completion_rate","conversions","conversion_value","commissionable_value","roas","cost_per_acquisition","new_to_brand_rate","leads","reach","frequency","grps","engagements","engagement_rate","follows","saves","profile_visits","viewability","viewable_rate","viewable_impressions","measurable_impressions","viewed_seconds","viewed_seconds_percentiles","viewed_seconds_histogram","quartile_data","quartile_25","quartile_50","quartile_75","quartile_100","time_based_views","dooh_metrics","ooh_metrics","cost_per_click","cost_per_completed_view","cpm","downloads","units_sold","new_to_brand_units","plays","incremental_sales_lift","brand_lift","foot_traffic","conversion_lift","brand_search_lift"]).describe("Standard delivery and performance metrics available for reporting. Most values name flat numeric fields of `core/delivery-metrics.json`. Leaf identities address a single numeric value nested inside an object-shaped metric so it can be declared, committed, aggregated, and sorted individually: `quartile_25`/`quartile_50`/`quartile_75`/`quartile_100` resolve to `quartile_data.q1_views`–`q4_views`, and `viewable_rate`/`viewable_impressions`/`measurable_impressions`/`viewed_seconds` resolve to the same-named fields of `viewability`. Structured nested identities `viewed_seconds_percentiles` and `viewed_seconds_histogram` make the corresponding optional distribution carriers discoverable, committable, and requestable, but not aggregatable or sortable. The nested object or array remains the canonical carrier — nested identities never introduce duplicate flat response fields. Container tokens such as `viewability`, `quartile_data`, `dooh_metrics`, and `time_based_views` declare their documented nested surface. **Container subsumption applies only to numeric leaves**: `viewability` subsumes `viewable_rate`, `viewable_impressions`, `measurable_impressions`, and `viewed_seconds`; `quartile_data` subsumes `quartile_25`, `quartile_50`, `quartile_75`, and `quartile_100`. This rule applies to capability declaration, `required_metrics` filtering, format `reported_metrics` intersection, and `requested_metrics` selection. Optional structured identities MUST be declared explicitly: `viewability` alone does not satisfy `viewed_seconds_percentiles` or `viewed_seconds_histogram`. Requesting any nested identity selects its canonical carrier in the response. A nested identity declaration does not imply sibling values or the carrier's non-metric fields."), "qualifier": z.object({ "viewability_standard": z.enum(["mrc","groupm"]).describe("Viewability measurement standard applied to determine whether an impression qualifies as viewable. These are materially different thresholds and should not be compared across standards.").optional(), "completion_source": z.enum(["seller_attested","vendor_attested"]).describe("Trust-source disambiguator for `completion_rate` — *who* attested to the completion event, not *how* (methodology granularity is a separate dimension; future qualifier keys may add it if buyer demand surfaces). The two paths can yield materially different rates, particularly in SSAI environments where the player's view of completion may differ from a vendor's. Used as a `qualifier.completion_source` key on `committed_metrics`, `missing_metrics`, and package-level delivery values (`metric_values` or `vendor_metric_values`) to disambiguate which trust source the row represents. Edge cases: walled gardens where the seller is also the measurement vendor (YouTube, Spotify) collapse to `seller_attested` by trust-model logic — the same party served and counted. IAB-certified first-party podcast measurement (Podtrac, Triton on their own platforms; Art19 on its own platform) likewise collapses to `seller_attested`. The same vendor's offering on a third-party platform (Podtrac on a publisher who isn't Podtrac) is `vendor_attested`. The trust axis is *not* who runs the SDK — it's who is independent of the seller's revenue interest.").optional(), "attribution_methodology": z.enum(["deterministic_purchase","probabilistic","panel_based","modeled"]).describe("How attribution between ad exposure and outcome events was computed. Used as a `qualifier.attribution_methodology` key on `committed_metrics`, `missing_metrics`, package-level delivery values (`metric_values` or `vendor_metric_values`), and `performance-feedback.metric` to disambiguate the same outcome metric reported under different methodologies — `conversion_value` measured deterministically (matched purchase IDs) is not the same number as `conversion_value` measured probabilistically (modeled match) and should never be summed across methodologies. The retail-media closed-loop pattern typically reports under `deterministic_purchase`; MMM and clean-room outputs typically report under `modeled` or `probabilistic`; panel-based measurement (Nielsen, comScore, Edison) reports under `panel_based`.").optional(), "attribution_window": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").optional(), "lift_dimension": z.enum(["awareness","consideration","favorability","purchase_intent","ad_recall"]).describe("Brand-lift dimension disambiguator. Brand lift is multidimensional in production — Kantar, Upwave, Cint, DoubleVerify, and similar vendors report awareness, consideration, favorability, purchase intent, and ad recall as separate measurements with their own sample sizes and confidence intervals. Used as a `qualifier.lift_dimension` key on `committed_metrics`, `missing_metrics`, package-level delivery values (`metric_values` or `vendor_metric_values`), and `performance-feedback.metric` to disambiguate which dimension of `brand_lift` a row represents. Two `brand_lift` rows under different lift dimensions represent different surveyed outcomes and must not be combined into a single number.").optional() }).passthrough().describe("Compact qualifier set that distinguishes incompatible reporting definitions for the same metric ID.").optional(), "effective_at": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() }).passthrough(), z.object({ "scope": z.literal("vendor"), "vendor": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery."), "metric_id": z.string().regex(new RegExp("^[a-z][a-z0-9_]*$")).min(1).max(64).describe("Identifier for a vendor-defined metric within the vendor's vocabulary. Stable lookup key; the vendor publishes the canonical list (with category, methodology, and standard alignment) in `brand.json` `agents[type='measurement']`. Lowercase with underscores so a future enum promotion into `available-metric.json` is a literal string lift. Identifier is namespaced by the vendor — the same `metric_id` may mean different things in different vendors' vocabularies."), "qualifier": z.object({ "viewability_standard": z.enum(["mrc","groupm"]).describe("Viewability measurement standard applied to determine whether an impression qualifies as viewable. These are materially different thresholds and should not be compared across standards.").optional(), "completion_source": z.enum(["seller_attested","vendor_attested"]).describe("Trust-source disambiguator for `completion_rate` — *who* attested to the completion event, not *how* (methodology granularity is a separate dimension; future qualifier keys may add it if buyer demand surfaces). The two paths can yield materially different rates, particularly in SSAI environments where the player's view of completion may differ from a vendor's. Used as a `qualifier.completion_source` key on `committed_metrics`, `missing_metrics`, and package-level delivery values (`metric_values` or `vendor_metric_values`) to disambiguate which trust source the row represents. Edge cases: walled gardens where the seller is also the measurement vendor (YouTube, Spotify) collapse to `seller_attested` by trust-model logic — the same party served and counted. IAB-certified first-party podcast measurement (Podtrac, Triton on their own platforms; Art19 on its own platform) likewise collapses to `seller_attested`. The same vendor's offering on a third-party platform (Podtrac on a publisher who isn't Podtrac) is `vendor_attested`. The trust axis is *not* who runs the SDK — it's who is independent of the seller's revenue interest.").optional(), "attribution_methodology": z.enum(["deterministic_purchase","probabilistic","panel_based","modeled"]).describe("How attribution between ad exposure and outcome events was computed. Used as a `qualifier.attribution_methodology` key on `committed_metrics`, `missing_metrics`, package-level delivery values (`metric_values` or `vendor_metric_values`), and `performance-feedback.metric` to disambiguate the same outcome metric reported under different methodologies — `conversion_value` measured deterministically (matched purchase IDs) is not the same number as `conversion_value` measured probabilistically (modeled match) and should never be summed across methodologies. The retail-media closed-loop pattern typically reports under `deterministic_purchase`; MMM and clean-room outputs typically report under `modeled` or `probabilistic`; panel-based measurement (Nielsen, comScore, Edison) reports under `panel_based`.").optional(), "attribution_window": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").optional(), "lift_dimension": z.enum(["awareness","consideration","favorability","purchase_intent","ad_recall"]).describe("Brand-lift dimension disambiguator. Brand lift is multidimensional in production — Kantar, Upwave, Cint, DoubleVerify, and similar vendors report awareness, consideration, favorability, purchase intent, and ad recall as separate measurements with their own sample sizes and confidence intervals. Used as a `qualifier.lift_dimension` key on `committed_metrics`, `missing_metrics`, package-level delivery values (`metric_values` or `vendor_metric_values`), and `performance-feedback.metric` to disambiguate which dimension of `brand_lift` a row represents. Two `brand_lift` rows under different lift dimensions represent different surveyed outcomes and must not be combined into a single number.").optional() }).passthrough().describe("Compact qualifier set that distinguishes incompatible reporting definitions for the same metric ID.").optional(), "effective_at": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() }).passthrough()]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17756,7 +15714,8 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - }).describe("Canonical 3.2 optimization objective. Monetary execution policy belongs in BiddingPolicy; legacy monetary targets and unbound attention metrics are excluded.")).min(1) }).passthrough()]; + })).describe("One metric the seller commits to report for a commercial product term. Vendor identity uses BrandKey so the compact lifecycle does not inline brand or provenance documents.")).min(1) }).passthrough()).min(1).describe("Binding reporting contract keyed by position in purchases. Amendments preserve prior entries and add metrics with effective_at; seller-assigned package IDs live in the execution binding, outside this digest.").optional(), "cancellation_terms": z.object({ "effective_at": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time"), "fee": z.object({ "amount": z.number().gte(0), "currency": z.string().regex(new RegExp("^[A-Z]{3}$")) }).passthrough().optional(), "reason": z.string().min(1).max(500).optional() }).passthrough().optional(), "change_terms": z.array(z.object({ "term_id": z.string().regex(new RegExp("^[A-Za-z0-9_.:-]+$")), "action": z.enum(["pause","resume","cancel","extend_flight","shorten_flight","update_flight_dates","increase_budget","decrease_budget","reallocate_budget","update_budget_allocation","update_targeting","update_pacing","update_bidding","update_frequency_caps","update_media_buy_frequency_cap","update_catalog_assignments","update_keywords","update_optimization_goals","update_impression_goal","update_spend_target","update_reporting_webhook","replace_creative","update_creative_assignments","remove_creative","add_packages","remove_packages"]).describe("Fine-grained MediaBuy action vocabulary for compact product and lifecycle surfaces. Deprecated coarse 3.x actions are absent."), "service_mode": z.enum(["self_serve","conditional_self_serve","seller_managed","requires_approval"]).describe("How a seller honors a routed compact-lifecycle action."), "allowed_statuses": z.array(z.enum(["pending_creatives","pending_start","active","paused"])).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Non-terminal MediaBuy statuses in which this negotiated right may be exercised. When absent, the right applies in every non-terminal status where the canonical action itself is meaningful. This field describes contractual lifecycle scope; available_actions[] remains authoritative for the current instant.").optional(), "processing_sla": z.object({ "response_max": z.string().regex(new RegExp("^P(?!$)(\\d+Y)?(\\d+M)?(\\d+D)?(T(\\d+H)?(\\d+M)?(\\d+S)?)?$")).describe("Maximum elapsed time from when the buyer issues the action to when the seller acknowledges receipt (mode-appropriate: synchronous response for self_serve, tolerance decision for conditional_self_serve, or queue acknowledgement for seller_managed and legacy requires_approval). Sellers include weekends and non-working periods in the maximum. ISO 8601 duration.").optional(), "completion_max": z.string().regex(new RegExp("^P(?!$)(\\d+Y)?(\\d+M)?(\\d+D)?(T(\\d+H)?(\\d+M)?(\\d+S)?)?$")).describe("Maximum elapsed time from buyer issuing the action to the seller completing it (mutation applied, proposal finalized, or seller-managed decision resolved). Sellers include weekends and non-working periods in the maximum. ISO 8601 duration.").optional() }).passthrough().describe("Binding elapsed-time acknowledgement and completion commitment. Sellers account for weekends and non-working periods when declaring the maximum.").optional(), "conditions": z.array(z.string().regex(new RegExp("^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Opaque stable condition identifiers defined by terms_ref or bilateral commercial documentation. Implementations compare identifiers; they MUST NOT execute or interpret them as instructions.").optional(), "constraints": z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "kind": z.literal("budget"), "max_delta_amount": z.object({ "amount": z.number().gte(0), "currency": z.string().regex(new RegExp("^[A-Z]{3}$")) }).passthrough().describe("Maximum absolute amount by which the affected budget may change in the direction named by the action.").optional(), "max_delta_percent": z.number().gte(0).describe("Maximum percentage change relative to the current committed value. Values above 100 are valid for increases greater than the current value.").optional(), "min_result_amount": z.object({ "amount": z.number().gte(0), "currency": z.string().regex(new RegExp("^[A-Z]{3}$")) }).passthrough().describe("Minimum resulting committed value after the change.").optional(), "max_result_amount": z.object({ "amount": z.number().gte(0), "currency": z.string().regex(new RegExp("^[A-Z]{3}$")) }).passthrough().describe("Maximum resulting committed value after the change.").optional() }).passthrough().and(z.union([z.object({ "max_delta_amount": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max_delta_percent": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "min_result_amount": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max_result_amount": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])), z.object({ "kind": z.literal("flight"), "max_change": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("Maximum extension, shortening, or shift in the direction named by the action.").optional(), "earliest_result": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "latest_result": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "minimum_notice": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("Minimum elapsed notice before the requested flight change may take effect.").optional() }).passthrough().and(z.union([z.object({ "max_change": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "earliest_result": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "latest_result": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "minimum_notice": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])), z.object({ "kind": z.literal("package_count"), "max_additions": z.number().int().gte(0).describe("Maximum packages that may be added by one exercise of the right.").optional(), "max_removals": z.number().int().gte(0).describe("Maximum packages that may be removed by one exercise of the right.").optional(), "max_result_count": z.number().int().gte(0).describe("Maximum active package count after the change.").optional() }).passthrough().and(z.union([z.object({ "max_additions": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max_removals": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max_result_count": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])), z.object({ "kind": z.literal("effective_timing"), "minimum_notice": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("Minimum elapsed notice before pause, resume, cancellation, or another operational action may take effect.").optional(), "earliest_effective_at": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "latest_effective_at": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() }).passthrough().and(z.union([z.object({ "minimum_notice": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "earliest_effective_at": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "latest_effective_at": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]))]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17787,8 +15746,9 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - }).describe("Canonical fixed or seller-optimized allocation using only canonical optimization goals.").optional(), "pacing": z.enum(["even","asap","front_loaded"]).describe("Budget pacing strategy").optional(), "bidding": z.object({ "automatic": z.literal(true).describe("Explicitly use seller/provider automatic bidding at this authored scope. At package scope this is a complete override of a media-buy policy, not inheritance. It MUST be the only field in the block and MUST be preserved on readback.").optional(), "bid_amount": z.number().gt(0).describe("Manual auction bid denominated in the media-buy currency and expressed per the selected pricing option's auction unit. For example, a CPM option interprets the amount per thousand impressions. This is the amount submitted to the auction, not a promise that the clearing price equals it. Requires an auction-priced pricing option whose currency equals the media-buy currency.").optional(), "max_bid": z.number().gt(0).describe("Hard per-auction ceiling denominated in the media-buy currency and expressed per the selected pricing option's auction unit. This is the only canonical hard auction ceiling and MUST NOT be translated into an average outcome-cost control. Requires an auction-priced pricing option whose currency equals the media-buy currency. May stand alone or supplement cost_per/roas only when the relevant scope capability advertises that combination.").optional(), "cost_per": z.object({ "amount": z.number().gt(0).describe("Average cost amount per scope-bound primary-goal result, denominated in the media-buy currency."), "strength": z.enum(["cap","target"]).describe("`cap` optimizes for an average at or below the amount and accepts underdelivery when necessary; `target` optimizes around the amount while balancing volume and spend. Neither is a per-result or per-auction guarantee.") }).passthrough().describe("Average cost control per result of the scope-bound primary optimization goal. At seller-optimized media-buy scope it binds to budget_allocation.optimization_goals; at package scope it binds to that package's optimization_goals; at fixed media-buy scope it binds independently to each inheriting package and is valid only when their primary-goal result units are compatible. Metric goals are compatible only when metric and every result-defining qualifier match; vendor_metric goals only when vendor and metric_id match; event goals only when the event_type/custom_event_name set and resolved attribution_window match. Primary is the earliest array entry among goals tied for the lowest explicit numeric priority; unprioritized goals follow explicitly prioritized goals; when all priorities are absent, the first entry is primary.").optional(), "roas": z.object({ "value": z.number().gt(0).describe("Return per unit of ad spend; 4 means 4 units of value per 1 unit spent."), "strength": z.enum(["floor","target"]).describe("`floor` prefers underdelivery to knowingly optimizing below the requested return; `target` optimizes around the requested return. Neither guarantees realized return.") }).passthrough().describe("Dimensionless return-on-ad-spend control bound to the same scope-specific primary goal rules as cost_per. The bound goal must be value-bearing; a fixed media-buy default requires a value-bearing primary goal on every inheriting package. Every referenced value-bearing event source MUST declare value_currencies containing the media-buy currency. The seller validates this at buy creation; each buy consumes only exact-currency records, while other declared currencies remain available to other buys. Sellers MUST NOT perform currency conversion.").optional() }).passthrough().and(z.any().refine((value) => !z.union([z.object({ "automatic": z.any().refine((value) => value !== undefined, "Required"), "bid_amount": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "automatic": z.any().refine((value) => value !== undefined, "Required"), "max_bid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "automatic": z.any().refine((value) => value !== undefined, "Required"), "cost_per": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "automatic": z.any().refine((value) => value !== undefined, "Required"), "roas": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "bid_amount": z.any().refine((value) => value !== undefined, "Required"), "max_bid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "bid_amount": z.any().refine((value) => value !== undefined, "Required"), "cost_per": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "bid_amount": z.any().refine((value) => value !== undefined, "Required"), "roas": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "cost_per": z.any().refine((value) => value !== undefined, "Required"), "roas": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]).safeParse(value).success, "Invalid input: Should NOT be valid against schema")).describe("Buyer-authored execution policy for automatic delivery, auction bidding, average outcome cost, or return on ad spend. The containing object determines authored scope: media-buy `bidding` is a complete inherited default and package `bidding` is a complete package override. Sellers MUST preserve authored scope on readback and MUST NOT copy an inherited media-buy policy into package `bidding`. Every monetary field in this block is denominated in the media-buy currency; the selected pricing option supplies the auction unit, never another denomination. Auction-unit identity is the pricing_model plus every canonical billing-event qualifier after defaults are applied: for example CPV view threshold, CPP demographic system/demographic, CPA event tuple, time time_unit, and flat-rate/DOOH parameters. An extension qualifier participates only when its registered extension specification explicitly defines how it contributes to auction-unit identity. A media-buy bid_amount or max_bid is valid only when every inheriting package resolves the same auction-unit identity. Every affected pricing option MUST use the media-buy currency; split currency-mismatched packages into separate buys. Seller-optimized media-buy cost_per/roas bind to the primary budget_allocation.optimization_goals goal. Package-authored cost_per/roas bind to the package primary optimization goal. The primary goal is the earliest array entry among goals with the lowest explicit numeric priority; unprioritized goals follow explicitly prioritized goals; when all priorities are absent, the first entry is primary. In fixed allocation, an inherited media-buy cost_per is valid only when all inheriting packages have compatible primary-goal result units; inherited roas requires value-bearing primary goals on every inheriting package. Canonical ROAS requires each value-bearing event source to declare the media-buy currency in value_currencies; each buy consumes only exact-currency records and sellers MUST NOT convert them. Absence invokes inheritance or provider automatic delivery; `{automatic:true}` is an explicit authored policy that overrides inheritance. Sellers MUST reject unsupported modes, combinations, units, currency, goal bindings, or native placements before any provider mutation and MUST NOT silently translate semantics.").refine((value) => Object.keys(value).length >= 1, "Object must contain at least 1 property").optional(), "invoice_recipient": z.object({ "legal_name": z.string().max(200).describe("Registered legal name of the business entity"), "vat_id": z.string().regex(new RegExp("^[A-Z]{2}[A-Z0-9]{2,13}$")).describe("VAT identification number (e.g., DE123456789 for Germany, FR12345678901 for France). Required for B2B invoicing in the EU. Must be normalized: no spaces, dots, or dashes.").optional(), "tax_id": z.string().max(30).describe("Tax identification number for jurisdictions that do not use VAT (e.g., US EIN)").optional(), "registration_number": z.string().max(50).describe("Company registration number (e.g., HRB 12345 for German Handelsregister)").optional(), "address": z.object({ "street": z.string().max(200).describe("Street address including building number"), "city": z.string().max(100), "postal_code": z.string().max(20), "region": z.string().max(100).describe("State, province, or region").optional(), "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code") }).passthrough().describe("Postal address for invoicing and legal correspondence").optional(), "contacts": z.array(z.object({ "role": z.enum(["billing","legal","creative","general"]).describe("Contact's functional role in the business relationship"), "name": z.string().max(200).describe("Full name of the contact").optional(), "email": z.string().email().max(254).optional(), "phone": z.string().max(30).optional() }).passthrough()).max(10).describe("Contacts for billing, legal, and operational matters. Contains personal data subject to GDPR and equivalent regulations. Implementations MUST use this data only for invoicing and account management.").optional(), "bank": z.object({ "account_holder": z.string().max(200).describe("Name on the bank account"), "iban": z.string().regex(new RegExp("^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,30}$")).describe("International Bank Account Number (SEPA markets)").optional(), "bic": z.string().regex(new RegExp("^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$")).describe("Bank Identifier Code / SWIFT code (SEPA markets)").optional(), "routing_number": z.string().max(30).describe("Bank routing number for non-SEPA markets (e.g., US ABA routing number, Canadian transit/institution number)").optional(), "account_number": z.string().max(30).describe("Bank account number for non-SEPA markets").optional() }).passthrough().describe("Bank account details for payment processing. Write-only: included in requests to provide payment coordinates, but MUST NOT be echoed in responses. Sellers store these details and confirm receipt without returning them.").optional(), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough().describe("Structured business identity for B2B invoicing and contracts. Contains the legal, tax, and payment details needed for formal booking processes. Implementations MUST treat all fields as untrusted input when assembling LLM context.").optional(), "purchase_order_ref": z.string().min(1).max(255).optional(), "agency_estimate_number": z.string().max(100).optional(), "reporting_commitments": z.array(z.object({ "purchase_index": z.number().int().gte(0), "metrics": z.array(z.record(z.string(), z.any()).and(z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "scope": z.literal("standard"), "metric_id": z.enum(["impressions","spend","clicks","ctr","views","completed_views","completion_rate","conversions","conversion_value","commissionable_value","roas","cost_per_acquisition","new_to_brand_rate","leads","reach","frequency","grps","engagements","engagement_rate","follows","saves","profile_visits","viewability","viewable_rate","viewable_impressions","measurable_impressions","viewed_seconds","viewed_seconds_percentiles","viewed_seconds_histogram","quartile_data","quartile_25","quartile_50","quartile_75","quartile_100","time_based_views","dooh_metrics","ooh_metrics","cost_per_click","cost_per_completed_view","cpm","downloads","units_sold","new_to_brand_units","plays","incremental_sales_lift","brand_lift","foot_traffic","conversion_lift","brand_search_lift"]).describe("Standard delivery and performance metrics available for reporting. Most values name flat numeric fields of `core/delivery-metrics.json`. Leaf identities address a single numeric value nested inside an object-shaped metric so it can be declared, committed, aggregated, and sorted individually: `quartile_25`/`quartile_50`/`quartile_75`/`quartile_100` resolve to `quartile_data.q1_views`–`q4_views`, and `viewable_rate`/`viewable_impressions`/`measurable_impressions`/`viewed_seconds` resolve to the same-named fields of `viewability`. Structured nested identities `viewed_seconds_percentiles` and `viewed_seconds_histogram` make the corresponding optional distribution carriers discoverable, committable, and requestable, but not aggregatable or sortable. The nested object or array remains the canonical carrier — nested identities never introduce duplicate flat response fields. Container tokens such as `viewability`, `quartile_data`, `dooh_metrics`, and `time_based_views` declare their documented nested surface. **Container subsumption applies only to numeric leaves**: `viewability` subsumes `viewable_rate`, `viewable_impressions`, `measurable_impressions`, and `viewed_seconds`; `quartile_data` subsumes `quartile_25`, `quartile_50`, `quartile_75`, and `quartile_100`. This rule applies to capability declaration, `required_metrics` filtering, format `reported_metrics` intersection, and `requested_metrics` selection. Optional structured identities MUST be declared explicitly: `viewability` alone does not satisfy `viewed_seconds_percentiles` or `viewed_seconds_histogram`. Requesting any nested identity selects its canonical carrier in the response. A nested identity declaration does not imply sibling values or the carrier's non-metric fields."), "qualifier": z.object({ "viewability_standard": z.enum(["mrc","groupm"]).describe("Viewability measurement standard applied to determine whether an impression qualifies as viewable. These are materially different thresholds and should not be compared across standards.").optional(), "completion_source": z.enum(["seller_attested","vendor_attested"]).describe("Trust-source disambiguator for `completion_rate` — *who* attested to the completion event, not *how* (methodology granularity is a separate dimension; future qualifier keys may add it if buyer demand surfaces). The two paths can yield materially different rates, particularly in SSAI environments where the player's view of completion may differ from a vendor's. Used as a `qualifier.completion_source` key on `committed_metrics`, `missing_metrics`, and package-level delivery values (`metric_values` or `vendor_metric_values`) to disambiguate which trust source the row represents. Edge cases: walled gardens where the seller is also the measurement vendor (YouTube, Spotify) collapse to `seller_attested` by trust-model logic — the same party served and counted. IAB-certified first-party podcast measurement (Podtrac, Triton on their own platforms; Art19 on its own platform) likewise collapses to `seller_attested`. The same vendor's offering on a third-party platform (Podtrac on a publisher who isn't Podtrac) is `vendor_attested`. The trust axis is *not* who runs the SDK — it's who is independent of the seller's revenue interest.").optional(), "attribution_methodology": z.enum(["deterministic_purchase","probabilistic","panel_based","modeled"]).describe("How attribution between ad exposure and outcome events was computed. Used as a `qualifier.attribution_methodology` key on `committed_metrics`, `missing_metrics`, package-level delivery values (`metric_values` or `vendor_metric_values`), and `performance-feedback.metric` to disambiguate the same outcome metric reported under different methodologies — `conversion_value` measured deterministically (matched purchase IDs) is not the same number as `conversion_value` measured probabilistically (modeled match) and should never be summed across methodologies. The retail-media closed-loop pattern typically reports under `deterministic_purchase`; MMM and clean-room outputs typically report under `modeled` or `probabilistic`; panel-based measurement (Nielsen, comScore, Edison) reports under `panel_based`.").optional(), "attribution_window": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").optional(), "lift_dimension": z.enum(["awareness","consideration","favorability","purchase_intent","ad_recall"]).describe("Brand-lift dimension disambiguator. Brand lift is multidimensional in production — Kantar, Upwave, Cint, DoubleVerify, and similar vendors report awareness, consideration, favorability, purchase intent, and ad recall as separate measurements with their own sample sizes and confidence intervals. Used as a `qualifier.lift_dimension` key on `committed_metrics`, `missing_metrics`, package-level delivery values (`metric_values` or `vendor_metric_values`), and `performance-feedback.metric` to disambiguate which dimension of `brand_lift` a row represents. Two `brand_lift` rows under different lift dimensions represent different surveyed outcomes and must not be combined into a single number.").optional() }).passthrough().describe("Compact qualifier set that distinguishes incompatible reporting definitions for the same metric ID.").optional(), "effective_at": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() }).passthrough(), z.object({ "scope": z.literal("vendor"), "vendor": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery."), "metric_id": z.string().regex(new RegExp("^[a-z][a-z0-9_]*$")).min(1).max(64).describe("Identifier for a vendor-defined metric within the vendor's vocabulary. Stable lookup key; the vendor publishes the canonical list (with category, methodology, and standard alignment) in `brand.json` `agents[type='measurement']`. Lowercase with underscores so a future enum promotion into `available-metric.json` is a literal string lift. Identifier is namespaced by the vendor — the same `metric_id` may mean different things in different vendors' vocabularies."), "qualifier": z.object({ "viewability_standard": z.enum(["mrc","groupm"]).describe("Viewability measurement standard applied to determine whether an impression qualifies as viewable. These are materially different thresholds and should not be compared across standards.").optional(), "completion_source": z.enum(["seller_attested","vendor_attested"]).describe("Trust-source disambiguator for `completion_rate` — *who* attested to the completion event, not *how* (methodology granularity is a separate dimension; future qualifier keys may add it if buyer demand surfaces). The two paths can yield materially different rates, particularly in SSAI environments where the player's view of completion may differ from a vendor's. Used as a `qualifier.completion_source` key on `committed_metrics`, `missing_metrics`, and package-level delivery values (`metric_values` or `vendor_metric_values`) to disambiguate which trust source the row represents. Edge cases: walled gardens where the seller is also the measurement vendor (YouTube, Spotify) collapse to `seller_attested` by trust-model logic — the same party served and counted. IAB-certified first-party podcast measurement (Podtrac, Triton on their own platforms; Art19 on its own platform) likewise collapses to `seller_attested`. The same vendor's offering on a third-party platform (Podtrac on a publisher who isn't Podtrac) is `vendor_attested`. The trust axis is *not* who runs the SDK — it's who is independent of the seller's revenue interest.").optional(), "attribution_methodology": z.enum(["deterministic_purchase","probabilistic","panel_based","modeled"]).describe("How attribution between ad exposure and outcome events was computed. Used as a `qualifier.attribution_methodology` key on `committed_metrics`, `missing_metrics`, package-level delivery values (`metric_values` or `vendor_metric_values`), and `performance-feedback.metric` to disambiguate the same outcome metric reported under different methodologies — `conversion_value` measured deterministically (matched purchase IDs) is not the same number as `conversion_value` measured probabilistically (modeled match) and should never be summed across methodologies. The retail-media closed-loop pattern typically reports under `deterministic_purchase`; MMM and clean-room outputs typically report under `modeled` or `probabilistic`; panel-based measurement (Nielsen, comScore, Edison) reports under `panel_based`.").optional(), "attribution_window": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("A time duration expressed as an interval and unit. Used for frequency cap windows, attribution windows, reach optimization windows, time budgets, and other time-based settings. When unit is 'campaign', interval must be 1 — the window spans the full campaign flight.").optional(), "lift_dimension": z.enum(["awareness","consideration","favorability","purchase_intent","ad_recall"]).describe("Brand-lift dimension disambiguator. Brand lift is multidimensional in production — Kantar, Upwave, Cint, DoubleVerify, and similar vendors report awareness, consideration, favorability, purchase intent, and ad recall as separate measurements with their own sample sizes and confidence intervals. Used as a `qualifier.lift_dimension` key on `committed_metrics`, `missing_metrics`, package-level delivery values (`metric_values` or `vendor_metric_values`), and `performance-feedback.metric` to disambiguate which dimension of `brand_lift` a row represents. Two `brand_lift` rows under different lift dimensions represent different surveyed outcomes and must not be combined into a single number.").optional() }).passthrough().describe("Compact qualifier set that distinguishes incompatible reporting definitions for the same metric ID.").optional(), "effective_at": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() }).passthrough()]; + }).describe("Portable bounds that buyer and seller SDKs can preflight. Omission means no machine-readable bound was promised; opaque conditions remain unevaluated.").optional(), "terms_ref": z.string().min(1).max(1000).describe("Stable contract reference. Resolving it cannot expand the typed right and MUST use the caller's normal authenticated contract-document path, never ambient seller credentials.").optional(), "description": z.string().min(1).max(1000).describe("Display-only summary; it cannot grant authority, add an action, or override typed fields.").optional(), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough().describe("A proposal-bound buyer change right. It binds to the resulting media buy and account, not personally to the caller, and may be exercised by any caller admitted by both seller account authorization and applicable signed governance delegation.")).min(1).describe("Binding buyer change rights included in the commercial envelope and therefore covered by terms_digest. Entries are uniquely keyed by action. When this field is present, an omitted action is not a negotiated change right. Omission of the entire field means legacy-unspecified rights, not a prohibition.").optional() }).passthrough().describe("Complete typed commercial envelope for a compact-lifecycle proposal. This is the authoritative audit and refinement snapshot; allocations and narrative fields are explanatory views rather than substitutes for these terms."), "terms_digest": z.string().regex(new RegExp("^sha256:[A-Za-z0-9_-]{43}$")).describe("Base64url SHA-256 digest of the RFC 8785 JCS serialization of commercial_terms, prefixed with sha256:."), "insertion_order": z.object({ "io_id": z.string().max(255).describe("Unique identifier for this insertion order. Referenced by io_acceptance on create_media_buy."), "terms": z.object({ "advertiser": z.string().max(500).describe("Advertiser name or identifier").optional(), "publisher": z.string().max(500).describe("Publisher name or identifier").optional(), "total_budget": z.object({ "amount": z.number().gte(0), "currency": z.string().min(3).max(3).describe("ISO 4217 currency code") }).describe("Total committed budget").optional(), "flight_start": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "flight_end": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "payment_terms": z.enum(["net_30","net_60","net_90","prepaid","due_on_receipt"]).describe("Payment terms").optional() }).catchall(z.any()).describe("Summary fields echoed from the committed proposal for agent verification. Buyer agents use these to confirm the IO matches what was negotiated before a human signs. These are read-only summaries, not negotiation surfaces — deal terms live on products and packages.").optional(), "terms_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL to a human-readable document containing the full insertion order terms").optional(), "signing_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL to an electronic signing service (e.g., DocuSign) for human signature workflows. When present, a human must sign before the buyer agent can proceed with create_media_buy.").optional(), "requires_signature": z.boolean().describe("Whether the buyer must accept this IO before creating a media buy. When true, create_media_buy requires an io_acceptance referencing this io_id.") }).catchall(z.any()).describe("A signing wrapper attached to a committed proposal. The IO does not introduce new deal terms — all negotiated terms (performance standards, measurement terms, cancellation policy, pricing) live on the product and package. The IO exists for human signature workflows and provides summary fields so buyer agents can verify the IO matches the committed proposal before a human signs.").optional(), "total_budget_guidance": z.object({ "min": z.number().gte(0).optional(), "recommended": z.number().gte(0).optional(), "max": z.number().gte(0).optional(), "currency": z.string().regex(new RegExp("^[A-Z]{3}$")) }).passthrough().and(z.union([z.object({ "recommended": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "min": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("Optional budget guidance for this proposal — the planning answer to criteria.outcome_target and to open-budget briefs. commercial_terms.total_budget remains the concrete figure the plan is priced at; this band expresses the seller's recommended range around it.").optional(), "forecast": z.object({ "points": z.array(z.object({ "label": z.string().max(128).optional(), "budget": z.number().gte(0).optional(), "product_id": z.string().optional(), "dimensions": z.array(z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "kind": z.literal("geo").describe("Dimension family discriminator."), "geo_level": z.enum(["country","region","metro","postal_area"]).describe("Geographic level for this forecast point."), "system": z.string().describe("Classification system for metro or postal_area levels. Required when geo_level is 'metro' or 'postal_area'. Metro rows use metro-system enum values such as 'nielsen_dma'; native postal rows use country-local postal-system enum values such as 'zip' with country 'US'; deprecated legacy postal rows may use legacy-postal-system enum values such as 'us_zip'. Omit for country and region rows.").optional(), "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code. Required for native postal_area rows and omitted for legacy postal rows, metro rows, country rows, and region rows.").optional(), "geo_code": z.string().describe("Geographic code within the level and system. Country: ISO 3166-1 alpha-2 ('US'). Region: ISO 3166-2 with country prefix ('US-CA'). Metro/postal: system-specific code ('501', '10001')."), "geo_name": z.string().describe("Human-readable geographic name (e.g., 'United States', 'California', 'New York DMA').").optional() }).passthrough().and(z.intersection(z.intersection(z.union([z.any().refine((value) => !z.object({ "geo_level": z.literal("country") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "geo_level": z.literal("country") }), z.object({ "geo_code": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code.").optional() }))]), z.union([z.any().refine((value) => !z.object({ "geo_level": z.literal("region") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "geo_level": z.literal("region") }), z.object({ "geo_code": z.string().regex(new RegExp("^[A-Z]{2}-[A-Z0-9]{1,3}$")).describe("ISO 3166-2 subdivision code.").optional() }))])), z.intersection(z.union([z.any().refine((value) => !z.object({ "geo_level": z.literal("metro") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "geo_level": z.literal("metro") }), z.object({ "system": z.enum(["nielsen_dma","uk_itl1","uk_itl2","eurostat_nuts2","custom"]).describe("Metro area classification system (e.g., 'nielsen_dma', 'uk_itl2')") }))]), z.union([z.any().refine((value) => !z.object({ "geo_level": z.literal("postal_area") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "geo_level": z.literal("postal_area") }), z.union([z.object({ "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code."), "system": z.enum(["postal_code","zip","zip_plus_four","outward","full","fsa","plz","code_postal","postcode","cep","pin","custom","us_zip","us_zip_plus_four","gb_outward","gb_full","ca_fsa","ca_full","de_plz","fr_code_postal","au_postcode","ch_plz","at_plz"]).describe("Country-local postal code system.") }).and(z.union([z.object({ "country": z.literal("US").optional(), "system": z.enum(["zip","zip_plus_four"]).optional() }), z.object({ "country": z.literal("GB").optional(), "system": z.enum(["outward","full"]).optional() }), z.object({ "country": z.literal("CA").optional(), "system": z.enum(["fsa","full"]).optional() }), z.object({ "country": z.enum(["DE","CH","AT"]).optional(), "system": z.literal("plz").optional() }), z.object({ "country": z.literal("FR").optional(), "system": z.literal("code_postal").optional() }), z.object({ "country": z.literal("AU").optional(), "system": z.literal("postcode").optional() }), z.object({ "country": z.literal("BR").optional(), "system": z.literal("cep").optional() }), z.object({ "country": z.literal("IN").optional(), "system": z.literal("pin").optional() }), z.object({ "country": z.literal("ZA").optional(), "system": z.literal("postal_code").optional() }), z.object({ "country": z.any().refine((value) => !z.enum(["US","GB","CA","DE","CH","AT","FR","AU","BR","IN","ZA"]).safeParse(value).success, "Invalid input: Should NOT be valid against schema").optional(), "system": z.enum(["postal_code","custom"]).optional() })])).describe("Valid country-local postal system pairing. Registered countries only accept their registered local systems; countries without a registered local system use postal_code or custom."), z.object({ "system": z.enum(["us_zip","us_zip_plus_four","gb_outward","gb_full","ca_fsa","ca_full","de_plz","fr_code_postal","au_postcode","ch_plz","at_plz"]).describe("Deprecated country-fused postal code system (e.g., 'us_zip', 'gb_outward'). Prefer country + postal-system.") })]))])))).describe("A geographic dimension for a ForecastPoint row. Variant of ForecastPoint dimensions; see forecast-point-dimensions.json for dispatch rules."), z.object({ "kind": z.literal("placement").describe("Dimension family discriminator."), "placement_ref": z.object({ "publisher_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain where the adagents.json declaring a publisher-catalog placement is hosted, or the inventory publisher associated with an inline placement. Omitted only for legacy single-publisher product-context references.").optional(), "placement_id": z.string().describe("Placement ID from the publisher's adagents.json placement catalog, or an inline seller-defined placement ID interpreted within the enclosing seller and product context.") }).catchall(z.any()).describe("Structured placement reference for this forecast row. References an entry from the product's placements array."), "placement_name": z.string().describe("Human-readable placement name, useful when the buyer has not resolved the placement catalog.").optional() }).passthrough().describe("A placement dimension for a ForecastPoint row. Variant of ForecastPoint dimensions; see forecast-point-dimensions.json for dispatch rules."), z.object({ "kind": z.literal("device_type").describe("Dimension family discriminator."), "device_type": z.enum(["desktop","mobile","tablet","ctv","dooh","unknown"]).describe("Device form factor categories for targeting and reporting. Complements device-platform (operating system) with hardware classification. OpenRTB mapping: 1 (Mobile/Tablet General) → mobile, 2 (PC) → desktop, 4 (Phone) → mobile, 5 (Tablet) → tablet, 6 (Connected Device) → ctv, 7 (Set Top Box) → ctv. DOOH inventory uses dooh.") }).passthrough().describe("A device form-factor dimension for a ForecastPoint row. Variant of ForecastPoint dimensions; see forecast-point-dimensions.json for dispatch rules."), z.object({ "kind": z.literal("device_platform").describe("Dimension family discriminator."), "device_platform": z.enum(["ios","android","windows","macos","linux","chromeos","tvos","tizen","webos","fire_os","roku_os","unknown"]).describe("Operating system platforms for device targeting. Browser values from Sec-CH-UA-Platform standard, extended for CTV.") }).passthrough().describe("An operating-system or platform dimension for a ForecastPoint row. Variant of ForecastPoint dimensions; see forecast-point-dimensions.json for dispatch rules."), z.object({ "kind": z.literal("audience").describe("Dimension family discriminator."), "audience_id": z.string().describe("Audience segment identifier for this forecast row."), "audience_source": z.enum(["synced","platform","third_party","lookalike","retargeting","unknown"]).describe("Origin of the audience segment."), "audience_name": z.string().describe("Human-readable audience segment name.").optional() }).passthrough().describe("An audience segment dimension for a ForecastPoint row. Variant of ForecastPoint dimensions; see forecast-point-dimensions.json for dispatch rules."), z.object({ "kind": z.literal("signal").describe("Dimension family discriminator."), "signal_ref": z.any().superRefine((x, ctx) => { + const schemas = [z.object({ "scope": z.literal("product").describe("Discriminator indicating the signal resolves through the selected product's included_signals or signal_targeting_options."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Product-local signal identifier. For local signals exposed on both get_signals and get_products, this MUST match get_signals.signals[].signal_ref.signal_id for the same signal.") }).catchall(z.any()).describe("Product-scoped signal. The signal_id is meaningful only within the selected product/package context and MUST match a Product.included_signals[].signal_ref.signal_id or Product.signal_targeting_options[].signal_ref.signal_id for that product, depending on whether the signal is descriptive or selectable."), z.object({ "scope": z.literal("data_provider").describe("Discriminator indicating the signal resolves through a data provider's published adagents.json signals[]."), "data_provider_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that publishes the signal definition in its adagents.json signals[]."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the data provider's published adagents.json signals[].") }).catchall(z.any()).describe("Data-provider-scoped signal. The signal_id resolves through the data provider's published adagents.json signals[] and can be authorization-verified there."), z.object({ "scope": z.literal("signal_source").describe("Discriminator indicating the signal resolves through the issuing signal source."), "signal_source_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the signal source that issues this source-native signal."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the issuing signal source's signal set.") }).catchall(z.any()).describe("Signal-source-scoped signal. Use this for source-native signals that are not published in upstream adagents.json signals[]. The buyer trusts the issuing signal source for this identity; use scope 'data_provider' instead when the signal is published in adagents.json signals[], even if the publisher is also the seller or signal source.")]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17819,8 +15779,7 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - })).describe("One metric the seller commits to report for a commercial product term. Vendor identity uses BrandKey so the compact lifecycle does not inline brand or provenance documents.")).min(1) }).passthrough()).min(1).describe("Binding reporting contract keyed by position in purchases. Amendments preserve prior entries and add metrics with effective_at; seller-assigned package IDs live in the execution binding, outside this digest.").optional(), "cancellation_terms": z.object({ "effective_at": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time"), "fee": z.object({ "amount": z.number().gte(0), "currency": z.string().regex(new RegExp("^[A-Z]{3}$")) }).passthrough().optional(), "reason": z.string().min(1).max(500).optional() }).passthrough().optional(), "change_terms": z.array(z.object({ "term_id": z.string().regex(new RegExp("^[A-Za-z0-9_.:-]+$")), "action": z.enum(["pause","resume","cancel","extend_flight","shorten_flight","update_flight_dates","increase_budget","decrease_budget","reallocate_budget","update_budget_allocation","update_targeting","update_pacing","update_bidding","update_frequency_caps","update_catalog_assignments","update_keywords","update_optimization_goals","update_impression_goal","update_spend_target","update_reporting_webhook","replace_creative","update_creative_assignments","remove_creative","add_packages","remove_packages"]).describe("Fine-grained MediaBuy action vocabulary for compact product and lifecycle surfaces. Deprecated coarse 3.x actions are absent."), "service_mode": z.enum(["self_serve","conditional_self_serve","seller_managed","requires_approval"]).describe("How a seller honors a routed compact-lifecycle action."), "allowed_statuses": z.array(z.enum(["pending_creatives","pending_start","active","paused"])).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Non-terminal MediaBuy statuses in which this negotiated right may be exercised. When absent, the right applies in every non-terminal status where the canonical action itself is meaningful. This field describes contractual lifecycle scope; available_actions[] remains authoritative for the current instant.").optional(), "processing_sla": z.object({ "response_max": z.string().regex(new RegExp("^P(?!$)(\\d+Y)?(\\d+M)?(\\d+D)?(T(\\d+H)?(\\d+M)?(\\d+S)?)?$")).describe("Maximum elapsed time from when the buyer issues the action to when the seller acknowledges receipt (mode-appropriate: synchronous response for self_serve, tolerance decision for conditional_self_serve, or queue acknowledgement for seller_managed and legacy requires_approval). Sellers include weekends and non-working periods in the maximum. ISO 8601 duration.").optional(), "completion_max": z.string().regex(new RegExp("^P(?!$)(\\d+Y)?(\\d+M)?(\\d+D)?(T(\\d+H)?(\\d+M)?(\\d+S)?)?$")).describe("Maximum elapsed time from buyer issuing the action to the seller completing it (mutation applied, proposal finalized, or seller-managed decision resolved). Sellers include weekends and non-working periods in the maximum. ISO 8601 duration.").optional() }).passthrough().describe("Binding elapsed-time acknowledgement and completion commitment. Sellers account for weekends and non-working periods when declaring the maximum.").optional(), "conditions": z.array(z.string().regex(new RegExp("^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Opaque stable condition identifiers defined by terms_ref or bilateral commercial documentation. Implementations compare identifiers; they MUST NOT execute or interpret them as instructions.").optional(), "constraints": z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "kind": z.literal("budget"), "max_delta_amount": z.object({ "amount": z.number().gte(0), "currency": z.string().regex(new RegExp("^[A-Z]{3}$")) }).passthrough().describe("Maximum absolute amount by which the affected budget may change in the direction named by the action.").optional(), "max_delta_percent": z.number().gte(0).describe("Maximum percentage change relative to the current committed value. Values above 100 are valid for increases greater than the current value.").optional(), "min_result_amount": z.object({ "amount": z.number().gte(0), "currency": z.string().regex(new RegExp("^[A-Z]{3}$")) }).passthrough().describe("Minimum resulting committed value after the change.").optional(), "max_result_amount": z.object({ "amount": z.number().gte(0), "currency": z.string().regex(new RegExp("^[A-Z]{3}$")) }).passthrough().describe("Maximum resulting committed value after the change.").optional() }).passthrough().and(z.union([z.object({ "max_delta_amount": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max_delta_percent": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "min_result_amount": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max_result_amount": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])), z.object({ "kind": z.literal("flight"), "max_change": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("Maximum extension, shortening, or shift in the direction named by the action.").optional(), "earliest_result": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "latest_result": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "minimum_notice": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("Minimum elapsed notice before the requested flight change may take effect.").optional() }).passthrough().and(z.union([z.object({ "max_change": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "earliest_result": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "latest_result": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "minimum_notice": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])), z.object({ "kind": z.literal("package_count"), "max_additions": z.number().int().gte(0).describe("Maximum packages that may be added by one exercise of the right.").optional(), "max_removals": z.number().int().gte(0).describe("Maximum packages that may be removed by one exercise of the right.").optional(), "max_result_count": z.number().int().gte(0).describe("Maximum active package count after the change.").optional() }).passthrough().and(z.union([z.object({ "max_additions": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max_removals": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max_result_count": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])), z.object({ "kind": z.literal("effective_timing"), "minimum_notice": z.object({ "interval": z.number().int().gte(1).describe("Number of time units. Must be 1 when unit is 'campaign'."), "unit": z.enum(["seconds","minutes","hours","days","campaign"]).describe("Time unit. 'seconds' for sub-minute precision. 'campaign' spans the full campaign flight.") }).passthrough().describe("Minimum elapsed notice before pause, resume, cancellation, or another operational action may take effect.").optional(), "earliest_effective_at": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "latest_effective_at": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() }).passthrough().and(z.union([z.object({ "minimum_notice": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "earliest_effective_at": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "latest_effective_at": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]))]; + }).describe("Canonical signal reference for this forecast row. Required when the row needs to disambiguate product-local, data-provider, or signal-source identity. Product-relative forecasts SHOULD use signal_ref.").optional(), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier shorthand for this forecast row. Use only when the enclosing context already identifies the signal unambiguously, such as a coverage_forecast nested directly under one get_signals signal item. Otherwise use signal_ref.").optional(), "signal_value": z.union([z.string().describe("Signal value bucket represented by this point. Use null with presence 'absent' to represent inventory where the signal is not present. Omit when the row describes any present value rather than one specific value."), z.number().describe("Signal value bucket represented by this point. Use null with presence 'absent' to represent inventory where the signal is not present. Omit when the row describes any present value rather than one specific value."), z.boolean().describe("Signal value bucket represented by this point. Use null with presence 'absent' to represent inventory where the signal is not present. Omit when the row describes any present value rather than one specific value."), z.null().describe("Signal value bucket represented by this point. Use null with presence 'absent' to represent inventory where the signal is not present. Omit when the row describes any present value rather than one specific value.")]).describe("Signal value bucket represented by this point. Use null with presence 'absent' to represent inventory where the signal is not present. Omit when the row describes any present value rather than one specific value.").optional(), "presence": z.enum(["present","absent"]).describe("Whether the signal is present for this point. Use 'absent' for the explicit not-present bucket."), "signal_name": z.string().describe("Human-readable signal name, useful when the buyer has not resolved the signal definition.").optional(), "signal_value_name": z.string().describe("Human-readable label for the signal value bucket.").optional() }).passthrough().and(z.union([z.object({ "signal_ref": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "signal_id": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).and(z.intersection(z.union([z.any().refine((value) => !z.object({ "presence": z.literal("absent") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "presence": z.literal("absent") }), z.object({ "signal_value": z.null() }))]), z.union([z.any().refine((value) => !z.object({ "presence": z.literal("present") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "presence": z.literal("present") }), z.object({ "signal_value": z.union([z.string(), z.number(), z.boolean()]).optional() }))]))).describe("A signal value or signal-presence dimension for a ForecastPoint row. Variant of ForecastPoint dimensions; see forecast-point-dimensions.json for dispatch rules."), z.object({ "kind": z.literal("time").describe("Dimension family discriminator."), "start_time": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time"), "end_time": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time") }).passthrough().describe("A calendar-window dimension for a ForecastPoint row. Variant of ForecastPoint dimensions; see forecast-point-dimensions.json for dispatch rules. Windows are half-open intervals [start_time, end_time): the row covers instants at or after start_time and strictly before end_time, so adjacent windows share a boundary without overlapping. end_time MUST be after start_time; JSON Schema draft-07 cannot compare sibling values, so conformance tooling enforces the ordering. Within one forecast, sellers MUST emit non-overlapping windows and SHOULD coalesce adjacent windows whose availability_status and metrics do not materially differ. When the request scoped the forecast with offer_filters.availability_horizon, a complete forecast partitions the requested horizon; a seller that cannot cover the full horizon signals the gap through the response's incomplete[] mechanism rather than silently omitting windows.")]; const { errors, failed } = schemas.reduce<{ errors: z.core.$ZodIssue[]; failed: number; @@ -17851,121 +15810,2439 @@ export const CanonicalProposalSchema: z.ZodObject<{ [K in keyof CanonicalProposa message: "Invalid input: Should pass single schema. Passed " + passed, }); } - }).describe("Portable bounds that buyer and seller SDKs can preflight. Omission means no machine-readable bound was promised; opaque conditions remain unevaluated.").optional(), "terms_ref": z.string().min(1).max(1000).describe("Stable contract reference. Resolving it cannot expand the typed right and MUST use the caller's normal authenticated contract-document path, never ambient seller credentials.").optional(), "description": z.string().min(1).max(1000).describe("Display-only summary; it cannot grant authority, add an action, or override typed fields.").optional(), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough().describe("A proposal-bound buyer change right. It binds to the resulting media buy and account, not personally to the caller, and may be exercised by any caller admitted by both seller account authorization and applicable signed governance delegation.")).min(1).describe("Binding buyer change rights included in the commercial envelope and therefore covered by terms_digest. Entries are uniquely keyed by action. When this field is present, an omitted action is not a negotiated change right. Omission of the entire field means legacy-unspecified rights, not a prohibition.").optional() }).passthrough().describe("Complete typed commercial envelope for a compact-lifecycle proposal. This is the authoritative audit and refinement snapshot; allocations and narrative fields are explanatory views rather than substitutes for these terms."), "terms_digest": z.string().regex(new RegExp("^sha256:[A-Za-z0-9_-]{43}$")).describe("Base64url SHA-256 digest of the RFC 8785 JCS serialization of commercial_terms, prefixed with sha256:."), "insertion_order": z.object({ "io_id": z.string().max(255).describe("Unique identifier for this insertion order. Referenced by io_acceptance on create_media_buy."), "terms": z.object({ "advertiser": z.string().max(500).describe("Advertiser name or identifier").optional(), "publisher": z.string().max(500).describe("Publisher name or identifier").optional(), "total_budget": z.object({ "amount": z.number().gte(0), "currency": z.string().min(3).max(3).describe("ISO 4217 currency code") }).describe("Total committed budget").optional(), "flight_start": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "flight_end": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "payment_terms": z.enum(["net_30","net_60","net_90","prepaid","due_on_receipt"]).describe("Payment terms").optional() }).catchall(z.any()).describe("Summary fields echoed from the committed proposal for agent verification. Buyer agents use these to confirm the IO matches what was negotiated before a human signs. These are read-only summaries, not negotiation surfaces — deal terms live on products and packages.").optional(), "terms_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL to a human-readable document containing the full insertion order terms").optional(), "signing_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL to an electronic signing service (e.g., DocuSign) for human signature workflows. When present, a human must sign before the buyer agent can proceed with create_media_buy.").optional(), "requires_signature": z.boolean().describe("Whether the buyer must accept this IO before creating a media buy. When true, create_media_buy requires an io_acceptance referencing this io_id.") }).catchall(z.any()).describe("A signing wrapper attached to a committed proposal. The IO does not introduce new deal terms — all negotiated terms (performance standards, measurement terms, cancellation policy, pricing) live on the product and package. The IO exists for human signature workflows and provides summary fields so buyer agents can verify the IO matches the committed proposal before a human signs.").optional(), "total_budget_guidance": z.object({ "min": z.number().gte(0).optional(), "recommended": z.number().gte(0).optional(), "max": z.number().gte(0).optional(), "currency": z.string().regex(new RegExp("^[A-Z]{3}$")) }).passthrough().and(z.union([z.object({ "recommended": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "min": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "max": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("Optional budget guidance for this proposal — the planning answer to criteria.outcome_target and to open-budget briefs. commercial_terms.total_budget remains the concrete figure the plan is priced at; this band expresses the seller's recommended range around it.").optional(), "forecast": z.object({ "points": z.array(z.object({ "label": z.string().max(128).optional(), "budget": z.number().gte(0).optional(), "product_id": z.string().optional(), "dimensions": z.array(z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "kind": z.literal("geo").describe("Dimension family discriminator."), "geo_level": z.enum(["country","region","metro","postal_area"]).describe("Geographic level for this forecast point."), "system": z.string().describe("Classification system for metro or postal_area levels. Required when geo_level is 'metro' or 'postal_area'. Metro rows use metro-system enum values such as 'nielsen_dma'; native postal rows use country-local postal-system enum values such as 'zip' with country 'US'; deprecated legacy postal rows may use legacy-postal-system enum values such as 'us_zip'. Omit for country and region rows.").optional(), "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code. Required for native postal_area rows and omitted for legacy postal rows, metro rows, country rows, and region rows.").optional(), "geo_code": z.string().describe("Geographic code within the level and system. Country: ISO 3166-1 alpha-2 ('US'). Region: ISO 3166-2 with country prefix ('US-CA'). Metro/postal: system-specific code ('501', '10001')."), "geo_name": z.string().describe("Human-readable geographic name (e.g., 'United States', 'California', 'New York DMA').").optional() }).passthrough().and(z.intersection(z.intersection(z.union([z.any().refine((value) => !z.object({ "geo_level": z.literal("country") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "geo_level": z.literal("country") }), z.object({ "geo_code": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code.").optional() }))]), z.union([z.any().refine((value) => !z.object({ "geo_level": z.literal("region") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "geo_level": z.literal("region") }), z.object({ "geo_code": z.string().regex(new RegExp("^[A-Z]{2}-[A-Z0-9]{1,3}$")).describe("ISO 3166-2 subdivision code.").optional() }))])), z.intersection(z.union([z.any().refine((value) => !z.object({ "geo_level": z.literal("metro") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "geo_level": z.literal("metro") }), z.object({ "system": z.enum(["nielsen_dma","uk_itl1","uk_itl2","eurostat_nuts2","custom"]).describe("Metro area classification system (e.g., 'nielsen_dma', 'uk_itl2')") }))]), z.union([z.any().refine((value) => !z.object({ "geo_level": z.literal("postal_area") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "geo_level": z.literal("postal_area") }), z.union([z.object({ "country": z.string().regex(new RegExp("^[A-Z]{2}$")).describe("ISO 3166-1 alpha-2 country code."), "system": z.enum(["postal_code","zip","zip_plus_four","outward","full","fsa","plz","code_postal","postcode","cep","pin","custom","us_zip","us_zip_plus_four","gb_outward","gb_full","ca_fsa","ca_full","de_plz","fr_code_postal","au_postcode","ch_plz","at_plz"]).describe("Country-local postal code system.") }).and(z.union([z.object({ "country": z.literal("US").optional(), "system": z.enum(["zip","zip_plus_four"]).optional() }), z.object({ "country": z.literal("GB").optional(), "system": z.enum(["outward","full"]).optional() }), z.object({ "country": z.literal("CA").optional(), "system": z.enum(["fsa","full"]).optional() }), z.object({ "country": z.enum(["DE","CH","AT"]).optional(), "system": z.literal("plz").optional() }), z.object({ "country": z.literal("FR").optional(), "system": z.literal("code_postal").optional() }), z.object({ "country": z.literal("AU").optional(), "system": z.literal("postcode").optional() }), z.object({ "country": z.literal("BR").optional(), "system": z.literal("cep").optional() }), z.object({ "country": z.literal("IN").optional(), "system": z.literal("pin").optional() }), z.object({ "country": z.literal("ZA").optional(), "system": z.literal("postal_code").optional() }), z.object({ "country": z.any().refine((value) => !z.enum(["US","GB","CA","DE","CH","AT","FR","AU","BR","IN","ZA"]).safeParse(value).success, "Invalid input: Should NOT be valid against schema").optional(), "system": z.enum(["postal_code","custom"]).optional() })])).describe("Valid country-local postal system pairing. Registered countries only accept their registered local systems; countries without a registered local system use postal_code or custom."), z.object({ "system": z.enum(["us_zip","us_zip_plus_four","gb_outward","gb_full","ca_fsa","ca_full","de_plz","fr_code_postal","au_postcode","ch_plz","at_plz"]).describe("Deprecated country-fused postal code system (e.g., 'us_zip', 'gb_outward'). Prefer country + postal-system.") })]))])))).describe("A geographic dimension for a ForecastPoint row. Variant of ForecastPoint dimensions; see forecast-point-dimensions.json for dispatch rules."), z.object({ "kind": z.literal("placement").describe("Dimension family discriminator."), "placement_ref": z.object({ "publisher_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain where the adagents.json declaring a publisher-catalog placement is hosted, or the inventory publisher associated with an inline placement. Omitted only for legacy single-publisher product-context references.").optional(), "placement_id": z.string().describe("Placement ID from the publisher's adagents.json placement catalog, or an inline seller-defined placement ID interpreted within the enclosing seller and product context.") }).catchall(z.any()).describe("Structured placement reference for this forecast row. References an entry from the product's placements array."), "placement_name": z.string().describe("Human-readable placement name, useful when the buyer has not resolved the placement catalog.").optional() }).passthrough().describe("A placement dimension for a ForecastPoint row. Variant of ForecastPoint dimensions; see forecast-point-dimensions.json for dispatch rules."), z.object({ "kind": z.literal("device_type").describe("Dimension family discriminator."), "device_type": z.enum(["desktop","mobile","tablet","ctv","dooh","unknown"]).describe("Device form factor categories for targeting and reporting. Complements device-platform (operating system) with hardware classification. OpenRTB mapping: 1 (Mobile/Tablet General) → mobile, 2 (PC) → desktop, 4 (Phone) → mobile, 5 (Tablet) → tablet, 6 (Connected Device) → ctv, 7 (Set Top Box) → ctv. DOOH inventory uses dooh.") }).passthrough().describe("A device form-factor dimension for a ForecastPoint row. Variant of ForecastPoint dimensions; see forecast-point-dimensions.json for dispatch rules."), z.object({ "kind": z.literal("device_platform").describe("Dimension family discriminator."), "device_platform": z.enum(["ios","android","windows","macos","linux","chromeos","tvos","tizen","webos","fire_os","roku_os","unknown"]).describe("Operating system platforms for device targeting. Browser values from Sec-CH-UA-Platform standard, extended for CTV.") }).passthrough().describe("An operating-system or platform dimension for a ForecastPoint row. Variant of ForecastPoint dimensions; see forecast-point-dimensions.json for dispatch rules."), z.object({ "kind": z.literal("audience").describe("Dimension family discriminator."), "audience_id": z.string().describe("Audience segment identifier for this forecast row."), "audience_source": z.enum(["synced","platform","third_party","lookalike","retargeting","unknown"]).describe("Origin of the audience segment."), "audience_name": z.string().describe("Human-readable audience segment name.").optional() }).passthrough().describe("An audience segment dimension for a ForecastPoint row. Variant of ForecastPoint dimensions; see forecast-point-dimensions.json for dispatch rules."), z.object({ "kind": z.literal("signal").describe("Dimension family discriminator."), "signal_ref": z.any().superRefine((x, ctx) => { - const schemas = [z.object({ "scope": z.literal("product").describe("Discriminator indicating the signal resolves through the selected product's included_signals or signal_targeting_options."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Product-local signal identifier. For local signals exposed on both get_signals and get_products, this MUST match get_signals.signals[].signal_ref.signal_id for the same signal.") }).catchall(z.any()).describe("Product-scoped signal. The signal_id is meaningful only within the selected product/package context and MUST match a Product.included_signals[].signal_ref.signal_id or Product.signal_targeting_options[].signal_ref.signal_id for that product, depending on whether the signal is descriptive or selectable."), z.object({ "scope": z.literal("data_provider").describe("Discriminator indicating the signal resolves through a data provider's published adagents.json signals[]."), "data_provider_domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that publishes the signal definition in its adagents.json signals[]."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the data provider's published adagents.json signals[].") }).catchall(z.any()).describe("Data-provider-scoped signal. The signal_id resolves through the data provider's published adagents.json signals[] and can be authorization-verified there."), z.object({ "scope": z.literal("signal_source").describe("Discriminator indicating the signal resolves through the issuing signal source."), "signal_source_url": z.string().refine(adcpJsonSchemaUri, "Invalid URI").describe("URL of the signal source that issues this source-native signal."), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier within the issuing signal source's signal set.") }).catchall(z.any()).describe("Signal-source-scoped signal. Use this for source-native signals that are not published in upstream adagents.json signals[]. The buyer trusts the issuing signal source for this identity; use scope 'data_provider' instead when the signal is published in adagents.json signals[], even if the publisher is also the seller or signal source.")]; - const { errors, failed } = schemas.reduce<{ - errors: z.core.$ZodIssue[]; - failed: number; - }>( - ({ errors, failed }, schema) => - ((result) => - result.error - ? { - errors: [...errors, ...result.error.issues], - failed: failed + 1, - } - : { errors, failed })( - schema.safeParse(x), - ), - { errors: [], failed: 0 }, - ); - const passed = schemas.length - failed; - if (passed !== 1) { - ctx.addIssue(errors.length ? { - path: [], - code: "invalid_union", - errors: [errors], - message: "Invalid input: Should pass single schema. Passed " + passed, - } : { - path: [], - code: "custom", - errors: [errors], - message: "Invalid input: Should pass single schema. Passed " + passed, - }); + })).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Dimension constraints represented by a ForecastPoint. Use this when one product, proposal, or signal coverage forecast needs to expose availability or forecasted delivery by country, region, placement, device, audience, signal value, time window, or intersections such as placement x country without creating separate products solely for each slice. Each item declares one dimension family via `kind`; when multiple items are present, the point represents their intersection. Sellers MUST NOT emit more than one item for each `kind` in a point. Consumers MUST NOT treat repeated kinds as OR semantics; repeated peer values such as two countries are a seller conformance issue. Dimension values are descriptors of the forecast row and are independent of pricing_options.").optional(), "availability_status": z.enum(["available","unavailable"]).describe("Bookability of the inventory a forecast row describes, as of the forecast's generated_at. A snapshot, never a hold: valid_until bounds freshness, and proposal finalization or purchase remains the commitment boundary.").optional(), "metrics": z.object({ "coverage_rate": z.intersection(z.object({ "low": z.number().gte(0).describe("Conservative (low-end) forecast value").optional(), "mid": z.number().gte(0).describe("Expected (most likely) forecast value").optional(), "high": z.number().gte(0).describe("Optimistic (high-end) forecast value").optional() }).catchall(z.any()).and(z.union([z.object({ "mid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "low": z.any().refine((value) => value !== undefined, "Required"), "high": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A forecast value with optional confidence bounds. Either mid (point estimate) or both low and high (range) must be provided. mid represents the most likely outcome. low and high represent conservative and optimistic estimates. All three can be provided together."), z.object({ "low": z.any().optional(), "mid": z.any().optional(), "high": z.any().optional() })).describe("A forecast range whose low, midpoint, and high values are rates in the inclusive interval from 0 to 1.").optional() }).catchall(z.object({ "low": z.number().gte(0).describe("Conservative (low-end) forecast value").optional(), "mid": z.number().gte(0).describe("Expected (most likely) forecast value").optional(), "high": z.number().gte(0).describe("Optimistic (high-end) forecast value").optional() }).catchall(z.any()).and(z.union([z.object({ "mid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "low": z.any().refine((value) => value !== undefined, "Required"), "high": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A forecast value with optional confidence bounds. Either mid (point estimate) or both low and high (range) must be provided. mid represents the most likely outcome. low and high represent conservative and optimistic estimates. All three can be provided together.")), "viewability": z.object({ "vendor": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery.").optional(), "measurable_impressions": z.object({ "low": z.number().gte(0).describe("Conservative (low-end) forecast value").optional(), "mid": z.number().gte(0).describe("Expected (most likely) forecast value").optional(), "high": z.number().gte(0).describe("Optimistic (high-end) forecast value").optional() }).catchall(z.any()).and(z.union([z.object({ "mid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "low": z.any().refine((value) => value !== undefined, "Required"), "high": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A forecast value with optional confidence bounds. Either mid (point estimate) or both low and high (range) must be provided. mid represents the most likely outcome. low and high represent conservative and optimistic estimates. All three can be provided together.").optional(), "viewable_impressions": z.object({ "low": z.number().gte(0).describe("Conservative (low-end) forecast value").optional(), "mid": z.number().gte(0).describe("Expected (most likely) forecast value").optional(), "high": z.number().gte(0).describe("Optimistic (high-end) forecast value").optional() }).catchall(z.any()).and(z.union([z.object({ "mid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "low": z.any().refine((value) => value !== undefined, "Required"), "high": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A forecast value with optional confidence bounds. Either mid (point estimate) or both low and high (range) must be provided. mid represents the most likely outcome. low and high represent conservative and optimistic estimates. All three can be provided together.").optional(), "viewable_rate": z.intersection(z.object({ "low": z.number().gte(0).describe("Conservative (low-end) forecast value").optional(), "mid": z.number().gte(0).describe("Expected (most likely) forecast value").optional(), "high": z.number().gte(0).describe("Optimistic (high-end) forecast value").optional() }).catchall(z.any()).and(z.union([z.object({ "mid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "low": z.any().refine((value) => value !== undefined, "Required"), "high": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A forecast value with optional confidence bounds. Either mid (point estimate) or both low and high (range) must be provided. mid represents the most likely outcome. low and high represent conservative and optimistic estimates. All three can be provided together."), z.object({ "low": z.any().optional(), "mid": z.any().optional(), "high": z.any().optional() })).describe("A forecast range whose low, midpoint, and high values are rates in the inclusive interval from 0 to 1.").optional(), "viewed_seconds": z.object({ "low": z.number().gte(0).describe("Conservative (low-end) forecast value").optional(), "mid": z.number().gte(0).describe("Expected (most likely) forecast value").optional(), "high": z.number().gte(0).describe("Optimistic (high-end) forecast value").optional() }).catchall(z.any()).and(z.union([z.object({ "mid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "low": z.any().refine((value) => value !== undefined, "Required"), "high": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A forecast value with optional confidence bounds. Either mid (point estimate) or both low and high (range) must be provided. mid represents the most likely outcome. low and high represent conservative and optimistic estimates. All three can be provided together.").optional(), "standard": z.enum(["mrc","groupm"]).describe("Viewability measurement standard applied to determine whether an impression qualifies as viewable. These are materially different thresholds and should not be compared across standards.").optional() }).passthrough().and(z.union([z.any().refine((value) => !z.union([z.object({ "measurable_impressions": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "viewable_impressions": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "viewable_rate": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "viewed_seconds": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.object({ "standard": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).optional(), "vendor_metric_values": z.array(z.object({ "vendor": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery."), "metric_id": z.string().regex(new RegExp("^[a-z][a-z0-9_]*$")).min(1).max(64).describe("Identifier for a vendor-defined metric within the vendor's vocabulary. Stable lookup key; the vendor publishes the canonical list (with category, methodology, and standard alignment) in `brand.json` `agents[type='measurement']`. Lowercase with underscores so a future enum promotion into `available-metric.json` is a literal string lift. Identifier is namespaced by the vendor — the same `metric_id` may mean different things in different vendors' vocabularies."), "value": z.object({ "low": z.number().gte(0).describe("Conservative (low-end) forecast value").optional(), "mid": z.number().gte(0).describe("Expected (most likely) forecast value").optional(), "high": z.number().gte(0).describe("Optimistic (high-end) forecast value").optional() }).catchall(z.any()).and(z.union([z.object({ "mid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "low": z.any().refine((value) => value !== undefined, "Required"), "high": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A forecast value with optional confidence bounds. Either mid (point estimate) or both low and high (range) must be provided. mid represents the most likely outcome. low and high represent conservative and optimistic estimates. All three can be provided together."), "unit": z.string().optional(), "measurable_impressions": z.object({ "low": z.number().gte(0).describe("Conservative (low-end) forecast value").optional(), "mid": z.number().gte(0).describe("Expected (most likely) forecast value").optional(), "high": z.number().gte(0).describe("Optimistic (high-end) forecast value").optional() }).catchall(z.any()).and(z.union([z.object({ "mid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "low": z.any().refine((value) => value !== undefined, "Required"), "high": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A forecast value with optional confidence bounds. Either mid (point estimate) or both low and high (range) must be provided. mid represents the most likely outcome. low and high represent conservative and optimistic estimates. All three can be provided together.").optional(), "breakdown": z.record(z.string(), z.any()).optional() }).passthrough().describe("Compact forecasted vendor metric with a BrandKey vendor pointer and no embedded brand assets.")).optional() }).passthrough().describe("Compact forecast row with numeric ranges and identity-only measurement-vendor references.")).min(1), "forecast_range_unit": z.enum(["spend","availability","reach_freq","weekly","daily","clicks","conversions","package"]).describe("Describes how to interpret the points array in a DeliveryForecast — what axis the curve represents").optional(), "method": z.enum(["estimate","modeled","guaranteed"]).describe("Method used to produce a delivery forecast"), "currency": z.string().regex(new RegExp("^[A-Z]{3}$")), "demographic_system": z.enum(["nielsen","nielsen_audio","barb","agf","oztam","mediametrie","custom"]).describe("Audience measurement systems for demographic notation in GRP forecasts and pricing, across video and audio channels. Specifies how demographics are written, not whose panel produced the numbers — provider identity is measurement_source.").optional(), "demographic": z.string().optional(), "measurement_source": z.string().regex(new RegExp("^[a-z0-9_]+$")).max(64).optional(), "reach_unit": z.enum(["individuals","households","devices","accounts","cookies","custom"]).describe("Unit of measurement for reach and audience size metrics. Different channels and measurement providers count reach in fundamentally different units, making cross-channel comparison impossible without declaring the unit.").optional(), "generated_at": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "valid_until": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough().describe("Compact product forecast without legacy BrandRef or creative dependencies.").describe("Aggregate forecasted delivery for the proposal. For outcome_target requests, points carry the goal's metric or event key in metrics.").optional() }).passthrough().describe("Compact immutable proposal for the AdCP 3.2 lifecycle. commercial_terms is the sole authoritative commercial envelope; narrative fields do not duplicate legacy allocation or creative graphs."); + const exactSchema = objectSchema.superRefine((value, ctx) => { + const checked = z.intersection(z.intersection(z.union([z.any().refine((value) => !z.object({ "proposal_kind": z.enum(["media_buy_update","media_buy_cancellation"]) }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "proposal_kind": z.enum(["media_buy_update","media_buy_cancellation"]) }), z.object({ "parent_proposal_id": z.any().refine((value) => value !== undefined, "Required"), "media_buy_id": z.any().refine((value) => value !== undefined, "Required"), "base_media_buy_revision": z.any().refine((value) => value !== undefined, "Required") }).passthrough())]), z.union([z.any().refine((value) => !z.object({ "proposal_status": z.literal("accepted") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "proposal_status": z.literal("accepted") }), z.object({ "media_buy_id": z.any().refine((value) => value !== undefined, "Required"), "accepted_at": z.any().refine((value) => value !== undefined, "Required") }).passthrough())])), z.intersection(z.union([z.any().refine((value) => !z.object({ "proposal_status": z.literal("committed") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "proposal_status": z.literal("committed") }), z.object({ "expires_at": z.any().refine((value) => value !== undefined, "Required") }).passthrough())]), z.union([z.any().refine((value) => !z.object({ "proposal_kind": z.literal("media_buy_cancellation") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "proposal_kind": z.literal("media_buy_cancellation") }), z.object({ "commercial_terms": z.object({ "cancellation_terms": z.any().refine((value) => value !== undefined, "Required") }).passthrough().optional() }))]))).safeParse(value); + if (!checked.success) { + for (const issue of checked.error.issues) { + ctx.addIssue({ code: "custom", path: issue.path, message: issue.message }); + } + } + }); + return Object.assign(exactSchema, { + pick: objectSchema.pick.bind(objectSchema), + omit: objectSchema.omit.bind(objectSchema), + extend: objectSchema.extend.bind(objectSchema), + }); + })(); + +export const CanonicalProductSchema = z.object({}).passthrough().merge(z.object({ + product_id: z.string().min(1), + name: z.string().min(1), + description: z.string().optional(), + publisher_properties: z.array(PublisherPropertySelectorSchema.and(z.object({}).passthrough())).optional(), + channels: z.array(MediaChannelSchema).optional(), + video_placement_types: z.array(VideoPlacementTypeSchema).optional(), + audio_distribution_types: z.array(AudioDistributionTypeSchema).optional(), + sponsored_placement_types: z.array(SponsoredPlacementTypeSchema).optional(), + social_placement_surfaces: z.array(SocialPlacementSurfaceSchema).optional(), + format_options: z.array(CanonicalFormatOptionSchema).optional(), + placements: z.array(CanonicalProductPlacementSchema).optional(), + delivery_type: DeliveryTypeSchema.optional(), + exclusivity: ExclusivitySchema.optional(), + pricing_options: z.array(CanonicalPricingOptionSchema).optional(), + forecast: CanonicalDeliveryForecastSchema.optional(), + reporting_capabilities: CanonicalReportingCapabilitiesSchema.optional(), + measurement_terms: CanonicalMeasurementTermsSchema.optional(), + performance_standards: z.array(CanonicalPerformanceStandardSchema).optional(), + catalog_types: z.array(CatalogTypeSchema).optional(), + signal_targeting_allowed: z.boolean().optional(), + signal_targeting_rules: SignalTargetingRulesSchema.optional(), + demographic_targeting: DemographicTargetingCapabilitySchema.optional(), + overlay_support: TargetingOverlaySupportSchema.optional(), + media_buy_support: ProductMediaBuySupportSchema.optional(), + identity: ProductIdentitySchema.optional(), + audience_evidence: z.array(CanonicalAudienceEvidenceSchema).optional(), + audience_evidence_selections: z.array(CanonicalAudienceEvidenceSelectionSchema).optional(), + max_optimization_goals: z.number().int().gte(0).optional(), + catalog_match: z.object({ + matched_gtins: z.array(z.string()).optional(), + matched_ids: z.array(z.string()).optional(), + matched_count: z.number().int().gte(0).optional(), + submitted_count: z.number().int().gte(0) + }).passthrough().optional(), + list_applications: z.array(InventoryListApplicationSchema).optional(), + brief_relevance: z.string().optional(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + allowed_actions: z.array(CanonicalProductActionSchema).optional(), + acceptance_policy_profile_ids: AcceptancePolicyProfileIDsSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough()); + +export const BuyProductsRequestSchema = z.object({ + adcp_version: z.string().optional(), + adcp_major_version: z.number().optional(), + idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/), + account: CanonicalAccountReferenceSchema, + brand: BrandKeySchema.optional(), + advertiser_industry: AdvertiserIndustrySchema.optional(), + feed_version: z.string().min(1), + pricing_version: z.string().min(1).optional(), + purchases: z.array(ProductPurchaseInputSchema), + total_budget: z.object({ + amount: z.number().min(0), + currency: z.string().regex(/^[A-Z]{3}$/) + }).passthrough().optional(), + daily_budget_cap: z.number().min(0).optional(), + frequency_cap: MediaBuyFrequencyCapSchema.optional(), + budget_cap_timezone: z.string().min(1).optional(), + budget_allocation: CanonicalBudgetAllocationSchema.optional(), + start_time: StartTimingSchema, + end_time: z.iso.datetime(), + pacing: PacingSchema.optional(), + bidding: BiddingPolicySchema.optional(), + paused: z.boolean().optional(), + purchase_order_ref: z.string().min(1).max(255).optional(), + agency_estimate_number: z.string().max(100).optional(), + invoice_recipient: BusinessEntitySchema.optional(), + governance_context: z.string().min(1).max(4096).optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + reporting_webhook: ReportingWebhookSchema.optional(), + opportunity: OpportunityContextSchema.and(z.object({ + status: z.literal("closed").optional() + }).passthrough()).optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const CommittedMediaBuySchema = z.object({ + status: z.literal("completed"), + media_buy_id: z.string(), + revision: z.number(), + media_buy_status: MediaBuyStatusSchema.optional(), + confirmed_at: z.string().optional().nullable(), + accepted_proposal: CanonicalProposalSchema.and(z.object({ + proposal_status: z.literal("accepted"), + media_buy_id: z.string() + }).passthrough()), + purchase_bindings: z.array(z.object({ + purchase_index: z.number(), + product_id: z.string(), + package_id: z.string() + }).passthrough()), + available_actions: z.array(CanonicalMediaBuyActionSchema), + warnings: z.array(WarningSchema.and(z.object({ + code: z.union([z.literal("inventory_shortfall_forecast"), z.literal("flight_change_creates_pacing_risk")]).optional() + }).passthrough())).optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional(), + replayed: z.literal(true).optional() +}).passthrough(); + +export const MediaBuyCommitmentResponseSchema = z.union([CommittedMediaBuySchema, CommitmentErrorSchema, CommitmentSubmittedSchema]); + +export const PackageControlSchema = z.object({}).passthrough().merge(z.object({ + package_id: z.string().min(1), + budget: z.number().gte(0).optional().nullable(), + daily_budget_cap: z.number().gte(0).optional().nullable(), + min_spend_target: z.number().gte(0).optional().nullable(), + impressions: z.number().gte(0).optional(), + pacing: PacingSchema.optional(), + bidding: BiddingPolicySchema.optional().nullable(), + paused: z.boolean().optional(), + canceled: z.literal(true).optional(), + cancellation_reason: z.string().min(1).max(500).optional(), + targeting_overlay: TargetingOverlayInputSchema.optional(), + catalog_ids: z.array(z.string()).optional(), + keyword_targets_add: z.array(KeywordTargetSchema).optional(), + keyword_targets_remove: z.array(KeywordTargetSchema).optional(), + negative_keywords_add: z.array(KeywordTargetSchema).optional(), + negative_keywords_remove: z.array(KeywordTargetSchema).optional(), + optimization_goals: z.array(CanonicalOptimizationGoalSchema).optional() +}).passthrough()); + +export const ControlMediaBuyRequestSchema = z.object({ + adcp_version: z.string().optional(), + adcp_major_version: z.number().optional(), + idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/), + account: CanonicalAccountReferenceSchema, + media_buy_id: z.string().min(1), + revision: z.int().min(1), + name: z.string().min(1).max(255).regex(/\S/).optional(), + paused: z.boolean().optional(), + canceled: z.literal(true).optional(), + cancellation_reason: z.string().min(1).max(500).optional(), + total_budget: z.object({ + amount: z.number().min(0), + currency: z.string().regex(/^[A-Z]{3}$/) + }).passthrough().optional(), + daily_budget_cap: z.number().min(0).optional().nullable(), + frequency_cap: MediaBuyFrequencyCapSchema.optional().nullable(), + budget_cap_timezone: z.string().min(1).optional().nullable(), + budget_allocation: CanonicalBudgetAllocationSchema.optional(), + pacing: PacingSchema.optional(), + bidding: BiddingPolicySchema.optional().nullable(), + packages: z.array(PackageControlSchema).optional(), + reporting_webhook: ReportingWebhookSchema.optional(), + governance_context: z.string().min(1).max(4096).optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. +export const ListCreativeFormatsResponseSchema: z.ZodObject<{ [K in keyof ListCreativeFormatsResponse]-?: undefined extends ListCreativeFormatsResponse[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, ListCreativeFormatsResponse & Record> = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + formats: z.array(FormatSchema), + source: z.union([z.literal("publisher"), z.literal("aao_mirror"), z.literal("agent_derived")]).optional(), + creative_agents: z.array(z.object({ + agent_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI"), + agent_name: z.string().optional(), + capabilities: z.array(CreativeAgentCapabilitySchema).optional() + }).passthrough()).optional(), + errors: z.array(ErrorSchema).optional(), + pagination: PaginationResponseSchema.optional(), + sandbox: z.boolean().optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const CreativeAssetSchema = z.object({}).passthrough().merge(z.object({ + creative_id: z.string(), + name: z.string(), + format_id: FormatReferenceStructuredObjectSchema.optional(), + format_kind: CanonicalFormatKindSchema.optional(), + format_option_ref: FormatOptionReferenceSchema.optional(), + representation_selection: RepresentationSelectionSchema.optional(), + assets: CreativeAssetsRuntimeSchema, + component_assets: z.record(z.string(), CreativeAssetsSchema).optional(), + inputs: z.array(z.object({ + name: z.string(), + macros: z.record(z.string(), z.string()).optional(), + context_description: z.string().optional() + }).passthrough()).optional(), + tags: z.array(z.string()).optional(), + status: CreativeStatusSchema.optional(), + weight: z.number().gte(0).lte(100).optional(), + placement_refs: z.array(PlacementReferenceSchema).optional(), + placement_ids: z.array(z.string()).optional(), + industry_identifiers: z.array(IndustryIdentifierSchema).optional(), + provenance: ProvenanceSchema.optional(), + rights: z.array(RightsConstraintSchema).optional() +}).passthrough()).superRefine((value, ctx) => { + const hasFormatId = value.format_id !== undefined; + const hasFormatKind = value.format_kind !== undefined; + if (hasFormatId === hasFormatKind) { + ctx.addIssue({ + code: "custom", + path: [], + message: "creative identity requires exactly one of format_id or format_kind" + }); + } + if ("capability_id" in value || "capability_ref" in value) { + ctx.addIssue({ + code: "custom", + path: [], + message: "creative identity does not allow capability_id or capability_ref" + }); } - }).describe("Canonical signal reference for this forecast row. Required when the row needs to disambiguate product-local, data-provider, or signal-source identity. Product-relative forecasts SHOULD use signal_ref.").optional(), "signal_id": z.string().regex(new RegExp("^[a-zA-Z0-9_-]+$")).describe("Signal identifier shorthand for this forecast row. Use only when the enclosing context already identifies the signal unambiguously, such as a coverage_forecast nested directly under one get_signals signal item. Otherwise use signal_ref.").optional(), "signal_value": z.union([z.string().describe("Signal value bucket represented by this point. Use null with presence 'absent' to represent inventory where the signal is not present. Omit when the row describes any present value rather than one specific value."), z.number().describe("Signal value bucket represented by this point. Use null with presence 'absent' to represent inventory where the signal is not present. Omit when the row describes any present value rather than one specific value."), z.boolean().describe("Signal value bucket represented by this point. Use null with presence 'absent' to represent inventory where the signal is not present. Omit when the row describes any present value rather than one specific value."), z.null().describe("Signal value bucket represented by this point. Use null with presence 'absent' to represent inventory where the signal is not present. Omit when the row describes any present value rather than one specific value.")]).describe("Signal value bucket represented by this point. Use null with presence 'absent' to represent inventory where the signal is not present. Omit when the row describes any present value rather than one specific value.").optional(), "presence": z.enum(["present","absent"]).describe("Whether the signal is present for this point. Use 'absent' for the explicit not-present bucket."), "signal_name": z.string().describe("Human-readable signal name, useful when the buyer has not resolved the signal definition.").optional(), "signal_value_name": z.string().describe("Human-readable label for the signal value bucket.").optional() }).passthrough().and(z.union([z.object({ "signal_ref": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "signal_id": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).and(z.intersection(z.union([z.any().refine((value) => !z.object({ "presence": z.literal("absent") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "presence": z.literal("absent") }), z.object({ "signal_value": z.null() }))]), z.union([z.any().refine((value) => !z.object({ "presence": z.literal("present") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "presence": z.literal("present") }), z.object({ "signal_value": z.union([z.string(), z.number(), z.boolean()]).optional() }))]))).describe("A signal value or signal-presence dimension for a ForecastPoint row. Variant of ForecastPoint dimensions; see forecast-point-dimensions.json for dispatch rules."), z.object({ "kind": z.literal("time").describe("Dimension family discriminator."), "start_time": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time"), "end_time": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time") }).passthrough().describe("A calendar-window dimension for a ForecastPoint row. Variant of ForecastPoint dimensions; see forecast-point-dimensions.json for dispatch rules. Windows are half-open intervals [start_time, end_time): the row covers instants at or after start_time and strictly before end_time, so adjacent windows share a boundary without overlapping. end_time MUST be after start_time; JSON Schema draft-07 cannot compare sibling values, so conformance tooling enforces the ordering. Within one forecast, sellers MUST emit non-overlapping windows and SHOULD coalesce adjacent windows whose availability_status and metrics do not materially differ. When the request scoped the forecast with offer_filters.availability_horizon, a complete forecast partitions the requested horizon; a seller that cannot cover the full horizon signals the gap through the response's incomplete[] mechanism rather than silently omitting windows.")]; - const { errors, failed } = schemas.reduce<{ - errors: z.core.$ZodIssue[]; - failed: number; - }>( - ({ errors, failed }, schema) => - ((result) => - result.error - ? { - errors: [...errors, ...result.error.issues], - failed: failed + 1, - } - : { errors, failed })( - schema.safeParse(x), - ), - { errors: [], failed: 0 }, - ); - const passed = schemas.length - failed; - if (passed !== 1) { - ctx.addIssue(errors.length ? { - path: [], - code: "invalid_union", - errors: [errors], - message: "Invalid input: Should pass single schema. Passed " + passed, - } : { - path: [], - code: "custom", - errors: [errors], - message: "Invalid input: Should pass single schema. Passed " + passed, +}); + +// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. +export const PackageRequestSchema: z.ZodObject<{ [K in keyof PackageRequest]-?: undefined extends PackageRequest[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, PackageRequest & Record> = AdCPVersionEnvelopeSchema.merge(z.object({}).passthrough()).merge(z.object({ + product_id: z.string(), + format_ids: z.array(FormatReferenceStructuredObjectSchema).optional(), + format_option_refs: z.array(FormatOptionReferenceSchema).optional(), + format_kind: CanonicalFormatKindSchema.optional(), + params: z.object({}).passthrough().optional(), + budget: z.number().gte(0).optional(), + min_spend_target: z.number().gte(0).optional(), + pacing: PacingSchema.optional(), + pricing_option_id: z.string(), + bid_price: z.number().gte(0).optional(), + bidding: BiddingPolicySchema.optional(), + impressions: z.number().gte(0).optional(), + daily_budget_cap: z.number().gte(0).optional(), + start_time: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + end_time: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + paused: z.boolean().optional(), + catalogs: z.array(CatalogSchema).optional(), + optimization_goals: z.array(OptimizationGoalSchema).optional(), + targeting_overlay: TargetingOverlayInputSchema.optional(), + audience_evidence_requirements: AudienceEvidenceRequirementsSchema.optional(), + audience_evidence_pins: z.array(AudienceEvidencePinSchema).optional(), + measurement_terms: MeasurementTermsSchema.optional(), + performance_standards: z.array(PerformanceStandardSchema).optional(), + committed_metrics: z.array(z.union([z.object({ + scope: z.literal("standard"), + metric_id: AvailableMetricSchema, + qualifier: z.object({ + viewability_standard: ViewabilityStandardSchema.optional(), + completion_source: CompletionSourceSchema.optional(), + attribution_methodology: AttributionMethodologySchema.optional(), + attribution_window: DurationSchema.optional(), + lift_dimension: LiftDimensionSchema.optional() + }).passthrough().optional() + }).passthrough(), z.object({ + scope: z.literal("vendor"), + vendor: BrandReferenceSchema, + metric_id: VendorMetricIDSchema, + methodology_version: z.string().optional(), + qualifier: z.object({ + viewability_standard: ViewabilityStandardSchema.optional(), + completion_source: CompletionSourceSchema.optional(), + attribution_methodology: AttributionMethodologySchema.optional(), + attribution_window: DurationSchema.optional(), + lift_dimension: LiftDimensionSchema.optional() + }).passthrough().optional() + }).passthrough()])).optional(), + creative_assignments: z.array(CreativeAssignmentSchema).optional(), + creatives: z.array(CreativeAssetSchema.and(z.object({}).passthrough())).max(100).optional(), + agency_estimate_number: z.string().max(100).optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough()); + +export const ReportingDeliveryConfigurationSchema = z.object({}).passthrough().merge(z.object({}).passthrough()).merge(z.object({}).passthrough()).merge(z.object({ + delivery_config_id: z.string().min(1).max(64).regex(new RegExp("^[A-Za-z0-9_.:-]{1,64}$")), + delivery_config_version: z.number().int().gte(1), + offering_id: z.string().min(1).max(128).regex(new RegExp("^[A-Za-z0-9_.:-]{1,128}$")), + active: z.boolean(), + feed_purpose: ReportingFeedPurposeSchema, + report_definition_id: z.string().min(1).max(255).regex(new RegExp("^[A-Za-z0-9_.:-]{1,255}$")), + reporting_profile: z.string().min(1).max(128).regex(new RegExp("^[A-Za-z0-9_.:-]{1,128}$")), + scope: z.object({ + all_media_buys: z.literal(true).optional(), + media_buy_ids: z.array(ReportingMediaBuyIDSchema).optional() + }).passthrough(), + coverage_requirement: z.union([z.literal("full"), z.literal("allow_partial")]), + required_finality: ReportingFinalitySchema, + reconciliation_mode: ReportingReconciliationModeSchema, + authoritative_party: z.union([z.literal("seller"), z.literal("consumer")]).optional(), + schedule: ReportingScheduleSchema, + method: ReportingDeliveryMethodSchema.optional(), + revocation_effective_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() +}).passthrough()); + +// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. +export const PackageSchema: z.ZodObject<{ [K in keyof Package]-?: undefined extends Package[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, Package & Record> = z.object({}).passthrough().merge(z.object({ + package_id: z.string(), + product_id: z.string().optional(), + audience_evidence_selections: z.array(AudienceEvidenceSelectionSchema).optional(), + budget: z.number().gte(0).optional(), + min_spend_target: z.number().gte(0).optional(), + daily_budget_cap: z.number().gte(0).optional(), + pacing: PacingSchema.optional(), + pricing_option_id: z.string().optional(), + bid_price: z.number().gte(0).optional(), + bidding: BiddingPolicySchema.optional(), + price_breakdown: PriceBreakdownSchema.optional(), + impressions: z.number().gte(0).optional(), + catalogs: z.array(CatalogSchema).optional(), + format_ids: z.array(FormatReferenceStructuredObjectSchema).optional(), + format_option_refs: z.array(FormatOptionReferenceSchema).optional(), + format_kind: CanonicalFormatKindSchema.optional(), + params: z.object({}).passthrough().optional(), + targeting_overlay: TargetingOverlaySchema.optional(), + targeting_resolution: PackageTargetingResolutionSchema.optional(), + measurement_terms: MeasurementTermsSchema.optional(), + performance_standards: z.array(PerformanceStandardSchema).optional(), + committed_metrics: z.array(CommittedMetricSchema).optional(), + creative_assignments: z.array(CreativeAssignmentSchema).optional(), + formats_to_provide: z.array(PackageFormatSnapshotSchema).optional(), + formats_pending: z.array(PackageFormatSnapshotSchema).optional(), + format_ids_to_provide: z.array(FormatReferenceStructuredObjectSchema).optional(), + format_ids_pending: z.array(FormatReferenceStructuredObjectSchema).optional(), + optimization_goals: z.array(OptimizationGoalSchema).optional(), + start_time: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + end_time: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + paused: z.boolean().optional(), + canceled: z.boolean().optional(), + cancellation: z.object({ + canceled_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time"), + canceled_by: CanceledBySchema, + reason: z.string().max(500).optional(), + acknowledged_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + agency_estimate_number: z.string().max(100).optional(), + creative_deadline: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough()); + +export const ReportingDeliveryConfigurationStateSchema = z.object({}).passthrough().merge(z.object({}).passthrough()).merge(z.object({}).passthrough()).merge(z.object({ + configuration: ReportingDeliveryConfigurationSchema, + state: ReportingDeliveryConfigurationLifecycleStateSchema, + destination_ref: z.string().min(1).max(255).optional(), + validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + current_coverage: ReportingCoverageSchema.optional(), + setup: z.object({ + action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), + message: z.string().min(1).max(2000), + url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + issues: z.array(ReportingStatusIssueSchema).optional() +}).passthrough()).merge(z.object({ + configuration: ReportingDeliveryConfigurationSchema, + state: ReportingDeliveryConfigurationLifecycleStateSchema, + destination_ref: z.string().min(1).max(255).optional(), + validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + current_coverage: ReportingCoverageSchema.optional(), + setup: z.object({ + action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), + message: z.string().min(1).max(2000), + url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + issues: z.array(ReportingStatusIssueSchema).optional() +}).passthrough()).merge(z.object({ + configuration: ReportingDeliveryConfigurationSchema, + state: ReportingDeliveryConfigurationLifecycleStateSchema, + destination_ref: z.string().min(1).max(255).optional(), + validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + current_coverage: ReportingCoverageSchema.optional(), + setup: z.object({ + action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), + message: z.string().min(1).max(2000), + url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + issues: z.array(ReportingStatusIssueSchema).optional() +}).passthrough()).merge(z.object({ + configuration: ReportingDeliveryConfigurationSchema, + state: ReportingDeliveryConfigurationLifecycleStateSchema, + destination_ref: z.string().min(1).max(255).optional(), + validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + current_coverage: ReportingCoverageSchema.optional(), + setup: z.object({ + action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), + message: z.string().min(1).max(2000), + url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + issues: z.array(ReportingStatusIssueSchema).optional() +}).passthrough()).merge(z.object({ + configuration: ReportingDeliveryConfigurationSchema, + state: ReportingDeliveryConfigurationLifecycleStateSchema, + destination_ref: z.string().min(1).max(255).optional(), + validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + current_coverage: ReportingCoverageSchema.optional(), + setup: z.object({ + action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), + message: z.string().min(1).max(2000), + url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + issues: z.array(ReportingStatusIssueSchema).optional() +}).passthrough()).merge(z.object({ + configuration: ReportingDeliveryConfigurationSchema, + state: ReportingDeliveryConfigurationLifecycleStateSchema, + destination_ref: z.string().min(1).max(255).optional(), + validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + current_coverage: ReportingCoverageSchema.optional(), + setup: z.object({ + action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), + message: z.string().min(1).max(2000), + url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + issues: z.array(ReportingStatusIssueSchema).optional() +}).passthrough()).merge(z.object({ + configuration: ReportingDeliveryConfigurationSchema, + state: ReportingDeliveryConfigurationLifecycleStateSchema, + destination_ref: z.string().min(1).max(255).optional(), + validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + current_coverage: ReportingCoverageSchema.optional(), + setup: z.object({ + action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), + message: z.string().min(1).max(2000), + url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + issues: z.array(ReportingStatusIssueSchema).optional() +}).passthrough()).merge(z.object({ + configuration: ReportingDeliveryConfigurationSchema, + state: ReportingDeliveryConfigurationLifecycleStateSchema, + destination_ref: z.string().min(1).max(255).optional(), + validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + current_coverage: ReportingCoverageSchema.optional(), + setup: z.object({ + action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), + message: z.string().min(1).max(2000), + url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + issues: z.array(ReportingStatusIssueSchema).optional() +}).passthrough()).merge(z.object({ + configuration: ReportingDeliveryConfigurationSchema, + state: ReportingDeliveryConfigurationLifecycleStateSchema, + destination_ref: z.string().min(1).max(255).optional(), + validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + current_coverage: ReportingCoverageSchema.optional(), + setup: z.object({ + action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), + message: z.string().min(1).max(2000), + url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + issues: z.array(ReportingStatusIssueSchema).optional() +}).passthrough()).merge(z.object({ + configuration: ReportingDeliveryConfigurationSchema, + state: ReportingDeliveryConfigurationLifecycleStateSchema, + destination_ref: z.string().min(1).max(255).optional(), + validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + current_coverage: ReportingCoverageSchema.optional(), + setup: z.object({ + action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), + message: z.string().min(1).max(2000), + url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + issues: z.array(ReportingStatusIssueSchema).optional() +}).passthrough()).merge(z.object({ + configuration: ReportingDeliveryConfigurationSchema, + state: ReportingDeliveryConfigurationLifecycleStateSchema, + destination_ref: z.string().min(1).max(255).optional(), + validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + current_coverage: ReportingCoverageSchema.optional(), + setup: z.object({ + action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), + message: z.string().min(1).max(2000), + url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + issues: z.array(ReportingStatusIssueSchema).optional() +}).passthrough()).merge(z.object({ + configuration: ReportingDeliveryConfigurationSchema, + state: ReportingDeliveryConfigurationLifecycleStateSchema, + destination_ref: z.string().min(1).max(255).optional(), + validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + current_coverage: ReportingCoverageSchema.optional(), + setup: z.object({ + action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), + message: z.string().min(1).max(2000), + url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + issues: z.array(ReportingStatusIssueSchema).optional() +}).passthrough()).merge(z.object({ + configuration: ReportingDeliveryConfigurationSchema, + state: ReportingDeliveryConfigurationLifecycleStateSchema, + destination_ref: z.string().min(1).max(255).optional(), + validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + current_coverage: ReportingCoverageSchema.optional(), + setup: z.object({ + action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), + message: z.string().min(1).max(2000), + url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + issues: z.array(ReportingStatusIssueSchema).optional() +}).passthrough()).merge(z.object({ + configuration: ReportingDeliveryConfigurationSchema, + state: ReportingDeliveryConfigurationLifecycleStateSchema, + destination_ref: z.string().min(1).max(255).optional(), + validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + current_coverage: ReportingCoverageSchema.optional(), + setup: z.object({ + action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), + message: z.string().min(1).max(2000), + url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + issues: z.array(ReportingStatusIssueSchema).optional() +}).passthrough()).merge(z.object({ + configuration: ReportingDeliveryConfigurationSchema, + state: ReportingDeliveryConfigurationLifecycleStateSchema, + destination_ref: z.string().min(1).max(255).optional(), + validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + current_coverage: ReportingCoverageSchema.optional(), + setup: z.object({ + action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), + message: z.string().min(1).max(2000), + url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + issues: z.array(ReportingStatusIssueSchema).optional() +}).passthrough()).merge(z.object({ + configuration: ReportingDeliveryConfigurationSchema, + state: ReportingDeliveryConfigurationLifecycleStateSchema, + destination_ref: z.string().min(1).max(255).optional(), + validated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + activated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + deactivated_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + publication_stopped_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + seller_managed_access_ends_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + current_coverage: ReportingCoverageSchema.optional(), + setup: z.object({ + action: z.union([z.literal("grant_access"), z.literal("activate_recipient"), z.literal("authorize_provider"), z.literal("repair_access")]), + message: z.string().min(1).max(2000), + url: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + issues: z.array(ReportingStatusIssueSchema).optional() +}).passthrough()); + +// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. +export const PackageUpdateSchema: z.ZodObject<{ [K in keyof PackageUpdate]-?: undefined extends PackageUpdate[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, PackageUpdate & Record> = z.object({ + package_id: z.string(), + budget: z.number().min(0).optional().nullable(), + min_spend_target: z.number().min(0).optional().nullable(), + pacing: PacingSchema.optional(), + bid_price: z.number().min(0).optional(), + bidding: BiddingPolicySchema.optional().nullable(), + impressions: z.number().min(0).optional(), + daily_budget_cap: z.number().min(0).optional().nullable(), + start_time: z.iso.datetime().optional(), + end_time: z.iso.datetime().optional(), + paused: z.boolean().optional(), + canceled: z.literal(true).optional(), + cancellation_reason: z.string().max(500).optional(), + catalogs: z.array(CatalogSchema).optional(), + optimization_goals: z.array(OptimizationGoalSchema).optional(), + targeting_overlay: TargetingOverlayInputSchema.optional(), + keyword_targets_add: z.array(z.object({ + keyword: z.string().min(1), + match_type: MatchTypeSchema, + bid_price: z.number().min(0).optional() + }).passthrough()).optional(), + keyword_targets_remove: z.array(z.object({ + keyword: z.string().min(1), + match_type: MatchTypeSchema + }).passthrough()).optional(), + negative_keywords_add: z.array(z.object({ + keyword: z.string().min(1), + match_type: MatchTypeSchema + }).passthrough()).optional(), + negative_keywords_remove: z.array(z.object({ + keyword: z.string().min(1), + match_type: MatchTypeSchema + }).passthrough()).optional(), + creative_assignments: z.array(CreativeAssignmentSchema).optional(), + creatives: z.array(CreativeAssetSchema).max(100).optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const UpdateMediaBuySuccessSchema: z.ZodType = z.object({ + media_buy_id: z.string(), + name: z.string().min(1).max(255).regex(/\S/).optional(), + media_buy_status: MediaBuyStatusSchema.optional(), + revision: z.int().min(1).optional(), + currency: z.string().regex(/^[A-Z]{3}$/).optional(), + total_budget: z.number().min(0).optional(), + daily_budget_cap: z.number().min(0).optional(), + frequency_cap: MediaBuyFrequencyCapSchema.optional(), + budget_cap_timezone: z.string().optional(), + budget_allocation: BudgetAllocationSchema.optional(), + pacing: PacingSchema.optional(), + bidding: BiddingPolicySchema.optional(), + implementation_date: z.iso.datetime().optional().nullable(), + invoice_recipient: BusinessEntitySchema.optional(), + affected_packages: z.array(PackageSchema).optional(), + valid_actions: z.array(MediaBuyValidActionSchema).optional(), + available_actions: z.array(MediaBuyAvailableActionSchema).optional(), + warnings: z.array(WarningSchema).optional(), + sandbox: z.boolean().optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const AccountSchema = z.object({ + account_id: z.string(), + name: z.string(), + advertiser: z.string().optional(), + billing_proxy: z.string().optional(), + status: AccountStatusSchema, + brand: BrandReferenceSchema.optional(), + operator: z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).optional(), + operator_unit: OperatorUnitSchema.optional(), + revision: z.number().int().gte(1).optional(), + identity_change: AccountIdentityChangeSchema.optional(), + currency: z.string().regex(new RegExp("^[A-Z]{3}$")).optional(), + timezone: z.string().min(1).optional(), + billing: BillingPartySchema.optional(), + billing_entity: BusinessEntitySchema.optional(), + destination_billing_entity: z.object({}).passthrough().optional(), + rate_card: z.string().optional(), + payment_terms: PaymentTermsSchema.optional(), + credit_limit: z.object({ + amount: z.number().gte(0), + currency: z.string().regex(new RegExp("^[A-Z]{3}$")) + }).passthrough().optional(), + setup: z.object({ + url: z.string().optional(), + message: z.string(), + expires_at: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional() + }).passthrough().optional(), + account_scope: AccountScopeSchema.optional(), + governance_agents: z.tuple([z.object({ + url: z.string() + }).passthrough()]).optional(), + reporting_bucket: z.object({ + protocol: CloudStorageProtocolSchema, + bucket: z.string().min(3).max(63).regex(new RegExp("^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$")), + prefix: z.string().max(512).regex(new RegExp("^[a-zA-Z0-9/_.-]+$")).optional(), + region: z.string().max(64).regex(new RegExp("^[a-z0-9-]+$")).optional(), + format: z.union([z.literal("jsonl"), z.literal("csv"), z.literal("parquet"), z.literal("avro"), z.literal("orc")]).optional(), + compression: z.union([z.literal("gzip"), z.literal("none")]).optional(), + file_retention_days: z.number().int().gte(1), + setup_instructions: z.string().regex(new RegExp("^https://")).refine(adcpJsonSchemaUri, "Invalid URI").optional() + }).passthrough().optional(), + sandbox: z.boolean().optional(), + notification_configs: z.array(NotificationConfigSchema).max(16).optional(), + reporting_delivery_configs: z.array(ReportingDeliveryConfigurationStateSchema).max(16).optional(), + webhook_activity: z.array(WebhookActivityRecordSchema).max(200).optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. +export const PackageStatusSchema: z.ZodObject<{ [K in keyof PackageStatus]-?: undefined extends PackageStatus[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, PackageStatus & Record> = z.object({ + package_id: z.string(), + product_id: z.string().optional(), + budget: z.number().min(0).optional(), + min_spend_target: z.number().min(0).optional(), + daily_budget_cap: z.number().min(0).optional(), + currency: z.string().regex(/^[A-Z]{3}$/).optional(), + bid_price: z.number().min(0).optional(), + bidding: BiddingPolicySchema.optional(), + optimization_goals: z.array(OptimizationGoalSchema).optional(), + format_ids: z.array(FormatReferenceStructuredObjectSchema).optional(), + format_option_refs: z.array(FormatOptionReferenceSchema).optional(), + format_kind: CanonicalFormatKindSchema.optional(), + params: z.object({}).passthrough().optional(), + impressions: z.number().min(0).optional(), + pacing: PacingSchema.optional(), + targeting_overlay: TargetingOverlaySchema.optional(), + targeting_resolution: PackageTargetingResolutionSchema.optional(), + start_time: z.iso.datetime().optional(), + end_time: z.iso.datetime().optional(), + paused: z.boolean().optional(), + canceled: z.boolean().optional(), + cancellation: z.object({ + canceled_at: z.iso.datetime(), + canceled_by: CanceledBySchema, + reason: z.string().max(500).optional() + }).passthrough().optional(), + creative_deadline: z.iso.datetime().optional(), + context: ContextObjectSchema.optional(), + creative_approvals: z.array(z.object({ + creative_id: z.string(), + approval_status: CreativeApprovalStatusSchema.optional(), + rejection_reason: z.string().optional(), + approval_scopes: z.array(ScopedCreativeApprovalSchema).optional(), + indicators: z.array(IndicatorSchema.and(z.object({ + type: z.union([z.literal("creative_fatigue"), z.literal("creative_quality_opportunity")]).optional() + }).passthrough())).optional(), + indicator_types_evaluated: z.array(IndicatorTypeSchema.and(z.union([z.literal("creative_fatigue"), z.literal("creative_quality_opportunity")]))).optional(), + indicators_as_of: z.iso.datetime().optional(), + indicators_evaluated_scope: z.array(IndicatorScopeSchema).optional() + }).passthrough()).optional(), + formats_to_provide: z.array(PackageFormatSnapshotSchema).optional(), + formats_pending: z.array(PackageFormatSnapshotSchema).optional(), + format_ids_to_provide: z.array(FormatReferenceStructuredObjectSchema).optional(), + format_ids_pending: z.array(FormatReferenceStructuredObjectSchema).optional(), + snapshot_unavailable_reason: SnapshotUnavailableReasonSchema.optional(), + snapshot: z.object({ + as_of: z.iso.datetime(), + staleness_seconds: z.int().min(0), + impressions: z.number().min(0), + spend: z.number().min(0), + currency: z.string().regex(/^[A-Z]{3}$/).optional(), + clicks: z.number().min(0).optional(), + pacing_index: z.number().min(0).optional(), + delivery_status: DeliveryStatusSchema.optional(), + ext: ExtensionObjectSchema.optional() + }).passthrough().optional(), + ext: ExtensionObjectSchema.optional(), + indicator_types_evaluated: z.array(z.union([z.literal("creative_diversity_low"), z.literal("audience_saturation"), z.literal("inventory_shortfall_forecast"), z.literal("pacing_risk"), z.literal("budget_constrained")])).optional(), + indicators: z.array(z.object({ + type: z.union([z.literal("creative_diversity_low"), z.literal("audience_saturation"), z.literal("inventory_shortfall_forecast"), z.literal("pacing_risk"), z.literal("budget_constrained")]).optional() + }).passthrough()).optional() +}).passthrough(); + +export const GetMediaBuyDeliveryCatalogItemMetricsSchema = DeliveryMetricsSchema.merge(z.object({ + content_id: z.string().optional(), + content_id_type: ContentIDTypeSchema.optional() +}).passthrough()); + +export const GetMediaBuyDeliveryKeywordMetricsSchema = DeliveryMetricsSchema.merge(z.object({ + keyword: z.string().optional(), + match_type: MatchTypeSchema.optional() +}).passthrough()); + +export const GetMediaBuyDeliveryGeoMetricsSchema = DeliveryMetricsSchema.merge(z.object({ + geo_level: GeographicTargetingLevelSchema.optional(), + system: z.string().optional(), + country: z.string().regex(/^[A-Z]{2}$/).optional(), + geo_code: z.string().optional(), + geo_name: z.string().optional() +}).passthrough()); + +export const GetMediaBuyDeliveryDeviceTypeMetricsSchema = DeliveryMetricsSchema.merge(z.object({ + device_type: DeviceTypeSchema.optional() +}).passthrough()); + +export const GetMediaBuyDeliveryDevicePlatformMetricsSchema = DeliveryMetricsSchema.merge(z.object({ + device_platform: DevicePlatformSchema.optional() +}).passthrough()); + +export const GetMediaBuyDeliveryAudienceMetricsSchema = DeliveryMetricsSchema.merge(z.object({ + audience_id: z.string().optional(), + audience_source: AudienceSourceSchema.optional(), + audience_name: z.string().optional() +}).passthrough()); + +export const GetMediaBuyDeliveryPlacementMetricsSchema = DeliveryMetricsSchema.merge(z.object({ + placement_identity: PlacementIdentitySchema.optional(), + placement_name: z.string().optional(), + placement_id: z.string().optional(), + publisher_domain: z.string().regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/).optional() +}).passthrough()); + +export const GetMediaBuyDeliveryResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + notification_type: z.union([z.literal("scheduled"), z.literal("final"), z.literal("delayed"), z.literal("adjusted"), z.literal("window_update")]).optional(), + partial_data: z.boolean().optional(), + unavailable_count: z.int().min(0).optional(), + sequence_number: z.int().min(1).optional(), + next_expected_at: z.iso.datetime().optional(), + reporting_period: z.object({ + start: z.iso.datetime(), + end: z.iso.datetime() + }).passthrough(), + reporting_revision_binding: z.object({ + reporting_revision_id: z.string().min(1).max(255), + row_count: z.int().min(0), + control_totals: z.array(ReportingControlTotalSchema), + content_sha256: z.string().regex(/^[A-Fa-f0-9]{64}$/) + }).passthrough().optional(), + reporting_revision: ReportingRevisionSchema.optional(), + reporting_rows: z.array(z.object({}).passthrough()).optional(), + pagination: PaginationResponseSchema.optional(), + currency: z.string().regex(/^[A-Z]{3}$/).optional(), + attribution_window: AttributionWindowSchema.optional(), + aggregated_totals: z.object({ + impressions: z.number().min(0), + spend: z.number().min(0), + clicks: z.number().min(0).optional(), + completed_views: z.number().min(0).optional(), + views: z.number().min(0).optional(), + conversions: z.number().min(0).optional(), + conversion_value: z.number().min(0).optional(), + commissionable_value: z.number().min(0).optional(), + roas: z.number().min(0).optional(), + new_to_brand_rate: z.number().min(0).max(1).optional(), + cost_per_acquisition: z.number().min(0).optional(), + completion_rate: z.number().min(0).max(1).optional().nullable(), + reach: z.number().min(0).optional(), + reach_aggregation: ReachAggregationSchema.optional(), + reach_unit: ReachUnitSchema.optional(), + frequency: z.number().min(0).optional(), + media_buy_count: z.int().min(0), + metric_aggregates: z.array(DeliveryMetricAggregateSchema).optional() + }).passthrough().optional(), + media_buy_deliveries: z.array(z.object({ + media_buy_id: z.string(), + currency: z.string().regex(/^[A-Z]{3}$/).optional(), + status: z.union([z.literal("pending_creatives"), z.literal("pending_start"), z.literal("pending"), z.literal("active"), z.literal("paused"), z.literal("completed"), z.literal("rejected"), z.literal("canceled"), z.literal("failed"), z.literal("reporting_delayed")]), + expected_availability: z.iso.datetime().optional(), + is_adjusted: z.boolean().optional(), + is_final: z.boolean().optional(), + finalized_at: z.iso.datetime().optional(), + pricing_model: PricingModelSchema.optional(), + pacing_index: z.number().min(0).optional(), + totals: DeliveryMetricsSchema.merge(z.object({ + effective_rate: z.number().min(0).optional() + }).passthrough()), + by_package: z.array(DeliveryMetricsSchema.merge(z.object({ + package_id: z.string(), + pacing_index: z.number().min(0).optional(), + pricing_model: PricingModelSchema.optional(), + rate: z.number().min(0).optional(), + currency: z.string().regex(/^[A-Z]{3}$/).optional(), + delivery_status: DeliveryStatusSchema.optional(), + paused: z.boolean().optional(), + is_final: z.boolean().optional(), + finalized_at: z.iso.datetime().optional(), + measurement_window: z.string().max(50).optional(), + supersedes_window: z.string().max(50).optional(), + missing_metrics: z.array(MissingMetricSchema).optional(), + metric_values: z.array(PackageDeliveryMetricValueSchema).optional(), + by_catalog_item: z.array(GetMediaBuyDeliveryCatalogItemMetricsSchema).optional(), + by_catalog_item_truncated: z.boolean().optional(), + by_catalog_item_sorted_by: SortMetricSchema.optional(), + by_catalog_item_sort_direction: SortDirectionSchema.optional(), + by_creative: z.array(CreativeDeliveryMetricsSchema).optional(), + by_format: z.array(DeliveryMetricsSchema.merge(z.object({ + format_kind: CanonicalFormatKindSchema + }).passthrough())).optional(), + by_format_truncated: z.boolean().optional(), + by_format_sorted_by: SortMetricSchema.optional(), + by_format_sort_direction: SortDirectionSchema.optional(), + by_creative_truncated: z.boolean().optional(), + by_creative_sorted_by: SortMetricSchema.optional(), + by_creative_sort_direction: SortDirectionSchema.optional(), + by_keyword: z.array(GetMediaBuyDeliveryKeywordMetricsSchema).optional(), + by_keyword_truncated: z.boolean().optional(), + by_keyword_sorted_by: SortMetricSchema.optional(), + by_keyword_sort_direction: SortDirectionSchema.optional(), + by_geo: z.array(GetMediaBuyDeliveryGeoMetricsSchema).optional(), + by_geo_truncated: z.boolean().optional(), + by_geo_sorted_by: SortMetricSchema.optional(), + by_geo_sort_direction: SortDirectionSchema.optional(), + by_device_type: z.array(GetMediaBuyDeliveryDeviceTypeMetricsSchema).optional(), + by_device_type_truncated: z.boolean().optional(), + by_device_type_sorted_by: SortMetricSchema.optional(), + by_device_type_sort_direction: SortDirectionSchema.optional(), + by_device_type_pagination: PaginationResponseSchema.optional(), + by_device_platform: z.array(GetMediaBuyDeliveryDevicePlatformMetricsSchema).optional(), + by_device_platform_truncated: z.boolean().optional(), + by_device_platform_sorted_by: SortMetricSchema.optional(), + by_device_platform_sort_direction: SortDirectionSchema.optional(), + by_device_platform_pagination: PaginationResponseSchema.optional(), + by_audience: z.array(GetMediaBuyDeliveryAudienceMetricsSchema).optional(), + by_audience_truncated: z.boolean().optional(), + by_audience_sorted_by: SortMetricSchema.optional(), + by_audience_sort_direction: SortDirectionSchema.optional(), + by_audience_pagination: PaginationResponseSchema.optional(), + by_demographic: z.array(DeliveryMetricsSchema.merge(z.object({ + demographic: z.string().min(1).regex(/\S/), + demographic_system: DemographicSystemSchema, + age: DemographicAgeRangeSchema.optional() + }).passthrough())).optional(), + by_demographic_truncated: z.boolean().optional(), + by_demographic_sorted_by: SortMetricSchema.optional(), + by_demographic_sort_direction: SortDirectionSchema.optional(), + by_demographic_suppressed: z.boolean().optional(), + by_placement: z.array(GetMediaBuyDeliveryPlacementMetricsSchema).optional(), + by_placement_truncated: z.boolean().optional(), + by_placement_sorted_by: SortMetricSchema.optional(), + by_placement_sort_direction: SortDirectionSchema.optional(), + by_placement_pagination: PaginationResponseSchema.optional(), + by_property: z.array(PropertyDeliveryMetricsSchema).optional(), + by_property_truncated: z.boolean().optional(), + by_property_suppressed: z.boolean().optional(), + by_property_sorted_by: SortMetricSchema.optional(), + by_property_sort_direction: SortDirectionSchema.optional(), + by_collection: z.array(CollectionDeliveryMetricsSchema).optional(), + by_collection_truncated: z.boolean().optional(), + by_collection_sorted_by: SortMetricSchema.optional(), + by_collection_sort_direction: SortDirectionSchema.optional(), + by_installment: z.array(InstallmentDeliveryMetricsSchema).optional(), + by_installment_truncated: z.boolean().optional(), + by_installment_sorted_by: SortMetricSchema.optional(), + by_installment_sort_direction: SortDirectionSchema.optional(), + by_collection_property: z.array(CollectionPropertyDeliveryMetricsSchema).optional(), + by_collection_property_truncated: z.boolean().optional(), + by_collection_property_suppressed: z.boolean().optional(), + by_collection_property_sorted_by: SortMetricSchema.optional(), + by_collection_property_sort_direction: SortDirectionSchema.optional(), + by_installment_property: z.array(InstallmentPropertyDeliveryMetricsSchema).optional(), + by_installment_property_truncated: z.boolean().optional(), + by_installment_property_suppressed: z.boolean().optional(), + by_installment_property_sorted_by: SortMetricSchema.optional(), + by_installment_property_sort_direction: SortDirectionSchema.optional(), + by_placement_property: z.array(PlacementPropertyDeliveryMetricsSchema).optional(), + by_placement_property_truncated: z.boolean().optional(), + by_placement_property_suppressed: z.boolean().optional(), + by_placement_property_sorted_by: SortMetricSchema.optional(), + by_placement_property_sort_direction: SortDirectionSchema.optional(), + by_spot: z.array(DeliveryMetricsSchema.merge(z.object({ + spot_id: z.string().min(1), + creative_id: z.string().min(1).optional(), + aired_at: z.iso.datetime(), + network: z.string().min(1).optional(), + station: z.string().min(1).optional(), + daypart: z.string().min(1).optional() + }).passthrough())).optional(), + by_spot_truncated: z.boolean().optional(), + daily_breakdown: z.array(z.object({ + date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), + impressions: z.number().min(0), + spend: z.number().min(0), + conversions: z.number().min(0).optional(), + conversion_value: z.number().min(0).optional(), + commissionable_value: z.number().min(0).optional(), + roas: z.number().min(0).optional(), + new_to_brand_rate: z.number().min(0).max(1).optional() + }).passthrough()).optional() + }).passthrough())), + windows: z.array(z.object({ + window_start: z.iso.datetime(), + window_end: z.iso.datetime(), + totals: DeliveryMetricsSchema, + by_package: z.array(DeliveryMetricsSchema.merge(z.object({ + package_id: z.string(), + currency: z.string().regex(/^[A-Z]{3}$/).optional() + }).passthrough())).optional(), + is_final: z.boolean().optional(), + measurement_window: z.string().max(50).optional() + }).passthrough()).optional(), + daily_breakdown: z.array(z.object({ + date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), + impressions: z.number().min(0), + spend: z.number().min(0), + conversions: z.number().min(0).optional(), + conversion_value: z.number().min(0).optional(), + commissionable_value: z.number().min(0).optional(), + roas: z.number().min(0).optional(), + new_to_brand_rate: z.number().min(0).max(1).optional() + }).passthrough()).optional() + }).passthrough()), + errors: z.array(ErrorSchema).optional(), + sandbox: z.boolean().optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const SuccessfulLookupSchema = z.union([SummaryViewSchema, PeriodsViewSchema, RevisionViewSchema]); + +export const FailedLookupSchema = z.union([UnavailableLookupSchema, OperationalFailureSchema]); + +export const SyncReportingStatusResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + results: z.array(z.union([RecordedReportingConsumerStatusSchema, UnchangedReportingConsumerStatusSchema, FailedReportingConsumerStatusSchema])).max(100), + ext: ExtensionObjectSchema.optional() +}).passthrough().superRefine((value, ctx) => { + // reporting consumer status canonical parity + if (value.status === "completed" && value.results.length < 1) { + ctx.addIssue({ code: "custom", path: ["results"], message: "Array must contain at least 1 element(s)" }); + } + if (value.status !== "completed") return; + value.results.forEach((entry, index) => { + if (entry.result === "failed") { + if (entry.errors.length < 1) ctx.addIssue({ code: "custom", path: ["results", index, "errors"], message: "Array must contain at least 1 element(s)" }); + return; + } + const status = entry.consumer_status as Record; + if (status.recorded_at === undefined) { + ctx.addIssue({ code: "custom", path: ["results", index, "consumer_status", "recorded_at"], message: "recorded_at is required" }); + } }); + }); + +export const SyncReportingReceiptsResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + results: z.array(z.union([RecordedReportingReceiptSchema, UnchangedReportingReceiptSchema, RecordedReportingAdjustmentReceiptSchema, UnchangedReportingAdjustmentReceiptSchema, FailedReportingReceiptSchema])).max(100), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const ProvidePerformanceFeedbackResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional() +}).passthrough().and(z.union([ProvidePerformanceFeedbackSuccessSchema, ProvidePerformanceFeedbackErrorSchema])); + +// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. +export const SyncEventSourcesResponseSchema: z.ZodType, SyncEventSourcesResponse & Record> = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional() +}).passthrough().and(z.union([SyncEventSourcesSuccessSchema, SyncEventSourcesErrorSchema])); + +export const LogEventResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional() +}).passthrough().and(z.union([LogEventSuccessSchema, LogEventErrorSchema])); + +export const SyncAudiencesResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional() +}).passthrough().and(z.union([SyncAudiencesSuccessSchema, SyncAudiencesErrorSchema, SyncAudiencesSubmittedSchema])); + +export const BuildCreativeRequestSchema = z.object({ + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + governance_context: z.string().min(1).max(4096).regex(/^[\x20-\x7E]+$/).optional(), + message: z.string().optional(), + creative_manifest: CreativeManifestSchema.optional(), + creative_representation_set: CreativeRepresentationSetSchema.optional(), + representation_destination: RepresentationDestinationSchema.optional(), + representation_selection_strategy: RepresentationSelectionStrategySchema.optional(), + creative_id: z.string().optional(), + concept_id: z.string().optional(), + media_buy_id: z.string().optional(), + package_id: z.string().optional(), + target_format_id: FormatReferenceStructuredObjectSchema.optional(), + target_format_ids: z.array(FormatReferenceStructuredObjectSchema).max(50).optional(), + target_capability_id: z.string().regex(/^[a-zA-Z0-9_-]+$/).optional(), + target_capability_ids: z.array(z.string()).max(50).optional(), + transformer_id: z.string().optional(), + config: z.object({}).passthrough().optional(), + refine_from_build_variant_id: z.string().optional(), + mode: z.union([z.literal("execute"), z.literal("estimate")]).optional(), + max_spend: z.object({ + amount: z.number().min(0), + currency: z.string().regex(/^[A-Z]{3}$/) + }).passthrough().optional(), + max_creatives: z.int().min(1).optional(), + signal_conditions: z.array(SignalTargetingSchema.and(z.object({ + signal_agent_segment_id: z.string().optional() + }).passthrough())).optional(), + max_variants: z.int().min(1).optional(), + variant_axis: z.object({ + dimension: z.union([z.literal("voice"), z.literal("theme"), z.literal("best_of_n"), z.literal("transformer_config"), z.literal("custom")]), + field: z.string().optional(), + values: z.array(z.unknown()).optional(), + label: z.string().optional() + }).passthrough().optional(), + keep_mode: z.union([z.literal("keep_all"), z.literal("keep_one"), z.literal("keep_some")]).optional(), + selection_strategy: CreativeSelectionStrategySchema.optional(), + account: AccountReferenceSchema.optional(), + brand: BrandReferenceSchema.optional(), + quality: CreativeQualitySchema.optional(), + evaluator: EvaluatorSpecSchema.optional(), + item_limit: z.int().min(1).optional(), + include_preview: z.boolean().optional(), + preview_inputs: z.array(z.object({ + name: z.string(), + macros: z.record(z.string(), z.string()).optional(), + context_description: z.string().optional() + }).passthrough()).optional(), + preview_quality: CreativeQualitySchema.optional(), + preview_output_format: PreviewOutputFormatSchema.optional(), + macro_values: z.record(z.string(), z.string()).optional(), + idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/), + push_notification_config: PushNotificationConfigSchema.optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const BuildCreativeSuccessSchema = z.object({ + creative_manifest: CreativeManifestSchema, + build_variant_id: z.string().optional(), + recipe_hash: z.string().optional(), + sandbox: z.boolean().optional(), + expires_at: z.iso.datetime().optional(), + preview: z.object({ + previews: z.array(z.object({ + preview_id: z.string(), + renders: z.array(PreviewRenderSchema), + input: z.object({ + name: z.string(), + macros: z.record(z.string(), z.string()).optional(), + context_description: z.string().optional() + }).passthrough() + }).passthrough()), + interactive_url: z.string().optional(), + expires_at: z.iso.datetime() + }).passthrough().optional(), + preview_error: ErrorSchema.optional(), + pricing_option_id: z.string().optional(), + vendor_cost: z.number().min(0).optional(), + currency: z.string().regex(/^[A-Z]{3}$/).optional(), + consumption: CreativeConsumptionSchema.optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. +export const PreviewCreativeRequestSchema: z.ZodObject<{ request_type: z.ZodType } & Record, z.core.$loose> & z.ZodType, PreviewCreativeRequest & Record> = z.object({}).passthrough().merge(z.object({ + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + request_type: z.union([z.literal("single"), z.literal("batch"), z.literal("variant")]), + creative_manifest: CreativeManifestSchema.optional(), + target_capability_id: z.string().regex(/^[a-zA-Z0-9_-]+$/).optional(), + format_id: FormatReferenceStructuredObjectSchema.optional(), + inputs: z.array(z.object({ + name: z.string(), + macros: z.record(z.string(), z.string()).optional(), + context_description: z.string().optional() + }).passthrough()).optional(), + template_id: z.string().optional(), + quality: CreativeQualitySchema.optional(), + output_format: PreviewOutputFormatSchema.optional(), + item_limit: z.int().min(1).optional(), + requests: z.array(z.object({ + target_capability_id: z.string().regex(/^[a-zA-Z0-9_-]+$/).optional(), + format_id: FormatReferenceStructuredObjectSchema.optional(), + creative_manifest: CreativeManifestSchema.optional(), + creative_id: z.string().optional(), + inputs: z.array(z.object({ + name: z.string(), + macros: z.record(z.string(), z.string()).optional(), + context_description: z.string().optional() + }).passthrough()).optional(), + template_id: z.string().optional(), + quality: CreativeQualitySchema.optional(), + output_format: PreviewOutputFormatSchema.optional(), + item_limit: z.int().min(1).optional() + }).passthrough()).max(50).optional(), + variant_id: z.string().optional(), + creative_id: z.string().optional(), + allow_async: z.boolean().optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough()).superRefine((value, ctx) => { + const defined = (field: string): boolean => value[field as keyof typeof value] !== undefined; + const rejectPair = (left: string, right: string): void => { + if (defined(left) && defined(right)) { + ctx.addIssue({ code: "custom", path: [right], message: "the paired fields are mutually exclusive" }); + } + }; + rejectPair("target_capability_id", "format_id"); + rejectPair("creative_manifest", "creative_id"); + if (value.requests !== undefined) { + if (value.requests.length < 1 || value.requests.length > 50) { + ctx.addIssue({ code: "custom", path: ["requests"], message: "preview requests must contain 1 to 50 items" }); + } + const canonicalRouting = defined("target_capability_id") || value.requests.some(item => item.target_capability_id !== undefined); + const legacyRouting = defined("format_id") || value.requests.some(item => item.format_id !== undefined); + if (canonicalRouting && legacyRouting) { + ctx.addIssue({ code: "custom", path: ["requests"], message: "preview requests cannot mix canonical and legacy routing selectors" }); + } + for (const [index, item] of value.requests.entries()) { + const hasManifest = item.creative_manifest !== undefined; + const hasCreativeId = item.creative_id !== undefined; + if (hasManifest === hasCreativeId) { + ctx.addIssue({ code: "custom", path: ["requests", index, "creative_manifest"], message: "each preview request requires exactly one of creative_manifest or creative_id" }); + } + } } - })).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Dimension constraints represented by a ForecastPoint. Use this when one product, proposal, or signal coverage forecast needs to expose availability or forecasted delivery by country, region, placement, device, audience, signal value, time window, or intersections such as placement x country without creating separate products solely for each slice. Each item declares one dimension family via `kind`; when multiple items are present, the point represents their intersection. Sellers MUST NOT emit more than one item for each `kind` in a point. Consumers MUST NOT treat repeated kinds as OR semantics; repeated peer values such as two countries are a seller conformance issue. Dimension values are descriptors of the forecast row and are independent of pricing_options.").optional(), "availability_status": z.enum(["available","unavailable"]).describe("Bookability of the inventory a forecast row describes, as of the forecast's generated_at. A snapshot, never a hold: valid_until bounds freshness, and proposal finalization or purchase remains the commitment boundary.").optional(), "metrics": z.object({ "coverage_rate": z.intersection(z.object({ "low": z.number().gte(0).describe("Conservative (low-end) forecast value").optional(), "mid": z.number().gte(0).describe("Expected (most likely) forecast value").optional(), "high": z.number().gte(0).describe("Optimistic (high-end) forecast value").optional() }).catchall(z.any()).and(z.union([z.object({ "mid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "low": z.any().refine((value) => value !== undefined, "Required"), "high": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A forecast value with optional confidence bounds. Either mid (point estimate) or both low and high (range) must be provided. mid represents the most likely outcome. low and high represent conservative and optimistic estimates. All three can be provided together."), z.object({ "low": z.any().optional(), "mid": z.any().optional(), "high": z.any().optional() })).describe("A forecast range whose low, midpoint, and high values are rates in the inclusive interval from 0 to 1.").optional() }).catchall(z.object({ "low": z.number().gte(0).describe("Conservative (low-end) forecast value").optional(), "mid": z.number().gte(0).describe("Expected (most likely) forecast value").optional(), "high": z.number().gte(0).describe("Optimistic (high-end) forecast value").optional() }).catchall(z.any()).and(z.union([z.object({ "mid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "low": z.any().refine((value) => value !== undefined, "Required"), "high": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A forecast value with optional confidence bounds. Either mid (point estimate) or both low and high (range) must be provided. mid represents the most likely outcome. low and high represent conservative and optimistic estimates. All three can be provided together.")), "viewability": z.object({ "vendor": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery.").optional(), "measurable_impressions": z.object({ "low": z.number().gte(0).describe("Conservative (low-end) forecast value").optional(), "mid": z.number().gte(0).describe("Expected (most likely) forecast value").optional(), "high": z.number().gte(0).describe("Optimistic (high-end) forecast value").optional() }).catchall(z.any()).and(z.union([z.object({ "mid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "low": z.any().refine((value) => value !== undefined, "Required"), "high": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A forecast value with optional confidence bounds. Either mid (point estimate) or both low and high (range) must be provided. mid represents the most likely outcome. low and high represent conservative and optimistic estimates. All three can be provided together.").optional(), "viewable_impressions": z.object({ "low": z.number().gte(0).describe("Conservative (low-end) forecast value").optional(), "mid": z.number().gte(0).describe("Expected (most likely) forecast value").optional(), "high": z.number().gte(0).describe("Optimistic (high-end) forecast value").optional() }).catchall(z.any()).and(z.union([z.object({ "mid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "low": z.any().refine((value) => value !== undefined, "Required"), "high": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A forecast value with optional confidence bounds. Either mid (point estimate) or both low and high (range) must be provided. mid represents the most likely outcome. low and high represent conservative and optimistic estimates. All three can be provided together.").optional(), "viewable_rate": z.intersection(z.object({ "low": z.number().gte(0).describe("Conservative (low-end) forecast value").optional(), "mid": z.number().gte(0).describe("Expected (most likely) forecast value").optional(), "high": z.number().gte(0).describe("Optimistic (high-end) forecast value").optional() }).catchall(z.any()).and(z.union([z.object({ "mid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "low": z.any().refine((value) => value !== undefined, "Required"), "high": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A forecast value with optional confidence bounds. Either mid (point estimate) or both low and high (range) must be provided. mid represents the most likely outcome. low and high represent conservative and optimistic estimates. All three can be provided together."), z.object({ "low": z.any().optional(), "mid": z.any().optional(), "high": z.any().optional() })).describe("A forecast range whose low, midpoint, and high values are rates in the inclusive interval from 0 to 1.").optional(), "viewed_seconds": z.object({ "low": z.number().gte(0).describe("Conservative (low-end) forecast value").optional(), "mid": z.number().gte(0).describe("Expected (most likely) forecast value").optional(), "high": z.number().gte(0).describe("Optimistic (high-end) forecast value").optional() }).catchall(z.any()).and(z.union([z.object({ "mid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "low": z.any().refine((value) => value !== undefined, "Required"), "high": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A forecast value with optional confidence bounds. Either mid (point estimate) or both low and high (range) must be provided. mid represents the most likely outcome. low and high represent conservative and optimistic estimates. All three can be provided together.").optional(), "standard": z.enum(["mrc","groupm"]).describe("Viewability measurement standard applied to determine whether an impression qualifies as viewable. These are materially different thresholds and should not be compared across standards.").optional() }).passthrough().and(z.union([z.any().refine((value) => !z.union([z.object({ "measurable_impressions": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "viewable_impressions": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "viewable_rate": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "viewed_seconds": z.any().refine((value) => value !== undefined, "Required") }).passthrough()]).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.object({ "standard": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).optional(), "vendor_metric_values": z.array(z.object({ "vendor": z.object({ "domain": z.string().regex(new RegExp("^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$")).describe("Domain that hosts /.well-known/brand.json or is registered for the brand."), "brand_id": z.string().regex(new RegExp("^[a-z0-9_]+$")).describe("Brand within a house-of-brands manifest. Omit for a single-brand domain.").optional(), "countries": z.array(z.string().regex(new RegExp("^[A-Z]{2}$"))).min(1).refine((arr) => arr.every((item, i) => arr.indexOf(item) == i), "All items must be unique!").describe("Canonical set of ISO 3166-1 alpha-2 countries for this advertiser identity. Omit when the identity is global or the house does not split the brand geographically. Array order is not meaningful; producers MUST sort codes lexicographically before computing keys or signatures. This qualifies account and proposal identity and is not delivery targeting.").optional() }).passthrough().describe("Stable brand identity used to resolve the canonical brand manifest, optionally qualified by the countries of a commercial advertiser entity. The manifest URL is derived from domain; callers do not send brand assets or per-call brand overrides. Countries do not target delivery."), "metric_id": z.string().regex(new RegExp("^[a-z][a-z0-9_]*$")).min(1).max(64).describe("Identifier for a vendor-defined metric within the vendor's vocabulary. Stable lookup key; the vendor publishes the canonical list (with category, methodology, and standard alignment) in `brand.json` `agents[type='measurement']`. Lowercase with underscores so a future enum promotion into `available-metric.json` is a literal string lift. Identifier is namespaced by the vendor — the same `metric_id` may mean different things in different vendors' vocabularies."), "value": z.object({ "low": z.number().gte(0).describe("Conservative (low-end) forecast value").optional(), "mid": z.number().gte(0).describe("Expected (most likely) forecast value").optional(), "high": z.number().gte(0).describe("Optimistic (high-end) forecast value").optional() }).catchall(z.any()).and(z.union([z.object({ "mid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "low": z.any().refine((value) => value !== undefined, "Required"), "high": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A forecast value with optional confidence bounds. Either mid (point estimate) or both low and high (range) must be provided. mid represents the most likely outcome. low and high represent conservative and optimistic estimates. All three can be provided together."), "unit": z.string().optional(), "measurable_impressions": z.object({ "low": z.number().gte(0).describe("Conservative (low-end) forecast value").optional(), "mid": z.number().gte(0).describe("Expected (most likely) forecast value").optional(), "high": z.number().gte(0).describe("Optimistic (high-end) forecast value").optional() }).catchall(z.any()).and(z.union([z.object({ "mid": z.any().refine((value) => value !== undefined, "Required") }).passthrough(), z.object({ "low": z.any().refine((value) => value !== undefined, "Required"), "high": z.any().refine((value) => value !== undefined, "Required") }).passthrough()])).describe("A forecast value with optional confidence bounds. Either mid (point estimate) or both low and high (range) must be provided. mid represents the most likely outcome. low and high represent conservative and optimistic estimates. All three can be provided together.").optional(), "breakdown": z.record(z.string(), z.any()).optional() }).passthrough().describe("Compact forecasted vendor metric with a BrandKey vendor pointer and no embedded brand assets.")).optional() }).passthrough().describe("Compact forecast row with numeric ranges and identity-only measurement-vendor references.")).min(1), "forecast_range_unit": z.enum(["spend","availability","reach_freq","weekly","daily","clicks","conversions","package"]).describe("Describes how to interpret the points array in a DeliveryForecast — what axis the curve represents").optional(), "method": z.enum(["estimate","modeled","guaranteed"]).describe("Method used to produce a delivery forecast"), "currency": z.string().regex(new RegExp("^[A-Z]{3}$")), "demographic_system": z.enum(["nielsen","nielsen_audio","barb","agf","oztam","mediametrie","custom"]).describe("Audience measurement systems for demographic notation in GRP forecasts and pricing, across video and audio channels. Specifies how demographics are written, not whose panel produced the numbers — provider identity is measurement_source.").optional(), "demographic": z.string().optional(), "measurement_source": z.string().regex(new RegExp("^[a-z0-9_]+$")).max(64).optional(), "reach_unit": z.enum(["individuals","households","devices","accounts","cookies","custom"]).describe("Unit of measurement for reach and audience size metrics. Different channels and measurement providers count reach in fundamentally different units, making cross-channel comparison impossible without declaring the unit.").optional(), "generated_at": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "valid_until": z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), "ext": z.record(z.string(), z.any()).describe("Extension object for platform-specific, vendor-namespaced parameters. Extensions are always optional and must be namespaced under a vendor/platform key (e.g., ext.gam, ext.roku). Used for custom capabilities, partner-specific configuration, and features being proposed for standardization.").optional() }).passthrough().describe("Compact product forecast without legacy BrandRef or creative dependencies.").describe("Aggregate forecasted delivery for the proposal. For outcome_target requests, points carry the goal's metric or event key in metrics.").optional() }).passthrough().describe("Compact immutable proposal for the AdCP 3.2 lifecycle. commercial_terms is the sole authoritative commercial envelope; narrative fields do not duplicate legacy allocation or creative graphs."); - const exactSchema = objectSchema.superRefine((value, ctx) => { - const checked = z.intersection(z.intersection(z.union([z.any().refine((value) => !z.object({ "proposal_kind": z.enum(["media_buy_update","media_buy_cancellation"]) }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "proposal_kind": z.enum(["media_buy_update","media_buy_cancellation"]) }), z.object({ "parent_proposal_id": z.any().refine((value) => value !== undefined, "Required"), "media_buy_id": z.any().refine((value) => value !== undefined, "Required"), "base_media_buy_revision": z.any().refine((value) => value !== undefined, "Required") }).passthrough())]), z.union([z.any().refine((value) => !z.object({ "proposal_status": z.literal("accepted") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "proposal_status": z.literal("accepted") }), z.object({ "media_buy_id": z.any().refine((value) => value !== undefined, "Required"), "accepted_at": z.any().refine((value) => value !== undefined, "Required") }).passthrough())])), z.intersection(z.union([z.any().refine((value) => !z.object({ "proposal_status": z.literal("committed") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "proposal_status": z.literal("committed") }), z.object({ "expires_at": z.any().refine((value) => value !== undefined, "Required") }).passthrough())]), z.union([z.any().refine((value) => !z.object({ "proposal_kind": z.literal("media_buy_cancellation") }).safeParse(value).success, "Invalid input: Should NOT be valid against schema"), z.intersection(z.object({ "proposal_kind": z.literal("media_buy_cancellation") }), z.object({ "commercial_terms": z.object({ "cancellation_terms": z.any().refine((value) => value !== undefined, "Required") }).passthrough().optional() }))]))).safeParse(value); - if (!checked.success) { - for (const issue of checked.error.issues) { - ctx.addIssue({ code: "custom", path: issue.path, message: issue.message }); + if (value.request_type === "single") { + const hasManifest = defined("creative_manifest"); + const hasCreativeId = defined("creative_id"); + if (hasManifest === hasCreativeId) { + ctx.addIssue({ code: "custom", path: ["creative_manifest"], message: "single preview requires exactly one of creative_manifest or creative_id" }); } - } - }); - return Object.assign(exactSchema, { - pick: objectSchema.pick.bind(objectSchema), - omit: objectSchema.omit.bind(objectSchema), - extend: objectSchema.extend.bind(objectSchema), - }); - })(); + } else if (value.request_type === "batch") { + if (value.requests === undefined) { + ctx.addIssue({ code: "custom", path: ["requests"], message: "batch preview requires 1 to 50 requests" }); + } + } else if (value.request_type === "variant" && !defined("variant_id")) { + ctx.addIssue({ code: "custom", path: ["variant_id"], message: "variant_id is required for variant preview" }); + } +}); + +export const PreviewCreativeResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional() +}).passthrough().and(z.union([PreviewCreativeSingleResponseSchema, PreviewCreativeBatchResponseSchema, PreviewCreativeVariantResponseSchema, PreviewCreativeSubmittedSchema])); + +// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. +export const ListTransformersResponseCreativeAgentSchema: z.ZodObject<{ [K in keyof ListTransformersResponseCreativeAgent]-?: undefined extends ListTransformersResponseCreativeAgent[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, ListTransformersResponseCreativeAgent & Record> = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + transformers: z.array(TransformerSchema), + errors: z.array(ErrorSchema).optional(), + pagination: PaginationResponseSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const GetCreativeDeliveryResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + account_id: z.string().optional(), + media_buy_id: z.string().optional(), + currency: z.string().regex(/^[A-Z]{3}$/), + reporting_period: z.object({ + start: z.iso.datetime(), + end: z.iso.datetime(), + timezone: z.string().optional() + }).passthrough(), + creatives: z.array(z.object({ + creative_id: z.string(), + media_buy_id: z.string().optional(), + format_id: FormatReferenceStructuredObjectSchema.optional(), + format_kind: CanonicalFormatKindSchema.optional(), + format_option_ref: FormatOptionReferenceSchema.optional(), + totals: DeliveryMetricsSchema.optional(), + variant_count: z.int().min(0).optional(), + variants: z.array(CreativeVariantSchema) + }).passthrough()), + pagination: z.object({ + limit: z.int().min(1), + offset: z.int().min(0), + has_more: z.boolean(), + total_count: z.int().min(0).optional(), + total: z.int().min(0).optional() + }).passthrough().optional(), + errors: z.array(ErrorSchema).optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const SourceLocalizationReadbackSchema = z.object({ + locale_variant_id: z.string(), + locale: LanguageTagSchema, + role: z.literal("source"), + assets: ResolvedAssetsSchema +}).passthrough(); + +export const CreativeLocalizationReadbackSchema: z.ZodType = z.object({ + default_locale_variant_id: z.string().min(1).max(255), + unmatched_locale_action: z.union([z.literal("serve_default"), z.literal("do_not_serve")]), + locale_matching: z.literal("rfc4647_lookup"), + locale_fallbacks: z.array(z.object({ + language_range: LanguageTagSchema, + locale_variant_id: z.string().min(1).max(255) + }).passthrough()).max(50).optional(), + variants: z.array(z.union([SourceLocalizationReadbackSchema, TargetLocalizationReadbackSchema])).max(51) +}).passthrough(); + +// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. +export const SyncCreativesRequestSchema: z.ZodObject<{ [K in keyof SyncCreativesRequest]-?: undefined extends SyncCreativesRequest[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, SyncCreativesRequest & Record> = z.object({ + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + account: AccountReferenceSchema, + creatives: z.array(CreativeAssetSchema.and(z.object({ + revision_id: CreativeRevisionIDSchema.optional(), + localization: CreativeLocalizationSchema.optional().nullable() + }).passthrough())).max(100).optional(), + creative_ids: z.array(z.string()).max(100).optional(), + assignments: z.array(z.object({ + creative_id: z.string(), + package_id: z.string(), + weight: z.number().min(0).max(100).optional(), + placement_ids: z.array(z.string()).optional() + }).passthrough()).optional(), + assignment_operations: z.array(z.union([AssignOrUpdateSchema, UnassignSchema, ReplaceAssignmentSchema])).max(500).optional(), + idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/), + delete_missing: z.boolean().optional(), + dry_run: z.boolean().optional(), + validation_mode: ValidationModeSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const SyncCreativesSuccessSchema: z.ZodType = z.object({ + dry_run: z.boolean().optional(), + creatives: z.array(z.object({ + creative_id: z.string(), + revision_id: CreativeRevisionIDSchema.optional(), + account: AccountSchema.optional(), + action: CreativeActionSchema, + status: CreativeStatusSchema.optional(), + platform_id: z.string().optional(), + localization: CreativeLocalizationReadbackSchema.optional(), + changes: z.array(z.string()).optional(), + errors: z.array(ErrorSchema).optional(), + warnings: z.array(z.string()).optional(), + macro_resolution_results: z.array(MacroResolutionResultSchema).optional(), + preview_url: z.string().optional(), + expires_at: z.iso.datetime().optional(), + assigned_to: z.array(z.string()).optional(), + assignment_errors: z.record(z.string(), z.string()).optional() + }).passthrough()), + sandbox: z.boolean().optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const ValidateInputRequestSchema = z.object({ + account: AccountReferenceSchema.optional(), + brand: BrandReferenceSchema.optional(), + manifest: CreativeManifestSchema, + targets: z.array(z.union([CanonicalFormatTargetSchema, ProductTargetSchema, ThirdPartyFormatTargetSchema, CreativeCapabilityTargetSchema])).max(50).optional() +}).passthrough(); + +export const ActivateSignalResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional() +}).passthrough().and(z.union([ActivateSignalSuccessSchema, ActivateSignalErrorSchema])); + +export const CreatePropertyListResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + list: PropertyListSchema, + auth_token: z.string(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const CreateCollectionListResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + list: CollectionListSchema, + auth_token: z.string(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const ListContentStandardsResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional() +}).passthrough().and(z.union([z.object({ + standards: z.array(ContentStandardsSchema), + pagination: PaginationResponseSchema.optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() + }).passthrough(), z.object({ + errors: z.array(ErrorSchema), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() + }).passthrough()])); + +export const GetContentStandardsResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional() +}).passthrough().and(z.union([z.object({ + standards_id: z.string(), + name: z.string().optional(), + countries_all: z.array(z.string()).optional(), + channels_any: z.array(MediaChannelSchema).optional(), + languages_any: z.array(z.string()).optional(), + policies: z.array(PolicyEntrySchema).optional(), + calibration_exemplars: z.object({ + pass: z.array(ArtifactSchema).optional(), + fail: z.array(ArtifactSchema).optional() + }).passthrough().optional(), + pricing_options: z.array(VendorPricingOptionSchema).optional(), + ext: ExtensionObjectSchema.optional(), + context: ContextObjectSchema.optional() + }).passthrough(), z.object({ + errors: z.array(ErrorSchema), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() + }).passthrough()])); + +export const CreateContentStandardsRequestSchema = z.object({ + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + scope: z.object({ + countries_all: z.array(z.string()).optional(), + channels_any: z.array(MediaChannelSchema).optional(), + languages_any: z.array(z.string()), + description: z.string().optional() + }).passthrough(), + registry_policy_ids: z.array(z.string()).optional(), + policies: z.array(PolicyEntrySchema).optional(), + calibration_exemplars: z.object({ + pass: z.array(z.union([z.object({ + type: z.literal("url"), + value: z.string(), + language: z.string().optional() + }).passthrough(), ArtifactSchema])).optional(), + fail: z.array(z.union([z.object({ + type: z.literal("url"), + value: z.string(), + language: z.string().optional() + }).passthrough(), Artifact1Schema])).optional() + }).passthrough().optional(), + idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const UpdateContentStandardsResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional() +}).passthrough().and(z.union([UpdateContentStandardsSuccessSchema, UpdateContentStandardsErrorSchema])); + +export const GetCreativeFeaturesRequestSchema = z.object({ + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + creative_manifest: CreativeManifestSchema, + feature_ids: z.array(z.string()).optional(), + account: AccountReferenceSchema.optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const ReportPlanOutcomeRequestSchema = z.object({ + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + plan_id: z.string(), + check_id: z.string().optional(), + idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/), + purchase_type: PurchaseTypeSchema.optional(), + outcome: OutcomeTypeSchema, + seller_response: z.object({ + seller_reference: z.string().max(255).optional(), + committed_budget: z.number().min(0).optional(), + packages: z.array(z.object({ + budget: z.number().min(0).optional() + }).passthrough()).optional(), + planned_delivery: PlannedDeliverySchema.optional(), + creative_deadline: z.iso.datetime().optional() + }).passthrough().optional(), + delivery: z.union([z.object({ + observation_id: z.string().min(1).max(255), + source: z.literal("seller_statement_copy"), + observed_at: z.iso.datetime(), + seller_statement_id: z.string(), + seller_statement_digest: z.string().regex(/^sha256:[a-f0-9]{64}$/), + reporting_period: z.object({ + start: z.iso.datetime(), + end: z.iso.datetime() + }).passthrough(), + cumulative_spend: z.number().min(0), + currency: z.string().regex(/^[A-Z]{3}$/), + period_closed: z.boolean().optional(), + impressions: z.int().min(0).optional() + }).passthrough(), z.object({ + observation_id: z.string().min(1).max(255), + source: z.literal("buyer_measurement"), + observed_at: z.iso.datetime(), + seller_statement_id: z.string().optional(), + seller_statement_digest: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional(), + reporting_period: z.object({ + start: z.iso.datetime(), + end: z.iso.datetime() + }).passthrough(), + cumulative_spend: z.number().min(0), + currency: z.string().regex(/^[A-Z]{3}$/), + period_closed: z.boolean().optional(), + impressions: z.int().min(0).optional() + }).passthrough()]).optional(), + error: ReportedOutcomeErrorSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(/^[\x20-\x7E]+$/).optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const GetPlanAuditLogsResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + plans: z.array(z.object({ + plan_id: z.string(), + plan_version: z.int(), + status: z.union([z.literal("active"), z.literal("suspended"), z.literal("completed")]), + budget: z.object({ + authorized: z.number().optional(), + accounting_mode: z.union([z.literal("gross_commitment"), z.literal("verified_net_cost")]).optional(), + committed: z.number().optional(), + gross_committed: z.number().optional(), + adjustments_reported: z.number().optional(), + adjustments_verified: z.number().optional(), + net_cost: z.number().optional(), + headroom_restored: z.number().optional(), + net_committed: z.number().optional(), + ledger_committed: z.number().optional(), + remaining: z.number().optional(), + utilization_pct: z.number().optional() + }).passthrough(), + channel_allocation: z.record(z.string(), z.object({ + committed: z.number().optional(), + pct: z.number().optional() + }).passthrough()).optional(), + summary: z.object({ + checks_performed: z.int().optional(), + outcomes_reported: z.int().optional(), + adjustments_reported: z.int().optional(), + adjustments_verified: z.int().optional(), + statuses: z.object({ + approved: z.int().optional(), + denied: z.int().optional(), + conditions: z.int().optional(), + human_reviewed: z.int().optional() + }).passthrough().optional(), + findings_count: z.int().optional(), + escalations: z.array(z.object({ + check_id: z.string(), + reason: z.string(), + resolution: z.string().optional(), + resolved_at: z.iso.datetime().optional() + }).passthrough()).optional(), + drift_metrics: z.object({ + escalation_rate: z.number().min(0).max(1).optional(), + escalation_rate_trend: z.union([z.literal("increasing"), z.literal("stable"), z.literal("declining")]).optional(), + auto_approval_rate: z.number().min(0).max(1).optional(), + human_override_rate: z.number().min(0).max(1).optional(), + mean_confidence: z.number().min(0).max(1).optional(), + thresholds: z.object({ + escalation_rate_max: z.number().min(0).max(1).optional(), + escalation_rate_min: z.number().min(0).max(1).optional(), + auto_approval_rate_max: z.number().min(0).max(1).optional(), + human_override_rate_max: z.number().min(0).max(1).optional() + }).passthrough().optional() + }).passthrough().optional() + }).passthrough(), + entries: z.array(z.object({ + id: z.string(), + type: z.union([z.literal("check"), z.literal("outcome"), z.literal("adjustment")]), + timestamp: z.iso.datetime(), + plan_id: z.string().optional(), + caller: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional(), + tool: z.string().optional(), + verdict: GovernanceDecisionSchema.optional(), + check_type: z.union([z.literal("intent"), z.literal("execution")]).optional(), + mode: GovernanceModeSchema.optional(), + explanation: z.string().optional(), + policies_evaluated: z.array(z.string()).optional(), + categories_evaluated: z.array(z.string()).optional(), + findings: z.array(z.object({ + category_id: z.string(), + policy_id: z.string().optional(), + source_plan_id: z.string().optional(), + severity: EscalationSeveritySchema, + explanation: z.string(), + details: z.object({}).passthrough().optional(), + confidence: z.number().min(0).max(1).optional(), + uncertainty_reason: z.string().optional(), + attestation_reference_digest: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional() + }).passthrough()).optional(), + delivery_statement: z.object({ + statement_id: z.string(), + statement_digest: z.string().regex(/^sha256:[a-f0-9]{64}$/), + sequence: z.int().min(1), + issued_at: z.iso.datetime(), + seller_reference: z.string(), + cumulative_spend: z.number().min(0), + currency: z.string().regex(/^[A-Z]{3}$/), + reporting_period: z.object({ + start: z.iso.datetime(), + end: z.iso.datetime() + }).passthrough(), + canonical_payload: z.object({ + seller_reference: z.string(), + delivery_metrics: z.object({}).passthrough() + }).passthrough() + }).passthrough().optional(), + outcome: OutcomeTypeSchema.optional(), + error: ReportedOutcomeErrorSchema.optional(), + outcome_id: z.string().optional(), + seller_adjustment_id: z.string().optional(), + adjustment_type: z.union([z.literal("decommitment"), z.literal("refund"), z.literal("credit"), z.literal("makegood")]).optional(), + amount: z.object({ + amount: z.number(), + currency: z.string().regex(/^[A-Z]{3}$/) + }).passthrough().optional(), + headroom_restored: z.number().min(0).optional(), + reason: z.string().optional(), + effective_at: z.iso.datetime().optional(), + committed_budget: z.number().optional(), + reported_committed_budget: z.number().min(0).optional(), + seller_reference: z.string().optional(), + delivery: z.object({ + observation_id: z.string().min(1).max(255).optional(), + source: z.union([z.literal("seller_statement_copy"), z.literal("buyer_measurement")]).optional(), + observed_at: z.iso.datetime().optional(), + seller_statement_id: z.string().optional(), + seller_statement_digest: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional(), + reporting_period: z.object({ + start: z.iso.datetime(), + end: z.iso.datetime() + }).passthrough().optional(), + cumulative_spend: z.number().min(0).optional(), + currency: z.string().regex(/^[A-Z]{3}$/).optional(), + period_closed: z.boolean().optional(), + impressions: z.int().min(0).optional() + }).passthrough().optional(), + governance_context: z.string().optional(), + plan_hash: z.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(), + runtime_attestations: z.array(z.object({ + reference: AttestationReferenceSchema, + evaluation: AttestationEvaluationSchema + }).passthrough()).max(10).optional(), + runtime_attestation_binding_digest: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional(), + purchase_type: PurchaseTypeSchema.optional(), + outcome_status: z.string().optional(), + delivery_reconciliation_status: z.union([z.literal("consistent"), z.literal("measurement_variance"), z.literal("disputed"), z.literal("unmatched"), z.literal("closed_unresolved")]).optional(), + delivery_period_state: z.union([z.literal("open"), z.literal("closed")]).optional(), + adjustment_state: z.union([z.literal("reported"), z.literal("verified"), z.literal("disputed")]).optional(), + verified_amount: z.number().min(0).optional(), + evidence: z.object({ + evidence_id: z.string(), + evidence_type: z.union([z.literal("decommitment_agreement"), z.literal("refund_settlement"), z.literal("credit_note"), z.literal("makegood_agreement")]), + digest: z.string().regex(/^sha256:[a-f0-9]{64}$/), + issued_at: z.iso.datetime() + }).passthrough().optional(), + reviewed_by: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional(), + reviewed_at: z.iso.datetime().optional(), + review_reason: z.string().optional() + }).passthrough()).optional(), + governed_actions: z.array(z.object({ + governance_context: z.string(), + purchase_type: PurchaseTypeSchema, + status: z.union([z.literal("active"), z.literal("suspended"), z.literal("completed")]), + committed: z.number(), + adjustments_reported: z.number().optional(), + adjustments_verified: z.number().optional(), + net_cost: z.number().optional(), + headroom_restored: z.number().optional(), + net_committed: z.number().optional(), + seller_reported_spend: z.number().min(0).optional(), + buyer_observed_spend: z.number().min(0).optional(), + delivery_reporting_period: z.object({ + start: z.iso.datetime(), + end: z.iso.datetime() + }).passthrough().optional(), + conservative_exposure: z.number().min(0).optional(), + delivery_reconciliation_status: z.union([z.literal("consistent"), z.literal("measurement_variance"), z.literal("disputed"), z.literal("unmatched"), z.literal("closed_unresolved")]).optional(), + delivery_period_state: z.union([z.literal("open"), z.literal("closed")]).optional(), + check_count: z.int(), + seller_reference: z.string().optional() + }).passthrough()) + }).passthrough()), + ext: ExtensionObjectSchema.optional() +}).passthrough(); -export const MediaBuySchema: z.ZodType = z.object({ - media_buy_id: z.string(), - name: z.string().min(1).max(255).regex(/\S/).optional(), - accepted_proposal_id: z.string().min(1).max(255).optional(), - accepted_proposal_terms_digest: z.string().regex(/^sha256:[A-Za-z0-9_-]{43}$/).optional(), - account: AccountSchema.optional(), - status: MediaBuyStatusSchema, - health: MediaBuyHealthSchema.and(z.string()).optional(), - impairments: z.array(ImpairmentSchema).optional(), - rejection_reason: z.string().optional(), - confirmed_at: z.iso.datetime().nullable(), - cancellation: z.object({ - canceled_at: z.iso.datetime(), - canceled_by: CanceledBySchema, - reason: z.string().max(500).optional() +export const CheckGovernanceRequestSchema = z.object({}).passthrough().merge(z.object({ + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + plan_id: z.string().optional(), + caller: z.string().refine(adcpJsonSchemaUri, "Invalid URI"), + purchase_type: PurchaseTypeSchema.optional(), + target_agent: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional(), + proposed_commitment: z.object({ + amount: z.number().min(0), + currency: z.string().regex(/^[A-Z]{3}$/) + }).passthrough().optional(), + execution_commitment: z.object({ + amount: z.number().min(0), + currency: z.string().regex(/^[A-Z]{3}$/) + }).passthrough().optional(), + tool: z.string().optional(), + payload: z.object({}).passthrough().optional(), + proposal: CanonicalProposalSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(/^[\x20-\x7E]+$/).optional(), + consultation_context: z.string().min(1).max(255).regex(/^[A-Za-z0-9_.:-]+$/).optional(), + phase: GovernancePhaseSchema.optional(), + planned_delivery: PlannedDeliverySchema.optional(), + delivery_metrics: z.object({ + statement_id: z.string().min(1).max(255).optional(), + statement_digest: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional(), + sequence: z.int().min(1).optional(), + issued_at: z.iso.datetime().optional(), + reporting_period: z.object({ + start: z.iso.datetime(), + end: z.iso.datetime() + }).passthrough(), + spend: z.number().min(0).optional(), + cumulative_spend: z.number().min(0).optional(), + currency: z.string().regex(/^[A-Z]{3}$/).optional(), + impressions: z.int().min(0).optional(), + cumulative_impressions: z.int().min(0).optional(), + geo_distribution: z.record(z.string(), z.number()).optional(), + channel_distribution: z.record(z.string(), z.number()).optional(), + pacing: z.union([z.literal("ahead"), z.literal("on_track"), z.literal("behind")]).optional(), + audience_distribution: z.object({ + baseline: z.union([z.literal("census"), z.literal("platform"), z.literal("custom")]), + baseline_description: z.string().optional(), + indices: z.record(z.string(), z.number()), + cumulative_indices: z.record(z.string(), z.number()).optional() + }).passthrough().optional() + }).passthrough().optional(), + modification_summary: z.string().max(1000).optional(), + runtime_attestations: z.array(AttestationReferenceSchema.and(z.object({ + subject: z.object({ + type: z.literal("resource"), + resource_type: z.literal("https://adcontextprotocol.org/claims/subjects/signal") + }).passthrough().optional() + }).passthrough())).max(10).optional(), + invoice_recipient: BusinessEntitySchema.optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough()); + +// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. +export const GetAdCPCapabilitiesResponseSchema: z.ZodObject<{ [K in keyof GetAdCPCapabilitiesResponse]-?: undefined extends GetAdCPCapabilitiesResponse[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, GetAdCPCapabilitiesResponse & Record> = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + adcp: z.object({ + major_versions: z.array(z.number()), + supported_versions: z.array(z.string()).optional(), + build_version: z.string().regex(/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$/).optional(), + idempotency: z.union([IdempotencySupportedSchema, IdempotencyUnsupportedSchema]), + principal: z.object({ + supported: z.literal(true), + sync_task: z.literal("sync_principal"), + read_task: z.literal("get_principal"), + supported_sections: z.array(z.union([z.literal("notification_configs"), z.literal("reporting_destinations"), z.literal("declarations")])), + max_reporting_destinations: z.int().min(1).max(64).optional(), + reporting_destination_offerings: z.array(z.object({ + pattern: z.union([z.literal("file_transfer"), z.literal("warehouse_materialization"), z.literal("dataset_share")]), + transports: z.array(z.string()), + formats: z.array(z.union([z.literal("jsonl"), z.literal("csv"), z.literal("parquet"), z.literal("avro"), z.literal("orc")])).optional(), + access_modes: z.array(z.string()).optional(), + verification_profiles: ReportingVerificationProfileSetSchema + }).passthrough()).max(3).optional(), + suspension_interval_seconds: z.int().min(1).max(86400).optional(), + caller_event_types: z.array(NotificationTypeSchema).optional(), + optimistic_concurrency: z.boolean() + }).passthrough().optional(), + capability_changes: z.object({ + capabilities_version: z.string().min(1).max(255).optional(), + last_modified: z.iso.datetime().optional(), + cache_ttl_seconds: z.int().min(60).max(604800).optional(), + notifications: z.union([CapabilityChangeNotificationsSupportedSchema, CapabilityChangeNotificationsUnsupportedSchema]).optional() + }).passthrough().optional(), + governance_enforcement: z.object({ + tasks: z.array(z.union([z.object({ + task: z.literal("create_media_buy"), + modes: z.array(z.union([z.literal("signed_context"), z.literal("online_execution_check")])).max(1) + }).passthrough(), z.object({ + task: z.literal("update_media_buy"), + modes: z.array(z.union([z.literal("signed_context"), z.literal("online_execution_check")])).max(1) + }).passthrough(), z.object({ + task: z.literal("buy_products"), + modes: z.array(z.union([z.literal("signed_context"), z.literal("online_execution_check")])).max(1) + }).passthrough(), z.object({ + task: z.literal("accept_proposal"), + modes: z.array(z.union([z.literal("signed_context"), z.literal("online_execution_check")])).max(1) + }).passthrough(), z.object({ + task: z.literal("control_media_buy"), + modes: z.array(z.union([z.literal("signed_context"), z.literal("online_execution_check")])).max(1) + }).passthrough(), z.object({ + task: z.literal("build_creative"), + modes: z.array(z.literal("signed_context")).max(1) + }).passthrough(), z.object({ + task: z.literal("activate_signal"), + modes: z.array(z.literal("signed_context")).max(1) + }).passthrough(), z.object({ + task: z.literal("acquire_rights"), + modes: z.array(z.literal("signed_context")).max(1) + }).passthrough(), z.object({ + task: z.literal("update_rights"), + modes: z.array(z.literal("signed_context")).max(1) + }).passthrough()])), + accepted_governance_agents: AcceptedGovernanceAgentsSchema.optional() + }).passthrough().optional(), + attestations: AttestationCapabilitiesSchema.optional() + }).passthrough(), + supported_protocols: z.array(z.union([z.literal("media_buy"), z.literal("signals"), z.literal("governance"), z.literal("sponsored_intelligence"), z.literal("creative"), z.literal("brand"), z.literal("measurement")])), + account: z.object({ + require_operator_auth: z.boolean().optional(), + authorization_endpoint: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional(), + supported_billing: z.array(BillingPartySchema), + supported_account_currency_modes: z.array(AccountCurrencyModeSchema).optional(), + timezone: AccountTimezoneCapabilitySchema.optional(), + required_for_products: z.boolean().optional(), + account_financials: z.boolean().optional(), + notifications: z.union([AccountNotificationsSupportedSchema, AccountNotificationsUnsupportedSchema]).optional(), + change_feed: z.union([AccountChangeFeedSupportedSchema, AccountChangeFeedUnsupportedSchema]).optional(), + identity_updates: z.union([AccountIdentityUpdatesSupportedSchema, AccountIdentityUpdatesUnsupportedSchema]).optional(), + sandbox: z.boolean().optional() + }).passthrough().optional(), + media_buy: z.object({ + acceptance_policy_discovery: z.object({ + catalog_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI").regex(/^https:\/\//), + catalog_digest: z.string().regex(/^sha256:[a-f0-9]{64}$/), + default_profile_ids: z.array(z.string()).optional() + }).passthrough().optional(), + supported_pricing_models: z.array(PricingModelSchema).optional(), + buying_modes: z.array(z.union([z.literal("brief"), z.literal("wholesale"), z.literal("refine")])).optional(), + measurement_terms_acceptance: z.boolean().optional(), + availability_horizon: z.boolean().optional(), + lifecycle_tools: z.array(z.union([z.literal("list_products"), z.literal("request_proposals"), z.literal("refine_proposals"), z.literal("decline_proposals"), z.literal("buy_products"), z.literal("accept_proposal"), z.literal("control_media_buy")])).optional(), + proposal_refinement: z.object({ + supported_dimensions: z.array(z.union([z.literal("total_budget"), z.literal("cpm"), z.literal("impressions"), z.literal("flight"), z.literal("product_changes"), z.literal("alternatives"), z.literal("criteria")])), + max_alternatives: z.int().min(2).max(10).optional() + }).passthrough().optional(), + reporting_delivery_methods: z.array(CapabilityReportingDeliveryMethodSchema).optional(), + performance_feedback: z.object({ + reports_application_status: z.boolean().optional() + }).passthrough().optional(), + offline_delivery_protocols: z.array(CloudStorageProtocolSchema).optional(), + reporting_delivery: ReportingDeliveryCapabilitiesSchema.optional(), + supports_proposals: z.boolean().optional(), + outcome_target: z.boolean().optional(), + governance_aware: z.boolean().optional(), + propagation_surfaces: z.array(z.union([z.literal("snapshot"), z.literal("webhook"), z.literal("out_of_band")])).optional(), + creative_approval_mode: z.union([z.literal("auto_approve"), z.literal("require_human")]).optional(), + supported_indicator_types: z.array(IndicatorTypeSchema).optional(), + relationship_notifications: z.object({ + supported: z.literal(true), + registration_task: z.literal("sync_accounts"), + event_types: z.array(z.union([z.literal("indicators.changed"), z.literal("creative.assignment_changed")])).max(2), + repair_tasks: z.array(z.literal("get_media_buys")).max(1), + projection_tasks: z.array(z.literal("list_creatives")).max(1).optional(), + supports_webhook_activity: z.boolean().optional() + }).passthrough().optional(), + features: MediaBuyFeaturesSchema.optional(), + execution: z.object({ + trusted_match: z.object({ + surfaces: z.array(PropertyTypeSchema).optional() + }).passthrough().optional(), + axe_integrations: z.array(z.string()).optional(), + creative_specs: z.object({ + vast_versions: z.array(VASTVersionSchema).optional(), + macro_resolution_capabilities: z.array(MacroProcessingCapabilitySchema).optional(), + mraid_versions: z.array(z.string()).optional(), + vpaid: z.boolean().optional(), + simid: z.boolean().optional(), + vast_validation: z.union([z.literal("structural"), z.literal("document"), z.literal("wrapper")]).optional() + }).passthrough().optional(), + targeting: z.object({ + geo_countries: z.boolean().optional(), + geo_regions: z.union([z.boolean(), GeographicRegionSupportSchema]).optional(), + geo_regions_exclude: z.union([z.boolean(), GeographicRegionSupportSchema]).optional(), + geo_metros: z.object({ + nielsen_dma: z.boolean().optional(), + uk_itl1: z.boolean().optional(), + uk_itl2: z.boolean().optional(), + eurostat_nuts2: z.boolean().optional() + }).passthrough().optional(), + geo_postal_areas: PostalAreaSupportSchema.optional(), + geo_places: z.record(z.string(), GeographicPlaceSystemSupportSchema).optional(), + age_restriction: z.object({ + supported: z.boolean().optional(), + verification_methods: z.array(AgeVerificationMethodSchema).optional() + }).passthrough().optional(), + demographics: z.object({ + supported: z.boolean() + }).passthrough().optional(), + language: z.union([z.boolean(), z.object({ + supported: z.boolean().optional(), + supported_languages: z.array(LanguageTagSchema).optional() + }).passthrough()]).optional(), + keyword_targets: z.object({ + supported_match_types: z.array(MatchTypeSchema) + }).passthrough().optional(), + negative_keywords: z.object({ + supported_match_types: z.array(MatchTypeSchema) + }).passthrough().optional(), + placement_selection: z.boolean().optional(), + property_list: z.boolean().optional(), + property_list_exclude: z.boolean().optional(), + collection_list: z.boolean().optional(), + collection_list_exclude: z.boolean().optional(), + geo_proximity: z.object({ + radius: z.boolean().optional(), + travel_time: z.boolean().optional(), + geometry: z.boolean().optional(), + transport_modes: z.array(TransportModeSchema).optional() + }).passthrough().optional() + }).passthrough().optional() + }).passthrough().optional(), + audience_evidence: z.object({ + supported_requirement_modes: z.array(z.union([z.literal("required"), z.literal("preferred")])), + supported_presence_modes: z.array(z.union([z.literal("required"), z.literal("when_available")])), + supports_attestation_evaluation: z.boolean() + }).passthrough().optional(), + rights_attestations: z.object({ + requirement: z.union([z.literal("optional"), z.literal("required")]) + }).passthrough().optional(), + audience_targeting: z.object({ + supported_identifier_types: z.array(z.union([z.literal("hashed_email"), z.literal("hashed_phone")])), + supports_platform_customer_id: z.boolean().optional(), + supported_uid_types: z.array(UIDTypeSchema).optional(), + minimum_audience_size: z.int().min(1), + supported_activation_methods: z.array(AudienceActivationMethodSchema).optional(), + matching_latency_hours: z.object({ + min: z.int().min(0).optional(), + max: z.int().min(0).optional() + }).passthrough().optional() + }).passthrough().optional(), + supported_optimization_metrics: z.array(z.union([z.literal("clicks"), z.literal("views"), z.literal("completed_views"), z.literal("viewed_seconds"), z.literal("attention_seconds"), z.literal("attention_score"), z.literal("engagements"), z.literal("follows"), z.literal("saves"), z.literal("profile_visits"), z.literal("reach")])).optional(), + vendor_metric_optimization: z.object({ + supported_targets: z.array(z.union([z.literal("cost_per"), z.literal("threshold_rate")])).optional() + }).passthrough().optional(), + conversion_tracking: z.object({ + multi_source_event_dedup: z.boolean().optional(), + per_creative_attribution: z.boolean().optional(), + supported_event_types: z.array(EventTypeSchema).optional(), + supported_targets: z.array(z.union([z.literal("cost_per"), z.literal("per_ad_spend"), z.literal("maximize_value")])).optional(), + supported_uid_types: z.array(UIDTypeSchema).optional(), + supported_hashed_identifiers: z.array(z.union([z.literal("hashed_email"), z.literal("hashed_phone")])).optional(), + supported_action_sources: z.array(ActionSourceSchema).optional(), + attribution_windows: z.array(z.object({ + event_type: EventTypeSchema.optional(), + post_click: z.array(DurationSchema), + post_view: z.array(DurationSchema).optional() + }).passthrough()).optional() + }).passthrough().optional(), + frequency_capping: z.object({ + supported_per_units: z.array(ReachUnitSchema).optional(), + supported_window_units: z.array(z.string()).optional() + }).passthrough().optional(), + aggregate_frequency_capping: MediaBuyFrequencyCapCapabilitySchema.optional(), + budget_capping: z.object({ + supported_scopes: z.array(z.union([z.literal("media_buy"), z.literal("package")])), + supported_periods: z.array(z.literal("day")), + timezone_basis: BudgetCappingTimezoneBasisSchema, + fixed_timezone: z.string().min(1).optional(), + buyer_timezone_override: z.boolean().optional() + }).passthrough().optional(), + content_standards: z.object({ + supports_local_evaluation: z.boolean().optional(), + supported_channels: z.array(MediaChannelSchema).optional(), + supports_webhook_delivery: z.boolean().optional() + }).passthrough().optional(), + portfolio: z.object({ + publisher_domains: z.array(z.string()), + primary_channels: z.array(MediaChannelSchema).optional(), + primary_countries: z.array(z.string()).optional(), + description: z.string().max(5000).optional(), + advertising_policies: z.string().max(10000).optional() + }).passthrough().optional() + }).passthrough().optional(), + signals: z.object({ + data_provider_domains: z.array(z.string()).optional(), + discovery_modes: z.array(z.union([z.literal("brief"), z.literal("wholesale")])).optional(), + features: z.object({ + catalog_signals: z.boolean().optional() + }).passthrough().catchall(z.boolean()).optional() + }).passthrough().optional(), + governance: z.object({ + runtime_attestations: z.object({ + signal_activation: z.object({ + requirement: z.union([z.literal("optional"), z.literal("required")]), + claim_types: z.array(z.string()) + }).passthrough() + }).passthrough().optional(), + aggregation_window_days: z.int().min(1).max(365).optional(), + property_features: z.array(z.object({ + feature_id: z.string(), + type: z.union([z.literal("binary"), z.literal("quantitative"), z.literal("categorical")]), + range: z.object({ + min: z.number(), + max: z.number() + }).passthrough().optional(), + categories: z.array(z.string()).optional(), + description: z.string().optional(), + methodology_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional() + }).passthrough()).optional(), + creative_features: z.array(z.object({ + feature_id: z.string(), + type: z.union([z.literal("binary"), z.literal("quantitative"), z.literal("categorical")]), + range: z.object({ + min: z.number(), + max: z.number() + }).passthrough().optional(), + categories: z.array(z.string()).optional(), + description: z.string().optional(), + methodology_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional() + }).passthrough()).optional() + }).passthrough().optional(), + sponsored_intelligence: z.object({ + endpoint: z.object({ + transports: z.array(z.object({ + type: z.union([z.literal("mcp"), z.literal("a2a")]), + url: z.string().refine(adcpJsonSchemaUri, "Invalid URI") + }).passthrough()), + preferred: z.union([z.literal("mcp"), z.literal("a2a")]).optional() + }).passthrough(), + capabilities: SICapabilitiesSchema, + brand_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional() + }).passthrough().optional(), + brand: z.object({ + rights: z.boolean().optional(), + right_types: z.array(RightTypeSchema).optional(), + available_uses: z.array(RightUseSchema).optional(), + generation_providers: z.array(z.string()).optional(), + description: z.string().max(5000).optional() + }).passthrough().optional(), + creative: z.object({ + supports_compliance: z.boolean().optional(), + has_creative_library: z.boolean().optional(), + supports_revisions: z.boolean().optional(), + supports_generation: z.boolean().optional(), + supports_transformation: z.boolean().optional(), + representation_resolution: z.object({ + supported: z.literal(true), + strategies: z.array(RepresentationSelectionStrategySchema) + }).passthrough().optional(), + supports_transformers: z.boolean().optional(), + supports_refinement: z.boolean().optional(), + supports_spend_controls: z.boolean().optional(), + supports_evaluator: z.boolean().optional(), + refinable_retention_seconds: z.int().min(0).optional(), + multiplicity: z.object({ + supports_catalog_fanout: z.boolean().optional(), + max_creatives_limit: z.int().min(1).optional(), + supports_signal_fanout: z.boolean().optional(), + max_signal_conditions_limit: z.int().min(1).optional(), + supports_variants: z.boolean().optional(), + max_variants_limit: z.int().min(1).optional(), + variant_dimensions: z.array(z.union([z.literal("voice"), z.literal("theme"), z.literal("best_of_n"), z.literal("transformer_config"), z.literal("custom")])).optional(), + selection_strategies: z.array(CreativeSelectionStrategySchema).optional() + }).passthrough().optional(), + supported_formats: z.array(z.object({ + capability_id: z.string().regex(/^[a-zA-Z0-9_-]+$/).optional(), + format: CreativeOperationFormatDeclarationSchema, + operations: z.array(z.union([z.literal("build"), z.literal("validate"), z.literal("preview")])).optional() + }).passthrough()).optional(), + preview: z.object({ + routes: z.array(z.object({ + capability_id: z.string().regex(/^[a-zA-Z0-9_-]+$/), + rendering_origin: z.union([z.literal("platform_native"), z.literal("agent_approximation")]) + }).passthrough()) + }).passthrough().optional(), + localization: z.object({ + max_target_variants: z.int().min(0).max(50).optional(), + locale_matching: z.literal("rfc4647_lookup") + }).passthrough().optional(), + bills_through_adcp: z.boolean().optional(), + canonical_catalog_version: z.string().regex(/^\d+\.\d+(\.\d+)?$/).optional() + }).passthrough().optional(), + oauth: z.object({ + supported: z.boolean() }).passthrough().optional(), - total_budget: z.number().min(0), - daily_budget_cap: z.number().min(0).optional(), - budget_cap_timezone: z.string().optional(), - currency: z.string().regex(/^[A-Z]{3}$/).optional(), - budget_allocation: BudgetAllocationSchema.optional(), - pacing: PacingSchema.optional(), - bidding: BiddingPolicySchema.optional(), - packages: z.array(PackageSchema), + request_signing: z.object({ + supported: z.boolean(), + covers_content_digest: z.union([z.literal("required"), z.literal("forbidden"), z.literal("either")]).optional(), + required_for: z.array(z.string()).optional(), + warn_for: z.array(z.string()).optional(), + supported_for: z.array(z.string()).optional(), + protocol_methods_supported_for: z.array(z.string()).optional(), + protocol_methods_warn_for: z.array(z.string()).optional(), + protocol_methods_required_for: z.array(z.string()).optional() + }).passthrough().optional(), + webhook_signing: z.object({ + supported: z.boolean(), + profile: z.literal("adcp/webhook-signing/v1").optional(), + algorithms: z.array(z.union([z.literal("ed25519"), z.literal("ecdsa-p256-sha256")])).optional(), + legacy_hmac_fallback: z.boolean().optional(), + delivery_retry_horizon_seconds: z.int().min(86400).max(604800).optional() + }).passthrough().optional(), + identity: z.object({ + brand_json_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI").regex(/^https:\/\//).optional(), + per_principal_key_isolation: z.boolean().optional(), + key_origins: z.object({ + governance_signing: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional(), + request_signing: z.string().optional(), + webhook_signing: z.string().optional(), + tmp_signing: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional() + }).passthrough().optional(), + compromise_notification: z.object({ + emits: z.boolean().optional(), + accepts: z.boolean().optional() + }).passthrough().optional() + }).passthrough().optional(), + measurement_gateway: z.object({ + delivery_task: z.literal("get_media_buy_delivery"), + feedback_task: z.literal("provide_performance_feedback") + }).passthrough().optional(), + measurement: z.object({ + produces_performance_feedback: z.boolean().optional(), + metrics: z.array(z.object({ + metric_id: VendorMetricIDSchema, + standard_reference: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional(), + accreditations: z.array(z.object({ + accrediting_body: z.string(), + certification_id: z.string().optional(), + valid_until: z.iso.date().optional(), + evidence_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional() + }).passthrough()).optional(), + unit: z.string().optional(), + description: z.string().optional(), + methodology_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional(), + methodology_version: z.string().optional(), + ext: ExtensionObjectSchema.optional() + }).passthrough()) + }).passthrough().optional(), + compliance_testing: z.object({ + scenarios: z.array(z.string()) + }).passthrough().optional(), + specialisms: z.array(AdCPSpecialismSchema).optional(), + extensions_supported: z.array(z.string()).optional(), + experimental_features: z.array(ExperimentalFeatureIDSchema).optional(), + wholesale_feed_versioning: z.object({ + supported: z.boolean(), + pricing_version_separate: z.boolean().optional(), + cache_scope_account: z.boolean().optional() + }).passthrough().optional(), + last_updated: z.iso.datetime().optional(), + errors: z.array(ErrorSchema).optional(), + ext: ExtensionObjectSchema.optional(), + wholesale_feed_webhooks: z.object({ + supported: z.boolean(), + event_types: z.array(z.union([z.literal("product.created"), z.literal("product.updated"), z.literal("product.priced"), z.literal("product.removed"), z.literal("signal.created"), z.literal("signal.updated"), z.literal("signal.priced"), z.literal("signal.removed"), z.literal("wholesale_feed.bulk_change")])).optional() + }).passthrough().optional() +}).passthrough(); + +export const SyncPrincipalRequestSchema = z.object({ + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/), + expected_configuration_version: z.string().min(1).max(255).optional(), + expected_principal_kind: PrincipalKindSchema.optional(), + configuration: z.object({ + notification_configs: z.array(AgentNotificationConfigSchema).max(16).optional(), + reporting_destinations: z.array(AgentReportingDestinationSchema).max(64).optional(), + declarations: AgentDeclarationsSchema.optional() + }).passthrough(), + dry_run: z.boolean().optional(), context: ContextObjectSchema.optional(), - invoice_recipient: BusinessEntity1Schema.optional(), - creative_deadline: z.iso.datetime().optional(), - revision: z.int().min(1), - created_at: z.iso.datetime().optional(), - updated_at: z.iso.datetime().optional(), ext: ExtensionObjectSchema.optional() }).passthrough(); -// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. -export const GetProductsResponseSchema: z.ZodObject<{ [K in keyof GetProductsResponse]-?: undefined extends GetProductsResponse[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, GetProductsResponse & Record> = z.object({ +export const AppliedPrincipalConfigurationSchema = z.object({ + kind: z.literal("applied"), + action: z.union([z.literal("updated"), z.literal("unchanged"), z.literal("cleared")]), + dry_run: z.literal(false), + principal_id: z.string().min(1).max(255), + principal_kind: PrincipalKindSchema, + configuration_version: z.string().min(1).max(255), + configuration: PrincipalStateSchema, + warnings: z.array(ErrorSchema).max(16).optional() +}).passthrough(); + +export const GetPrincipalResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + result: z.union([CurrentPrincipalConfigurationSchema, RecognizedPrincipalWithoutStandingConfigurationSchema, UnconfiguredPrincipalSchema, FailedPrincipalReadSchema]), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const AccountWithAuthorizationSchema = AccountSchema.merge(z.object({ + authorization: AccountAuthorizationSchema.optional() +}).passthrough()); + +export const ListAccountsResponseSchema = z.object({ context_id: z.string().optional(), context: ContextObjectSchema.optional(), task_id: z.string().optional(), @@ -17979,17 +18256,120 @@ export const GetProductsResponseSchema: z.ZodObject<{ [K in keyof GetProductsRes payload: z.object({}).passthrough().optional(), adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), adcp_major_version: z.number().int().gte(1).lte(99).optional(), + accounts: z.array(AccountWithAuthorizationSchema), + errors: z.array(ErrorSchema).optional(), + pagination: PaginationResponseSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const ProvisioningModeSchema = z.object({ + brand: BrandReferenceSchema, + operator: z.string().regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/), + operator_unit: OperatorUnitSchema.optional(), + currency: z.string().regex(/^[A-Z]{3}$/).optional(), + timezone: z.string().min(1).optional(), + billing: BillingPartySchema, + billing_entity: BusinessEntitySchema.optional(), + payment_terms: PaymentTermsSchema.optional(), + sandbox: z.boolean().optional(), + preferred_reporting_protocol: CloudStorageProtocolSchema.optional(), + reporting_delivery_configs: z.array(ReportingDeliveryConfigurationSchema).max(16).optional(), + notification_configs: z.array(NotificationConfigSchema).max(16).optional() +}).passthrough(); + +export const SettingsUpdateModeSchema = z.object({ + account: AccountReferenceSchema, + revision: z.int().min(1).optional(), + operator_identity: OperatorIdentitySchema.optional(), + destination_billing_entity: BusinessEntitySchema.optional(), + billing_entity: BusinessEntitySchema.optional(), + payment_terms: PaymentTermsSchema.optional(), + sandbox: z.boolean().optional(), + preferred_reporting_protocol: CloudStorageProtocolSchema.optional(), + reporting_delivery_configs: z.array(ReportingDeliveryConfigurationSchema).max(16).optional(), + notification_configs: z.array(NotificationConfigSchema).max(16).optional() +}).passthrough(); + +export const SyncAccountsSuccessSchema = z.object({ + dry_run: z.boolean().optional(), + accounts: z.array(z.object({ + account_id: z.string().optional(), + brand: BrandReferenceSchema, + operator: z.string(), + operator_unit: OperatorUnitSchema.optional(), + revision: z.int().min(1).optional(), + identity_change: AccountIdentityChangeSchema.optional(), + identity_change_preview: AccountIdentityChangePreviewSchema.optional(), + currency: z.string().regex(/^[A-Z]{3}$/).optional(), + timezone: z.string().min(1).optional(), + name: z.string().optional(), + action: z.union([z.literal("created"), z.literal("updated"), z.literal("unchanged"), z.literal("failed")]), + status: z.union([z.literal("active"), z.literal("pending_approval"), z.literal("rejected"), z.literal("payment_required"), z.literal("suspended"), z.literal("closed")]), + billing: BillingPartySchema.optional(), + billing_entity: BusinessEntitySchema.optional(), + destination_billing_entity: z.object({}).passthrough().optional(), + account_scope: AccountScopeSchema.optional(), + setup: z.object({ + url: z.string().optional(), + message: z.string(), + expires_at: z.iso.datetime().optional() + }).passthrough().optional(), + rate_card: z.string().optional(), + payment_terms: PaymentTermsSchema.optional(), + credit_limit: z.object({ + amount: z.number().min(0), + currency: z.string().regex(/^[A-Z]{3}$/) + }).passthrough().optional(), + errors: z.array(ErrorSchema).optional(), + warnings: z.array(z.string()).optional(), + sandbox: z.boolean().optional(), + notification_configs: z.array(NotificationConfigSchema).max(16).optional(), + reporting_delivery_configs: z.array(ReportingDeliveryConfigurationStateSchema).max(16).optional(), + authorization: AccountAuthorizationSchema.optional() + }).passthrough()), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const SyncGovernanceResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional() +}).passthrough().and(z.union([SyncGovernanceSuccessSchema, SyncGovernanceErrorSchema])); + +export const GetAccountFinancialsResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional() +}).passthrough().and(z.union([GetAccountFinancialsSuccessSchema, GetAccountFinancialsErrorSchema])); + +export const GetProductsCompletionSchema: z.ZodType = AdCPVersionEnvelopeSchema.merge(ProtocolEnvelopeSchema).merge(z.object({}).passthrough()).merge(z.object({ products: z.array(ProductSchema).optional(), targeting_resolution: ProductDiscoveryTargetingResolutionSchema.optional(), - extensions: z.record(z.string(), z.object({ - extends: z.string(), - fields: z.object({}).passthrough(), - version: z.string().optional(), - description: z.string().optional() - }).passthrough()).optional(), + extensions: z.object({}).passthrough().optional(), proposals: z.array(ProposalSchema).optional(), errors: z.array(ErrorSchema).optional(), - reason: z.string().min(1).max(2000).optional(), + reason: z.string().optional(), suggestions: z.array(z.string()).max(20).optional(), property_list_applied: z.boolean().optional(), catalog_applied: z.boolean().optional(), @@ -18004,7 +18384,7 @@ export const GetProductsResponseSchema: z.ZodObject<{ [K in keyof GetProductsRes notes: z.string().optional() }).passthrough(), z.object({ scope: z.literal("proposal"), - proposal_id: z.string().max(255), + proposal_id: z.string(), status: z.union([z.literal("applied"), z.literal("partial"), z.literal("unable")]), notes: z.string().optional() }).passthrough()])).optional(), @@ -18015,9 +18395,9 @@ export const GetProductsResponseSchema: z.ZodObject<{ [K in keyof GetProductsRes }).passthrough()).optional(), filter_diagnostics: z.object({ semantics: z.union([z.literal("only"), z.literal("any"), z.literal("approximate")]).optional(), - total_candidates: z.int().min(0).optional(), + total_candidates: z.number().optional(), excluded_by: z.record(z.string(), z.object({ - count: z.int().min(0), + count: z.number(), values: z.array(z.union([z.string(), z.object({}).passthrough()])).optional(), notes: z.string().optional() }).passthrough()).optional() @@ -18028,6 +18408,83 @@ export const GetProductsResponseSchema: z.ZodObject<{ [K in keyof GetProductsRes cache_scope: z.union([z.literal("public"), z.literal("account")]).optional(), unchanged: z.literal(true).optional(), sandbox: z.boolean().optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough()); + +export const ComplianceTaskCompletionDataSchema: z.ZodType = z.union([GetProductsCompletionSchema, GetSignalsCompletionSchema, CreateMediaBuyCompletionSchema]); + +export const UpstreamTrafficSuccessSchema = z.object({ + success: z.literal(true), + recorded_calls: z.array(z.union([RawAttestationSchema, DigestAttestationSchema])), + total_count: z.int().min(0), + truncated: z.boolean().optional(), + since_timestamp: z.iso.datetime(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. +export const ListTransformersResponseSchema: z.ZodObject<{ [K in keyof ListTransformersResponse]-?: undefined extends ListTransformersResponse[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, ListTransformersResponse & Record> = ListTransformersResponseCreativeAgentSchema; + +export const ValidatePropertyDeliveryRequestSchema = z.object({ + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + list_id: z.string(), + account: AccountReferenceSchema.optional(), + records: z.array(DeliveryRecordSchema).max(10000), + include_compliant: z.boolean().optional(), + context: ContextObjectSchema.optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + +export const ValidatePropertyDeliveryResponseSchema = z.object({ + context_id: z.string().optional(), + context: ContextObjectSchema.optional(), + task_id: z.string().optional(), + status: TaskStatusSchema, + message: z.string().optional(), + timestamp: z.string().refine(adcpJsonSchemaDateTime, "Invalid date-time").optional(), + replayed: z.boolean().optional(), + adcp_error: ErrorSchema.optional(), + push_notification_config: PushNotificationConfigSchema.optional(), + governance_context: z.string().min(1).max(4096).regex(new RegExp("^[\\x20-\\x7E]+$")).optional(), + payload: z.object({}).passthrough().optional(), + adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), + adcp_major_version: z.number().int().gte(1).lte(99).optional(), + compliant: z.boolean().optional(), + list_id: z.string(), + summary: z.object({ + total_records: z.int(), + total_impressions: z.int(), + compliant_records: z.int(), + compliant_impressions: z.int(), + non_compliant_records: z.int(), + non_compliant_impressions: z.int(), + not_covered_records: z.int(), + not_covered_impressions: z.int(), + unidentified_records: z.int(), + unidentified_impressions: z.int() + }).passthrough(), + aggregate: z.object({ + score: z.number().optional(), + grade: z.string().optional(), + label: z.string().optional(), + methodology_url: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional() + }).passthrough().optional(), + authorization_summary: z.object({ + records_checked: z.int(), + impressions_checked: z.int(), + authorized_records: z.int(), + authorized_impressions: z.int(), + unauthorized_records: z.int(), + unauthorized_impressions: z.int(), + unknown_records: z.int(), + unknown_impressions: z.int() + }).passthrough().optional(), + results: z.array(ValidationResultSchema), + validated_at: z.iso.datetime(), + list_resolved_at: z.iso.datetime().optional(), ext: ExtensionObjectSchema.optional() }).passthrough(); @@ -18256,6 +18713,40 @@ export const RequestProposalsResponseSchema = z.union([z.object({ } }); +export const MediaBuySchema: z.ZodType = z.object({ + media_buy_id: z.string(), + name: z.string().min(1).max(255).regex(/\S/).optional(), + accepted_proposal_id: z.string().min(1).max(255).optional(), + accepted_proposal_terms_digest: z.string().regex(/^sha256:[A-Za-z0-9_-]{43}$/).optional(), + account: AccountSchema.optional(), + status: MediaBuyStatusSchema, + health: MediaBuyHealthSchema.and(z.string()).optional(), + impairments: z.array(ImpairmentSchema).optional(), + rejection_reason: z.string().optional(), + confirmed_at: z.iso.datetime().nullable(), + cancellation: z.object({ + canceled_at: z.iso.datetime(), + canceled_by: CanceledBySchema, + reason: z.string().max(500).optional() + }).passthrough().optional(), + total_budget: z.number().min(0), + daily_budget_cap: z.number().min(0).optional(), + frequency_cap: MediaBuyFrequencyCapSchema.optional(), + budget_cap_timezone: z.string().optional(), + currency: z.string().regex(/^[A-Z]{3}$/).optional(), + budget_allocation: BudgetAllocationSchema.optional(), + pacing: PacingSchema.optional(), + bidding: BiddingPolicySchema.optional(), + packages: z.array(PackageSchema), + context: ContextObjectSchema.optional(), + invoice_recipient: BusinessEntity1Schema.optional(), + creative_deadline: z.iso.datetime().optional(), + revision: z.int().min(1), + created_at: z.iso.datetime().optional(), + updated_at: z.iso.datetime().optional(), + ext: ExtensionObjectSchema.optional() +}).passthrough(); + export const RefineProposalsResponseSchema = z.union([z.object({ adcp_version: z.string().optional(), results: z.array(z.union([z.object({ @@ -18497,30 +18988,6 @@ export const SyncCreativesResponseSchema: z.ZodType = z.object({ adcp_major_version: z.number().int().gte(1).lte(99).optional() }).passthrough().and(z.union([SyncCreativesSuccessSchema, SyncCreativesErrorSchema, SyncCreativesSubmittedSchema])); -export const CommittedMediaBuySchema = z.object({ - status: z.literal("completed"), - media_buy_id: z.string(), - revision: z.number(), - media_buy_status: MediaBuyStatusSchema.optional(), - confirmed_at: z.string().optional().nullable(), - accepted_proposal: CanonicalProposalSchema.and(z.object({ - proposal_status: z.literal("accepted"), - media_buy_id: z.string() - }).passthrough()), - purchase_bindings: z.array(z.object({ - purchase_index: z.number(), - product_id: z.string(), - package_id: z.string() - }).passthrough()), - available_actions: z.array(CanonicalMediaBuyActionSchema), - warnings: z.array(WarningSchema.and(z.object({ - code: z.union([z.literal("inventory_shortfall_forecast"), z.literal("flight_change_creates_pacing_risk")]).optional() - }).passthrough())).optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional(), - replayed: z.literal(true).optional() -}).passthrough(); - export const CreateMediaBuySuccessSchema: z.ZodType = z.object({ proposal_id: z.string().min(1).optional(), media_buy_id: z.string(), @@ -18534,6 +19001,7 @@ export const CreateMediaBuySuccessSchema: z.ZodType = z.object({ currency: z.string().regex(/^[A-Z]{3}$/).optional(), total_budget: z.number().min(0).optional(), daily_budget_cap: z.number().min(0).optional(), + frequency_cap: MediaBuyFrequencyCapSchema.optional(), budget_cap_timezone: z.string().optional(), budget_allocation: BudgetAllocationSchema.optional(), pacing: PacingSchema.optional(), @@ -18843,65 +19311,6 @@ export const AvailablePackageSchema: z.ZodObject<{ [K in keyof AvailablePackage] export const ContextMatchResponseSchema = ContextMatchResponseRouterPublisherSchema; -// @ts-ignore -- preserve the public schema type across lossy TS-to-Zod projection details. -export const GetProductsRequestSchema: z.ZodObject<{ [K in keyof GetProductsRequest]-?: undefined extends GetProductsRequest[K] ? z.ZodOptional, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, GetProductsRequest & Record> = z.object({ - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/).optional(), - buying_mode: z.union([z.literal("brief"), z.literal("wholesale"), z.literal("refine")]), - brief: z.string().optional(), - refine: z.array(z.union([z.object({ - scope: z.literal("request"), - ask: z.string().min(1) - }).passthrough(), z.object({ - scope: z.literal("product"), - product_id: z.string().min(1), - action: z.union([z.literal("include"), z.literal("omit"), z.literal("more_like_this")]).optional(), - ask: z.string().min(1).optional() - }).passthrough(), z.object({ - scope: z.literal("proposal"), - proposal_id: z.string().min(1), - action: z.union([z.literal("include"), z.literal("omit"), z.literal("finalize")]).optional(), - ask: z.string().min(1).optional() - }).passthrough()])).optional(), - brand: BrandReferenceSchema.optional(), - acceptance_context: AcceptanceContextSchema.optional(), - catalog: CatalogSchema.optional(), - account: AccountReferenceSchema.optional(), - preferred_delivery_types: z.array(DeliveryTypeSchema).optional(), - filters: ProductFiltersSchema.optional(), - targeting_overlay: TargetingOverlaySchema.optional(), - required_overlay_support: TargetingOverlayRequirementsSchema.optional(), - property_list: PropertyListReferenceSchema.optional(), - fields: z.array(z.union([z.union([z.literal("product_id"), z.literal("name"), z.literal("description"), z.literal("publisher_properties"), z.literal("channels"), z.literal("video_placement_types"), z.literal("audio_distribution_types"), z.literal("sponsored_placement_types"), z.literal("social_placement_surfaces"), z.literal("format_options"), z.literal("placements"), z.literal("delivery_type"), z.literal("exclusivity"), z.literal("pricing_options"), z.literal("forecast"), z.literal("reporting_capabilities"), z.literal("measurement_terms"), z.literal("performance_standards"), z.literal("catalog_types"), z.literal("signal_targeting_allowed"), z.literal("signal_targeting_rules"), z.literal("demographic_targeting"), z.literal("audience_evidence"), z.literal("audience_evidence_selections"), z.literal("max_optimization_goals"), z.literal("catalog_match"), z.literal("list_applications"), z.literal("brief_relevance"), z.literal("acceptance_policy_profile_ids"), z.literal("identity"), z.literal("expires_at"), z.literal("allowed_actions")]), z.union([z.literal("format_ids"), z.literal("outcome_measurement"), z.literal("delivery_measurement"), z.literal("creative_policy"), z.literal("metric_optimization"), z.literal("conversion_tracking"), z.literal("data_provider_signals"), z.literal("included_signals"), z.literal("signal_targeting_options"), z.literal("overlay_support"), z.literal("targeting_resolution"), z.literal("collections"), z.literal("collection_targeting_allowed"), z.literal("installments"), z.literal("is_custom"), z.literal("product_card"), z.literal("product_card_detailed"), z.literal("enforced_policies"), z.literal("trusted_match")])])).optional(), - time_budget: DurationSchema.optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - pagination: PaginationRequestSchema.optional(), - if_wholesale_feed_version: z.string().optional(), - if_pricing_version: z.string().optional(), - context: ContextObjectSchema.optional(), - required_policies: z.array(z.string()).optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough(); - -export const ListProductsRequestSchema = z.object({ - adcp_version: z.string().optional(), - adcp_major_version: z.number().optional(), - idempotency_key: z.string().min(16).max(255).regex(/^[A-Za-z0-9_.:-]{16,255}$/).optional(), - context_id: z.string().min(1).optional(), - context: ContextObjectSchema.optional(), - governance_context: z.string().min(1).max(4096).optional(), - push_notification_config: PushNotificationConfigSchema.optional(), - account: CanonicalAccountReferenceSchema.optional(), - brand: BrandKeySchema.optional(), - criteria: ProductDiscoveryCriteriaSchema.optional(), - fields: ProductResponseFieldsSchema.optional(), - cursor: z.string().min(1).optional(), - max_results: z.int().min(1).max(100).optional(), - if_feed_version: z.string().optional(), - if_pricing_version: z.string().optional() -}).passthrough(); - export const ListProductsResponseSchema = z.object({ outcome: z.union([z.literal("listed"), z.literal("unchanged")]).optional(), products: z.array(CanonicalProductSchema).optional(), @@ -18948,7 +19357,7 @@ export const ListProductsResponseSchema = z.object({ ext: ExtensionObjectSchema.optional() }).passthrough()])); -export const MediaBuyCommitmentResponseSchema = z.union([CommittedMediaBuySchema, CommitmentErrorSchema, CommitmentSubmittedSchema]); +export const BuyProductsResponseSchema = MediaBuyCommitmentResponseSchema; export const AcceptProposalResponseSchema = MediaBuyCommitmentResponseSchema; @@ -18994,6 +19403,7 @@ export const UpdateMediaBuyRequestSchema: z.ZodObject<{ [K in keyof UpdateMediaB currency: z.string().regex(/^[A-Z]{3}$/) }).passthrough().optional(), daily_budget_cap: z.number().min(0).optional().nullable(), + frequency_cap: MediaBuyFrequencyCapSchema.optional().nullable(), budget_cap_timezone: z.string().min(1).optional().nullable(), budget_allocation: BudgetAllocationSchema.optional(), pacing: PacingSchema.optional(), @@ -19027,6 +19437,7 @@ export const GetMediaBuysResponseMediaBuySchema: z.ZodType = z.object({ currency: z.string().regex(/^[A-Z]{3}$/), total_budget: z.number().min(0).optional(), daily_budget_cap: z.number().min(0).optional(), + frequency_cap: MediaBuyFrequencyCapSchema.optional(), budget_cap_timezone: z.string().optional(), budget_allocation: BudgetAllocationSchema.optional(), pacing: PacingSchema.optional(), @@ -19109,7 +19520,8 @@ export const GetReportingStatusResponseSchema = z.object({ healthy: z.int().min(0), delayed: z.int().min(0), action_required: z.int().min(0), - complete: z.int().min(0) + complete: z.int().min(0), + consumer_status_pending: z.int().min(0).optional() }).passthrough().optional(), issues: z.array(ReportingStatusIssueSchema).optional(), periods: z.array(ReportingObligationSchema).optional(), @@ -19125,7 +19537,7 @@ export const GetReportingStatusResponseSchema = z.object({ ext: ExtensionObjectSchema.optional() }).passthrough().and(z.union([SuccessfulLookupSchema, FailedLookupSchema])).superRefine((value, ctx) => { // reporting evidence strictness - const closedStructures = {"scope":{"allowedFields":["period_start","period_end","scope_closed","media_buy_ids","all_accessible_media_buys","delivery_config_generations","feed_purposes","finality","ledger_retained_from","coverage_complete"],"requiredFields":["period_start","period_end","scope_closed","all_accessible_media_buys","delivery_config_generations","feed_purposes","finality","ledger_retained_from","coverage_complete"]},"deliveryConfigGeneration":{"allowedFields":["delivery_config_id","delivery_config_version","feed_purpose"],"requiredFields":["delivery_config_id","delivery_config_version","feed_purpose"]},"obligationCounts":{"allowedFields":["total","waiting","healthy","delayed","action_required","complete"],"requiredFields":["total","waiting","healthy","delayed","action_required","complete"]},"pagination":{"allowedFields":["has_more","cursor","total_count"],"requiredFields":["has_more"]},"paginationRequiredByView":{"periods":["has_more","total_count"],"revision":["has_more","total_count"]}} as const; + const closedStructures = {"scope":{"allowedFields":["period_start","period_end","scope_closed","media_buy_ids","all_accessible_media_buys","delivery_config_generations","feed_purposes","finality","ledger_retained_from","coverage_complete"],"requiredFields":["period_start","period_end","scope_closed","all_accessible_media_buys","delivery_config_generations","feed_purposes","finality","ledger_retained_from","coverage_complete"]},"deliveryConfigGeneration":{"allowedFields":["delivery_config_id","delivery_config_version","feed_purpose"],"requiredFields":["delivery_config_id","delivery_config_version","feed_purpose"]},"obligationCounts":{"allowedFields":["total","waiting","healthy","delayed","action_required","complete","consumer_status_pending"],"requiredFields":["total","waiting","healthy","delayed","action_required","complete"]},"pagination":{"allowedFields":["has_more","cursor","total_count"],"requiredFields":["has_more"]},"paginationRequiredByView":{"periods":["has_more","total_count"],"revision":["has_more","total_count"]}} as const; const addIssues = (schema: z.ZodType, candidate: unknown, path: Array) => { const parsed = schema.safeParse(candidate); if (parsed.success) return; @@ -19317,64 +19729,6 @@ export const ListedCreativeCanonicalFormatKindSchema: z.ZodType = z.object({ webhook_activity: z.array(WebhookActivityRecordSchema).max(200).optional() }).passthrough(); -export const CheckGovernanceRequestSchema = z.object({}).passthrough().merge(z.object({ - adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), - adcp_major_version: z.number().int().gte(1).lte(99).optional(), - plan_id: z.string().optional(), - caller: z.string().refine(adcpJsonSchemaUri, "Invalid URI"), - purchase_type: PurchaseTypeSchema.optional(), - target_agent: z.string().refine(adcpJsonSchemaUri, "Invalid URI").optional(), - proposed_commitment: z.object({ - amount: z.number().min(0), - currency: z.string().regex(/^[A-Z]{3}$/) - }).passthrough().optional(), - execution_commitment: z.object({ - amount: z.number().min(0), - currency: z.string().regex(/^[A-Z]{3}$/) - }).passthrough().optional(), - tool: z.string().optional(), - payload: z.object({}).passthrough().optional(), - proposal: CanonicalProposalSchema.optional(), - governance_context: z.string().min(1).max(4096).regex(/^[\x20-\x7E]+$/).optional(), - consultation_context: z.string().min(1).max(255).regex(/^[A-Za-z0-9_.:-]+$/).optional(), - phase: GovernancePhaseSchema.optional(), - planned_delivery: PlannedDeliverySchema.optional(), - delivery_metrics: z.object({ - statement_id: z.string().min(1).max(255).optional(), - statement_digest: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional(), - sequence: z.int().min(1).optional(), - issued_at: z.iso.datetime().optional(), - reporting_period: z.object({ - start: z.iso.datetime(), - end: z.iso.datetime() - }).passthrough(), - spend: z.number().min(0).optional(), - cumulative_spend: z.number().min(0).optional(), - currency: z.string().regex(/^[A-Z]{3}$/).optional(), - impressions: z.int().min(0).optional(), - cumulative_impressions: z.int().min(0).optional(), - geo_distribution: z.record(z.string(), z.number()).optional(), - channel_distribution: z.record(z.string(), z.number()).optional(), - pacing: z.union([z.literal("ahead"), z.literal("on_track"), z.literal("behind")]).optional(), - audience_distribution: z.object({ - baseline: z.union([z.literal("census"), z.literal("platform"), z.literal("custom")]), - baseline_description: z.string().optional(), - indices: z.record(z.string(), z.number()), - cumulative_indices: z.record(z.string(), z.number()).optional() - }).passthrough().optional() - }).passthrough().optional(), - modification_summary: z.string().max(1000).optional(), - runtime_attestations: z.array(AttestationReferenceSchema.and(z.object({ - subject: z.object({ - type: z.literal("resource"), - resource_type: z.literal("https://adcontextprotocol.org/claims/subjects/signal") - }).passthrough().optional() - }).passthrough())).max(10).optional(), - invoice_recipient: BusinessEntitySchema.optional(), - context: ContextObjectSchema.optional(), - ext: ExtensionObjectSchema.optional() -}).passthrough()); - export const SyncPrincipalResponseSchema = z.object({ context_id: z.string().optional(), context: ContextObjectSchema.optional(), @@ -19436,8 +19790,10 @@ export const ComplyTestControllerRequestSchema: z.ZodObject, Exclude>> : z.ZodType }, z.core.$loose> & z.ZodType, CreateMediaBuyRequest & Record> = z.object({ adcp_version: z.string().regex(new RegExp("^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?)?$")).optional(), @@ -19560,6 +19914,7 @@ export const CreateMediaBuyRequestSchema: z.ZodObject<{ [K in keyof CreateMediaB currency: z.string().regex(/^[A-Z]{3}$/) }).passthrough().optional(), daily_budget_cap: z.number().min(0).optional(), + frequency_cap: MediaBuyFrequencyCapSchema.optional(), budget_cap_timezone: z.string().min(1).optional(), budget_allocation: BudgetAllocationSchema.optional(), packages: z.array(PackageRequestSchema).optional(), diff --git a/src/lib/types/tools.generated.ts b/src/lib/types/tools.generated.ts index 6e8b97c5d..95a1860ed 100644 --- a/src/lib/types/tools.generated.ts +++ b/src/lib/types/tools.generated.ts @@ -129,6 +129,8 @@ import type { FormatIDParameter, FormatReferenceStructuredObject, FrameRateType, + FrequencyCapControlMode, + FrequencyCapMutableField, FrequencyCapScope, GOPType, GenreTaxonomy, @@ -168,6 +170,7 @@ import type { MeasurementTerms, MediaBuyActionMode, MediaBuyAvailableAction, + MediaBuyFrequencyCapControlMode, MediaBuyHealth, MediaBuyStatus, MediaBuyValidAction, @@ -274,7 +277,7 @@ import type { WebhookSecurityMethod, } from './core.generated'; -export type { AccountCurrencyMode, AccountReference, AccountScope, AccountStatus, ActionNotAllowedReason, ActionSource, AdCPProtocol, AdCPSpecialism, AdCPVersionEnvelope, AdvertiserIndustry, AgeDeterminationBasis, AgeVerificationMethod, AssessmentStatus, AssetContentType, AssetVariant, AttestationClaim, AttributionMethodology, AttributionModel, AudienceConstraints, AudienceEvidenceMethodology, AudienceResolutionMethod, AudienceSource, AudienceStatus, AudienceSubjectType, AudioChannelLayout, AudioDistributionType, AuthenticationScheme, AvailabilityStatus, AvailableMetric, BillingParty, BinaryVerdict, BrandAgentType, BrandReference, BrowserFamily, BusinessEntity, C2PAWatermarkAction, CTVAdExperience, CanceledBy, CancellationPolicy, CanonicalFormatAgentPlacementAISurfaceSponsoredPlacement, CanonicalFormatBase, CanonicalFormatCoordinatedPlacements, CanonicalFormatDAASTAudio, CanonicalFormatDisplayTag, CanonicalFormatHTML5Banner, CanonicalFormatHostedAudio, CanonicalFormatHostedVideo, CanonicalFormatImage, CanonicalFormatImageCarousel, CanonicalFormatNativeInFeed, CanonicalFormatOption, CanonicalFormatResponsiveCreative, CanonicalFormatSellerRenderedStatefulDisplay, CanonicalFormatSponsoredPlacementRetailMediaCatalogDriven, CanonicalFormatVASTAudio, CanonicalFormatVASTVideo, CanonicalMediaBuyActionMode, CanonicalMediaBuyActionName, CanonicalProposal, CatalogAction, CatalogItemDeliveryMetrics, CatalogItemStatus, CatalogType, CloudStorageProtocol, CoBrandingRequirement, CollectionCadence, CollectionKind, CollectionRelationship, CollectionStatus, CompletionSource, ConsentBasis, ContentIDType, ContentRatingSystem, CountryFusedPostalCodeSystem, CreativeAction, CreativeActivationMethod, CreativeAgentCapability, CreativeApprovalStatus, CreativeAsset, CreativeBrief, CreativeEventReasonCode, CreativeIdentifierType, CreativeMotionLevel, CreativeQuality, CreativeSelectionStrategy, CreativeSortField, CreativeStatus, DAASTTrackingEvent, DAASTVersion, DOOHMotionType, DayOfWeek, DaypartTimezoneMode, DelegationAuthority, DeliveryMetricAggregate, DeliveryMetrics, DeliveryRecipientCloud, DeliveryStatus, DeliveryType, DemographicSystem, DerivativeType, DevicePlatform, DeviceType, DigitalSourceType, DimensionUnit, DisclosurePersistence, DisclosurePosition, DistanceUnit, DistributionIdentifierType, EmbeddedProvenanceMethod, ErrorCode, ErrorScope, EscalationSeverity, EventType, Exclusivity, ExtensionObject, FeatureCheckStatus, FeedFormat, FeedbackSource, Fixed, ForecastMethod, ForecastPoint, ForecastRangeUnit, ForecastableMetric, Format, FormatIDParameter, FormatReferenceStructuredObject, FrameRateType, FrequencyCapScope, GOPType, GenreTaxonomy, GeoDeliveryMetrics, GeographicTargetingLevel, GetProductsAsyncSubmitted, GovernanceDecision, GovernanceDomain, GovernanceMode, GovernancePhase, HTTPMethod, HistoryEntryType, ImageAsset, ImpairmentOfflineState, ImpairmentReasonCode, IndicatorType, InstallmentStatus, JavaScriptModuleType, KeywordDeliveryMetrics, LandingPageRequirement, LiftDimension, LogoSlot, MacroDialectFamily, MacroMappingStatus, MacroProcessingActor, MacroProcessingOperation, MacroResolutionReason, MacroValueContext, MakegoodRemedy, MarkdownFlavor, MatchIDType, MatchType, MeasurementTerms, MediaBuyActionMode, MediaBuyAvailableAction, MediaBuyHealth, MediaBuyStatus, MediaBuyValidAction, MediaChannel, MetricScope, MetricType, MetroAreaSystem, MoovAtomPosition, MultiSize, None, NotificationType, OfferingAvailabilityStatus, OutcomeType, Pacing, PackageUpdate, PaymentTerms, PerformanceBaseline, PerformanceStandardMetric, PixelTrackingEvent, PlatformExtensionReference, PolicyCategory, PolicyEnforcementLevel, PostalCodeSystem, PostalCountrySystem, PreviewOutputFormat, PriceAdjustmentKind, PricingModel, PricingStructure, PrincipalKind, ProductAllowedAction, ProductionQuality, PropertyIdentifierTypes, PropertyType, ProposalDeclineReason, ProposalRefinementReason, ProposalStatus, ProtocolEnvelope, Provenance, PublisherIdentifierTypes, PublisherPropertySelector, PurchaseType, ReachAggregation, ReachUnit, ReportingDeliveryMethod, ReportingDestinationSetupState, ReportingFinality, ReportingFrequency, ReportingHealth, RepresentationSelectionStrategy, RequestProposalsResponse, Responsive, RestrictedAttribute, RightType, RightUse, RightsBillingPeriod, RightsConstraint, SISessionStatus, ScanType, ScopedCreativeApproval, SignalAvailabilityType, SignalDefinitionEnrichment, SignalSource, SignalTargetingExpression, SignalValueType, SizeModeMutex, SnapshotUnavailableReason, SocialPlacementSurface, SortDirection, SortMetric, SpecialCategory, SponsoredPlacementType, TMPResponseType, TalentRole, TargetingOverlayRequirements, TargetingOverlaySupport, TaskStatus, TaskType, TrackerExecutionActor, TrackerFiringPath, TransportMode, TravelTimeUnit, UIDType, URLAssetType, UniversalMacro, UpdateFrequency, VASTMediaDeliveryMethod, VASTTrackingEvent, VASTVersion, ValidationMode, VendorRelationship, VideoPlacementType, ViewThresholdBasis, ViewabilityStandard, WCAGLevel, WarningAffectedResource, WarningCode, WatermarkMediaType, WebhookResponseType, WebhookSecurityMethod } from './core.generated'; +export type { AccountCurrencyMode, AccountReference, AccountScope, AccountStatus, ActionNotAllowedReason, ActionSource, AdCPProtocol, AdCPSpecialism, AdCPVersionEnvelope, AdvertiserIndustry, AgeDeterminationBasis, AgeVerificationMethod, AssessmentStatus, AssetContentType, AssetVariant, AttestationClaim, AttributionMethodology, AttributionModel, AudienceConstraints, AudienceEvidenceMethodology, AudienceResolutionMethod, AudienceSource, AudienceStatus, AudienceSubjectType, AudioChannelLayout, AudioDistributionType, AuthenticationScheme, AvailabilityStatus, AvailableMetric, BillingParty, BinaryVerdict, BrandAgentType, BrandReference, BrowserFamily, BusinessEntity, C2PAWatermarkAction, CTVAdExperience, CanceledBy, CancellationPolicy, CanonicalFormatAgentPlacementAISurfaceSponsoredPlacement, CanonicalFormatBase, CanonicalFormatCoordinatedPlacements, CanonicalFormatDAASTAudio, CanonicalFormatDisplayTag, CanonicalFormatHTML5Banner, CanonicalFormatHostedAudio, CanonicalFormatHostedVideo, CanonicalFormatImage, CanonicalFormatImageCarousel, CanonicalFormatNativeInFeed, CanonicalFormatOption, CanonicalFormatResponsiveCreative, CanonicalFormatSellerRenderedStatefulDisplay, CanonicalFormatSponsoredPlacementRetailMediaCatalogDriven, CanonicalFormatVASTAudio, CanonicalFormatVASTVideo, CanonicalMediaBuyActionMode, CanonicalMediaBuyActionName, CanonicalProposal, CatalogAction, CatalogItemDeliveryMetrics, CatalogItemStatus, CatalogType, CloudStorageProtocol, CoBrandingRequirement, CollectionCadence, CollectionKind, CollectionRelationship, CollectionStatus, CompletionSource, ConsentBasis, ContentIDType, ContentRatingSystem, CountryFusedPostalCodeSystem, CreativeAction, CreativeActivationMethod, CreativeAgentCapability, CreativeApprovalStatus, CreativeAsset, CreativeBrief, CreativeEventReasonCode, CreativeIdentifierType, CreativeMotionLevel, CreativeQuality, CreativeSelectionStrategy, CreativeSortField, CreativeStatus, DAASTTrackingEvent, DAASTVersion, DOOHMotionType, DayOfWeek, DaypartTimezoneMode, DelegationAuthority, DeliveryMetricAggregate, DeliveryMetrics, DeliveryRecipientCloud, DeliveryStatus, DeliveryType, DemographicSystem, DerivativeType, DevicePlatform, DeviceType, DigitalSourceType, DimensionUnit, DisclosurePersistence, DisclosurePosition, DistanceUnit, DistributionIdentifierType, EmbeddedProvenanceMethod, ErrorCode, ErrorScope, EscalationSeverity, EventType, Exclusivity, ExtensionObject, FeatureCheckStatus, FeedFormat, FeedbackSource, Fixed, ForecastMethod, ForecastPoint, ForecastRangeUnit, ForecastableMetric, Format, FormatIDParameter, FormatReferenceStructuredObject, FrameRateType, FrequencyCapControlMode, FrequencyCapMutableField, FrequencyCapScope, GOPType, GenreTaxonomy, GeoDeliveryMetrics, GeographicTargetingLevel, GetProductsAsyncSubmitted, GovernanceDecision, GovernanceDomain, GovernanceMode, GovernancePhase, HTTPMethod, HistoryEntryType, ImageAsset, ImpairmentOfflineState, ImpairmentReasonCode, IndicatorType, InstallmentStatus, JavaScriptModuleType, KeywordDeliveryMetrics, LandingPageRequirement, LiftDimension, LogoSlot, MacroDialectFamily, MacroMappingStatus, MacroProcessingActor, MacroProcessingOperation, MacroResolutionReason, MacroValueContext, MakegoodRemedy, MarkdownFlavor, MatchIDType, MatchType, MeasurementTerms, MediaBuyActionMode, MediaBuyAvailableAction, MediaBuyFrequencyCapControlMode, MediaBuyHealth, MediaBuyStatus, MediaBuyValidAction, MediaChannel, MetricScope, MetricType, MetroAreaSystem, MoovAtomPosition, MultiSize, None, NotificationType, OfferingAvailabilityStatus, OutcomeType, Pacing, PackageUpdate, PaymentTerms, PerformanceBaseline, PerformanceStandardMetric, PixelTrackingEvent, PlatformExtensionReference, PolicyCategory, PolicyEnforcementLevel, PostalCodeSystem, PostalCountrySystem, PreviewOutputFormat, PriceAdjustmentKind, PricingModel, PricingStructure, PrincipalKind, ProductAllowedAction, ProductionQuality, PropertyIdentifierTypes, PropertyType, ProposalDeclineReason, ProposalRefinementReason, ProposalStatus, ProtocolEnvelope, Provenance, PublisherIdentifierTypes, PublisherPropertySelector, PurchaseType, ReachAggregation, ReachUnit, ReportingDeliveryMethod, ReportingDestinationSetupState, ReportingFinality, ReportingFrequency, ReportingHealth, RepresentationSelectionStrategy, RequestProposalsResponse, Responsive, RestrictedAttribute, RightType, RightUse, RightsBillingPeriod, RightsConstraint, SISessionStatus, ScanType, ScopedCreativeApproval, SignalAvailabilityType, SignalDefinitionEnrichment, SignalSource, SignalTargetingExpression, SignalValueType, SizeModeMutex, SnapshotUnavailableReason, SocialPlacementSurface, SortDirection, SortMetric, SpecialCategory, SponsoredPlacementType, TMPResponseType, TalentRole, TargetingOverlayRequirements, TargetingOverlaySupport, TaskStatus, TaskType, TrackerExecutionActor, TrackerFiringPath, TransportMode, TravelTimeUnit, UIDType, URLAssetType, UniversalMacro, UpdateFrequency, VASTMediaDeliveryMethod, VASTTrackingEvent, VASTVersion, ValidationMode, VendorRelationship, VideoPlacementType, ViewThresholdBasis, ViewabilityStandard, WCAGLevel, WarningAffectedResource, WarningCode, WatermarkMediaType, WebhookResponseType, WebhookSecurityMethod } from './core.generated'; // Tool Parameter and Response Types // Generated from official AdCP schemas @@ -558,328 +561,257 @@ export type AttestationIssuer = AttestationBrandIssuer | AttestationAgentIssuer /** * Concrete delivery constraints the buyer expects to carry into create_media_buy. Buyers SHOULD use this field instead of putting equivalent exact targeting only in brief prose. Sellers evaluate these constraints during discovery and scope returned pricing and forecasts to the effective targeting. If a product cannot honor the request exactly, the seller may omit it or return a request-scoped configured product with Product targeting_resolution modifications. Absence of Product targeting_resolution means exact acceptance of this structured overlay; it does not confirm how targeting in the brief was interpreted. On refine, presence is complete replacement state for returned configurations; when omitted, each referenced product's bound targeting remains in force. */ -export type TargetingOverlay = { -} & { - /** - * Restrict delivery to specific countries. ISO 3166-1 alpha-2 codes (e.g., 'US', 'GB', 'DE'). - * - * @minItems 1 - */ - geo_countries?: [string, ...string[]]; - /** - * Exclude specific countries from delivery. ISO 3166-1 alpha-2 codes (e.g., 'US', 'GB', 'DE'). - * - * @minItems 1 - */ - geo_countries_exclude?: [string, ...string[]]; - /** - * Restrict delivery to exact canonical ISO 3166-2 subdivisions (states, provinces, regions, departments, or other subdivision categories). Unknown identifiers are invalid. At create or update, sellers MUST reject unsupported identifiers and MUST NOT silently widen, drop, or partially apply the list. During get_products, a seller may instead return a sparse, buyer-reviewable targeting_resolution modification for a valid but unsupported requested outcome. Exact internal translation preserves accepted identifiers in package readback. - * - * @minItems 1 - */ - geo_regions?: [string, ...string[]]; - /** - * Exclude exact canonical ISO 3166-2 subdivisions. Support is independent from geo_regions inclusion support. Unknown identifiers and values also present in geo_regions are invalid. At create or update, sellers MUST reject unsupported identifiers and partial application; during get_products, a seller may instead return a sparse, buyer-reviewable targeting_resolution modification for a valid but unsupported requested outcome. - * - * @minItems 1 - */ - geo_regions_exclude?: [string, ...string[]]; - /** - * Restrict delivery to specific metro areas. Each entry specifies the classification system and target values. Seller must declare supported systems in get_adcp_capabilities. - * - * @minItems 1 - */ - geo_metros?: [ - { - system: MetroAreaSystem; - /** - * Metro codes within the system (e.g., ['501', '602'] for Nielsen DMAs) - * - * @minItems 1 - */ - values: [string, ...string[]]; - }, - ...{ - system: MetroAreaSystem; +export type TargetingOverlay = TargetingUnknownAgeEligibilityConstraint & + TargetingVerifiedAgeBasisConstraint & { + /** + * Restrict delivery to specific countries. ISO 3166-1 alpha-2 codes (e.g., 'US', 'GB', 'DE'). + * + * @minItems 1 + */ + geo_countries?: [string, ...string[]]; + /** + * Exclude specific countries from delivery. ISO 3166-1 alpha-2 codes (e.g., 'US', 'GB', 'DE'). + * + * @minItems 1 + */ + geo_countries_exclude?: [string, ...string[]]; + /** + * Restrict delivery to exact canonical ISO 3166-2 subdivisions (states, provinces, regions, departments, or other subdivision categories). Unknown identifiers are invalid. At create or update, sellers MUST reject unsupported identifiers and MUST NOT silently widen, drop, or partially apply the list. During get_products, a seller may instead return a sparse, buyer-reviewable targeting_resolution modification for a valid but unsupported requested outcome. Exact internal translation preserves accepted identifiers in package readback. + * + * @minItems 1 + */ + geo_regions?: [string, ...string[]]; + /** + * Exclude exact canonical ISO 3166-2 subdivisions. Support is independent from geo_regions inclusion support. Unknown identifiers and values also present in geo_regions are invalid. At create or update, sellers MUST reject unsupported identifiers and partial application; during get_products, a seller may instead return a sparse, buyer-reviewable targeting_resolution modification for a valid but unsupported requested outcome. + * + * @minItems 1 + */ + geo_regions_exclude?: [string, ...string[]]; + geo_metros?: TargetingGeoMetros; + /** + * Exclude specific metro areas from delivery. Each entry specifies the classification system and excluded values. Seller must declare supported systems in get_adcp_capabilities. + * + * @minItems 1 + */ + geo_metros_exclude?: [ + { + system: MetroAreaSystem; + /** + * Metro codes to exclude within the system (e.g., ['501', '602'] for Nielsen DMAs) + * + * @minItems 1 + */ + values: [string, ...string[]]; + }, + ...{ + system: MetroAreaSystem; + /** + * Metro codes to exclude within the system (e.g., ['501', '602'] for Nielsen DMAs) + * + * @minItems 1 + */ + values: [string, ...string[]]; + }[] + ]; + /** + * Restrict delivery to specific postal areas. Prefer the native country + postal system form. The deprecated legacy country-fused postal-system tokens remain accepted for compatibility. Seller must declare supported systems in get_adcp_capabilities. + * + * @minItems 1 + */ + geo_postal_areas?: [PostalArea, ...PostalArea[]]; + /** + * Exclude specific postal areas from delivery. Prefer the native country + postal system form. The deprecated legacy country-fused postal-system tokens remain accepted for compatibility. Seller must declare supported systems in get_adcp_capabilities. + * + * @minItems 1 + */ + geo_postal_areas_exclude?: [PostalArea, ...PostalArea[]]; + /** + * Restrict delivery to catalog-backed named places. Values MUST be stable identifiers in the declared system, not display names. Sellers must declare supported systems, countries, and place types in get_adcp_capabilities and reject unsupported entries rather than silently dropping them. + * + * @minItems 1 + */ + geo_places?: [GeographicPlaceArea, ...GeographicPlaceArea[]]; + /** + * Exclude catalog-backed named places. Uses the same identifier-based shape as geo_places. Sellers MUST reject overlap with geo_places for the same country, system, place_type, and value. + * + * @minItems 1 + */ + geo_places_exclude?: [GeographicPlaceArea, ...GeographicPlaceArea[]]; + /** + * Restrict delivery to specific time windows. Each entry specifies days of week, an hour range, and an optional timezone that defaults to inventory_local. A concrete IANA zone uses one shared civil-time clock, while inventory_local evaluates each inventory unit in its seller-assigned local timezone. Entries are independent and MAY use different clocks. + * + * @minItems 1 + */ + daypart_targets?: [DaypartTarget, ...DaypartTarget[]]; + /** + * @deprecated + * Deprecated: Use TMP provider fields instead. AXE segment ID to include for targeting. + */ + axe_include_segment?: string; + /** + * @deprecated + * Deprecated: Use TMP provider fields instead. AXE segment ID to exclude from targeting. + */ + axe_exclude_segment?: string; + /** + * Restrict delivery to members of these first-party CRM audiences. Only users present in the uploaded lists are eligible. References audience_id values from sync_audiences on the same seller account — audience IDs are not portable across sellers. Not for lookalike expansion — express that intent in the campaign brief. Seller must declare support in get_adcp_capabilities. + * + * @minItems 1 + */ + audience_include?: [string, ...string[]]; + /** + * Suppress delivery to members of these first-party CRM audiences. Matched users are excluded regardless of other targeting. References audience_id values from sync_audiences on the same seller account — audience IDs are not portable across sellers. Seller must declare support in get_adcp_capabilities. + * + * @minItems 1 + */ + audience_exclude?: [string, ...string[]]; + signal_targeting_groups?: TargetingSignalGroups; + /** + * @deprecated + * DEPRECATED. Use signal_targeting_groups for package-level signal targeting. Legacy flat signal_targeting remains accepted during the SignalRef migration window but cannot express grouped include/exclude composition or product-scoped pricing. + * + * @minItems 1 + */ + signal_targeting?: [SignalTargeting, ...SignalTargeting[]]; + demographics?: DemographicTargetingIntent; + frequency_cap?: TargetingFrequencyCap; + property_list?: TargetingPropertyList; + property_list_exclude?: PropertyListReference; + collection_list?: TargetingCollectionList; + collection_list_exclude?: CollectionListReference; + placement_selection?: PlacementSelection; + collection_selection?: TargetingCollectionSelection; + /** + * Age restriction for compliance. Use for legal requirements (alcohol, gambling), not audience targeting. + */ + age_restriction?: { /** - * Metro codes within the system (e.g., ['501', '602'] for Nielsen DMAs) - * - * @minItems 1 + * Minimum age required */ - values: [string, ...string[]]; - }[] - ]; - /** - * Exclude specific metro areas from delivery. Each entry specifies the classification system and excluded values. Seller must declare supported systems in get_adcp_capabilities. - * - * @minItems 1 - */ - geo_metros_exclude?: [ - { - system: MetroAreaSystem; + min: number; /** - * Metro codes to exclude within the system (e.g., ['501', '602'] for Nielsen DMAs) - * - * @minItems 1 + * Whether verified age (not inferred) is required for compliance */ - values: [string, ...string[]]; - }, - ...{ - system: MetroAreaSystem; + verification_required?: boolean; /** - * Metro codes to exclude within the system (e.g., ['501', '602'] for Nielsen DMAs) + * Accepted verification methods. If omitted, any method the platform supports is acceptable. * * @minItems 1 */ - values: [string, ...string[]]; - }[] - ]; - /** - * Restrict delivery to specific postal areas. Prefer the native country + postal system form. The deprecated legacy country-fused postal-system tokens remain accepted for compatibility. Seller must declare supported systems in get_adcp_capabilities. - * - * @minItems 1 - */ - geo_postal_areas?: [PostalArea, ...PostalArea[]]; - /** - * Exclude specific postal areas from delivery. Prefer the native country + postal system form. The deprecated legacy country-fused postal-system tokens remain accepted for compatibility. Seller must declare supported systems in get_adcp_capabilities. - * - * @minItems 1 - */ - geo_postal_areas_exclude?: [PostalArea, ...PostalArea[]]; - /** - * Restrict delivery to catalog-backed named places. Values MUST be stable identifiers in the declared system, not display names. Sellers must declare supported systems, countries, and place types in get_adcp_capabilities and reject unsupported entries rather than silently dropping them. - * - * @minItems 1 - */ - geo_places?: [GeographicPlaceArea, ...GeographicPlaceArea[]]; - /** - * Exclude catalog-backed named places. Uses the same identifier-based shape as geo_places. Sellers MUST reject overlap with geo_places for the same country, system, place_type, and value. - * - * @minItems 1 - */ - geo_places_exclude?: [GeographicPlaceArea, ...GeographicPlaceArea[]]; - /** - * Restrict delivery to specific time windows. Each entry specifies days of week, an hour range, and an optional timezone that defaults to inventory_local. A concrete IANA zone uses one shared civil-time clock, while inventory_local evaluates each inventory unit in its seller-assigned local timezone. Entries are independent and MAY use different clocks. - * - * @minItems 1 - */ - daypart_targets?: [DaypartTarget, ...DaypartTarget[]]; - /** - * @deprecated - * Deprecated: Use TMP provider fields instead. AXE segment ID to include for targeting. - */ - axe_include_segment?: string; - /** - * @deprecated - * Deprecated: Use TMP provider fields instead. AXE segment ID to exclude from targeting. - */ - axe_exclude_segment?: string; - /** - * Restrict delivery to members of these first-party CRM audiences. Only users present in the uploaded lists are eligible. References audience_id values from sync_audiences on the same seller account — audience IDs are not portable across sellers. Not for lookalike expansion — express that intent in the campaign brief. Seller must declare support in get_adcp_capabilities. - * - * @minItems 1 - */ - audience_include?: [string, ...string[]]; - /** - * Suppress delivery to members of these first-party CRM audiences. Matched users are excluded regardless of other targeting. References audience_id values from sync_audiences on the same seller account — audience IDs are not portable across sellers. Seller must declare support in get_adcp_capabilities. - * - * @minItems 1 - */ - audience_exclude?: [string, ...string[]]; - signal_targeting_groups?: PackageSignalTargetingGroups; - /** - * @deprecated - * DEPRECATED. Use signal_targeting_groups for package-level signal targeting. Legacy flat signal_targeting remains accepted during the SignalRef migration window but cannot express grouped include/exclude composition or product-scoped pricing. - * - * @minItems 1 - */ - signal_targeting?: [SignalTargeting, ...SignalTargeting[]]; - demographics?: DemographicTargetingIntent; - frequency_cap?: FrequencyCap; - property_list?: PropertyListReference; - property_list_exclude?: PropertyListReference; - collection_list?: CollectionListReference; - collection_list_exclude?: CollectionListReference; - placement_selection?: PlacementSelection; - collection_selection?: CollectionSelection; - /** - * Age restriction for compliance. Use for legal requirements (alcohol, gambling), not audience targeting. - */ - age_restriction?: { + accepted_methods?: [AgeVerificationMethod, ...AgeVerificationMethod[]]; + }; + /** + * Restrict to specific platforms. Use for technical compatibility (app only works on iOS). Values from Sec-CH-UA-Platform standard, extended for CTV. + * + * @minItems 1 + */ + device_platform?: [DevicePlatform, ...DevicePlatform[]]; + /** + * Exclude specific operating-system platforms from delivery. When a platform appears in both device_platform and device_platform_exclude, exclusion wins. Sellers MUST reject a request they cannot enforce rather than silently dropping the exclusion. + * + * @minItems 1 + */ + device_platform_exclude?: [DevicePlatform, ...DevicePlatform[]]; + /** + * Restrict to specific device form factors. Use for campaigns targeting hardware categories rather than operating systems (e.g., mobile-only promotions, CTV campaigns). + * + * @minItems 1 + */ + device_type?: [DeviceType, ...DeviceType[]]; + /** + * Exclude specific device form factors from delivery (e.g., exclude CTV for app-install campaigns). + * + * @minItems 1 + */ + device_type_exclude?: [DeviceType, ...DeviceType[]]; /** - * Minimum age required + * Restrict delivery to specific canonical browser families in the impression delivery and rendering environment, not the post-click landing-page browser. Values MUST NOT be inferred solely from operating system, device, web/mobile-web inventory, or placement. Values in this array use OR semantics. When browser is supplied, families not listed are ineligible: other includes a seller-recognized family that is not explicitly enumerated, while unknown includes a browser the seller cannot classify into a recognized family. When the same family appears in browser and browser_exclude, exclusion wins. Browser and device constraints intersect; a seller that cannot enforce the exact combination MUST exclude or explicitly reconfigure the product during discovery and MUST reject it at create or update rather than silently widening delivery. Browser versions and seller-native IDs are intentionally unsupported. + * + * @minItems 1 */ - min: number; + browser?: [BrowserFamily, ...BrowserFamily[]]; /** - * Whether verified age (not inferred) is required for compliance + * Exclude specific canonical browser families from delivery. other excludes seller-recognized families that are not explicitly enumerated; unknown excludes browsers the seller cannot classify into a recognized family. When the same family appears in browser and browser_exclude, exclusion wins. Sellers MUST reject a request they cannot enforce rather than silently dropping the exclusion. + * + * @minItems 1 */ - verification_required?: boolean; + browser_exclude?: [BrowserFamily, ...BrowserFamily[]]; /** - * Accepted verification methods. If omitted, any method the platform supports is acceptable. + * Target users within store catchment areas from a synced store catalog. Each entry references a store-type catalog and optionally narrows to specific stores or catchment zones. * * @minItems 1 */ - accepted_methods?: [AgeVerificationMethod, ...AgeVerificationMethod[]]; + store_catchments?: [ + { + /** + * Synced store-type catalog ID from sync_catalogs. + */ + catalog_id: string; + /** + * Filter to specific stores within the catalog. Omit to target all stores. + * + * @minItems 1 + */ + store_ids?: [string, ...string[]]; + /** + * Catchment zone IDs to target (e.g., 'walk', 'drive'). Omit to target all catchment zones. + * + * @minItems 1 + */ + catchment_ids?: [string, ...string[]]; + }, + ...{ + /** + * Synced store-type catalog ID from sync_catalogs. + */ + catalog_id: string; + /** + * Filter to specific stores within the catalog. Omit to target all stores. + * + * @minItems 1 + */ + store_ids?: [string, ...string[]]; + /** + * Catchment zone IDs to target (e.g., 'walk', 'drive'). Omit to target all catchment zones. + * + * @minItems 1 + */ + catchment_ids?: [string, ...string[]]; + }[] + ]; + /** + * Target users within travel time, distance, or a custom boundary around arbitrary geographic points. Multiple entries use OR semantics — a user within range of any listed point is eligible. For campaigns targeting 10+ locations, consider using store_catchments with a location catalog instead. Seller must declare support in get_adcp_capabilities. + * + * @minItems 1 + */ + geo_proximity?: [ + ( + | { + } + | { + } + | { + } + ), + ...( + | { + } + | { + } + | { + } + )[] + ]; + language?: TargetingLanguages; + keyword_targets?: TargetingKeywords; + negative_keywords?: TargetingNegativeKeywords; }; - /** - * Restrict to specific platforms. Use for technical compatibility (app only works on iOS). Values from Sec-CH-UA-Platform standard, extended for CTV. - * - * @minItems 1 - */ - device_platform?: [DevicePlatform, ...DevicePlatform[]]; - /** - * Exclude specific operating-system platforms from delivery. When a platform appears in both device_platform and device_platform_exclude, exclusion wins. Sellers MUST reject a request they cannot enforce rather than silently dropping the exclusion. - * - * @minItems 1 - */ - device_platform_exclude?: [DevicePlatform, ...DevicePlatform[]]; - /** - * Restrict to specific device form factors. Use for campaigns targeting hardware categories rather than operating systems (e.g., mobile-only promotions, CTV campaigns). - * - * @minItems 1 - */ - device_type?: [DeviceType, ...DeviceType[]]; - /** - * Exclude specific device form factors from delivery (e.g., exclude CTV for app-install campaigns). - * - * @minItems 1 - */ - device_type_exclude?: [DeviceType, ...DeviceType[]]; - /** - * Restrict delivery to specific canonical browser families in the impression delivery and rendering environment, not the post-click landing-page browser. Values MUST NOT be inferred solely from operating system, device, web/mobile-web inventory, or placement. Values in this array use OR semantics. When browser is supplied, families not listed are ineligible: other includes a seller-recognized family that is not explicitly enumerated, while unknown includes a browser the seller cannot classify into a recognized family. When the same family appears in browser and browser_exclude, exclusion wins. Browser and device constraints intersect; a seller that cannot enforce the exact combination MUST exclude or explicitly reconfigure the product during discovery and MUST reject it at create or update rather than silently widening delivery. Browser versions and seller-native IDs are intentionally unsupported. - * - * @minItems 1 - */ - browser?: [BrowserFamily, ...BrowserFamily[]]; - /** - * Exclude specific canonical browser families from delivery. other excludes seller-recognized families that are not explicitly enumerated; unknown excludes browsers the seller cannot classify into a recognized family. When the same family appears in browser and browser_exclude, exclusion wins. Sellers MUST reject a request they cannot enforce rather than silently dropping the exclusion. - * - * @minItems 1 - */ - browser_exclude?: [BrowserFamily, ...BrowserFamily[]]; - /** - * Target users within store catchment areas from a synced store catalog. Each entry references a store-type catalog and optionally narrows to specific stores or catchment zones. - * - * @minItems 1 - */ - store_catchments?: [ - { - /** - * Synced store-type catalog ID from sync_catalogs. - */ - catalog_id: string; - /** - * Filter to specific stores within the catalog. Omit to target all stores. - * - * @minItems 1 - */ - store_ids?: [string, ...string[]]; - /** - * Catchment zone IDs to target (e.g., 'walk', 'drive'). Omit to target all catchment zones. - * - * @minItems 1 - */ - catchment_ids?: [string, ...string[]]; - }, - ...{ - /** - * Synced store-type catalog ID from sync_catalogs. - */ - catalog_id: string; - /** - * Filter to specific stores within the catalog. Omit to target all stores. - * - * @minItems 1 - */ - store_ids?: [string, ...string[]]; - /** - * Catchment zone IDs to target (e.g., 'walk', 'drive'). Omit to target all catchment zones. - * - * @minItems 1 - */ - catchment_ids?: [string, ...string[]]; - }[] - ]; - /** - * Target users within travel time, distance, or a custom boundary around arbitrary geographic points. Multiple entries use OR semantics — a user within range of any listed point is eligible. For campaigns targeting 10+ locations, consider using store_catchments with a location catalog instead. Seller must declare support in get_adcp_capabilities. - * - * @minItems 1 - */ - geo_proximity?: [ - ( - | { - } - | { - } - | { - } - ), - ...( - | { - } - | { - } - | { - } - )[] - ]; - /** - * Restrict to users with specific language preferences using canonical BCP 47 language ranges. Each buyer range is evaluated against a user's language-preference tag with RFC 4647 section 3.3.1 Basic Filtering: 'fr' matches 'fr', 'fr-CA', and 'fr-FR', while 'fr-CA' matches 'fr-CA' and more-specific descendants but not 'fr' or 'fr-FR'. Values use OR logic. - * - * @minItems 1 - */ - language?: [LanguageTag, ...LanguageTag[]]; - /** - * Keyword targeting for search and retail media platforms. Restricts delivery to queries matching the specified keywords. Each keyword is identified by the tuple (keyword, match_type) — the same keyword string with different match types are distinct targets. Sellers SHOULD reject duplicate (keyword, match_type) pairs within a single request. Seller must declare support in get_adcp_capabilities. - * - * @minItems 1 - */ - keyword_targets?: [ - { - /** - * The keyword to target - */ - keyword: string; - match_type: MatchType; - /** - * Per-keyword bid price, denominated in the same currency as the package's pricing option. Overrides the package-level bid_price for this keyword. Inherits the max_bid interpretation from the pricing option: when max_bid is true, this is the keyword's bid ceiling; when false, this is the exact bid. If omitted, the package bid_price applies. - */ - bid_price?: number; - }, - ...{ - /** - * The keyword to target - */ - keyword: string; - match_type: MatchType; - /** - * Per-keyword bid price, denominated in the same currency as the package's pricing option. Overrides the package-level bid_price for this keyword. Inherits the max_bid interpretation from the pricing option: when max_bid is true, this is the keyword's bid ceiling; when false, this is the exact bid. If omitted, the package bid_price applies. - */ - bid_price?: number; - }[] - ]; - /** - * Keywords to exclude from delivery. Queries matching these keywords will not trigger the ad. Each negative keyword is identified by the tuple (keyword, match_type). Seller must declare support in get_adcp_capabilities. - * - * @minItems 1 - */ - negative_keywords?: [ - { - /** - * The keyword to exclude - */ - keyword: string; - match_type: MatchType; - }, - ...{ - /** - * The keyword to exclude - */ - keyword: string; - match_type: MatchType; - }[] - ]; -}; +/** + * Restrict delivery to specific metro areas. Each entry specifies the classification system and target values. Seller must declare supported systems in get_adcp_capabilities. + * + * @minItems 1 + */ +export type TargetingGeoMetros = [GeoMetro, ...GeoMetro[]]; /** * A catalog-backed named place target. Values are stable identifiers in the declared system. Entries within geo_places form a union; different geographic inclusion dimensions intersect. value_labels are diagnostic only and MUST NOT be used to resolve targeting. */ @@ -1077,9 +1009,9 @@ export type DemographicAgeRange = { include_unknown: boolean; }; /** - * Frequency capping settings for package-level application. Two types of frequency control can be used independently or together: suppress enforces a cooldown between consecutive exposures; max_impressions + per + window caps total exposures per entity in a time window. When both suppress and max_impressions are set, an impression is delivered only if both constraints permit it (AND semantics). At least one of suppress, suppress_minutes, or max_impressions must be set. + * Frequency capping settings for package-level application. Two types of frequency control can be used independently or together: suppress enforces a cooldown between consecutive exposures; max_impressions + per + window caps total exposures per entity in a time window. When both suppress and max_impressions are set, an impression is delivered only if both constraints permit it (AND semantics). At least one of suppress, suppress_minutes, or max_impressions must be set. Field location determines scope; this value has no scope discriminator. The MediaBuy root uses the narrower media-buy-frequency-cap schema, which permits maximum impressions only in 3.2. */ -export type FrequencyCap = { +export type TargetingFrequencyCap = { } & { /** * Cooldown period between consecutive exposures to the same entity. Prevents back-to-back ad delivery (e.g. {"interval": 60, "unit": "minutes"} for a 1-hour cooldown). Preferred over suppress_minutes. @@ -1091,7 +1023,7 @@ export type FrequencyCap = { */ suppress_minutes?: number; /** - * Maximum number of impressions per entity per window. For duration windows, implementations typically use a rolling window; 'campaign' applies a fixed cap across the full flight. + * Maximum number of impressions per entity per window. For duration windows, implementations typically use a rolling window. campaign applies across the owning field's full flight: the package flight for a targeting overlay, or the MediaBuy flight for a root cap. */ max_impressions?: number; /** @@ -1104,7 +1036,7 @@ export type FrequencyCap = { window?: Duration; }; /** - * Purchased placement selection within the product. This constrains package inventory; it is distinct from creative_assignments[].placement_refs, which only route individual creatives within the purchased set. On create, mode selected supplies the complete selected set and mode default uses the product default. On update, the surrounding targeting_overlay replacement semantics apply. + * Purchased placement selection within the product. This constrains package inventory; it is distinct from creative_assignments[].placement_refs, which only route individual creatives within the purchased set. On create, mode selected supplies the complete selected set and mode default uses the product default. In request-side Targeting Input, a non-null value replaces this dimension, omission preserves or inherits it, and null clears it when the product permits that broader inventory set. */ export type PlacementSelection = SelectedPlacements | ProductDefaultPlacements; /** @@ -1112,13 +1044,86 @@ export type PlacementSelection = SelectedPlacements | ProductDefaultPlacements; */ export type PlacementIdentity = PublisherCatalogPlacementIdentity | SellerInlinePlacementIdentity; /** - * Purchased collection selection within the product. On create, mode selected supplies the complete selected set and mode default uses the product's full bundle. On package readback this is the committed selection sellers MUST echo as concrete selectors, materializing any collection_list composition; collection_list fields remain the buyer-managed list mechanism. On update, the surrounding targeting_overlay replacement semantics apply. + * Purchased collection selection within the product. On create, mode selected supplies the complete selected set and mode default uses the product's full bundle. On package readback this is the committed selection sellers MUST echo as concrete selectors, materializing any collection_list composition; collection_list fields remain the buyer-managed list mechanism. In request-side Targeting Input, a non-null value replaces this dimension, omission preserves or inherits it, and null clears it when the product permits that broader inventory set. + */ +export type TargetingCollectionSelection = SelectedCollections | ProductDefaultCollections; +/** + * Restrict to users with specific language preferences using canonical BCP 47 language ranges. Each buyer range is evaluated against a user's language-preference tag with RFC 4647 section 3.3.1 Basic Filtering: 'fr' matches 'fr', 'fr-CA', and 'fr-FR', while 'fr-CA' matches 'fr-CA' and more-specific descendants but not 'fr' or 'fr-FR'. Values use OR logic. + * + * @minItems 1 */ -export type CollectionSelection = SelectedCollections | ProductDefaultCollections; +export type TargetingLanguages = [LanguageTag, ...LanguageTag[]]; /** * A well-formed BCP 47 language tag used by AdCP only as language identity. Script and region may refine that identity; other valid BCP 47 subtags remain part of tag matching but do not make this a general locale-settings object. It does not determine currency, time zone, number/date formatting, market, or legal jurisdiction. The AdCP canonical wire profile requires lower-case language and variants, title-case script, and upper-case region (for example `en-US`, `zh-Hant-TW`, or `x-private`). RFC 5646 comparisons are case-insensitive and its case regularization is optional; AdCP intentionally requires this stricter single wire spelling and receivers MUST reject differently cased tags rather than silently normalizing them. The schema pattern enforces the AdCP casing profile and extension structure for commonly used tags; conforming receivers additionally validate the complete RFC 5646 grammar and registry rules. Every new AdCP field carrying BCP 47 language identity or a concrete language range MUST reference this schema instead of declaring independent string constraints. */ export type LanguageTag = string; +/** + * Keyword targeting for search and retail media platforms. Restricts delivery to queries matching the specified keywords. Each keyword is identified by the tuple (keyword, match_type) — the same keyword string with different match types are distinct targets. Sellers SHOULD reject duplicate (keyword, match_type) pairs within a single request. Seller must declare support in get_adcp_capabilities. + * + * @minItems 1 + */ +export type TargetingKeywords = [ + { + /** + * The keyword to target + */ + keyword: string; + match_type: MatchType; + /** + * Per-keyword bid price, denominated in the same currency as the package's pricing option. Overrides the package-level bid_price for this keyword. Inherits the max_bid interpretation from the pricing option: when max_bid is true, this is the keyword's bid ceiling; when false, this is the exact bid. If omitted, the package bid_price applies. + */ + bid_price?: number; + }, + ...{ + /** + * The keyword to target + */ + keyword: string; + match_type: MatchType; + /** + * Per-keyword bid price, denominated in the same currency as the package's pricing option. Overrides the package-level bid_price for this keyword. Inherits the max_bid interpretation from the pricing option: when max_bid is true, this is the keyword's bid ceiling; when false, this is the exact bid. If omitted, the package bid_price applies. + */ + bid_price?: number; + }[] +]; +/** + * Keywords to exclude from delivery. Queries matching these keywords will not trigger the ad. Each negative keyword is identified by the tuple (keyword, match_type). Seller must declare support in get_adcp_capabilities. + * + * @minItems 1 + */ +export type TargetingNegativeKeywords = [NegativeKeyword, ...NegativeKeyword[]]; +/** + * Concrete aggregate max-impression cap intended for the MediaBuy root. Every returned product must participate in one shared counter for this exact value. Legacy proposals echo it as proposals[].frequency_cap; direct buyers repeat it at purchase. + */ +export type MediaBuyFrequencyCap = FrequencyCap & { +}; +/** + * Frequency capping settings for package-level application. Two types of frequency control can be used independently or together: suppress enforces a cooldown between consecutive exposures; max_impressions + per + window caps total exposures per entity in a time window. When both suppress and max_impressions are set, an impression is delivered only if both constraints permit it (AND semantics). At least one of suppress, suppress_minutes, or max_impressions must be set. Field location determines scope; this value has no scope discriminator. The MediaBuy root uses the narrower media-buy-frequency-cap schema, which permits maximum impressions only in 3.2. + */ +export type FrequencyCap = { +} & { + /** + * Cooldown period between consecutive exposures to the same entity. Prevents back-to-back ad delivery (e.g. {"interval": 60, "unit": "minutes"} for a 1-hour cooldown). Preferred over suppress_minutes. + */ + suppress?: Duration; + /** + * @deprecated + * Deprecated — use suppress instead. Cooldown period in minutes between consecutive exposures to the same entity (e.g. 60 for a 1-hour cooldown). + */ + suppress_minutes?: number; + /** + * Maximum number of impressions per entity per window. For duration windows, implementations typically use a rolling window. campaign applies across the owning field's full flight: the package flight for a targeting overlay, or the MediaBuy flight for a root cap. + */ + max_impressions?: number; + /** + * Entity granularity for impression counting. Required when max_impressions is set. + */ + per?: ReachUnit; + /** + * Time window for the max_impressions cap (e.g. {"interval": 7, "unit": "days"} or {"interval": 1, "unit": "campaign"} for the full flight). Required when max_impressions is set. + */ + window?: Duration; +}; /** * Non-vacuous postal capability used for hard targeting requirements and product overlay support. At least one native system array or true-valued deprecated alias is required. The general seller-capabilities postal schema remains permissive for backward compatibility, but an empty or false-only map cannot satisfy a hard discovery requirement. */ @@ -1135,6 +1140,19 @@ export type PositivePostalAreaSupport = PostalAreaSupport & { ch_plz?: true; at_plz?: true; }; +/** + * A duration unit supported for a frequency-cap window or suppression period. + */ +export type FrequencyCapDurationUnit = 'seconds' | 'minutes' | 'hours' | 'days' | 'campaign'; +/** + * Buyer minimum product-support detail for an aggregate MediaBuy frequency cap. Aggregate support in 3.2 is max-impressions only. + */ +export type MediaBuyFrequencyCapRequirement = FrequencyCapRequirements & { + /** + * @minItems 1 + */ + supported_control_modes?: [MediaBuyFrequencyCapControlMode, ...MediaBuyFrequencyCapControlMode[]]; +}; /** * AdCP 3.x compatibility request for discovering and changing advertising products and proposals. Buyers SHOULD express every campaign constraint that has a structured field in that field rather than relying on prose: structured input is cheaper to transmit, deterministic to process, and avoids lossy inference. Exact targeting_overlay values scope returned products, pricing, and forecasts; required_overlay_support identifies targeting dimensions whose values will be supplied on packages later. Explicit hard targeting stated only in a brief remains binding. AdCP 3.2 introduces the narrower list_products, request_proposals, refine_proposals, and decline_proposals tasks; new callers SHOULD use those tasks while existing get_products payloads remain valid throughout 3.x. */ @@ -1235,10 +1253,12 @@ export interface GetProductsRequest { preferred_delivery_types?: DeliveryType[]; filters?: ProductFilters; targeting_overlay?: TargetingOverlay; + media_buy_frequency_cap?: MediaBuyFrequencyCap; required_overlay_support?: TargetingOverlayRequirements; + required_media_buy_support?: ProductMediaBuySupportRequirements; property_list?: PropertyListReference; /** - * Specific product fields to include in the response. When omitted, all fields are returned. Use for lightweight discovery calls where only a subset of product data is needed. product_id and name are always included. `format_ids` is a deprecated 3.x compatibility projection; new integrations request canonical `format_options`. Safety-critical request-specific fields override projection: Product.targeting_resolution and expires_at MUST be included whenever the seller returns modifications, overlay_support MUST be included when required_overlay_support was requested, list_applications MUST be included when a property or collection list is in the effective targeting, and audience_evidence_selections MUST be included when filters.audience_evidence_requirements affects eligibility or ranking. fields controls the optional audience_evidence payload, not either decision receipt. Response-level brief targeting confirmation is not a projected product field. + * Specific product fields to include in the response. When omitted, all fields are returned. Use for lightweight discovery calls where only a subset of product data is needed. product_id and name are always included. `format_ids` is a deprecated 3.x compatibility projection; new integrations request canonical `format_options`. Safety-critical request-specific fields override projection: Product.targeting_resolution and expires_at MUST be included whenever the seller returns modifications, overlay_support MUST be included when required_overlay_support was requested, media_buy_support MUST be included when required_media_buy_support or media_buy_frequency_cap was requested, list_applications MUST be included when a property or collection list is in the effective targeting, and audience_evidence_selections MUST be included when filters.audience_evidence_requirements affects eligibility or ranking. fields controls the optional audience_evidence payload, not either decision receipt. Response-level brief targeting confirmation is not a projected product field. */ fields?: ( | ( @@ -1264,6 +1284,8 @@ export interface GetProductsRequest { | 'signal_targeting_allowed' | 'signal_targeting_rules' | 'demographic_targeting' + | 'overlay_support' + | 'media_buy_support' | 'audience_evidence' | 'audience_evidence_selections' | 'max_optimization_goals' @@ -1286,6 +1308,7 @@ export interface GetProductsRequest { | 'included_signals' | 'signal_targeting_options' | 'overlay_support' + | 'media_buy_support' | 'targeting_resolution' | 'collections' | 'collection_targeting_allowed' @@ -1304,7 +1327,7 @@ export interface GetProductsRequest { push_notification_config?: PushNotificationConfig; pagination?: PaginationRequest; /** - * Opaque wholesale_feed_version token returned by a prior wholesale-mode get_products response from this agent. Only valid when buying_mode is wholesale. When provided, the seller compares against its current wholesale product feed version for the buyer's cache_scope and MAY return an unchanged: true response (with products omitted) if nothing has changed. The token is scope-keyed: buyers cache `(cache_scope, wholesale_feed_version)` pairs. Scoping dimensions: (agent, buying_mode, filters, targeting_overlay, required_overlay_support, deprecated property_list, catalog) for cache_scope: 'public'; that tuple plus account identity for cache_scope: 'account'. pagination.cursor is NOT part of the scoping tuple. Backward-compatible: pre-v3.1 agents that ignore this field simply return the full payload, same as the unchanged-server path. See specs/wholesale-feed-webhooks.md for the full sync pattern. + * Opaque wholesale_feed_version token returned by a prior wholesale-mode get_products response from this agent. Only valid when buying_mode is wholesale. When provided, the seller compares against its current wholesale product feed version for the buyer's cache_scope and MAY return an unchanged: true response (with products omitted) if nothing has changed. The token is scope-keyed: buyers cache `(cache_scope, wholesale_feed_version)` pairs. Scoping dimensions: (agent, buying_mode, filters, targeting_overlay, media_buy_frequency_cap, required_overlay_support, required_media_buy_support, deprecated property_list, catalog) for cache_scope: 'public'; that tuple plus account identity for cache_scope: 'account'. pagination.cursor is NOT part of the scoping tuple. Backward-compatible: pre-v3.1 agents that ignore this field simply return the full payload, same as the unchanged-server path. See specs/wholesale-feed-webhooks.md for the full sync pattern. */ if_wholesale_feed_version?: string; /** @@ -1976,6 +1999,28 @@ export interface AttestationOriginIssuer { origin: string; ext?: ExtensionObject; } +/** + * Unknown-age delivery cannot satisfy a minimum-age eligibility policy. When demographic audience targeting and age_restriction are both present, include_unknown must be false. + */ +export interface TargetingUnknownAgeEligibilityConstraint { +} +/** + * A legal verification requirement always narrows demographic targeting. When the buyer supplies accepted_bases and age_restriction requires verification, verified must be accepted; otherwise the constraints have an empty intersection and the request is invalid. + */ +export interface TargetingVerifiedAgeBasisConstraint { +} +/** + * A targeted metro area. + */ +export interface GeoMetro { + system: MetroAreaSystem; + /** + * Metro codes within the system (e.g., ['501', '602'] for Nielsen DMAs) + * + * @minItems 1 + */ + values: [string, ...string[]]; +} /** * A time window for daypart targeting. Specifies days of week, an hour range, and the civil-time clock used to evaluate it. start_hour is inclusive, end_hour is exclusive (e.g., 6-10 = 6:00am to 10:00am). Follows the Google Ads AdScheduleInfo / DV360 DayPartTargeting pattern. */ @@ -2006,7 +2051,7 @@ export interface DaypartTarget { /** * Basic Boolean grouping for seller-offered signals. v1 supports a required top-level operator 'all' and child groups with operator 'any' for include groups or 'none' for exclusion groups. Example semantics: group 1 any(A, B) plus group 2 none(C, D) means (A OR B) AND NOT (C OR D). Signal entries reference named signal definitions with signal_ref scope 'product' for product-local signal options or scope 'data_provider' for external signals published in adagents.json signals[]. For simple include-only targeting, send one child group with operator 'any'. Sellers SHOULD reject entries that are not available for the product through inline signal_targeting_options or get_signals, are not active for the account, or exceed the product's signal_targeting_allowed/signal_targeting_rules/product terms. Signal targeting limits are product-scoped, not declared in get_adcp_capabilities, because products may be backed by different ad servers. Sellers MUST echo applied signal_targeting_groups on the resulting package state, including fixed/default selections. Sellers MAY return REQUOTE_REQUIRED when a targeting mutation changes commercial terms. */ -export interface PackageSignalTargetingGroups { +export interface TargetingSignalGroups { /** * Groups-level operator. Required even though v1 only supports 'all': every child group must be satisfied. */ @@ -2043,6 +2088,23 @@ export interface DemographicTargetingIntent { /** * Reference to a property list for targeting specific properties within this product. The package runs on the intersection of the product's publisher_properties and this list. Sellers SHOULD return a validation error if the product has property_targeting_allowed: false. */ +export interface TargetingPropertyList { + /** + * URL of the agent managing the property list + */ + agent_url: string; + /** + * Identifier for the property list within the agent + */ + list_id: string; + /** + * JWT or other authorization token for accessing the list. Optional if the list is public or caller has implicit access. + */ + auth_token?: string; +} +/** + * Reference to a property list whose properties must not carry the buyer's ads. Matched properties are removed from delivery. Use for brand-safety do-not-run lists (apps, sites). Exclude wins on overlap with property_list, and applies regardless of the product's property_targeting_allowed flag. Seller must declare support in get_adcp_capabilities. + */ export interface PropertyListReference { /** * URL of the agent managing the property list @@ -2060,6 +2122,23 @@ export interface PropertyListReference { /** * Reference to a collection list for including specific collections (programs, publications, channels) within this product. The package runs on the intersection of matched collections and this list. Use for inclusion-based collection targeting. Seller must declare support in get_adcp_capabilities. */ +export interface TargetingCollectionList { + /** + * URL of the agent managing the collection list + */ + agent_url: string; + /** + * Identifier for the collection list within the agent + */ + list_id: string; + /** + * JWT or other authorization token for accessing the list. Optional if the list is public or caller has implicit access. + */ + auth_token?: string; +} +/** + * Reference to a collection list for excluding specific collections (programs, publications, channels) from this product. Matched collections must not carry the buyer's ads. Use for brand safety do-not-air lists. Seller must declare support in get_adcp_capabilities. + */ export interface CollectionListReference { /** * URL of the agent managing the collection list @@ -2175,6 +2254,16 @@ export interface ProductDefaultCollections { mode: 'default'; ext?: ExtensionObject; } +/** + * An excluded keyword. + */ +export interface NegativeKeyword { + /** + * The keyword to exclude + */ + keyword: string; + match_type: MatchType; +} /** * Buyer minimum requirements for ISO 3166-2 subdivision values that must remain independently selectable later. Country keys prevent a false cross-country capability claim. all_values requires support for every protocol-valid ISO subdivision active in the seller's support snapshot when the declaration is issued; values requests an exact finite candidate set. Exact delivery values known now belong in get_products.targeting_overlay instead. */ @@ -2325,6 +2414,47 @@ export interface PostalAreaSupport { */ [country: `${Uppercase}`]: ('zip' | 'zip_plus_four' | 'outward' | 'full' | 'fsa' | 'plz' | 'code_postal' | 'postcode' | 'cep' | 'pin' | 'postal_code' | 'custom')[] | undefined; } +/** + * Minimum structured package-cap support. Matches a broad legacy frequency_cap: true or a containing frequency_cap_support object. Mutually exclusive with a frequency_cap: true requirement, which would exclude every constrained product. + */ +export interface FrequencyCapRequirements { + /** + * Require each listed logical field to be mutable after creation. Matches a product whose mutable_fields contains every listed value, or a product that omits mutable_fields, or legacy frequency_cap: true. A product declaring mutable_fields: [] is create-only and never matches a non-empty list. + * + * @minItems 1 + */ + mutable_fields?: [FrequencyCapMutableField, ...FrequencyCapMutableField[]]; + /** + * @minItems 1 + */ + supported_control_modes?: [FrequencyCapControlMode, ...FrequencyCapControlMode[]]; + /** + * @minItems 1 + */ + supported_per_units?: [ReachUnit, ...ReachUnit[]]; + /** + * Require each listed unit to be a supported max_impressions.window unit after seller-wide inheritance. + * + * @minItems 1 + */ + supported_window_units?: [FrequencyCapDurationUnit, ...FrequencyCapDurationUnit[]]; + /** + * Require each listed unit to be a supported suppress unit after seller-wide inheritance. + * + * @minItems 1 + */ + supported_suppression_units?: [FrequencyCapDurationUnit, ...FrequencyCapDurationUnit[]]; +} +/** + * Minimum product participation in shared MediaBuy-level controls. For a frequency cap, every returned product must be composable in one seller-maintained aggregate counter for every requested per unit. On refine, presence is complete replacement state. + */ +export interface ProductMediaBuySupportRequirements { + /** + * Require product participation in one shared MediaBuy frequency-cap counter. + */ + frequency_cap?: true; + frequency_cap_constraints?: MediaBuyFrequencyCapRequirement; +} /** * Optional webhook configuration for async terminal completion/failure notifications on curated discovery. Meaningful only for `buying_mode: "brief"` and `buying_mode: "refine"` requests that enter the async lifecycle. Submitted envelopes with `task_id` remain pollable through `get_task_status` (legacy `tasks/get`) whether or not this field is present. If a brief/refine request includes this field and the seller returns a Submitted envelope, the seller MUST deliver at least the terminal completion/failure notification to the configured URL; intermediate progress notifications are MAY. If the seller cannot honor the webhook channel, it MUST reject the request with a structured error instead of silently accepting. This field does not change wholesale timing semantics: sellers MUST NOT route `buying_mode: "wholesale"` requests through the async/Submitted arm or emit async delivery solely because `push_notification_config` is present; partial wholesale completion is reported via `incomplete[]`. */ @@ -2531,6 +2661,7 @@ export type Product = { signal_targeting_allowed?: boolean; demographic_targeting?: DemographicTargetingCapability; overlay_support?: TargetingOverlaySupport; + media_buy_support?: ProductMediaBuySupport; identity?: ProductIdentity; targeting_resolution?: ProductTargetingResolution; /** @@ -3877,6 +4008,10 @@ export interface ForecastRange { high?: number; } export type VendorMetricID = string; +/** + * The action identifier. Accepts every legacy valid_actions value plus structured-only actions such as update_media_buy_frequency_cap. + */ +export type MediaBuyAvailableActionID = MediaBuyValidAction | 'update_media_buy_frequency_cap'; /** * Optional advisory machine-readable bounds buyers can use during product selection. The proposal must restate any binding bounds in commercial_terms.change_terms[].constraints. */ @@ -4264,6 +4399,124 @@ export type VendorPricingOption = { * Pricing model for a vendor service. Discriminated by model: 'cpm' (fixed CPM), 'percent_of_media' (percentage of spend with optional CPM cap), 'flat_fee' (fixed charge per reporting period), 'per_unit' (fixed price per unit of work), or 'custom' (escape hatch for models not covered by the enumerated forms — requires a description and structured metadata). */ export type VendorPricing = CpmPricing | PercentOfMediaPricing | FlatFeePricing | PerUnitPricing | CustomPricing; +/** + * Structured frequency-cap constraints. Count and duration declarations are exact: each uses either an exhaustive preset list or an inclusive range, never a unit-only promise. At product scope, omitted fields inherit the applicable seller-wide capability and never broaden it. Product mutability describes implementation capability; MediaBuy.available_actions remains authoritative for a live buy. + */ +export type FrequencyCapConstraints = { +} & { + /** + * Logical cap fields that can change after creation. An empty array means create-only. For example, [max_impressions] permits changing the count while keeping per and window fixed. Omission means update support is undeclared and the legacy broad meaning applies. + */ + mutable_fields?: FrequencyCapMutableField[]; + /** + * FrequencyCap shapes accepted by the product. max_impressions_and_suppress means both controls may appear together and are enforced with AND semantics. + * + * @minItems 1 + */ + supported_control_modes?: [FrequencyCapControlMode, ...FrequencyCapControlMode[]]; + /** + * Entity granularities accepted by max_impressions caps. + * + * @minItems 1 + */ + supported_per_units?: [ReachUnit, ...ReachUnit[]]; + max_impressions_constraints?: FrequencyCapImpressionConstraints; + /** + * Exact supported max_impressions.window intervals, one entry per duration unit. + * + * @minItems 1 + */ + window_constraints?: [FrequencyCapIntervalConstraints, ...FrequencyCapIntervalConstraints[]]; + /** + * Exact supported suppress cooldown intervals, one entry per duration unit. + * + * @minItems 1 + */ + suppression_constraints?: [FrequencyCapIntervalConstraints, ...FrequencyCapIntervalConstraints[]]; + ext?: ExtensionObject; +}; +/** + * Exact supported max_impressions presets or range. + */ +export type FrequencyCapImpressionConstraints = { + minimum?: number; + maximum?: number; + /** + * @minItems 1 + */ + allowed_values?: [number, ...number[]]; + ext?: ExtensionObject; +} & { +}; +/** + * Exact supported intervals for one duration unit, declared as either an exhaustive preset list or an inclusive integer range. The two forms are mutually exclusive. + */ +export type FrequencyCapIntervalConstraints = { + unit: FrequencyCapDurationUnit; + minimum_interval?: number; + maximum_interval?: number; + /** + * @minItems 1 + */ + allowed_intervals?: [number, ...number[]]; + ext?: ExtensionObject; +} & ( + | { + } + | { + } +) & { + unit: FrequencyCapDurationUnit; + minimum_interval?: number; + maximum_interval?: number; + /** + * @minItems 1 + */ + allowed_intervals?: [number, ...number[]]; + ext?: ExtensionObject; + } & ( + | { + } + | { + } + ) & { + unit: FrequencyCapDurationUnit; + minimum_interval?: number; + maximum_interval?: number; + /** + * @minItems 1 + */ + allowed_intervals?: [number, ...number[]]; + ext?: ExtensionObject; + } & ( + | { + } + | { + } + ) & { + unit: FrequencyCapDurationUnit; + minimum_interval?: number; + maximum_interval?: number; + /** + * @minItems 1 + */ + allowed_intervals?: [number, ...number[]]; + ext?: ExtensionObject; + } & ( + | { + } + | { + } + ); +/** + * Optional product support detail for aggregate MediaBuy frequency caps. Aggregate support in 3.2 is max-impressions only. + */ +export type MediaBuyFrequencyCapSupport = FrequencyCapConstraints & { + /** + * @minItems 1 + */ + supported_control_modes?: [MediaBuyFrequencyCapControlMode, ...MediaBuyFrequencyCapControlMode[]]; +}; /** * Sparse, buyer-reviewable change from targeting requested in get_products to targeting bound to a returned configured product. Entries are applied in array order to the original targeting_overlay; after every entry, the complete result MUST validate against targeting.json. A seller MUST NOT emit two replace operations for the same path or combine replace and remove_values on the same path. Selecting the configured product_id accepts the ordered result. */ @@ -4841,6 +5094,7 @@ export type Proposal = { */ budget_allocation?: BudgetAllocation; pacing?: Pacing; + frequency_cap?: MediaBuyFrequencyCap; proposal_status?: ProposalStatus; /** * When this proposal expires and can no longer be executed. For draft proposals, indicates when indicative pricing becomes stale. For committed proposals, indicates when the inventory hold lapses — the buyer must call create_media_buy before this time. @@ -5145,7 +5399,7 @@ export interface GetProductsResponse { }; }; /** - * Optional array of proposed media plans with budget allocations across products. Publishers include proposals when they can provide strategic guidance based on the brief. Proposals are actionable - buyers can refine them via follow-up get_products calls within the same session, or execute them directly via create_media_buy. + * Optional legacy proposed media plans. When the request carries media_buy_frequency_cap, every returned proposal echoes the bound value as proposal.frequency_cap. Buyers may refine or execute a committed proposal by ID. */ proposals?: Proposal[]; /** @@ -5283,7 +5537,7 @@ export interface GetProductsResponse { }; pagination?: PaginationResponse; /** - * Opaque token representing the version of the wholesale product feed state used to compose this response. Sellers that implement conditional-fetch (if_wholesale_feed_version) MUST return this on every wholesale-mode response so buyers can cache and probe later. Buyers MUST treat the value as opaque — no format, no ordering, no inspection. The token is scope-keyed: it describes a version for the cache_scope declared on this response, NOT a global agent version. A buyer caches `(cache_scope, wholesale_feed_version)` pairs and presents the matching token on the next request. Scoping dimensions: (agent, buying_mode, filters, targeting_overlay, required_overlay_support, deprecated property_list, catalog) for cache_scope: 'public'; that tuple plus account_id for cache_scope: 'account'. pagination.cursor is NOT part of the scoping tuple. See specs/wholesale-feed-webhooks.md for the full cache layering model. + * Opaque token representing the version of the wholesale product feed state used to compose this response. Sellers that implement conditional-fetch (if_wholesale_feed_version) MUST return this on every wholesale-mode response so buyers can cache and probe later. Buyers MUST treat the value as opaque — no format, no ordering, no inspection. The token is scope-keyed: it describes a version for the cache_scope declared on this response, NOT a global agent version. A buyer caches `(cache_scope, wholesale_feed_version)` pairs and presents the matching token on the next request. Scoping dimensions: (agent, buying_mode, filters, targeting_overlay, media_buy_frequency_cap, required_overlay_support, required_media_buy_support, deprecated property_list, catalog) for cache_scope: 'public'; that tuple plus account_id for cache_scope: 'account'. pagination.cursor is NOT part of the scoping tuple. See specs/wholesale-feed-webhooks.md for the full cache layering model. */ wholesale_feed_version?: string; /** @@ -5291,7 +5545,7 @@ export interface GetProductsResponse { */ pricing_version?: string; /** - * Declares whether the wholesale_feed_version and pricing_version on this response describe a universal layer or an account-specific overlay. REQUIRED on every 3.1+ response (the 3.1 schema enforces this — the safety property of the two-layer cache model depends on it). 'public': this response describes the seller's published rate card; the buyer MAY dedupe under (agent, buying_mode, filters, targeting_overlay, required_overlay_support, deprecated property_list, catalog) without scoping by account. 'account': this response includes account-specific overrides; the buyer MUST cache the version under (agent, buying_mode, filters, targeting_overlay, required_overlay_support, deprecated property_list, catalog, account_id). When the request did NOT include `account`, the seller MUST return `cache_scope: 'public'`. When the request included `account`, the seller MUST return either: 'public' (this account prices off the public rate card — buyer dedupes) or 'account' (account-specific overrides exist — buyer caches under the account key). Sellers MAY return 'public' on an account-scoped request that previously had overrides — buyers SHOULD interpret this as a downgrade and drop their account-overlay for the (agent, filters, targeting, support, mode) tuple. Without schema-required cache_scope, a seller silently omitting the field on an account-scoped response would cause buyers to mis-key the cache and serve account-overlay payloads to other accounts — the canonical safety invariant of the entire cache layering model. **Backward-compatibility note for 3.1 validators:** SDKs that validate strictly against the 3.1 schema MUST select the validator based on the server-declared `adcp_version` (release-precision version negotiation, 3.1). For responses with `adcp_version` starting `3.0`, the 3.1 cache_scope-required constraint MUST be relaxed — pre-3.1 sellers correctly emit no cache_scope and remain conformant to their declared version. This is a tightening within 3.1, not a 3.0 break. + * Declares whether the wholesale_feed_version and pricing_version on this response describe a universal layer or an account-specific overlay. REQUIRED on every 3.1+ response (the 3.1 schema enforces this — the safety property of the two-layer cache model depends on it). 'public': this response describes the seller's published rate card; the buyer MAY dedupe under (agent, buying_mode, filters, targeting_overlay, media_buy_frequency_cap, required_overlay_support, required_media_buy_support, deprecated property_list, catalog) without scoping by account. 'account': this response includes account-specific overrides; the buyer MUST cache the version under that tuple plus account_id. When the request did NOT include `account`, the seller MUST return `cache_scope: 'public'`. When the request included `account`, the seller MUST return either: 'public' (this account prices off the public rate card — buyer dedupes) or 'account' (account-specific overrides exist — buyer caches under the account key). Sellers MAY return 'public' on an account-scoped request that previously had overrides — buyers SHOULD interpret this as a downgrade and drop their account-overlay. Without schema-required cache_scope, a seller silently omitting the field on an account-scoped response would cause buyers to mis-key the cache and serve account-overlay payloads to other accounts. **Backward-compatibility note for 3.1 validators:** SDKs that validate strictly against the 3.1 schema MUST select the validator based on the server-declared `adcp_version` (release-precision version negotiation, 3.1). For responses with `adcp_version` starting `3.0`, the 3.1 cache_scope-required constraint MUST be relaxed. */ cache_scope?: 'public' | 'account'; /** @@ -6748,7 +7002,18 @@ export interface PlaceCatalogSupport { ext?: ExtensionObject; } /** - * Experimental product-scoped identity and reach-measurement facts. Absence is undeclared, not a claim that the product has persistent identifiers. Sellers implementing this surface MUST list media_buy.product_identity in experimental_features on get_adcp_capabilities. When persistent_identifier is false, the product MUST NOT declare overlay_support.frequency_cap; create and update reject that overlay under the ordinary exact-apply-or-reject rule. Delivery for the product MUST NOT report devices, accounts, or cookies as reach_unit. Individuals and households remain valid for panel-based or place-based modeled measurement. When delivery reports reach or frequency with reach_unit custom, reach_methodology is required and explains that unit. + * Binding product participation in shared MediaBuy-level controls. This is separate from overlay_support because a root frequency cap aggregates exposures across packages rather than targeting one package. Returned products MUST cover every field requested through required_media_buy_support. + */ +export interface ProductMediaBuySupport { + /** + * This product can participate in the seller's shared counter for a root MediaBuy.frequency_cap. A buy mixing this product with one that lacks this declaration, or whose resolved supported_per_units omits the root cap's per value, is rejected atomically. + */ + frequency_cap?: true; + frequency_cap_constraints?: MediaBuyFrequencyCapSupport; + ext?: ExtensionObject; +} +/** + * Experimental product-scoped identity and reach-measurement facts. Absence is undeclared, not a claim that the product has persistent identifiers. Sellers implementing this surface MUST list media_buy.product_identity in experimental_features on get_adcp_capabilities. When persistent_identifier is false, the product MUST NOT declare overlay_support.frequency_cap, overlay_support.frequency_cap_support, or media_buy_support.frequency_cap; create and update reject those caps under the ordinary exact-apply-or-reject rule. Delivery for the product MUST NOT report devices, accounts, or cookies as reach_unit. Individuals and households remain valid for panel-based or place-based modeled measurement. When delivery reports reach or frequency with reach_unit custom, reach_methodology is required and explains that unit. */ export interface ProductIdentity { /** @@ -7990,6 +8255,8 @@ export type ProductResponseFields = [ | 'signal_targeting_allowed' | 'signal_targeting_rules' | 'demographic_targeting' + | 'overlay_support' + | 'media_buy_support' | 'audience_evidence' | 'audience_evidence_selections' | 'max_optimization_goals' @@ -8024,6 +8291,8 @@ export type ProductResponseFields = [ | 'signal_targeting_allowed' | 'signal_targeting_rules' | 'demographic_targeting' + | 'overlay_support' + | 'media_buy_support' | 'audience_evidence' | 'audience_evidence_selections' | 'max_optimization_goals' @@ -8115,7 +8384,7 @@ export interface BrandKey { countries?: [string, ...string[]]; } /** - * Structured criteria shared by product listing and proposal requests. Offer filters decide which commercial offers may be returned; targeting_overlay constrains deliverable inventory; required_overlay_support requires package-level targeting capability for values the buyer will supply later; acceptance_context supplies facts for advisory seller-policy preflight. + * Structured criteria shared by product listing and proposal requests. Offer filters decide which commercial offers may be returned; targeting_overlay constrains deliverable inventory; required_overlay_support requires package-level targeting capability; required_media_buy_support requires participation in shared MediaBuy controls; acceptance_context supplies facts for advisory seller-policy preflight. */ export interface ProductDiscoveryCriteria { /** @@ -8126,7 +8395,9 @@ export interface ProductDiscoveryCriteria { product_ids?: [string, ...string[]]; offer_filters?: ProductOfferFilters; targeting_overlay?: TargetingOverlay; + media_buy_frequency_cap?: MediaBuyFrequencyCap; required_overlay_support?: TargetingOverlayRequirements; + required_media_buy_support?: ProductMediaBuySupportRequirements; outcome_target?: OutcomeTarget; acceptance_context?: AcceptanceContext; catalog?: CatalogSelection; @@ -8367,6 +8638,7 @@ export type CanonicalProduct = { signal_targeting_rules?: SignalTargetingRules; demographic_targeting?: DemographicTargetingCapability; overlay_support?: TargetingOverlaySupport; + media_buy_support?: ProductMediaBuySupport; identity?: ProductIdentity; /** * @minItems 1 @@ -8885,6 +9157,7 @@ export interface RequestProposalsRequest { status?: 'open'; }; } +export type ProductPurchaseImpressions = number; /** * Buyer-authored execution policy for automatic delivery, auction bidding, average outcome cost, or return on ad spend. The containing object determines authored scope: media-buy `bidding` is a complete inherited default and package `bidding` is a complete package override. Sellers MUST preserve authored scope on readback and MUST NOT copy an inherited media-buy policy into package `bidding`. Every monetary field in this block is denominated in the media-buy currency; the selected pricing option supplies the auction unit, never another denomination. Auction-unit identity is the pricing_model plus every canonical billing-event qualifier after defaults are applied: for example CPV view threshold, CPP demographic system/demographic, CPA event tuple, time time_unit, and flat-rate/DOOH parameters. An extension qualifier participates only when its registered extension specification explicitly defines how it contributes to auction-unit identity. A media-buy bid_amount or max_bid is valid only when every inheriting package resolves the same auction-unit identity. Every affected pricing option MUST use the media-buy currency; split currency-mismatched packages into separate buys. Seller-optimized media-buy cost_per/roas bind to the primary budget_allocation.optimization_goals goal. Package-authored cost_per/roas bind to the package primary optimization goal. The primary goal is the earliest array entry among goals with the lowest explicit numeric priority; unprioritized goals follow explicitly prioritized goals; when all priorities are absent, the first entry is primary. In fixed allocation, an inherited media-buy cost_per is valid only when all inheriting packages have compatible primary-goal result units; inherited roas requires value-bearing primary goals on every inheriting package. Canonical ROAS requires each value-bearing event source to declare the media-buy currency in value_currencies; each buy consumes only exact-currency records and sellers MUST NOT convert them. Absence invokes inheritance or provider automatic delivery; `{automatic:true}` is an explicit authored policy that overrides inheritance. Sellers MUST reject unsupported modes, combinations, units, currency, goal bindings, or native placements before any provider mutation and MUST NOT silently translate semantics. */ @@ -8995,6 +9268,95 @@ export type CanonicalOptimizationGoal = }; priority?: number; }; +/** + * Buyer evidence-admissibility policy carried into the accepted purchase snapshot. + */ +export type ProductPurchaseAudienceEvidenceRequirements = { +} & { + requirement_mode: 'required' | 'preferred'; + evidence_presence: 'required' | 'when_available'; + /** + * @minItems 1 + */ + accepted_methodologies?: [AudienceEvidenceMethodology, ...AudienceEvidenceMethodology[]]; + /** + * @minItems 1 + */ + excluded_methodologies?: [AudienceEvidenceMethodology, ...AudienceEvidenceMethodology[]]; + /** + * @minItems 1 + */ + accepted_evidence_types?: [ + 'measured' | 'forecast' | 'seller_declared', + ...('measured' | 'forecast' | 'seller_declared')[] + ]; + /** + * @minItems 1 + */ + accepted_providers?: [BrandKey, ...BrandKey[]]; + /** + * @minItems 1 + */ + excluded_providers?: [BrandKey, ...BrandKey[]]; + /** + * @minItems 1 + */ + accepted_subject_types?: [AudienceSubjectType, ...AudienceSubjectType[]]; + /** + * @minItems 1 + */ + accepted_resolution_methods?: [AudienceResolutionMethod, ...AudienceResolutionMethod[]]; + minimum_confidence?: number; + maximum_age?: Duration & { + unit?: 'seconds' | 'minutes' | 'hours' | 'days'; + }; + methodology_documentation_required?: boolean; + independent_attestation_required?: boolean; + /** + * @minItems 1 + */ + accepted_attestation_issuers?: [ + ( + | { + type: 'brand'; + brand: BrandKey; + ext?: ExtensionObject; + } + | { + type: 'agent'; + agent_url: string; + ext?: ExtensionObject; + } + | { + type: 'origin'; + origin: string; + ext?: ExtensionObject; + } + ), + ...( + | { + type: 'brand'; + brand: BrandKey; + ext?: ExtensionObject; + } + | { + type: 'agent'; + agent_url: string; + ext?: ExtensionObject; + } + | { + type: 'origin'; + origin: string; + ext?: ExtensionObject; + } + )[] + ]; + /** + * @minItems 1 + */ + accepted_attestation_claim_types?: [string, ...string[]]; + ext?: ExtensionObject; +}; /** * Campaign start timing: 'asap' or ISO 8601 date-time */ @@ -9065,6 +9427,7 @@ export interface CommercialTerms { * Hard aggregate daily spend ceiling accepted as part of these terms. It bounds total spend without creating purchase allocations. */ daily_budget_cap?: number; + frequency_cap?: MediaBuyFrequencyCap; /** * Shared IANA calendar-day boundary for aggregate and purchase daily caps in these terms. */ @@ -9112,7 +9475,7 @@ export interface CommercialTerms { change_terms?: [MediaBuyChangeTerm, ...MediaBuyChangeTerm[]]; } /** - * One canonical product selection shared by buy_products inputs and compact proposal snapshots. Direct purchases accept published terms as-is; sellers resolve omitted inherited flight, measurement, and performance terms into the accepted commercial snapshot. Changes to those terms belong in the proposal lifecycle. Creative content and creative assignments are intentionally absent. + * One resolved canonical product selection in a compact proposal or accepted commercial snapshot. Request-side buy_products selections use product-purchase-input.json. This strict snapshot shape contains effective non-null targeting and resolved inherited terms. Creative content and creative assignments are intentionally absent. */ export interface ProductPurchase { product_id: string; @@ -9142,7 +9505,7 @@ export interface ProductPurchase { * Soft lifetime spend target for seller-optimized allocation. */ min_spend_target?: number; - impressions?: number; + impressions?: ProductPurchaseImpressions; /** * Resolved package flight start. On direct-purchase input, omission inherits the MediaBuy start; accepted proposal snapshots carry the resolved timestamp. */ @@ -9158,7 +9521,7 @@ export interface ProductPurchase { * @minItems 1 */ optimization_goals?: [CanonicalOptimizationGoal, ...CanonicalOptimizationGoal[]]; - audience_evidence_requirements?: ProductAudienceEvidenceRequirements; + audience_evidence_requirements?: ProductPurchaseAudienceEvidenceRequirements; /** * Exact immutable audience-evidence snapshots selected for package construction. * @@ -9171,7 +9534,7 @@ export interface ProductPurchase { agency_estimate_number?: string; context?: ContextObject; ext?: ExtensionObject; - measurement_terms?: CanonicalMeasurementTerms; + measurement_terms?: ProductPurchaseMeasurementTerms; /** * Published or negotiated metric thresholds and measurement vendors. Direct buyers may omit this to inherit the product defaults; accepted proposal snapshots preserve every applicable standard. * @@ -9189,6 +9552,23 @@ export interface AudienceEvidencePin { content_digest: string; ext?: ExtensionObject; } +/** + * Published or negotiated billing-measurement and makegood terms for this purchase. Direct buyers may omit this to inherit the product default; accepted proposal snapshots preserve the resolved terms. + */ +export interface ProductPurchaseMeasurementTerms { + billing_measurement?: { + vendor: BrandKey; + max_variance_percent?: number; + measurement_window?: string; + finalization_deadline_hours?: number; + }; + makegood_policy?: { + /** + * @minItems 1 + */ + available_remedies: [MakegoodRemedy, ...MakegoodRemedy[]]; + }; +} /** * Compact qualifier set that distinguishes incompatible reporting definitions for the same metric ID. */ @@ -9236,7 +9616,7 @@ export interface MediaBuyChangeTerm { // refine_proposals parameters /** - * Fork an immutable proposal or finalize a draft into a held committed snapshot. Revising with structured criteria, typed boundaries, product changes, requested alternatives, and/or a semantic ask creates one or more new drafts; finalizing changes no terms. Refining an accepted proposal creates a draft amendment or cancellation proposal against its MediaBuy; the source remains accepted and unchanged. + * Fork an immutable proposal or finalize a draft into a held committed snapshot. Revising with structured criteria, typed boundaries, product changes, requested alternatives, and/or a semantic ask creates one or more new drafts; finalizing changes no terms. Refining an accepted proposal creates a draft amendment or cancellation proposal against its MediaBuy; the source remains accepted and unchanged. A revised product mix must support the resulting root frequency cap; because omitted criteria inherit, clearing the cap is explicit through remove_media_buy_frequency_cap. */ export type ProposalRefinement = { proposal_id: string; @@ -9287,6 +9667,10 @@ export type ProposalRefinement = { */ ask?: string; criteria?: ProductDiscoveryCriteria; + /** + * Request a revised draft whose commercial terms omit the existing MediaBuy frequency cap. Omission inherits it. To replace it, provide criteria.media_buy_frequency_cap instead. + */ + remove_media_buy_frequency_cap?: true; } & ( | { action: 'finalize'; @@ -9776,6 +10160,241 @@ export type DeclineProposalsResponse = // buy_products parameters +/** + * Canonical format options selected from the published product offer. Legacy named-format identifiers are not accepted. + * + * @minItems 1 + */ +export type FormatOptionRefs = [FormatOptionReference, ...FormatOptionReference[]]; +/** + * Previously synchronized account catalog IDs promoted by this selection. Callers manage catalog bodies through sync_catalogs rather than inlining them here. + * + * @minItems 1 + */ +export type CatalogIds = [string, ...string[]]; +/** + * Per-dimension targeting input. Omission inherits the selected product's configured/default dimension, a non-null value replaces it, and null explicitly suppresses it. A clear cannot remove inherent product scope. + */ +export type TargetingOverlayInput = TargetingUnknownAgeEligibilityConstraint & + TargetingVerifiedAgeBasisConstraint & { + geo_countries?: GeoCountries | null; + geo_countries_exclude?: GeoCountriesExclude | null; + geo_regions?: GeoRegions | null; + geo_regions_exclude?: GeoRegionsExclude | null; + geo_metros?: TargetingGeoMetros; + geo_metros_exclude?: GeoMetrosExclude | null; + geo_postal_areas?: GeoPostalAreas | null; + geo_postal_areas_exclude?: GeoPostalAreasExclude | null; + geo_places?: GeoPlaces | null; + geo_places_exclude?: GeoPlacesExclude | null; + daypart_targets?: DaypartTargets | null; + axe_include_segment?: string | null; + axe_exclude_segment?: string | null; + audience_include?: AudienceInclude | null; + audience_exclude?: AudienceExclude | null; + signal_targeting_groups?: TargetingSignalGroups | null; + /** + * @deprecated + * DEPRECATED. Use signal_targeting_groups for package-level signal targeting. Legacy flat signal_targeting remains accepted during the SignalRef migration window but cannot express grouped include/exclude composition or product-scoped pricing. + * + * @minItems 1 + */ + signal_targeting?: [SignalTargeting, ...SignalTargeting[]] | null; + demographics?: DemographicTargetingIntent | null; + frequency_cap?: TargetingFrequencyCap | null; + property_list?: TargetingPropertyList | null; + property_list_exclude?: PropertyListReference | null; + collection_list?: TargetingCollectionList | null; + collection_list_exclude?: CollectionListReference | null; + placement_selection?: PlacementSelection | null; + collection_selection?: TargetingCollectionSelection | null; + age_restriction?: AgeRestriction | null; + device_platform?: DevicePlatform | null; + device_platform_exclude?: DevicePlatformExclude | null; + device_type?: DeviceType | null; + device_type_exclude?: DeviceTypeExclude | null; + browser?: Browser | null; + browser_exclude?: BrowserExclude | null; + store_catchments?: StoreCatchments | null; + geo_proximity?: GeoProximity | null; + language?: TargetingLanguages; + keyword_targets?: TargetingKeywords; + negative_keywords?: TargetingNegativeKeywords; + }; +/** + * Restrict delivery to specific countries. ISO 3166-1 alpha-2 codes (e.g., 'US', 'GB', 'DE'). + * + * @minItems 1 + */ +export type GeoCountries = [string, ...string[]]; +/** + * Exclude specific countries from delivery. ISO 3166-1 alpha-2 codes (e.g., 'US', 'GB', 'DE'). + * + * @minItems 1 + */ +export type GeoCountriesExclude = [string, ...string[]]; +/** + * Restrict delivery to exact canonical ISO 3166-2 subdivisions (states, provinces, regions, departments, or other subdivision categories). Unknown identifiers are invalid. At create or update, sellers MUST reject unsupported identifiers and MUST NOT silently widen, drop, or partially apply the list. During get_products, a seller may instead return a sparse, buyer-reviewable targeting_resolution modification for a valid but unsupported requested outcome. Exact internal translation preserves accepted identifiers in package readback. + * + * @minItems 1 + */ +export type GeoRegions = [string, ...string[]]; +/** + * Exclude exact canonical ISO 3166-2 subdivisions. Support is independent from geo_regions inclusion support. Unknown identifiers and values also present in geo_regions are invalid. At create or update, sellers MUST reject unsupported identifiers and partial application; during get_products, a seller may instead return a sparse, buyer-reviewable targeting_resolution modification for a valid but unsupported requested outcome. + * + * @minItems 1 + */ +export type GeoRegionsExclude = [string, ...string[]]; +/** + * Exclude specific metro areas from delivery. Each entry specifies the classification system and excluded values. Seller must declare supported systems in get_adcp_capabilities. + * + * @minItems 1 + */ +export type GeoMetrosExclude = [ + { + system: MetroAreaSystem; + /** + * Metro codes to exclude within the system (e.g., ['501', '602'] for Nielsen DMAs) + * + * @minItems 1 + */ + values: [string, ...string[]]; + }, + ...{ + system: MetroAreaSystem; + /** + * Metro codes to exclude within the system (e.g., ['501', '602'] for Nielsen DMAs) + * + * @minItems 1 + */ + values: [string, ...string[]]; + }[] +]; +/** + * Restrict delivery to specific postal areas. Prefer the native country + postal system form. The deprecated legacy country-fused postal-system tokens remain accepted for compatibility. Seller must declare supported systems in get_adcp_capabilities. + * + * @minItems 1 + */ +export type GeoPostalAreas = [PostalArea, ...PostalArea[]]; +/** + * Exclude specific postal areas from delivery. Prefer the native country + postal system form. The deprecated legacy country-fused postal-system tokens remain accepted for compatibility. Seller must declare supported systems in get_adcp_capabilities. + * + * @minItems 1 + */ +export type GeoPostalAreasExclude = [PostalArea, ...PostalArea[]]; +/** + * Restrict delivery to catalog-backed named places. Values MUST be stable identifiers in the declared system, not display names. Sellers must declare supported systems, countries, and place types in get_adcp_capabilities and reject unsupported entries rather than silently dropping them. + * + * @minItems 1 + */ +export type GeoPlaces = [GeographicPlaceArea, ...GeographicPlaceArea[]]; +/** + * Exclude catalog-backed named places. Uses the same identifier-based shape as geo_places. Sellers MUST reject overlap with geo_places for the same country, system, place_type, and value. + * + * @minItems 1 + */ +export type GeoPlacesExclude = [GeographicPlaceArea, ...GeographicPlaceArea[]]; +/** + * Restrict delivery to specific time windows. Each entry specifies days of week, an hour range, and an optional timezone that defaults to inventory_local. A concrete IANA zone uses one shared civil-time clock, while inventory_local evaluates each inventory unit in its seller-assigned local timezone. Entries are independent and MAY use different clocks. + * + * @minItems 1 + */ +export type DaypartTargets = [DaypartTarget, ...DaypartTarget[]]; +/** + * Restrict delivery to members of these first-party CRM audiences. Only users present in the uploaded lists are eligible. References audience_id values from sync_audiences on the same seller account — audience IDs are not portable across sellers. Not for lookalike expansion — express that intent in the campaign brief. Seller must declare support in get_adcp_capabilities. + * + * @minItems 1 + */ +export type AudienceInclude = [string, ...string[]]; +/** + * Suppress delivery to members of these first-party CRM audiences. Matched users are excluded regardless of other targeting. References audience_id values from sync_audiences on the same seller account — audience IDs are not portable across sellers. Seller must declare support in get_adcp_capabilities. + * + * @minItems 1 + */ +export type AudienceExclude = [string, ...string[]]; +/** + * Exclude specific operating-system platforms from delivery. When a platform appears in both device_platform and device_platform_exclude, exclusion wins. Sellers MUST reject a request they cannot enforce rather than silently dropping the exclusion. + * + * @minItems 1 + */ +export type DevicePlatformExclude = [DevicePlatform, ...DevicePlatform[]]; +/** + * Exclude specific device form factors from delivery (e.g., exclude CTV for app-install campaigns). + * + * @minItems 1 + */ +export type DeviceTypeExclude = [DeviceType, ...DeviceType[]]; +/** + * Restrict delivery to specific canonical browser families in the impression delivery and rendering environment, not the post-click landing-page browser. Values MUST NOT be inferred solely from operating system, device, web/mobile-web inventory, or placement. Values in this array use OR semantics. When browser is supplied, families not listed are ineligible: other includes a seller-recognized family that is not explicitly enumerated, while unknown includes a browser the seller cannot classify into a recognized family. When the same family appears in browser and browser_exclude, exclusion wins. Browser and device constraints intersect; a seller that cannot enforce the exact combination MUST exclude or explicitly reconfigure the product during discovery and MUST reject it at create or update rather than silently widening delivery. Browser versions and seller-native IDs are intentionally unsupported. + * + * @minItems 1 + */ +export type Browser = [BrowserFamily, ...BrowserFamily[]]; +/** + * Exclude specific canonical browser families from delivery. other excludes seller-recognized families that are not explicitly enumerated; unknown excludes browsers the seller cannot classify into a recognized family. When the same family appears in browser and browser_exclude, exclusion wins. Sellers MUST reject a request they cannot enforce rather than silently dropping the exclusion. + * + * @minItems 1 + */ +export type BrowserExclude = [BrowserFamily, ...BrowserFamily[]]; +/** + * Target users within store catchment areas from a synced store catalog. Each entry references a store-type catalog and optionally narrows to specific stores or catchment zones. + * + * @minItems 1 + */ +export type StoreCatchments = [ + { + /** + * Synced store-type catalog ID from sync_catalogs. + */ + catalog_id: string; + /** + * Filter to specific stores within the catalog. Omit to target all stores. + * + * @minItems 1 + */ + store_ids?: [string, ...string[]]; + /** + * Catchment zone IDs to target (e.g., 'walk', 'drive'). Omit to target all catchment zones. + * + * @minItems 1 + */ + catchment_ids?: [string, ...string[]]; + }, + ...{ + /** + * Synced store-type catalog ID from sync_catalogs. + */ + catalog_id: string; + /** + * Filter to specific stores within the catalog. Omit to target all stores. + * + * @minItems 1 + */ + store_ids?: [string, ...string[]]; + /** + * Catchment zone IDs to target (e.g., 'walk', 'drive'). Omit to target all catchment zones. + * + * @minItems 1 + */ + catchment_ids?: [string, ...string[]]; + }[] +]; +/** + * @minItems 1 + */ +export type OptimizationGoals = [CanonicalOptimizationGoal, ...CanonicalOptimizationGoal[]]; +/** + * Exact immutable audience-evidence snapshots selected for package construction. + * + * @minItems 1 + */ +export type AudienceEvidencePins = [AudienceEvidencePin, ...AudienceEvidencePin[]]; +/** + * Published or negotiated metric thresholds and measurement vendors. Direct buyers may omit this to inherit the product defaults; accepted proposal snapshots preserve every applicable standard. + * + * @minItems 1 + */ +export type PerformanceStandards = [CanonicalPerformanceStandard, ...CanonicalPerformanceStandard[]]; /** * Create a MediaBuy directly from published product offers. Provide exactly one brand source: top-level brand when account is ID-only, or brand and operator inside a natural-key account. This buyer-composed path accepts published commercial terms, supports targeting and delivery controls, and never accepts inline creatives or creative assignments. The seller records an immutable accepted proposal snapshot so later commercial amendments can use refine_proposals. */ @@ -9811,7 +10430,7 @@ export interface BuyProductsRequest { * @minLength 1 */ pricing_version?: string; - purchases: ProductPurchase[]; + purchases: ProductPurchaseInput[]; total_budget?: { /** * @minimum 0 @@ -9827,6 +10446,7 @@ export interface BuyProductsRequest { * @minimum 0 */ daily_budget_cap?: number; + frequency_cap?: MediaBuyFrequencyCap; /** * Optional IANA timezone override shared by every aggregate and purchase daily cap. Requires buyer_timezone_override support; otherwise rejected with UNSUPPORTED_FEATURE. When omitted, budget_capping.timezone_basis selects Account.timezone or fixed_timezone. * @minLength 1 @@ -9867,6 +10487,70 @@ export interface BuyProductsRequest { context?: ContextObject; ext?: ExtensionObject; } +/** + * Request-only canonical product selection for buy_products. It shares the strict Product Purchase field shapes but uses Targeting Input so a buyer can distinguish inheritance, replacement, and explicit clearing. Accepted commercial snapshots use product-purchase.json and contain only resolved, non-null effective targeting. + */ +export interface ProductPurchaseInput { + product_id: string; + pricing_option_id: string; + pricing?: CanonicalPricingOption; + format_option_refs?: FormatOptionRefs; + catalog_ids?: CatalogIds; + /** + * Hard spend cap for this selection in the media-buy currency. + */ + budget?: number; + /** + * Optional hard daily spend ceiling for this purchase. It is subordinate to the media-buy aggregate daily cap and is not a reserved daily allocation. Its day boundary is the media buy's budget_cap_timezone. + */ + daily_budget_cap?: number; + /** + * Soft lifetime spend target for seller-optimized allocation. + */ + min_spend_target?: number; + impressions?: ProductPurchaseImpressions; + /** + * Resolved package flight start. On direct-purchase input, omission inherits the MediaBuy start; accepted proposal snapshots carry the resolved timestamp. + */ + start_time?: string; + /** + * Resolved package flight end. On direct-purchase input, omission inherits the MediaBuy end; accepted proposal snapshots carry the resolved timestamp. + */ + end_time?: string; + pacing?: Pacing; + bidding?: BiddingPolicy; + targeting_overlay?: TargetingOverlayInput; + optimization_goals?: OptimizationGoals; + audience_evidence_requirements?: ProductPurchaseAudienceEvidenceRequirements; + audience_evidence_pins?: AudienceEvidencePins; + /** + * Package-level agency estimate or authorization reference. + */ + agency_estimate_number?: string; + context?: ContextObject; + ext?: ExtensionObject; + measurement_terms?: ProductPurchaseMeasurementTerms; + performance_standards?: PerformanceStandards; +} +/** + * Age restriction for compliance. Use for legal requirements (alcohol, gambling), not audience targeting. + */ +export interface AgeRestriction { + /** + * Minimum age required + */ + min: number; + /** + * Whether verified age (not inferred) is required for compliance + */ + verification_required?: boolean; + /** + * Accepted verification methods. If omitted, any method the platform supports is acceptable. + * + * @minItems 1 + */ + accepted_methods?: [AgeVerificationMethod, ...AgeVerificationMethod[]]; +} /** * Optional reporting delivery configuration established atomically with the MediaBuy. This is execution metadata and is not part of the immutable product pricing terms. */ @@ -9927,6 +10611,10 @@ export type MediaBuyChangeTermID = string; * Deprecated 3.1 opaque commercial-terms pointer. A 3.2 compatibility projection MAY echo change_term_id here for older buyers, but new buyers MUST prefer change_term_id and MUST NOT assume an arbitrary 3.1 value identifies an accepted change term. */ export type MediaBuyTermsReference = string; +/** + * A package identifier to which a package-scoped media-buy action currently applies. + */ +export type ApplicablePackageID = string; /** * A non-blocking observation returned with a successful operation. The operation succeeded exactly as its success arm states. Warnings are immediate receipts, not durable lifecycle state; a continuing condition MUST also appear on its authoritative read surface as an indicator, defect, delivery issue, approval state, or other applicable resource state. */ @@ -10001,6 +10689,12 @@ export interface CanonicalMediaBuyActionFields { sla?: SLAWindow; change_term_id?: MediaBuyChangeTermID; terms_ref?: MediaBuyTermsReference; + /** + * Exact eligible packages for a package-scoped action; omission means all relevant packages. + * + * @minItems 1 + */ + applicable_package_ids?: [ApplicablePackageID, ...ApplicablePackageID[]]; } export interface CommitmentError { status: 'failed'; @@ -10125,7 +10819,7 @@ export type AcceptProposalResponse = MediaBuyCommitmentResponse; // control_media_buy parameters /** - * Operational controls for an existing package that remain inside its accepted commercial envelope. targeting_overlay is a complete replacement; keyword add/remove arrays are incremental, and the same keyword MUST NOT appear in both directions. Creative mutation, flight changes, new products, pricing changes, and billing-term changes require their dedicated lifecycle or a refined proposal. + * Operational controls for an existing package that remain inside its accepted commercial envelope. targeting_overlay is a per-dimension patch; keyword add/remove arrays are incremental, and the same keyword MUST NOT appear in both directions. Creative mutation, flight changes, new products, pricing changes, and billing-term changes require their dedicated lifecycle or a refined proposal. */ export type PackageControl = { } & { @@ -10145,7 +10839,7 @@ export type PackageControl = { */ canceled?: true; cancellation_reason?: string; - targeting_overlay?: TargetingOverlay; + targeting_overlay?: TargetingOverlayInput; /** * Replace the package's promoted catalogs with references previously managed through sync_catalogs. * @@ -10235,6 +10929,10 @@ export interface ControlMediaBuyRequest { * @minimum 0 */ daily_budget_cap?: number | null; + /** + * Replace the shared MediaBuy frequency cap; null removes it. The change applies immediately without resetting counters: qualifying prior exposures still count in the resulting active window. Sellers MUST reject the complete mutation with UNSUPPORTED_FEATURE, before any change, if the cap is outside declared constraints or any active package cannot participate in the resulting shared counter, and MUST NOT clamp it. Requires update_media_buy_frequency_cap in available_actions. + */ + frequency_cap?: MediaBuyFrequencyCap | null; /** * Replace the shared IANA cap-day timezone override; null restores the default selected by budget_capping.timezone_basis (Account.timezone or fixed_timezone). A timezone change begins at the next boundary under the previously effective timezone. * @minLength 1 @@ -11002,6 +11700,7 @@ export type CreateMediaBuyRequest = ( * @minimum 0 */ daily_budget_cap?: number; + frequency_cap?: MediaBuyFrequencyCap; /** * Optional shared IANA day boundary override for all caps. Requires buyer_timezone_override; otherwise rejected with UNSUPPORTED_FEATURE. When omitted, budget_capping.timezone_basis selects Account.timezone or the advertised fixed_timezone. * @minLength 1 @@ -11206,7 +11905,7 @@ export type PackageRequest = AdCPVersionEnvelope & { * @minItems 1 */ optimization_goals?: [OptimizationGoal, ...OptimizationGoal[]]; - targeting_overlay?: TargetingOverlay; + targeting_overlay?: TargetingOverlayInput; audience_evidence_requirements?: AudienceEvidenceRequirements; /** * Exact immutable evidence snapshots selected by the buyer during discovery. The seller MUST match evidence_id, snapshot_id, version, and content_digest against one published snapshot and MUST reject catalog mutation, snapshot reuse, missing snapshots, or substitutions. Every accepted pin MUST be echoed in the confirmed package's audience_evidence_selections with decision_use package_construction. @@ -14360,6 +15059,10 @@ export type ReportingDeliveryConfiguration = { coverage_requirement: 'full' | 'allow_partial'; required_finality: ReportingFinality; reconciliation_mode: ReportingReconciliationMode; + /** + * Reserved: which party's count of this feed is authoritative. seller (the default, and the only value any 3.2 seller accepts) means the seller produces every revision and the consumer may only attest to what it consumed. consumer is reserved for the buyer-deposited billing revision task scoped to a later minor; until that task exists sellers MUST reject it with UNSUPPORTED_FEATURE. Reserving the field now keeps a future buyer-basis billing feed additive instead of breaking the billing-feed constraints. See https://github.com/adcontextprotocol/adcp/issues/7440. + */ + authoritative_party?: 'seller' | 'consumer'; schedule: ReportingSchedule; method?: ReportingDeliveryMethod; /** @@ -14373,7 +15076,7 @@ export type ReportingDeliveryConfiguration = { export type ReportingFeedPurpose = 'pacing' | 'analytics' | 'billing'; export type ReportingMediaBuyID = string; /** - * Whether producer-side delivery evidence is sufficient or the selected consumer must submit an authenticated matching receipt. Billing MUST use consumer_receipt. + * Whether producer-side delivery evidence is sufficient or the selected consumer must submit an authenticated matching receipt. A seller-authoritative billing feed MUST use consumer_receipt. */ export type ReportingReconciliationMode = 'delivery_only' | 'consumer_receipt'; /** @@ -14423,6 +15126,143 @@ export type ReportingDeliveryConfigurationLifecycleState = | 'action_required' | 'inactive'; export type ReportingPackageID = string; +/** + * Structured reporting condition that explains delayed or action_required health without exposing credentials, provider response bodies, or internal stack traces. + */ +export type ReportingStatusIssue = { +} & { + /** + * Seller-issued stable identifier for this logical issue: re-emissions and later polls of the same unresolved condition reuse it, and resolution retires it, so consumers can project AdCP reporting issues into durable work items. A recurrence after resolution receives a new id. + */ + issue_id: string; + code: + | 'REPORT_OVERDUE' + | 'PRODUCTION_FAILED' + | 'DELIVERY_FAILED' + | 'ACCESS_REQUIRED' + | 'CONFIGURATION_REQUIRED' + | 'REPORTING_COVERAGE_INCOMPLETE' + | 'RESOURCE_EXPIRED' + | 'READER_INCOMPATIBLE' + | 'HISTORY_UNAVAILABLE' + | 'RECEIPT_REQUIRED' + | 'RECEIPT_REJECTED' + | 'ADJUSTMENT_RECEIPT_REQUIRED' + | 'ADJUSTMENT_RECEIPT_REJECTED' + | 'CONSUMER_STATUS_MISMATCH'; + severity: ReportingStatusSeverity; + /** + * When the seller first observed this logical condition, carried unchanged across every re-emission until the issue is retired. It anchors the escalation clock advertised as consumer_mismatch_escalation_seconds and lets a consumer age an issue without keeping its own first-seen table. Required when code is CONSUMER_STATUS_MISMATCH. + */ + opened_at?: string; + /** + * Optional seller-maintained lifecycle for this issue_id. open is the default when omitted. acknowledged means a human on responsible_party has taken it up but the condition persists. resolved means the underlying condition no longer holds; a recurrence uses a new issue_id. waived means the parties agreed off-protocol to stop acting on it. Only open and acknowledged issues appear in issues[]; retiring an issue removes it from the projection rather than publishing it at resolved or waived, so a reader that treats a nonempty issues[] as degradation stays correct. Retiring is never a way to discharge a condition that still holds: for CONSUMER_STATUS_MISMATCH see the consumer_mismatch_lifecycle rule. + */ + issue_state?: 'open' | 'acknowledged' | 'resolved' | 'waived'; + /** + * Optional opaque, non-secret correlation string for the party's own tracker — a ticket key, incident ID, or case number. Untrusted display text only. The character class excludes whitespace and the solidus, so the value cannot express a URL or a sentence; receivers compare, store, and display it as inert text and never dereference, resolve, or execute it. It confers no authorization and MUST NOT be used to look up state across accounts or callers. + */ + external_ref?: string; + responsible_party: 'buyer' | 'seller' | 'provider'; + recommended_action: + | 'wait_for_retry' + | 'contact_buyer' + | 'contact_seller' + | 'contact_provider' + | 'repair_access' + | 'update_configuration' + | 'change_reporting_scope' + | 'use_supported_reader'; + /** + * Untrusted display text only. SDKs and agents dispatch exclusively on closed code/recommended_action values and never execute embedded links or instructions. + */ + message?: string; + reporting_obligation_id?: string; + /** + * Current authenticated consumer status statement that caused this mismatch. + */ + reporting_status_id?: string; + delivery_config_id?: string; + delivery_config_version?: number; + feed_purpose?: ReportingFeedPurpose; + /** + * @minItems 1 + */ + media_buy_ids?: [ReportingMediaBuyID, ...ReportingMediaBuyID[]]; + /** + * @minItems 1 + */ + package_ids?: [ReportingPackageID, ...ReportingPackageID[]]; + period_start?: string; + period_end?: string; + expected_at?: string; +} & { + /** + * Seller-issued stable identifier for this logical issue: re-emissions and later polls of the same unresolved condition reuse it, and resolution retires it, so consumers can project AdCP reporting issues into durable work items. A recurrence after resolution receives a new id. + */ + issue_id: string; + code: + | 'REPORT_OVERDUE' + | 'PRODUCTION_FAILED' + | 'DELIVERY_FAILED' + | 'ACCESS_REQUIRED' + | 'CONFIGURATION_REQUIRED' + | 'REPORTING_COVERAGE_INCOMPLETE' + | 'RESOURCE_EXPIRED' + | 'READER_INCOMPATIBLE' + | 'HISTORY_UNAVAILABLE' + | 'RECEIPT_REQUIRED' + | 'RECEIPT_REJECTED' + | 'ADJUSTMENT_RECEIPT_REQUIRED' + | 'ADJUSTMENT_RECEIPT_REJECTED' + | 'CONSUMER_STATUS_MISMATCH'; + severity: ReportingStatusSeverity; + /** + * When the seller first observed this logical condition, carried unchanged across every re-emission until the issue is retired. It anchors the escalation clock advertised as consumer_mismatch_escalation_seconds and lets a consumer age an issue without keeping its own first-seen table. Required when code is CONSUMER_STATUS_MISMATCH. + */ + opened_at?: string; + /** + * Optional seller-maintained lifecycle for this issue_id. open is the default when omitted. acknowledged means a human on responsible_party has taken it up but the condition persists. resolved means the underlying condition no longer holds; a recurrence uses a new issue_id. waived means the parties agreed off-protocol to stop acting on it. Only open and acknowledged issues appear in issues[]; retiring an issue removes it from the projection rather than publishing it at resolved or waived, so a reader that treats a nonempty issues[] as degradation stays correct. Retiring is never a way to discharge a condition that still holds: for CONSUMER_STATUS_MISMATCH see the consumer_mismatch_lifecycle rule. + */ + issue_state?: 'open' | 'acknowledged' | 'resolved' | 'waived'; + /** + * Optional opaque, non-secret correlation string for the party's own tracker — a ticket key, incident ID, or case number. Untrusted display text only. The character class excludes whitespace and the solidus, so the value cannot express a URL or a sentence; receivers compare, store, and display it as inert text and never dereference, resolve, or execute it. It confers no authorization and MUST NOT be used to look up state across accounts or callers. + */ + external_ref?: string; + responsible_party: 'buyer' | 'seller' | 'provider'; + recommended_action: + | 'wait_for_retry' + | 'contact_buyer' + | 'contact_seller' + | 'contact_provider' + | 'repair_access' + | 'update_configuration' + | 'change_reporting_scope' + | 'use_supported_reader'; + /** + * Untrusted display text only. SDKs and agents dispatch exclusively on closed code/recommended_action values and never execute embedded links or instructions. + */ + message?: string; + reporting_obligation_id?: string; + /** + * Current authenticated consumer status statement that caused this mismatch. + */ + reporting_status_id?: string; + delivery_config_id?: string; + delivery_config_version?: number; + feed_purpose?: ReportingFeedPurpose; + /** + * @minItems 1 + */ + media_buy_ids?: [ReportingMediaBuyID, ...ReportingMediaBuyID[]]; + /** + * @minItems 1 + */ + package_ids?: [ReportingPackageID, ...ReportingPackageID[]]; + period_start?: string; + period_end?: string; + expected_at?: string; +}; export type ReportingStatusSeverity = 'delayed' | 'action_required'; /** * A specific product within a media buy (line item) @@ -14891,6 +15731,7 @@ export interface CreateMediaBuySuccess { * @minimum 0 */ daily_budget_cap?: number; + frequency_cap?: MediaBuyFrequencyCap; /** * Accepted IANA timezone shared by every aggregate and package daily cap. Sellers MUST echo it whenever any daily cap is set on the media buy. */ @@ -15235,64 +16076,6 @@ export interface ReportingCoverage { package_ids?: [ReportingPackageID, ...ReportingPackageID[]]; }[]; } -/** - * Structured reporting condition that explains delayed or action_required health without exposing credentials, provider response bodies, or internal stack traces. - */ -export interface ReportingStatusIssue { - /** - * Seller-issued stable identifier for this logical issue: re-emissions and later polls of the same unresolved condition reuse it, and resolution retires it, so consumers can project AdCP reporting issues into durable work items. A recurrence after resolution receives a new id. - */ - issue_id: string; - code: - | 'REPORT_OVERDUE' - | 'PRODUCTION_FAILED' - | 'DELIVERY_FAILED' - | 'ACCESS_REQUIRED' - | 'CONFIGURATION_REQUIRED' - | 'REPORTING_COVERAGE_INCOMPLETE' - | 'RESOURCE_EXPIRED' - | 'READER_INCOMPATIBLE' - | 'HISTORY_UNAVAILABLE' - | 'RECEIPT_REQUIRED' - | 'RECEIPT_REJECTED' - | 'ADJUSTMENT_RECEIPT_REQUIRED' - | 'ADJUSTMENT_RECEIPT_REJECTED' - | 'CONSUMER_STATUS_MISMATCH'; - severity: ReportingStatusSeverity; - responsible_party: 'buyer' | 'seller' | 'provider'; - recommended_action: - | 'wait_for_retry' - | 'contact_buyer' - | 'contact_seller' - | 'contact_provider' - | 'repair_access' - | 'update_configuration' - | 'change_reporting_scope' - | 'use_supported_reader'; - /** - * Untrusted display text only. SDKs and agents dispatch exclusively on closed code/recommended_action values and never execute embedded links or instructions. - */ - message?: string; - reporting_obligation_id?: string; - /** - * Current authenticated consumer status statement that caused this mismatch. - */ - reporting_status_id?: string; - delivery_config_id?: string; - delivery_config_version?: number; - feed_purpose?: ReportingFeedPurpose; - /** - * @minItems 1 - */ - media_buy_ids?: [ReportingMediaBuyID, ...ReportingMediaBuyID[]]; - /** - * @minItems 1 - */ - package_ids?: [ReportingPackageID, ...ReportingPackageID[]]; - period_start?: string; - period_end?: string; - expected_at?: string; -} /** * Single webhook delivery attempt surfaced to a calling principal as a buyer-side debug aid. Represents one HTTP attempt of a logical webhook fire from the seller to the buyer's registered endpoint — retries of the same logical fire share `idempotency_key` and differ by `attempt`. This is the canonical record shape for any AdCP resource that exposes a `webhook_activity[]` log on its read API; see snapshot-and-log.mdx § Webhook activity log pattern for the full normative contract (scoping, retention, three-state presence, request-field conventions). */ @@ -15472,6 +16255,10 @@ export interface UpdateMediaBuyRequest { * @minimum 0 */ daily_budget_cap?: number | null; + /** + * Replace the hard MediaBuy-level frequency cap; null removes it. Changes apply immediately without resetting the shared counter, so prior qualifying exposures in the resulting window continue to count. Every active package must support the resulting cap or the request is rejected atomically with UNSUPPORTED_FEATURE before any change; sellers MUST NOT clamp it. The check applies to the state the request would produce, so null combined with new_packages adds those packages uncapped. + */ + frequency_cap?: MediaBuyFrequencyCap | null; /** * Replace the shared IANA cap-day timezone; null restores the default selected by budget_capping.timezone_basis (Account.timezone or fixed_timezone). Requires buyer_timezone_override. Changes start at the next boundary in the previously effective timezone; numeric cap changes remain immediate. * @minLength 1 @@ -15492,7 +16279,7 @@ export interface UpdateMediaBuyRequest { packages?: PackageUpdate[]; invoice_recipient?: BusinessEntity; /** - * New packages to add to this media buy. Uses the same schema as create_media_buy packages. When budget_allocation is omitted or fixed, every new package MUST carry budget and MUST NOT carry min_spend_target. To add a package without a hard cap to an existing seller-optimized buy, include its resulting seller_optimized budget_allocation block in the update so the allocation context is schema-visible. Repeating an unchanged allocation block does not itself switch modes. Sellers that support mid-flight package additions advertise `add_packages` in both `valid_actions[]` (deprecated) and as an entry in `available_actions[]` (authoritative). Sellers that do not support this MUST reject with ACTION_NOT_ALLOWED (preferred) or UNSUPPORTED_FEATURE (legacy). + * New packages to add to this media buy. Uses the same schema as create_media_buy packages. When budget_allocation is omitted or fixed, every new package MUST carry budget and MUST NOT carry min_spend_target. To add a package without a hard cap to an existing seller-optimized buy, include its resulting seller_optimized budget_allocation block in the update so the allocation context is schema-visible. Repeating an unchanged allocation block does not itself switch modes. Sellers that support mid-flight package additions advertise `add_packages` in both `valid_actions[]` (deprecated) and as an entry in `available_actions[]` (authoritative). Sellers that do not support this MUST reject with ACTION_NOT_ALLOWED (preferred) or UNSUPPORTED_FEATURE (legacy). If the buy has a root frequency_cap, every added product must support that exact aggregate cap; otherwise the seller rejects atomically with UNSUPPORTED_FEATURE, leaving the whole update unapplied and preserving the buy and its counter history. */ new_packages?: PackageRequest[]; reporting_webhook?: ReportingWebhook; @@ -15596,6 +16383,7 @@ export interface UpdateMediaBuySuccess { * @minimum 0 */ daily_budget_cap?: number; + frequency_cap?: MediaBuyFrequencyCap; /** * Post-update IANA timezone shared by every aggregate and package daily cap. Echoed whenever the update affects daily caps or their timezone. */ @@ -15862,6 +16650,7 @@ export interface GetMediaBuysResponseMediaBuy { * @minimum 0 */ daily_budget_cap?: number; + frequency_cap?: MediaBuyFrequencyCap; /** * IANA timezone defining the shared calendar-day boundary for every aggregate and package daily cap. Present whenever any daily cap is set on the media buy. */ @@ -18023,6 +18812,12 @@ export type GetReportingStatusResponse = { * @format int */ complete: number; + /** + * Obligations in this scope whose elapsed expected period has passed its consumer-status deadline — expected_at plus automated_recovery_window_seconds — without a current consumer status from the authenticated caller. A chain with any unsuperseded leaf counts as current whatever that leaf says; only an empty chain is pending. Because it counts obligations, a period the seller omitted entirely has no obligation and is not counted here — the buyer's independently derived denominator, not this field, remains the authority on omitted periods. It is a visibility count over the caller's own silence, never a health input: it MUST NOT change health, any other count, or seller-advertised reliability_statistics, and it overlaps the health counts rather than partitioning them. Required when the seller advertises consumer_status_task. + * @minimum 0 + * @format int + */ + consumer_status_pending?: number; }; issues?: ReportingStatusIssue[]; periods?: ReportingObligation[]; @@ -18181,17 +18976,27 @@ export type ReportingConsumerStatus = { */ reporting_revision_id?: string; /** - * revision_content_sha256 independently recomputed from the exact consumed Core revision binding. Required only for received; unlike a Reconciled Billing receipt it carries no materialization evidence, row totals, canonical digest, or billing acceptance. + * revision_content_sha256 independently recomputed from the exact consumed Core revision binding. Required for received and content_mismatch, where it proves which exact revision content the consumer read; unlike a Reconciled Billing receipt it carries no materialization evidence, row totals, canonical digest, or billing acceptance. */ observed_revision_content_sha256?: string; /** - * received means the exact revision content was successfully consumed; obligation_missing means the independently expected period was absent from the seller ledger; revision_missing means the obligation existed but no required revision was available after expected_at; unreadable means a named revision was advertised but its exact content could not be consumed. None of these values reconciles billing evidence. + * received means the exact revision content was successfully consumed; obligation_missing means the independently expected period was absent from the seller ledger; revision_missing means the obligation existed but no required revision was available after expected_at; unreadable means a named revision was advertised but its exact content could not be consumed; content_mismatch means the exact revision content was read but contradicts a fact the accepted configuration generation already fixed, named by the closed mismatch_code. None of these values reconciles billing evidence, and content_mismatch in particular is not a measurement dispute. */ - consumer_status: 'received' | 'obligation_missing' | 'revision_missing' | 'unreadable'; + consumer_status: 'received' | 'obligation_missing' | 'revision_missing' | 'unreadable' | 'content_mismatch'; /** * When the consumer established this status. For received, this is when the named revision first became consumable to this consumer; sellers use it as buyer-attributed arrival evidence rather than silently substituting publication time. */ status_as_of: string; + /** + * Closed reason the consumed revision contradicts the accepted configuration generation. Each value is decidable from the obligation, the pinned report definition, and the revision itself, with no reference to either party's own measurement. scope_media_buy_missing: a media buy frozen in the obligation's media_buy_ids denominator is absent from the revision and is not represented by an explicit zero row, so the revision cannot distinguish zero delivery from an omitted buy. coverage_short: the revision covers fewer packages than the obligation's frozen coverage.covered_package_ids claims. metric_missing: a metric named in the pinned report definition's metrics[].name is absent from the revision. schema_nonconformant: rows do not validate against the reporting profile's pinned schema_uri and schema_sha256. currency_mismatch: a value's unit disagrees with the unit the pinned report definition fixed for that metric, or a control total's unit disagrees with the profile-defined unit for that name. period_mismatch: the revision carries a time dimension declared by the pinned grain whose values fall outside the obligation's half-open period. Precedence when more than one applies: schema_nonconformant is used only when the failure is structural validation against the pinned schema; a metric that is simply absent uses metric_missing even when the pinned schema declares it required. Each names a contract fact already fixed by the accepted generation, never a difference of opinion about counts. Agents dispatch on this value, not on prose. + */ + mismatch_code?: + | 'scope_media_buy_missing' + | 'coverage_short' + | 'metric_missing' + | 'schema_nonconformant' + | 'currency_mismatch' + | 'period_mismatch'; /** * Typed reason a named revision was unreadable. Agents dispatch on this value, not prose or provider response bodies. */ @@ -18552,7 +19357,7 @@ export interface SyncReportingStatusRequest { */ idempotency_key: string; /** - * Immutable status updates. New state uses a new reporting_status_id and explicitly supersedes the current status for that expected period. A batch contains at most one update for each logical status chain. + * Immutable status updates. New state uses a new reporting_status_id and explicitly supersedes the current status for that expected period. A batch contains at most one update for each logical status chain. content_mismatch entries report a consumed revision that contradicts the accepted configuration generation; they are operational disagreements about contract facts, never measurement disputes. * @maxItems 100 */ statuses: ReportingConsumerStatus[]; @@ -31521,6 +32326,23 @@ export type ReportingDeliveryCapabilities = { * Minimum period for which obligation, revision, and materialization metadata remain queryable. */ status_retention_days: number; + /** + * Maximum interval after a CONSUMER_STATUS_MISMATCH issue's opened_at during which the seller may keep that issue at a non-escalated recommended_action. After it, the issue MUST be action_required with a contact_ recommended_action naming the diagnosed responsible_party. Declaring it requires operations_contact so the escalation has a destination. Absence means the seller publishes no escalation commitment; it never means an unbounded one. + */ + consumer_mismatch_escalation_seconds?: number; + /** + * Optional non-secret human escalation path for reporting issues the protocol cannot resolve. It is display metadata for an operator, not an AdCP endpoint: agents MUST NOT dereference, probe, or send protocol traffic to these values, and they carry no authorization. Required when consumer_mismatch_escalation_seconds is advertised. + */ + operations_contact?: { + /** + * HTTPS page a human uses to open or track a reporting issue, such as a support portal or status page. Same hardened origin shape as the offering document URIs: never an IP literal, userinfo URL, loopback host, AdCP task endpoint, webhook target, or credentialed link. + */ + url?: string; + /** + * Monitored operations mailbox for reporting escalations. A role address, not an individual. + */ + email?: string; + }; /** * Optional evidence-scoped observed performance for advertised offerings. offering_id values MUST be unique and name offerings in this capability block. */ @@ -31749,6 +32571,15 @@ export type ReportingReliabilityStatistics = { evidence: { }; }; +/** + * Seller-wide support for a maximum-impression cap whose single counter is shared across every package in a MediaBuy. Presence is required before a buyer sends a root frequency_cap. Products additionally declare media_buy_support.frequency_cap and any narrower constraints. + */ +export type MediaBuyFrequencyCapCapability = FrequencyCapConstraints & { + /** + * @minItems 1 + */ + supported_control_modes: [MediaBuyFrequencyCapControlMode, ...MediaBuyFrequencyCapControlMode[]]; +}; /** * Source of the default cap-day boundary. account uses the selected Account.timezone and therefore supports different boundaries for different accounts. fixed uses fixed_timezone for every media buy regardless of account timezone. */ @@ -32546,7 +33377,7 @@ export interface GetAdCPCapabilitiesResponse { }[]; }; /** - * Frequency capping capabilities. Presence of this object indicates the seller honors targeting.frequency_cap on packages and MUST reject caps it cannot enforce rather than silently dropping them. Buyers SHOULD inspect supported_per_units and supported_window_units before submitting caps; sellers without these sub-fields populated MAY accept any reach-unit / duration-unit combination they can enforce. Per-product overrides (for sellers with mixed addressable/non-addressable inventory) are a likely follow-up — file a separate RFC if needed. + * Seller-wide package frequency-capping infrastructure. Presence means the seller honors targeting_overlay.frequency_cap on packages, with an independent counter per package, and MUST reject caps it cannot enforce rather than silently dropping them. Product.overlay_support is the binding per-product declaration. A cap whose single counter spans every package in a MediaBuy is advertised separately through aggregate_frequency_capping. */ frequency_capping?: { /** @@ -32558,6 +33389,7 @@ export interface GetAdCPCapabilitiesResponse { */ supported_window_units?: string[]; }; + aggregate_frequency_capping?: MediaBuyFrequencyCapCapability; /** * Hard daily budget-cap capabilities. Presence declares only the scopes listed in supported_scopes; sellers MUST reject a daily_budget_cap at an undeclared scope with UNSUPPORTED_FEATURE before mutation and MUST NOT silently drop or soften it. A cap is always a hard ceiling. Sellers that offer a best-effort pacing target must expose that under a separately named feature rather than interpreting daily_budget_cap as soft. Daily caps are orthogonal to pacing. */ @@ -36178,7 +37010,7 @@ export type GetProductsCompletion = AdCPVersionEnvelope & extensions?: { }; /** - * Optional array of proposed media plans with budget allocations across products. Publishers include proposals when they can provide strategic guidance based on the brief. Proposals are actionable - buyers can refine them via follow-up get_products calls within the same session, or execute them directly via create_media_buy. + * Optional legacy proposed media plans. When the request carries media_buy_frequency_cap, every returned proposal echoes the bound value as proposal.frequency_cap. Buyers may refine or execute a committed proposal by ID. */ proposals?: Proposal[]; /** @@ -36330,7 +37162,7 @@ export type GetProductsCompletion = AdCPVersionEnvelope & }; pagination?: PaginationResponse; /** - * Opaque token representing the version of the wholesale product feed state used to compose this response. Sellers that implement conditional-fetch (if_wholesale_feed_version) MUST return this on every wholesale-mode response so buyers can cache and probe later. Buyers MUST treat the value as opaque — no format, no ordering, no inspection. The token is scope-keyed: it describes a version for the cache_scope declared on this response, NOT a global agent version. A buyer caches `(cache_scope, wholesale_feed_version)` pairs and presents the matching token on the next request. Scoping dimensions: (agent, buying_mode, filters, targeting_overlay, required_overlay_support, deprecated property_list, catalog) for cache_scope: 'public'; that tuple plus account_id for cache_scope: 'account'. pagination.cursor is NOT part of the scoping tuple. See specs/wholesale-feed-webhooks.md for the full cache layering model. + * Opaque token representing the version of the wholesale product feed state used to compose this response. Sellers that implement conditional-fetch (if_wholesale_feed_version) MUST return this on every wholesale-mode response so buyers can cache and probe later. Buyers MUST treat the value as opaque — no format, no ordering, no inspection. The token is scope-keyed: it describes a version for the cache_scope declared on this response, NOT a global agent version. A buyer caches `(cache_scope, wholesale_feed_version)` pairs and presents the matching token on the next request. Scoping dimensions: (agent, buying_mode, filters, targeting_overlay, media_buy_frequency_cap, required_overlay_support, required_media_buy_support, deprecated property_list, catalog) for cache_scope: 'public'; that tuple plus account_id for cache_scope: 'account'. pagination.cursor is NOT part of the scoping tuple. See specs/wholesale-feed-webhooks.md for the full cache layering model. */ wholesale_feed_version?: string; /** @@ -36338,7 +37170,7 @@ export type GetProductsCompletion = AdCPVersionEnvelope & */ pricing_version?: string; /** - * Declares whether the wholesale_feed_version and pricing_version on this response describe a universal layer or an account-specific overlay. REQUIRED on every 3.1+ response (the 3.1 schema enforces this — the safety property of the two-layer cache model depends on it). 'public': this response describes the seller's published rate card; the buyer MAY dedupe under (agent, buying_mode, filters, targeting_overlay, required_overlay_support, deprecated property_list, catalog) without scoping by account. 'account': this response includes account-specific overrides; the buyer MUST cache the version under (agent, buying_mode, filters, targeting_overlay, required_overlay_support, deprecated property_list, catalog, account_id). When the request did NOT include `account`, the seller MUST return `cache_scope: 'public'`. When the request included `account`, the seller MUST return either: 'public' (this account prices off the public rate card — buyer dedupes) or 'account' (account-specific overrides exist — buyer caches under the account key). Sellers MAY return 'public' on an account-scoped request that previously had overrides — buyers SHOULD interpret this as a downgrade and drop their account-overlay for the (agent, filters, targeting, support, mode) tuple. Without schema-required cache_scope, a seller silently omitting the field on an account-scoped response would cause buyers to mis-key the cache and serve account-overlay payloads to other accounts — the canonical safety invariant of the entire cache layering model. **Backward-compatibility note for 3.1 validators:** SDKs that validate strictly against the 3.1 schema MUST select the validator based on the server-declared `adcp_version` (release-precision version negotiation, 3.1). For responses with `adcp_version` starting `3.0`, the 3.1 cache_scope-required constraint MUST be relaxed — pre-3.1 sellers correctly emit no cache_scope and remain conformant to their declared version. This is a tightening within 3.1, not a 3.0 break. + * Declares whether the wholesale_feed_version and pricing_version on this response describe a universal layer or an account-specific overlay. REQUIRED on every 3.1+ response (the 3.1 schema enforces this — the safety property of the two-layer cache model depends on it). 'public': this response describes the seller's published rate card; the buyer MAY dedupe under (agent, buying_mode, filters, targeting_overlay, media_buy_frequency_cap, required_overlay_support, required_media_buy_support, deprecated property_list, catalog) without scoping by account. 'account': this response includes account-specific overrides; the buyer MUST cache the version under that tuple plus account_id. When the request did NOT include `account`, the seller MUST return `cache_scope: 'public'`. When the request included `account`, the seller MUST return either: 'public' (this account prices off the public rate card — buyer dedupes) or 'account' (account-specific overrides exist — buyer caches under the account key). Sellers MAY return 'public' on an account-scoped request that previously had overrides — buyers SHOULD interpret this as a downgrade and drop their account-overlay. Without schema-required cache_scope, a seller silently omitting the field on an account-scoped response would cause buyers to mis-key the cache and serve account-overlay payloads to other accounts. **Backward-compatibility note for 3.1 validators:** SDKs that validate strictly against the 3.1 schema MUST select the validator based on the server-declared `adcp_version` (release-precision version negotiation, 3.1). For responses with `adcp_version` starting `3.0`, the 3.1 cache_scope-required constraint MUST be relaxed. */ cache_scope?: 'public' | 'account'; /** @@ -36446,7 +37278,7 @@ export interface ComplyTestControllerRequest { */ adcp_major_version?: number; /** - * Test scenario to execute. 'list_scenarios' discovers supported scenarios. 'force_*' and 'simulate_*' trigger state transitions. 'reporting_core_lifecycle_probe' installs a caller/account-scoped Core fixture whose first elapsed obligation is visible before any report, advances its virtual clock into delayed or action_required, and can publish deterministic zero-row or non-empty revisions without waiting for wall-clock boundaries. Other scenarios provide deterministic sandbox probes for their documented lifecycle checks. Runners and sellers MUST accept unknown scenario strings - new scenarios may be added in additive releases. + * Test scenario to execute. 'list_scenarios' discovers supported scenarios. 'force_*' and 'simulate_*' trigger state transitions. 'reporting_core_lifecycle_probe' installs a caller/account-scoped Core fixture whose first elapsed obligation is visible before any report, advances its virtual clock into delayed or action_required, and can publish deterministic zero-row or non-empty revisions, restate a provisional revision, or restate one the caller already received, without waiting for wall-clock boundaries. Other scenarios provide deterministic sandbox probes for their documented lifecycle checks. Runners and sellers MUST accept unknown scenario strings - new scenarios may be added in additive releases. */ scenario: string; /** @@ -36495,7 +37327,7 @@ export interface ComplyTestControllerRequest { */ fixture?: {}; /** - * Scenario-specific probe operation. catalog_item_availability_probe uses seed_inaccessible_item, query_eligibility, advance_time, and recreate_catalog. compact_product_lifecycle_probe uses prepare to make one seeded product's compact proposal, acceptance, operational-control, and MediaBuy readback path deterministic and expire_proposal to advance strictly beyond a committed proposal's stored expires_at and process the hold lapse. compact_direct_buy_lifecycle_probe uses prepare to make one seeded product's list, direct-purchase, operational-control, and readback path deterministic. reporting_core_lifecycle_probe uses prepare, advance_time, publish_zero_row, publish_nonempty, restate_snapshot, and omit_obligation to exercise obligation availability, health deadlines, explicit reporting, provisional restatement, and buyer-side missing-obligation detection. restate_snapshot publishes a new snapshot revision that immediately supersedes the current snapshot for the same logical slice and is invalid when the current revision is official. Reliable Reporting tier probes use prepare plus publish_official_adjustment, probe_scheduler_dst, suppress_readiness, advance_within_retention, revoke_access, or publish_adjustment to seed deterministic Core-integrity, Managed Delivery, and Reconciled Billing lifecycle evidence. + * Scenario-specific probe operation. catalog_item_availability_probe uses seed_inaccessible_item, query_eligibility, advance_time, and recreate_catalog. compact_product_lifecycle_probe uses prepare to make one seeded product's compact proposal, acceptance, operational-control, and MediaBuy readback path deterministic and expire_proposal to advance strictly beyond a committed proposal's stored expires_at and process the hold lapse. compact_direct_buy_lifecycle_probe uses prepare to make one seeded product's list, direct-purchase, operational-control, and readback path deterministic. reporting_core_lifecycle_probe uses prepare, advance_time, publish_zero_row, publish_nonempty, restate_snapshot, restate_after_received, and omit_obligation to exercise obligation availability, health deadlines, explicit reporting, provisional restatement, stale-received grace, and buyer-side missing-obligation detection. restate_snapshot publishes a new snapshot revision that immediately supersedes the current snapshot for the same logical slice and is invalid when the current revision is official. restate_after_received does the same restatement but only against the revision named in received_reporting_revision_id, so the stale-received grace projection can be graded live; it returns the grace deadline and advance_to positions the virtual clock inside or past it. Reliable Reporting tier probes use prepare plus publish_official_adjustment, probe_scheduler_dst, suppress_readiness, advance_within_retention, revoke_access, or publish_adjustment to seed deterministic Core-integrity, Managed Delivery, and Reconciled Billing lifecycle evidence. */ operation?: | 'seed_inaccessible_item' @@ -36507,6 +37339,7 @@ export interface ComplyTestControllerRequest { | 'publish_zero_row' | 'publish_nonempty' | 'restate_snapshot' + | 'restate_after_received' | 'omit_obligation' | 'publish_official_adjustment' | 'probe_scheduler_dst' @@ -36518,6 +37351,17 @@ export interface ComplyTestControllerRequest { * Clock-derived health boundary selected by reporting_core_lifecycle_probe advance_time. The controller chooses the corresponding deterministic target time; callers do not supply timestamps. */ target_health?: 'delayed' | 'action_required'; + /** + * Revision the caller currently reports as received, required by reporting_core_lifecycle_probe restate_after_received. The seller MUST reject the operation unless this names the caller's current required revision for the fixture obligation, and a seller advertising consumer_status_task MUST additionally require a current received consumer status from this caller naming it. This binds the restatement to a real prior read instead of restating into a vacuum. + * @minLength 1 + * @maxLength 255 + * @pattern ^[A-Za-z0-9_.:-]{1,255}$ + */ + received_reporting_revision_id?: string; + /** + * Where reporting_core_lifecycle_probe restate_after_received leaves the virtual clock relative to the returned stale_received_grace_deadline. within_grace grades the delayed projection; past_grace grades the escalation to action_required. Repeating the operation is convergent: it reuses the committed restatement and only moves the clock. + */ + advance_to?: 'within_grace' | 'past_grace'; /** * Catalog operated on by catalog_item_availability_probe. * @minLength 1 @@ -36901,7 +37745,7 @@ export type ComplyTestControllerResponse = { export interface ListScenariosSuccess { success: true; /** - * Scenarios this seller has implemented. Runners and sellers MUST accept unknown scenario strings (open-for-extension) — new scenarios may be added in additive releases. Adopters who advertise `catalog_item_availability_probe` support deterministic cross-principal reference, eligibility-gate, expiry-clock, and catalog-generation tests for the catalog availability storyboard. Adopters who advertise `compact_product_lifecycle_probe` support deterministic synchronous list/request/finalize/decline/accept/control/readback behavior for a prepared product and strict post-deadline expiry of a committed proposal. Adopters who advertise `compact_direct_buy_lifecycle_probe` support deterministic synchronous list/buy/control/readback behavior for a prepared product. Adopters who advertise `reporting_core_lifecycle_probe` support deterministic obligation-before-report, clock-health, zero-row reporting, and provisional-restatement tests without wall-clock waits. `reliable_reporting_core_integrity_probe`, `reliable_reporting_managed_delivery_probe`, and `reliable_reporting_reconciled_billing_probe` seed the source-calendar/checkpoint, managed-resource, and receipt/adjustment workflows used by the Reliable Reporting tier storyboards. Adopters who advertise `force_creative_purge` opt in to deterministic creative purge coverage for account-level lifecycle webhooks. Adopters who advertise `seed_measurement_catalog` opt in to deterministic measurement-catalog fixtures used by vendor_metric precondition storyboards. Adopters who advertise `query_upstream_traffic` opt in to the upstream-traffic conformance contract; storyboards that declare `check: upstream_traffic` grade not_applicable against adopters who do not advertise it. Adopters who advertise `query_provenance_audit_observations` opt in to sandbox-only audit-observation assertions for accepted creatives. Adopters who advertise `force_upstream_unavailable` opt in to stale-cache conformance testing via the `stale_response_advisory` storyboard. + * Scenarios this seller has implemented. Runners and sellers MUST accept unknown scenario strings (open-for-extension) — new scenarios may be added in additive releases. Adopters who advertise `catalog_item_availability_probe` support deterministic cross-principal reference, eligibility-gate, expiry-clock, and catalog-generation tests for the catalog availability storyboard. Adopters who advertise `compact_product_lifecycle_probe` support deterministic synchronous list/request/finalize/decline/accept/control/readback behavior for a prepared product and strict post-deadline expiry of a committed proposal. Adopters who advertise `compact_direct_buy_lifecycle_probe` support deterministic synchronous list/buy/control/readback behavior for a prepared product. Adopters who advertise `reporting_core_lifecycle_probe` support deterministic obligation-before-report, clock-health, zero-row reporting, provisional-restatement, and post-received restatement-grace tests without wall-clock waits. `reliable_reporting_core_integrity_probe`, `reliable_reporting_managed_delivery_probe`, and `reliable_reporting_reconciled_billing_probe` seed the source-calendar/checkpoint, managed-resource, and receipt/adjustment workflows used by the Reliable Reporting tier storyboards. Adopters who advertise `force_creative_purge` opt in to deterministic creative purge coverage for account-level lifecycle webhooks. Adopters who advertise `seed_measurement_catalog` opt in to deterministic measurement-catalog fixtures used by vendor_metric precondition storyboards. Adopters who advertise `query_upstream_traffic` opt in to the upstream-traffic conformance contract; storyboards that declare `check: upstream_traffic` grade not_applicable against adopters who do not advertise it. Adopters who advertise `query_provenance_audit_observations` opt in to sandbox-only audit-observation assertions for accepted creatives. Adopters who advertise `force_upstream_unavailable` opt in to stale-cache conformance testing via the `stale_response_advisory` storyboard. */ scenarios: string[]; context?: ContextObject; @@ -36928,7 +37772,7 @@ export interface StateTransitionSuccess { ext?: ExtensionObject; } /** - * A simulate_delivery, simulate_budget_spend, catalog_item_availability_probe, compact_product_lifecycle_probe, compact_direct_buy_lifecycle_probe, reporting_core_lifecycle_probe, or Reliable Reporting tier-probe operation succeeded. For delivery: simulated contains the metrics injected by this call (impressions/clicks/plays/reported_spend/conversions plus optional DOOH, reach, frequency, reach-window, and viewability values) and cumulative contains running totals or latest non-additive metric state. For budget: simulated contains spend_percentage/computed_spend/budget. For catalog availability: simulated reports seeded foreign identity, actual eligibility gates, processed expiry time, or delete/recreate generation rotation according to params.operation. For compact product lifecycle: simulated reports deterministic preparation through MediaBuy control/readback or strict post-deadline proposal expiry. For compact direct-buy lifecycle: simulated reports deterministic preparation. For reporting Core: simulated reports the fixed virtual time plus stable account, configuration, obligation, and revision identifiers created or advanced by the operation; prepare also reports the complete resolved configuration, period, expected_at, and recovery_deadline, and restate_snapshot reports the new revision plus supersedes_reporting_revision_id. Reliable Reporting tier probes return the exact seeded ledger IDs, checkpoints, notification order, resource lifecycle evidence, and receipt bodies required by their storyboards. + * A simulate_delivery, simulate_budget_spend, catalog_item_availability_probe, compact_product_lifecycle_probe, compact_direct_buy_lifecycle_probe, reporting_core_lifecycle_probe, or Reliable Reporting tier-probe operation succeeded. For delivery: simulated contains the metrics injected by this call (impressions/clicks/plays/reported_spend/conversions plus optional DOOH, reach, frequency, reach-window, and viewability values) and cumulative contains running totals or latest non-additive metric state. For budget: simulated contains spend_percentage/computed_spend/budget. For catalog availability: simulated reports seeded foreign identity, actual eligibility gates, processed expiry time, or delete/recreate generation rotation according to params.operation. For compact product lifecycle: simulated reports deterministic preparation through MediaBuy control/readback or strict post-deadline proposal expiry. For compact direct-buy lifecycle: simulated reports deterministic preparation. For reporting Core: simulated reports the fixed virtual time plus stable account, configuration, obligation, and revision identifiers created or advanced by the operation; prepare also reports the complete resolved configuration, period, expected_at, and recovery_deadline, restate_snapshot reports the new revision plus supersedes_reporting_revision_id, and restate_after_received additionally reports received_reporting_revision_id, restated_at, and stale_received_grace_deadline. Reliable Reporting tier probes return the exact seeded ledger IDs, checkpoints, notification order, resource lifecycle evidence, and receipt bodies required by their storyboards. */ export interface SimulationSuccess { success: true; diff --git a/src/lib/version.ts b/src/lib/version.ts index c4dc590fa..747912841 100644 --- a/src/lib/version.ts +++ b/src/lib/version.ts @@ -9,7 +9,7 @@ export const LIBRARY_VERSION = '14.0.0-rc.36'; /** * AdCP specification version this library is built for */ -export const ADCP_VERSION = '3.2.0-rc.2'; +export const ADCP_VERSION = '3.2.0-rc.3'; /** * AdCP major version sent with every request (adcp_major_version field). @@ -81,8 +81,8 @@ export const COMPATIBLE_ADCP_VERSIONS = [ '3.1.16', '3.1.17', '3.1.18', - '3.2.0-rc.2', - '3.2-rc.2', + '3.2.0-rc.3', + '3.2-rc.3', ] as const; /** @@ -100,9 +100,9 @@ export type AdcpVersion = (typeof COMPATIBLE_ADCP_VERSIONS)[number]; */ export const VERSION_INFO = { library: '14.0.0-rc.36', - adcp: '3.2.0-rc.2', + adcp: '3.2.0-rc.3', compatibleVersions: COMPATIBLE_ADCP_VERSIONS, - generatedAt: '2026-09-14T13:27:21.313Z', + generatedAt: '2026-09-14T14:22:59.344Z', } as const; /** diff --git a/test/capabilities-overrides.test.js b/test/capabilities-overrides.test.js index cf955ba0a..9141280b8 100644 --- a/test/capabilities-overrides.test.js +++ b/test/capabilities-overrides.test.js @@ -276,7 +276,7 @@ describe('capabilities.overrides — per-domain merge (#654)', () => { }); const caps = await callCapabilities(server); assert.strictEqual(caps.request_signing.covers_content_digest, 'required'); - assert.strictEqual(caps.adcp_version, '3.2-rc.2'); + assert.strictEqual(caps.adcp_version, '3.2-rc.3'); }); it('undefined overrides are no-ops', async () => { diff --git a/test/examples/hello-seller-adapter-non-guaranteed.test.js b/test/examples/hello-seller-adapter-non-guaranteed.test.js index 295284b7a..f01020380 100644 --- a/test/examples/hello-seller-adapter-non-guaranteed.test.js +++ b/test/examples/hello-seller-adapter-non-guaranteed.test.js @@ -42,7 +42,7 @@ runHelloAdapterGates({ sandbox: true, }; const created = await callTool('create_media_buy', { - adcp_version: '3.2-rc.2', + adcp_version: '3.2-rc.3', idempotency_key: 'sequential-budget-create-0001', account, brand: { domain: 'buyer.example' }, @@ -59,14 +59,14 @@ runHelloAdapterGates({ assert.equal(buy.packages.length, 2); await callTool('update_media_buy', { - adcp_version: '3.2-rc.2', + adcp_version: '3.2-rc.3', idempotency_key: 'sequential-budget-update-0001', account, media_buy_id: buy.media_buy_id, packages: [{ package_id: buy.packages[0].package_id, budget: 800 }], }); await callTool('update_media_buy', { - adcp_version: '3.2-rc.2', + adcp_version: '3.2-rc.3', idempotency_key: 'sequential-budget-update-0002', account, media_buy_id: buy.media_buy_id, @@ -74,7 +74,7 @@ runHelloAdapterGates({ }); const read = await callTool('get_media_buys', { - adcp_version: '3.2-rc.2', + adcp_version: '3.2-rc.3', account, media_buy_ids: [buy.media_buy_id], }); @@ -95,7 +95,7 @@ runHelloAdapterGates({ sandbox: true, }; const created = await callTool('create_media_buy', { - adcp_version: '3.2-rc.2', + adcp_version: '3.2-rc.3', idempotency_key: 'terminal-budget-create-0001', account, brand: { domain: 'buyer.example' }, @@ -106,7 +106,7 @@ runHelloAdapterGates({ const buy = created.structuredContent; assert.ok(buy?.media_buy_id, JSON.stringify(created)); await callTool('update_media_buy', { - adcp_version: '3.2-rc.2', + adcp_version: '3.2-rc.3', idempotency_key: 'terminal-budget-cancel-0001', account, media_buy_id: buy.media_buy_id, @@ -114,7 +114,7 @@ runHelloAdapterGates({ }); const before = await fetch(`${mockUrl}/_debug/traffic`).then(response => response.json()); const rejected = await callTool('update_media_buy', { - adcp_version: '3.2-rc.2', + adcp_version: '3.2-rc.3', idempotency_key: 'terminal-budget-update-0001', account, media_buy_id: buy.media_buy_id, diff --git a/test/fixtures/reporting-reconciliation/consumer-status.json b/test/fixtures/reporting-reconciliation/consumer-status.json index 5e5a8597c..766bc19be 100644 --- a/test/fixtures/reporting-reconciliation/consumer-status.json +++ b/test/fixtures/reporting-reconciliation/consumer-status.json @@ -1,6 +1,6 @@ { "version": "1.0", - "protocol_version": "3.2.0-rc.2", + "protocol_version": "3.2.0-rc.3", "description": "Portable sync_reporting_status acceptance vectors. Consumer status is an operational acknowledgement, never a managed-delivery or billing-receipt oracle.", "frozen": { "clocks": { diff --git a/test/fixtures/reporting-reconciliation/fixture.json b/test/fixtures/reporting-reconciliation/fixture.json index e2a3e9652..6f21efcc7 100644 --- a/test/fixtures/reporting-reconciliation/fixture.json +++ b/test/fixtures/reporting-reconciliation/fixture.json @@ -23,7 +23,7 @@ }, "consumer-status.json": { "size_bytes": 59976, - "sha256": "59a6edd4abde344ba882117e51c25069bd54a04e34d89f7189d2eddce5e91917" + "sha256": "d9a84be67f80108cc0af7ea6fef073dac1eeaab5ca9071e1043286994ad05c7b" } }, "expected": { diff --git a/test/generate-zod-consumer-status.test.js b/test/generate-zod-consumer-status.test.js index 9b74f2293..a3bd29306 100644 --- a/test/generate-zod-consumer-status.test.js +++ b/test/generate-zod-consumer-status.test.js @@ -65,7 +65,7 @@ function request(item) { } function response(result) { - return { adcp_version: '3.2-rc.2', adcp_major_version: 3, status: 'completed', results: [result] }; + return { adcp_version: '3.2-rc.3', adcp_major_version: 3, status: 'completed', results: [result] }; } const canonical = JSON.parse(fs.readFileSync(SCHEMAS.status, 'utf8')); diff --git a/test/lib/adcp-major-version.test.js b/test/lib/adcp-major-version.test.js index 1f26aecd4..9f03e48d3 100644 --- a/test/lib/adcp-major-version.test.js +++ b/test/lib/adcp-major-version.test.js @@ -201,10 +201,10 @@ describe('AdCP 3.2 strict compact request envelopes', () => { const agent = { id: 'beta1-a2a', name: 'beta1-a2a', agent_uri: 'https://seller.example/a2a', protocol: 'a2a' }; for (const [toolName, request] of Object.entries(compactRequests)) { - const prepared = prepareProtocolToolCall(agent, request, { toolName, adcpVersion: '3.2.0-rc.2' }).args; - assert.strictEqual(prepared.adcp_version, '3.2-rc.2', `${toolName} keeps the release pin`); + const prepared = prepareProtocolToolCall(agent, request, { toolName, adcpVersion: '3.2.0-rc.3' }).args; + assert.strictEqual(prepared.adcp_version, '3.2-rc.3', `${toolName} keeps the release pin`); assert.strictEqual(prepared.adcp_major_version, 3, `${toolName} keeps the SDK-injected major`); - const validation = validateRequest(toolName, prepared, '3.2.0-rc.2'); + const validation = validateRequest(toolName, prepared, '3.2.0-rc.3'); assert.strictEqual(validation.valid, true, `${toolName}: ${JSON.stringify(validation.issues)}`); } }); diff --git a/test/lib/beta6-reporting-version.test.js b/test/lib/beta6-reporting-version.test.js index 1c607a798..ff59d1771 100644 --- a/test/lib/beta6-reporting-version.test.js +++ b/test/lib/beta6-reporting-version.test.js @@ -12,7 +12,7 @@ function clientForSellerVersion(version) { protocol: 'mcp', }, { - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', validateFeatures: false, validation: { requests: 'off', responses: 'off' }, } diff --git a/test/lib/capability-probe-operation-id.test.js b/test/lib/capability-probe-operation-id.test.js index 53a75f68d..e0fa8bf81 100644 --- a/test/lib/capability-probe-operation-id.test.js +++ b/test/lib/capability-probe-operation-id.test.js @@ -63,10 +63,10 @@ async function createHarness(mutationName, { clientConfig = {}, beforeCapabiliti await beforeCapabilitiesResponse?.(); return toolResult({ status: 'completed', - adcp_version: '3.2.0-rc.2', + adcp_version: '3.2.0-rc.3', adcp: { major_versions: [3], - supported_versions: ['3.2.0-rc.2'], + supported_versions: ['3.2.0-rc.3'], idempotency: { supported: true, replay_ttl_seconds: 86400 }, }, supported_protocols: ['media_buy'], diff --git a/test/lib/cli-storyboard-file-flag.test.js b/test/lib/cli-storyboard-file-flag.test.js index 39770496e..bc813a8d4 100644 --- a/test/lib/cli-storyboard-file-flag.test.js +++ b/test/lib/cli-storyboard-file-flag.test.js @@ -208,7 +208,7 @@ test('--file forwards explicit cache authority for a declared test kit', { timeo const cliHome = path.join(fixtureRoot, 'home'); mkdirSync(kitDir, { recursive: true }); mkdirSync(cliHome, { recursive: true }); - writeComplianceIndex(complianceDir, '3.2.0-rc.2'); + writeComplianceIndex(complianceDir, '3.2.0-rc.3'); writeFileSync( path.join(kitDir, 'live.yaml'), ['auth:', ' api_key: "cli-declared-kit-key"', ' probe_task: list_creatives', ''].join('\n') @@ -287,7 +287,7 @@ test('--file forwards explicit cache authority for a declared test kit', { timeo assert.strictEqual(explicitDir.status, 0, explicitDir.stderr); assert.ok(authorizations.includes('Bearer cli-declared-kit-key')); - const versionOnly = await run(['--compliance-version', '3.2.0-rc.2'], { + const versionOnly = await run(['--compliance-version', '3.2.0-rc.3'], { ADCP_COMPLIANCE_DIR: complianceDir, }); assert.strictEqual(versionOnly.status, 0, versionOnly.stderr); diff --git a/test/lib/cli-test-kit-compliance-version.test.js b/test/lib/cli-test-kit-compliance-version.test.js index a1738ddd8..3de0a2327 100644 --- a/test/lib/cli-test-kit-compliance-version.test.js +++ b/test/lib/cli-test-kit-compliance-version.test.js @@ -327,7 +327,7 @@ describe('storyboard run --test-kit compliance-line selection', () => { }); test('malformed test-kit YAML never echoes source credentials', () => { - const fixture = createTestKitCache('3.2.0-rc.2'); + const fixture = createTestKitCache('3.2.0-rc.3'); const secret = 'sk-cli-secret-that-must-not-reach-stderr'; writeFileSync(fixture.testKitPath, `auth: [${secret}`); try { @@ -350,7 +350,7 @@ describe('storyboard run --test-kit compliance-line selection', () => { }); test('a falsy parsed --test-kit is forwarded and rejected instead of falling back to disk', () => { - const fixture = createTestKitCache('3.2.0-rc.2'); + const fixture = createTestKitCache('3.2.0-rc.3'); writeFileSync(fixture.testKitPath, 'null\n'); try { const result = runCli([ diff --git a/test/lib/compact-commitment-cli.test.js b/test/lib/compact-commitment-cli.test.js index 117f85b68..824e27d1e 100644 --- a/test/lib/compact-commitment-cli.test.js +++ b/test/lib/compact-commitment-cli.test.js @@ -96,7 +96,7 @@ before(async () => { createAdcpServer({ name: 'Compact commitment seller', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', idempotency: 'disabled', validation: { requests: 'strict', responses: 'strict' }, mediaBuy: { @@ -167,7 +167,7 @@ for (const [tool, payload] of calls) { ); assert.doesNotMatch(result.stderr, /Schema validation failed/, `${tool}: ${result.stderr}`); const output = JSON.parse(result.stdout); - assert.strictEqual(output.data.adcp_version, '3.2-rc.2'); + assert.strictEqual(output.data.adcp_version, '3.2-rc.3'); assert.strictEqual(output.data.media_buy_id, 'mb-1'); }); } diff --git a/test/lib/compact-lifecycle-storyboard-runner.test.js b/test/lib/compact-lifecycle-storyboard-runner.test.js index bfe20ff46..d07209cc3 100644 --- a/test/lib/compact-lifecycle-storyboard-runner.test.js +++ b/test/lib/compact-lifecycle-storyboard-runner.test.js @@ -12,7 +12,7 @@ const { TOOL_INPUT_SHAPE, toMcpResponse } = require('../../dist/lib/server/test- const { getComplianceStoryboardById } = require('../../dist/lib/testing/storyboard/index.js'); const { runStoryboard } = require('../../dist/lib/testing/storyboard/runner.js'); -const ADCP_VERSION = '3.2.0-rc.2'; +const ADCP_VERSION = '3.2.0-rc.3'; const ACCOUNT = { brand: { domain: 'acmeoutdoor.example' }, operator: 'pinnacle-agency.example', @@ -56,7 +56,7 @@ function closeServer(server) { } function assertBeta3Envelope(request) { - assert.equal(request.adcp_version, '3.2-rc.2'); + assert.equal(request.adcp_version, '3.2-rc.3'); assert.equal(request.adcp_major_version, 3); } diff --git a/test/lib/conformance-arbitrary.test.js b/test/lib/conformance-arbitrary.test.js index 68ad03dd4..df4994467 100644 --- a/test/lib/conformance-arbitrary.test.js +++ b/test/lib/conformance-arbitrary.test.js @@ -64,7 +64,7 @@ describe('conformance: schemaToArbitrary', { concurrency: false }, () => { assert.ok(!UPDATE_TIER_TOOLS.includes(tool), `${tool} is not forced into legacy defaults`); } for (const tool of compactTools) { - assert.equal(hasSchemas(tool, { version: '3.2.0-rc.2' }), true, `${tool} 3.2 schemas are loadable`); + assert.equal(hasSchemas(tool, { version: '3.2.0-rc.3' }), true, `${tool} 3.2 schemas are loadable`); assert.equal(hasSchemas(tool, { version: '3.1.18' }), false, `${tool} is gated out of 3.1`); assert.equal(hasSchemas(tool, { version: '3.0.25' }), false, `${tool} is gated out of 3.0`); } @@ -74,9 +74,9 @@ describe('conformance: schemaToArbitrary', { concurrency: false }, () => { const versionOnly = prepareConformanceProbeRequest( 'list_products', { adcp_version: '99.99' }, - { adcpVersion: '3.2.0-rc.2' } + { adcpVersion: '3.2.0-rc.3' } ); - assert.equal(versionOnly.adcp_version, '3.2-rc.2'); + assert.equal(versionOnly.adcp_version, '3.2-rc.3'); assert.equal(Object.hasOwn(versionOnly, 'adcp_major_version'), false); const majorOnly = prepareConformanceProbeRequest( @@ -140,8 +140,8 @@ describe('conformance: schemaToArbitrary', { concurrency: false }, () => { }; for (const [tool, sample] of Object.entries(samples)) { - const probe = prepareConformanceProbeRequest(tool, sample, { fixtures, adcpVersion: '3.2.0-rc.2' }); - const validate = makeAjv().compile(loadRequestSchema(tool, { version: '3.2.0-rc.2' })); + const probe = prepareConformanceProbeRequest(tool, sample, { fixtures, adcpVersion: '3.2.0-rc.3' }); + const validate = makeAjv().compile(loadRequestSchema(tool, { version: '3.2.0-rc.3' })); assert.equal(validate(probe), true, `${tool}: ${JSON.stringify(validate.errors)}`); } diff --git a/test/lib/conformance-seeder.test.js b/test/lib/conformance-seeder.test.js index 2554fa637..5dff52494 100644 --- a/test/lib/conformance-seeder.test.js +++ b/test/lib/conformance-seeder.test.js @@ -271,7 +271,7 @@ describe('conformance: seedFixtures', () => { }); let proposalSequence = 0; const { server, port } = await startAgent({ - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', // This regression fixture must stay valid against the selected rc.2 // response schemas. Strict mode turns schema drift into a test failure // instead of the SDK's usual non-blocking validation warning. @@ -419,7 +419,7 @@ describe('conformance: seedFixtures', () => { brand_id: 'compact_brand', }); assert.equal(observed.bought.length, 1); - assert.equal(observed.bought[0].adcp_version, '3.2-rc.2'); + assert.equal(observed.bought[0].adcp_version, '3.2-rc.3'); assert.equal(observed.bought[0].adcp_major_version, 3); assert.match(observed.bought[0].idempotency_key, /^[0-9a-f-]{36}$/); assert.equal(observed.bought[0].feed_version, 'feed-compact-1'); @@ -435,7 +435,7 @@ describe('conformance: seedFixtures', () => { test('default seeding does not probe the compact lifecycle unless the selected bundle enables it', async () => { let compactCalls = 0; const { server, port } = await startAgent({ - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', mediaBuy: { getProducts: async () => ({ products: [], cache_scope: 'public' }), listProducts: async () => { diff --git a/test/lib/functional-request-signing.test.js b/test/lib/functional-request-signing.test.js index 5d7d4c7d5..36ea08dc4 100644 --- a/test/lib/functional-request-signing.test.js +++ b/test/lib/functional-request-signing.test.js @@ -136,7 +136,7 @@ async function startSigningCaptureSeller() { return mcpResult({ adcp: { major_versions: [3], - supported_versions: ['3.2.0-rc.2'], + supported_versions: ['3.2.0-rc.3'], idempotency: { supported: true, replay_ttl_seconds: 86400 }, }, supported_protocols: ['media_buy'], @@ -255,7 +255,7 @@ describe('functional request signing', () => { replayStore, revocationStore: new InMemoryRevocationStore(), operation: 'get_products', - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', }); assert.strictEqual(verified.status, 'verified'); assert.strictEqual(verified.keyid, options.functional_request_signing.kid); @@ -541,7 +541,7 @@ describe('functional request signing', () => { const options = applyFunctionalRequestSigning( { sandbox: true, - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', wireAdcpVersion: '3.1.0', _profile: { name: 'Versioned seller', @@ -562,7 +562,7 @@ describe('functional request signing', () => { await getOrDiscoverProfile(client, options); const wireContext = buildAgentSigningContext(client.getAgent(), { adcpVersion: '3.1.0' }); - const schemaContext = buildAgentSigningContext(client.getAgent(), { adcpVersion: '3.2.0-rc.2' }); + const schemaContext = buildAgentSigningContext(client.getAgent(), { adcpVersion: '3.2.0-rc.3' }); assert.deepStrictEqual(wireContext.cache.get(wireContext.capabilityCacheKey)?.requestSigning, { supported: true, required_for: ['get_products'], @@ -583,10 +583,10 @@ describe('functional request signing', () => { }, }; - seedTestClientSigningCapability(client, profile, '3.2.0-rc.2'); + seedTestClientSigningCapability(client, profile, '3.2.0-rc.3'); const pinnedContext = buildAgentSigningContext(client.getAgent(), { adcpVersion: '3.1.0' }); - const fallbackContext = buildAgentSigningContext(client.getAgent(), { adcpVersion: '3.2.0-rc.2' }); + const fallbackContext = buildAgentSigningContext(client.getAgent(), { adcpVersion: '3.2.0-rc.3' }); assert.deepStrictEqual(pinnedContext.cache.get(pinnedContext.capabilityCacheKey)?.requestSigning, { supported: true, required_for: ['get_products'], diff --git a/test/lib/get-signals-pre31-wholesale.test.js b/test/lib/get-signals-pre31-wholesale.test.js index e6d6f1b08..8c595411c 100644 --- a/test/lib/get-signals-pre31-wholesale.test.js +++ b/test/lib/get-signals-pre31-wholesale.test.js @@ -63,7 +63,7 @@ function makeModernClientTargeting30(protocol = 'mcp', config = {}, capabilityOv protocol, }, { - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', validateFeatures: false, validation: { requests: 'off', responses: 'off' }, ...config, diff --git a/test/lib/mcp-modern-negotiation.test.js b/test/lib/mcp-modern-negotiation.test.js index af95b0f1a..3a35335e4 100644 --- a/test/lib/mcp-modern-negotiation.test.js +++ b/test/lib/mcp-modern-negotiation.test.js @@ -600,7 +600,7 @@ test('modern serving returns structured AdCP validation errors while advertising createAdcpServer({ name: 'modern-validation-test', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', mcpToolProfile: 'all', stateStore: new InMemoryStateStore(), validation: { requests: 'off', responses: 'off' }, @@ -685,7 +685,7 @@ test('modern serving honors the resolved AdCP MCP tool profile', async () => { createAdcpServer({ name: 'modern-profile-test', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', idempotency: 'disabled', ...(mcpToolProfile !== undefined && { mcpToolProfile }), stateStore: new InMemoryStateStore(), @@ -766,7 +766,7 @@ test('modern serving honors the resolved AdCP MCP tool profile', async () => { compactNames.every(name => MEDIA_BUY_MCP_TOOL_PROFILE.includes(name)), compactNames.join(', ') ); - assert.equal(compact._meta.adcp_version, '3.2.0-rc.2'); + assert.equal(compact._meta.adcp_version, '3.2.0-rc.3'); assert.equal(compact._meta.adcp_profile, 'media-buy'); assert.equal( compact.tools.find(tool => tool.name === 'list_products').description, @@ -811,7 +811,7 @@ test('modern serving honors the resolved AdCP MCP tool profile', async () => { 'https://json-schema.org/draft/2020-12/schema' ); assert.doesNotMatch(all.tools.find(tool => tool.name === 'request_proposals').inputSchema.$id, /\/profiles\//); - assert.equal(all._meta.adcp_version, '3.2.0-rc.2'); + assert.equal(all._meta.adcp_version, '3.2.0-rc.3'); assert.equal(all._meta.adcp_profile, 'all'); }); @@ -883,7 +883,7 @@ test('modern serving preserves explicitly registered custom schemas and descript return { content: [{ type: 'text', text: 'unused' }] }; } ); - const adapter = createModernMcpServerAdapter(wrapMcpServer(legacy, undefined, '3.2.0-rc.2')); + const adapter = createModernMcpServerAdapter(wrapMcpServer(legacy, undefined, '3.2.0-rc.3')); const httpServer = createServer((req, res) => void adapter.handle(req, res)); const url = await listen(httpServer); const client = new Client( diff --git a/test/lib/media-buy-lifecycle-compatibility.test.js b/test/lib/media-buy-lifecycle-compatibility.test.js index 9c3768c60..ab3ff01f1 100644 --- a/test/lib/media-buy-lifecycle-compatibility.test.js +++ b/test/lib/media-buy-lifecycle-compatibility.test.js @@ -23,7 +23,7 @@ async function withDualSurfaceSeller(serverAdcpVersion, buyerAdcpVersion, run, o end_time: '2027-02-01T00:00:00Z', confirmed_at: '2027-01-01T00:00:00Z', }; - const supportedVersions = ['3.0.25', '3.1.18', '3.2.0-rc.2'].filter(version => { + const supportedVersions = ['3.0.25', '3.1.18', '3.2.0-rc.3'].filter(version => { if (serverAdcpVersion.startsWith('3.0.')) return version.startsWith('3.0.'); if (serverAdcpVersion.startsWith('3.1.')) return !version.startsWith('3.2.'); return true; @@ -138,11 +138,11 @@ async function withDualSurfaceSeller(serverAdcpVersion, buyerAdcpVersion, run, o test('dual-surface seller defaults unversioned MCP callers to 3.1 while explicit 3.2 remains reachable', async () => { await withDualSurfaceSeller( - '3.2.0-rc.2', - '3.2.0-rc.2', + '3.2.0-rc.3', + '3.2.0-rc.3', async ({ mcpClient, calls }) => { const sdkTools = await AgentClient.fromMCPClient(mcpClient, { - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', validation: { requests: 'strict', responses: 'off' }, }).getAgentInfo(); assert.ok(sdkTools.tools.some(tool => tool.name === 'list_products')); @@ -153,8 +153,8 @@ test('dual-surface seller defaults unversioned MCP callers to 3.1 while explicit assert.ok(defaultTools.tools.some(tool => tool.name === 'get_products')); assert.ok(!defaultTools.tools.some(tool => tool.name === 'list_products')); - const explicitTools = await mcpClient.listTools({ _meta: { adcp_version: '3.2.0-rc.2' } }); - assert.strictEqual(explicitTools._meta.adcp_version, '3.2.0-rc.2'); + const explicitTools = await mcpClient.listTools({ _meta: { adcp_version: '3.2.0-rc.3' } }); + assert.strictEqual(explicitTools._meta.adcp_version, '3.2.0-rc.3'); assert.ok(explicitTools.tools.some(tool => tool.name === 'list_products')); assert.ok(!explicitTools.tools.some(tool => tool.name === 'get_products')); @@ -167,10 +167,10 @@ test('dual-surface seller defaults unversioned MCP callers to 3.1 while explicit const compact = await mcpClient.callTool({ name: 'list_products', - arguments: { adcp_version: '3.2-rc.2', max_results: 10 }, + arguments: { adcp_version: '3.2-rc.3', max_results: 10 }, }); assert.notStrictEqual(compact.isError, true, JSON.stringify(compact.structuredContent)); - assert.strictEqual(compact.structuredContent.adcp_version, '3.2-rc.2'); + assert.strictEqual(compact.structuredContent.adcp_version, '3.2-rc.3'); assert.deepStrictEqual( calls.map(([tool]) => tool), ['get_products', 'list_products'] @@ -182,8 +182,8 @@ test('dual-surface seller defaults unversioned MCP callers to 3.1 while explicit test('forced established diagnostics use actual MCP tool discovery on an all-tools 3.2 seller', async () => { await withDualSurfaceSeller( - '3.2.0-rc.2', - '3.2.0-rc.2', + '3.2.0-rc.3', + '3.2.0-rc.3', async ({ buyer, calls }) => { const lifecycle = await buyer.negotiateMediaBuyLifecycle({ preferredLifecycle: 'established', @@ -324,7 +324,7 @@ test('forced established diagnostics use actual MCP tool discovery on an all-too }); test('SDK buyer uses the compact lifecycle against a 3.2 seller profile', async () => { - await withDualSurfaceSeller('3.2.0-rc.2', '3.2.0-rc.2', async ({ buyer, mcpClient, calls }) => { + await withDualSurfaceSeller('3.2.0-rc.3', '3.2.0-rc.3', async ({ buyer, mcpClient, calls }) => { const listed = await mcpClient.listTools(); assert.ok(listed.tools.some(tool => tool.name === 'list_products')); assert.ok(!listed.tools.some(tool => tool.name === 'get_products')); @@ -332,15 +332,15 @@ test('SDK buyer uses the compact lifecycle against a 3.2 seller profile', async const result = await buyer.listProducts({ max_results: 10 }); assert.strictEqual(result.success, true, JSON.stringify(result)); assert.strictEqual(result.data.feed_version, 'feed-modern'); - assert.deepStrictEqual(calls, [['list_products', '3.2-rc.2', 3]]); + assert.deepStrictEqual(calls, [['list_products', '3.2-rc.3', 3]]); const lifecycle = await buyer.negotiateMediaBuyLifecycle(); const compatible = await lifecycle.listProducts({ max_results: 5 }); - assert.strictEqual(lifecycle.negotiated_version, '3.2-rc.2'); + assert.strictEqual(lifecycle.negotiated_version, '3.2-rc.3'); assert.strictEqual(compatible.compatibility.lifecycle, 'compact'); assert.deepStrictEqual(compatible.compatibility.tools_used, ['list_products']); assert.strictEqual(compatible.data.feed_version, 'feed-modern'); - assert.deepStrictEqual(calls.at(-1), ['list_products', '3.2-rc.2', 3]); + assert.deepStrictEqual(calls.at(-1), ['list_products', '3.2-rc.3', 3]); const rejected = await mcpClient.callTool({ name: 'request_proposals', @@ -365,7 +365,7 @@ test('SDK buyer uses the compact lifecycle against a 3.2 seller profile', async for (const adcpVersion of ['3.1.18', '3.0.25']) { test(`SDK buyer pinned to ${adcpVersion} can call a 3.2 seller's hidden legacy facade`, async () => { - await withDualSurfaceSeller('3.2.0-rc.2', adcpVersion, async ({ buyer, mcpClient, calls, legacyRequests }) => { + await withDualSurfaceSeller('3.2.0-rc.3', adcpVersion, async ({ buyer, mcpClient, calls, legacyRequests }) => { const listed = await mcpClient.listTools(); assert.ok(!listed.tools.some(tool => tool.name === 'get_products')); @@ -402,7 +402,7 @@ for (const adcpVersion of ['3.1.18', '3.0.25']) { }); test(`SDK buyer pinned to ${adcpVersion} preserves the full hidden legacy lifecycle on a normal 3.2 profile`, async () => { - await withDualSurfaceSeller('3.2.0-rc.2', adcpVersion, async ({ buyer, mcpClient, calls }) => { + await withDualSurfaceSeller('3.2.0-rc.3', adcpVersion, async ({ buyer, mcpClient, calls }) => { const listedTools = await mcpClient.listTools(); for (const hidden of ['get_products', 'create_media_buy', 'update_media_buy']) { assert.ok(!listedTools.tools.some(tool => tool.name === hidden), `${hidden} must stay hidden from tools/list`); @@ -632,10 +632,10 @@ for (const lane of [ ]) { test(`3.2-pinned buyer projects ${lane.name} claims to a hidden legacy handler`, async () => { await withDualSurfaceSeller( - '3.2.0-rc.2', - '3.2.0-rc.2', + '3.2.0-rc.3', + '3.2.0-rc.3', async ({ buyer, mcpClient, calls, legacyRequests }) => { - const compactTools = await mcpClient.listTools({ _meta: { adcp_version: '3.2-rc.2' } }); + const compactTools = await mcpClient.listTools({ _meta: { adcp_version: '3.2-rc.3' } }); assert.ok(!compactTools.tools.some(tool => tool.name === 'get_products')); buyer.getCapabilities = async () => lane.capabilities; diff --git a/test/lib/media-buy-lifecycle-coordinator.test.js b/test/lib/media-buy-lifecycle-coordinator.test.js index badf00eb5..cb887d049 100644 --- a/test/lib/media-buy-lifecycle-coordinator.test.js +++ b/test/lib/media-buy-lifecycle-coordinator.test.js @@ -43,7 +43,7 @@ const AGENT = { protocol: 'mcp', }; -function capabilities({ version = '3.2.0-rc.2', tools, discoveredTools, replayTtlSeconds = 3600 } = {}) { +function capabilities({ version = '3.2.0-rc.3', tools, discoveredTools, replayTtlSeconds = 3600 } = {}) { if (version === '2.5') { return { version: 'v2', @@ -3742,7 +3742,7 @@ describe('MediaBuyLifecycleCoordinator negotiation matrix', () => { test('does not select a newer prerelease than the compact buyer pin', async () => { const caps = capabilities({ tools: COMPACT_TOOLS }); caps.supportedVersions = ['3.1', '3.2.0-rc.3']; - const agent = clientWithCaps(caps, '3.2.0-rc.2'); + const agent = clientWithCaps(caps, '3.2.0-rc.3'); const calls = []; agent.getProducts = async () => { calls.push('get_products'); @@ -3759,7 +3759,7 @@ describe('MediaBuyLifecycleCoordinator negotiation matrix', () => { test('fails closed when every valid advertised version is newer than the buyer pin', async () => { const caps = capabilities({ tools: COMPACT_TOOLS }); caps.supportedVersions = ['3.2.0-rc.3']; - const agent = clientWithCaps(caps, '3.2.0-rc.2'); + const agent = clientWithCaps(caps, '3.2.0-rc.3'); await assert.rejects( agent.negotiateMediaBuyLifecycle(), @@ -3771,7 +3771,7 @@ describe('MediaBuyLifecycleCoordinator negotiation matrix', () => { const caps = capabilities({ tools: COMPACT_TOOLS }); delete caps.supportedVersions; caps._synthetic = true; - const agent = clientWithCaps(caps, '3.2.0-rc.2'); + const agent = clientWithCaps(caps, '3.2.0-rc.3'); const calls = []; agent.listProducts = async () => { calls.push('list_products'); @@ -3782,7 +3782,7 @@ describe('MediaBuyLifecycleCoordinator negotiation matrix', () => { const coordinator = await agent.negotiateMediaBuyLifecycle(); await coordinator.listProducts({}); - assert.equal(coordinator.negotiated_version, '3.2.0-rc.2'); + assert.equal(coordinator.negotiated_version, '3.2.0-rc.3'); assert.deepEqual(calls, ['list_products']); }); @@ -3799,13 +3799,13 @@ describe('MediaBuyLifecycleCoordinator negotiation matrix', () => { test('fails closed when an exact newer prerelease is served despite an older advertised fallback', async () => { const caps = capabilities({ tools: COMPACT_TOOLS }); - caps.servedVersion = '3.2.0-rc.3'; - caps.supportedVersions = ['3.2.0-rc.3', '3.2.0-rc.2']; - const agent = clientWithCaps(caps, '3.2.0-rc.2'); + caps.servedVersion = '3.2.0-rc.4'; + caps.supportedVersions = ['3.2.0-rc.4', '3.2.0-rc.3']; + const agent = clientWithCaps(caps, '3.2.0-rc.3'); await assert.rejects( agent.negotiateMediaBuyLifecycle(), - /served AdCP 3\.2\.0-rc\.3, which is newer than the client pin 3\.2\.0-rc\.2/ + /served AdCP 3\.2\.0-rc\.4, which is newer than the client pin 3\.2\.0-rc\.3/ ); }); @@ -3824,8 +3824,8 @@ describe('MediaBuyLifecycleCoordinator negotiation matrix', () => { test('accepts an authoritative served release at or below the buyer pin', async () => { const caps = capabilities({ tools: COMPACT_TOOLS }); caps.servedVersion = '3.2.0-beta.2'; - caps.supportedVersions = ['3.2.0-rc.2']; - const agent = clientWithCaps(caps, '3.2.0-rc.2'); + caps.supportedVersions = ['3.2.0-rc.3']; + const agent = clientWithCaps(caps, '3.2.0-rc.3'); agent.listProducts = async () => completed('list_products', { products: [], feed_version: 'feed-1' }); const coordinator = await agent.negotiateMediaBuyLifecycle(); @@ -3839,7 +3839,7 @@ describe('MediaBuyLifecycleCoordinator negotiation matrix', () => { const caps = capabilities({ tools: COMPACT_TOOLS }); delete caps.supportedVersions; caps.buildVersion = '3.2.0-beta.5+sha.abc123'; - const agent = clientWithCaps(caps, '3.2.0-rc.2'); + const agent = clientWithCaps(caps, '3.2.0-rc.3'); agent.getProducts = async () => completed('get_products', { products: [] }); agent.listProducts = async () => assert.fail('build metadata must not enable compact wire tools'); @@ -6290,11 +6290,11 @@ describe('legacy products-only purchase continuations', () => { const native = clientWithCaps( capabilities({ - version: '3.2.0-rc.2', + version: '3.2.0-rc.3', tools: COMPACT_TOOLS, discoveredTools: ['get_products', ...COMPACT_TOOLS], }), - '3.2.0-rc.2' + '3.2.0-rc.3' ); native.getProducts = async () => completed('get_products', { products: [{ product_id: 'p-native', name: 'Native' }] }); @@ -6314,7 +6314,7 @@ describe('legacy products-only purchase continuations', () => { test('executes the signed account-fenced listed_purchase vector through native buy_products', async () => { const vector = PRODUCTS_ONLY_BRIEF_VECTORS.listed_purchase_cases[0]; - const agent = clientWithCaps(capabilities({ version: '3.2.0-rc.2', tools: COMPACT_TOOLS }), '3.2.0-rc.2'); + const agent = clientWithCaps(capabilities({ version: '3.2.0-rc.3', tools: COMPACT_TOOLS }), '3.2.0-rc.3'); const calls = []; agent.buyProducts = async request => { calls.push(request); @@ -11242,7 +11242,7 @@ describe('MediaBuyLifecycleCoordinator mutation boundaries', () => { }); test('readback fields are gated by the exact established schema version', async () => { - for (const version of ['3.0', '3.1', '3.2.0-rc.2']) { + for (const version of ['3.0', '3.1', '3.2.0-rc.3']) { const tools = version.startsWith('3.2') ? [...COMPACT_TOOLS, 'get_media_buys', 'get_media_buy_delivery'] : undefined; @@ -13998,7 +13998,7 @@ describe('MediaBuyLifecycleCoordinator mutation boundaries', () => { }); test('rejects media-buy cancellation combined with name on compact and established lifecycles', async () => { - for (const { version, tools } of [{ version: '3.0' }, { version: '3.2.0-rc.2', tools: COMPACT_TOOLS }]) { + for (const { version, tools } of [{ version: '3.0' }, { version: '3.2.0-rc.3', tools: COMPACT_TOOLS }]) { const agent = clientWithCaps(capabilities({ version, tools })); let mutations = 0; agent.updateMediaBuy = async () => { diff --git a/test/lib/media-buy-lifecycle-release-gate.test.js b/test/lib/media-buy-lifecycle-release-gate.test.js index 262d13a48..dacd46783 100644 --- a/test/lib/media-buy-lifecycle-release-gate.test.js +++ b/test/lib/media-buy-lifecycle-release-gate.test.js @@ -197,7 +197,7 @@ async function withHonestEstablishedSeller(version, run) { const mcp = new Client({ name: `compact-buyer-for-${version}`, version: '1.0.0' }); await Promise.all([mcp.connect(clientTransport), server.connect(serverTransport)]); const buyer = AgentClient.fromMCPClient(mcp, { - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', validation: { requests: 'strict', responses: 'strict' }, }); try { @@ -274,7 +274,7 @@ async function withHonestV25Seller(run) { const mcp = new Client({ name: 'compact-buyer-for-v2.5', version: '1.0.0' }); await Promise.all([mcp.connect(clientTransport), server.connect(serverTransport)]); const buyer = AgentClient.fromMCPClient(mcp, { - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', allowV2: true, validation: { requests: 'strict', responses: 'strict' }, }); @@ -326,7 +326,7 @@ async function withHonestEstablishedProposalState(state, run) { const mcp = new Client({ name: `proposal-${state}-buyer`, version: '1.0.0' }); await Promise.all([mcp.connect(clientTransport), server.connect(serverTransport)]); const buyer = AgentClient.fromMCPClient(mcp, { - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', validation: { requests: 'strict', responses: 'strict' }, }); try { @@ -434,7 +434,7 @@ for (const state of ['submitted', 'input-required']) { }); } -for (const version of ['3.0.25', '3.1.18', '3.2.0-rc.2']) { +for (const version of ['3.0.25', '3.1.18', '3.2.0-rc.3']) { test(`3.2 compact facade preserves the complete ${version} direct lifecycle over honest MCP wire`, async () => { await withHonestEstablishedSeller(version, async ({ buyer, calls, mutations }) => { const lifecycle = await buyer.negotiateMediaBuyLifecycle({ @@ -446,7 +446,7 @@ for (const version of ['3.0.25', '3.1.18', '3.2.0-rc.2']) { assert.equal(lifecycle.lifecycle, 'established'); assert.equal( lifecycle.negotiated_version, - version.startsWith('3.2') ? '3.2-rc.2' : version.startsWith('3.1') ? '3.1' : '3.0' + version.startsWith('3.2') ? '3.2-rc.3' : version.startsWith('3.1') ? '3.1' : '3.0' ); assert.equal(listed.data.feed_version, 'legacy-feed-1'); assert.equal(listed.data.pricing_version, 'legacy-price-1'); @@ -816,7 +816,7 @@ test('the same compact-first buyer facade projects established direct and propos try { const buyer = new AgentClient( { id: 'a2a-release-gate', name: 'A2A release gate', agent_uri: url, protocol: 'a2a' }, - { adcpVersion: '3.2.0-rc.2', validation: { requests: 'strict', responses: 'strict' } } + { adcpVersion: '3.2.0-rc.3', validation: { requests: 'strict', responses: 'strict' } } ); const lifecycle = await buyer.negotiateMediaBuyLifecycle({ principalScope: 'release-gate-buyer', @@ -1067,8 +1067,8 @@ test('the compact-first buyer uses the native 3.2 lifecycle discovered over offi const adcp = createAdcpServer({ name: 'a2a-compact-release-gate', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', - capabilities: { supported_versions: ['3.0', '3.1', '3.2-rc.2'] }, + adcpVersion: '3.2.0-rc.3', + capabilities: { supported_versions: ['3.0', '3.1', '3.2-rc.3'] }, validation: { requests: 'strict', responses: 'strict' }, mediaBuy: { listProducts: async params => { @@ -1187,13 +1187,13 @@ test('the compact-first buyer uses the native 3.2 lifecycle discovered over offi try { const buyer = new AgentClient( { id: 'a2a-compact-release-gate', name: 'A2A compact release gate', agent_uri: url, protocol: 'a2a' }, - { adcpVersion: '3.2.0-rc.2', validation: { requests: 'strict', responses: 'strict' } } + { adcpVersion: '3.2.0-rc.3', validation: { requests: 'strict', responses: 'strict' } } ); const capabilities = await buyer.getAdcpCapabilities({}); assert.equal(capabilities.success, true, JSON.stringify(capabilities)); const lifecycle = await buyer.negotiateMediaBuyLifecycle({ principalScope: 'release-gate-buyer' }); assert.equal(lifecycle.lifecycle, 'compact'); - assert.equal(lifecycle.negotiated_version, '3.2-rc.2'); + assert.equal(lifecycle.negotiated_version, '3.2-rc.3'); const listed = await lifecycle.listProducts({ account: ACCOUNT, brand: BRAND }); assert.equal(listed.success, true, JSON.stringify(listed)); diff --git a/test/lib/preview-creative-client.test.js b/test/lib/preview-creative-client.test.js index bc4628828..330533301 100644 --- a/test/lib/preview-creative-client.test.js +++ b/test/lib/preview-creative-client.test.js @@ -40,7 +40,7 @@ function runtimeClient(executeTask, config = {}) { client.cachedCapabilities = { version: 'v3', majorVersions: [3], - supportedVersions: ['3.2.0-rc.2'], + supportedVersions: ['3.2.0-rc.3'], protocols: ['creative'], features: {}, extensions: [], diff --git a/test/lib/proposal-manager-e2e.test.js b/test/lib/proposal-manager-e2e.test.js index d1ac4953e..56bd7116d 100644 --- a/test/lib/proposal-manager-e2e.test.js +++ b/test/lib/proposal-manager-e2e.test.js @@ -163,7 +163,7 @@ test('e2e: getProducts validates push config before proposal finalization and no }, }; const server = createAdcpServerFromPlatform( - buildPlatform({ proposalManager, sales: {}, capabilities: { adcp_version: '3.2.0-rc.2' } }), + buildPlatform({ proposalManager, sales: {}, capabilities: { adcp_version: '3.2.0-rc.3' } }), { name: `push-before-finalize-${label}`, version: '1.0', @@ -179,7 +179,7 @@ test('e2e: getProducts validates push config before proposal finalization and no params: { name: 'get_products', arguments: { - adcp_version: '3.2.0-rc.2', + adcp_version: '3.2.0-rc.3', buying_mode: 'refine', refine: [{ scope: 'proposal', action: 'finalize', proposal_id: 'p1' }], push_notification_config, @@ -198,7 +198,7 @@ test('e2e: getProducts validates push config before proposal finalization and no method: 'tools/call', params: { name: 'get_products', - arguments: { adcp_version: '3.2.0-rc.2', buying_mode: 'brief', push_notification_config }, + arguments: { adcp_version: '3.2.0-rc.3', buying_mode: 'brief', push_notification_config }, }, }, { authInfo } @@ -390,7 +390,7 @@ test('e2e: response summaries fail closed outside native getProducts', async () proposalManager: undefined, sales: { getProducts: async () => ({ products: [], cache_scope: 'public' }) }, }); - platform.capabilities.adcp_version = '3.2.0-rc.2'; + platform.capabilities.adcp_version = '3.2.0-rc.3'; platform.mediaBuyLifecycle = { listProducts: async () => withResponseSummary({ products: [], feed_version: 'feed_1' }, 'Unsupported summary text.'), @@ -410,7 +410,7 @@ test('e2e: response summaries fail closed outside native getProducts', async () assert.strictEqual(response.isError, true); assert.notStrictEqual(response.content[0].text, 'Unsupported summary text.'); assert.notDeepStrictEqual(response.structuredContent, { - adcp_version: '3.2-rc.2', + adcp_version: '3.2-rc.3', }); const proposalStore = new InMemoryProposalStore(); diff --git a/test/lib/proposal-negotiation-server.test.js b/test/lib/proposal-negotiation-server.test.js index 72d74306e..bf9ffa8d7 100644 --- a/test/lib/proposal-negotiation-server.test.js +++ b/test/lib/proposal-negotiation-server.test.js @@ -100,7 +100,7 @@ describe('refine_proposals server integration', () => { test('modern platform seam auto-pins to an advertised 3.2 release', async () => { const server = createAdcpServerFromPlatform( { - capabilities: { specialisms: [], supported_versions: ['3.2-rc.2'] }, + capabilities: { specialisms: [], supported_versions: ['3.2-rc.3'] }, accounts: { resolution: 'derived', resolve: async () => ({ id: 'account-1', metadata: {} }), @@ -133,8 +133,8 @@ describe('refine_proposals server integration', () => { const listed = await server.dispatchTestRequest({ method: 'tools/list' }); assert.ok(listed.tools.some(tool => tool.name === 'refine_proposals')); const capabilities = await call(server, 'get_adcp_capabilities', {}); - assert.equal(capabilities.structuredContent.adcp_version, '3.2-rc.2'); - assert.deepEqual(capabilities.structuredContent.adcp.supported_versions, ['3.2-rc.2']); + assert.equal(capabilities.structuredContent.adcp_version, '3.2-rc.3'); + assert.deepEqual(capabilities.structuredContent.adcp.supported_versions, ['3.2-rc.3']); assert.deepEqual(capabilities.structuredContent.media_buy.proposal_refinement, { supported_dimensions: [], }); @@ -150,11 +150,11 @@ describe('refine_proposals server integration', () => { supported_dimensions: ['total_budget', 'alternatives'], max_alternatives: 4, }); - assert.equal(capabilities.structuredContent.adcp_version, '3.2-rc.2'); + assert.equal(capabilities.structuredContent.adcp_version, '3.2-rc.3'); assert.ok(capabilities.structuredContent.media_buy.lifecycle_tools.includes('refine_proposals')); const response = await call(server, 'refine_proposals', request('version-envelope-key-0001'), 'buyer-a'); - assert.equal(response.structuredContent.adcp_version, '3.2-rc.2'); + assert.equal(response.structuredContent.adcp_version, '3.2-rc.3'); }); test('rejects an explicit pre-3.2 server pin', () => { @@ -170,7 +170,7 @@ describe('refine_proposals server integration', () => { test('hides proposal refinement capabilities from a negotiated pre-3.2 response', async () => { const server = negotiationServer(undefined, { - serverCapabilities: { supported_versions: ['3.1', '3.2-rc.2'] }, + serverCapabilities: { supported_versions: ['3.1', '3.2-rc.3'] }, }); const legacy = await call(server, 'get_adcp_capabilities', { @@ -182,10 +182,10 @@ describe('refine_proposals server integration', () => { assert.equal(legacy.structuredContent.media_buy.lifecycle_tools, undefined); const modern = await call(server, 'get_adcp_capabilities', { - adcp_version: '3.2-rc.2', + adcp_version: '3.2-rc.3', adcp_major_version: 3, }); - assert.equal(modern.structuredContent.adcp_version, '3.2-rc.2'); + assert.equal(modern.structuredContent.adcp_version, '3.2-rc.3'); assert.deepEqual(modern.structuredContent.media_buy.proposal_refinement, { supported_dimensions: ['total_budget', 'alternatives'], max_alternatives: 4, @@ -311,7 +311,7 @@ describe('refine_proposals server integration', () => { assert.equal(response.isError, undefined); assert.equal(response.structuredContent.status, 'submitted'); assert.equal(response.structuredContent.task_id, 'proposal-task-1'); - assert.equal(response.structuredContent.adcp_version, '3.2-rc.2'); + assert.equal(response.structuredContent.adcp_version, '3.2-rc.3'); assert.equal(response.structuredContent.results, undefined); assert.equal(response.structuredContent.products, undefined); }); diff --git a/test/lib/proposal-negotiation-validation.test.js b/test/lib/proposal-negotiation-validation.test.js index 6782addcb..01329444a 100644 --- a/test/lib/proposal-negotiation-validation.test.js +++ b/test/lib/proposal-negotiation-validation.test.js @@ -97,7 +97,7 @@ test('commercial-terms verifier accepts a digest-bound exact reviewed snapshot', const result = verifyProposalCommercialTerms( proposal('proposal-terms', 'source-1', { commercial_terms: terms }), terms, - { adcpVersion: '3.2-rc.2' } + { adcpVersion: '3.2-rc.3' } ); assert.equal(result.ok, true); @@ -331,7 +331,7 @@ test('commercial-terms verifier fails closed when the requested schema bundle is proposal('proposal-version', 'source-1', { commercial_terms: terms }), terms, { - adcpVersion: '3.2.0-rc.299', + adcpVersion: '3.2.0-rc.399', } ); assert.equal(result.ok, false); @@ -515,7 +515,7 @@ test('builder pins the 3.2 wire envelope and returns an immutable deep snapshot input.context.planning.attempt = 2; input.refinements[0].ask = 'Changed after construction'; - assert.equal(built.adcp_version, '3.2-rc.2'); + assert.equal(built.adcp_version, '3.2-rc.3'); assert.equal(built.adcp_major_version, 3); assert.equal(built.context.planning.attempt, 1); assert.equal(built.refinements[0].ask, 'Improve the terms'); @@ -661,7 +661,7 @@ test('compact submitted responses validate without completed-field access', () = }); test('response verifier accepts only the 3.2 response release line and reports rejected values', () => { - for (const adcp_version of ['3.2', '3.2-beta.0', '3.2-rc.2']) { + for (const adcp_version of ['3.2', '3.2-beta.0', '3.2-rc.3']) { assert.equal( validateRefineProposalsResponseShape({ ...response(), diff --git a/test/lib/proposal-negotiation.test.js b/test/lib/proposal-negotiation.test.js index 5ace824a4..604250b28 100644 --- a/test/lib/proposal-negotiation.test.js +++ b/test/lib/proposal-negotiation.test.js @@ -56,7 +56,7 @@ function revise(overrides = {}) { } function request(refinements = [revise()]) { - return { adcp_version: '3.2-rc.2', adcp_major_version: 3, idempotency_key: KEY, refinements }; + return { adcp_version: '3.2-rc.3', adcp_major_version: 3, idempotency_key: KEY, refinements }; } function completed(data) { @@ -339,7 +339,7 @@ test('AgentClient.refineProposals dispatches through the official MCP client wit const mcpClient = new Client({ name: 'Buyer', version: '1.0.0' }); await mcpClient.connect(clientTransport); const agent = AgentClient.fromMCPClient(mcpClient, { - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', wireAdcpVersion: '3.2.0-beta.1', }); @@ -357,7 +357,7 @@ test('AgentClient.refineProposals dispatches through the official MCP client wit test('ADCPMultiAgentClient.simple forwards an exact prerelease wire pin to proposal requests', async () => { const { ADCPMultiAgentClient } = require('../../dist/lib/index.js'); const client = ADCPMultiAgentClient.simple('https://seller.example.com/mcp', { - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', wireAdcpVersion: '3.2.0-beta.1', }); const agent = client.agent('default-agent'); @@ -381,7 +381,7 @@ test('ADCPMultiAgentClient.simple forwards an exact prerelease wire pin to propo }; await agent.refineProposals({ refinements: [revise()] }); - assert.equal(client.getAdcpVersion(), '3.2.0-rc.2'); + assert.equal(client.getAdcpVersion(), '3.2.0-rc.3'); assert.equal(captured.adcp_version, '3.2-beta.1'); assert.equal(captured.adcp_major_version, 3); }); diff --git a/test/lib/reporting-consumer-status-fixtures.test.js b/test/lib/reporting-consumer-status-fixtures.test.js index 452d9fb77..ed869f026 100644 --- a/test/lib/reporting-consumer-status-fixtures.test.js +++ b/test/lib/reporting-consumer-status-fixtures.test.js @@ -32,7 +32,7 @@ test('portable consumer-status vectors retain exact bytes, clocks, principals, r assert.deepEqual(publishedFixtureExport, fixture); assert.equal(fixtureBytes.byteLength, manifest.files['consumer-status.json'].size_bytes); assert.equal(sha256(fixtureBytes), manifest.files['consumer-status.json'].sha256); - assert.equal(fixture.protocol_version, '3.2.0-rc.2'); + assert.equal(fixture.protocol_version, '3.2.0-rc.3'); assert.deepEqual( fixture.frozen.expected_periods.map(period => Date.parse(period.end) - Date.parse(period.start)), [82_800_000, 90_000_000, 2_419_200_000] diff --git a/test/lib/reporting-ledger.test.js b/test/lib/reporting-ledger.test.js index 24488e6de..7bb368e2c 100644 --- a/test/lib/reporting-ledger.test.js +++ b/test/lib/reporting-ledger.test.js @@ -1039,7 +1039,7 @@ describe('seller reporting ledger', () => { true, parsedPeriods.success ? undefined : JSON.stringify(parsedPeriods.error.issues) ); - const validatedPeriods = validateResponse('get_reporting_status', periods, '3.2.0-rc.2'); + const validatedPeriods = validateResponse('get_reporting_status', periods, '3.2.0-rc.3'); if (!validatedPeriods.valid) throw new Error(JSON.stringify(validatedPeriods)); const firstPage = await handler( { account: request.account, view: 'periods', pagination: { max_results: 1 } }, @@ -1059,7 +1059,7 @@ describe('seller reporting ledger', () => { assert.equal(secondPage.periods.length, 0); assert.equal(secondPage.revisions.length, 1); assert.equal(secondPage.pagination.total_count, 2); - assert.equal(validateResponse('get_reporting_status', secondPage, '3.2.0-rc.2').valid, true); + assert.equal(validateResponse('get_reporting_status', secondPage, '3.2.0-rc.3').valid, true); const exact = await handler( { account: request.account, @@ -1073,7 +1073,7 @@ describe('seller reporting ledger', () => { assert.equal(exact.reporting_revision_binding.revision_content_sha256, revisions[0].binding.sha256); const parsedExact = GetReportingStatusResponseSchema.safeParse(exact); assert.equal(parsedExact.success, true, parsedExact.success ? undefined : JSON.stringify(parsedExact.error.issues)); - assert.equal(validateResponse('get_reporting_status', exact, '3.2.0-rc.2').valid, true); + assert.equal(validateResponse('get_reporting_status', exact, '3.2.0-rc.3').valid, true); const deliveryHandler = createReportingDeliveryHandler(store); const delivery = await deliveryHandler( { @@ -1108,14 +1108,14 @@ describe('seller reporting ledger', () => { /cursor is invalid/ ); assert.equal(delivery.reporting_revision_binding.content_sha256, revisions[0].binding.sha256); - const validatedDelivery = validateResponse('get_media_buy_delivery', delivery, '3.2.0-rc.2'); + const validatedDelivery = validateResponse('get_media_buy_delivery', delivery, '3.2.0-rc.3'); if (!validatedDelivery.valid) throw new Error(JSON.stringify(validatedDelivery)); const missing = await handler( { account: request.account, view: 'revision', reporting_revision_id: 'rrev_missing' }, context ); assert.equal(missing.failure_kind, 'lookup_unavailable'); - assert.equal(validateResponse('get_reporting_status', missing, '3.2.0-rc.2').valid, true); + assert.equal(validateResponse('get_reporting_status', missing, '3.2.0-rc.3').valid, true); const summary = await handler({ account: request.account, view: 'summary' }, context); const parsedSummary = GetReportingStatusResponseSchema.safeParse(summary); assert.equal( @@ -1128,7 +1128,7 @@ describe('seller reporting ledger', () => { context ); assert.equal(unknownMediaBuy.failure_kind, 'lookup_unavailable'); - assert.equal(validateResponse('get_reporting_status', summary, '3.2.0-rc.2').valid, true); + assert.equal(validateResponse('get_reporting_status', summary, '3.2.0-rc.3').valid, true); const filteredSummary = await handler({ account: request.account, view: 'summary', health: ['delayed'] }, context); assert.equal(filteredSummary.obligation_counts.total, 1, 'health is a periods-only filter'); assert.equal(filteredSummary.health, summary.health); @@ -1137,7 +1137,7 @@ describe('seller reporting ledger', () => { assert.equal(officialOnly.revisions.length, 0); assert.equal(officialOnly.pagination.has_more, false, 'filtered revisions must not create empty pages'); assert.equal(officialOnly.pagination.total_count, 1); - assert.equal(validateResponse('get_reporting_status', officialOnly, '3.2.0-rc.2').valid, true); + assert.equal(validateResponse('get_reporting_status', officialOnly, '3.2.0-rc.3').valid, true); const completeOnly = await handler({ account: request.account, view: 'periods', health: ['complete'] }, context); assert.equal(completeOnly.periods.length, 1); const unknownConfiguration = await handler( @@ -1145,13 +1145,13 @@ describe('seller reporting ledger', () => { context ); assert.equal(unknownConfiguration.failure_kind, 'lookup_unavailable'); - assert.equal(validateResponse('get_reporting_status', unknownConfiguration, '3.2.0-rc.2').valid, true); + assert.equal(validateResponse('get_reporting_status', unknownConfiguration, '3.2.0-rc.3').valid, true); const malformedCursor = await handler( { account: request.account, view: 'periods', pagination: { cursor: 'not-json' } }, context ); assert.equal(malformedCursor.failure_kind, 'lookup_unavailable'); - assert.equal(validateResponse('get_reporting_status', malformedCursor, '3.2.0-rc.2').valid, true); + assert.equal(validateResponse('get_reporting_status', malformedCursor, '3.2.0-rc.3').valid, true); const restatement = await producer.runWorker({ now: () => new Date(anchor + 3 * 86_400_000), maxIterations: 1 }); assert.equal(restatement.revisionsCommitted, 1); assert.equal((await store.listRevisions(planned[0].reporting_obligation_id)).length, 2); @@ -1260,7 +1260,7 @@ describe('seller reporting ledger', () => { { account: { account_id: request.account.account_id } } ); assert.equal(response.failure_kind, 'operational'); - assert.equal(validateResponse('get_reporting_status', response, '3.2.0-rc.2').valid, true); + assert.equal(validateResponse('get_reporting_status', response, '3.2.0-rc.3').valid, true); } }); @@ -1414,7 +1414,7 @@ describe('seller reporting ledger', () => { assert.equal(periods.periods[0].adjustment_count, 1); const parsed = GetReportingStatusResponseSchema.safeParse(periods); assert.equal(parsed.success, true, parsed.success ? undefined : JSON.stringify(parsed.error.issues)); - const validatedPeriods = validateResponse('get_reporting_status', periods, '3.2.0-rc.2'); + const validatedPeriods = validateResponse('get_reporting_status', periods, '3.2.0-rc.3'); if (!validatedPeriods.valid) throw new Error(JSON.stringify(validatedPeriods)); const exact = await handler( { @@ -1449,7 +1449,7 @@ describe('seller reporting ledger', () => { assert.equal(secondExactPage.pagination.has_more, false); const parsedExact = GetReportingStatusResponseSchema.safeParse(exact); assert.equal(parsedExact.success, true, parsedExact.success ? undefined : JSON.stringify(parsedExact.error.issues)); - assert.equal(validateResponse('get_reporting_status', exact, '3.2.0-rc.2').valid, true); + assert.equal(validateResponse('get_reporting_status', exact, '3.2.0-rc.3').valid, true); }); test('exports one idempotent migration for the complete store surface', () => { diff --git a/test/lib/request-validation.test.js b/test/lib/request-validation.test.js index 8d2709803..d50877438 100644 --- a/test/lib/request-validation.test.js +++ b/test/lib/request-validation.test.js @@ -302,7 +302,7 @@ describe('SingleAgentClient Request Validation', () => { inner.cachedCapabilities = { version: 'v3', majorVersions: [3], - supportedVersions: ['3.2.0-rc.2'], + supportedVersions: ['3.2.0-rc.3'], protocols: ['media_buy'], features: { inlineCreativeManagement: false, @@ -1094,7 +1094,7 @@ describe('v3 partial-schema field stripping', () => { inner.cachedCapabilities = { version: 'v3', majorVersions: [3], - supportedVersions: ['3.2.0-rc.2'], + supportedVersions: ['3.2.0-rc.3'], protocols: ['media_buy'], features: { inlineCreativeManagement: false, diff --git a/test/lib/schema-validation.test.js b/test/lib/schema-validation.test.js index 440cb772a..5093866a6 100644 --- a/test/lib/schema-validation.test.js +++ b/test/lib/schema-validation.test.js @@ -234,10 +234,10 @@ describe('schema-driven validation', () => { test('accepts SDK-stamped adcp_version through nested compact commitment aliases', () => { for (const tool of ['buy_products', 'accept_proposal']) { for (const response of [ - compactCommitmentResponse({ adcp_version: '3.2-rc.2' }), - failedCompactCommitmentResponse({ adcp_version: '3.2-rc.2' }), + compactCommitmentResponse({ adcp_version: '3.2-rc.3' }), + failedCompactCommitmentResponse({ adcp_version: '3.2-rc.3' }), ]) { - const outcome = validateResponse(tool, response, '3.2.0-rc.2'); + const outcome = validateResponse(tool, response, '3.2.0-rc.3'); assert.strictEqual(outcome.valid, true, `${tool} ${response.status}: ${formatIssues(outcome.issues)}`); } } @@ -246,7 +246,7 @@ describe('schema-driven validation', () => { test('compact commitment relaxation does not make nested bodies permissive', () => { const response = compactCommitmentResponse(); response.accepted_proposal.commercial_terms.unknown_nested_field = 'typo'; - const outcome = validateResponse('buy_products', response, '3.2.0-rc.2'); + const outcome = validateResponse('buy_products', response, '3.2.0-rc.3'); assert.ok( outcome.issues.some( issue => diff --git a/test/lib/storyboard-schema-invalid-negative-path.test.js b/test/lib/storyboard-schema-invalid-negative-path.test.js index e92867495..1730dda33 100644 --- a/test/lib/storyboard-schema-invalid-negative-path.test.js +++ b/test/lib/storyboard-schema-invalid-negative-path.test.js @@ -71,14 +71,14 @@ describe('storyboard schema-invalid negative paths', () => { protocol: 'mcp', }; const client = new SingleAgentClient(agent, { - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', validateFeatures: false, validation: { requests: 'strict', responses: 'off' }, }); client.getCapabilities = async () => ({ version: 'v3', majorVersions: [3], - supportedVersions: ['3.2.0-rc.2'], + supportedVersions: ['3.2.0-rc.3'], protocols: ['media_buy'], features: {}, extensions: [], diff --git a/test/lib/storyboard-security.test.js b/test/lib/storyboard-security.test.js index 4ace812f4..7b78c4e2e 100644 --- a/test/lib/storyboard-security.test.js +++ b/test/lib/storyboard-security.test.js @@ -1110,7 +1110,7 @@ describe('storyboard runner: auth-override dispatch', () => { { kind: 'data', data: { - adcp_version: '3.2-rc.2', + adcp_version: '3.2-rc.3', supported_protocols: ['creative'], tools: [{ name: 'list_creatives' }], }, diff --git a/test/lib/storyboard-task-map-error.test.js b/test/lib/storyboard-task-map-error.test.js index a85ae1a9e..120f97d5e 100644 --- a/test/lib/storyboard-task-map-error.test.js +++ b/test/lib/storyboard-task-map-error.test.js @@ -598,7 +598,7 @@ describe('executeStoryboardTask creative wire selection', () => { await executeStoryboardTask( { - getAdcpVersion: () => '3.2.0-rc.2', + getAdcpVersion: () => '3.2.0-rc.3', createMediaBuy: async () => { throw new Error('canonical projection must not drop an authored legacy route'); }, @@ -630,7 +630,7 @@ describe('executeStoryboardTask creative wire selection', () => { await executeStoryboardTask( { - getAdcpVersion: () => '3.2.0-rc.2', + getAdcpVersion: () => '3.2.0-rc.3', updateMediaBuy: async () => { throw new Error('canonical projection must not drop new_packages format_ids'); }, diff --git a/test/lib/task-executor-operation-error.test.js b/test/lib/task-executor-operation-error.test.js index feae5fe9d..90a12a0a0 100644 --- a/test/lib/task-executor-operation-error.test.js +++ b/test/lib/task-executor-operation-error.test.js @@ -15,7 +15,7 @@ describe('TaskExecutor business rejection diagnostics', () => { suggestions: ['Try broadening the requested geography'], }, }); - const executor = new TaskExecutor({ strictSchemaValidation: false, adcpVersion: '3.2.0-rc.2' }); + const executor = new TaskExecutor({ strictSchemaValidation: false, adcpVersion: '3.2.0-rc.3' }); try { const result = await executor.executeTask( { id: 'seller', name: 'Seller', agent_uri: 'https://seller.example/mcp', protocol: 'mcp' }, diff --git a/test/lib/v2-getproducts-autowire.test.js b/test/lib/v2-getproducts-autowire.test.js index eefdb1eda..490c51917 100644 --- a/test/lib/v2-getproducts-autowire.test.js +++ b/test/lib/v2-getproducts-autowire.test.js @@ -32,8 +32,8 @@ async function buildMockSeller(getProductsResponse, clientConfig = {}, { adverti server.registerTool('get_adcp_capabilities', { inputSchema: {} }, async () => { const capabilities = { status: 'completed', - adcp_version: '3.2.0-rc.2', - adcp: { major_versions: [3], supported_versions: ['3.2.0-rc.2'] }, + adcp_version: '3.2.0-rc.3', + adcp: { major_versions: [3], supported_versions: ['3.2.0-rc.3'] }, supported_protocols: ['media_buy'], specialisms: [], }; diff --git a/test/lib/version-sync.test.js b/test/lib/version-sync.test.js index 8daa7b3d5..4c8ed91ee 100644 --- a/test/lib/version-sync.test.js +++ b/test/lib/version-sync.test.js @@ -25,11 +25,11 @@ test('AdCP semver pins normalize to release-precision wire values', () => { }); test('3.2 prerelease remains exact while retaining the complete supported 3.0 and 3.1 GA lines', () => { - assert.equal(ADCP_VERSION, '3.2.0-rc.2'); + assert.equal(ADCP_VERSION, '3.2.0-rc.3'); assert.ok(COMPATIBLE_ADCP_VERSIONS.includes('3.0.25')); assert.ok(COMPATIBLE_ADCP_VERSIONS.includes('3.1.18')); - assert.ok(COMPATIBLE_ADCP_VERSIONS.includes('3.2.0-rc.2')); - assert.ok(COMPATIBLE_ADCP_VERSIONS.includes('3.2-rc.2')); + assert.ok(COMPATIBLE_ADCP_VERSIONS.includes('3.2.0-rc.3')); + assert.ok(COMPATIBLE_ADCP_VERSIONS.includes('3.2-rc.3')); assert.ok(!COMPATIBLE_ADCP_VERSIONS.includes('3.2.0-beta.1')); assert.ok(!COMPATIBLE_ADCP_VERSIONS.includes('3.2-beta.1')); assert.ok(!COMPATIBLE_ADCP_VERSIONS.includes('3.2.0-beta.0')); diff --git a/test/lib/versioned-tool-schemas.test.js b/test/lib/versioned-tool-schemas.test.js index 307a32d75..a8cec4ad1 100644 --- a/test/lib/versioned-tool-schemas.test.js +++ b/test/lib/versioned-tool-schemas.test.js @@ -7,7 +7,7 @@ describe('version-aware tool JSON Schemas (#2678)', () => { it('selects distinct 3.0, 3.1, and 3.2 request schemas and reports the resolved release', () => { const v30 = getToolInputSchema('create_media_buy', { adcpVersion: '3.0' }); const v31 = getToolInputSchema('create_media_buy', { adcpVersion: '3.1' }); - const v32 = getToolInputSchema('create_media_buy', { adcpVersion: '3.2.0-rc.2' }); + const v32 = getToolInputSchema('create_media_buy', { adcpVersion: '3.2.0-rc.3' }); assert.strictEqual(v30.bundleKey, '3.0'); assert.strictEqual(v30.resolvedVersion, '3.0.25'); @@ -19,8 +19,8 @@ describe('version-aware tool JSON Schemas (#2678)', () => { assert.strictEqual(v31.schema.properties.adcp_major_version, undefined); assert.ok(v31.schema.properties.paused); - assert.strictEqual(v32.bundleKey, '3.2.0-rc.2'); - assert.strictEqual(v32.resolvedVersion, '3.2.0-rc.2'); + assert.strictEqual(v32.bundleKey, '3.2.0-rc.3'); + assert.strictEqual(v32.resolvedVersion, '3.2.0-rc.3'); assert.strictEqual(v32.schema.deprecated, true); assert.deepStrictEqual(v32.schema['x-superseded-by'], ['buy_products', 'accept_proposal']); }); diff --git a/test/server-a2a-adapter.test.js b/test/server-a2a-adapter.test.js index 1f5e6b4b5..b8e25cda1 100644 --- a/test/server-a2a-adapter.test.js +++ b/test/server-a2a-adapter.test.js @@ -409,9 +409,9 @@ describe('createA2AAdapter', () => { const adcp = createAdcpServer({ name: 'dual-version A2A seller', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', defaultAdcpVersion: '3.1.18', - capabilities: { supported_versions: ['3.1.18', '3.2.0-rc.2'] }, + capabilities: { supported_versions: ['3.1.18', '3.2.0-rc.3'] }, mediaBuy: { getProducts: async () => ({ products: [] }), listProducts: async () => ({ outcome: 'listed', products: [], feed_version: 'feed-1' }), @@ -428,8 +428,8 @@ describe('createA2AAdapter', () => { const adcp = createAdcpServer({ name: '3.2 A2A task seller', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', - capabilities: { supported_versions: ['3.1.18', '3.2.0-rc.2'] }, + adcpVersion: '3.2.0-rc.3', + capabilities: { supported_versions: ['3.1.18', '3.2.0-rc.3'] }, toolVersions: { tasks_get: { max: '3.1' } }, customTools: { tasks_get: { diff --git a/test/server-create-adcp-server.test.js b/test/server-create-adcp-server.test.js index 8fb9938d0..ac96b607e 100644 --- a/test/server-create-adcp-server.test.js +++ b/test/server-create-adcp-server.test.js @@ -106,9 +106,9 @@ describe('createAdcpServer', () => { const server = createAdcpServer({ name: 'Dual-version seller', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', defaultAdcpVersion: '3.1.18', - capabilities: { supported_versions: ['3.1.18', '3.2.0-rc.2'] }, + capabilities: { supported_versions: ['3.1.18', '3.2.0-rc.3'] }, resolveAccountFromAuth: async context => { accountResolverContexts.push(context); return undefined; @@ -147,23 +147,23 @@ describe('createAdcpServer', () => { responseEnhancer: (_response, context) => enhancedContexts.push(context), }); - assert.strictEqual(server.getAdcpVersion(), '3.2.0-rc.2'); + assert.strictEqual(server.getAdcpVersion(), '3.2.0-rc.3'); assert.strictEqual(server.getDefaultAdcpVersion(), '3.1.18'); const defaultProducts = await callTool(server, 'get_products', {}); - const modernProducts = await callTool(server, 'get_products', { adcp_version: '3.2.0-rc.2' }); + const modernProducts = await callTool(server, 'get_products', { adcp_version: '3.2.0-rc.3' }); assert.strictEqual(defaultProducts.adcp_version, '3.1'); - assert.strictEqual(modernProducts.adcp_version, '3.2-rc.2'); + assert.strictEqual(modernProducts.adcp_version, '3.2-rc.3'); assert.deepStrictEqual( standardContexts.map(context => context.version), - ['3.1', '3.2-rc.2'] + ['3.1', '3.2-rc.3'] ); assert.ok(standardContexts.every(context => context.descriptor?.writable === false)); for (const contexts of [accountResolverContexts, sessionResolverContexts]) { const getProductsContexts = contexts.filter(context => context.toolName === 'get_products'); assert.deepStrictEqual( getProductsContexts.map(context => context.servedAdcpVersion), - ['3.1', '3.2-rc.2'] + ['3.1', '3.2-rc.3'] ); assert.ok( getProductsContexts.every( @@ -173,31 +173,31 @@ describe('createAdcpServer', () => { } await callTool(server, 'version_probe', {}); - await callTool(server, 'version_probe', { adcp_version: '3.2.0-rc.2' }); + await callTool(server, 'version_probe', { adcp_version: '3.2.0-rc.3' }); assert.deepStrictEqual( customContexts.map(context => context.version), - ['3.1', '3.2-rc.2'] + ['3.1', '3.2-rc.3'] ); assert.ok(customContexts.every(context => context.descriptor?.writable === false)); const defaultCapabilities = await callTool(server, 'get_adcp_capabilities', {}); const modernCapabilities = await callTool(server, 'get_adcp_capabilities', { - adcp_version: '3.2.0-rc.2', + adcp_version: '3.2.0-rc.3', }); assert.strictEqual(defaultCapabilities.adcp_version, '3.1'); assert.strictEqual(defaultCapabilities.media_buy.lifecycle_tools, undefined); - assert.strictEqual(modernCapabilities.adcp_version, '3.2-rc.2'); + assert.strictEqual(modernCapabilities.adcp_version, '3.2-rc.3'); assert.deepStrictEqual(modernCapabilities.media_buy.lifecycle_tools, ['list_products']); const defaultTools = await server.dispatchTestRequest({ method: 'tools/list' }); const modernTools = await server.dispatchTestRequest({ method: 'tools/list', - params: { _meta: { adcp_version: '3.2.0-rc.2' } }, + params: { _meta: { adcp_version: '3.2.0-rc.3' } }, }); assert.strictEqual(defaultTools._meta.adcp_version, '3.1.18'); assert.ok(defaultTools.tools.some(tool => tool.name === 'get_products')); assert.ok(!defaultTools.tools.some(tool => tool.name === 'list_products')); - assert.strictEqual(modernTools._meta.adcp_version, '3.2.0-rc.2'); + assert.strictEqual(modernTools._meta.adcp_version, '3.2.0-rc.3'); assert.ok(modernTools.tools.some(tool => tool.name === 'list_products')); assert.ok(!modernTools.tools.some(tool => tool.name === 'get_products')); @@ -213,9 +213,9 @@ describe('createAdcpServer', () => { createAdcpServer({ name: 'Bad default', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', defaultAdcpVersion: '3.1.18', - capabilities: { supported_versions: ['3.2.0-rc.2'] }, + capabilities: { supported_versions: ['3.2.0-rc.3'] }, }), /defaultAdcpVersion .*must be present/ ); @@ -225,7 +225,7 @@ describe('createAdcpServer', () => { name: 'Newer default', version: '1.0.0', adcpVersion: '3.1.18', - defaultAdcpVersion: '3.2.0-rc.2', + defaultAdcpVersion: '3.2.0-rc.3', }), /defaultAdcpVersion .*must not be newer/ ); @@ -392,8 +392,8 @@ describe('createAdcpServer', () => { const server = createAdcpServer({ name: 'Profile projection seller', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', - capabilities: { supported_versions: ['3.1.18', '3.2.0-rc.2'] }, + adcpVersion: '3.2.0-rc.3', + capabilities: { supported_versions: ['3.1.18', '3.2.0-rc.3'] }, mediaBuy: { ...compactHandlers, getProducts: async () => ({ products: [], cache_scope: 'public' }), @@ -425,8 +425,8 @@ describe('createAdcpServer', () => { const server = createAdcpServer({ name: 'Profile seller', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', - capabilities: { supported_versions: ['3.0.25', '3.1.18', '3.2.0-rc.2'] }, + adcpVersion: '3.2.0-rc.3', + capabilities: { supported_versions: ['3.0.25', '3.1.18', '3.2.0-rc.3'] }, mediaBuy: { ...compactHandlers, getProducts: async params => { @@ -463,10 +463,10 @@ describe('createAdcpServer', () => { assert.ok(!names.includes('update_media_buy'), 'deprecated update alias should not be advertised'); assert.ok(!names.includes('build_creative'), 'creative-builder tools are outside the media-buy role profile'); assert.deepStrictEqual(listed._meta, { - adcp_version: '3.2.0-rc.2', + adcp_version: '3.2.0-rc.3', adcp_profile: 'media-buy', }); - assert.strictEqual(listed.tools[0]._meta.adcp_version, '3.2.0-rc.2'); + assert.strictEqual(listed.tools[0]._meta.adcp_version, '3.2.0-rc.3'); const requestProposalsTool = listed.tools.find(tool => tool.name === 'request_proposals'); const officialRequestSchema = JSON.parse( readFileSync( @@ -519,7 +519,7 @@ describe('createAdcpServer', () => { const server = createAdcpServer({ name: 'Migration seller', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', mcpToolProfile: 'all', mediaBuy: { ...compactHandlers, @@ -1146,7 +1146,7 @@ describe('createAdcpServer', () => { const server = createAdcpServer({ name: `push-config-guard-${label}`, version: '1.0.0', - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', validation: { requests: 'off', responses: 'off' }, mediaBuy: { getProducts: async () => { @@ -1742,7 +1742,7 @@ describe('createAdcpServer', () => { acceptProposal: async () => ({}), }, }); - const modern = await callTool(server, 'get_adcp_capabilities', { adcp_version: '3.2-rc.2' }); + const modern = await callTool(server, 'get_adcp_capabilities', { adcp_version: '3.2-rc.3' }); assert.deepStrictEqual(modern.media_buy.lifecycle_tools, [ 'list_products', 'request_proposals', @@ -3220,7 +3220,7 @@ describe('createAdcpServer', () => { assert.strictEqual(status.task_type, 'sync_creatives'); assert.strictEqual(status.protocol, 'media-buy'); assert.strictEqual(status.has_webhook, true); - assert.strictEqual(status.adcp_version, '3.2-rc.2'); + assert.strictEqual(status.adcp_version, '3.2-rc.3'); assert.deepStrictEqual(status.result, { creatives: [{ creative_id: 'cr_1' }] }); assert.deepStrictEqual(status.context, { trace_id: 'trace_1' }); @@ -3270,7 +3270,7 @@ describe('createAdcpServer', () => { assert.strictEqual(listed.tasks[0].task_type, 'sync_creatives'); assert.strictEqual(listed.tasks[0].has_webhook, true); assert.strictEqual(listed.pagination.total_count, 1); - assert.strictEqual(listed.adcp_version, '3.2-rc.2'); + assert.strictEqual(listed.adcp_version, '3.2-rc.3'); const buyerTwoList = await callTool( server, @@ -3284,7 +3284,7 @@ describe('createAdcpServer', () => { const badCursor = await callToolRaw(server, 'list_tasks', { pagination: { cursor: 'not-a-number' } }, buyerOne); assert.strictEqual(badCursor.isError, true); assert.strictEqual(badCursor.structuredContent.adcp_error.code, 'INVALID_REQUEST'); - assert.strictEqual(badCursor.structuredContent.adcp_version, '3.2-rc.2'); + assert.strictEqual(badCursor.structuredContent.adcp_version, '3.2-rc.3'); const opaqueTaskId = 'opaque_' + 'x'.repeat(160); const opaque = await taskRegistry.create({ @@ -3793,12 +3793,12 @@ describe('createAdcpServer', () => { const status = await callToolRaw(server, 'get_task_status', { task_id: owned.taskId }, extra); assert.strictEqual(status.isError, true); assert.strictEqual(status.structuredContent.adcp_error.code, 'PERMISSION_DENIED'); - assert.strictEqual(status.structuredContent.adcp_version, '3.2-rc.2'); + assert.strictEqual(status.structuredContent.adcp_version, '3.2-rc.3'); const listed = await callToolRaw(server, 'list_tasks', {}, extra); assert.strictEqual(listed.isError, true); assert.strictEqual(listed.structuredContent.adcp_error.code, 'PERMISSION_DENIED'); - assert.strictEqual(listed.structuredContent.adcp_version, '3.2-rc.2'); + assert.strictEqual(listed.structuredContent.adcp_version, '3.2-rc.3'); const contextLeak = await callToolRaw( server, diff --git a/test/server-decisioning-comply-gate.test.js b/test/server-decisioning-comply-gate.test.js index a5f1f137d..648a9cf42 100644 --- a/test/server-decisioning-comply-gate.test.js +++ b/test/server-decisioning-comply-gate.test.js @@ -197,7 +197,7 @@ describe('createAdcpServerFromPlatform — sandbox-authority gate (resolver path const listed = await listTools(server); assert.ok(listed.tools.some(tool => tool.name === 'comply_test_controller')); - assert.strictEqual(isToolAvailableForVersion(server, 'comply_test_controller', '3.2.0-rc.2'), true); + assert.strictEqual(isToolAvailableForVersion(server, 'comply_test_controller', '3.2.0-rc.3'), true); const result = await callForceCreative(server, { account: { account_id: 'sb_acc' } }); diff --git a/test/server-decisioning-from-platform.test.js b/test/server-decisioning-from-platform.test.js index c1f2d6e14..17207c5bc 100644 --- a/test/server-decisioning-from-platform.test.js +++ b/test/server-decisioning-from-platform.test.js @@ -183,8 +183,8 @@ describe('createAdcpServerFromPlatform — v6.0 alpha', () => { const server = createAdcpServerFromPlatform(platform, { name: 'compact-and-legacy', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', - capabilities: { supported_versions: ['3.0.25', '3.1.18', '3.2.0-rc.2'] }, + adcpVersion: '3.2.0-rc.3', + capabilities: { supported_versions: ['3.0.25', '3.1.18', '3.2.0-rc.3'] }, validation: { requests: 'off', responses: 'off' }, }); @@ -210,7 +210,7 @@ describe('createAdcpServerFromPlatform — v6.0 alpha', () => { method: 'tools/call', params: { name: 'list_products', - arguments: { adcp_version: '3.2.0-rc.2', account: { account_id: 'acc-modern' } }, + arguments: { adcp_version: '3.2.0-rc.3', account: { account_id: 'acc-modern' } }, }, }); assert.notStrictEqual(compact.isError, true, JSON.stringify(compact.structuredContent)); @@ -227,7 +227,7 @@ describe('createAdcpServerFromPlatform — v6.0 alpha', () => { assert.notStrictEqual(legacy.isError, true, JSON.stringify(legacy.structuredContent)); } assert.deepStrictEqual(calls, [ - ['list_products', '3.2.0-rc.2', 'acc-modern'], + ['list_products', '3.2.0-rc.3', 'acc-modern'], ['get_products', '3.1.18', 'acc-3.1.18'], ['get_products', '3.0.25', 'acc-3.0.25'], ]); @@ -274,8 +274,8 @@ describe('createAdcpServerFromPlatform — v6.0 alpha', () => { const server = createAdcpServerFromPlatform(platform, { name: 'signed-reverse-compatibility', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', - capabilities: { supported_versions: ['3.1.18', '3.2.0-rc.2'] }, + adcpVersion: '3.2.0-rc.3', + capabilities: { supported_versions: ['3.1.18', '3.2.0-rc.3'] }, validation: { requests: 'off', responses: 'off' }, legacyCreativeFormatConverter: ({ formatId }) => formatId.id === 'display-300x250' @@ -329,7 +329,7 @@ describe('createAdcpServerFromPlatform — v6.0 alpha', () => { const server = createAdcpServerFromPlatform(platform, { name: 'compact-only', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', validation: { requests: 'off', responses: 'off' }, }); @@ -362,7 +362,7 @@ describe('createAdcpServerFromPlatform — v6.0 alpha', () => { const server = createAdcpServerFromPlatform(platform, { name: 'scoped-compact', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', validation: { requests: 'off', responses: 'off' }, }); const response = await server.dispatchTestRequest( @@ -399,7 +399,7 @@ describe('createAdcpServerFromPlatform — v6.0 alpha', () => { const server = createAdcpServerFromPlatform(platform, { name: 'anonymous-session', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', resolveSessionKey: () => 'anonymous-session', validation: { requests: 'off', responses: 'off' }, }); @@ -427,7 +427,7 @@ describe('createAdcpServerFromPlatform — v6.0 alpha', () => { const server = createAdcpServerFromPlatform(platform, { name: 'compact-replay-auth', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', idempotency: createIdempotencyStore({ backend: memoryBackend({ sweepIntervalMs: 0 }) }), resolveIdempotencyPrincipal: () => 'deliberately-shared-principal', resolveSessionKey: () => 'deliberately-shared-session', @@ -476,7 +476,7 @@ describe('createAdcpServerFromPlatform — v6.0 alpha', () => { const server = createAdcpServerFromPlatform(platform, { name: 'refinement-scope', version: '1.0.0', - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', validation: { requests: 'off', responses: 'off' }, }); const response = await server.dispatchTestRequest( @@ -8062,11 +8062,11 @@ describe('HITL push notification webhook on terminal state', () => { }; const platform = buildHitlPlatform(async () => ({ media_buy_id: 'mb_42', status: 'active' })); - for (const adcpVersion of ['3.2-rc.2']) { + for (const adcpVersion of ['3.2-rc.3']) { const server = createAdcpServerFromPlatform(platform, { name: 'webhook', version: '0.0.1', - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', validation: { requests: 'off', responses: 'off' }, taskWebhookEmitter: fakeEmitter, }); @@ -8649,9 +8649,9 @@ describe('tasks_get wire tool (B9)', () => { { name: 'versioned-handoff', version: '0.0.1', - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', defaultAdcpVersion: '3.1.18', - capabilities: { supported_versions: ['3.1.18', '3.2.0-rc.2'] }, + capabilities: { supported_versions: ['3.1.18', '3.2.0-rc.3'] }, resolveSessionKey: async context => { sessionResolverContexts.push(context); return 'session-version-probe'; @@ -8661,10 +8661,10 @@ describe('tasks_get wire tool (B9)', () => { ); const defaultTaskId = await createTask(server, 'acc_default'); - const modernTaskId = await createTask(server, 'acc_modern', '3.2.0-rc.2'); + const modernTaskId = await createTask(server, 'acc_modern', '3.2.0-rc.3'); for (const [taskId, accountId, adcpVersion] of [ [defaultTaskId, 'acc_default', undefined], - [modernTaskId, 'acc_modern', '3.2.0-rc.2'], + [modernTaskId, 'acc_modern', '3.2.0-rc.3'], ]) { await server.dispatchTestRequest({ method: 'tools/call', @@ -8681,11 +8681,11 @@ describe('tasks_get wire tool (B9)', () => { assert.deepStrictEqual( requestContexts.map(ctx => ctx.servedAdcpVersion), - ['3.1', '3.2-rc.2'] + ['3.1', '3.2-rc.3'] ); assert.deepStrictEqual( taskContexts.map(ctx => ctx.servedAdcpVersion), - ['3.1', '3.2-rc.2'] + ['3.1', '3.2-rc.3'] ); for (const context of [ ...requestContexts, @@ -8696,9 +8696,9 @@ describe('tasks_get wire tool (B9)', () => { assert.strictEqual(Object.getOwnPropertyDescriptor(context, 'servedAdcpVersion').writable, false); } assert.ok(accountResolverContexts.some(ctx => ctx.servedAdcpVersion === '3.1')); - assert.ok(accountResolverContexts.some(ctx => ctx.servedAdcpVersion === '3.2-rc.2')); + assert.ok(accountResolverContexts.some(ctx => ctx.servedAdcpVersion === '3.2-rc.3')); assert.ok(sessionResolverContexts.some(ctx => ctx.servedAdcpVersion === '3.1')); - assert.ok(sessionResolverContexts.some(ctx => ctx.servedAdcpVersion === '3.2-rc.2')); + assert.ok(sessionResolverContexts.some(ctx => ctx.servedAdcpVersion === '3.2-rc.3')); }); it('returns spec-flat lifecycle shape for a completed task', async () => { @@ -8783,7 +8783,7 @@ describe('tasks_get wire tool (B9)', () => { creatives_processed: 2, }); assert.deepStrictEqual(legacy.structuredContent.progress, canonical.structuredContent.progress); - assert.strictEqual(legacy.structuredContent.adcp_version, '3.2-rc.2'); + assert.strictEqual(legacy.structuredContent.adcp_version, '3.2-rc.3'); assert.strictEqual(legacy.structuredContent.adcp_version, canonical.structuredContent.adcp_version); const legacyPinned = await server.dispatchTestRequest({ @@ -8889,7 +8889,7 @@ describe('tasks_get wire tool (B9)', () => { assert.strictEqual(status.structuredContent.status, 'submitted'); assert.strictEqual(status.structuredContent.has_webhook, true); assert.strictEqual(status.structuredContent.result, undefined); - assert.strictEqual(status.structuredContent.adcp_version, '3.2-rc.2'); + assert.strictEqual(status.structuredContent.adcp_version, '3.2-rc.3'); const listed = await server.dispatchTestRequest({ method: 'tools/call', @@ -9820,7 +9820,7 @@ describe('createAdcpServerFromPlatform — default resolveIdempotencyPrincipal', { name: 'principal-compat', version: '0.0.1', - adcpVersion: '3.2.0-rc.2', + adcpVersion: '3.2.0-rc.3', idempotency, validation: { requests: 'off', responses: 'off' }, } From 5e87af55465197c030149d923f8c441fc64cde03 Mon Sep 17 00:00:00 2001 From: Brian O'Kelley Date: Mon, 14 Sep 2026 15:48:42 +0000 Subject: [PATCH 2/3] fix(protocol): close rc.3 adoption gaps and land null-clear durability MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four things, all consequences of the rc.3 bundle meeting the existing surface. **Package budget.** rc.3 publishes sixteen new source schemas (the scoped and media-buy frequency-cap families, `core/media-buy-available-action-id.json`, and the shared frequency-cap duration/control/mutable-field enums) plus two new compliance storyboards. With bundled and compact-projection copies that is +26 published files; the Targeting Input helper module adds +4 more. Budget moves 5,995 -> 6,025 with the itemization in the comment. Unpacked is 101.7 MiB against a 120 MiB ceiling. **Version-negotiation fixtures.** The blanket rc.2 -> rc.3 pin sweep inverted three fail-closed tests: their whole point is that the seller advertises or serves something *newer* than the buyer pin, and rewriting the buyer pin to match made "newer" equal. They now derive both sides from `ADCP_VERSION` and a `ONE_BEYOND_SDK_PIN` computed from it, so the relationship survives the next bump instead of silently degrading into "seller advertises the same version". **Targeting Input codegen.** `TargetingOverlayInput.device_platform` and `.device_type` were emitted as the scalar `DevicePlatform` / `DeviceType` enums where the wire carries arrays. `core/targeting-input.json` reaches those dimensions through a JSON-pointer `$ref` into `core/targeting.json#/properties/`, and for an array with no `title` of its own json-schema-to-typescript names the result after the items' canonical `$ref`. Verified against a standalone jsts compile, which produces the correct tuple — the loss is specific to the aggregate pass. `alignTargetingInputArrayCardinality` repairs it from the invariant the two schemas actually satisfy (identical property sets, so Input is Overlay plus `| null` per dimension), and only where the Input side is provably the item type of the Overlay side's array, so a correct alias is never rewritten and per-property JSDoc is preserved. **Null-clear durability (#7466 / DR-0020).** `resolveTargetingInput`, `applyTargetingInput`, and `hasTargetingClears` project between the request-only Targeting Input and the strict overlay used by snapshots, responses, and readback. `createMediaBuyStore` had two paths that could write a clear command into durable state — `persistFromCreate` falling back to the request overlay verbatim when the seller echoed none, and the `new_packages` arm of `mergeFromUpdate` assigning the incoming overlay directly — after which `backfill` would echo `null` into a `get_media_buys` response whose schema forbids it. Both resolve clears away now, and clearing the last surviving dimension drops the tracked overlay rather than persisting `{}`. The store's input types widen to the request shape so a real payload typechecks; persisted and echoed values stay strict. `examples/seller-3.2-starter.ts` projects the same way when building its accepted proposal, which is what CI's example typecheck was failing on. Co-Authored-By: Claude Opus 5 (1M context) --- .changeset/targeting-input-null-clear.md | 29 ++++ examples/seller-3.2-starter.ts | 11 +- scripts/check-package-size.mjs | 8 +- scripts/generate-types.ts | 133 ++++++++++++++--- src/lib/index.ts | 5 + src/lib/media-buy/index.ts | 3 + src/lib/media-buy/targeting-input.ts | 136 +++++++++++++++++ src/lib/server/index.ts | 5 + src/lib/server/media-buy-store.ts | 72 +++++---- src/lib/types/core.generated.ts | 6 +- src/lib/types/tools.generated.ts | 4 +- .../media-buy-lifecycle-coordinator.test.js | 39 +++-- test/lib/targeting-input-null-clear.test.js | 137 ++++++++++++++++++ 13 files changed, 511 insertions(+), 77 deletions(-) create mode 100644 .changeset/targeting-input-null-clear.md create mode 100644 src/lib/media-buy/targeting-input.ts create mode 100644 test/lib/targeting-input-null-clear.test.js diff --git a/.changeset/targeting-input-null-clear.md b/.changeset/targeting-input-null-clear.md new file mode 100644 index 000000000..6b832aaed --- /dev/null +++ b/.changeset/targeting-input-null-clear.md @@ -0,0 +1,29 @@ +--- +'@adcp/sdk': minor +--- + +Add request-only Targeting Input helpers for the AdCP 3.2 null-clear semantics (DR-0020) and stop +`createMediaBuyStore` from persisting a clear command. + +`resolveTargetingInput`, `applyTargetingInput`, and `hasTargetingClears` are exported from the root +and `@adcp/sdk/server`. They project between the request-only Targeting Input — where a dimension may +be `null` to suppress a product default on create or clear stored state on update — and the strict +Targeting Overlay used by discovery criteria, accepted commercial snapshots, mutation responses, and +package readback, which must not contain `null`. + +Two fixes in `createMediaBuyStore`, both reachable only once rc.3 makes the nullable input types +real: `persistFromCreate` fell back to the request overlay verbatim when the seller's response did +not echo one, and the `new_packages` arm of `mergeFromUpdate` assigned the incoming overlay directly. +Either path could write a `null` clear command into durable state, which `backfill` would then echo +into a `get_media_buys` response whose schema forbids null. Both now resolve clears away, and a patch +that clears the last surviving dimension drops the tracked overlay instead of persisting `{}`. + +The store's `CreateMediaBuyInputForStore` / `UpdateMediaBuyInputForStore` input types widen from the +strict overlay to the request shape, so passing a real `create_media_buy` / `update_media_buy` +payload typechecks. Persisted and echoed values remain strict. + +Codegen fix: `TargetingOverlayInput.device_platform` and `.device_type` were emitted as the scalar +`DevicePlatform` / `DeviceType` enums instead of arrays. `core/targeting-input.json` reaches those +dimensions through a JSON-pointer `$ref` into `core/targeting.json#/properties/`, and for +an array with no `title` of its own json-schema-to-typescript names the result after the items' +canonical `$ref`. Both types now match the wire. diff --git a/examples/seller-3.2-starter.ts b/examples/seller-3.2-starter.ts index 34593a92a..15dcf9251 100644 --- a/examples/seller-3.2-starter.ts +++ b/examples/seller-3.2-starter.ts @@ -1,7 +1,7 @@ // prettier-ignore import { AdcpError, createAdcpServerFromPlatform, createIdempotencyStore, createInMemoryTaskRegistry, - definePlatform, memoryBackend, proposalTermsDigest, serve, verifyApiKey, type BuyProductsPayload, - type GetMediaBuysPayload, type ListProductsPayload } from '@adcp/sdk/server'; + definePlatform, memoryBackend, proposalTermsDigest, resolveTargetingInput, serve, verifyApiKey, + type BuyProductsPayload, type GetMediaBuysPayload, type ListProductsPayload } from '@adcp/sdk/server'; const TOKEN = process.env.ADCP_AUTH_TOKEN; if (!TOKEN) throw new Error('Set ADCP_AUTH_TOKEN before starting the seller'); const ACCOUNT_ID = process.env.ADCP_ACCOUNT_ID; @@ -80,7 +80,12 @@ const platform = definePlatform({ for (const field of ['measurement_terms', 'performance_standards'] as const) { if (purchase[field] !== undefined && !sameTerms(purchase[field], published[field])) throw new AdcpError('TERMS_REJECTED', { message: `${field} must match the published product terms` }); } - return { ...purchase, pricing, ...published, start_time: resolvedStart, end_time: req.end_time }; + // `purchase.targeting_overlay` is a request-only Targeting Input, so a + // dimension may be `null` to suppress a product default. The accepted + // proposal is a strict snapshot that must not carry clear commands. + const targetingOverlay = resolveTargetingInput(purchase.targeting_overlay); + return { ...purchase, pricing, ...published, start_time: resolvedStart, end_time: req.end_time, + ...(targetingOverlay ? { targeting_overlay: targetingOverlay } : { targeting_overlay: undefined }) }; }), ...(req.total_budget && { total_budget: req.total_budget }), ...(req.invoice_recipient && { invoice_recipient: req.invoice_recipient }), diff --git a/scripts/check-package-size.mjs b/scripts/check-package-size.mjs index fde5d23de..b89f02eba 100644 --- a/scripts/check-package-size.mjs +++ b/scripts/check-package-size.mjs @@ -29,7 +29,13 @@ const MAX_UNPACKED_PACKAGE_BYTES = 120 * 1024 * 1024; // and one migration guide. Byte budgets remain unchanged. // The standalone proposal verifier adds twelve helper module artifacts and // one buyer guide; byte budgets remain unchanged. -const MAX_PACKED_FILE_COUNT = 6_029; +// AdCP 3.2.0-rc.3 publishes sixteen new source schemas — the scoped and +// media-buy frequency-cap families plus `core/media-buy-available-action-id.json` +// and the shared frequency-cap duration/control/mutable-field enums — and two +// new compliance storyboards. With their bundled and compact-projection copies +// that is +26 published files. The request-only Targeting Input helpers add one +// module (CJS + ESM + both declaration flavours), for +4 more. +const MAX_PACKED_FILE_COUNT = 6_059; const MAX_BUNDLED_SCHEMA_BYTES = 1280 * 1024; const MAX_CJS_SCHEMA_DECLARATION_BYTES = 45 * 1024 * 1024; const MAX_ESM_SCHEMA_FACADE_BYTES = 1024; diff --git a/scripts/generate-types.ts b/scripts/generate-types.ts index c442b4a32..754fd5759 100644 --- a/scripts/generate-types.ts +++ b/scripts/generate-types.ts @@ -3430,6 +3430,94 @@ const JSTS_NUMBERED_SEMANTIC_RENAMES: Array<{ numbered: string; semantic: string { numbered: 'TaskStatus2', semantic: 'GetProductsRejectedStatus' }, ]; +/** + * Extract the 4-space-indented property declarations of one generated + * `export type = ... & { ... };` block, keyed by property name. + * + * Returns `undefined` when the type is absent, which is the normal case on + * schema pins that predate it. + */ +function generatedObjectTypeProperties( + typeDefinitions: string, + typeName: string +): { start: number; end: number; properties: Map } | undefined { + const pattern = new RegExp(`export type ${typeName} = [^{]*\\{([\\s\\S]*?)\\n \\};`, 'm'); + const match = pattern.exec(typeDefinitions); + if (!match) return undefined; + const body = match[1]!; + const properties = new Map(); + const propertyPattern = /\n (\w+)\?: ([^;]+);/g; + let property; + while ((property = propertyPattern.exec(body)) !== null) { + properties.set(property[1]!, { type: property[2]!.trim(), declaration: property[0]! }); + } + return { start: match.index + match[0].indexOf(body), end: match.index + match[0].length, properties }; +} + +/** Item type of `[T, ...T[]]` or `T[]` when `T` is a single identifier. */ +function soleArrayItemTypeName(type: string): string | undefined { + const normalized = type.replace(/\s+/g, ' ').trim(); + const tuple = /^\[(\w+), \.\.\.\1\[\]\]$/.exec(normalized); + if (tuple) return tuple[1]; + const array = /^(\w+)\[\]$/.exec(normalized); + return array?.[1]; +} + +/** + * Restore array cardinality on request-only Targeting Input dimensions that + * json-schema-to-typescript collapsed to their item type. + * + * `core/targeting-input.json` reaches each dimension through a JSON-pointer + * `$ref` into `core/targeting.json#/properties/` (AdCP 3.2, + * DR-0020). For a dimension whose array has no `title` of its own, jsts can + * name the resulting type after the items' canonical `$ref` — so + * `device_platform` and `device_type` end up declared as the scalar + * `DevicePlatform` / `DeviceType` enums instead of the arrays the wire + * carries. Left uncorrected, an adopter clearing or replacing those + * dimensions gets a type error on correct code and no error on a payload the + * seller must reject. + * + * The two schemas declare an identical property set, so the invariant is + * exact: `TargetingOverlayInput` is `TargetingOverlay` plus `| null` on each + * dimension. This only rewrites the narrow case that provably lost + * cardinality — the Input side is a bare identifier that is precisely the item + * type of the Overlay side's array — so a dimension that legitimately differs, + * or that is already a correct array alias, is left untouched. Per-property + * JSDoc is preserved because only the type annotation is replaced. + */ +export function alignTargetingInputArrayCardinality(typeDefinitions: string): string { + const overlay = generatedObjectTypeProperties(typeDefinitions, 'TargetingOverlay'); + const input = generatedObjectTypeProperties(typeDefinitions, 'TargetingOverlayInput'); + if (!overlay || !input) return typeDefinitions; + + const corrections: string[] = []; + let result = typeDefinitions; + for (const [name, inputProperty] of input.properties) { + const overlayProperty = overlay.properties.get(name); + if (!overlayProperty) continue; + const itemType = soleArrayItemTypeName(overlayProperty.type); + if (!itemType) continue; + const nullStripped = inputProperty.type.replace(/\s*\|\s*null$/, '').trim(); + if (nullStripped !== itemType) continue; + const repaired = inputProperty.declaration.replace( + `${name}?: ${inputProperty.type};`, + `${name}?: ${overlayProperty.type} | null;` + ); + result = + result.slice(0, input.start) + + result.slice(input.start, input.end).replace(inputProperty.declaration, repaired) + + result.slice(input.end); + corrections.push(`${name}: ${nullStripped} -> ${overlayProperty.type}`); + } + + if (corrections.length > 0) { + console.log( + `🎯 Restored ${corrections.length} TargetingOverlayInput array dimension(s): ${corrections.join(', ')}` + ); + } + return result; +} + export function renameKnownNumberedSemanticTypes(typeDefinitions: string): string { const exportedTypes = collectExportedTypeNames(typeDefinitions); let result = typeDefinitions; @@ -4428,6 +4516,9 @@ async function generateTypes() { toolTypes = widenMediaBuyFeaturesIndexSignature(toolTypes); toolTypes = simplifyForecastRange(toolTypes); toolTypes = simplifyPriceBreakdown(toolTypes); + // Runs before the core-import rewrite so the repaired declaration still sees + // both Targeting types spelled out in this unit. + toolTypes = alignTargetingInputArrayCardinality(toolTypes); // This set is deliberately limited to canonical enums plus the handful of // shared core contracts above. Import all of them: numbered-type cleanup can // introduce a canonical reference after lexical reference scanning, and @@ -4462,23 +4553,25 @@ async function generateTypes() { // residual jsts under-resolution artifacts (*Asset1, AssetVariant1, CreativeAsset1) — // see applyKnownJstsAliases for the rationale. Finally, restore the asset_type // discriminator on Individual*Asset slot aliases that jsts collapses (#1498). - const processedCoreTypes = relaxArrayCardinalityTypes( - normalizeTransformerParamJsonValueTypes( - relaxZodCompatibilityArrayTypes( - hardenTrustedMatchGeneratedTypes( - applyIndividualAssetDiscriminators( - addBackwardCompatTypeAliases( - simplifyForecastRange( - simplifyPriceBreakdown( - widenMediaBuyFeaturesIndexSignature( - widenPostalAreaSupportIndexSignature( - widenReportedOutcomeErrorIndexSignature( - fixTypedIndexSignatures( - removeResidualInlineIndexSignatureArms( - applyKnownJstsAliases( - namePostalAreaCountryBranch( - renameKnownNumberedSemanticTypes( - removeNumberedTypeDuplicates(removeIndexSignatureTypes(coreTypes)) + const processedCoreTypes = alignTargetingInputArrayCardinality( + relaxArrayCardinalityTypes( + normalizeTransformerParamJsonValueTypes( + relaxZodCompatibilityArrayTypes( + hardenTrustedMatchGeneratedTypes( + applyIndividualAssetDiscriminators( + addBackwardCompatTypeAliases( + simplifyForecastRange( + simplifyPriceBreakdown( + widenMediaBuyFeaturesIndexSignature( + widenPostalAreaSupportIndexSignature( + widenReportedOutcomeErrorIndexSignature( + fixTypedIndexSignatures( + removeResidualInlineIndexSignatureArms( + applyKnownJstsAliases( + namePostalAreaCountryBranch( + renameKnownNumberedSemanticTypes( + removeNumberedTypeDuplicates(removeIndexSignatureTypes(coreTypes)) + ) ) ) ) @@ -4492,9 +4585,9 @@ async function generateTypes() { ) ) ) - ) - ), - { maxItemsOnly: true } + ), + { maxItemsOnly: true } + ) ); const coreChanged = writeFileIfChanged(coreTypesPath, processedCoreTypes); diff --git a/src/lib/index.ts b/src/lib/index.ts index 7fd55930f..5988f889c 100644 --- a/src/lib/index.ts +++ b/src/lib/index.ts @@ -737,6 +737,8 @@ export type { SLAWindow, SlaWindow, StructuredOnlyMediaBuyAction, + ResolvedTargetingInput, + TargetingInputFor, ValidateProductsAgainstPropertyPolicyOptions, UpdateFieldEntry, UpdateMediaBuyRequestLike, @@ -746,6 +748,9 @@ export { LEGACY_COARSE_ACTIONS, STRUCTURED_ONLY_MEDIA_BUY_ACTIONS, UPDATE_FIELDS_BY_ACTION, + applyTargetingInput, + hasTargetingClears, + resolveTargetingInput, canAddPackages, canCancel, canDecreaseBudget, diff --git a/src/lib/media-buy/index.ts b/src/lib/media-buy/index.ts index 0cd86134e..7d81333e8 100644 --- a/src/lib/media-buy/index.ts +++ b/src/lib/media-buy/index.ts @@ -88,6 +88,9 @@ export { UPDATE_FIELDS_BY_ACTION, } from './update-fields.generated'; +export { applyTargetingInput, hasTargetingClears, resolveTargetingInput } from './targeting-input'; +export type { ResolvedTargetingInput, TargetingInputFor } from './targeting-input'; + export * from './compatibility'; export * from './established-proposal-store'; export * from './legacy-purchase-continuation'; diff --git a/src/lib/media-buy/targeting-input.ts b/src/lib/media-buy/targeting-input.ts new file mode 100644 index 000000000..6b9028339 --- /dev/null +++ b/src/lib/media-buy/targeting-input.ts @@ -0,0 +1,136 @@ +/** + * Request-only Targeting Input helpers (AdCP 3.2, DR-0020). + * + * AdCP 3.2 mutation requests carry a **Targeting Input** with three states for + * every targeting dimension: + * + * | wire state | create | update | + * |---|---|---| + * | dimension omitted | inherit the configured-product / product default | leave stored state unchanged | + * | dimension `null` | suppress that default | clear the stored dimension | + * | dimension non-null | replace the complete dimension | replace the complete dimension | + * + * `null` is a **command, not targeting state**. Discovery criteria, configured + * products, accepted commercial snapshots, mutation responses, and package + * readback all use the strict Targeting *Overlay* and MUST NOT contain `null` — + * which is why codegen emits two types (`TargetingOverlayInput` with nullable + * dimensions, `TargetingOverlay` without). After a successful clear the + * dimension is simply absent from effective readback. + * + * These helpers are the projection between the two. Use them anywhere a + * request-shaped overlay flows into durable state or into a response: + * persisting an overlay verbatim would write a clear command into stored + * targeting, and echoing it back would emit `null` on a wire shape whose schema + * forbids it. + * + * `null` cannot remove inherent product scope. These helpers only project the + * three states; deciding whether a clear is *executable* for a given product + * remains the seller's validation step, which rejects a clear it cannot honor + * rather than silently retaining the default. + */ + +/** + * Strict effective overlay derived from a request-only Targeting Input: the + * same dimensions, with the `null` clear command removed from each. + * + * Generic rather than hardcoded to the generated `TargetingOverlay` because + * the per-tool payload types widen non-empty-array tuples (`[string, + * ...string[]]` becomes `string[]`), so a call site holding a payload-shaped + * purchase or package still gets a precisely-typed result instead of being + * pushed into a cast. + */ +export type ResolvedTargetingInput = { [K in keyof T]?: Exclude }; + +/** + * Request-only Targeting Input derived from a strict overlay type: every + * dimension additionally accepts `null` as the clear command. + * + * The generated `TargetingOverlayInput` is the canonical instance of this + * shape; expressing it as a mapping keeps {@link applyTargetingInput} usable + * from a call site whose overlay type is a payload-shaped widening. + */ +export type TargetingInputFor = { [K in keyof T]?: T[K] | null }; + +/** + * Resolve a request-only Targeting Input into the strict effective overlay, + * dropping every `null` clear command. + * + * Use this on the **create** path, and whenever a request-shaped overlay is + * about to become an accepted snapshot, a readback value, or durable state. + * + * Returns `undefined` when the input is absent, is an explicit whole-overlay + * clear, or resolves to no surviving dimensions — a cleared dimension is absent + * from effective readback, so an empty overlay is expressed by omitting it + * rather than by echoing `{}`. + * + * @example + * ```ts + * resolveTargetingInput({ geo_countries: ['US'], audience_include: null }); + * // → { geo_countries: ['US'] } — the clear command is not stored + * ``` + */ +export function resolveTargetingInput( + input: T | null | undefined +): ResolvedTargetingInput | undefined { + if (!input) return undefined; + return compactOverlay>(Object.entries(input)); +} + +/** + * Apply a request-only Targeting Input patch to the prior effective overlay. + * + * Use this on the **update** path. Implements the three states per dimension: + * a dimension absent from the patch keeps its prior value, a dimension set to + * `null` is cleared, and a non-null dimension replaces the prior value + * completely. + * + * A `null` patch (rather than a patch *containing* nulls) clears the whole + * overlay; an `undefined` patch leaves the prior overlay untouched, which is + * how "the request did not mention targeting" is distinguished from "the + * request asked to clear it". + * + * The merge is one level deep. `property_list` / `collection_list` are + * reference objects keyed by `list_id`, so a partial merge of one would be + * meaningless — a top-level replace is the correct semantics. + * + * @example + * ```ts + * applyTargetingInput({ geo_countries: ['US'], audience_include: [...] }, { audience_include: null }); + * // → { geo_countries: ['US'] } — only the named dimension is cleared + * ``` + */ +export function applyTargetingInput( + prior: TOverlay | undefined, + input: TargetingInputFor | null | undefined +): TOverlay | undefined { + if (input === undefined) return prior; + if (input === null) return undefined; + return compactOverlay([...Object.entries(prior ?? {}), ...Object.entries(input)]); +} + +/** + * True when the input carries at least one `null` clear command. + * + * Useful for a seller that must decide whether a clear is executable against + * inherent product scope before accepting the mutation, and for asserting at a + * response boundary that no clear command leaked into a strict overlay. + */ +export function hasTargetingClears(input: object | null | undefined): boolean { + if (input === null) return true; + if (!input) return false; + return Object.values(input).some(value => value === null); +} + +/** + * Fold ordered `[key, value]` pairs into a strict overlay. Later pairs win, a + * `null` value deletes the key outright, and `undefined` is treated as "not + * mentioned" so an explicitly-undefined patch key cannot erase a prior value. + */ +function compactOverlay(entries: Array<[string, unknown]>): T | undefined { + const merged: Record = {}; + for (const [key, value] of entries) { + if (value === null) delete merged[key]; + else if (value !== undefined) merged[key] = value; + } + return Object.keys(merged).length > 0 ? (merged as T) : undefined; +} diff --git a/src/lib/server/index.ts b/src/lib/server/index.ts index 98b246abc..42aa10a52 100644 --- a/src/lib/server/index.ts +++ b/src/lib/server/index.ts @@ -175,6 +175,11 @@ export { assertUpdateMediaBuyAllowed } from './media-buy-actions'; export type { AssertUpdateMediaBuyAllowedOptions } from './media-buy-actions'; export { createMediaBuyStore, DEFAULT_MEDIA_BUY_STORE_COLLECTION } from './media-buy-store'; +// Request-only Targeting Input projection (AdCP 3.2, DR-0020). Re-exported on +// the server subpath because sellers are the side that has to resolve a clear +// command into strict effective targeting before persisting or echoing it. +export { applyTargetingInput, hasTargetingClears, resolveTargetingInput } from '../media-buy/targeting-input'; +export type { ResolvedTargetingInput, TargetingInputFor } from '../media-buy/targeting-input'; export type { MediaBuyStore, CreateMediaBuyStoreOptions, diff --git a/src/lib/server/media-buy-store.ts b/src/lib/server/media-buy-store.ts index f35d925d0..3c4181555 100644 --- a/src/lib/server/media-buy-store.ts +++ b/src/lib/server/media-buy-store.ts @@ -32,7 +32,8 @@ * ``` */ -import type { TargetingOverlay } from '../types/core.generated'; +import { applyTargetingInput, resolveTargetingInput } from '../media-buy/targeting-input'; +import type { TargetingOverlay, TargetingOverlayInput } from '../types/core.generated'; import type { AdcpStateStore } from './state-store'; import { scopedStore } from './state-store'; @@ -58,7 +59,12 @@ export interface CreateMediaBuyInputForStore { packages?: Array<{ package_id?: string; buyer_ref?: string; - targeting_overlay?: TargetingOverlay; + /** + * Request-shaped Targeting Input: individual dimensions may be `null` to + * suppress a configured-product or product default (AdCP 3.2, DR-0020). + * The store resolves those clear commands away before persisting. + */ + targeting_overlay?: TargetingOverlayInput | null; }>; } @@ -78,12 +84,17 @@ export interface CreateMediaBuyResultForStore { export interface UpdateMediaBuyInputForStore { packages?: Array<{ package_id?: string; - targeting_overlay?: TargetingOverlay | null; + /** + * Request-shaped Targeting Input patch. `undefined` (or absent) leaves the + * stored overlay unchanged, `null` clears it entirely, and an object + * merges per dimension where a `null` dimension clears just that one. + */ + targeting_overlay?: TargetingOverlayInput | null; }>; new_packages?: Array<{ package_id?: string; buyer_ref?: string; - targeting_overlay?: TargetingOverlay; + targeting_overlay?: TargetingOverlayInput | null; }>; } @@ -124,6 +135,10 @@ export interface MediaBuyStore { * - field present with a non-null value → replace * - field present and `null` → clear (drop the field) * + * A patch that clears the last surviving dimension drops the package's + * tracked overlay entirely, so `backfill` stops echoing one — a cleared + * dimension is absent from effective readback rather than present as `null`. + * * `new_packages` from the patch are persisted as fresh entries when * they declare `targeting_overlay`. Entries that omit it are * intentionally NOT tracked — this store is overlay-only, and a @@ -187,10 +202,14 @@ export function createMediaBuyStore(options: CreateMediaBuyStoreOptions): MediaB const packageId = respPkg?.package_id; if (!packageId) continue; - persistedPackages.push({ - package_id: packageId, - targeting_overlay: respPkg?.targeting_overlay ?? reqPkg.targeting_overlay, - }); + // The seller's echo is already the strict effective overlay. Falling + // back to the request means falling back to a *Targeting Input*, so + // resolve its clear commands away first: persisting `null` would put a + // command into durable state, and `backfill` would then echo it into a + // get_media_buys response whose schema forbids null. + const persistedOverlay = respPkg?.targeting_overlay ?? resolveTargetingInput(reqPkg.targeting_overlay); + if (!persistedOverlay) continue; + persistedPackages.push({ package_id: packageId, targeting_overlay: persistedOverlay }); } if (persistedPackages.length === 0) return; @@ -217,18 +236,19 @@ export function createMediaBuyStore(options: CreateMediaBuyStoreOptions): MediaB // parse, omitted fields are absent from the object entirely. if (!('targeting_overlay' in pkg)) continue; const incoming = pkg.targeting_overlay; - if (incoming === null) { - byId.delete(packageId); - continue; - } if (incoming === undefined) continue; - const priorOverlay = byId.get(packageId); - byId.set(packageId, mergeOverlay(priorOverlay, incoming)); + const merged = applyTargetingInput(byId.get(packageId), incoming); + if (merged) byId.set(packageId, merged); + else byId.delete(packageId); } for (const pkg of patch.new_packages ?? []) { if (!pkg?.targeting_overlay || !pkg.package_id) continue; - byId.set(pkg.package_id, pkg.targeting_overlay); + // A brand-new package has no prior state to patch, so a `null` + // dimension suppresses a product default rather than clearing stored + // targeting. Either way it must not reach durable state. + const resolved = resolveTargetingInput(pkg.targeting_overlay); + if (resolved) byId.set(pkg.package_id, resolved); } await writeRecord(accountId, { @@ -258,25 +278,3 @@ export function createMediaBuyStore(options: CreateMediaBuyStoreOptions): MediaB }, }; } - -/** - * Per-key merge of an incoming `TargetingOverlay` patch against the prior - * persisted overlay. Each key the patch sets to `null` is dropped; each - * key the patch sets to a value replaces the prior; keys absent from the - * patch are preserved. - * - * The merge is one level deep — `property_list` / `collection_list` are - * reference objects keyed by `list_id`, so a "partial" property-list - * update is meaningless and a top-level replace is the right semantics. - */ -function mergeOverlay(prior: TargetingOverlay | undefined, patch: TargetingOverlay): TargetingOverlay { - const merged: Record = { ...(prior ?? {}) }; - for (const [key, value] of Object.entries(patch)) { - if (value === null) { - delete merged[key]; - } else if (value !== undefined) { - merged[key] = value; - } - } - return merged as TargetingOverlay; -} diff --git a/src/lib/types/core.generated.ts b/src/lib/types/core.generated.ts index 9bcae2c4a..22012c30a 100644 --- a/src/lib/types/core.generated.ts +++ b/src/lib/types/core.generated.ts @@ -1,5 +1,5 @@ // Generated AdCP core types from official schemas v3.2.0-rc.3 -// Generated at: 2026-09-14T14:16:05.638Z +// Generated at: 2026-09-14T15:25:53.002Z // ACCOUNTCURRENCYMODE CANONICAL ENUM /** @@ -5857,9 +5857,9 @@ export type TargetingOverlayInput = TargetingUnknownAgeEligibilityConstraint & placement_selection?: PlacementSelection | null; collection_selection?: TargetingCollectionSelection | null; age_restriction?: AgeRestriction | null; - device_platform?: DevicePlatform | null; + device_platform?: [DevicePlatform, ...DevicePlatform[]] | null; device_platform_exclude?: DevicePlatformExclude | null; - device_type?: DeviceType | null; + device_type?: [DeviceType, ...DeviceType[]] | null; device_type_exclude?: DeviceTypeExclude | null; browser?: Browser | null; browser_exclude?: BrowserExclude | null; diff --git a/src/lib/types/tools.generated.ts b/src/lib/types/tools.generated.ts index 95a1860ed..6958a81b2 100644 --- a/src/lib/types/tools.generated.ts +++ b/src/lib/types/tools.generated.ts @@ -10209,9 +10209,9 @@ export type TargetingOverlayInput = TargetingUnknownAgeEligibilityConstraint & placement_selection?: PlacementSelection | null; collection_selection?: TargetingCollectionSelection | null; age_restriction?: AgeRestriction | null; - device_platform?: DevicePlatform | null; + device_platform?: [DevicePlatform, ...DevicePlatform[]] | null; device_platform_exclude?: DevicePlatformExclude | null; - device_type?: DeviceType | null; + device_type?: [DeviceType, ...DeviceType[]] | null; device_type_exclude?: DeviceTypeExclude | null; browser?: Browser | null; browser_exclude?: BrowserExclude | null; diff --git a/test/lib/media-buy-lifecycle-coordinator.test.js b/test/lib/media-buy-lifecycle-coordinator.test.js index cb887d049..da9dc5f23 100644 --- a/test/lib/media-buy-lifecycle-coordinator.test.js +++ b/test/lib/media-buy-lifecycle-coordinator.test.js @@ -19,7 +19,22 @@ const { memoryBackend, proposalTermsDigest, } = require('../../dist/lib/index.js'); +const { ADCP_VERSION } = require('../../dist/lib/version.js'); const { normalizeGetProductsResponse } = require('../../dist/lib/utils/pricing-adapter.js'); + +// The SDK's own default pin, plus a synthetic release one step beyond it. +// Negotiation fail-closed tests are about the *relationship* between what a +// seller advertises and what the buyer is pinned to, so deriving the "newer" +// side keeps them meaningful across pin bumps instead of silently inverting +// into "seller advertises the same version" the next time the pin moves. +const SDK_PIN = ADCP_VERSION; +const ONE_BEYOND_SDK_PIN = (() => { + const prerelease = /^(\d+\.\d+\.\d+-[0-9A-Za-z-]+\.)(\d+)$/.exec(SDK_PIN); + if (prerelease) return `${prerelease[1]}${Number(prerelease[2]) + 1}`; + const stable = /^(\d+)\.(\d+)\.(\d+)$/.exec(SDK_PIN); + if (stable) return `${stable[1]}.${Number(stable[2]) + 1}.0`; + throw new Error(`Cannot derive a newer release than the SDK pin ${SDK_PIN}`); +})(); const { DEFERRED_SETTLEMENT_ACK, DeferredSettlementOwnershipError, @@ -43,7 +58,7 @@ const AGENT = { protocol: 'mcp', }; -function capabilities({ version = '3.2.0-rc.3', tools, discoveredTools, replayTtlSeconds = 3600 } = {}) { +function capabilities({ version = SDK_PIN, tools, discoveredTools, replayTtlSeconds = 3600 } = {}) { if (version === '2.5') { return { version: 'v2', @@ -3741,8 +3756,8 @@ describe('MediaBuyLifecycleCoordinator negotiation matrix', () => { test('does not select a newer prerelease than the compact buyer pin', async () => { const caps = capabilities({ tools: COMPACT_TOOLS }); - caps.supportedVersions = ['3.1', '3.2.0-rc.3']; - const agent = clientWithCaps(caps, '3.2.0-rc.3'); + caps.supportedVersions = ['3.1', ONE_BEYOND_SDK_PIN]; + const agent = clientWithCaps(caps, SDK_PIN); const calls = []; agent.getProducts = async () => { calls.push('get_products'); @@ -3758,12 +3773,12 @@ describe('MediaBuyLifecycleCoordinator negotiation matrix', () => { test('fails closed when every valid advertised version is newer than the buyer pin', async () => { const caps = capabilities({ tools: COMPACT_TOOLS }); - caps.supportedVersions = ['3.2.0-rc.3']; - const agent = clientWithCaps(caps, '3.2.0-rc.3'); + caps.supportedVersions = [ONE_BEYOND_SDK_PIN]; + const agent = clientWithCaps(caps, SDK_PIN); await assert.rejects( agent.negotiateMediaBuyLifecycle(), - /advertises only AdCP versions newer than the client pin 3\.2\.0-rc\.2/ + new RegExp(`advertises only AdCP versions newer than the client pin ${SDK_PIN.replace(/\./g, '\\.')}`) ); }); @@ -3793,19 +3808,21 @@ describe('MediaBuyLifecycleCoordinator negotiation matrix', () => { await assert.rejects( agent.negotiateMediaBuyLifecycle(), - /served AdCP 3\.3, which is newer than the client pin 3\.2\.0-rc\.2/ + new RegExp(`served AdCP 3\\.3, which is newer than the client pin ${SDK_PIN.replace(/\./g, '\\.')}`) ); }); test('fails closed when an exact newer prerelease is served despite an older advertised fallback', async () => { const caps = capabilities({ tools: COMPACT_TOOLS }); - caps.servedVersion = '3.2.0-rc.4'; - caps.supportedVersions = ['3.2.0-rc.4', '3.2.0-rc.3']; - const agent = clientWithCaps(caps, '3.2.0-rc.3'); + caps.servedVersion = ONE_BEYOND_SDK_PIN; + caps.supportedVersions = [ONE_BEYOND_SDK_PIN, SDK_PIN]; + const agent = clientWithCaps(caps, SDK_PIN); await assert.rejects( agent.negotiateMediaBuyLifecycle(), - /served AdCP 3\.2\.0-rc\.4, which is newer than the client pin 3\.2\.0-rc\.3/ + new RegExp( + `served AdCP ${ONE_BEYOND_SDK_PIN.replace(/\./g, '\\.')}, which is newer than the client pin ${SDK_PIN.replace(/\./g, '\\.')}` + ) ); }); diff --git a/test/lib/targeting-input-null-clear.test.js b/test/lib/targeting-input-null-clear.test.js new file mode 100644 index 000000000..27f86a30e --- /dev/null +++ b/test/lib/targeting-input-null-clear.test.js @@ -0,0 +1,137 @@ +const { describe, test } = require('node:test'); +const assert = require('node:assert/strict'); + +const { applyTargetingInput, hasTargetingClears, resolveTargetingInput } = require('../../dist/lib/index.js'); +const { createMediaBuyStore, InMemoryStateStore } = require('../../dist/lib/server/index.js'); + +const PROPERTY_LIST = { list_id: 'pl_1' }; +const COLLECTION_LIST = { list_id: 'cl_1' }; + +// AdCP 3.2 / DR-0020. `null` on a targeting dimension is a *command* — suppress +// a default on create, clear stored state on update — and never targeting state +// itself. Discovery criteria, accepted commercial snapshots, mutation responses, +// and package readback all use the strict overlay and MUST NOT contain null. +describe('request-only Targeting Input projection (DR-0020)', () => { + test('resolveTargetingInput drops clear commands and keeps replacements', () => { + assert.deepEqual( + resolveTargetingInput({ geo_countries: ['US'], audience_include: null, property_list: PROPERTY_LIST }), + { geo_countries: ['US'], property_list: PROPERTY_LIST } + ); + }); + + test('resolveTargetingInput yields undefined rather than an empty overlay', () => { + // A cleared dimension is *absent* from effective readback. Returning `{}` + // would put an empty object on the wire where the seller should simply + // omit targeting_overlay. + assert.equal(resolveTargetingInput({ geo_countries: null }), undefined); + assert.equal(resolveTargetingInput({}), undefined); + assert.equal(resolveTargetingInput(null), undefined); + assert.equal(resolveTargetingInput(undefined), undefined); + }); + + test('applyTargetingInput implements all three per-dimension states', () => { + const prior = { geo_countries: ['US'], property_list: PROPERTY_LIST, collection_list: COLLECTION_LIST }; + + // omitted → preserve; null → clear; value → replace. All in one patch. + assert.deepEqual(applyTargetingInput(prior, { property_list: null, geo_countries: ['CA'] }), { + geo_countries: ['CA'], + collection_list: COLLECTION_LIST, + }); + }); + + test('applyTargetingInput distinguishes an absent patch from a whole-overlay clear', () => { + const prior = { geo_countries: ['US'] }; + assert.deepEqual(applyTargetingInput(prior, undefined), prior, 'undefined leaves stored state untouched'); + assert.equal(applyTargetingInput(prior, null), undefined, 'null clears the whole overlay'); + }); + + test('applyTargetingInput never lets an explicit undefined erase a prior dimension', () => { + // JSON round-trips drop undefined, but an in-process caller can still spell + // it. Only `null` is the clear command; `undefined` means "not mentioned". + assert.deepEqual(applyTargetingInput({ geo_countries: ['US'] }, { geo_countries: undefined }), { + geo_countries: ['US'], + }); + }); + + test('hasTargetingClears reports whether a patch carries any command', () => { + assert.equal(hasTargetingClears({ geo_countries: ['US'] }), false); + assert.equal(hasTargetingClears({ geo_countries: null }), true); + assert.equal(hasTargetingClears(null), true); + assert.equal(hasTargetingClears(undefined), false); + }); +}); + +describe('createMediaBuyStore never persists a clear command', () => { + const setup = () => ({ store: createMediaBuyStore({ store: new InMemoryStateStore() }) }); + const readBack = (store, accountId = 'acct_a', packageIds = ['seller_pkg_001']) => + store.backfill(accountId, { + media_buys: [{ media_buy_id: 'mb_1', packages: packageIds.map(package_id => ({ package_id })) }], + }); + + test('persistFromCreate resolves request nulls away when the seller does not echo an overlay', async () => { + const { store } = setup(); + // No `targeting_overlay` on the response package, so the store falls back + // to the request — which is a Targeting *Input* and may carry commands. + await store.persistFromCreate( + 'acct_a', + { packages: [{ buyer_ref: 'pkg_a', targeting_overlay: { property_list: PROPERTY_LIST, geo_countries: null } }] }, + { media_buy_id: 'mb_1', packages: [{ package_id: 'seller_pkg_001', buyer_ref: 'pkg_a' }] } + ); + + const overlay = (await readBack(store)).media_buys[0].packages[0].targeting_overlay; + assert.deepEqual(overlay, { property_list: PROPERTY_LIST }); + assert.equal(hasTargetingClears(overlay), false, 'a clear command must not reach get_media_buys readback'); + }); + + test('persistFromCreate tracks nothing when every requested dimension is a clear', async () => { + const { store } = setup(); + await store.persistFromCreate( + 'acct_a', + { packages: [{ buyer_ref: 'pkg_a', targeting_overlay: { geo_countries: null } }] }, + { media_buy_id: 'mb_1', packages: [{ package_id: 'seller_pkg_001', buyer_ref: 'pkg_a' }] } + ); + + assert.equal((await readBack(store)).media_buys[0].packages[0].targeting_overlay, undefined); + }); + + test('mergeFromUpdate drops the tracked overlay once its last dimension is cleared', async () => { + const { store } = setup(); + await store.persistFromCreate( + 'acct_a', + { packages: [{ buyer_ref: 'pkg_a', targeting_overlay: { property_list: PROPERTY_LIST } }] }, + { media_buy_id: 'mb_1', packages: [{ package_id: 'seller_pkg_001', buyer_ref: 'pkg_a' }] } + ); + + await store.mergeFromUpdate('acct_a', 'mb_1', { + packages: [{ package_id: 'seller_pkg_001', targeting_overlay: { property_list: null } }], + }); + + // Not `{}` — an overlay with no surviving dimensions is omitted entirely. + assert.equal((await readBack(store)).media_buys[0].packages[0].targeting_overlay, undefined); + }); + + test('mergeFromUpdate new_packages resolves clears rather than persisting them', async () => { + const { store } = setup(); + await store.persistFromCreate( + 'acct_a', + { packages: [{ buyer_ref: 'pkg_a', targeting_overlay: { property_list: PROPERTY_LIST } }] }, + { media_buy_id: 'mb_1', packages: [{ package_id: 'seller_pkg_001', buyer_ref: 'pkg_a' }] } + ); + + await store.mergeFromUpdate('acct_a', 'mb_1', { + new_packages: [ + { + package_id: 'seller_pkg_002', + buyer_ref: 'pkg_b', + // A brand-new package has no stored state, so `null` here suppresses a + // product default. Either way it must not become durable state. + targeting_overlay: { collection_list: COLLECTION_LIST, geo_countries: null }, + }, + ], + }); + + const packages = (await readBack(store, 'acct_a', ['seller_pkg_001', 'seller_pkg_002'])).media_buys[0].packages; + assert.deepEqual(packages[1].targeting_overlay, { collection_list: COLLECTION_LIST }); + assert.equal(hasTargetingClears(packages[1].targeting_overlay), false); + }); +}); From c9dbdcd6bd145e168c1e6cb9acf129c0f3a29d88 Mon Sep 17 00:00:00 2001 From: Brian O'Kelley Date: Mon, 14 Sep 2026 16:22:20 +0000 Subject: [PATCH 3/3] fix(media-buy): harden the Targeting Input projection against wire keys MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two defects the review stack converged on — flagged independently by all three codex personas, the code reviewer, and the security reviewer. **Prototype swap via a wire-supplied `__proto__`.** `targeting_overlay` comes off `JSON.parse`, which produces a real *own* `__proto__` key that `Object.entries` yields. Assigning it with `=` invoked the inherited setter instead of creating an own property, swapping the accumulator's prototype. Reproduced against the built package before the fix: resolveTargetingInput(JSON.parse('{"__proto__":{"geo_regions":["INJECTED"]},"geo_countries":["US"]}')) Object.keys(result) -> ['geo_countries'] result.geo_regions -> ['INJECTED'] Global `Object.prototype` was never touched, but that is not the interesting part: an own-key validator and a dot-access enforcement path disagree about the same object, and the attacker-chosen dimension is invisible to `Object.keys` and `JSON.stringify` while still reading back off the overlay the seller persists and echoes. A payload whose only key is `__proto__` also resolved to `undefined`, which made the store silently drop the package's stored overlay. The accumulator is now null-prototype, `__proto__` / `constructor` / `prototype` are dropped outright so a later spread cannot reintroduce the problem, and the result is rehydrated as an ordinary object so adopters see normal behaviour. `hasTargetingClears` filters the same key set, because otherwise the two functions disagreed about whether `{"__proto__": null}` is a clear command. **Stale slice offsets in `alignTargetingInputArrayCardinality`.** The block offsets were computed once from the pre-edit string, then the string was rewritten inside the loop. Every repair grows it by two characters, so the replacement window progressively under-covers the tail of the block: a declaration past the truncated boundary is never found, `.replace()` no-ops, and `corrections.push()` still reports success. Today's pin needs two repairs and both sit well before the block end, so the committed output happens to be correct — latent, not manifesting, until an rc bump adds a third nullable array dimension or moves one to the end. The block is now repaired in isolation and spliced back once, and a replacement that fails to land throws instead of being logged as applied. Silently reporting a correction that did not happen is exactly the failure this function exists to prevent. Both are covered: 6 codegen cases including the four-repair shape that exposes the offset bug (verified failing against the previous implementation), and 2 prototype cases driving real `JSON.parse` output. Co-Authored-By: Claude Opus 5 (1M context) --- scripts/generate-types.ts | 27 ++-- src/lib/media-buy/targeting-input.ts | 30 +++- ...argeting-input-cardinality-codegen.test.js | 130 ++++++++++++++++++ test/lib/targeting-input-null-clear.test.js | 27 ++++ 4 files changed, 200 insertions(+), 14 deletions(-) create mode 100644 test/lib/targeting-input-cardinality-codegen.test.js diff --git a/scripts/generate-types.ts b/scripts/generate-types.ts index 754fd5759..9d468988d 100644 --- a/scripts/generate-types.ts +++ b/scripts/generate-types.ts @@ -3490,8 +3490,13 @@ export function alignTargetingInputArrayCardinality(typeDefinitions: string): st const input = generatedObjectTypeProperties(typeDefinitions, 'TargetingOverlayInput'); if (!overlay || !input) return typeDefinitions; + // Repair the extracted block in isolation, then splice it back exactly once. + // Rewriting `result` inside the loop would invalidate the `start`/`end` + // offsets on every correction that changes length, so a later property could + // silently fall outside the replacement window and stay broken while still + // being reported as fixed. const corrections: string[] = []; - let result = typeDefinitions; + let block = typeDefinitions.slice(input.start, input.end); for (const [name, inputProperty] of input.properties) { const overlayProperty = overlay.properties.get(name); if (!overlayProperty) continue; @@ -3503,19 +3508,19 @@ export function alignTargetingInputArrayCardinality(typeDefinitions: string): st `${name}?: ${inputProperty.type};`, `${name}?: ${overlayProperty.type} | null;` ); - result = - result.slice(0, input.start) + - result.slice(input.start, input.end).replace(inputProperty.declaration, repaired) + - result.slice(input.end); + const next = block.replace(inputProperty.declaration, repaired); + if (next === block) { + // Never report a correction that did not land: a silent no-op here is + // exactly the failure this function exists to prevent. + throw new Error(`alignTargetingInputArrayCardinality: could not repair TargetingOverlayInput.${name}`); + } + block = next; corrections.push(`${name}: ${nullStripped} -> ${overlayProperty.type}`); } - if (corrections.length > 0) { - console.log( - `🎯 Restored ${corrections.length} TargetingOverlayInput array dimension(s): ${corrections.join(', ')}` - ); - } - return result; + if (corrections.length === 0) return typeDefinitions; + console.log(`🎯 Restored ${corrections.length} TargetingOverlayInput array dimension(s): ${corrections.join(', ')}`); + return typeDefinitions.slice(0, input.start) + block + typeDefinitions.slice(input.end); } export function renameKnownNumberedSemanticTypes(typeDefinitions: string): string { diff --git a/src/lib/media-buy/targeting-input.ts b/src/lib/media-buy/targeting-input.ts index 6b9028339..22031efca 100644 --- a/src/lib/media-buy/targeting-input.ts +++ b/src/lib/media-buy/targeting-input.ts @@ -29,6 +29,20 @@ * rather than silently retaining the default. */ +/** + * Keys that must never be copied off a wire-supplied overlay. + * + * `targeting_overlay` arrives from `JSON.parse`, which happily produces an own + * `__proto__` key. Assigning that key with `=` invokes the inherited setter + * instead of creating an own property, which swaps the accumulator's prototype + * and makes attacker-chosen targeting dimensions readable on the result while + * staying invisible to `Object.keys`. The accumulator below is null-prototype, + * which already defuses the setter, but these keys are dropped outright so a + * later consumer that spreads the result into an ordinary object cannot + * reintroduce the problem. + */ +const UNSAFE_OVERLAY_KEYS = new Set(['__proto__', 'constructor', 'prototype']); + /** * Strict effective overlay derived from a request-only Targeting Input: the * same dimensions, with the `null` clear command removed from each. @@ -118,19 +132,29 @@ export function applyTargetingInput( export function hasTargetingClears(input: object | null | undefined): boolean { if (input === null) return true; if (!input) return false; - return Object.values(input).some(value => value === null); + // Mirror compactOverlay's key filter. A `{"__proto__": null}` payload is not + // a targeting clear — the projection drops that key entirely — so counting it + // here would make the two functions disagree about the same input. + return Object.entries(input).some(([key, value]) => value === null && !UNSAFE_OVERLAY_KEYS.has(key)); } /** * Fold ordered `[key, value]` pairs into a strict overlay. Later pairs win, a * `null` value deletes the key outright, and `undefined` is treated as "not * mentioned" so an explicitly-undefined patch key cannot erase a prior value. + * + * The result is a plain object (not null-prototype) so it behaves normally for + * adopters, but it is assembled on a null-prototype accumulator so no wire key + * can reach a setter on `Object.prototype` on the way in. */ function compactOverlay(entries: Array<[string, unknown]>): T | undefined { - const merged: Record = {}; + const merged = Object.create(null) as Record; for (const [key, value] of entries) { + if (UNSAFE_OVERLAY_KEYS.has(key)) continue; if (value === null) delete merged[key]; else if (value !== undefined) merged[key] = value; } - return Object.keys(merged).length > 0 ? (merged as T) : undefined; + const keys = Object.keys(merged); + if (keys.length === 0) return undefined; + return Object.fromEntries(keys.map(key => [key, merged[key]])) as T; } diff --git a/test/lib/targeting-input-cardinality-codegen.test.js b/test/lib/targeting-input-cardinality-codegen.test.js new file mode 100644 index 000000000..9356d9622 --- /dev/null +++ b/test/lib/targeting-input-cardinality-codegen.test.js @@ -0,0 +1,130 @@ +const { describe, test, before } = require('node:test'); +const assert = require('node:assert/strict'); +const { spawnSync } = require('node:child_process'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); + +const ROOT = path.resolve(__dirname, '../..'); +const GENERATOR = path.join(ROOT, 'scripts/generate-types.ts'); + +// `core/targeting-input.json` reaches each dimension through a JSON-pointer $ref +// into `core/targeting.json#/properties/`. Where that array has no +// `title` of its own, json-schema-to-typescript names the result after the +// items' canonical $ref, so the Input side declares the scalar enum where the +// wire carries an array. `alignTargetingInputArrayCardinality` repairs that from +// the invariant the two schemas satisfy: identical property sets, so Input is +// Overlay plus `| null` per dimension. +// +// The generator is TypeScript, so the cases run through one `tsx` harness — +// the same pattern test/generate-zod-*.test.js uses. +function unit({ overlay, input }) { + const render = (name, properties) => + `export type ${name} = SomeConstraint &\n OtherConstraint & {\n` + + properties.map(([property, type]) => ` /** doc for ${property} */\n ${property}?: ${type};`).join('\n') + + '\n };\n'; + return `${render('TargetingOverlay', overlay)}\n${render('TargetingOverlayInput', input)}`; +} + +const ITEMS = { + geo_countries: 'GeoCountry', + device_platform: 'DevicePlatform', + device_type: 'DeviceType', + browser: 'BrowserFamily', +}; +const arrayOf = name => `[${ITEMS[name]}, ...${ITEMS[name]}[]]`; +const FOUR = Object.keys(ITEMS); + +const CASES = { + single: unit({ + overlay: [['device_platform', arrayOf('device_platform')]], + input: [['device_platform', 'DevicePlatform | null']], + }), + // The original implementation computed the block offsets once and then mutated + // the string inside the loop, so each repair shifted the window and a later + // declaration could fall outside it — silently unrepaired while still being + // logged as fixed. Four repairs with the last property affected exposes it. + four: unit({ + overlay: FOUR.map(name => [name, arrayOf(name)]), + input: FOUR.map(name => [name, `${ITEMS[name]} | null`]), + }), + correctAlias: unit({ + overlay: [['device_platform_exclude', arrayOf('device_platform')]], + input: [['device_platform_exclude', 'DevicePlatformExclude | null']], + }), + scalarDimension: unit({ + overlay: [['axe_include_segment', 'string']], + input: [['axe_include_segment', 'string | null']], + }), + overlayOnly: 'export type TargetingOverlay = A &\n B & {\n x?: [Y, ...Y[]];\n };\n', + empty: '', +}; + +let output; + +before(() => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), '.targeting-cardinality-')); + const inputPath = path.join(directory, 'cases.json'); + const outputPath = path.join(directory, 'out.json'); + const harnessPath = path.join(directory, 'harness.ts'); + fs.writeFileSync(inputPath, JSON.stringify(CASES)); + fs.writeFileSync( + harnessPath, + ` +import { readFileSync, writeFileSync } from 'node:fs'; +import { alignTargetingInputArrayCardinality } from ${JSON.stringify(GENERATOR)}; +const cases = JSON.parse(readFileSync(${JSON.stringify(inputPath)}, 'utf8')); +writeFileSync(${JSON.stringify(outputPath)}, JSON.stringify( + Object.fromEntries(Object.entries(cases).map(([id, source]) => [id, alignTargetingInputArrayCardinality(source as string)])) +)); +` + ); + try { + const result = spawnSync('npx', ['tsx', harnessPath], { cwd: ROOT, encoding: 'utf8' }); + assert.equal(result.status, 0, `cardinality harness failed:\n${result.stderr}\n${result.stdout}`); + output = JSON.parse(fs.readFileSync(outputPath, 'utf8')); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +}); + +const declared = (source, name, property) => + new RegExp(`export type ${name} =[\\s\\S]*?\\n ${property}\\?: ([^;]+);`).exec(source)?.[1]; + +describe('alignTargetingInputArrayCardinality', () => { + test('repairs a dimension collapsed to its array item type', () => { + assert.equal( + declared(output.single, 'TargetingOverlayInput', 'device_platform'), + '[DevicePlatform, ...DevicePlatform[]] | null' + ); + }); + + test('repairs every collapsed dimension, including the last one in the block', () => { + for (const name of FOUR) { + assert.equal( + declared(output.four, 'TargetingOverlayInput', name), + `${arrayOf(name)} | null`, + `${name} must be repaired` + ); + } + }); + + test('leaves a correct array alias untouched', () => { + // The Input side is an alias, not the item type, so there is nothing to + // prove wrong — rewriting it would replace a clean name with an inline tuple. + assert.equal(output.correctAlias, CASES.correctAlias); + }); + + test('leaves a non-array dimension untouched', () => { + assert.equal(output.scalarDimension, CASES.scalarDimension); + }); + + test('preserves the per-property JSDoc it repairs around', () => { + assert.equal((output.single.match(/\/\*\* doc for device_platform \*\//g) ?? []).length, 2); + }); + + test('is a no-op when either type is absent from the unit', () => { + assert.equal(output.overlayOnly, CASES.overlayOnly); + assert.equal(output.empty, CASES.empty); + }); +}); diff --git a/test/lib/targeting-input-null-clear.test.js b/test/lib/targeting-input-null-clear.test.js index 27f86a30e..dbbdbdc6e 100644 --- a/test/lib/targeting-input-null-clear.test.js +++ b/test/lib/targeting-input-null-clear.test.js @@ -53,6 +53,33 @@ describe('request-only Targeting Input projection (DR-0020)', () => { }); }); + test('a wire-supplied __proto__ key cannot inject inherited targeting', () => { + // `targeting_overlay` comes off JSON.parse, which produces a real own + // `__proto__` key. Assigning it with `=` would invoke the inherited setter, + // swapping the result's prototype so an attacker-chosen dimension reads + // back on the overlay while staying invisible to Object.keys — and then + // gets persisted and echoed. + const hostile = JSON.parse('{"__proto__": {"geo_regions": ["INJECTED"]}, "geo_countries": ["US"]}'); + + const resolved = resolveTargetingInput(hostile); + assert.deepEqual(Object.keys(resolved), ['geo_countries']); + assert.equal(resolved.geo_regions, undefined, 'no dimension may arrive through the prototype'); + assert.equal(Object.getPrototypeOf(resolved), Object.prototype); + + const applied = applyTargetingInput({ geo_countries: ['CA'] }, hostile); + assert.equal(applied.geo_regions, undefined); + assert.equal(Object.getPrototypeOf(applied), Object.prototype); + // The global must be untouched either way. + assert.equal({}.geo_regions, undefined); + }); + + test('constructor and prototype keys are dropped rather than copied', () => { + const resolved = resolveTargetingInput( + JSON.parse('{"constructor": "x", "prototype": "y", "geo_countries": ["US"]}') + ); + assert.deepEqual(Object.keys(resolved), ['geo_countries']); + }); + test('hasTargetingClears reports whether a patch carries any command', () => { assert.equal(hasTargetingClears({ geo_countries: ['US'] }), false); assert.equal(hasTargetingClears({ geo_countries: null }), true);