{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "/schemas/3.0.18/core/protocol-envelope.json",
  "title": "Protocol Envelope",
  "description": "Standard envelope structure for AdCP task responses. This envelope is added by the protocol layer (MCP, A2A, REST) and wraps the task-specific response payload. Task response schemas should NOT include these fields - they are protocol-level concerns.",
  "type": "object",
  "properties": {
    "context_id": {
      "type": "string",
      "description": "Session/conversation identifier for tracking related operations across multiple task invocations. Managed by the protocol layer to maintain conversational context."
    },
    "task_id": {
      "type": "string",
      "description": "Unique identifier for tracking asynchronous operations. Present when a task requires extended processing time. Used to query task status and retrieve results when complete.",
      "x-entity": "task"
    },
    "status": {
      "$ref": "/schemas/3.0.18/enums/task-status.json",
      "description": "Current task execution state. Indicates whether the task is completed, in progress (working), submitted for async processing, failed, or requires user input. Managed by the protocol layer. Agents MUST NOT emit the legacy task_status or response_status fields alongside this field — the status field is the single authoritative task state."
    },
    "message": {
      "type": "string",
      "description": "Human-readable summary of the task result. Provides natural language explanation of what happened, suitable for display to end users or for AI agent comprehension. Generated by the protocol layer based on the task response."
    },
    "timestamp": {
      "type": "string",
      "format": "date-time",
      "description": "ISO 8601 timestamp when the response was generated. Useful for debugging, logging, cache validation, and tracking async operation progress."
    },
    "replayed": {
      "type": "boolean",
      "description": "Set to true when this response is a cached replay returned for an idempotency_key that was already processed. Set to false (or omitted) when the request was executed fresh. Buyers use this to distinguish cached replays from new executions — matters for billing reconciliation, audit logs, and any downstream system that assumes exactly-once event semantics. Only present on responses to mutating requests that carry idempotency_key.",
      "default": false
    },
    "push_notification_config": {
      "$ref": "/schemas/3.0.18/core/push-notification-config.json",
      "description": "Push notification configuration for async task updates (A2A and REST protocols). Echoed from the request to confirm webhook settings. Specifies URL, authentication scheme (Bearer or HMAC-SHA256), and credentials. MCP uses progress notifications instead of webhooks."
    },
    "governance_context": {
      "type": "string",
      "description": "Governance context token issued by a governance agent during check_governance. Buyers attach it to governed purchase requests (media buys, rights acquisitions, signal activations, creative services); sellers persist it and include it on all subsequent governance calls for that action's lifecycle.\n\nValue format: in 3.0 governance agents MUST emit a compact JWS per the AdCP JWS profile (see Security — Signed Governance Context). Sellers MAY verify; sellers that do not verify MUST persist and forward the token unchanged. In 3.1 all sellers MUST verify. Non-JWS values from pre-3.0 governance agents are deprecated.\n\nThis is the primary correlation key for audit and reporting across the governance lifecycle.",
      "minLength": 1,
      "maxLength": 4096,
      "pattern": "^[\\x20-\\x7E]+$"
    },
    "payload": {
      "type": "object",
      "description": "The actual task-specific response data. This is the content defined in individual task response schemas (e.g., get-products-response.json, create-media-buy-response.json). Contains only domain-specific data without protocol-level fields.",
      "additionalProperties": true
    }
  },
  "required": [
    "status",
    "payload"
  ],
  "additionalProperties": true,
  "not": {
    "anyOf": [
      { "required": ["task_status"] },
      { "required": ["response_status"] }
    ]
  },
  "examples": [
    {
      "description": "Synchronous task response with immediate results",
      "data": {
        "context_id": "ctx_abc123",
        "status": "completed",
        "message": "Found 3 products matching your criteria for CTV inventory in California",
        "timestamp": "2025-10-14T14:25:30Z",
        "payload": {
          "products": [
            {
              "product_id": "ctv_premium_ca",
              "name": "CTV Premium - California",
              "description": "Premium connected TV inventory across California",
              "pricing": {
                "model": "cpm",
                "amount": 45.0,
                "currency": "USD"
              }
            }
          ]
        }
      }
    },
    {
      "description": "Asynchronous task response with pending operation",
      "data": {
        "context_id": "ctx_def456",
        "task_id": "task_789",
        "status": "submitted",
        "message": "Media buy creation submitted. Processing will take approximately 5-10 minutes. You'll receive updates via webhook.",
        "timestamp": "2025-10-14T14:30:00Z",
        "push_notification_config": {
          "url": "https://buyer.example.com/webhooks/adcp",
          "authentication": {
            "schemes": [
              "HMAC-SHA256"
            ],
            "credentials": "shared_secret_exchanged_during_onboarding_min_32_chars"
          }
        },
        "payload": {
          "account": { "account_id": "acct_123" }
        }
      }
    },
    {
      "description": "Task response requiring user input",
      "data": {
        "context_id": "ctx_ghi789",
        "task_id": "task_101",
        "status": "input-required",
        "message": "This media buy requires manual approval. Please review the terms and confirm to proceed.",
        "timestamp": "2025-10-14T14:32:15Z",
        "payload": {
          "media_buy_id": "mb_123456",
          "packages": [
            {
              "package_id": "pkg_001"
            }
          ],
          "errors": [
            {
              "code": "APPROVAL_REQUIRED",
              "message": "Budget exceeds auto-approval threshold",
              "severity": "warning"
            }
          ]
        }
      }
    },
    {
      "description": "Idempotent replay — same key and payload as a prior request within the replay window",
      "data": {
        "context_id": "ctx_abc123",
        "status": "completed",
        "message": "Returning cached response for idempotency_key (already processed)",
        "timestamp": "2025-10-14T14:35:00Z",
        "replayed": true,
        "payload": {
          "media_buy_id": "mb_01HW7J8K9P0Q1R2S3T4U5V6W7X"
        }
      }
    },
    {
      "description": "Failed task response with error details",
      "data": {
        "context_id": "ctx_jkl012",
        "status": "failed",
        "message": "Unable to create media buy due to invalid targeting parameters",
        "timestamp": "2025-10-14T14:28:45Z",
        "payload": {
          "errors": [
            {
              "code": "INVALID_TARGETING",
              "message": "Geographic targeting codes are invalid",
              "field": "targeting.geo_countries",
              "severity": "error"
            }
          ]
        }
      }
    }
  ],
  "notes": [
    "Task response schemas (e.g., get-products-response.json) define ONLY the payload structure",
    "Protocol implementations (MCP, A2A, REST) wrap the payload with this envelope",
    "Different protocols may use different serialization formats but maintain the same semantic structure",
    "MCP may represent this via tool response content fields and metadata",
    "A2A may represent this via assistant messages with structured data",
    "REST may use HTTP headers for status/task metadata and JSON body for payload",
    "The envelope ensures consistent behavior across all protocol implementations"
  ]
}
