@adcp/sdk 14.0.0-beta.12 → 14.0.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/dist/lib/index.d.mts +3 -3
  2. package/dist/lib/index.d.ts +3 -3
  3. package/dist/lib/index.d.ts.map +1 -1
  4. package/dist/lib/index.js +2 -0
  5. package/dist/lib/index.js.map +1 -1
  6. package/dist/lib/index.mjs +3 -1
  7. package/dist/lib/index.mjs.map +1 -1
  8. package/dist/lib/schemas-data/v2.5/_provenance.json +1 -1
  9. package/dist/lib/server/create-adcp-server.d.mts +2 -2
  10. package/dist/lib/server/create-adcp-server.d.ts +2 -2
  11. package/dist/lib/server/create-adcp-server.d.ts.map +1 -1
  12. package/dist/lib/server/create-adcp-server.js +6 -1
  13. package/dist/lib/server/create-adcp-server.js.map +1 -1
  14. package/dist/lib/server/create-adcp-server.mjs +6 -1
  15. package/dist/lib/server/create-adcp-server.mjs.map +1 -1
  16. package/dist/lib/server/decisioning/index.d.mts +3 -3
  17. package/dist/lib/server/decisioning/index.d.ts +3 -3
  18. package/dist/lib/server/decisioning/index.d.ts.map +1 -1
  19. package/dist/lib/server/decisioning/index.js.map +1 -1
  20. package/dist/lib/server/decisioning/index.mjs.map +1 -1
  21. package/dist/lib/server/decisioning/runtime/from-platform.d.mts +24 -17
  22. package/dist/lib/server/decisioning/runtime/from-platform.d.ts +24 -17
  23. package/dist/lib/server/decisioning/runtime/from-platform.d.ts.map +1 -1
  24. package/dist/lib/server/decisioning/runtime/from-platform.js +71 -42
  25. package/dist/lib/server/decisioning/runtime/from-platform.js.map +1 -1
  26. package/dist/lib/server/decisioning/runtime/from-platform.mjs +75 -43
  27. package/dist/lib/server/decisioning/runtime/from-platform.mjs.map +1 -1
  28. package/dist/lib/server/decisioning/runtime/postgres-task-registry.d.mts +15 -21
  29. package/dist/lib/server/decisioning/runtime/postgres-task-registry.d.ts +15 -21
  30. package/dist/lib/server/decisioning/runtime/postgres-task-registry.d.ts.map +1 -1
  31. package/dist/lib/server/decisioning/runtime/postgres-task-registry.js +100 -30
  32. package/dist/lib/server/decisioning/runtime/postgres-task-registry.js.map +1 -1
  33. package/dist/lib/server/decisioning/runtime/postgres-task-registry.mjs +100 -30
  34. package/dist/lib/server/decisioning/runtime/postgres-task-registry.mjs.map +1 -1
  35. package/dist/lib/server/decisioning/runtime/task-registry.d.mts +30 -16
  36. package/dist/lib/server/decisioning/runtime/task-registry.d.ts +30 -16
  37. package/dist/lib/server/decisioning/runtime/task-registry.d.ts.map +1 -1
  38. package/dist/lib/server/decisioning/runtime/task-registry.js +40 -20
  39. package/dist/lib/server/decisioning/runtime/task-registry.js.map +1 -1
  40. package/dist/lib/server/decisioning/runtime/task-registry.mjs +38 -19
  41. package/dist/lib/server/decisioning/runtime/task-registry.mjs.map +1 -1
  42. package/dist/lib/server/decisioning/runtime/to-context.d.mts +2 -2
  43. package/dist/lib/server/decisioning/runtime/to-context.d.ts +2 -2
  44. package/dist/lib/server/decisioning/runtime/to-context.d.ts.map +1 -1
  45. package/dist/lib/server/decisioning/runtime/to-context.js +2 -2
  46. package/dist/lib/server/decisioning/runtime/to-context.js.map +1 -1
  47. package/dist/lib/server/decisioning/runtime/to-context.mjs +2 -2
  48. package/dist/lib/server/decisioning/runtime/to-context.mjs.map +1 -1
  49. package/dist/lib/server/decisioning/specialisms/creative-ad-server.d.mts +3 -2
  50. package/dist/lib/server/decisioning/specialisms/creative-ad-server.d.ts +3 -2
  51. package/dist/lib/server/decisioning/specialisms/creative-ad-server.d.ts.map +1 -1
  52. package/dist/lib/server/decisioning/specialisms/creative-ad-server.js.map +1 -1
  53. package/dist/lib/server/decisioning/specialisms/creative.d.mts +10 -10
  54. package/dist/lib/server/decisioning/specialisms/creative.d.ts +10 -10
  55. package/dist/lib/server/decisioning/specialisms/creative.d.ts.map +1 -1
  56. package/dist/lib/server/decisioning/specialisms/creative.js.map +1 -1
  57. package/dist/lib/server/index.d.mts +1 -1
  58. package/dist/lib/server/index.d.ts +1 -1
  59. package/dist/lib/server/index.d.ts.map +1 -1
  60. package/dist/lib/server/index.js.map +1 -1
  61. package/dist/lib/server/index.mjs.map +1 -1
  62. package/dist/lib/testing/storyboard/default-invariants.d.ts.map +1 -1
  63. package/dist/lib/testing/storyboard/default-invariants.js +11 -2
  64. package/dist/lib/testing/storyboard/default-invariants.js.map +1 -1
  65. package/dist/lib/testing/storyboard/default-invariants.mjs +11 -2
  66. package/dist/lib/testing/storyboard/default-invariants.mjs.map +1 -1
  67. package/dist/lib/testing/storyboard/index.d.mts +1 -1
  68. package/dist/lib/testing/storyboard/index.d.ts +1 -1
  69. package/dist/lib/testing/storyboard/index.d.ts.map +1 -1
  70. package/dist/lib/testing/storyboard/index.js.map +1 -1
  71. package/dist/lib/testing/storyboard/index.mjs.map +1 -1
  72. package/dist/lib/testing/storyboard/loader.d.ts.map +1 -1
  73. package/dist/lib/testing/storyboard/loader.js +14 -0
  74. package/dist/lib/testing/storyboard/loader.js.map +1 -1
  75. package/dist/lib/testing/storyboard/loader.mjs +14 -0
  76. package/dist/lib/testing/storyboard/loader.mjs.map +1 -1
  77. package/dist/lib/testing/storyboard/phase-condition.d.mts +41 -0
  78. package/dist/lib/testing/storyboard/phase-condition.d.ts +42 -0
  79. package/dist/lib/testing/storyboard/phase-condition.d.ts.map +1 -0
  80. package/dist/lib/testing/storyboard/phase-condition.js +215 -0
  81. package/dist/lib/testing/storyboard/phase-condition.js.map +1 -0
  82. package/dist/lib/testing/storyboard/phase-condition.mjs +189 -0
  83. package/dist/lib/testing/storyboard/phase-condition.mjs.map +1 -0
  84. package/dist/lib/testing/storyboard/request-builder.d.ts.map +1 -1
  85. package/dist/lib/testing/storyboard/request-builder.js +15 -2
  86. package/dist/lib/testing/storyboard/request-builder.js.map +1 -1
  87. package/dist/lib/testing/storyboard/request-builder.mjs +15 -2
  88. package/dist/lib/testing/storyboard/request-builder.mjs.map +1 -1
  89. package/dist/lib/testing/storyboard/runner.d.ts.map +1 -1
  90. package/dist/lib/testing/storyboard/runner.js +57 -23
  91. package/dist/lib/testing/storyboard/runner.js.map +1 -1
  92. package/dist/lib/testing/storyboard/runner.mjs +57 -23
  93. package/dist/lib/testing/storyboard/runner.mjs.map +1 -1
  94. package/dist/lib/testing/storyboard/task-map.d.ts.map +1 -1
  95. package/dist/lib/testing/storyboard/task-map.js +6 -2
  96. package/dist/lib/testing/storyboard/task-map.js.map +1 -1
  97. package/dist/lib/testing/storyboard/task-map.mjs +6 -2
  98. package/dist/lib/testing/storyboard/task-map.mjs.map +1 -1
  99. package/dist/lib/testing/storyboard/types.d.mts +5 -4
  100. package/dist/lib/testing/storyboard/types.d.ts +5 -4
  101. package/dist/lib/testing/storyboard/types.d.ts.map +1 -1
  102. package/dist/lib/testing/storyboard/types.js.map +1 -1
  103. package/dist/lib/testing/storyboard/types.mjs.map +1 -1
  104. package/dist/lib/testing/storyboard/validations.d.mts +1 -1
  105. package/dist/lib/testing/storyboard/validations.d.ts +1 -1
  106. package/dist/lib/testing/storyboard/webhook-assertions.d.ts.map +1 -1
  107. package/dist/lib/testing/storyboard/webhook-assertions.js +60 -4
  108. package/dist/lib/testing/storyboard/webhook-assertions.js.map +1 -1
  109. package/dist/lib/testing/storyboard/webhook-assertions.mjs +60 -4
  110. package/dist/lib/testing/storyboard/webhook-assertions.mjs.map +1 -1
  111. package/dist/lib/testing/storyboard/webhook-receiver.d.mts +15 -0
  112. package/dist/lib/testing/storyboard/webhook-receiver.d.ts +15 -0
  113. package/dist/lib/testing/storyboard/webhook-receiver.d.ts.map +1 -1
  114. package/dist/lib/testing/storyboard/webhook-receiver.js +57 -6
  115. package/dist/lib/testing/storyboard/webhook-receiver.js.map +1 -1
  116. package/dist/lib/testing/storyboard/webhook-receiver.mjs +57 -6
  117. package/dist/lib/testing/storyboard/webhook-receiver.mjs.map +1 -1
  118. package/dist/lib/testing/types.d.mts +2 -0
  119. package/dist/lib/testing/types.d.ts +2 -0
  120. package/dist/lib/testing/types.d.ts.map +1 -1
  121. package/dist/lib/testing/types.js.map +1 -1
  122. package/dist/lib/types/core.generated.d.mts +5 -2
  123. package/dist/lib/types/core.generated.d.ts +5 -2
  124. package/dist/lib/types/core.generated.d.ts.map +1 -1
  125. package/dist/lib/types/core.generated.js.map +1 -1
  126. package/dist/lib/types/index.d.mts +1 -1
  127. package/dist/lib/types/index.d.ts +1 -1
  128. package/dist/lib/types/index.d.ts.map +1 -1
  129. package/dist/lib/types/index.js.map +1 -1
  130. package/dist/lib/types/index.mjs.map +1 -1
  131. package/dist/lib/types/list-transformers.d.ts +9 -5
  132. package/dist/lib/types/schemas.generated.d.ts +21 -298
  133. package/dist/lib/types/schemas.generated.d.ts.map +1 -1
  134. package/dist/lib/types/schemas.generated.js +5 -2
  135. package/dist/lib/types/schemas.generated.js.map +1 -1
  136. package/dist/lib/types/schemas.generated.mjs +4 -2
  137. package/dist/lib/types/schemas.generated.mjs.map +1 -1
  138. package/dist/lib/types/server-payload-aliases.d.mts +2 -1
  139. package/dist/lib/types/server-payload-aliases.d.ts +2 -1
  140. package/dist/lib/types/server-payload-aliases.d.ts.map +1 -1
  141. package/dist/lib/types/server-payload-aliases.js.map +1 -1
  142. package/dist/lib/types/tools.generated.d.mts +5 -2
  143. package/dist/lib/types/tools.generated.d.ts +5 -2
  144. package/dist/lib/types/tools.generated.d.ts.map +1 -1
  145. package/dist/lib/types/tools.generated.js.map +1 -1
  146. package/dist/lib/utils/build-creative-return-builders.d.mts +5 -1
  147. package/dist/lib/utils/build-creative-return-builders.d.ts +5 -1
  148. package/dist/lib/utils/build-creative-return-builders.d.ts.map +1 -1
  149. package/dist/lib/utils/build-creative-return-builders.js +9 -3
  150. package/dist/lib/utils/build-creative-return-builders.js.map +1 -1
  151. package/dist/lib/utils/build-creative-return-builders.mjs +7 -2
  152. package/dist/lib/utils/build-creative-return-builders.mjs.map +1 -1
  153. package/dist/lib/utils/response-unwrapper.js +1 -1
  154. package/dist/lib/utils/response-unwrapper.js.map +1 -1
  155. package/dist/lib/utils/response-unwrapper.mjs +1 -1
  156. package/dist/lib/utils/response-unwrapper.mjs.map +1 -1
  157. package/dist/lib/validation/schema-loader.d.ts.map +1 -1
  158. package/dist/lib/validation/schema-loader.js +16 -7
  159. package/dist/lib/validation/schema-loader.js.map +1 -1
  160. package/dist/lib/validation/schema-loader.mjs +16 -7
  161. package/dist/lib/validation/schema-loader.mjs.map +1 -1
  162. package/dist/lib/version.d.mts +3 -3
  163. package/dist/lib/version.d.ts +3 -3
  164. package/dist/lib/version.js +3 -3
  165. package/dist/lib/version.js.map +1 -1
  166. package/dist/lib/version.mjs +3 -3
  167. package/dist/lib/version.mjs.map +1 -1
  168. package/docs/llms.txt +2 -2
  169. package/docs/migration-5.x-to-6.x.md +3 -2
  170. package/docs/migration-task-registry-scoping.md +61 -0
  171. package/examples/hello_seller_adapter_guaranteed.ts +1 -1
  172. package/package.json +4 -4
  173. package/skills/build-decisioning-creative-template/SKILL.md +2 -2
  174. package/skills/build-decisioning-platform/SKILL.md +4 -2
  175. package/skills/build-decisioning-platform/advanced/REFERENCE.md +7 -6
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/utils/response-unwrapper.ts"],"sourcesContent":["/**\n * Response Unwrapper\n *\n * Extracts raw AdCP responses from protocol wrappers (MCP/A2A).\n * Follows canonical A2A response format per AdCP specification.\n */\n\nimport { z } from 'zod';\nimport { getBestUnionErrors } from './union-errors';\n\n/**\n * Standard error codes for response unwrapping\n */\nconst ERROR_CODES = {\n MCP_ERROR: 'mcp_error',\n INVALID_RESPONSE: 'invalid_response',\n UNKNOWN: 'unknown',\n} as const;\n\nimport type {\n GetProductsResponse,\n ListCreativeFormatsResponse,\n CreateMediaBuyResponse,\n SyncCreativesResponse,\n ListCreativesResponse,\n UpdateMediaBuyResponse,\n GetMediaBuysResponse,\n GetMediaBuyDeliveryResponse,\n ProvidePerformanceFeedbackResponse,\n BuildCreativeResponse,\n PreviewCreativeResponse,\n GetSignalsResponse,\n ActivateSignalResponse,\n} from '../types/tools.generated';\nimport { prepareResponseForSchemaValidation, TOOL_RESPONSE_SCHEMAS } from './response-schemas';\nimport { injectLegacyEnvelopeStatus, normalizeLegacyMediaBuyStatusForReturn } from './envelope-status-compat';\nimport { getLatestA2ADataPartFromResponse } from './a2a-artifacts';\n\n/**\n * Typed error thrown when the response unwrapper's Zod schema rejects an\n * agent response. Carries the structured rejection detail so the storyboard\n * runner can attribute the failure to its canonical `response_schema`\n * validation entry instead of silently falling through to whichever\n * step-level invariant fires next (e.g., `context.no_secret_echo`).\n *\n * Without this typed boundary, the runner can only catch a generic `Error`\n * with a freeform message — there's no stable way to distinguish a\n * schema rejection from a transport error or any other failure. The\n * misattribution this caused (every BidMachine `sync_accounts` failure\n * surfaced as `no_secret_echo`, masking the root cause across 10+ deploys)\n * is the canonical evidence for adcp-client#1709 and the reason this\n * class exists. The runner pattern-matches `err instanceof\n * ResponseSchemaValidationError` to synthesize the correct attribution.\n *\n * Stable wire surface: `name` is the literal string `'ResponseSchemaValidationError'`\n * so consumers that can't import the class (cross-bundle, dynamic\n * `require`) can still recognize it by string comparison.\n *\n * Spec: adcp-client#1709.\n */\nexport class ResponseSchemaValidationError extends Error {\n readonly name = 'ResponseSchemaValidationError';\n /** The AdCP tool name whose response failed validation (e.g., `'sync_accounts'`). */\n readonly toolName: string;\n /** The structured Zod issues from the failed `safeParse`. */\n readonly issues: z.core.$ZodIssue[];\n /** The raw response data that failed validation, for diagnostic reporting. */\n readonly data: unknown;\n\n constructor(toolName: string, issues: z.core.$ZodIssue[], data: unknown, summaryMessage: string) {\n super(`Response validation failed for ${toolName}: ${summaryMessage}`);\n this.toolName = toolName;\n this.issues = issues;\n this.data = data;\n }\n}\n\n/**\n * Union type of all possible AdCP responses\n * Each response type is a discriminated union of success | error\n */\nexport type AdCPResponse =\n | GetProductsResponse\n | ListCreativeFormatsResponse\n | CreateMediaBuyResponse\n | SyncCreativesResponse\n | ListCreativesResponse\n | UpdateMediaBuyResponse\n | GetMediaBuysResponse\n | GetMediaBuyDeliveryResponse\n | ProvidePerformanceFeedbackResponse\n | BuildCreativeResponse\n | PreviewCreativeResponse\n | GetSignalsResponse\n | ActivateSignalResponse;\n\nconst SUCCESS_PAYLOAD_FIELD_GROUPS_BY_TOOL: Readonly<Record<string, readonly (readonly string[])[]>> = {\n get_adcp_capabilities: [['adcp', 'supported_protocols']],\n list_accounts: [['accounts']],\n sync_accounts: [['accounts']],\n sync_governance: [['accounts']],\n report_usage: [['accepted']],\n get_account_financials: [['account', 'currency', 'period', 'timezone']],\n get_products: [['products'], ['unchanged']],\n request_proposals: [['outcome']],\n refine_proposals: [['results', 'products']],\n decline_proposals: [['results']],\n list_creative_formats: [['formats']],\n create_media_buy: [['media_buy_id', 'packages']],\n update_media_buy: [['media_buy_id']],\n get_media_buys: [['media_buys']],\n get_media_buy_delivery: [['reporting_period', 'currency', 'media_buy_deliveries']],\n provide_performance_feedback: [['success']],\n sync_event_sources: [['event_sources']],\n log_event: [['events_received', 'events_processed']],\n sync_audiences: [['audiences']],\n sync_catalogs: [['catalogs']],\n sync_creatives: [['creatives']],\n list_creatives: [['query_summary', 'pagination', 'creatives']],\n build_creative: [['creative_manifest'], ['creative_manifests']],\n preview_creative: [['response_type', 'previews']],\n get_creative_delivery: [['currency', 'reporting_period', 'creatives']],\n validate_input: [['results']],\n get_signals: [['signals'], ['unchanged']],\n activate_signal: [['deployments']],\n create_property_list: [['list', 'auth_token']],\n update_property_list: [['list']],\n get_property_list: [['list']],\n list_property_lists: [['lists']],\n delete_property_list: [['deleted', 'list_id']],\n create_collection_list: [['list', 'auth_token']],\n update_collection_list: [['list']],\n get_collection_list: [['list']],\n list_collection_lists: [['lists']],\n delete_collection_list: [['deleted', 'list_id']],\n list_content_standards: [['standards']],\n create_content_standards: [['standards_id']],\n update_content_standards: [['success', 'standards_id']],\n calibrate_content: [['verdict']],\n validate_content_delivery: [['summary', 'results']],\n get_media_buy_artifacts: [['media_buy_id', 'artifacts']],\n get_creative_features: [['results']],\n sync_plans: [['plans']],\n check_governance: [['check_id', 'verdict', 'plan_id', 'explanation']],\n report_plan_outcome: [['outcome_id', 'outcome_state']],\n get_plan_audit_logs: [['plans']],\n si_get_offering: [['available']],\n si_initiate_session: [['session_id', 'session_status']],\n si_send_message: [['session_id', 'session_status']],\n si_terminate_session: [['session_id', 'terminated']],\n comply_test_controller: [['success']],\n validate_property_delivery: [['list_id', 'summary', 'results', 'validated_at']],\n get_brand_identity: [['brand_id', 'house', 'names']],\n verify_brand_claim: [['claim_type', 'verification_status']],\n get_rights: [['rights']],\n acquire_rights: [['rights_id', 'rights_status', 'brand_id']],\n update_rights: [['rights_id']],\n creative_approval: [['decision']],\n verify_brand_claims: [['results']],\n search_brands: [['brands']],\n};\n\nfunction hasOwnField(value: Record<string, unknown>, field: string): boolean {\n return Object.prototype.hasOwnProperty.call(value, field);\n}\n\n/**\n * Top-level `errors[]` can be either a terminal Error arm or non-fatal\n * advisory diagnostics on a Success/Submitted arm. Envelope-only fields\n * (`status`, `context`, `ext`, version fields) do not prove success, so this\n * requires per-tool success-field evidence or the universal submitted envelope.\n * Completed payloads still flow through normal tool-schema validation after\n * this check.\n */\nexport function hasAdvisorySuccessPayload(response: unknown, toolName?: string): boolean {\n if (response == null || typeof response !== 'object' || Array.isArray(response)) return false;\n const obj = response as Record<string, unknown>;\n\n if (obj.status === 'failed' || obj.status === 'rejected') return false;\n if (obj.success === false) return false;\n\n if (obj.status === 'submitted' && (typeof obj.task_id === 'string' || typeof obj.taskId === 'string')) {\n return true;\n }\n\n if (!toolName) return false;\n\n const successFieldGroups = SUCCESS_PAYLOAD_FIELD_GROUPS_BY_TOOL[toolName];\n if (!successFieldGroups) return false;\n return successFieldGroups.some(group => group.every(field => hasOwnField(obj, field)));\n}\n\n/**\n * AdCP 3.2 models an inventory refusal from `get_products` as a successful,\n * typed business outcome. Its `status: \"rejected\"` discriminator must not be\n * confused with the task-envelope terminal state that uses the same literal.\n */\nfunction isStructuredGetProductsRejection(response: unknown, toolName?: string, responseAdcpVersion?: string): boolean {\n if (toolName !== 'get_products' || response == null || typeof response !== 'object' || Array.isArray(response)) {\n return false;\n }\n\n const obj = response as Record<string, unknown>;\n const effectiveVersion = typeof obj.adcp_version === 'string' ? obj.adcp_version : responseAdcpVersion;\n const versionMatch =\n typeof effectiveVersion === 'string' ? /^v?(\\d+)\\.(\\d+)(?:\\.|-|$)/.exec(effectiveVersion.trim()) : null;\n const major = versionMatch?.[1] === undefined ? undefined : Number.parseInt(versionMatch[1], 10);\n const minor = versionMatch?.[2] === undefined ? undefined : Number.parseInt(versionMatch[2], 10);\n const declaresStructuredRejectionVersion =\n major !== undefined && minor !== undefined && (major > 3 || (major === 3 && minor >= 2));\n const suggestionsValid =\n obj.suggestions === undefined ||\n (Array.isArray(obj.suggestions) &&\n obj.suggestions.length >= 1 &&\n obj.suggestions.length <= 20 &&\n obj.suggestions.every(\n suggestion => typeof suggestion === 'string' && suggestion.length >= 1 && suggestion.length <= 1000\n ));\n const forbiddenFields = [\n 'products',\n 'proposals',\n 'errors',\n 'adcp_error',\n 'incomplete',\n 'cache_scope',\n 'filter_diagnostics',\n 'refinement_applied',\n 'unchanged',\n 'wholesale_feed_version',\n 'pricing_version',\n 'pagination',\n ];\n return (\n declaresStructuredRejectionVersion &&\n obj.status === 'rejected' &&\n typeof obj.reason === 'string' &&\n obj.reason.length >= 1 &&\n obj.reason.length <= 2000 &&\n suggestionsValid &&\n obj.success !== false &&\n obj.error == null &&\n typeof obj.error_code !== 'string' &&\n forbiddenFields.every(field => !hasOwnField(obj, field))\n );\n}\n\nexport function isTerminalAdcpError(response: unknown, toolName?: string, responseAdcpVersion?: string): boolean {\n const obj = response as Record<string, unknown> | null | undefined;\n if (isStructuredGetProductsRejection(obj, toolName, responseAdcpVersion)) return false;\n if (obj?.status === 'failed' || obj?.status === 'rejected') return true;\n if (obj?.adcp_error && typeof (obj.adcp_error as { code?: unknown }).code === 'string') return true;\n if (typeof obj?.error_code === 'string') {\n return !hasAdvisorySuccessPayload(obj, toolName);\n }\n if (Array.isArray(obj?.errors) && obj.errors.length > 0) {\n return !hasAdvisorySuccessPayload(obj, toolName);\n }\n return false;\n}\n\n/**\n * Check whether an extracted AdCP operation payload represents success.\n * A transport task may be `completed` while its operation payload is terminally\n * unsuccessful, so callers must evaluate both layers.\n */\nexport function isAdcpOperationSuccess(response: unknown, toolName?: string, responseAdcpVersion?: string): boolean {\n const obj = response as Record<string, unknown> | null | undefined;\n return (\n obj?.success !== false &&\n !obj?.error &&\n !obj?.adcp_error &&\n !isTerminalAdcpError(response, toolName, responseAdcpVersion)\n );\n}\n\n/**\n * Extract raw AdCP response from protocol wrapper\n *\n * @param protocolResponse - Raw response from MCP or A2A protocol\n * @param toolName - Optional AdCP tool name for validation\n * @param protocol - Protocol type ('mcp' or 'a2a'), if known. If not provided, will auto-detect.\n * @param options - Optional validation behavior overrides\n * @returns Raw AdCP response data matching schema exactly\n * @throws {Error} If response doesn't match expected schema for the tool\n */\nexport function unwrapProtocolResponse(\n protocolResponse: any,\n toolName?: string,\n protocol?: 'mcp' | 'a2a',\n options?: { filterInvalidProducts?: boolean; responseAdcpVersion?: string }\n): AdCPResponse & { _message?: string } {\n if (!protocolResponse) {\n throw new Error('Protocol response is null or undefined');\n }\n\n // Extract response from protocol wrapper\n let unwrapped: any;\n let mcpExtractionPath: McpExtractionPath | undefined;\n if (protocol === 'mcp') {\n const outcome = unwrapMCPResponse(protocolResponse);\n unwrapped = outcome.result;\n mcpExtractionPath = outcome.extractionPath;\n } else if (protocol === 'a2a') {\n unwrapped = unwrapA2AResponse(protocolResponse);\n } else {\n // Auto-detect protocol if not specified\n if (isMCPResponse(protocolResponse)) {\n const outcome = unwrapMCPResponse(protocolResponse);\n unwrapped = outcome.result;\n mcpExtractionPath = outcome.extractionPath;\n } else if (isA2AResponse(protocolResponse)) {\n unwrapped = unwrapA2AResponse(protocolResponse);\n } else {\n throw new Error('Unable to extract AdCP response from protocol wrapper');\n }\n }\n // Preserve the extraction path across Zod's `safeParse` (which returns a\n // fresh object). `retag` re-attaches the provenance to whichever object we\n // return so the tag survives validation, filtering, and _message merging.\n const retag = <T extends AdCPResponse & { _message?: string }>(value: T): T => {\n if (mcpExtractionPath !== undefined) tagExtractionPath(value, mcpExtractionPath);\n return value;\n };\n\n if (mcpExtractionPath !== undefined) {\n tagExtractionPath(unwrapped, mcpExtractionPath);\n }\n\n // Skip schema validation for error responses — they don't include\n // tool-specific fields like `products`. Handles both AdCP-standard\n // { errors: [...] } and legacy singular { error: \"...\" } patterns.\n if (\n isTerminalAdcpError(unwrapped, toolName, options?.responseAdcpVersion) ||\n (unwrapped?.error && typeof unwrapped.error === 'string')\n ) {\n return retag(unwrapped);\n }\n\n // Validate success responses against tool schema if tool name provided\n if (toolName) {\n const schema = TOOL_RESPONSE_SCHEMAS[toolName];\n if (schema) {\n // Strip _message before validation — it's a text summary added by the unwrapper,\n // not part of the AdCP response schema. Intersection with union schemas fails in Zod v4.\n const { _message: _msg, ...stripped } = unwrapped as Record<string, unknown>;\n // Back-compat: 3.0.x sellers may omit envelope `status` (made REQUIRED\n // in 3.1.0-beta.2). Inject a synthetic status only when the response\n // declares itself as 3.0.x (or carries no version field at all).\n const dataToValidate = prepareResponseForSchemaValidation(\n toolName,\n injectLegacyEnvelopeStatus(stripped, { toolName }),\n options?.responseAdcpVersion\n ) as Record<string, unknown>;\n const result = schema.safeParse(dataToValidate);\n if (!result.success) {\n // When filterInvalidArrayItems is enabled and this is a get_products response,\n // try filtering invalid products individually rather than rejecting the entire response.\n if (options?.filterInvalidProducts && toolName === 'get_products') {\n const filtered = filterInvalidProducts(schema, dataToValidate);\n if (filtered) {\n let validated = filtered as unknown as AdCPResponse & { _message?: string };\n // Strip compat-injected `status` before returning — same rationale as\n // the main success path below. See adcp-client#1961.\n if (!('status' in stripped)) {\n const { status: _s, ...rest } = validated as unknown as Record<string, unknown>;\n validated = rest as unknown as typeof validated;\n } else {\n validated = restoreLegacyMediaBuyStatusForReturn(validated, stripped, dataToValidate, toolName);\n }\n if (!('adcp_version' in stripped)) {\n const { adcp_version: _v, ...rest } = validated as unknown as Record<string, unknown>;\n validated = rest as unknown as typeof validated;\n }\n if (_msg) validated._message = _msg as string;\n return retag(validated);\n }\n }\n\n // Union schemas produce a generic \"Invalid input\" at (root).\n // Try each variant to surface the actual missing/invalid fields.\n const firstIssue = result.error.issues[0];\n const isUnionError = result.error.issues.length === 1 && firstIssue?.code === 'invalid_union';\n\n if (isUnionError) {\n const betterErrors = getBestUnionErrors(schema, dataToValidate);\n if (betterErrors && betterErrors.length > 0) {\n const bestMessage = betterErrors.map(e => `${e.path}: ${e.message}`).join('; ');\n throw new ResponseSchemaValidationError(toolName, result.error.issues, dataToValidate, bestMessage);\n }\n }\n\n throw new ResponseSchemaValidationError(toolName, result.error.issues, dataToValidate, result.error.message);\n }\n\n // Re-attach _message after validation so it's available for text summaries.\n // Strip any compat-injected `status` before returning: the injection was\n // purely to let a 3.0.x seller pass the 3.1 envelope schema; propagating\n // it into taskResult.data causes storyboard field_value_or_absent checks\n // on the deprecated legacy `status` field to fail with a false positive\n // (sees injected \"completed\" instead of absent). See adcp-client#1961.\n let validated = result.data as AdCPResponse & { _message?: string };\n if (!('status' in stripped)) {\n const { status: _s, ...rest } = validated as unknown as Record<string, unknown>;\n validated = rest as unknown as typeof validated;\n } else {\n validated = restoreLegacyMediaBuyStatusForReturn(validated, stripped, dataToValidate, toolName);\n }\n if (!('adcp_version' in stripped)) {\n const { adcp_version: _v, ...rest } = validated as unknown as Record<string, unknown>;\n validated = rest as unknown as typeof validated;\n }\n if (_msg) validated._message = _msg as string;\n return retag(validated);\n }\n }\n\n // Return unwrapped response (no validation) — already tagged above.\n return unwrapped as AdCPResponse;\n}\n\nfunction restoreLegacyMediaBuyStatusForReturn<T extends AdCPResponse & { _message?: string }>(\n validated: T,\n original: Record<string, unknown>,\n compat: Record<string, unknown>,\n toolName: string\n): T {\n if (\n (toolName === 'create_media_buy' || toolName === 'update_media_buy') &&\n typeof original.media_buy_id === 'string' &&\n typeof original.status === 'string' &&\n compat.status === 'completed' &&\n typeof compat.media_buy_status === 'string'\n ) {\n return normalizeLegacyMediaBuyStatusForReturn(\n { ...validated, status: original.status } as unknown as Record<string, unknown>,\n { toolName }\n ) as unknown as T;\n }\n return normalizeLegacyMediaBuyStatusForReturn(validated as unknown as Record<string, unknown>, {\n toolName,\n }) as unknown as T;\n}\n\n/**\n * Filter invalid products from a get_products response.\n *\n * Validates each product individually against the ProductSchema,\n * keeps only valid ones, and re-validates the full response.\n * Returns the filtered response, or null if filtering can't help.\n */\nfunction filterInvalidProducts(schema: z.ZodType, data: Record<string, unknown>): Record<string, unknown> | null {\n const products = data.products;\n if (!Array.isArray(products)) return null;\n\n // `products` is optional on `get_products` since AdCP 3.1.0-beta.3 (the\n // `unchanged: true` wholesale-feed branch legitimately omits it). The Zod\n // shape is now `ZodOptional<ZodArray<...>>` rather than the bare\n // `ZodArray<...>` we used to see. Unwrap a level of `ZodOptional` /\n // `ZodNullable` before the array check so the helper still finds the\n // element schema.\n let ProductSchema = (schema as z.ZodObject<any>).shape?.products;\n if (ProductSchema instanceof z.ZodOptional || ProductSchema instanceof z.ZodNullable) {\n ProductSchema = (ProductSchema as z.ZodOptional<any>).unwrap();\n }\n if (!(ProductSchema instanceof z.ZodArray)) return null;\n\n const elementSchema = (ProductSchema as z.ZodArray<any>).element;\n const validProducts: unknown[] = [];\n for (const product of products) {\n if (elementSchema.safeParse(product).success) {\n validProducts.push(product);\n }\n }\n\n // Nothing was filtered — all products are individually valid, so the validation\n // error is at the response level (not caused by invalid products). Fall through\n // to the normal error path.\n if (validProducts.length === products.length) return null;\n\n const filtered = { ...data, products: validProducts };\n const revalidated = schema.safeParse(filtered);\n if (revalidated.success) {\n const droppedCount = products.length - validProducts.length;\n console.warn(\n `[adcp-client] Filtered ${droppedCount} invalid product(s) from get_products response (${validProducts.length} valid, ${products.length} total)`\n );\n return revalidated.data as Record<string, unknown>;\n }\n\n return null;\n}\n\n/**\n * Check if response is MCP format\n */\nfunction isMCPResponse(response: any): boolean {\n return 'structuredContent' in response || 'isError' in response || 'content' in response;\n}\n\n/**\n * Check if response is A2A format.\n * A2A errors are JSON-RPC objects ({ code, message }), not strings.\n */\nfunction isA2AResponse(response: any): boolean {\n return 'result' in response || ('error' in response && typeof response.error === 'object' && response.error !== null);\n}\n\n/**\n * MCP response extraction provenance. Set as a non-enumerable `_extraction_path`\n * property on the unwrapped object so the storyboard runner can surface it in\n * its runner-output contract without leaking into JSON-serialized or spread\n * responses. See `src/lib/testing/storyboard/types.ts` → `RunnerExtractionPath`.\n */\nexport type McpExtractionPath = 'structured_content' | 'text_fallback' | 'error' | 'none';\n\nexport const EXTRACTION_PATH_KEY = '_extraction_path' as const;\n\ninterface McpUnwrapOutcome {\n result: AdCPResponse;\n extractionPath: McpExtractionPath;\n}\n\n/**\n * Unwrap MCP response - all MCP logic in one place.\n *\n * Also records which branch produced the parsed response (structuredContent\n * vs text content) so downstream tooling can tell a runner extraction bug\n * apart from an agent bug.\n */\nfunction unwrapMCPResponse(response: any): McpUnwrapOutcome {\n // MCP error response — preserve full structured data (context, ext, adcp_error)\n if (response.isError === true) {\n // L3: structuredContent has the full error payload.\n // Trust boundary: this is untrusted agent content passed through as-is.\n // Consumers must sanitize fields like suggestion/details before rendering.\n if (response.structuredContent && typeof response.structuredContent === 'object') {\n return { result: response.structuredContent as AdCPResponse, extractionPath: 'error' };\n }\n\n // L2: JSON in text content\n if (Array.isArray(response.content)) {\n for (const item of response.content) {\n if (item?.type === 'text' && item.text) {\n try {\n const parsed = JSON.parse(item.text);\n if (parsed?.adcp_error && typeof parsed.adcp_error.code === 'string') {\n return { result: parsed as AdCPResponse, extractionPath: 'error' };\n }\n } catch {\n // not JSON, continue to raw text fallback\n }\n }\n }\n }\n\n // L1: Raw text fallback — no structured data available\n const errorContent = Array.isArray(response.content)\n ? response.content.find((c: any) => c.type === 'text')?.text\n : response.content?.text || 'Unknown error';\n\n return {\n result: {\n adcp_error: {\n code: ERROR_CODES.MCP_ERROR,\n message: errorContent || 'MCP tool call failed',\n synthetic: true,\n },\n } as unknown as AdCPResponse,\n extractionPath: 'error',\n };\n }\n\n // MCP success response with structuredContent\n if (response.structuredContent !== undefined && response.structuredContent !== null) {\n const data = response.structuredContent;\n\n // Extract text messages from content field (parallel to A2A TextParts)\n const textMessages: string[] = [];\n if (response.content && Array.isArray(response.content)) {\n for (const item of response.content) {\n if (item.type === 'text' && item.text) {\n textMessages.push(item.text);\n }\n }\n }\n\n // Include text messages if present (same pattern as A2A)\n if (textMessages.length > 0) {\n return {\n result: {\n ...data,\n _message: textMessages.join('\\n'),\n },\n extractionPath: 'structured_content',\n };\n }\n\n return { result: data, extractionPath: 'structured_content' };\n }\n\n // MCP text content fallback (try parsing as JSON)\n if (response.content && Array.isArray(response.content)) {\n const textContent = response.content.find((c: any) => c.type === 'text');\n if (textContent?.text) {\n try {\n return { result: JSON.parse(textContent.text), extractionPath: 'text_fallback' };\n } catch {\n // Include snippet of text for debugging (max 100 chars)\n const snippet = textContent.text.length > 100 ? textContent.text.substring(0, 100) + '...' : textContent.text;\n\n return {\n result: {\n // AdCP 3.1.0-beta.2+: envelope `status` is REQUIRED on every\n // response. Synthetic error envelopes synthesized by the SDK\n // when the wire doesn't carry a valid AdCP payload need the\n // same. `failed` matches the error semantics of this branch.\n status: 'failed' as const,\n errors: [\n {\n code: ERROR_CODES.INVALID_RESPONSE,\n message: `Response does not contain structured AdCP data. Text content: \"${snippet}\"`,\n },\n ],\n } as AdCPResponse,\n extractionPath: 'text_fallback',\n };\n }\n }\n }\n\n throw new Error('Invalid MCP response format');\n}\n\n/**\n * Attach the extraction path to an unwrapped object as a non-enumerable\n * property. Non-enumerable so `JSON.stringify`, `Object.keys`, and spread\n * ignore it — the storyboard runner reads it via a direct property access\n * but the rest of the system sees the unwrapped data unchanged.\n */\nfunction tagExtractionPath(result: AdCPResponse, path: McpExtractionPath): AdCPResponse {\n if (result === null || typeof result !== 'object') return result;\n try {\n Object.defineProperty(result, EXTRACTION_PATH_KEY, {\n value: path,\n enumerable: false,\n configurable: true,\n writable: true,\n });\n } catch {\n // Frozen / sealed objects reject defineProperty; drop the tag silently —\n // the runner's fallback inference in extractionFromTaskResult still works.\n }\n return result;\n}\n\n/**\n * Read the extraction path from an unwrapped AdCP response, or `undefined`\n * if the response did not originate from an MCP unwrap path.\n */\nexport function readExtractionPath(data: unknown): McpExtractionPath | undefined {\n if (data === null || typeof data !== 'object') return undefined;\n const path = (data as Record<string, unknown>)[EXTRACTION_PATH_KEY];\n return typeof path === 'string' ? (path as McpExtractionPath) : undefined;\n}\n\n/**\n * Unwrap A2A response\n *\n * Called for terminal task states (\"completed\", \"failed\", \"rejected\",\n * \"canceled\"). All four carry the same artifact + DataPart envelope per\n * AdCP transport-errors §A2A Binding — failed tasks place `adcp_error`\n * into the DataPart alongside an optional terse TextPart.\n *\n * Intermediate statuses (\"working\", \"submitted\", \"input-required\",\n * \"auth-required\") do not yet have AdCP artifacts and are rejected here\n * so callers handle them at the response level.\n */\nconst TERMINAL_A2A_STATES: ReadonlySet<string> = new Set(['completed', 'failed', 'rejected', 'canceled']);\n\n/**\n * Detect whether a response carries a spec-compliant terminal-state Task\n * with a structured DataPart artifact. Mirrors the protocol-layer guard in\n * `src/lib/protocols/a2a.ts` (`hasTerminalTaskWithDataArtifact`) so the\n * unwrapper defers to the canonical envelope when a non-conformant seller\n * surfaces both a top-level transport error and the AdCP artifact.\n */\nfunction hasTerminalTaskWithDataArtifact(response: unknown): boolean {\n if (!response || typeof response !== 'object') return false;\n const result = (response as { result?: unknown }).result;\n if (!result || typeof result !== 'object') return false;\n const r = result as { kind?: unknown; status?: unknown; artifacts?: unknown };\n if (r.kind !== 'task') return false;\n const status = r.status as { state?: unknown } | undefined;\n if (typeof status?.state !== 'string' || !TERMINAL_A2A_STATES.has(status.state)) return false;\n return getLatestA2ADataPartFromResponse(response) !== undefined;\n}\n\nfunction unwrapA2AResponse(response: any): AdCPResponse {\n const taskState = response.result?.status?.state;\n if (taskState && !TERMINAL_A2A_STATES.has(taskState)) {\n throw new Error(\n `Cannot unwrap A2A response with intermediate status: ${taskState}. ` +\n 'Only terminal responses (completed, failed, rejected, canceled) should be unwrapped.'\n );\n }\n // A2A error response (JSON-RPC error). adcp-client#1575: when a\n // non-conformant seller surfaces both a top-level JSON-RPC error AND a\n // terminal-state Task with a structured DataPart artifact, the artifact\n // is canonical per AdCP transport-errors §A2A Binding — defer to the\n // artifact extraction below. Mirrors the protocol-layer guard at\n // `src/lib/protocols/a2a.ts` so the two layers stay symmetric and\n // direct callers (storyboard fixtures, cached responses, webhook\n // payloads) inherit the same defensive behavior.\n if (response.error && !hasTerminalTaskWithDataArtifact(response)) {\n return {\n // AdCP 3.1.0-beta.2+: envelope `status` is REQUIRED. Synthetic error\n // envelopes for A2A JSON-RPC failures carry `failed` to match the\n // error semantics.\n status: 'failed' as const,\n errors: [\n {\n code: response.error.code?.toString() || ERROR_CODES.UNKNOWN,\n message: response.error.message || 'A2A JSON-RPC error occurred',\n ...(response.error.data && { data: response.error.data }),\n },\n ],\n } as AdCPResponse;\n }\n\n // A2A terminal response — same shape regardless of success or failure:\n // - MUST have result.artifacts array with at least one artifact\n // - Artifact MUST have at least one DataPart (kind: 'data') with the AdCP payload\n // (success payload for `completed`, `adcp_error` envelope for `failed`)\n // - MAY have TextParts (kind: 'text') with optional messages\n\n const artifacts = response.result?.artifacts;\n if (!Array.isArray(artifacts) || artifacts.length === 0) {\n throw new Error('A2A response must have at least one artifact');\n }\n\n const artifact = artifacts[artifacts.length - 1];\n if (!artifact || typeof artifact !== 'object' || Array.isArray(artifact)) {\n throw new Error('A2A response must have at least one artifact');\n }\n\n if (!('parts' in artifact) || !Array.isArray((artifact as { parts?: unknown }).parts)) {\n throw new Error('A2A artifact missing parts array');\n }\n\n // Extract DataPart (required) and TextParts (optional). Use the shared\n // latest structured DataPart helper so parser and validator agree.\n const extracted = getLatestA2ADataPartFromResponse(response);\n if (!extracted) {\n throw new Error('A2A response must have a DataPart with AdCP data');\n }\n\n const parts = (artifact as { parts: unknown[] }).parts;\n const textParts = parts\n .filter((p: any) => p && typeof p === 'object' && p.kind === 'text' && p.text)\n .map((p: any) => p.text);\n\n // Unwrap nested response field if present (some agents wrap AdCP responses)\n let data: any = extracted.data;\n if (data?.response && typeof data.response === 'object' && !Array.isArray(data.response)) {\n data = data.response;\n }\n\n // Return data with optional message\n if (textParts.length > 0) {\n return {\n ...data,\n _message: textParts.join('\\n'),\n };\n }\n\n return data;\n}\n\n/**\n * Check if a response is an AdCP error response.\n * Recognizes both `{ adcp_error: { code: string } }` (MCP structured errors)\n * and `{ errors: [{ code, message }] }` (legacy/A2A format).\n *\n * This helper is structural and intentionally does not know which tool\n * produced the payload. For AdCP 3.1 success/submitted payloads that can\n * carry advisory `errors[]`, prefer {@link isTerminalAdcpError} with a\n * `toolName`.\n */\nexport function isAdcpError(response: any): boolean {\n if (Array.isArray(response?.errors) && response.errors.length > 0) return true;\n if (response?.adcp_error && typeof response.adcp_error.code === 'string') return true;\n return false;\n}\n\n/**\n * Check if a response is an AdCP success response for a specific task\n *\n * Uses Zod schemas to validate the response structure matches the expected\n * success response format for the given task.\n */\nexport function isAdcpSuccess(response: any, taskName: string, responseAdcpVersion?: string): boolean {\n // First check if it's an error response\n if (isTerminalAdcpError(response, taskName, responseAdcpVersion)) {\n return false;\n }\n\n // Try to validate with Zod schema if available\n const schema = TOOL_RESPONSE_SCHEMAS[taskName];\n if (schema) {\n const { _message: _, ...stripped } = (response ?? {}) as Record<string, unknown>;\n // Apply the same 3.0.x envelope-status leniency as unwrapProtocolResponse\n // so success detection stays consistent across the two entry points.\n const dataToValidate = prepareResponseForSchemaValidation(\n taskName,\n injectLegacyEnvelopeStatus(stripped, { toolName: taskName }),\n responseAdcpVersion\n );\n const result = schema.safeParse(dataToValidate);\n return result.success;\n }\n\n // Unknown task - can't validate, assume success if no errors\n return true;\n}\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["validated"]}
1
+ {"version":3,"sources":["../../../src/lib/utils/response-unwrapper.ts"],"sourcesContent":["/**\n * Response Unwrapper\n *\n * Extracts raw AdCP responses from protocol wrappers (MCP/A2A).\n * Follows canonical A2A response format per AdCP specification.\n */\n\nimport { z } from 'zod';\nimport { getBestUnionErrors } from './union-errors';\n\n/**\n * Standard error codes for response unwrapping\n */\nconst ERROR_CODES = {\n MCP_ERROR: 'mcp_error',\n INVALID_RESPONSE: 'invalid_response',\n UNKNOWN: 'unknown',\n} as const;\n\nimport type {\n GetProductsResponse,\n ListCreativeFormatsResponse,\n CreateMediaBuyResponse,\n SyncCreativesResponse,\n ListCreativesResponse,\n UpdateMediaBuyResponse,\n GetMediaBuysResponse,\n GetMediaBuyDeliveryResponse,\n ProvidePerformanceFeedbackResponse,\n BuildCreativeResponse,\n PreviewCreativeResponse,\n GetSignalsResponse,\n ActivateSignalResponse,\n} from '../types/tools.generated';\nimport { prepareResponseForSchemaValidation, TOOL_RESPONSE_SCHEMAS } from './response-schemas';\nimport { injectLegacyEnvelopeStatus, normalizeLegacyMediaBuyStatusForReturn } from './envelope-status-compat';\nimport { getLatestA2ADataPartFromResponse } from './a2a-artifacts';\n\n/**\n * Typed error thrown when the response unwrapper's Zod schema rejects an\n * agent response. Carries the structured rejection detail so the storyboard\n * runner can attribute the failure to its canonical `response_schema`\n * validation entry instead of silently falling through to whichever\n * step-level invariant fires next (e.g., `context.no_secret_echo`).\n *\n * Without this typed boundary, the runner can only catch a generic `Error`\n * with a freeform message — there's no stable way to distinguish a\n * schema rejection from a transport error or any other failure. The\n * misattribution this caused (every BidMachine `sync_accounts` failure\n * surfaced as `no_secret_echo`, masking the root cause across 10+ deploys)\n * is the canonical evidence for adcp-client#1709 and the reason this\n * class exists. The runner pattern-matches `err instanceof\n * ResponseSchemaValidationError` to synthesize the correct attribution.\n *\n * Stable wire surface: `name` is the literal string `'ResponseSchemaValidationError'`\n * so consumers that can't import the class (cross-bundle, dynamic\n * `require`) can still recognize it by string comparison.\n *\n * Spec: adcp-client#1709.\n */\nexport class ResponseSchemaValidationError extends Error {\n readonly name = 'ResponseSchemaValidationError';\n /** The AdCP tool name whose response failed validation (e.g., `'sync_accounts'`). */\n readonly toolName: string;\n /** The structured Zod issues from the failed `safeParse`. */\n readonly issues: z.core.$ZodIssue[];\n /** The raw response data that failed validation, for diagnostic reporting. */\n readonly data: unknown;\n\n constructor(toolName: string, issues: z.core.$ZodIssue[], data: unknown, summaryMessage: string) {\n super(`Response validation failed for ${toolName}: ${summaryMessage}`);\n this.toolName = toolName;\n this.issues = issues;\n this.data = data;\n }\n}\n\n/**\n * Union type of all possible AdCP responses\n * Each response type is a discriminated union of success | error\n */\nexport type AdCPResponse =\n | GetProductsResponse\n | ListCreativeFormatsResponse\n | CreateMediaBuyResponse\n | SyncCreativesResponse\n | ListCreativesResponse\n | UpdateMediaBuyResponse\n | GetMediaBuysResponse\n | GetMediaBuyDeliveryResponse\n | ProvidePerformanceFeedbackResponse\n | BuildCreativeResponse\n | PreviewCreativeResponse\n | GetSignalsResponse\n | ActivateSignalResponse;\n\nconst SUCCESS_PAYLOAD_FIELD_GROUPS_BY_TOOL: Readonly<Record<string, readonly (readonly string[])[]>> = {\n get_adcp_capabilities: [['adcp', 'supported_protocols']],\n list_accounts: [['accounts']],\n sync_accounts: [['accounts']],\n sync_governance: [['accounts']],\n report_usage: [['accepted']],\n get_account_financials: [['account', 'currency', 'period', 'timezone']],\n get_products: [['products'], ['unchanged']],\n request_proposals: [['outcome']],\n refine_proposals: [['results', 'products']],\n decline_proposals: [['results']],\n list_creative_formats: [['formats']],\n create_media_buy: [['media_buy_id', 'packages']],\n update_media_buy: [['media_buy_id']],\n get_media_buys: [['media_buys']],\n get_media_buy_delivery: [['reporting_period', 'currency', 'media_buy_deliveries']],\n provide_performance_feedback: [['success']],\n sync_event_sources: [['event_sources']],\n log_event: [['events_received', 'events_processed']],\n sync_audiences: [['audiences']],\n sync_catalogs: [['catalogs']],\n sync_creatives: [['creatives']],\n list_creatives: [['query_summary', 'pagination', 'creatives']],\n build_creative: [['creative_manifest'], ['creative_manifests'], ['creatives']],\n preview_creative: [['response_type', 'previews']],\n get_creative_delivery: [['currency', 'reporting_period', 'creatives']],\n validate_input: [['results']],\n get_signals: [['signals'], ['unchanged']],\n activate_signal: [['deployments']],\n create_property_list: [['list', 'auth_token']],\n update_property_list: [['list']],\n get_property_list: [['list']],\n list_property_lists: [['lists']],\n delete_property_list: [['deleted', 'list_id']],\n create_collection_list: [['list', 'auth_token']],\n update_collection_list: [['list']],\n get_collection_list: [['list']],\n list_collection_lists: [['lists']],\n delete_collection_list: [['deleted', 'list_id']],\n list_content_standards: [['standards']],\n create_content_standards: [['standards_id']],\n update_content_standards: [['success', 'standards_id']],\n calibrate_content: [['verdict']],\n validate_content_delivery: [['summary', 'results']],\n get_media_buy_artifacts: [['media_buy_id', 'artifacts']],\n get_creative_features: [['results']],\n sync_plans: [['plans']],\n check_governance: [['check_id', 'verdict', 'plan_id', 'explanation']],\n report_plan_outcome: [['outcome_id', 'outcome_state']],\n get_plan_audit_logs: [['plans']],\n si_get_offering: [['available']],\n si_initiate_session: [['session_id', 'session_status']],\n si_send_message: [['session_id', 'session_status']],\n si_terminate_session: [['session_id', 'terminated']],\n comply_test_controller: [['success']],\n validate_property_delivery: [['list_id', 'summary', 'results', 'validated_at']],\n get_brand_identity: [['brand_id', 'house', 'names']],\n verify_brand_claim: [['claim_type', 'verification_status']],\n get_rights: [['rights']],\n acquire_rights: [['rights_id', 'rights_status', 'brand_id']],\n update_rights: [['rights_id']],\n creative_approval: [['decision']],\n verify_brand_claims: [['results']],\n search_brands: [['brands']],\n};\n\nfunction hasOwnField(value: Record<string, unknown>, field: string): boolean {\n return Object.prototype.hasOwnProperty.call(value, field);\n}\n\n/**\n * Top-level `errors[]` can be either a terminal Error arm or non-fatal\n * advisory diagnostics on a Success/Submitted arm. Envelope-only fields\n * (`status`, `context`, `ext`, version fields) do not prove success, so this\n * requires per-tool success-field evidence or the universal submitted envelope.\n * Completed payloads still flow through normal tool-schema validation after\n * this check.\n */\nexport function hasAdvisorySuccessPayload(response: unknown, toolName?: string): boolean {\n if (response == null || typeof response !== 'object' || Array.isArray(response)) return false;\n const obj = response as Record<string, unknown>;\n\n if (obj.status === 'failed' || obj.status === 'rejected') return false;\n if (obj.success === false) return false;\n\n if (obj.status === 'submitted' && (typeof obj.task_id === 'string' || typeof obj.taskId === 'string')) {\n return true;\n }\n\n if (!toolName) return false;\n\n const successFieldGroups = SUCCESS_PAYLOAD_FIELD_GROUPS_BY_TOOL[toolName];\n if (!successFieldGroups) return false;\n return successFieldGroups.some(group => group.every(field => hasOwnField(obj, field)));\n}\n\n/**\n * AdCP 3.2 models an inventory refusal from `get_products` as a successful,\n * typed business outcome. Its `status: \"rejected\"` discriminator must not be\n * confused with the task-envelope terminal state that uses the same literal.\n */\nfunction isStructuredGetProductsRejection(response: unknown, toolName?: string, responseAdcpVersion?: string): boolean {\n if (toolName !== 'get_products' || response == null || typeof response !== 'object' || Array.isArray(response)) {\n return false;\n }\n\n const obj = response as Record<string, unknown>;\n const effectiveVersion = typeof obj.adcp_version === 'string' ? obj.adcp_version : responseAdcpVersion;\n const versionMatch =\n typeof effectiveVersion === 'string' ? /^v?(\\d+)\\.(\\d+)(?:\\.|-|$)/.exec(effectiveVersion.trim()) : null;\n const major = versionMatch?.[1] === undefined ? undefined : Number.parseInt(versionMatch[1], 10);\n const minor = versionMatch?.[2] === undefined ? undefined : Number.parseInt(versionMatch[2], 10);\n const declaresStructuredRejectionVersion =\n major !== undefined && minor !== undefined && (major > 3 || (major === 3 && minor >= 2));\n const suggestionsValid =\n obj.suggestions === undefined ||\n (Array.isArray(obj.suggestions) &&\n obj.suggestions.length >= 1 &&\n obj.suggestions.length <= 20 &&\n obj.suggestions.every(\n suggestion => typeof suggestion === 'string' && suggestion.length >= 1 && suggestion.length <= 1000\n ));\n const forbiddenFields = [\n 'products',\n 'proposals',\n 'errors',\n 'adcp_error',\n 'incomplete',\n 'cache_scope',\n 'filter_diagnostics',\n 'refinement_applied',\n 'unchanged',\n 'wholesale_feed_version',\n 'pricing_version',\n 'pagination',\n ];\n return (\n declaresStructuredRejectionVersion &&\n obj.status === 'rejected' &&\n typeof obj.reason === 'string' &&\n obj.reason.length >= 1 &&\n obj.reason.length <= 2000 &&\n suggestionsValid &&\n obj.success !== false &&\n obj.error == null &&\n typeof obj.error_code !== 'string' &&\n forbiddenFields.every(field => !hasOwnField(obj, field))\n );\n}\n\nexport function isTerminalAdcpError(response: unknown, toolName?: string, responseAdcpVersion?: string): boolean {\n const obj = response as Record<string, unknown> | null | undefined;\n if (isStructuredGetProductsRejection(obj, toolName, responseAdcpVersion)) return false;\n if (obj?.status === 'failed' || obj?.status === 'rejected') return true;\n if (obj?.adcp_error && typeof (obj.adcp_error as { code?: unknown }).code === 'string') return true;\n if (typeof obj?.error_code === 'string') {\n return !hasAdvisorySuccessPayload(obj, toolName);\n }\n if (Array.isArray(obj?.errors) && obj.errors.length > 0) {\n return !hasAdvisorySuccessPayload(obj, toolName);\n }\n return false;\n}\n\n/**\n * Check whether an extracted AdCP operation payload represents success.\n * A transport task may be `completed` while its operation payload is terminally\n * unsuccessful, so callers must evaluate both layers.\n */\nexport function isAdcpOperationSuccess(response: unknown, toolName?: string, responseAdcpVersion?: string): boolean {\n const obj = response as Record<string, unknown> | null | undefined;\n return (\n obj?.success !== false &&\n !obj?.error &&\n !obj?.adcp_error &&\n !isTerminalAdcpError(response, toolName, responseAdcpVersion)\n );\n}\n\n/**\n * Extract raw AdCP response from protocol wrapper\n *\n * @param protocolResponse - Raw response from MCP or A2A protocol\n * @param toolName - Optional AdCP tool name for validation\n * @param protocol - Protocol type ('mcp' or 'a2a'), if known. If not provided, will auto-detect.\n * @param options - Optional validation behavior overrides\n * @returns Raw AdCP response data matching schema exactly\n * @throws {Error} If response doesn't match expected schema for the tool\n */\nexport function unwrapProtocolResponse(\n protocolResponse: any,\n toolName?: string,\n protocol?: 'mcp' | 'a2a',\n options?: { filterInvalidProducts?: boolean; responseAdcpVersion?: string }\n): AdCPResponse & { _message?: string } {\n if (!protocolResponse) {\n throw new Error('Protocol response is null or undefined');\n }\n\n // Extract response from protocol wrapper\n let unwrapped: any;\n let mcpExtractionPath: McpExtractionPath | undefined;\n if (protocol === 'mcp') {\n const outcome = unwrapMCPResponse(protocolResponse);\n unwrapped = outcome.result;\n mcpExtractionPath = outcome.extractionPath;\n } else if (protocol === 'a2a') {\n unwrapped = unwrapA2AResponse(protocolResponse);\n } else {\n // Auto-detect protocol if not specified\n if (isMCPResponse(protocolResponse)) {\n const outcome = unwrapMCPResponse(protocolResponse);\n unwrapped = outcome.result;\n mcpExtractionPath = outcome.extractionPath;\n } else if (isA2AResponse(protocolResponse)) {\n unwrapped = unwrapA2AResponse(protocolResponse);\n } else {\n throw new Error('Unable to extract AdCP response from protocol wrapper');\n }\n }\n // Preserve the extraction path across Zod's `safeParse` (which returns a\n // fresh object). `retag` re-attaches the provenance to whichever object we\n // return so the tag survives validation, filtering, and _message merging.\n const retag = <T extends AdCPResponse & { _message?: string }>(value: T): T => {\n if (mcpExtractionPath !== undefined) tagExtractionPath(value, mcpExtractionPath);\n return value;\n };\n\n if (mcpExtractionPath !== undefined) {\n tagExtractionPath(unwrapped, mcpExtractionPath);\n }\n\n // Skip schema validation for error responses — they don't include\n // tool-specific fields like `products`. Handles both AdCP-standard\n // { errors: [...] } and legacy singular { error: \"...\" } patterns.\n if (\n isTerminalAdcpError(unwrapped, toolName, options?.responseAdcpVersion) ||\n (unwrapped?.error && typeof unwrapped.error === 'string')\n ) {\n return retag(unwrapped);\n }\n\n // Validate success responses against tool schema if tool name provided\n if (toolName) {\n const schema = TOOL_RESPONSE_SCHEMAS[toolName];\n if (schema) {\n // Strip _message before validation — it's a text summary added by the unwrapper,\n // not part of the AdCP response schema. Intersection with union schemas fails in Zod v4.\n const { _message: _msg, ...stripped } = unwrapped as Record<string, unknown>;\n // Back-compat: 3.0.x sellers may omit envelope `status` (made REQUIRED\n // in 3.1.0-beta.2). Inject a synthetic status only when the response\n // declares itself as 3.0.x (or carries no version field at all).\n const dataToValidate = prepareResponseForSchemaValidation(\n toolName,\n injectLegacyEnvelopeStatus(stripped, { toolName }),\n options?.responseAdcpVersion\n ) as Record<string, unknown>;\n const result = schema.safeParse(dataToValidate);\n if (!result.success) {\n // When filterInvalidArrayItems is enabled and this is a get_products response,\n // try filtering invalid products individually rather than rejecting the entire response.\n if (options?.filterInvalidProducts && toolName === 'get_products') {\n const filtered = filterInvalidProducts(schema, dataToValidate);\n if (filtered) {\n let validated = filtered as unknown as AdCPResponse & { _message?: string };\n // Strip compat-injected `status` before returning — same rationale as\n // the main success path below. See adcp-client#1961.\n if (!('status' in stripped)) {\n const { status: _s, ...rest } = validated as unknown as Record<string, unknown>;\n validated = rest as unknown as typeof validated;\n } else {\n validated = restoreLegacyMediaBuyStatusForReturn(validated, stripped, dataToValidate, toolName);\n }\n if (!('adcp_version' in stripped)) {\n const { adcp_version: _v, ...rest } = validated as unknown as Record<string, unknown>;\n validated = rest as unknown as typeof validated;\n }\n if (_msg) validated._message = _msg as string;\n return retag(validated);\n }\n }\n\n // Union schemas produce a generic \"Invalid input\" at (root).\n // Try each variant to surface the actual missing/invalid fields.\n const firstIssue = result.error.issues[0];\n const isUnionError = result.error.issues.length === 1 && firstIssue?.code === 'invalid_union';\n\n if (isUnionError) {\n const betterErrors = getBestUnionErrors(schema, dataToValidate);\n if (betterErrors && betterErrors.length > 0) {\n const bestMessage = betterErrors.map(e => `${e.path}: ${e.message}`).join('; ');\n throw new ResponseSchemaValidationError(toolName, result.error.issues, dataToValidate, bestMessage);\n }\n }\n\n throw new ResponseSchemaValidationError(toolName, result.error.issues, dataToValidate, result.error.message);\n }\n\n // Re-attach _message after validation so it's available for text summaries.\n // Strip any compat-injected `status` before returning: the injection was\n // purely to let a 3.0.x seller pass the 3.1 envelope schema; propagating\n // it into taskResult.data causes storyboard field_value_or_absent checks\n // on the deprecated legacy `status` field to fail with a false positive\n // (sees injected \"completed\" instead of absent). See adcp-client#1961.\n let validated = result.data as AdCPResponse & { _message?: string };\n if (!('status' in stripped)) {\n const { status: _s, ...rest } = validated as unknown as Record<string, unknown>;\n validated = rest as unknown as typeof validated;\n } else {\n validated = restoreLegacyMediaBuyStatusForReturn(validated, stripped, dataToValidate, toolName);\n }\n if (!('adcp_version' in stripped)) {\n const { adcp_version: _v, ...rest } = validated as unknown as Record<string, unknown>;\n validated = rest as unknown as typeof validated;\n }\n if (_msg) validated._message = _msg as string;\n return retag(validated);\n }\n }\n\n // Return unwrapped response (no validation) — already tagged above.\n return unwrapped as AdCPResponse;\n}\n\nfunction restoreLegacyMediaBuyStatusForReturn<T extends AdCPResponse & { _message?: string }>(\n validated: T,\n original: Record<string, unknown>,\n compat: Record<string, unknown>,\n toolName: string\n): T {\n if (\n (toolName === 'create_media_buy' || toolName === 'update_media_buy') &&\n typeof original.media_buy_id === 'string' &&\n typeof original.status === 'string' &&\n compat.status === 'completed' &&\n typeof compat.media_buy_status === 'string'\n ) {\n return normalizeLegacyMediaBuyStatusForReturn(\n { ...validated, status: original.status } as unknown as Record<string, unknown>,\n { toolName }\n ) as unknown as T;\n }\n return normalizeLegacyMediaBuyStatusForReturn(validated as unknown as Record<string, unknown>, {\n toolName,\n }) as unknown as T;\n}\n\n/**\n * Filter invalid products from a get_products response.\n *\n * Validates each product individually against the ProductSchema,\n * keeps only valid ones, and re-validates the full response.\n * Returns the filtered response, or null if filtering can't help.\n */\nfunction filterInvalidProducts(schema: z.ZodType, data: Record<string, unknown>): Record<string, unknown> | null {\n const products = data.products;\n if (!Array.isArray(products)) return null;\n\n // `products` is optional on `get_products` since AdCP 3.1.0-beta.3 (the\n // `unchanged: true` wholesale-feed branch legitimately omits it). The Zod\n // shape is now `ZodOptional<ZodArray<...>>` rather than the bare\n // `ZodArray<...>` we used to see. Unwrap a level of `ZodOptional` /\n // `ZodNullable` before the array check so the helper still finds the\n // element schema.\n let ProductSchema = (schema as z.ZodObject<any>).shape?.products;\n if (ProductSchema instanceof z.ZodOptional || ProductSchema instanceof z.ZodNullable) {\n ProductSchema = (ProductSchema as z.ZodOptional<any>).unwrap();\n }\n if (!(ProductSchema instanceof z.ZodArray)) return null;\n\n const elementSchema = (ProductSchema as z.ZodArray<any>).element;\n const validProducts: unknown[] = [];\n for (const product of products) {\n if (elementSchema.safeParse(product).success) {\n validProducts.push(product);\n }\n }\n\n // Nothing was filtered — all products are individually valid, so the validation\n // error is at the response level (not caused by invalid products). Fall through\n // to the normal error path.\n if (validProducts.length === products.length) return null;\n\n const filtered = { ...data, products: validProducts };\n const revalidated = schema.safeParse(filtered);\n if (revalidated.success) {\n const droppedCount = products.length - validProducts.length;\n console.warn(\n `[adcp-client] Filtered ${droppedCount} invalid product(s) from get_products response (${validProducts.length} valid, ${products.length} total)`\n );\n return revalidated.data as Record<string, unknown>;\n }\n\n return null;\n}\n\n/**\n * Check if response is MCP format\n */\nfunction isMCPResponse(response: any): boolean {\n return 'structuredContent' in response || 'isError' in response || 'content' in response;\n}\n\n/**\n * Check if response is A2A format.\n * A2A errors are JSON-RPC objects ({ code, message }), not strings.\n */\nfunction isA2AResponse(response: any): boolean {\n return 'result' in response || ('error' in response && typeof response.error === 'object' && response.error !== null);\n}\n\n/**\n * MCP response extraction provenance. Set as a non-enumerable `_extraction_path`\n * property on the unwrapped object so the storyboard runner can surface it in\n * its runner-output contract without leaking into JSON-serialized or spread\n * responses. See `src/lib/testing/storyboard/types.ts` → `RunnerExtractionPath`.\n */\nexport type McpExtractionPath = 'structured_content' | 'text_fallback' | 'error' | 'none';\n\nexport const EXTRACTION_PATH_KEY = '_extraction_path' as const;\n\ninterface McpUnwrapOutcome {\n result: AdCPResponse;\n extractionPath: McpExtractionPath;\n}\n\n/**\n * Unwrap MCP response - all MCP logic in one place.\n *\n * Also records which branch produced the parsed response (structuredContent\n * vs text content) so downstream tooling can tell a runner extraction bug\n * apart from an agent bug.\n */\nfunction unwrapMCPResponse(response: any): McpUnwrapOutcome {\n // MCP error response — preserve full structured data (context, ext, adcp_error)\n if (response.isError === true) {\n // L3: structuredContent has the full error payload.\n // Trust boundary: this is untrusted agent content passed through as-is.\n // Consumers must sanitize fields like suggestion/details before rendering.\n if (response.structuredContent && typeof response.structuredContent === 'object') {\n return { result: response.structuredContent as AdCPResponse, extractionPath: 'error' };\n }\n\n // L2: JSON in text content\n if (Array.isArray(response.content)) {\n for (const item of response.content) {\n if (item?.type === 'text' && item.text) {\n try {\n const parsed = JSON.parse(item.text);\n if (parsed?.adcp_error && typeof parsed.adcp_error.code === 'string') {\n return { result: parsed as AdCPResponse, extractionPath: 'error' };\n }\n } catch {\n // not JSON, continue to raw text fallback\n }\n }\n }\n }\n\n // L1: Raw text fallback — no structured data available\n const errorContent = Array.isArray(response.content)\n ? response.content.find((c: any) => c.type === 'text')?.text\n : response.content?.text || 'Unknown error';\n\n return {\n result: {\n adcp_error: {\n code: ERROR_CODES.MCP_ERROR,\n message: errorContent || 'MCP tool call failed',\n synthetic: true,\n },\n } as unknown as AdCPResponse,\n extractionPath: 'error',\n };\n }\n\n // MCP success response with structuredContent\n if (response.structuredContent !== undefined && response.structuredContent !== null) {\n const data = response.structuredContent;\n\n // Extract text messages from content field (parallel to A2A TextParts)\n const textMessages: string[] = [];\n if (response.content && Array.isArray(response.content)) {\n for (const item of response.content) {\n if (item.type === 'text' && item.text) {\n textMessages.push(item.text);\n }\n }\n }\n\n // Include text messages if present (same pattern as A2A)\n if (textMessages.length > 0) {\n return {\n result: {\n ...data,\n _message: textMessages.join('\\n'),\n },\n extractionPath: 'structured_content',\n };\n }\n\n return { result: data, extractionPath: 'structured_content' };\n }\n\n // MCP text content fallback (try parsing as JSON)\n if (response.content && Array.isArray(response.content)) {\n const textContent = response.content.find((c: any) => c.type === 'text');\n if (textContent?.text) {\n try {\n return { result: JSON.parse(textContent.text), extractionPath: 'text_fallback' };\n } catch {\n // Include snippet of text for debugging (max 100 chars)\n const snippet = textContent.text.length > 100 ? textContent.text.substring(0, 100) + '...' : textContent.text;\n\n return {\n result: {\n // AdCP 3.1.0-beta.2+: envelope `status` is REQUIRED on every\n // response. Synthetic error envelopes synthesized by the SDK\n // when the wire doesn't carry a valid AdCP payload need the\n // same. `failed` matches the error semantics of this branch.\n status: 'failed' as const,\n errors: [\n {\n code: ERROR_CODES.INVALID_RESPONSE,\n message: `Response does not contain structured AdCP data. Text content: \"${snippet}\"`,\n },\n ],\n } as AdCPResponse,\n extractionPath: 'text_fallback',\n };\n }\n }\n }\n\n throw new Error('Invalid MCP response format');\n}\n\n/**\n * Attach the extraction path to an unwrapped object as a non-enumerable\n * property. Non-enumerable so `JSON.stringify`, `Object.keys`, and spread\n * ignore it — the storyboard runner reads it via a direct property access\n * but the rest of the system sees the unwrapped data unchanged.\n */\nfunction tagExtractionPath(result: AdCPResponse, path: McpExtractionPath): AdCPResponse {\n if (result === null || typeof result !== 'object') return result;\n try {\n Object.defineProperty(result, EXTRACTION_PATH_KEY, {\n value: path,\n enumerable: false,\n configurable: true,\n writable: true,\n });\n } catch {\n // Frozen / sealed objects reject defineProperty; drop the tag silently —\n // the runner's fallback inference in extractionFromTaskResult still works.\n }\n return result;\n}\n\n/**\n * Read the extraction path from an unwrapped AdCP response, or `undefined`\n * if the response did not originate from an MCP unwrap path.\n */\nexport function readExtractionPath(data: unknown): McpExtractionPath | undefined {\n if (data === null || typeof data !== 'object') return undefined;\n const path = (data as Record<string, unknown>)[EXTRACTION_PATH_KEY];\n return typeof path === 'string' ? (path as McpExtractionPath) : undefined;\n}\n\n/**\n * Unwrap A2A response\n *\n * Called for terminal task states (\"completed\", \"failed\", \"rejected\",\n * \"canceled\"). All four carry the same artifact + DataPart envelope per\n * AdCP transport-errors §A2A Binding — failed tasks place `adcp_error`\n * into the DataPart alongside an optional terse TextPart.\n *\n * Intermediate statuses (\"working\", \"submitted\", \"input-required\",\n * \"auth-required\") do not yet have AdCP artifacts and are rejected here\n * so callers handle them at the response level.\n */\nconst TERMINAL_A2A_STATES: ReadonlySet<string> = new Set(['completed', 'failed', 'rejected', 'canceled']);\n\n/**\n * Detect whether a response carries a spec-compliant terminal-state Task\n * with a structured DataPart artifact. Mirrors the protocol-layer guard in\n * `src/lib/protocols/a2a.ts` (`hasTerminalTaskWithDataArtifact`) so the\n * unwrapper defers to the canonical envelope when a non-conformant seller\n * surfaces both a top-level transport error and the AdCP artifact.\n */\nfunction hasTerminalTaskWithDataArtifact(response: unknown): boolean {\n if (!response || typeof response !== 'object') return false;\n const result = (response as { result?: unknown }).result;\n if (!result || typeof result !== 'object') return false;\n const r = result as { kind?: unknown; status?: unknown; artifacts?: unknown };\n if (r.kind !== 'task') return false;\n const status = r.status as { state?: unknown } | undefined;\n if (typeof status?.state !== 'string' || !TERMINAL_A2A_STATES.has(status.state)) return false;\n return getLatestA2ADataPartFromResponse(response) !== undefined;\n}\n\nfunction unwrapA2AResponse(response: any): AdCPResponse {\n const taskState = response.result?.status?.state;\n if (taskState && !TERMINAL_A2A_STATES.has(taskState)) {\n throw new Error(\n `Cannot unwrap A2A response with intermediate status: ${taskState}. ` +\n 'Only terminal responses (completed, failed, rejected, canceled) should be unwrapped.'\n );\n }\n // A2A error response (JSON-RPC error). adcp-client#1575: when a\n // non-conformant seller surfaces both a top-level JSON-RPC error AND a\n // terminal-state Task with a structured DataPart artifact, the artifact\n // is canonical per AdCP transport-errors §A2A Binding — defer to the\n // artifact extraction below. Mirrors the protocol-layer guard at\n // `src/lib/protocols/a2a.ts` so the two layers stay symmetric and\n // direct callers (storyboard fixtures, cached responses, webhook\n // payloads) inherit the same defensive behavior.\n if (response.error && !hasTerminalTaskWithDataArtifact(response)) {\n return {\n // AdCP 3.1.0-beta.2+: envelope `status` is REQUIRED. Synthetic error\n // envelopes for A2A JSON-RPC failures carry `failed` to match the\n // error semantics.\n status: 'failed' as const,\n errors: [\n {\n code: response.error.code?.toString() || ERROR_CODES.UNKNOWN,\n message: response.error.message || 'A2A JSON-RPC error occurred',\n ...(response.error.data && { data: response.error.data }),\n },\n ],\n } as AdCPResponse;\n }\n\n // A2A terminal response — same shape regardless of success or failure:\n // - MUST have result.artifacts array with at least one artifact\n // - Artifact MUST have at least one DataPart (kind: 'data') with the AdCP payload\n // (success payload for `completed`, `adcp_error` envelope for `failed`)\n // - MAY have TextParts (kind: 'text') with optional messages\n\n const artifacts = response.result?.artifacts;\n if (!Array.isArray(artifacts) || artifacts.length === 0) {\n throw new Error('A2A response must have at least one artifact');\n }\n\n const artifact = artifacts[artifacts.length - 1];\n if (!artifact || typeof artifact !== 'object' || Array.isArray(artifact)) {\n throw new Error('A2A response must have at least one artifact');\n }\n\n if (!('parts' in artifact) || !Array.isArray((artifact as { parts?: unknown }).parts)) {\n throw new Error('A2A artifact missing parts array');\n }\n\n // Extract DataPart (required) and TextParts (optional). Use the shared\n // latest structured DataPart helper so parser and validator agree.\n const extracted = getLatestA2ADataPartFromResponse(response);\n if (!extracted) {\n throw new Error('A2A response must have a DataPart with AdCP data');\n }\n\n const parts = (artifact as { parts: unknown[] }).parts;\n const textParts = parts\n .filter((p: any) => p && typeof p === 'object' && p.kind === 'text' && p.text)\n .map((p: any) => p.text);\n\n // Unwrap nested response field if present (some agents wrap AdCP responses)\n let data: any = extracted.data;\n if (data?.response && typeof data.response === 'object' && !Array.isArray(data.response)) {\n data = data.response;\n }\n\n // Return data with optional message\n if (textParts.length > 0) {\n return {\n ...data,\n _message: textParts.join('\\n'),\n };\n }\n\n return data;\n}\n\n/**\n * Check if a response is an AdCP error response.\n * Recognizes both `{ adcp_error: { code: string } }` (MCP structured errors)\n * and `{ errors: [{ code, message }] }` (legacy/A2A format).\n *\n * This helper is structural and intentionally does not know which tool\n * produced the payload. For AdCP 3.1 success/submitted payloads that can\n * carry advisory `errors[]`, prefer {@link isTerminalAdcpError} with a\n * `toolName`.\n */\nexport function isAdcpError(response: any): boolean {\n if (Array.isArray(response?.errors) && response.errors.length > 0) return true;\n if (response?.adcp_error && typeof response.adcp_error.code === 'string') return true;\n return false;\n}\n\n/**\n * Check if a response is an AdCP success response for a specific task\n *\n * Uses Zod schemas to validate the response structure matches the expected\n * success response format for the given task.\n */\nexport function isAdcpSuccess(response: any, taskName: string, responseAdcpVersion?: string): boolean {\n // First check if it's an error response\n if (isTerminalAdcpError(response, taskName, responseAdcpVersion)) {\n return false;\n }\n\n // Try to validate with Zod schema if available\n const schema = TOOL_RESPONSE_SCHEMAS[taskName];\n if (schema) {\n const { _message: _, ...stripped } = (response ?? {}) as Record<string, unknown>;\n // Apply the same 3.0.x envelope-status leniency as unwrapProtocolResponse\n // so success detection stays consistent across the two entry points.\n const dataToValidate = prepareResponseForSchemaValidation(\n taskName,\n injectLegacyEnvelopeStatus(stripped, { toolName: taskName }),\n responseAdcpVersion\n );\n const result = schema.safeParse(dataToValidate);\n return result.success;\n }\n\n // Unknown task - can't validate, assume success if no errors\n return true;\n}\n"],"mappings":"AAOA,SAAS,SAAS;AAClB,SAAS,0BAA0B;AAKnC,MAAM,cAAc;AAAA,EAClB,WAAW;AAAA,EACX,kBAAkB;AAAA,EAClB,SAAS;AACX;AAiBA,SAAS,oCAAoC,6BAA6B;AAC1E,SAAS,4BAA4B,8CAA8C;AACnF,SAAS,wCAAwC;AAwB1C,MAAM,sCAAsC,MAAM;AAAA,EAC9C,OAAO;AAAA;AAAA,EAEP;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EAET,YAAY,UAAkB,QAA4B,MAAe,gBAAwB;AAC/F,UAAM,kCAAkC,QAAQ,KAAK,cAAc,EAAE;AACrE,SAAK,WAAW;AAChB,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EACd;AACF;AAqBA,MAAM,uCAAiG;AAAA,EACrG,uBAAuB,CAAC,CAAC,QAAQ,qBAAqB,CAAC;AAAA,EACvD,eAAe,CAAC,CAAC,UAAU,CAAC;AAAA,EAC5B,eAAe,CAAC,CAAC,UAAU,CAAC;AAAA,EAC5B,iBAAiB,CAAC,CAAC,UAAU,CAAC;AAAA,EAC9B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,GAAG,SAAS,CAmD9B;AAuCD,4EAA4E;AAC5E,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,MAAqB,GAAG,MAAM,EAAE,CAG1E;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,GAAE,MAAqB,GAAG,SAAS,MAAM,EAAE,CAMxF;AAED,8DAA8D;AAC9D,OAAO,EAAE,sBAAsB,EAAE,CAAC;AAElC;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAOxD;AA0GD,iFAAiF;AACjF,wBAAgB,wBAAwB,CACtC,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,OAAO,GAAE,MAAqB,GAC7B,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,SAAS,CAE/C;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAS7D;AAkDD,MAAM,WAAW,gBAAgB;IAC/B,gFAAgF;IAChF,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,qEAAqE;IACrE,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;;;GAQG;AACH,wBAAgB,2BAA2B,CACzC,QAAQ,EAAE,MAAM,EAChB,OAAO,GAAE,MAAqB,GAC7B,SAAS,gBAAgB,EAAE,CAuI7B"}
@@ -171,6 +171,7 @@ function compareBundleNamesDesc(a, b) {
171
171
  return b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" });
172
172
  }
173
173
  const states = /* @__PURE__ */ new Map();
174
+ const schemaRefValidators = /* @__PURE__ */ new Map();
174
175
  const externalSchemaRoots = /* @__PURE__ */ new Map();
175
176
  const scopedExternalSchemaRoots = new import_async_hooks.AsyncLocalStorage();
176
177
  function stateCacheKey(bundleKey, root) {
@@ -180,6 +181,9 @@ function clearStatesForBundle(bundleKey) {
180
181
  for (const [stateKey, state] of states) {
181
182
  if (state.version === bundleKey) states.delete(stateKey);
182
183
  }
184
+ for (const cacheKey of schemaRefValidators.keys()) {
185
+ if (cacheKey.startsWith(`${bundleKey}\0`)) schemaRefValidators.delete(cacheKey);
186
+ }
183
187
  }
184
188
  function hasSchemaRootShape(root) {
185
189
  if (!(0, import_fs.existsSync)(root)) return false;
@@ -493,23 +497,27 @@ function getToolSchemaDocument(toolName, direction, version = import_version.ADC
493
497
  };
494
498
  }
495
499
  function getSchemaValidatorByRef(schemaRef, version = import_version.ADCP_VERSION) {
496
- const s = ensureInit(version);
500
+ const bundleKey = resolveBundleKey(version);
501
+ const root = resolveSchemaRoot(version);
497
502
  const normalized = normalizeSchemaRef(schemaRef);
498
503
  if (!normalized) return void 0;
499
- const cacheKey = `schema-ref::${normalized}`;
500
- const cached = s.validators.get(cacheKey);
504
+ const cacheKey = `${stateCacheKey(bundleKey, root)}\0schema-ref::${normalized}`;
505
+ const cached = schemaRefValidators.get(cacheKey);
501
506
  if (cached) return cached;
502
- const file = import_path.default.join(s.root, normalized);
507
+ const file = import_path.default.join(root, normalized);
503
508
  if (!(0, import_fs.existsSync)(file)) return void 0;
504
509
  const ajv = new import_ajv.default({
505
510
  strict: false,
506
- allErrors: true,
511
+ // Schema-ref validators process remote webhook payloads. Fail on the
512
+ // first violation so deeply nested hostile input cannot amplify error
513
+ // collection into CPU or memory exhaustion.
514
+ allErrors: false,
507
515
  allowUnionTypes: true
508
516
  });
509
517
  (0, import_ajv_formats.default)(ajv);
510
518
  const dependencySchemas = [];
511
519
  const registeredIds = /* @__PURE__ */ new Set();
512
- for (const schemaFile of walkJsonFiles(s.root)) {
520
+ for (const schemaFile of walkJsonFiles(root)) {
513
521
  if (schemaFile.includes(`${import_path.default.sep}bundled${import_path.default.sep}`)) continue;
514
522
  if ([...TRANSPORT_PROJECTION_DIRECTORIES].some((directory) => schemaFile.includes(`${import_path.default.sep}${directory}${import_path.default.sep}`))) {
515
523
  continue;
@@ -526,7 +534,7 @@ function getSchemaValidatorByRef(schemaRef, version = import_version.ADCP_VERSIO
526
534
  }
527
535
  const rawSchema = loadJson(file);
528
536
  const compiled = ajv.compile(rawSchema);
529
- s.validators.set(cacheKey, compiled);
537
+ schemaRefValidators.set(cacheKey, compiled);
530
538
  return compiled;
531
539
  }
532
540
  function normalizeSchemaRef(schemaRef) {
@@ -643,6 +651,7 @@ function _resetValidationLoader(version) {
643
651
  mcpToolSummaryCache.clear();
644
652
  if (version === void 0) {
645
653
  states.clear();
654
+ schemaRefValidators.clear();
646
655
  } else {
647
656
  clearStatesForBundle(resolveBundleKey(version));
648
657
  }