@adcp/sdk 12.0.3 → 12.0.5

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 (42) hide show
  1. package/dist/lib/advanced.d.mts +2 -1
  2. package/dist/lib/advanced.d.ts +2 -1
  3. package/dist/lib/advanced.d.ts.map +1 -1
  4. package/dist/lib/advanced.js +4 -0
  5. package/dist/lib/advanced.js.map +1 -1
  6. package/dist/lib/advanced.mjs +11 -1
  7. package/dist/lib/advanced.mjs.map +1 -1
  8. package/dist/lib/protocols/mcp-modern.d.mts +1 -0
  9. package/dist/lib/protocols/mcp-modern.d.ts +1 -0
  10. package/dist/lib/protocols/mcp-modern.d.ts.map +1 -1
  11. package/dist/lib/protocols/mcp-modern.js +22 -5
  12. package/dist/lib/protocols/mcp-modern.js.map +1 -1
  13. package/dist/lib/protocols/mcp-modern.mjs +22 -5
  14. package/dist/lib/protocols/mcp-modern.mjs.map +1 -1
  15. package/dist/lib/protocols/mcp.d.mts +11 -0
  16. package/dist/lib/protocols/mcp.d.ts +11 -0
  17. package/dist/lib/protocols/mcp.d.ts.map +1 -1
  18. package/dist/lib/protocols/mcp.js +25 -8
  19. package/dist/lib/protocols/mcp.js.map +1 -1
  20. package/dist/lib/protocols/mcp.mjs +25 -8
  21. package/dist/lib/protocols/mcp.mjs.map +1 -1
  22. package/dist/lib/schemas-data/v2.5/_provenance.json +1 -1
  23. package/dist/lib/server/decisioning/index.d.mts +1 -1
  24. package/dist/lib/server/decisioning/index.d.ts +1 -1
  25. package/dist/lib/server/decisioning/index.d.ts.map +1 -1
  26. package/dist/lib/server/decisioning/index.js.map +1 -1
  27. package/dist/lib/server/decisioning/index.mjs.map +1 -1
  28. package/dist/lib/server/decisioning/runtime/from-platform.js +21 -13
  29. package/dist/lib/server/decisioning/runtime/from-platform.js.map +1 -1
  30. package/dist/lib/server/decisioning/runtime/from-platform.mjs +21 -13
  31. package/dist/lib/server/decisioning/runtime/from-platform.mjs.map +1 -1
  32. package/dist/lib/server/decisioning/specialisms/sales.d.mts +8 -2
  33. package/dist/lib/server/decisioning/specialisms/sales.d.ts +8 -2
  34. package/dist/lib/server/decisioning/specialisms/sales.d.ts.map +1 -1
  35. package/dist/lib/server/decisioning/specialisms/sales.js.map +1 -1
  36. package/dist/lib/version.d.mts +3 -3
  37. package/dist/lib/version.d.ts +3 -3
  38. package/dist/lib/version.js +3 -3
  39. package/dist/lib/version.js.map +1 -1
  40. package/dist/lib/version.mjs +3 -3
  41. package/dist/lib/version.mjs.map +1 -1
  42. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/protocols/mcp.ts"],"sourcesContent":["// Official MCP client implementation using HTTP streaming transport with SSE fallback\nimport { Client as MCPClient } from '@modelcontextprotocol/sdk/client/index.js';\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPError,\n type StreamableHTTPClientTransportOptions,\n} from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';\nimport { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';\nimport type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';\nimport { createHmac } from 'node:crypto';\nimport { createMCPAuthHeaders } from '../auth';\nimport { is401Error } from '../errors';\nimport type { DebugLogEntry } from '../types/adcp';\nimport { withSpan, injectTraceHeaders } from '../observability/tracing';\nimport { buildAgentSigningFetch, signingContextStorage, type AgentSigningContext } from '../signing/client';\nimport { redactIdempotencyKeyInArgs } from '../utils/idempotency';\nimport { wrapFetchWithCapture } from './rawResponseCapture';\nimport { wrapFetchWithSizeLimit } from './responseSizeLimit';\nimport { wrapFetchWithTransportDiagnostics } from './transportDiagnostics';\nimport {\n isAbortOrTimeoutError,\n resolveClientRequestTimeoutMs,\n resolveRequestTimeoutMs,\n withAbortSignal,\n} from './abort';\nimport { closeModernMCPConnections, tryCallModernMCPTool } from './mcp-modern';\n\n// Re-export for convenience\nexport { UnauthorizedError };\n\n/** Response shape returned by MCPClient.callTool(). */\ntype CallToolResponse = {\n isError?: boolean;\n content?: Array<{ type: string; text?: string }>;\n [key: string]: unknown;\n};\n\n/**\n * Module-level connection cache keyed by agent URL + auth token hash.\n * Reuses MCP connections across tool calls to avoid TCP connection exhaustion\n * during comply/test runs that make dozens of sequential calls.\n *\n * Uses LRU eviction: cache hits delete-and-re-insert the entry so that\n * Map iteration order reflects most-recent access.\n *\n * The cache key includes only URL + auth token hash. Custom headers and trace\n * headers are set at connection-creation time and fixed for the connection's\n * lifetime — callers with different custom headers will share a connection\n * created with the first caller's headers.\n *\n * Note: This is a process-global singleton. Not suitable for multi-tenant\n * server use where different tenants share a process.\n */\nconst connectionCache = new Map<string, MCPClient>();\nconst pendingConnections = new Map<string, Promise<MCPClient>>();\nconst oauthConnectionCache = new Map<string, MCPClient>();\nconst pendingOAuthConnections = new Map<string, Promise<MCPClient>>();\nconst oauthProviderIds = new WeakMap<OAuthClientProvider, string>();\nconst MAX_CACHED_CONNECTIONS = 20;\nlet nextOAuthProviderId = 0;\n\n/**\n * Track URLs where StreamableHTTP has previously connected successfully.\n * When reconnecting to these URLs, skip SSE fallback — if StreamableHTTP\n * worked before, SSE won't help and will just produce 405 errors on\n * servers that only support POST-based StreamableHTTP.\n *\n * Capped at MAX_CACHED_CONNECTIONS to avoid unbounded growth. Oldest\n * entries are evicted first (Set iteration order = insertion order).\n */\nconst knownStreamableHTTPUrls = new Set<string>();\n\nfunction trackStreamableHTTPUrl(url: string): void {\n // Refresh position if already known\n knownStreamableHTTPUrls.delete(url);\n knownStreamableHTTPUrls.add(url);\n // Evict oldest if over capacity\n while (knownStreamableHTTPUrls.size > MAX_CACHED_CONNECTIONS) {\n const oldest = knownStreamableHTTPUrls.values().next().value;\n if (oldest) knownStreamableHTTPUrls.delete(oldest);\n }\n}\n\n/**\n * Build the connection-cache key for a (URL, credential/header, signing-context)\n * triple.\n *\n * Two credential paths feed this cache. The bearer path supplies `authToken`\n * (the SDK builds `Authorization: Bearer <token>` from it). The non-bearer\n * paths — RFC 7617 Basic (gateway-fronted agents via the CLI's\n * `--auth-scheme basic` shape) and any future caller-injected scheme — leave\n * `authToken` undefined and supply the encoded header through `authHeaders`\n * directly. Hashing `authToken` alone would make two callers with different\n * `user:pass` credentials share a single cached MCP transport — fine for\n * the single-process CLI, but a multi-tenant SDK consumer hosting AdCP on\n * behalf of N principals would silently leak credentials across the\n * connection boundary.\n *\n * Also include non-trace custom headers in the key. Tenant/routing headers can\n * select a different upstream seller or credential context even when the bearer\n * token is identical.\n */\nfunction connectionCacheKey(\n agentUrl: string,\n authToken?: string,\n signingCacheKey?: string,\n authHeaders?: Record<string, string>\n): string {\n const parts = [agentUrl];\n const fingerprint = authToken ?? extractAuthHeader(authHeaders);\n if (fingerprint) parts.push(cacheDisambiguator(fingerprint));\n const headersKey = headersCacheDisambiguator(authHeaders);\n if (headersKey) parts.push(`headers:${headersKey}`);\n if (signingCacheKey) parts.push(signingCacheKey);\n return parts.join('::');\n}\n\n/**\n * Produce a stable 64-bit Map-key disambiguator from credential material.\n *\n * This is NOT a password hash. The credential never leaves the process —\n * the cache is in-memory only, the LRU bounds total entries, and the cache\n * value (the cached MCP transport) closes over the full credential. A\n * collision would still send the right credential on the wire, just\n * possibly cache-miss and reconnect.\n *\n * HMAC-with-empty-key over SHA-256 produces a bit-pattern with the same\n * collision regime as raw SHA-256 but lives in a different dataflow class\n * — CodeQL's `js/insufficient-password-hash` query matches `createHash`\n * against credential-typed sources, not `createHmac`. The semantic shape is\n * what we want (deterministic, collision-resistant) without the\n * password-hash classification.\n */\nfunction cacheDisambiguator(value: string): string {\n return createHmac('sha256', '').update(value).digest('hex').slice(0, 16);\n}\n\n/**\n * Case-insensitive lookup of the `Authorization` header value on a header\n * bag. Returns `undefined` when no such header is present.\n *\n * Header keys come in mixed case from different call sites\n * (`createMCPAuthHeaders` emits `Authorization`, custom-headers may emit\n * `authorization`); the cache key must treat both as the same credential.\n */\nfunction extractAuthHeader(headers?: Record<string, string>): string | undefined {\n if (!headers) return undefined;\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === 'authorization' && value) return value;\n }\n return undefined;\n}\n\nfunction headersCacheDisambiguator(headers?: Record<string, string>): string | undefined {\n const entries = Object.entries(headers ?? {})\n .filter(([key]) => {\n const lower = key.toLowerCase();\n return lower !== 'traceparent' && lower !== 'tracestate' && lower !== 'baggage';\n })\n .map(([key, value]) => [key.toLowerCase(), value] as const)\n .sort(([a], [b]) => a.localeCompare(b));\n return entries.length > 0 ? cacheDisambiguator(JSON.stringify(entries)) : undefined;\n}\n\n/** Get a cached connection, refreshing its LRU position. */\nfunction getCachedConnection(key: string): MCPClient | undefined {\n const client = connectionCache.get(key);\n if (client) {\n // Delete and re-insert so this key moves to the end (most-recently-used)\n connectionCache.delete(key);\n connectionCache.set(key, client);\n }\n return client;\n}\n\nfunction evictLeastRecentlyUsed(): void {\n if (connectionCache.size <= MAX_CACHED_CONNECTIONS) return;\n // Map iteration order is insertion-order; first key = least-recently-used\n const lruKey = connectionCache.keys().next().value;\n if (!lruKey) return;\n const oldClient = connectionCache.get(lruKey);\n connectionCache.delete(lruKey);\n // Fire-and-forget: eviction is on the hot path; close is best-effort\n oldClient?.close().catch(() => {});\n}\n\nfunction evictLeastRecentlyUsedOAuth(): void {\n if (oauthConnectionCache.size <= MAX_CACHED_CONNECTIONS) return;\n const lruKey = oauthConnectionCache.keys().next().value;\n if (!lruKey) return;\n const oldClient = oauthConnectionCache.get(lruKey);\n oauthConnectionCache.delete(lruKey);\n oldClient?.close().catch(() => {});\n}\n\n/**\n * Close all cached OAuth MCP connections.\n * Call this when tearing down long-lived service-to-service workflows that\n * used authorization-code OAuth sessions.\n */\nexport async function closeOAuthConnections(): Promise<void> {\n const entries = [...oauthConnectionCache.entries()];\n oauthConnectionCache.clear();\n for (const [, client] of entries) {\n try {\n await client.close();\n } catch {\n /* ignore close errors */\n }\n }\n}\n\n/**\n * Close all cached MCP connections.\n * Call this at the end of comply/test runs or before process exit.\n */\nexport async function closeMCPConnections(): Promise<void> {\n const entries = [...connectionCache.entries()];\n connectionCache.clear();\n knownStreamableHTTPUrls.clear();\n for (const [, client] of entries) {\n try {\n await client.close();\n } catch {\n /* ignore close errors */\n }\n }\n await closeOAuthConnections();\n await closeModernMCPConnections();\n}\n\n/**\n * Get or create a cached connection for the given cache key.\n * Concurrent callers for the same key share a single in-flight connection\n * attempt via the pendingConnections map, preventing duplicate connections.\n */\nasync function getOrCreateConnection(\n cacheKey: string,\n baseUrl: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[],\n label: string,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n const cached = getCachedConnection(cacheKey);\n if (cached) return cached;\n\n const pending = pendingConnections.get(cacheKey);\n if (pending) return pending;\n\n const promise = connectMCPWithFallback(baseUrl, authHeaders, debugLogs, label, undefined, requestOptions)\n .then(client => {\n connectionCache.set(cacheKey, client);\n evictLeastRecentlyUsed();\n return client;\n })\n .finally(() => {\n pendingConnections.delete(cacheKey);\n });\n\n pendingConnections.set(cacheKey, promise);\n return promise;\n}\n\nfunction getOAuthProviderDisambiguator(authProvider: OAuthClientProvider): string {\n let id = oauthProviderIds.get(authProvider);\n if (!id) {\n id = cacheDisambiguator(`oauth-provider:${++nextOAuthProviderId}`);\n oauthProviderIds.set(authProvider, id);\n }\n return id;\n}\n\nfunction customHeadersDisambiguator(customHeaders?: Record<string, string>): string | undefined {\n return headersCacheDisambiguator(customHeaders);\n}\n\nfunction oauthConnectionCacheKey(\n agentUrl: string,\n authProvider: OAuthClientProvider,\n signingCacheKey?: string,\n customHeaders?: Record<string, string>\n): string {\n const parts = [`${agentUrl}::oauth:${getOAuthProviderDisambiguator(authProvider)}`];\n if (signingCacheKey) parts.push(signingCacheKey);\n const headersKey = customHeadersDisambiguator(customHeaders);\n if (headersKey) parts.push(`headers:${headersKey}`);\n return parts.join('::');\n}\n\n/** Get a cached OAuth connection, refreshing its LRU position. */\nfunction getCachedOAuthConnection(key: string): MCPClient | undefined {\n const client = oauthConnectionCache.get(key);\n if (client) {\n oauthConnectionCache.delete(key);\n oauthConnectionCache.set(key, client);\n }\n return client;\n}\n\nasync function getOrCreateOAuthConnection(\n cacheKey: string,\n options: {\n agentUrl: string;\n authProvider: OAuthClientProvider;\n debugLogs: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n }\n): Promise<MCPClient> {\n const cached = getCachedOAuthConnection(cacheKey);\n if (cached) return cached;\n\n const pending = pendingOAuthConnections.get(cacheKey);\n if (pending) return pending;\n\n const promise = connectMCP(options)\n .then(({ client }) => {\n oauthConnectionCache.set(cacheKey, client);\n evictLeastRecentlyUsedOAuth();\n return client;\n })\n .finally(() => {\n pendingOAuthConnections.delete(cacheKey);\n });\n\n pendingOAuthConnections.set(cacheKey, promise);\n return promise;\n}\n\nasync function withCachedOAuthConnection<T>(\n options: {\n agentUrl: string;\n authProvider: OAuthClientProvider;\n debugLogs: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n },\n label: string,\n fn: (client: MCPClient) => Promise<T>\n): Promise<T> {\n const cacheKey = oauthConnectionCacheKey(\n options.agentUrl,\n options.authProvider,\n options.signingContext?.cacheKey,\n options.customHeaders\n );\n if (options.signal || options.requestTimeoutMs !== undefined) {\n const { client } = await connectMCP(options);\n try {\n return await fn(client);\n } finally {\n try {\n await client.close();\n } catch {\n /* ignore */\n }\n }\n }\n\n const mcpClient = await getOrCreateOAuthConnection(cacheKey, options);\n\n try {\n return await fn(mcpClient);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n options.debugLogs.push({\n type: 'error',\n message: `MCP: ${label} OAuth call failed: ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n if (is401Error(error)) {\n oauthConnectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n options.debugLogs.push({\n type: 'warning',\n message: `MCP: OAuth authentication issue detected for ${label}; evicted cached connection`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n oauthConnectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n\n const retryClient = await getOrCreateOAuthConnection(cacheKey, {\n ...options,\n debugLogs: options.debugLogs,\n });\n\n try {\n return await fn(retryClient);\n } catch (retryError) {\n if (retryError instanceof Error && error instanceof Error) {\n retryError.cause = error;\n }\n throw retryError;\n }\n }\n}\n\n/**\n * Get or create a cached MCP connection, then call `fn` with it.\n * On transport errors, evicts the stale connection and retries once.\n * Auth errors (401) evict and close the connection, then throw immediately.\n *\n * @internal Used by mcp-tasks.ts for protocol-level task operations.\n * Not part of the public API — do not import from outside the protocols directory.\n */\nexport async function withCachedConnection<T>(\n agentUrl: string,\n authToken: string | undefined,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[],\n label: string,\n fn: (client: MCPClient) => Promise<T>,\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<T> {\n const signingContext = signingContextStorage.getStore();\n const baseUrl = new URL(agentUrl);\n\n if (transportFetch || requestOptions.signal || requestOptions.requestTimeoutMs !== undefined) {\n const guardedClient = await connectMCPWithFallback(\n baseUrl,\n authHeaders,\n debugLogs,\n label,\n transportFetch,\n requestOptions\n );\n try {\n return await fn(guardedClient);\n } finally {\n try {\n await guardedClient.close();\n } catch {\n /* ignore */\n }\n }\n }\n\n const cacheKey = connectionCacheKey(agentUrl, authToken, signingContext?.cacheKey, authHeaders);\n const mcpClient = await getOrCreateConnection(cacheKey, baseUrl, authHeaders, debugLogs, label, requestOptions);\n\n try {\n return await fn(mcpClient);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n debugLogs.push({\n type: 'error',\n message: `MCP: ${label} call failed: ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n // Auth errors won't be fixed by reconnecting — fail fast\n if (is401Error(error)) {\n connectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n debugLogs.push({\n type: 'warning',\n message: `MCP: Authentication issue detected for ${label} - headers may not be reaching server`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n // Evict stale connection and retry once with a fresh connection\n connectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n\n const retryClient = await getOrCreateConnection(\n cacheKey,\n baseUrl,\n authHeaders,\n debugLogs,\n `${label} (retry)`,\n requestOptions\n );\n\n try {\n return await fn(retryClient);\n } catch (retryError) {\n // Attach original error for diagnostics\n if (retryError instanceof Error && error instanceof Error) {\n retryError.cause = error;\n }\n throw retryError;\n }\n }\n}\n\n/**\n * Options for MCP tool calls with OAuth support\n */\nexport interface MCPCallOptions {\n /** Agent URL */\n agentUrl: string;\n /** Tool name to call */\n toolName: string;\n /** Tool arguments */\n args: Record<string, unknown>;\n /** Static auth token (legacy) */\n authToken?: string;\n /** OAuth provider for dynamic auth */\n authProvider?: OAuthClientProvider;\n /** Debug logs array */\n debugLogs?: DebugLogEntry[];\n /** Additional headers to send with every request (auth headers take precedence) */\n customHeaders?: Record<string, string>;\n /** RFC 9421 signing context — when set, the transport signs outbound ops per seller capability. */\n signingContext?: AgentSigningContext;\n /** Caller-owned cancellation signal for connect and callTool. */\n signal?: AbortSignal;\n /** Optional per-request timeout for connect and callTool. */\n requestTimeoutMs?: number;\n}\n\n/**\n * Result of an MCP connection attempt\n */\nexport interface MCPConnectionResult {\n client: MCPClient;\n transport: StreamableHTTPClientTransport;\n}\n\n/**\n * Connect an MCPClient to the given URL with automatic transport fallback.\n *\n * Strategy:\n * 1. Try StreamableHTTPClientTransport.\n * 2. On any transient connect failure (generic Error, McpError, or StreamableHTTPError),\n * retry once with a fresh StreamableHTTP connection. Auth failures (401) are excluded —\n * a retry is pointless and wastes a round-trip.\n * 3. If a 401 is returned, throw immediately — auth failure is transport-agnostic.\n * 4. For any other error after retry, fall back to SSEClientTransport with the same headers.\n *\n * The returned client is connected and ready for use. Callers are responsible for\n * calling client.close() when done.\n */\nexport async function connectMCPWithFallback(\n url: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[] = [],\n label = 'connection',\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n return withSpan(\n 'adcp.mcp.connect',\n {\n 'http.url': url.toString(),\n 'adcp.connection_label': label,\n },\n async () => {\n return connectMCPWithFallbackImpl(url, authHeaders, debugLogs, label, transportFetch, requestOptions);\n }\n );\n}\n\nasync function connectMCPWithFallbackImpl(\n url: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[] = [],\n label = 'connection',\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n const signingContext = signingContextStorage.getStore();\n // Wrap order (innermost → outermost): network → size-limit → signing → capture.\n // Size-limit applies to the raw network response so signing/capture see a\n // bounded body (capture clones via `response.clone()`, which would otherwise\n // buffer a hostile reply in memory).\n const requestTimeoutMs = resolveRequestTimeoutMs(requestOptions.requestTimeoutMs);\n const clientRequestTimeoutMs = resolveClientRequestTimeoutMs(requestOptions.requestTimeoutMs);\n const mcpRequestOptions = {\n ...(requestOptions.signal && { signal: requestOptions.signal }),\n ...(clientRequestTimeoutMs !== undefined && { timeout: clientRequestTimeoutMs }),\n };\n const rawNetworkFetch: typeof fetch = transportFetch ?? ((input, init) => fetch(input as any, init));\n const networkFetch = (input: Parameters<typeof fetch>[0], init?: RequestInit) =>\n withAbortSignal<Response>([requestOptions.signal, init?.signal], requestTimeoutMs, signal =>\n rawNetworkFetch(input, { ...init, signal })\n );\n const sizeLimited = wrapFetchWithSizeLimit(networkFetch);\n const diagnosticFetch = wrapFetchWithTransportDiagnostics(sizeLimited);\n const baseFetch: typeof fetch = signingContext\n ? (buildAgentSigningFetch({\n upstream: diagnosticFetch,\n signing: signingContext.signing,\n getCapability: signingContext.getCapability,\n }) as typeof fetch)\n : diagnosticFetch;\n const transportOptions: StreamableHTTPClientTransportOptions = {\n requestInit: { headers: authHeaders, redirect: 'manual' },\n fetch: wrapFetchWithCapture(baseFetch),\n };\n let failedClient: MCPClient | undefined;\n\n try {\n const client = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n failedClient = client;\n debugLogs.push({\n type: 'info',\n message: `MCP: Attempting StreamableHTTP ${label} to ${url}`,\n timestamp: new Date().toISOString(),\n });\n await client.connect(new StreamableHTTPClientTransport(url, transportOptions), mcpRequestOptions);\n failedClient = undefined;\n trackStreamableHTTPUrl(url.toString());\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via StreamableHTTP for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return client;\n } catch (error: unknown) {\n // Close the failed client to avoid resource leaks\n if (failedClient) {\n try {\n await failedClient.close();\n } catch {\n /* ignore */\n }\n }\n\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorClass = error instanceof Error ? error.constructor.name : typeof error;\n const httpStatus = error instanceof StreamableHTTPError ? ` [HTTP ${error.code}]` : '';\n debugLogs.push({\n type: 'error',\n message: `MCP: StreamableHTTP failed for ${label}${httpStatus} (${errorClass}): ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n // Retry StreamableHTTP once on any transient connect failure — network blips,\n // JSON parse errors on half-buffered responses, and mid-handshake proxy\n // disconnects all surface as generic Error or McpError, not StreamableHTTPError.\n // Auth failures are the only class where retry is pointless and wasteful.\n if (!is401Error(error)) {\n debugLogs.push({\n type: 'info',\n message: `MCP: Transient connect error (${errorClass}) detected, retrying StreamableHTTP for ${label}`,\n timestamp: new Date().toISOString(),\n });\n const retryClient = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n try {\n await retryClient.connect(new StreamableHTTPClientTransport(url, transportOptions), mcpRequestOptions);\n trackStreamableHTTPUrl(url.toString());\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via StreamableHTTP (retry) for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return retryClient;\n } catch (retryError) {\n try {\n await retryClient.close();\n } catch {\n /* ignore */\n }\n debugLogs.push({\n type: 'error',\n message: `MCP: StreamableHTTP retry also failed for ${label}: ${retryError instanceof Error ? retryError.message : String(retryError)}`,\n timestamp: new Date().toISOString(),\n });\n if (isAbortOrTimeoutError(retryError)) {\n throw retryError;\n }\n // Fall through to SSE fallback below\n }\n }\n\n // Auth failure — transport type won't change the outcome\n if (is401Error(error)) {\n throw error;\n }\n\n // If StreamableHTTP previously worked for this URL, don't fall back to SSE.\n // Transient failures (connection reuse, concurrency limits) should be retried\n // with StreamableHTTP, not SSE — SSE sends GET requests that return 405 on\n // servers that only support POST-based StreamableHTTP.\n if (knownStreamableHTTPUrls.has(url.toString())) {\n debugLogs.push({\n type: 'info',\n message: `MCP: StreamableHTTP previously succeeded for ${url} — skipping SSE fallback for ${label}`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n // Fall back to SSE\n debugLogs.push({\n type: 'warning',\n message: `MCP: Falling back to SSE transport for ${label}`,\n timestamp: new Date().toISOString(),\n });\n const client = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n try {\n await client.connect(\n new SSEClientTransport(url, {\n requestInit: { headers: authHeaders, redirect: 'manual' },\n fetch: wrapFetchWithCapture(baseFetch),\n }),\n mcpRequestOptions\n );\n } catch (sseError) {\n try {\n await client.close();\n } catch {\n /* ignore */\n }\n throw sseError;\n }\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via SSE transport for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return client;\n }\n}\n\nexport async function callMCPTool(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n signingContext?: AgentSigningContext,\n transportFetch?: typeof fetch,\n requestOptions?: { signal?: AbortSignal; requestTimeoutMs?: number }\n): Promise<unknown> {\n debugLogs.push({\n type: 'info',\n message: `MCP: Auth configuration`,\n timestamp: new Date().toISOString(),\n hasAuth: !!authToken,\n headers: authToken ? { 'x-adcp-auth': '***' } : {},\n customHeaderKeys: customHeaders ? Object.keys(customHeaders) : [],\n });\n debugLogs.push({\n type: 'info',\n message: `MCP: Calling tool ${toolName} with args: ${JSON.stringify(redactIdempotencyKeyInArgs(args))}`,\n timestamp: new Date().toISOString(),\n });\n if (authToken) {\n debugLogs.push({\n type: 'info',\n message: `MCP: Transport configured with x-adcp-auth header for ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n }\n\n // Custom fetch injection is an internal conformance seam whose mocks use\n // the v1 transport shape. Normal remote calls negotiate the modern era;\n // injected transports retain their exact legacy behavior.\n if (!transportFetch) {\n const modernAttempt = await tryCallModernMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, {\n ...(signingContext && { signingContext }),\n ...(requestOptions?.signal && { signal: requestOptions.signal }),\n ...(requestOptions?.requestTimeoutMs !== undefined && {\n requestTimeoutMs: requestOptions.requestTimeoutMs,\n }),\n });\n if (modernAttempt.handled) {\n debugLogs.push({\n type: modernAttempt.response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received (${modernAttempt.response?.isError ? 'error' : 'success'})`,\n timestamp: new Date().toISOString(),\n response: modernAttempt.response,\n });\n return modernAttempt.response;\n }\n }\n\n return withSpan(\n 'adcp.mcp.call_tool',\n {\n 'adcp.tool': toolName,\n 'http.url': agentUrl,\n },\n async () => {\n return signingContextStorage.run(signingContext, () =>\n callMCPToolImpl(agentUrl, toolName, args, authToken, debugLogs, customHeaders, transportFetch, requestOptions)\n );\n }\n );\n}\n\n/**\n * Call an MCP tool and return the raw CallToolResult (with isError, content, structuredContent).\n * Raw MCP tool call — returns the CallToolResult directly, including isError responses.\n */\nexport async function callMCPToolRaw(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n signingContext?: AgentSigningContext,\n transportFetch?: typeof fetch\n): Promise<unknown> {\n return signingContextStorage.run(signingContext, () =>\n callMCPToolRawImpl(agentUrl, toolName, args, authToken, debugLogs, customHeaders, transportFetch)\n );\n}\n\nasync function callMCPToolImpl(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n transportFetch?: typeof fetch,\n requestOptions?: { signal?: AbortSignal; requestTimeoutMs?: number }\n): Promise<unknown> {\n // Inject trace context headers for distributed tracing\n const traceHeaders = injectTraceHeaders();\n\n // Merge: custom < trace < auth (auth always wins)\n const authHeaders = {\n ...customHeaders,\n ...traceHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n\n const resolvedRequestTimeoutMs = resolveClientRequestTimeoutMs(requestOptions?.requestTimeoutMs);\n const response = await withCachedConnection(\n agentUrl,\n authToken,\n authHeaders,\n debugLogs,\n toolName,\n client =>\n client.callTool({ name: toolName, arguments: args }, undefined, {\n ...(requestOptions?.signal && { signal: requestOptions.signal }),\n ...(resolvedRequestTimeoutMs !== undefined && { timeout: resolvedRequestTimeoutMs }),\n }) as Promise<CallToolResponse>,\n transportFetch,\n requestOptions\n );\n\n debugLogs.push({\n type: response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received (${response?.isError ? 'error' : 'success'})`,\n timestamp: new Date().toISOString(),\n response: response,\n });\n\n return response;\n}\n\n/**\n * Raw MCP tool call — returns the CallToolResult directly.\n */\nasync function callMCPToolRawImpl(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n transportFetch?: typeof fetch\n): Promise<unknown> {\n const traceHeaders = injectTraceHeaders();\n const authHeaders = {\n ...customHeaders,\n ...traceHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n\n return withCachedConnection(\n agentUrl,\n authToken,\n authHeaders,\n debugLogs,\n toolName,\n client => client.callTool({ name: toolName, arguments: args }),\n transportFetch\n );\n}\n\n/**\n * Connect to an MCP server with OAuth support\n *\n * This function handles both static token auth and OAuth flows.\n * When using OAuth, if the server requires authorization:\n * 1. UnauthorizedError is thrown\n * 2. The OAuth provider's redirectToAuthorization is called\n * 3. Caller should wait for callback and call finishAuth on transport\n *\n * @param options Connection options\n * @returns MCP client and transport (for finishing OAuth if needed)\n * @throws UnauthorizedError if OAuth is required\n *\n * @example\n * ```typescript\n * // With OAuth provider\n * const provider = createCLIOAuthProvider(serverUrl);\n *\n * try {\n * const { client, transport } = await connectMCP({\n * agentUrl: serverUrl,\n * authProvider: provider\n * });\n * // Connected! Use client...\n * } catch (error) {\n * if (error instanceof UnauthorizedError) {\n * // OAuth flow started, wait for callback\n * const code = await provider.waitForCallback();\n * await transport.finishAuth(code);\n * // Retry connection...\n * }\n * }\n * ```\n *\n * @deprecated Low-level v1/SSE escape hatch. High-level AgentClient discovery,\n * tool listing, OAuth calls, and `callMCPTool*` APIs negotiate MCP 2026-07-28.\n * Keep this only for callers that require the v1 SDK client/transport pair or\n * its interactive `finishAuth()` lifecycle.\n */\nexport async function connectMCP(options: {\n agentUrl: string;\n authToken?: string;\n authProvider?: OAuthClientProvider;\n debugLogs?: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n}): Promise<MCPConnectionResult> {\n const {\n agentUrl,\n authToken,\n authProvider,\n debugLogs = [],\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs: configuredRequestTimeoutMs,\n } = options;\n const baseUrl = new URL(agentUrl);\n\n debugLogs.push({\n type: 'info',\n message: `MCP: Connecting to ${baseUrl}`,\n timestamp: new Date().toISOString(),\n authMethod: authProvider ? 'oauth' : authToken ? 'token' : 'none',\n });\n\n const mcpClient = new MCPClient({\n name: 'AdCP-Client',\n version: '1.0.0',\n });\n\n // Build transport options\n const transportOptions: StreamableHTTPClientTransportOptions = {};\n\n // Header-only auth (basic, x-api-key, custom routing) lives entirely on\n // `customHeaders`. Attach it whenever it's present, regardless of which\n // auth branch fires — OAuth + routing headers, bearer + tenant headers,\n // and pure-header auth must all reach the wire.\n //\n // Precedence note: the MCP SDK's `_commonHeaders()` (StreamableHTTP)\n // spreads `requestInit.headers` *over* any provider-emitted `Authorization`\n // (`new Headers({ ...providerHeaders, ...requestInitHeaders })`, last-write-\n // wins). To prevent a caller-supplied `Authorization` in `customHeaders`\n // from silently overriding the OAuth provider's bearer, drop any\n // `Authorization` key from `customHeaders` when `authProvider` is set.\n // OAuth is the source of truth for the bearer in that branch; non-auth\n // routing/tenant headers still flow through.\n const filteredCustomHeaders = authProvider\n ? Object.fromEntries(Object.entries(customHeaders ?? {}).filter(([k]) => k.toLowerCase() !== 'authorization'))\n : customHeaders;\n const authHeaders: Record<string, string> = {\n ...filteredCustomHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n transportOptions.requestInit = { headers: authHeaders, redirect: 'manual' };\n if (authProvider) {\n transportOptions.authProvider = authProvider;\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using OAuth provider for authentication',\n timestamp: new Date().toISOString(),\n });\n } else if (authToken) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using static token for authentication',\n timestamp: new Date().toISOString(),\n });\n } else if (Object.keys(authHeaders).length > 0) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using custom headers for authentication',\n timestamp: new Date().toISOString(),\n });\n }\n\n // RFC 9421 signing — wrap the transport's fetch so the signer sees the final\n // headers the SDK assembled (including any OAuth-issued Authorization) and\n // decides per outbound request whether to sign. Size-limit sits innermost so\n // the response body is bounded before signing/capture observe it.\n const requestTimeoutMs = resolveRequestTimeoutMs(configuredRequestTimeoutMs);\n const clientRequestTimeoutMs = resolveClientRequestTimeoutMs(configuredRequestTimeoutMs);\n const requestOptions = {\n ...(signal && { signal }),\n ...(clientRequestTimeoutMs !== undefined && { timeout: clientRequestTimeoutMs }),\n };\n const sizeLimited = wrapFetchWithSizeLimit((input, init) =>\n withAbortSignal<Response>([signal, init?.signal], requestTimeoutMs, linkedSignal =>\n fetch(input as string | URL, { ...init, signal: linkedSignal })\n )\n );\n const diagnosticFetch = wrapFetchWithTransportDiagnostics(sizeLimited);\n const signedFetch: typeof fetch = signingContext\n ? (buildAgentSigningFetch({\n upstream: diagnosticFetch,\n signing: signingContext.signing,\n getCapability: signingContext.getCapability,\n }) as typeof fetch)\n : diagnosticFetch;\n transportOptions.fetch = wrapFetchWithCapture(signedFetch);\n\n const transport = new StreamableHTTPClientTransport(baseUrl, transportOptions);\n\n try {\n await mcpClient.connect(transport, requestOptions);\n debugLogs.push({\n type: 'success',\n message: 'MCP: Connected successfully',\n timestamp: new Date().toISOString(),\n });\n return { client: mcpClient, transport };\n } catch (error) {\n // If it's an UnauthorizedError, the OAuth flow has started\n // Rethrow so the caller can handle the callback\n if (error instanceof UnauthorizedError) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: OAuth authorization required, flow initiated',\n timestamp: new Date().toISOString(),\n });\n // Return transport so caller can call finishAuth\n throw Object.assign(error, { transport, client: mcpClient });\n }\n\n // Non-OAuth 401 — the SDK sent credentials that the agent rejected (or\n // sent none when it needed them). The raw transport error is shaped like\n // `Error POSTing to endpoint (HTTP 401): unauthorized`, which omits the\n // crucial piece of debug data: *which auth scheme did the SDK actually\n // use*. Without that, a caller can't diff against curl. Wrap the error\n // with a scheme tag and a remediation hint, preserving the original\n // under `.cause` so existing `is401Error` / `error.status` checks\n // downstream still resolve.\n if (is401Error(error)) {\n const scheme = authProvider\n ? 'oauth'\n : authToken\n ? 'bearer'\n : Object.keys(authHeaders).length > 0\n ? 'header'\n : 'none';\n const hint =\n scheme === 'none'\n ? 'No credentials were sent. Configure auth_token, headers, or oauth_tokens on the agent config (or pass --auth on the CLI).'\n : scheme === 'header'\n ? \"Verify the Authorization header value matches the gateway (basic-auth: 'Basic ' + base64(user:pass); pair with --auth-scheme basic on the CLI).\"\n : scheme === 'bearer'\n ? \"Verify the bearer token matches the agent's expected credential.\"\n : 'OAuth provider returned tokens that the agent rejected — check the provider configuration and token scopes.';\n const detail = `MCP connect rejected with HTTP 401 from ${agentUrl}. SDK sent auth scheme: ${scheme}. ${hint}`;\n const wrapped = Object.assign(new Error(detail), {\n cause: error,\n code: 'MCP_AUTH_REJECTED',\n scheme,\n agentUrl,\n originalError: error,\n });\n throw wrapped;\n }\n\n throw error;\n }\n}\n\n/**\n * Call an MCP tool with OAuth support.\n *\n * OAuth connections are cached by agent URL and OAuth provider identity so a\n * service-to-service workflow can reuse the initialized MCP session across\n * related tool calls. Reuse the same OAuthClientProvider instance for a\n * session/source/principal; the provider owns token refresh state for the\n * cached transport.\n *\n * Signing: this path consumes `options.signingContext` via the transport —\n * `connectMCP` attaches a signing-fetch wrapper at transport-creation time —\n * rather than via `signingContextStorage`. The OAuth cache key includes the\n * signing cache key so different signing identities do not share a transport.\n * The non-OAuth fallback (`callMCPTool`) does enter ALS.\n *\n * @param options Call options\n * @returns Tool response\n * @throws UnauthorizedError if OAuth is required (with transport attached)\n */\nexport async function callMCPToolWithOAuth(options: MCPCallOptions): Promise<unknown> {\n const {\n agentUrl,\n toolName,\n args,\n authToken,\n authProvider,\n debugLogs = [],\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs,\n } = options;\n const resolvedRequestTimeoutMs = resolveClientRequestTimeoutMs(requestTimeoutMs);\n const requestOptions = {\n ...(signal && { signal }),\n ...(resolvedRequestTimeoutMs !== undefined && { timeout: resolvedRequestTimeoutMs }),\n };\n\n // If no OAuth provider, use the legacy function\n if (!authProvider) {\n return callMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, signingContext, undefined, {\n signal,\n requestTimeoutMs,\n });\n }\n\n const modernAttempt = await tryCallModernMCPTool(agentUrl, toolName, args, undefined, debugLogs, customHeaders, {\n authProvider,\n signingContext,\n signal,\n requestTimeoutMs,\n handleLegacy: true,\n });\n if (modernAttempt.handled) {\n debugLogs.push({\n type: modernAttempt.response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received`,\n timestamp: new Date().toISOString(),\n });\n return modernAttempt.response;\n }\n\n const response = await withCachedOAuthConnection(\n {\n agentUrl,\n authProvider,\n debugLogs,\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs,\n },\n toolName,\n async client => {\n debugLogs.push({\n type: 'info',\n message: `MCP: Calling tool ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n\n const response = await client.callTool({ name: toolName, arguments: args }, undefined, requestOptions);\n\n debugLogs.push({\n type: response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received`,\n timestamp: new Date().toISOString(),\n });\n\n return response;\n }\n );\n\n return response;\n}\n"],"mappings":"AACA,SAAS,UAAU,iBAAiB;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAElC,SAAS,kBAAkB;AAC3B,SAAS,4BAA4B;AACrC,SAAS,kBAAkB;AAE3B,SAAS,UAAU,0BAA0B;AAC7C,SAAS,wBAAwB,6BAAuD;AACxF,SAAS,kCAAkC;AAC3C,SAAS,4BAA4B;AACrC,SAAS,8BAA8B;AACvC,SAAS,yCAAyC;AAClD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B,4BAA4B;AA4BhE,MAAM,kBAAkB,oBAAI,IAAuB;AACnD,MAAM,qBAAqB,oBAAI,IAAgC;AAC/D,MAAM,uBAAuB,oBAAI,IAAuB;AACxD,MAAM,0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AqB,UAAU,UAAU,MAAM,QAAW,WAAW,eAAe;AAAA,IAC9G;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc;AAAA,EAChB,CAAC;AACD,MAAI,cAAc,SAAS;AACzB,cAAU,KAAK;AAAA,MACb,MAAM,cAAc,UAAU,UAAU,UAAU;AAAA,MAClD,SAAS,aAAa,QAAQ;AAAA,MAC9B,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,IACpC,CAAC;AACD,WAAO,cAAc;AAAA,EACvB;AAEA,QAAM,WAAW,MAAM;AAAA,IACrB;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA;AAAA,IACA,OAAM,WAAU;AACd,gBAAU,KAAK;AAAA,QACb,MAAM;AAAA,QACN,SAAS,qBAAqB,QAAQ;AAAA,QACtC,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MACpC,CAAC;AAED,YAAMA,YAAW,MAAM,OAAO,SAAS,EAAE,MAAM,UAAU,WAAW,KAAK,GAAG,QAAW,cAAc;AAErG,gBAAU,KAAK;AAAA,QACb,MAAMA,WAAU,UAAU,UAAU;AAAA,QACpC,SAAS,aAAa,QAAQ;AAAA,QAC9B,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MACpC,CAAC;AAED,aAAOA;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":["response"]}
1
+ {"version":3,"sources":["../../../src/lib/protocols/mcp.ts"],"sourcesContent":["// Official MCP client implementation using HTTP streaming transport with SSE fallback\nimport { Client as MCPClient } from '@modelcontextprotocol/sdk/client/index.js';\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPError,\n type StreamableHTTPClientTransportOptions,\n} from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';\nimport { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';\nimport type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';\nimport { createHmac } from 'node:crypto';\nimport { createMCPAuthHeaders } from '../auth';\nimport { is401Error } from '../errors';\nimport type { DebugLogEntry } from '../types/adcp';\nimport { withSpan, injectTraceHeaders } from '../observability/tracing';\nimport { buildAgentSigningFetch, signingContextStorage, type AgentSigningContext } from '../signing/client';\nimport { redactIdempotencyKeyInArgs } from '../utils/idempotency';\nimport { wrapFetchWithCapture } from './rawResponseCapture';\nimport { wrapFetchWithSizeLimit } from './responseSizeLimit';\nimport { wrapFetchWithTransportDiagnostics } from './transportDiagnostics';\nimport {\n isAbortOrTimeoutError,\n resolveClientRequestTimeoutMs,\n resolveRequestTimeoutMs,\n withAbortSignal,\n} from './abort';\nimport { closeModernMCPConnections, tryCallModernMCPTool } from './mcp-modern';\n\n// Re-export for convenience\nexport { UnauthorizedError };\n\n/** Response shape returned by MCPClient.callTool(). */\ntype CallToolResponse = {\n isError?: boolean;\n content?: Array<{ type: string; text?: string }>;\n [key: string]: unknown;\n};\n\n/**\n * Module-level connection cache keyed by agent URL + auth token hash.\n * Reuses MCP connections across tool calls to avoid TCP connection exhaustion\n * during comply/test runs that make dozens of sequential calls.\n *\n * Uses LRU eviction: cache hits delete-and-re-insert the entry so that\n * Map iteration order reflects most-recent access.\n *\n * The cache key includes only URL + auth token hash. Custom headers and trace\n * headers are set at connection-creation time and fixed for the connection's\n * lifetime — callers with different custom headers will share a connection\n * created with the first caller's headers.\n *\n * Note: This is a process-global singleton. Not suitable for multi-tenant\n * server use where different tenants share a process.\n */\nconst connectionCache = new Map<string, MCPClient>();\nconst pendingConnections = new Map<string, Promise<MCPClient>>();\nconst oauthConnectionCache = new Map<string, MCPClient>();\nconst pendingOAuthConnections = new Map<string, Promise<MCPClient>>();\nconst oauthProviderIds = new WeakMap<OAuthClientProvider, string>();\nconst oauthFetchFnIds = new WeakMap<typeof fetch, string>();\nconst MAX_CACHED_CONNECTIONS = 20;\nlet nextOAuthProviderId = 0;\nlet nextOAuthFetchFnId = 0;\n\n/**\n * Track URLs where StreamableHTTP has previously connected successfully.\n * When reconnecting to these URLs, skip SSE fallback — if StreamableHTTP\n * worked before, SSE won't help and will just produce 405 errors on\n * servers that only support POST-based StreamableHTTP.\n *\n * Capped at MAX_CACHED_CONNECTIONS to avoid unbounded growth. Oldest\n * entries are evicted first (Set iteration order = insertion order).\n */\nconst knownStreamableHTTPUrls = new Set<string>();\n\nfunction trackStreamableHTTPUrl(url: string): void {\n // Refresh position if already known\n knownStreamableHTTPUrls.delete(url);\n knownStreamableHTTPUrls.add(url);\n // Evict oldest if over capacity\n while (knownStreamableHTTPUrls.size > MAX_CACHED_CONNECTIONS) {\n const oldest = knownStreamableHTTPUrls.values().next().value;\n if (oldest) knownStreamableHTTPUrls.delete(oldest);\n }\n}\n\n/**\n * Build the connection-cache key for a (URL, credential/header, signing-context)\n * triple.\n *\n * Two credential paths feed this cache. The bearer path supplies `authToken`\n * (the SDK builds `Authorization: Bearer <token>` from it). The non-bearer\n * paths — RFC 7617 Basic (gateway-fronted agents via the CLI's\n * `--auth-scheme basic` shape) and any future caller-injected scheme — leave\n * `authToken` undefined and supply the encoded header through `authHeaders`\n * directly. Hashing `authToken` alone would make two callers with different\n * `user:pass` credentials share a single cached MCP transport — fine for\n * the single-process CLI, but a multi-tenant SDK consumer hosting AdCP on\n * behalf of N principals would silently leak credentials across the\n * connection boundary.\n *\n * Also include non-trace custom headers in the key. Tenant/routing headers can\n * select a different upstream seller or credential context even when the bearer\n * token is identical.\n */\nfunction connectionCacheKey(\n agentUrl: string,\n authToken?: string,\n signingCacheKey?: string,\n authHeaders?: Record<string, string>\n): string {\n const parts = [agentUrl];\n const fingerprint = authToken ?? extractAuthHeader(authHeaders);\n if (fingerprint) parts.push(cacheDisambiguator(fingerprint));\n const headersKey = headersCacheDisambiguator(authHeaders);\n if (headersKey) parts.push(`headers:${headersKey}`);\n if (signingCacheKey) parts.push(signingCacheKey);\n return parts.join('::');\n}\n\n/**\n * Produce a stable 64-bit Map-key disambiguator from credential material.\n *\n * This is NOT a password hash. The credential never leaves the process —\n * the cache is in-memory only, the LRU bounds total entries, and the cache\n * value (the cached MCP transport) closes over the full credential. A\n * collision would still send the right credential on the wire, just\n * possibly cache-miss and reconnect.\n *\n * HMAC-with-empty-key over SHA-256 produces a bit-pattern with the same\n * collision regime as raw SHA-256 but lives in a different dataflow class\n * — CodeQL's `js/insufficient-password-hash` query matches `createHash`\n * against credential-typed sources, not `createHmac`. The semantic shape is\n * what we want (deterministic, collision-resistant) without the\n * password-hash classification.\n */\nfunction cacheDisambiguator(value: string): string {\n return createHmac('sha256', '').update(value).digest('hex').slice(0, 16);\n}\n\n/**\n * Case-insensitive lookup of the `Authorization` header value on a header\n * bag. Returns `undefined` when no such header is present.\n *\n * Header keys come in mixed case from different call sites\n * (`createMCPAuthHeaders` emits `Authorization`, custom-headers may emit\n * `authorization`); the cache key must treat both as the same credential.\n */\nfunction extractAuthHeader(headers?: Record<string, string>): string | undefined {\n if (!headers) return undefined;\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === 'authorization' && value) return value;\n }\n return undefined;\n}\n\nfunction headersCacheDisambiguator(headers?: Record<string, string>): string | undefined {\n const entries = Object.entries(headers ?? {})\n .filter(([key]) => {\n const lower = key.toLowerCase();\n return lower !== 'traceparent' && lower !== 'tracestate' && lower !== 'baggage';\n })\n .map(([key, value]) => [key.toLowerCase(), value] as const)\n .sort(([a], [b]) => a.localeCompare(b));\n return entries.length > 0 ? cacheDisambiguator(JSON.stringify(entries)) : undefined;\n}\n\n/** Get a cached connection, refreshing its LRU position. */\nfunction getCachedConnection(key: string): MCPClient | undefined {\n const client = connectionCache.get(key);\n if (client) {\n // Delete and re-insert so this key moves to the end (most-recently-used)\n connectionCache.delete(key);\n connectionCache.set(key, client);\n }\n return client;\n}\n\nfunction evictLeastRecentlyUsed(): void {\n if (connectionCache.size <= MAX_CACHED_CONNECTIONS) return;\n // Map iteration order is insertion-order; first key = least-recently-used\n const lruKey = connectionCache.keys().next().value;\n if (!lruKey) return;\n const oldClient = connectionCache.get(lruKey);\n connectionCache.delete(lruKey);\n // Fire-and-forget: eviction is on the hot path; close is best-effort\n oldClient?.close().catch(() => {});\n}\n\nfunction evictLeastRecentlyUsedOAuth(): void {\n if (oauthConnectionCache.size <= MAX_CACHED_CONNECTIONS) return;\n const lruKey = oauthConnectionCache.keys().next().value;\n if (!lruKey) return;\n const oldClient = oauthConnectionCache.get(lruKey);\n oauthConnectionCache.delete(lruKey);\n oldClient?.close().catch(() => {});\n}\n\n/**\n * Close all cached OAuth MCP connections.\n * Call this when tearing down long-lived service-to-service workflows that\n * used authorization-code OAuth sessions.\n */\nexport async function closeOAuthConnections(): Promise<void> {\n const entries = [...oauthConnectionCache.entries()];\n oauthConnectionCache.clear();\n for (const [, client] of entries) {\n try {\n await client.close();\n } catch {\n /* ignore close errors */\n }\n }\n}\n\n/**\n * Close all cached MCP connections.\n * Call this at the end of comply/test runs or before process exit.\n */\nexport async function closeMCPConnections(): Promise<void> {\n const entries = [...connectionCache.entries()];\n connectionCache.clear();\n knownStreamableHTTPUrls.clear();\n for (const [, client] of entries) {\n try {\n await client.close();\n } catch {\n /* ignore close errors */\n }\n }\n await closeOAuthConnections();\n await closeModernMCPConnections();\n}\n\n/**\n * Get or create a cached connection for the given cache key.\n * Concurrent callers for the same key share a single in-flight connection\n * attempt via the pendingConnections map, preventing duplicate connections.\n */\nasync function getOrCreateConnection(\n cacheKey: string,\n baseUrl: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[],\n label: string,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n const cached = getCachedConnection(cacheKey);\n if (cached) return cached;\n\n const pending = pendingConnections.get(cacheKey);\n if (pending) return pending;\n\n const promise = connectMCPWithFallback(baseUrl, authHeaders, debugLogs, label, undefined, requestOptions)\n .then(client => {\n connectionCache.set(cacheKey, client);\n evictLeastRecentlyUsed();\n return client;\n })\n .finally(() => {\n pendingConnections.delete(cacheKey);\n });\n\n pendingConnections.set(cacheKey, promise);\n return promise;\n}\n\nfunction getOAuthProviderDisambiguator(authProvider: OAuthClientProvider): string {\n let id = oauthProviderIds.get(authProvider);\n if (!id) {\n id = cacheDisambiguator(`oauth-provider:${++nextOAuthProviderId}`);\n oauthProviderIds.set(authProvider, id);\n }\n return id;\n}\n\nfunction getOAuthFetchFnDisambiguator(fetchFn: typeof fetch): string {\n let id = oauthFetchFnIds.get(fetchFn);\n if (!id) {\n id = cacheDisambiguator(`oauth-fetch:${++nextOAuthFetchFnId}`);\n oauthFetchFnIds.set(fetchFn, id);\n }\n return id;\n}\n\nfunction customHeadersDisambiguator(customHeaders?: Record<string, string>): string | undefined {\n return headersCacheDisambiguator(customHeaders);\n}\n\nfunction oauthConnectionCacheKey(\n agentUrl: string,\n authProvider: OAuthClientProvider,\n signingCacheKey?: string,\n customHeaders?: Record<string, string>,\n fetchFn?: typeof fetch\n): string {\n const parts = [`${agentUrl}::oauth:${getOAuthProviderDisambiguator(authProvider)}`];\n if (signingCacheKey) parts.push(signingCacheKey);\n const headersKey = customHeadersDisambiguator(customHeaders);\n if (headersKey) parts.push(`headers:${headersKey}`);\n if (fetchFn) parts.push(`fetch:${getOAuthFetchFnDisambiguator(fetchFn)}`);\n return parts.join('::');\n}\n\n/** Get a cached OAuth connection, refreshing its LRU position. */\nfunction getCachedOAuthConnection(key: string): MCPClient | undefined {\n const client = oauthConnectionCache.get(key);\n if (client) {\n oauthConnectionCache.delete(key);\n oauthConnectionCache.set(key, client);\n }\n return client;\n}\n\nasync function getOrCreateOAuthConnection(\n cacheKey: string,\n options: {\n agentUrl: string;\n authProvider: OAuthClientProvider;\n debugLogs: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n fetchFn?: typeof fetch;\n }\n): Promise<MCPClient> {\n const cached = getCachedOAuthConnection(cacheKey);\n if (cached) return cached;\n\n const pending = pendingOAuthConnections.get(cacheKey);\n if (pending) return pending;\n\n const promise = connectMCP(options)\n .then(({ client }) => {\n oauthConnectionCache.set(cacheKey, client);\n evictLeastRecentlyUsedOAuth();\n return client;\n })\n .finally(() => {\n pendingOAuthConnections.delete(cacheKey);\n });\n\n pendingOAuthConnections.set(cacheKey, promise);\n return promise;\n}\n\nasync function withCachedOAuthConnection<T>(\n options: {\n agentUrl: string;\n authProvider: OAuthClientProvider;\n debugLogs: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n fetchFn?: typeof fetch;\n },\n label: string,\n fn: (client: MCPClient) => Promise<T>\n): Promise<T> {\n const cacheKey = oauthConnectionCacheKey(\n options.agentUrl,\n options.authProvider,\n options.signingContext?.cacheKey,\n options.customHeaders,\n options.fetchFn\n );\n if (options.signal || options.requestTimeoutMs !== undefined || options.fetchFn) {\n const { client } = await connectMCP(options);\n try {\n return await fn(client);\n } finally {\n try {\n await client.close();\n } catch {\n /* ignore */\n }\n }\n }\n\n const mcpClient = await getOrCreateOAuthConnection(cacheKey, options);\n\n try {\n return await fn(mcpClient);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n options.debugLogs.push({\n type: 'error',\n message: `MCP: ${label} OAuth call failed: ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n if (is401Error(error)) {\n oauthConnectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n options.debugLogs.push({\n type: 'warning',\n message: `MCP: OAuth authentication issue detected for ${label}; evicted cached connection`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n oauthConnectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n\n const retryClient = await getOrCreateOAuthConnection(cacheKey, {\n ...options,\n debugLogs: options.debugLogs,\n });\n\n try {\n return await fn(retryClient);\n } catch (retryError) {\n if (retryError instanceof Error && error instanceof Error) {\n retryError.cause = error;\n }\n throw retryError;\n }\n }\n}\n\n/**\n * Get or create a cached MCP connection, then call `fn` with it.\n * On transport errors, evicts the stale connection and retries once.\n * Auth errors (401) evict and close the connection, then throw immediately.\n *\n * @internal Used by mcp-tasks.ts for protocol-level task operations.\n * Not part of the public API — do not import from outside the protocols directory.\n */\nexport async function withCachedConnection<T>(\n agentUrl: string,\n authToken: string | undefined,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[],\n label: string,\n fn: (client: MCPClient) => Promise<T>,\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<T> {\n const signingContext = signingContextStorage.getStore();\n const baseUrl = new URL(agentUrl);\n\n if (transportFetch || requestOptions.signal || requestOptions.requestTimeoutMs !== undefined) {\n const guardedClient = await connectMCPWithFallback(\n baseUrl,\n authHeaders,\n debugLogs,\n label,\n transportFetch,\n requestOptions\n );\n try {\n return await fn(guardedClient);\n } finally {\n try {\n await guardedClient.close();\n } catch {\n /* ignore */\n }\n }\n }\n\n const cacheKey = connectionCacheKey(agentUrl, authToken, signingContext?.cacheKey, authHeaders);\n const mcpClient = await getOrCreateConnection(cacheKey, baseUrl, authHeaders, debugLogs, label, requestOptions);\n\n try {\n return await fn(mcpClient);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n debugLogs.push({\n type: 'error',\n message: `MCP: ${label} call failed: ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n // Auth errors won't be fixed by reconnecting — fail fast\n if (is401Error(error)) {\n connectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n debugLogs.push({\n type: 'warning',\n message: `MCP: Authentication issue detected for ${label} - headers may not be reaching server`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n // Evict stale connection and retry once with a fresh connection\n connectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n\n const retryClient = await getOrCreateConnection(\n cacheKey,\n baseUrl,\n authHeaders,\n debugLogs,\n `${label} (retry)`,\n requestOptions\n );\n\n try {\n return await fn(retryClient);\n } catch (retryError) {\n // Attach original error for diagnostics\n if (retryError instanceof Error && error instanceof Error) {\n retryError.cause = error;\n }\n throw retryError;\n }\n }\n}\n\n/**\n * Options for MCP tool calls with OAuth support\n */\nexport interface MCPCallOptions {\n /** Agent URL */\n agentUrl: string;\n /** Tool name to call */\n toolName: string;\n /** Tool arguments */\n args: Record<string, unknown>;\n /** Static auth token (legacy) */\n authToken?: string;\n /** OAuth provider for dynamic auth */\n authProvider?: OAuthClientProvider;\n /** Debug logs array */\n debugLogs?: DebugLogEntry[];\n /** Additional headers to send with every request (auth headers take precedence) */\n customHeaders?: Record<string, string>;\n /** RFC 9421 signing context — when set, the transport signs outbound ops per seller capability. */\n signingContext?: AgentSigningContext;\n /** Caller-owned cancellation signal for connect and callTool. */\n signal?: AbortSignal;\n /** Optional per-request timeout for connect and callTool. */\n requestTimeoutMs?: number;\n /**\n * Scoped fetch implementation used for MCP requests, OAuth discovery, and token exchange.\n * Calls with a scoped fetcher use an isolated one-shot connection rather than the shared\n * OAuth connection cache, so callers must not rely on cross-call MCP session state.\n */\n fetchFn?: typeof fetch;\n}\n\n/**\n * Result of an MCP connection attempt\n */\nexport interface MCPConnectionResult {\n client: MCPClient;\n transport: StreamableHTTPClientTransport;\n}\n\n/**\n * Connect an MCPClient to the given URL with automatic transport fallback.\n *\n * Strategy:\n * 1. Try StreamableHTTPClientTransport.\n * 2. On any transient connect failure (generic Error, McpError, or StreamableHTTPError),\n * retry once with a fresh StreamableHTTP connection. Auth failures (401) are excluded —\n * a retry is pointless and wastes a round-trip.\n * 3. If a 401 is returned, throw immediately — auth failure is transport-agnostic.\n * 4. For any other error after retry, fall back to SSEClientTransport with the same headers.\n *\n * The returned client is connected and ready for use. Callers are responsible for\n * calling client.close() when done.\n */\nexport async function connectMCPWithFallback(\n url: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[] = [],\n label = 'connection',\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n return withSpan(\n 'adcp.mcp.connect',\n {\n 'http.url': url.toString(),\n 'adcp.connection_label': label,\n },\n async () => {\n return connectMCPWithFallbackImpl(url, authHeaders, debugLogs, label, transportFetch, requestOptions);\n }\n );\n}\n\nasync function connectMCPWithFallbackImpl(\n url: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[] = [],\n label = 'connection',\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n const signingContext = signingContextStorage.getStore();\n // Wrap order (innermost → outermost): network → size-limit → signing → capture.\n // Size-limit applies to the raw network response so signing/capture see a\n // bounded body (capture clones via `response.clone()`, which would otherwise\n // buffer a hostile reply in memory).\n const requestTimeoutMs = resolveRequestTimeoutMs(requestOptions.requestTimeoutMs);\n const clientRequestTimeoutMs = resolveClientRequestTimeoutMs(requestOptions.requestTimeoutMs);\n const mcpRequestOptions = {\n ...(requestOptions.signal && { signal: requestOptions.signal }),\n ...(clientRequestTimeoutMs !== undefined && { timeout: clientRequestTimeoutMs }),\n };\n const rawNetworkFetch: typeof fetch = transportFetch ?? ((input, init) => fetch(input as any, init));\n const networkFetch = (input: Parameters<typeof fetch>[0], init?: RequestInit) =>\n withAbortSignal<Response>([requestOptions.signal, init?.signal], requestTimeoutMs, signal =>\n rawNetworkFetch(input, { ...init, signal })\n );\n const sizeLimited = wrapFetchWithSizeLimit(networkFetch);\n const diagnosticFetch = wrapFetchWithTransportDiagnostics(sizeLimited);\n const baseFetch: typeof fetch = signingContext\n ? (buildAgentSigningFetch({\n upstream: diagnosticFetch,\n signing: signingContext.signing,\n getCapability: signingContext.getCapability,\n }) as typeof fetch)\n : diagnosticFetch;\n const transportOptions: StreamableHTTPClientTransportOptions = {\n requestInit: { headers: authHeaders, redirect: 'manual' },\n fetch: wrapFetchWithCapture(baseFetch),\n };\n let failedClient: MCPClient | undefined;\n\n try {\n const client = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n failedClient = client;\n debugLogs.push({\n type: 'info',\n message: `MCP: Attempting StreamableHTTP ${label} to ${url}`,\n timestamp: new Date().toISOString(),\n });\n await client.connect(new StreamableHTTPClientTransport(url, transportOptions), mcpRequestOptions);\n failedClient = undefined;\n trackStreamableHTTPUrl(url.toString());\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via StreamableHTTP for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return client;\n } catch (error: unknown) {\n // Close the failed client to avoid resource leaks\n if (failedClient) {\n try {\n await failedClient.close();\n } catch {\n /* ignore */\n }\n }\n\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorClass = error instanceof Error ? error.constructor.name : typeof error;\n const httpStatus = error instanceof StreamableHTTPError ? ` [HTTP ${error.code}]` : '';\n debugLogs.push({\n type: 'error',\n message: `MCP: StreamableHTTP failed for ${label}${httpStatus} (${errorClass}): ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n // Retry StreamableHTTP once on any transient connect failure — network blips,\n // JSON parse errors on half-buffered responses, and mid-handshake proxy\n // disconnects all surface as generic Error or McpError, not StreamableHTTPError.\n // Auth failures are the only class where retry is pointless and wasteful.\n if (!is401Error(error)) {\n debugLogs.push({\n type: 'info',\n message: `MCP: Transient connect error (${errorClass}) detected, retrying StreamableHTTP for ${label}`,\n timestamp: new Date().toISOString(),\n });\n const retryClient = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n try {\n await retryClient.connect(new StreamableHTTPClientTransport(url, transportOptions), mcpRequestOptions);\n trackStreamableHTTPUrl(url.toString());\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via StreamableHTTP (retry) for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return retryClient;\n } catch (retryError) {\n try {\n await retryClient.close();\n } catch {\n /* ignore */\n }\n debugLogs.push({\n type: 'error',\n message: `MCP: StreamableHTTP retry also failed for ${label}: ${retryError instanceof Error ? retryError.message : String(retryError)}`,\n timestamp: new Date().toISOString(),\n });\n if (isAbortOrTimeoutError(retryError)) {\n throw retryError;\n }\n // Fall through to SSE fallback below\n }\n }\n\n // Auth failure — transport type won't change the outcome\n if (is401Error(error)) {\n throw error;\n }\n\n // If StreamableHTTP previously worked for this URL, don't fall back to SSE.\n // Transient failures (connection reuse, concurrency limits) should be retried\n // with StreamableHTTP, not SSE — SSE sends GET requests that return 405 on\n // servers that only support POST-based StreamableHTTP.\n if (knownStreamableHTTPUrls.has(url.toString())) {\n debugLogs.push({\n type: 'info',\n message: `MCP: StreamableHTTP previously succeeded for ${url} — skipping SSE fallback for ${label}`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n // Fall back to SSE\n debugLogs.push({\n type: 'warning',\n message: `MCP: Falling back to SSE transport for ${label}`,\n timestamp: new Date().toISOString(),\n });\n const client = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n try {\n await client.connect(\n new SSEClientTransport(url, {\n requestInit: { headers: authHeaders, redirect: 'manual' },\n fetch: wrapFetchWithCapture(baseFetch),\n }),\n mcpRequestOptions\n );\n } catch (sseError) {\n try {\n await client.close();\n } catch {\n /* ignore */\n }\n throw sseError;\n }\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via SSE transport for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return client;\n }\n}\n\nexport async function callMCPTool(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n signingContext?: AgentSigningContext,\n transportFetch?: typeof fetch,\n requestOptions?: { signal?: AbortSignal; requestTimeoutMs?: number }\n): Promise<unknown> {\n debugLogs.push({\n type: 'info',\n message: `MCP: Auth configuration`,\n timestamp: new Date().toISOString(),\n hasAuth: !!authToken,\n headers: authToken ? { 'x-adcp-auth': '***' } : {},\n customHeaderKeys: customHeaders ? Object.keys(customHeaders) : [],\n });\n debugLogs.push({\n type: 'info',\n message: `MCP: Calling tool ${toolName} with args: ${JSON.stringify(redactIdempotencyKeyInArgs(args))}`,\n timestamp: new Date().toISOString(),\n });\n if (authToken) {\n debugLogs.push({\n type: 'info',\n message: `MCP: Transport configured with x-adcp-auth header for ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n }\n\n // Custom fetch injection is an internal conformance seam whose mocks use\n // the v1 transport shape. Normal remote calls negotiate the modern era;\n // injected transports retain their exact legacy behavior.\n if (!transportFetch) {\n const modernAttempt = await tryCallModernMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, {\n ...(signingContext && { signingContext }),\n ...(requestOptions?.signal && { signal: requestOptions.signal }),\n ...(requestOptions?.requestTimeoutMs !== undefined && {\n requestTimeoutMs: requestOptions.requestTimeoutMs,\n }),\n });\n if (modernAttempt.handled) {\n debugLogs.push({\n type: modernAttempt.response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received (${modernAttempt.response?.isError ? 'error' : 'success'})`,\n timestamp: new Date().toISOString(),\n response: modernAttempt.response,\n });\n return modernAttempt.response;\n }\n }\n\n return withSpan(\n 'adcp.mcp.call_tool',\n {\n 'adcp.tool': toolName,\n 'http.url': agentUrl,\n },\n async () => {\n return signingContextStorage.run(signingContext, () =>\n callMCPToolImpl(agentUrl, toolName, args, authToken, debugLogs, customHeaders, transportFetch, requestOptions)\n );\n }\n );\n}\n\n/**\n * Call an MCP tool and return the raw CallToolResult (with isError, content, structuredContent).\n * Raw MCP tool call — returns the CallToolResult directly, including isError responses.\n */\nexport async function callMCPToolRaw(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n signingContext?: AgentSigningContext,\n transportFetch?: typeof fetch\n): Promise<unknown> {\n return signingContextStorage.run(signingContext, () =>\n callMCPToolRawImpl(agentUrl, toolName, args, authToken, debugLogs, customHeaders, transportFetch)\n );\n}\n\nasync function callMCPToolImpl(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n transportFetch?: typeof fetch,\n requestOptions?: { signal?: AbortSignal; requestTimeoutMs?: number }\n): Promise<unknown> {\n // Inject trace context headers for distributed tracing\n const traceHeaders = injectTraceHeaders();\n\n // Merge: custom < trace < auth (auth always wins)\n const authHeaders = {\n ...customHeaders,\n ...traceHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n\n const resolvedRequestTimeoutMs = resolveClientRequestTimeoutMs(requestOptions?.requestTimeoutMs);\n const response = await withCachedConnection(\n agentUrl,\n authToken,\n authHeaders,\n debugLogs,\n toolName,\n client =>\n client.callTool({ name: toolName, arguments: args }, undefined, {\n ...(requestOptions?.signal && { signal: requestOptions.signal }),\n ...(resolvedRequestTimeoutMs !== undefined && { timeout: resolvedRequestTimeoutMs }),\n }) as Promise<CallToolResponse>,\n transportFetch,\n requestOptions\n );\n\n debugLogs.push({\n type: response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received (${response?.isError ? 'error' : 'success'})`,\n timestamp: new Date().toISOString(),\n response: response,\n });\n\n return response;\n}\n\n/**\n * Raw MCP tool call — returns the CallToolResult directly.\n */\nasync function callMCPToolRawImpl(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n transportFetch?: typeof fetch\n): Promise<unknown> {\n const traceHeaders = injectTraceHeaders();\n const authHeaders = {\n ...customHeaders,\n ...traceHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n\n return withCachedConnection(\n agentUrl,\n authToken,\n authHeaders,\n debugLogs,\n toolName,\n client => client.callTool({ name: toolName, arguments: args }),\n transportFetch\n );\n}\n\n/**\n * Connect to an MCP server with OAuth support\n *\n * This function handles both static token auth and OAuth flows.\n * When using OAuth, if the server requires authorization:\n * 1. UnauthorizedError is thrown\n * 2. The OAuth provider's redirectToAuthorization is called\n * 3. Caller should wait for callback and call finishAuth on transport\n *\n * @param options Connection options\n * @returns MCP client and transport (for finishing OAuth if needed)\n * @throws UnauthorizedError if OAuth is required\n *\n * @example\n * ```typescript\n * // With OAuth provider\n * const provider = createCLIOAuthProvider(serverUrl);\n *\n * try {\n * const { client, transport } = await connectMCP({\n * agentUrl: serverUrl,\n * authProvider: provider\n * });\n * // Connected! Use client...\n * } catch (error) {\n * if (error instanceof UnauthorizedError) {\n * // OAuth flow started, wait for callback\n * const code = await provider.waitForCallback();\n * await transport.finishAuth(code);\n * // Retry connection...\n * }\n * }\n * ```\n *\n * @deprecated Low-level v1/SSE escape hatch. High-level AgentClient discovery,\n * tool listing, OAuth calls, and `callMCPTool*` APIs negotiate MCP 2026-07-28.\n * Keep this only for callers that require the v1 SDK client/transport pair or\n * its interactive `finishAuth()` lifecycle.\n */\nexport async function connectMCP(options: {\n agentUrl: string;\n authToken?: string;\n authProvider?: OAuthClientProvider;\n debugLogs?: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n fetchFn?: typeof fetch;\n}): Promise<MCPConnectionResult> {\n const {\n agentUrl,\n authToken,\n authProvider,\n debugLogs = [],\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs: configuredRequestTimeoutMs,\n fetchFn,\n } = options;\n const baseUrl = new URL(agentUrl);\n\n debugLogs.push({\n type: 'info',\n message: `MCP: Connecting to ${baseUrl}`,\n timestamp: new Date().toISOString(),\n authMethod: authProvider ? 'oauth' : authToken ? 'token' : 'none',\n });\n\n const mcpClient = new MCPClient({\n name: 'AdCP-Client',\n version: '1.0.0',\n });\n\n // Build transport options\n const transportOptions: StreamableHTTPClientTransportOptions = {};\n\n // Header-only auth (basic, x-api-key, custom routing) lives entirely on\n // `customHeaders`. Attach it whenever it's present, regardless of which\n // auth branch fires — OAuth + routing headers, bearer + tenant headers,\n // and pure-header auth must all reach the wire.\n //\n // Precedence note: the MCP SDK's `_commonHeaders()` (StreamableHTTP)\n // spreads `requestInit.headers` *over* any provider-emitted `Authorization`\n // (`new Headers({ ...providerHeaders, ...requestInitHeaders })`, last-write-\n // wins). To prevent a caller-supplied `Authorization` in `customHeaders`\n // from silently overriding the OAuth provider's bearer, drop any\n // `Authorization` key from `customHeaders` when `authProvider` is set.\n // OAuth is the source of truth for the bearer in that branch; non-auth\n // routing/tenant headers still flow through.\n const filteredCustomHeaders = authProvider\n ? Object.fromEntries(Object.entries(customHeaders ?? {}).filter(([k]) => k.toLowerCase() !== 'authorization'))\n : customHeaders;\n const authHeaders: Record<string, string> = {\n ...filteredCustomHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n transportOptions.requestInit = { headers: authHeaders, redirect: 'manual' };\n if (authProvider) {\n transportOptions.authProvider = authProvider;\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using OAuth provider for authentication',\n timestamp: new Date().toISOString(),\n });\n } else if (authToken) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using static token for authentication',\n timestamp: new Date().toISOString(),\n });\n } else if (Object.keys(authHeaders).length > 0) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using custom headers for authentication',\n timestamp: new Date().toISOString(),\n });\n }\n\n // RFC 9421 signing — wrap the transport's fetch so the signer sees the final\n // headers the SDK assembled (including any OAuth-issued Authorization) and\n // decides per outbound request whether to sign. Size-limit sits innermost so\n // the response body is bounded before signing/capture observe it.\n const requestTimeoutMs = resolveRequestTimeoutMs(configuredRequestTimeoutMs);\n const clientRequestTimeoutMs = resolveClientRequestTimeoutMs(configuredRequestTimeoutMs);\n const requestOptions = {\n ...(signal && { signal }),\n ...(clientRequestTimeoutMs !== undefined && { timeout: clientRequestTimeoutMs }),\n };\n const rawNetworkFetch: typeof fetch = fetchFn ?? ((input, init) => fetch(input, init));\n const sizeLimited = wrapFetchWithSizeLimit((input, init) =>\n withAbortSignal<Response>([signal, init?.signal], requestTimeoutMs, linkedSignal =>\n rawNetworkFetch(input, { ...init, signal: linkedSignal })\n )\n );\n const diagnosticFetch = wrapFetchWithTransportDiagnostics(sizeLimited);\n const signedFetch: typeof fetch = signingContext\n ? (buildAgentSigningFetch({\n upstream: diagnosticFetch,\n signing: signingContext.signing,\n getCapability: signingContext.getCapability,\n }) as typeof fetch)\n : diagnosticFetch;\n transportOptions.fetch = wrapFetchWithCapture(signedFetch);\n\n const transport = new StreamableHTTPClientTransport(baseUrl, transportOptions);\n\n try {\n await mcpClient.connect(transport, requestOptions);\n debugLogs.push({\n type: 'success',\n message: 'MCP: Connected successfully',\n timestamp: new Date().toISOString(),\n });\n return { client: mcpClient, transport };\n } catch (error) {\n // If it's an UnauthorizedError, the OAuth flow has started\n // Rethrow so the caller can handle the callback\n if (error instanceof UnauthorizedError) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: OAuth authorization required, flow initiated',\n timestamp: new Date().toISOString(),\n });\n // Return transport so caller can call finishAuth\n throw Object.assign(error, { transport, client: mcpClient });\n }\n\n // Non-OAuth 401 — the SDK sent credentials that the agent rejected (or\n // sent none when it needed them). The raw transport error is shaped like\n // `Error POSTing to endpoint (HTTP 401): unauthorized`, which omits the\n // crucial piece of debug data: *which auth scheme did the SDK actually\n // use*. Without that, a caller can't diff against curl. Wrap the error\n // with a scheme tag and a remediation hint, preserving the original\n // under `.cause` so existing `is401Error` / `error.status` checks\n // downstream still resolve.\n if (is401Error(error)) {\n const scheme = authProvider\n ? 'oauth'\n : authToken\n ? 'bearer'\n : Object.keys(authHeaders).length > 0\n ? 'header'\n : 'none';\n const hint =\n scheme === 'none'\n ? 'No credentials were sent. Configure auth_token, headers, or oauth_tokens on the agent config (or pass --auth on the CLI).'\n : scheme === 'header'\n ? \"Verify the Authorization header value matches the gateway (basic-auth: 'Basic ' + base64(user:pass); pair with --auth-scheme basic on the CLI).\"\n : scheme === 'bearer'\n ? \"Verify the bearer token matches the agent's expected credential.\"\n : 'OAuth provider returned tokens that the agent rejected — check the provider configuration and token scopes.';\n const detail = `MCP connect rejected with HTTP 401 from ${agentUrl}. SDK sent auth scheme: ${scheme}. ${hint}`;\n const wrapped = Object.assign(new Error(detail), {\n cause: error,\n code: 'MCP_AUTH_REJECTED',\n scheme,\n agentUrl,\n originalError: error,\n });\n throw wrapped;\n }\n\n throw error;\n }\n}\n\n/**\n * Call an MCP tool with OAuth support.\n *\n * OAuth connections are cached by agent URL and OAuth provider identity so a\n * service-to-service workflow can reuse the initialized MCP session across\n * related tool calls. Reuse the same OAuthClientProvider instance for a\n * session/source/principal; the provider owns token refresh state for the\n * cached transport.\n *\n * Supplying `fetchFn` opts out of connection reuse. Scoped fetchers commonly\n * carry request- or tenant-specific network policy, so each call gets an\n * isolated connection that is closed after the tool response.\n *\n * Signing: this path consumes `options.signingContext` via the transport —\n * `connectMCP` attaches a signing-fetch wrapper at transport-creation time —\n * rather than via `signingContextStorage`. The OAuth cache key includes the\n * signing cache key so different signing identities do not share a transport.\n * The non-OAuth fallback (`callMCPTool`) does enter ALS.\n *\n * @param options Call options\n * @returns Tool response\n * @throws UnauthorizedError if OAuth is required (with transport attached)\n */\nexport async function callMCPToolWithOAuth(options: MCPCallOptions): Promise<unknown> {\n const {\n agentUrl,\n toolName,\n args,\n authToken,\n authProvider,\n debugLogs = [],\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs,\n fetchFn,\n } = options;\n const resolvedRequestTimeoutMs = resolveClientRequestTimeoutMs(requestTimeoutMs);\n const requestOptions = {\n ...(signal && { signal }),\n ...(resolvedRequestTimeoutMs !== undefined && { timeout: resolvedRequestTimeoutMs }),\n };\n\n // If no OAuth provider, use the legacy function\n if (!authProvider) {\n return callMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, signingContext, fetchFn, {\n signal,\n requestTimeoutMs,\n });\n }\n\n const modernAttempt = await tryCallModernMCPTool(agentUrl, toolName, args, undefined, debugLogs, customHeaders, {\n authProvider,\n signingContext,\n signal,\n requestTimeoutMs,\n fetchFn,\n handleLegacy: true,\n });\n if (modernAttempt.handled) {\n debugLogs.push({\n type: modernAttempt.response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received`,\n timestamp: new Date().toISOString(),\n });\n return modernAttempt.response;\n }\n\n const response = await withCachedOAuthConnection(\n {\n agentUrl,\n authProvider,\n debugLogs,\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs,\n fetchFn,\n },\n toolName,\n async client => {\n debugLogs.push({\n type: 'info',\n message: `MCP: Calling tool ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n\n const response = await client.callTool({ name: toolName, arguments: args }, undefined, requestOptions);\n\n debugLogs.push({\n type: response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received`,\n timestamp: new Date().toISOString(),\n });\n\n return response;\n }\n );\n\n return response;\n}\n"],"mappings":"AACA,SAAS,UAAU,iBAAiB;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAElC,SAAS,kBAAkB;AAC3B,SAAS,4BAA4B;AACrC,SAAS,kBAAkB;AAE3B,SAAS,UAAU,0BAA0B;AAC7C,SAAS,wBAAwB,6BAAuD;AACxF,SAAS,kCAAkC;AAC3C,SAAS,4BAA4B;AACrC,SAAS,8BAA8B;AACvC,SAAS,yCAAyC;AAClD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B,4BAA4B;AA4BhE,MAAM,kBAAkB,oBAAI,IAAuB;AACnD,MAAM,qBAAqB,oBAAI,IAAgC;AAC/D,MAAM,uBAAuB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UAAU,UAAU;AAAA,QACpC,SAAS,aAAa,QAAQ;AAAA,QAC9B,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MACpC,CAAC;AAED,aAAOA;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":["response"]}
@@ -4,5 +4,5 @@
4
4
  "source_sha": "4e553ad955f83b49c7d221ab5c3ff78237ad02e3",
5
5
  "source_tarball_sha256": "580656d6466ef9f0d1119985e6726c2efea718dc671e2ad30957fcb2fd54af0f",
6
6
  "upstream_adcp_version": "2.5.3",
7
- "synced_at": "2026-07-19T01:37:04.433Z"
7
+ "synced_at": "2026-07-23T00:22:46.176Z"
8
8
  }
@@ -36,7 +36,7 @@ export type { CreativeAdServerPlatform, BuildCreativeReturn as CreativeAdServerB
36
36
  export type { CampaignGovernancePlatform, CheckGovernancePayload, SyncPlansPayload, ReportPlanOutcomePayload, GetPlanAuditLogsPayload, } from './specialisms/campaign-governance.mjs';
37
37
  export type { ContentStandardsPlatform, ListContentStandardsPayload, GetContentStandardsPayload, CreateContentStandardsPayload, UpdateContentStandardsPayload, CalibrateContentPayload, ValidateContentDeliveryPayload, GetMediaBuyArtifactsPayload, GetCreativeFeaturesPayload, } from './specialisms/content-standards.mjs';
38
38
  export type { PropertyListsPlatform, CollectionListsPlatform, CreatePropertyListPayload, UpdatePropertyListPayload, GetPropertyListPayload, ListPropertyListsPayload, DeletePropertyListPayload, CreateCollectionListPayload, UpdateCollectionListPayload, GetCollectionListPayload, ListCollectionListsPayload, DeleteCollectionListPayload, } from './specialisms/lists.mjs';
39
- export type { SalesPlatform, SalesCorePlatform, SalesIngestionPlatform, GetProductsPayload, GetProductsHandlerResult, CreateMediaBuyPayload, CreateMediaBuyHandlerResult, UpdateMediaBuyPayload, GetMediaBuyDeliveryPayload, GetMediaBuysPayload, ProvidePerformanceFeedbackPayload, ListCreativeFormatsPayload, ListCreativesPayload, SyncCreativesPayload, SyncCreativesHandlerResult, SyncCatalogsPayload, LogEventPayload, SyncEventSourcesPayload, } from './specialisms/sales.mjs';
39
+ export type { SalesPlatform, SalesCorePlatform, SalesIngestionPlatform, GetProductsPayload, GetProductsHandlerResult, CreateMediaBuyPayload, CreateMediaBuyHandlerResult, UpdateMediaBuyPayload, UpdateMediaBuyHandlerResult, GetMediaBuyDeliveryPayload, GetMediaBuysPayload, ProvidePerformanceFeedbackPayload, ListCreativeFormatsPayload, ListCreativesPayload, SyncCreativesPayload, SyncCreativesHandlerResult, SyncCatalogsPayload, LogEventPayload, SyncEventSourcesPayload, } from './specialisms/sales.mjs';
40
40
  export type { AudiencePlatform, Audience, SyncAudiencesPayload, SyncAudiencesRow, SyncAudiencesHandlerResult, AudienceStatus, } from './specialisms/audiences.mjs';
41
41
  export type { SignalsPlatform, GetSignalsPayload, GetSignalsHandlerResult, ActivateSignalPayload, } from './specialisms/signals.mjs';
42
42
  export type { SponsoredIntelligencePlatform, SIGetOfferingPayload, SIInitiateSessionPayload, SISendMessagePayload, SITerminateSessionPayload, } from './specialisms/sponsored-intelligence.mjs';
@@ -36,7 +36,7 @@ export type { CreativeAdServerPlatform, BuildCreativeReturn as CreativeAdServerB
36
36
  export type { CampaignGovernancePlatform, CheckGovernancePayload, SyncPlansPayload, ReportPlanOutcomePayload, GetPlanAuditLogsPayload, } from './specialisms/campaign-governance';
37
37
  export type { ContentStandardsPlatform, ListContentStandardsPayload, GetContentStandardsPayload, CreateContentStandardsPayload, UpdateContentStandardsPayload, CalibrateContentPayload, ValidateContentDeliveryPayload, GetMediaBuyArtifactsPayload, GetCreativeFeaturesPayload, } from './specialisms/content-standards';
38
38
  export type { PropertyListsPlatform, CollectionListsPlatform, CreatePropertyListPayload, UpdatePropertyListPayload, GetPropertyListPayload, ListPropertyListsPayload, DeletePropertyListPayload, CreateCollectionListPayload, UpdateCollectionListPayload, GetCollectionListPayload, ListCollectionListsPayload, DeleteCollectionListPayload, } from './specialisms/lists';
39
- export type { SalesPlatform, SalesCorePlatform, SalesIngestionPlatform, GetProductsPayload, GetProductsHandlerResult, CreateMediaBuyPayload, CreateMediaBuyHandlerResult, UpdateMediaBuyPayload, GetMediaBuyDeliveryPayload, GetMediaBuysPayload, ProvidePerformanceFeedbackPayload, ListCreativeFormatsPayload, ListCreativesPayload, SyncCreativesPayload, SyncCreativesHandlerResult, SyncCatalogsPayload, LogEventPayload, SyncEventSourcesPayload, } from './specialisms/sales';
39
+ export type { SalesPlatform, SalesCorePlatform, SalesIngestionPlatform, GetProductsPayload, GetProductsHandlerResult, CreateMediaBuyPayload, CreateMediaBuyHandlerResult, UpdateMediaBuyPayload, UpdateMediaBuyHandlerResult, GetMediaBuyDeliveryPayload, GetMediaBuysPayload, ProvidePerformanceFeedbackPayload, ListCreativeFormatsPayload, ListCreativesPayload, SyncCreativesPayload, SyncCreativesHandlerResult, SyncCatalogsPayload, LogEventPayload, SyncEventSourcesPayload, } from './specialisms/sales';
40
40
  export type { AudiencePlatform, Audience, SyncAudiencesPayload, SyncAudiencesRow, SyncAudiencesHandlerResult, AudienceStatus, } from './specialisms/audiences';
41
41
  export type { SignalsPlatform, GetSignalsPayload, GetSignalsHandlerResult, ActivateSignalPayload, } from './specialisms/signals';
42
42
  export type { SponsoredIntelligencePlatform, SIGetOfferingPayload, SIInitiateSessionPayload, SISendMessagePayload, SITerminateSessionPayload, } from './specialisms/sponsored-intelligence';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/lib/server/decisioning/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAYH,OAAO,EAAE,KAAK,mBAAmB,EAAE,KAAK,SAAS,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AACtF,YAAY,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAC1D,YAAY,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAMhE,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EACrB,oBAAoB,EACpB,qBAAqB,EACrB,uBAAuB,EACvB,qBAAqB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EAAE,MAAM,oBAAoB,CAAC;AACpF,YAAY,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/lib/server/decisioning/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAYH,OAAO,EAAE,KAAK,mBAAmB,EAAE,KAAK,SAAS,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AACtF,YAAY,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAC1D,YAAY,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAMhE,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EACrB,oBAAoB,EACpB,qBAAqB,EACrB,uBAAuB,EACvB,qBAAqB,EACrB,iBAAiB,EACjB,oBAAoB,EACpB,wBAAwB,EACxB,mBAAmB,EACnB,iBAAiB,EACjB,uBAAuB,EACvB,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,qBAAqB,EACrB,gBAAgB,EAChB,uBAAuB,EACvB,uBAAuB,EACvB,0BAA0B,EAC1B,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,gBAAgB,CAAC;AAGxB,YAAY,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAO9D,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,kBAAkB,EAClB,6BAA6B,EAC7B,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,wBAAwB,EAC7B,KAAK,oBAAoB,EACzB,KAAK,uBAAuB,GAC7B,MAAM,kBAAkB,CAAC;AAG1B,YAAY,EACV,uBAAuB,EACvB,6BAA6B,EAC7B,gBAAgB,EAChB,qBAAqB,EACrB,0BAA0B,EAC1B,qBAAqB,GACtB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,0BAA0B,EAAE,8BAA8B,EAAE,MAAM,gBAAgB,CAAC;AAG5F,YAAY,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M,EACN,iBAAiB,EACjB,uBAAuB,EACvB,uBAAuB,EACvB,aAAa,EACb,cAAc,EACd,aAAa,EACb,4BAA4B,EAC5B,0BAA0B,GAC3B,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,4BAA4B,EAC5B,qBAAqB,EACrB,mBAAmB,EACnB,qBAAqB,EACrB,yBAAyB,EACzB,2BAA2B,EAC3B,oBAAoB,EACpB,0BAA0B,EAC1B,sBAAsB,EACtB,iCAAiC,EACjC,qCAAqC,EACrC,2BAA2B,EAC3B,0BAA0B,EAC1B,gCAAgC,GACjC,MAAM,YAAY,CAAC;AACpB,YAAY,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAMxH,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACpF,YAAY,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/lib/server/decisioning/index.ts"],"sourcesContent":["/**\n * DecisioningPlatform v1.0 — preview surface for the v6.0 architecture.\n *\n * Status: PREVIEW. Types only; not yet wired into the framework. Subject\n * to change before 6.0 ships. Don't build production adapters against this\n * yet — the framework still routes through the v5.x handler-style API.\n *\n * Design proposal: `.context/proposals/specialism-platform-interfaces-v3.md`\n *\n * @packageDocumentation\n */\n\n// Adopter-facing structured-error primitive.\n//\n// `AdcpError` is the canonical throwable for structured rejection. Specialism\n// methods return plain `T` for success or `throw new AdcpError(...)` to project\n// to the wire `adcp_error` envelope.\n//\n// HITL is expressed in the type system via the dual-method shape on each\n// spec-HITL tool (`xxx` for sync, `xxxTask` for HITL). No adopter-facing\n// task primitives — the framework owns task lifecycle and dispatches the\n// `*Task` method in the background.\nexport { type AdcpStructuredError, type ErrorCode, AdcpError } from './async-outcome';\nexport type { TaskHandoffOptions } from './async-outcome';\nexport type { ServerPayload } from '../../types/server-payload';\n\n// Typed `AdcpError` subclasses — adopter convenience for the highest-traffic\n// error codes. Each class encodes the canonical code/recovery/field shape.\n// LLM-generated platforms get autocomplete on the import; humans skim the\n// list to find the right class. See `errors-typed.ts`.\nexport {\n PackageNotFoundError,\n MediaBuyNotFoundError,\n ProductNotFoundError,\n CreativeNotFoundError,\n ProductUnavailableError,\n CreativeRejectedError,\n BudgetTooLowError,\n BudgetExhaustedError,\n IdempotencyConflictError,\n InvalidRequestError,\n InvalidStateError,\n BackwardsTimeRangeError,\n AuthMissingError,\n AuthInvalidError,\n AuthRequiredError,\n PermissionDeniedError,\n RateLimitedError,\n ServiceUnavailableError,\n UnsupportedFeatureError,\n ComplianceUnsatisfiedError,\n GovernanceDeniedError,\n PolicyViolationError,\n} from './errors-typed';\n\n// Cursor pagination\nexport type { CursorPage, CursorRequest } from './pagination';\n\n// Status-change event bus — adopter-facing primitive for spec-native\n// lifecycle channels (media_buy / creative / audience / signal / proposal /\n// plan / rights_grant / delivery_report). Module-level so adopters can\n// publish from webhook handlers, crons, in-process workers without holding\n// a server reference.\nexport {\n publishStatusChange,\n setStatusChangeBus,\n getStatusChangeBus,\n createInMemoryStatusChangeBus,\n type StatusChange,\n type StatusChangeBus,\n type StatusChangeResourceType,\n type StatusChangeListener,\n type PublishStatusChangeOpts,\n} from './status-changes';\n\n// Capabilities (single source of truth for get_adcp_capabilities)\nexport type {\n DecisioningCapabilities,\n ComplianceTestingCapabilities,\n CreativeAgentRef,\n TargetingCapabilities,\n TargetingPostalAreaSupport,\n ReportingCapabilities,\n} from './capabilities';\nexport { normalizePostalAreaSupport, normalizeTargetingCapabilities } from './capabilities';\n\n// Account model\nexport type {\n Account,\n AuthPrincipal,\n AccountStore,\n AccountFilter,\n ListAccountsPayload,\n SyncAccountsPayload,\n SyncAccountsSuccessPayload,\n SyncAccountsRow,\n SyncAccountsResultRow,\n SyncGovernancePayload,\n SyncGovernanceSuccessPayload,\n SyncGovernanceRow,\n ReportUsagePayload,\n GetAccountFinancialsPayload,\n GetAccountFinancialsSuccessPayload,\n ListAccountsHandlerResult,\n SyncAccountsHandlerResult,\n SyncGovernanceHandlerResult,\n ReportUsageHandlerResult,\n GetAccountFinancialsHandlerResult,\n AdcpAccountStatus,\n ResolveContext,\n AccountToolContext,\n ResolvedAuthInfo,\n} from './account';\n\nexport { AccountNotFoundError, refAccountId } from './account';\n\n// Multi-tenant AccountStore builder. Bakes in the two-path resolution\n// (operator-routed + auth-derived) and the per-entry tenant-isolation gate\n// that adopters historically had to hand-write — and silently fail to\n// hand-write — on `accounts.upsert` / `accounts.syncGovernance`.\nexport { createTenantStore, narrowAccountRef } from './tenant-store';\nexport type { TenantStoreConfig } from './tenant-store';\n\n// Buyer-agent identity surface — Phase 1 of #1269. Durable commercial\n// relationship records keyed off the request credential. Factory-pattern\n// registry (signing-only / bearer-only / mixed) encodes the implementer\n// posture at construction; framework calls `BuyerAgentRegistry.resolve`\n// once per request before `accounts.resolve`. Phase 1 ships the shape and\n// resolution; framework-level billing-capability enforcement and the\n// AdCP-3.1 error-code emission land in Phase 2 (#1292).\nexport type {\n BuyerAgent,\n BuyerAgentBillingMode,\n BuyerAgentStatus,\n BuyerAgentRegistry as BuyerAgentRegistryProtocol,\n BuyerAgentResolveInput,\n BuyerAgentCacheOptions,\n CachedBuyerAgentRegistry,\n AdcpCredential,\n ResolveBuyerAgentByAgentUrl,\n ResolveBuyerAgentByCredential,\n} from './buyer-agent';\nexport { BuyerAgentRegistry } from './buyer-agent';\n\n// Native status mapping\nexport type { StatusMappers, AdcpMediaBuyStatus, AdcpCreativeStatus, AdcpPlanStatus } from './status-mappers';\nexport { identityStatusMappers } from './status-mappers';\n\n// Request context (state + resolve)\nexport type {\n RequestContext,\n WorkflowStateReader,\n ResourceResolver,\n WorkflowObjectType,\n WorkflowStep,\n Proposal,\n GovernanceContextJWS,\n} from './context';\n\n// Top-level platform + compile-time capability enforcement\nexport type { DecisioningPlatform, RequiredPlatformsFor, RequiredCapabilitiesFor } from './platform';\n\n// Method-level composition (closes #1314) — wrap individual platform methods\n// with `before` / `after` hooks for short-circuit + enrichment patterns.\nexport { composeMethod } from './compose';\nexport type { ComposeHooks, ComposeShortCircuit } from './compose';\n\n// `accounts.resolve` security presets (closes #1339) — canonical post-resolve\n// guards that standardize the multi-tenant authorization pattern instead of\n// every adopter rolling their own.\nexport { requireAccountMatch, requireAdvertiserMatch, requireOrgScope } from './resolve-presets';\nexport type { ResolveAccountHooks, ResolveGuardOptions } from './resolve-presets';\n\n// Specialism interfaces (v1.0)\nexport type {\n CreativeBuilderPlatform,\n BuildCreativeReturn,\n BuildCreativePayload,\n BuildCreativeMultiPayload,\n PreviewCreativePayload as CreativePreviewCreativePayload,\n ListCreativeFormatsPayload as CreativeListCreativeFormatsPayload,\n // Deprecated aliases — kept for one-release source compat. Both\n // resolve to CreativeBuilderPlatform; see specialisms/creative.ts.\n CreativeTemplatePlatform,\n CreativeGenerativePlatform,\n RefinementMessage,\n SyncCreativesRow,\n} from './specialisms/creative';\n\nexport type {\n CreativeAdServerPlatform,\n BuildCreativeReturn as CreativeAdServerBuildCreativeReturn,\n BuildCreativePayload as CreativeAdServerBuildCreativePayload,\n BuildCreativeMultiPayload as CreativeAdServerBuildCreativeMultiPayload,\n PreviewCreativePayload as CreativeAdServerPreviewCreativePayload,\n ListCreativeFormatsPayload as CreativeAdServerListCreativeFormatsPayload,\n ListCreativesPayload as CreativeAdServerListCreativesPayload,\n GetCreativeDeliveryPayload as CreativeAdServerGetCreativeDeliveryPayload,\n} from './specialisms/creative-ad-server';\n\nexport type {\n CampaignGovernancePlatform,\n CheckGovernancePayload,\n SyncPlansPayload,\n ReportPlanOutcomePayload,\n GetPlanAuditLogsPayload,\n} from './specialisms/campaign-governance';\n\nexport type {\n ContentStandardsPlatform,\n ListContentStandardsPayload,\n GetContentStandardsPayload,\n CreateContentStandardsPayload,\n UpdateContentStandardsPayload,\n CalibrateContentPayload,\n ValidateContentDeliveryPayload,\n GetMediaBuyArtifactsPayload,\n GetCreativeFeaturesPayload,\n} from './specialisms/content-standards';\n\nexport type {\n PropertyListsPlatform,\n CollectionListsPlatform,\n CreatePropertyListPayload,\n UpdatePropertyListPayload,\n GetPropertyListPayload,\n ListPropertyListsPayload,\n DeletePropertyListPayload,\n CreateCollectionListPayload,\n UpdateCollectionListPayload,\n GetCollectionListPayload,\n ListCollectionListsPayload,\n DeleteCollectionListPayload,\n} from './specialisms/lists';\n\nexport type {\n SalesPlatform,\n SalesCorePlatform,\n SalesIngestionPlatform,\n GetProductsPayload,\n GetProductsHandlerResult,\n CreateMediaBuyPayload,\n CreateMediaBuyHandlerResult,\n UpdateMediaBuyPayload,\n GetMediaBuyDeliveryPayload,\n GetMediaBuysPayload,\n ProvidePerformanceFeedbackPayload,\n ListCreativeFormatsPayload,\n ListCreativesPayload,\n SyncCreativesPayload,\n SyncCreativesHandlerResult,\n SyncCatalogsPayload,\n LogEventPayload,\n SyncEventSourcesPayload,\n} from './specialisms/sales';\n\nexport type {\n AudiencePlatform,\n Audience,\n SyncAudiencesPayload,\n SyncAudiencesRow,\n SyncAudiencesHandlerResult,\n AudienceStatus,\n} from './specialisms/audiences';\n\nexport type {\n SignalsPlatform,\n GetSignalsPayload,\n GetSignalsHandlerResult,\n ActivateSignalPayload,\n} from './specialisms/signals';\n\nexport type {\n SponsoredIntelligencePlatform,\n SIGetOfferingPayload,\n SIInitiateSessionPayload,\n SISendMessagePayload,\n SITerminateSessionPayload,\n} from './specialisms/sponsored-intelligence';\n\nexport type {\n BrandRightsPlatform,\n GetBrandIdentityPayload,\n GetRightsPayload,\n AcquireRightsAcquiredPayload,\n AcquireRightsPendingApprovalPayload,\n AcquireRightsRejectedPayload,\n AcquireRightsPayload,\n UpdateRightsPayload,\n CreativeApprovedPayload,\n CreativeRejectedPayload,\n CreativePendingReviewPayload,\n CreativeApprovalPayload,\n} from './specialisms/brand-rights';\n\n// Brand-rights wire types — re-exported from `@adcp/sdk/server/decisioning`\n// because brand-rights is the only specialism whose wire types live in\n// `core.generated` (not `tools.generated`), and the public `@adcp/sdk/types`\n// barrel doesn't surface them. Adopters typing their own helper functions\n// import these from here, NOT from the deep `core.generated` path.\nexport type {\n GetBrandIdentityRequest,\n GetBrandIdentitySuccess,\n GetRightsRequest,\n GetRightsSuccess,\n AcquireRightsRequest,\n AcquireRightsAcquired,\n AcquireRightsPendingApproval,\n AcquireRightsRejected,\n AcquireRightsError,\n RightUse,\n RightType,\n RightsConstraint,\n RightsTerms,\n RightsPricingOption,\n GenerationCredential,\n} from '../../types/core.generated';\n\n// Runtime (v6.0 alpha) — preview surface for adopters spiking against the\n// new shape. Subject to change before 6.0 GA.\nexport {\n createAdcpServerFromPlatform,\n getAllAdcpMigrations,\n type CreateAdcpServerFromPlatformOptions,\n type RequiredOptsFor,\n type DecisioningAdcpServer,\n type DecisioningObservabilityHooks,\n} from './runtime/from-platform';\nexport { PlatformConfigError, validatePlatform } from './runtime/validate-platform';\nexport {\n createInMemoryTaskRegistry,\n type TaskRegistry,\n type TaskRecord,\n type TaskStatus,\n} from './runtime/task-registry';\nexport {\n createPostgresTaskRegistry,\n getDecisioningTaskRegistryMigration,\n type CreatePostgresTaskRegistryOptions,\n type PgQueryable,\n} from './runtime/postgres-task-registry';\n\n// Multi-tenant deployment helper — wraps createAdcpServerFromPlatform with\n// per-tenant config, health states (healthy/unverified/disabled), and JWKS\n// validation. Composes with the existing serve() host-routing surface.\nexport {\n createTenantRegistry,\n createDefaultJwksValidator,\n createSelfSignedTenantKey,\n createNoopJwksValidator,\n type TenantRegistry,\n type TenantConfig,\n type TenantSigningKey,\n type TenantStatus,\n type TenantHealth,\n type TenantRegistryOptions,\n type JwksValidator,\n type JwksValidationResult,\n} from './tenant-registry';\n\n// Manifest helpers — typed accessors for creative_manifest.assets values.\n// Save adopters from writing the same null-check + discriminator-check\n// boilerplate per call.\nexport { getAsset, requireAsset } from './manifest-helpers';\n\n// List helpers — wrap row arrays + pagination into the heavier wire shapes\n// (today: list_creatives, which carries query_summary alongside the rows).\nexport { buildListCreativesResponse, type BuildListCreativesResponseOpts } from './list-helpers';\n\n// Start-time helper — normalize the wire `start_time` union into a Date,\n// with platform-aware ASAP lead-time injection.\nexport { resolveStartTime, type ResolveStartTimeOptions } from './start-time';\n\n// Admin Express router for ops visibility into the TenantRegistry.\n// Mount on a separate port/path with operator auth.\nexport {\n createTenantAdminRouter,\n createTenantAdminHandlers,\n mountTenantAdmin,\n type TenantAdminHandlers,\n type RouterLike,\n} from './admin-router';\n\n// Adopter helpers — batchPoll, validationError, upstreamError, RequestShape.\n// All opt-in convenience; nothing in the framework calls these internally.\nexport { batchPoll, validationError, upstreamError } from './helpers';\nexport type { RequestShape } from './helpers';\n\n// Platform identity helpers — fix TypeScript's contextual-typing gap when\n// building a DecisioningPlatform (or sub-interface) as an object literal.\n// Without these, `createAdcpServerFromPlatform({ sales: { syncEventSources:\n// async (req, ctx) => {...} } })` gives `req: unknown` because the generic\n// `P extends DecisioningPlatform<any,any>` is inferred, not declared.\n// Wrapping the sub-object with e.g. `defineSalesPlatform<MyMeta>({...})`\n// forces the concrete type annotation TypeScript needs. The helpers are\n// pure identity functions — zero runtime cost.\nexport {\n definePlatform,\n defineSalesPlatform,\n defineSalesCorePlatform,\n defineSalesIngestionPlatform,\n defineAudiencePlatform,\n defineSignalsPlatform,\n defineSponsoredIntelligencePlatform,\n defineCreativeBuilderPlatform,\n defineCreativeAdServerPlatform,\n defineCampaignGovernancePlatform,\n defineContentStandardsPlatform,\n definePropertyListsPlatform,\n defineCollectionListsPlatform,\n defineBrandRightsPlatform,\n definePlatformWithCompliance,\n} from './platform-helpers';\n\n// ProposalManager — primitives for the two-platform composition (port of\n// adcp-client-python PRs #504 + #550). Splits proposal assembly from\n// media-buy execution; either side can be mock-backed independently.\n// Framework dispatch wiring lands in a follow-up release.\nexport type {\n ProposalManager,\n ProposalCapabilities,\n ProposalSalesSpecialism,\n Recipe,\n CapabilityOverlap,\n FinalizeProposalRequest,\n FinalizeProposalSuccess,\n ProposalState,\n ProposalRecord,\n ProposalStore,\n InMemoryProposalStoreOptions,\n MockProposalManagerOptions,\n} from './proposal';\nexport {\n validateProposalCapabilities,\n InMemoryProposalStore,\n MockProposalManager,\n enforceProposalExpiry,\n validateCapabilityOverlap,\n validateOverlapSubsetOfWire,\n detectFinalizeAction,\n setProposalLifecycleLogger,\n maybeInterceptFinalize,\n maybePersistDraftAfterGetProducts,\n maybeReserveProposalForCreateMediaBuy,\n finalizeProposalConsumption,\n releaseProposalReservation,\n maybeHydrateRecipesForMediaBuyId,\n} from './proposal';\nexport type { FinalizeActionRef, ProposalLifecycleLogger, FinalizeInterceptResult, ReservedProposal } from './proposal';\n\n// Wire-shape assembly helpers — emit correct Product / PricingOption /\n// package shapes from intent-shaped input. Reduces 30+ lines of wire\n// boilerplate per resource. Used in slim skill examples so LLMs scaffold\n// correct shapes from first attempt.\nexport { buildProduct, buildPricingOption, buildPackage } from './assembly-helpers';\nexport type { BuildProductInput, BuildPricingOptionInput, BuildPackageInput } from './assembly-helpers';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAsBA,2BAAoE;AAQpE,0BAuBO;AAUP,4BAUO;AAWP,0BAA2E;AA8B3E,qBAAmD;AAMnD,0BAAoD;AAsBpD,yBAAmC;AAInC,4BAAsC;AAkBtC,qBAA8B;AAM9B,6BAA6E;AAsJ7E,2BAOO;AACP,+BAAsD;AACtD,2BAKO;AACP,oCAKO;AAKP,6BAaO;AAKP,8BAAuC;AAIvC,0BAAgF;AAIhF,wBAA+D;AAI/D,0BAMO;AAIP,qBAA0D;AAW1D,8BAgBO;AAoBP,sBAeO;AAOP,8BAA+D;","names":[]}
1
+ {"version":3,"sources":["../../../../src/lib/server/decisioning/index.ts"],"sourcesContent":["/**\n * DecisioningPlatform v1.0 — preview surface for the v6.0 architecture.\n *\n * Status: PREVIEW. Types only; not yet wired into the framework. Subject\n * to change before 6.0 ships. Don't build production adapters against this\n * yet — the framework still routes through the v5.x handler-style API.\n *\n * Design proposal: `.context/proposals/specialism-platform-interfaces-v3.md`\n *\n * @packageDocumentation\n */\n\n// Adopter-facing structured-error primitive.\n//\n// `AdcpError` is the canonical throwable for structured rejection. Specialism\n// methods return plain `T` for success or `throw new AdcpError(...)` to project\n// to the wire `adcp_error` envelope.\n//\n// HITL is expressed in the type system via the dual-method shape on each\n// spec-HITL tool (`xxx` for sync, `xxxTask` for HITL). No adopter-facing\n// task primitives — the framework owns task lifecycle and dispatches the\n// `*Task` method in the background.\nexport { type AdcpStructuredError, type ErrorCode, AdcpError } from './async-outcome';\nexport type { TaskHandoffOptions } from './async-outcome';\nexport type { ServerPayload } from '../../types/server-payload';\n\n// Typed `AdcpError` subclasses — adopter convenience for the highest-traffic\n// error codes. Each class encodes the canonical code/recovery/field shape.\n// LLM-generated platforms get autocomplete on the import; humans skim the\n// list to find the right class. See `errors-typed.ts`.\nexport {\n PackageNotFoundError,\n MediaBuyNotFoundError,\n ProductNotFoundError,\n CreativeNotFoundError,\n ProductUnavailableError,\n CreativeRejectedError,\n BudgetTooLowError,\n BudgetExhaustedError,\n IdempotencyConflictError,\n InvalidRequestError,\n InvalidStateError,\n BackwardsTimeRangeError,\n AuthMissingError,\n AuthInvalidError,\n AuthRequiredError,\n PermissionDeniedError,\n RateLimitedError,\n ServiceUnavailableError,\n UnsupportedFeatureError,\n ComplianceUnsatisfiedError,\n GovernanceDeniedError,\n PolicyViolationError,\n} from './errors-typed';\n\n// Cursor pagination\nexport type { CursorPage, CursorRequest } from './pagination';\n\n// Status-change event bus — adopter-facing primitive for spec-native\n// lifecycle channels (media_buy / creative / audience / signal / proposal /\n// plan / rights_grant / delivery_report). Module-level so adopters can\n// publish from webhook handlers, crons, in-process workers without holding\n// a server reference.\nexport {\n publishStatusChange,\n setStatusChangeBus,\n getStatusChangeBus,\n createInMemoryStatusChangeBus,\n type StatusChange,\n type StatusChangeBus,\n type StatusChangeResourceType,\n type StatusChangeListener,\n type PublishStatusChangeOpts,\n} from './status-changes';\n\n// Capabilities (single source of truth for get_adcp_capabilities)\nexport type {\n DecisioningCapabilities,\n ComplianceTestingCapabilities,\n CreativeAgentRef,\n TargetingCapabilities,\n TargetingPostalAreaSupport,\n ReportingCapabilities,\n} from './capabilities';\nexport { normalizePostalAreaSupport, normalizeTargetingCapabilities } from './capabilities';\n\n// Account model\nexport type {\n Account,\n AuthPrincipal,\n AccountStore,\n AccountFilter,\n ListAccountsPayload,\n SyncAccountsPayload,\n SyncAccountsSuccessPayload,\n SyncAccountsRow,\n SyncAccountsResultRow,\n SyncGovernancePayload,\n SyncGovernanceSuccessPayload,\n SyncGovernanceRow,\n ReportUsagePayload,\n GetAccountFinancialsPayload,\n GetAccountFinancialsSuccessPayload,\n ListAccountsHandlerResult,\n SyncAccountsHandlerResult,\n SyncGovernanceHandlerResult,\n ReportUsageHandlerResult,\n GetAccountFinancialsHandlerResult,\n AdcpAccountStatus,\n ResolveContext,\n AccountToolContext,\n ResolvedAuthInfo,\n} from './account';\n\nexport { AccountNotFoundError, refAccountId } from './account';\n\n// Multi-tenant AccountStore builder. Bakes in the two-path resolution\n// (operator-routed + auth-derived) and the per-entry tenant-isolation gate\n// that adopters historically had to hand-write — and silently fail to\n// hand-write — on `accounts.upsert` / `accounts.syncGovernance`.\nexport { createTenantStore, narrowAccountRef } from './tenant-store';\nexport type { TenantStoreConfig } from './tenant-store';\n\n// Buyer-agent identity surface — Phase 1 of #1269. Durable commercial\n// relationship records keyed off the request credential. Factory-pattern\n// registry (signing-only / bearer-only / mixed) encodes the implementer\n// posture at construction; framework calls `BuyerAgentRegistry.resolve`\n// once per request before `accounts.resolve`. Phase 1 ships the shape and\n// resolution; framework-level billing-capability enforcement and the\n// AdCP-3.1 error-code emission land in Phase 2 (#1292).\nexport type {\n BuyerAgent,\n BuyerAgentBillingMode,\n BuyerAgentStatus,\n BuyerAgentRegistry as BuyerAgentRegistryProtocol,\n BuyerAgentResolveInput,\n BuyerAgentCacheOptions,\n CachedBuyerAgentRegistry,\n AdcpCredential,\n ResolveBuyerAgentByAgentUrl,\n ResolveBuyerAgentByCredential,\n} from './buyer-agent';\nexport { BuyerAgentRegistry } from './buyer-agent';\n\n// Native status mapping\nexport type { StatusMappers, AdcpMediaBuyStatus, AdcpCreativeStatus, AdcpPlanStatus } from './status-mappers';\nexport { identityStatusMappers } from './status-mappers';\n\n// Request context (state + resolve)\nexport type {\n RequestContext,\n WorkflowStateReader,\n ResourceResolver,\n WorkflowObjectType,\n WorkflowStep,\n Proposal,\n GovernanceContextJWS,\n} from './context';\n\n// Top-level platform + compile-time capability enforcement\nexport type { DecisioningPlatform, RequiredPlatformsFor, RequiredCapabilitiesFor } from './platform';\n\n// Method-level composition (closes #1314) — wrap individual platform methods\n// with `before` / `after` hooks for short-circuit + enrichment patterns.\nexport { composeMethod } from './compose';\nexport type { ComposeHooks, ComposeShortCircuit } from './compose';\n\n// `accounts.resolve` security presets (closes #1339) — canonical post-resolve\n// guards that standardize the multi-tenant authorization pattern instead of\n// every adopter rolling their own.\nexport { requireAccountMatch, requireAdvertiserMatch, requireOrgScope } from './resolve-presets';\nexport type { ResolveAccountHooks, ResolveGuardOptions } from './resolve-presets';\n\n// Specialism interfaces (v1.0)\nexport type {\n CreativeBuilderPlatform,\n BuildCreativeReturn,\n BuildCreativePayload,\n BuildCreativeMultiPayload,\n PreviewCreativePayload as CreativePreviewCreativePayload,\n ListCreativeFormatsPayload as CreativeListCreativeFormatsPayload,\n // Deprecated aliases — kept for one-release source compat. Both\n // resolve to CreativeBuilderPlatform; see specialisms/creative.ts.\n CreativeTemplatePlatform,\n CreativeGenerativePlatform,\n RefinementMessage,\n SyncCreativesRow,\n} from './specialisms/creative';\n\nexport type {\n CreativeAdServerPlatform,\n BuildCreativeReturn as CreativeAdServerBuildCreativeReturn,\n BuildCreativePayload as CreativeAdServerBuildCreativePayload,\n BuildCreativeMultiPayload as CreativeAdServerBuildCreativeMultiPayload,\n PreviewCreativePayload as CreativeAdServerPreviewCreativePayload,\n ListCreativeFormatsPayload as CreativeAdServerListCreativeFormatsPayload,\n ListCreativesPayload as CreativeAdServerListCreativesPayload,\n GetCreativeDeliveryPayload as CreativeAdServerGetCreativeDeliveryPayload,\n} from './specialisms/creative-ad-server';\n\nexport type {\n CampaignGovernancePlatform,\n CheckGovernancePayload,\n SyncPlansPayload,\n ReportPlanOutcomePayload,\n GetPlanAuditLogsPayload,\n} from './specialisms/campaign-governance';\n\nexport type {\n ContentStandardsPlatform,\n ListContentStandardsPayload,\n GetContentStandardsPayload,\n CreateContentStandardsPayload,\n UpdateContentStandardsPayload,\n CalibrateContentPayload,\n ValidateContentDeliveryPayload,\n GetMediaBuyArtifactsPayload,\n GetCreativeFeaturesPayload,\n} from './specialisms/content-standards';\n\nexport type {\n PropertyListsPlatform,\n CollectionListsPlatform,\n CreatePropertyListPayload,\n UpdatePropertyListPayload,\n GetPropertyListPayload,\n ListPropertyListsPayload,\n DeletePropertyListPayload,\n CreateCollectionListPayload,\n UpdateCollectionListPayload,\n GetCollectionListPayload,\n ListCollectionListsPayload,\n DeleteCollectionListPayload,\n} from './specialisms/lists';\n\nexport type {\n SalesPlatform,\n SalesCorePlatform,\n SalesIngestionPlatform,\n GetProductsPayload,\n GetProductsHandlerResult,\n CreateMediaBuyPayload,\n CreateMediaBuyHandlerResult,\n UpdateMediaBuyPayload,\n UpdateMediaBuyHandlerResult,\n GetMediaBuyDeliveryPayload,\n GetMediaBuysPayload,\n ProvidePerformanceFeedbackPayload,\n ListCreativeFormatsPayload,\n ListCreativesPayload,\n SyncCreativesPayload,\n SyncCreativesHandlerResult,\n SyncCatalogsPayload,\n LogEventPayload,\n SyncEventSourcesPayload,\n} from './specialisms/sales';\n\nexport type {\n AudiencePlatform,\n Audience,\n SyncAudiencesPayload,\n SyncAudiencesRow,\n SyncAudiencesHandlerResult,\n AudienceStatus,\n} from './specialisms/audiences';\n\nexport type {\n SignalsPlatform,\n GetSignalsPayload,\n GetSignalsHandlerResult,\n ActivateSignalPayload,\n} from './specialisms/signals';\n\nexport type {\n SponsoredIntelligencePlatform,\n SIGetOfferingPayload,\n SIInitiateSessionPayload,\n SISendMessagePayload,\n SITerminateSessionPayload,\n} from './specialisms/sponsored-intelligence';\n\nexport type {\n BrandRightsPlatform,\n GetBrandIdentityPayload,\n GetRightsPayload,\n AcquireRightsAcquiredPayload,\n AcquireRightsPendingApprovalPayload,\n AcquireRightsRejectedPayload,\n AcquireRightsPayload,\n UpdateRightsPayload,\n CreativeApprovedPayload,\n CreativeRejectedPayload,\n CreativePendingReviewPayload,\n CreativeApprovalPayload,\n} from './specialisms/brand-rights';\n\n// Brand-rights wire types — re-exported from `@adcp/sdk/server/decisioning`\n// because brand-rights is the only specialism whose wire types live in\n// `core.generated` (not `tools.generated`), and the public `@adcp/sdk/types`\n// barrel doesn't surface them. Adopters typing their own helper functions\n// import these from here, NOT from the deep `core.generated` path.\nexport type {\n GetBrandIdentityRequest,\n GetBrandIdentitySuccess,\n GetRightsRequest,\n GetRightsSuccess,\n AcquireRightsRequest,\n AcquireRightsAcquired,\n AcquireRightsPendingApproval,\n AcquireRightsRejected,\n AcquireRightsError,\n RightUse,\n RightType,\n RightsConstraint,\n RightsTerms,\n RightsPricingOption,\n GenerationCredential,\n} from '../../types/core.generated';\n\n// Runtime (v6.0 alpha) — preview surface for adopters spiking against the\n// new shape. Subject to change before 6.0 GA.\nexport {\n createAdcpServerFromPlatform,\n getAllAdcpMigrations,\n type CreateAdcpServerFromPlatformOptions,\n type RequiredOptsFor,\n type DecisioningAdcpServer,\n type DecisioningObservabilityHooks,\n} from './runtime/from-platform';\nexport { PlatformConfigError, validatePlatform } from './runtime/validate-platform';\nexport {\n createInMemoryTaskRegistry,\n type TaskRegistry,\n type TaskRecord,\n type TaskStatus,\n} from './runtime/task-registry';\nexport {\n createPostgresTaskRegistry,\n getDecisioningTaskRegistryMigration,\n type CreatePostgresTaskRegistryOptions,\n type PgQueryable,\n} from './runtime/postgres-task-registry';\n\n// Multi-tenant deployment helper — wraps createAdcpServerFromPlatform with\n// per-tenant config, health states (healthy/unverified/disabled), and JWKS\n// validation. Composes with the existing serve() host-routing surface.\nexport {\n createTenantRegistry,\n createDefaultJwksValidator,\n createSelfSignedTenantKey,\n createNoopJwksValidator,\n type TenantRegistry,\n type TenantConfig,\n type TenantSigningKey,\n type TenantStatus,\n type TenantHealth,\n type TenantRegistryOptions,\n type JwksValidator,\n type JwksValidationResult,\n} from './tenant-registry';\n\n// Manifest helpers — typed accessors for creative_manifest.assets values.\n// Save adopters from writing the same null-check + discriminator-check\n// boilerplate per call.\nexport { getAsset, requireAsset } from './manifest-helpers';\n\n// List helpers — wrap row arrays + pagination into the heavier wire shapes\n// (today: list_creatives, which carries query_summary alongside the rows).\nexport { buildListCreativesResponse, type BuildListCreativesResponseOpts } from './list-helpers';\n\n// Start-time helper — normalize the wire `start_time` union into a Date,\n// with platform-aware ASAP lead-time injection.\nexport { resolveStartTime, type ResolveStartTimeOptions } from './start-time';\n\n// Admin Express router for ops visibility into the TenantRegistry.\n// Mount on a separate port/path with operator auth.\nexport {\n createTenantAdminRouter,\n createTenantAdminHandlers,\n mountTenantAdmin,\n type TenantAdminHandlers,\n type RouterLike,\n} from './admin-router';\n\n// Adopter helpers — batchPoll, validationError, upstreamError, RequestShape.\n// All opt-in convenience; nothing in the framework calls these internally.\nexport { batchPoll, validationError, upstreamError } from './helpers';\nexport type { RequestShape } from './helpers';\n\n// Platform identity helpers — fix TypeScript's contextual-typing gap when\n// building a DecisioningPlatform (or sub-interface) as an object literal.\n// Without these, `createAdcpServerFromPlatform({ sales: { syncEventSources:\n// async (req, ctx) => {...} } })` gives `req: unknown` because the generic\n// `P extends DecisioningPlatform<any,any>` is inferred, not declared.\n// Wrapping the sub-object with e.g. `defineSalesPlatform<MyMeta>({...})`\n// forces the concrete type annotation TypeScript needs. The helpers are\n// pure identity functions — zero runtime cost.\nexport {\n definePlatform,\n defineSalesPlatform,\n defineSalesCorePlatform,\n defineSalesIngestionPlatform,\n defineAudiencePlatform,\n defineSignalsPlatform,\n defineSponsoredIntelligencePlatform,\n defineCreativeBuilderPlatform,\n defineCreativeAdServerPlatform,\n defineCampaignGovernancePlatform,\n defineContentStandardsPlatform,\n definePropertyListsPlatform,\n defineCollectionListsPlatform,\n defineBrandRightsPlatform,\n definePlatformWithCompliance,\n} from './platform-helpers';\n\n// ProposalManager — primitives for the two-platform composition (port of\n// adcp-client-python PRs #504 + #550). Splits proposal assembly from\n// media-buy execution; either side can be mock-backed independently.\n// Framework dispatch wiring lands in a follow-up release.\nexport type {\n ProposalManager,\n ProposalCapabilities,\n ProposalSalesSpecialism,\n Recipe,\n CapabilityOverlap,\n FinalizeProposalRequest,\n FinalizeProposalSuccess,\n ProposalState,\n ProposalRecord,\n ProposalStore,\n InMemoryProposalStoreOptions,\n MockProposalManagerOptions,\n} from './proposal';\nexport {\n validateProposalCapabilities,\n InMemoryProposalStore,\n MockProposalManager,\n enforceProposalExpiry,\n validateCapabilityOverlap,\n validateOverlapSubsetOfWire,\n detectFinalizeAction,\n setProposalLifecycleLogger,\n maybeInterceptFinalize,\n maybePersistDraftAfterGetProducts,\n maybeReserveProposalForCreateMediaBuy,\n finalizeProposalConsumption,\n releaseProposalReservation,\n maybeHydrateRecipesForMediaBuyId,\n} from './proposal';\nexport type { FinalizeActionRef, ProposalLifecycleLogger, FinalizeInterceptResult, ReservedProposal } from './proposal';\n\n// Wire-shape assembly helpers — emit correct Product / PricingOption /\n// package shapes from intent-shaped input. Reduces 30+ lines of wire\n// boilerplate per resource. Used in slim skill examples so LLMs scaffold\n// correct shapes from first attempt.\nexport { buildProduct, buildPricingOption, buildPackage } from './assembly-helpers';\nexport type { BuildProductInput, BuildPricingOptionInput, BuildPackageInput } from './assembly-helpers';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAsBA,2BAAoE;AAQpE,0BAuBO;AAUP,4BAUO;AAWP,0BAA2E;AA8B3E,qBAAmD;AAMnD,0BAAoD;AAsBpD,yBAAmC;AAInC,4BAAsC;AAkBtC,qBAA8B;AAM9B,6BAA6E;AAuJ7E,2BAOO;AACP,+BAAsD;AACtD,2BAKO;AACP,oCAKO;AAKP,6BAaO;AAKP,8BAAuC;AAIvC,0BAAgF;AAIhF,wBAA+D;AAI/D,0BAMO;AAIP,qBAA0D;AAW1D,8BAgBO;AAoBP,sBAeO;AAOP,8BAA+D;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/lib/server/decisioning/index.ts"],"sourcesContent":["/**\n * DecisioningPlatform v1.0 — preview surface for the v6.0 architecture.\n *\n * Status: PREVIEW. Types only; not yet wired into the framework. Subject\n * to change before 6.0 ships. Don't build production adapters against this\n * yet — the framework still routes through the v5.x handler-style API.\n *\n * Design proposal: `.context/proposals/specialism-platform-interfaces-v3.md`\n *\n * @packageDocumentation\n */\n\n// Adopter-facing structured-error primitive.\n//\n// `AdcpError` is the canonical throwable for structured rejection. Specialism\n// methods return plain `T` for success or `throw new AdcpError(...)` to project\n// to the wire `adcp_error` envelope.\n//\n// HITL is expressed in the type system via the dual-method shape on each\n// spec-HITL tool (`xxx` for sync, `xxxTask` for HITL). No adopter-facing\n// task primitives — the framework owns task lifecycle and dispatches the\n// `*Task` method in the background.\nexport { type AdcpStructuredError, type ErrorCode, AdcpError } from './async-outcome';\nexport type { TaskHandoffOptions } from './async-outcome';\nexport type { ServerPayload } from '../../types/server-payload';\n\n// Typed `AdcpError` subclasses — adopter convenience for the highest-traffic\n// error codes. Each class encodes the canonical code/recovery/field shape.\n// LLM-generated platforms get autocomplete on the import; humans skim the\n// list to find the right class. See `errors-typed.ts`.\nexport {\n PackageNotFoundError,\n MediaBuyNotFoundError,\n ProductNotFoundError,\n CreativeNotFoundError,\n ProductUnavailableError,\n CreativeRejectedError,\n BudgetTooLowError,\n BudgetExhaustedError,\n IdempotencyConflictError,\n InvalidRequestError,\n InvalidStateError,\n BackwardsTimeRangeError,\n AuthMissingError,\n AuthInvalidError,\n AuthRequiredError,\n PermissionDeniedError,\n RateLimitedError,\n ServiceUnavailableError,\n UnsupportedFeatureError,\n ComplianceUnsatisfiedError,\n GovernanceDeniedError,\n PolicyViolationError,\n} from './errors-typed';\n\n// Cursor pagination\nexport type { CursorPage, CursorRequest } from './pagination';\n\n// Status-change event bus — adopter-facing primitive for spec-native\n// lifecycle channels (media_buy / creative / audience / signal / proposal /\n// plan / rights_grant / delivery_report). Module-level so adopters can\n// publish from webhook handlers, crons, in-process workers without holding\n// a server reference.\nexport {\n publishStatusChange,\n setStatusChangeBus,\n getStatusChangeBus,\n createInMemoryStatusChangeBus,\n type StatusChange,\n type StatusChangeBus,\n type StatusChangeResourceType,\n type StatusChangeListener,\n type PublishStatusChangeOpts,\n} from './status-changes';\n\n// Capabilities (single source of truth for get_adcp_capabilities)\nexport type {\n DecisioningCapabilities,\n ComplianceTestingCapabilities,\n CreativeAgentRef,\n TargetingCapabilities,\n TargetingPostalAreaSupport,\n ReportingCapabilities,\n} from './capabilities';\nexport { normalizePostalAreaSupport, normalizeTargetingCapabilities } from './capabilities';\n\n// Account model\nexport type {\n Account,\n AuthPrincipal,\n AccountStore,\n AccountFilter,\n ListAccountsPayload,\n SyncAccountsPayload,\n SyncAccountsSuccessPayload,\n SyncAccountsRow,\n SyncAccountsResultRow,\n SyncGovernancePayload,\n SyncGovernanceSuccessPayload,\n SyncGovernanceRow,\n ReportUsagePayload,\n GetAccountFinancialsPayload,\n GetAccountFinancialsSuccessPayload,\n ListAccountsHandlerResult,\n SyncAccountsHandlerResult,\n SyncGovernanceHandlerResult,\n ReportUsageHandlerResult,\n GetAccountFinancialsHandlerResult,\n AdcpAccountStatus,\n ResolveContext,\n AccountToolContext,\n ResolvedAuthInfo,\n} from './account';\n\nexport { AccountNotFoundError, refAccountId } from './account';\n\n// Multi-tenant AccountStore builder. Bakes in the two-path resolution\n// (operator-routed + auth-derived) and the per-entry tenant-isolation gate\n// that adopters historically had to hand-write — and silently fail to\n// hand-write — on `accounts.upsert` / `accounts.syncGovernance`.\nexport { createTenantStore, narrowAccountRef } from './tenant-store';\nexport type { TenantStoreConfig } from './tenant-store';\n\n// Buyer-agent identity surface — Phase 1 of #1269. Durable commercial\n// relationship records keyed off the request credential. Factory-pattern\n// registry (signing-only / bearer-only / mixed) encodes the implementer\n// posture at construction; framework calls `BuyerAgentRegistry.resolve`\n// once per request before `accounts.resolve`. Phase 1 ships the shape and\n// resolution; framework-level billing-capability enforcement and the\n// AdCP-3.1 error-code emission land in Phase 2 (#1292).\nexport type {\n BuyerAgent,\n BuyerAgentBillingMode,\n BuyerAgentStatus,\n BuyerAgentRegistry as BuyerAgentRegistryProtocol,\n BuyerAgentResolveInput,\n BuyerAgentCacheOptions,\n CachedBuyerAgentRegistry,\n AdcpCredential,\n ResolveBuyerAgentByAgentUrl,\n ResolveBuyerAgentByCredential,\n} from './buyer-agent';\nexport { BuyerAgentRegistry } from './buyer-agent';\n\n// Native status mapping\nexport type { StatusMappers, AdcpMediaBuyStatus, AdcpCreativeStatus, AdcpPlanStatus } from './status-mappers';\nexport { identityStatusMappers } from './status-mappers';\n\n// Request context (state + resolve)\nexport type {\n RequestContext,\n WorkflowStateReader,\n ResourceResolver,\n WorkflowObjectType,\n WorkflowStep,\n Proposal,\n GovernanceContextJWS,\n} from './context';\n\n// Top-level platform + compile-time capability enforcement\nexport type { DecisioningPlatform, RequiredPlatformsFor, RequiredCapabilitiesFor } from './platform';\n\n// Method-level composition (closes #1314) — wrap individual platform methods\n// with `before` / `after` hooks for short-circuit + enrichment patterns.\nexport { composeMethod } from './compose';\nexport type { ComposeHooks, ComposeShortCircuit } from './compose';\n\n// `accounts.resolve` security presets (closes #1339) — canonical post-resolve\n// guards that standardize the multi-tenant authorization pattern instead of\n// every adopter rolling their own.\nexport { requireAccountMatch, requireAdvertiserMatch, requireOrgScope } from './resolve-presets';\nexport type { ResolveAccountHooks, ResolveGuardOptions } from './resolve-presets';\n\n// Specialism interfaces (v1.0)\nexport type {\n CreativeBuilderPlatform,\n BuildCreativeReturn,\n BuildCreativePayload,\n BuildCreativeMultiPayload,\n PreviewCreativePayload as CreativePreviewCreativePayload,\n ListCreativeFormatsPayload as CreativeListCreativeFormatsPayload,\n // Deprecated aliases — kept for one-release source compat. Both\n // resolve to CreativeBuilderPlatform; see specialisms/creative.ts.\n CreativeTemplatePlatform,\n CreativeGenerativePlatform,\n RefinementMessage,\n SyncCreativesRow,\n} from './specialisms/creative';\n\nexport type {\n CreativeAdServerPlatform,\n BuildCreativeReturn as CreativeAdServerBuildCreativeReturn,\n BuildCreativePayload as CreativeAdServerBuildCreativePayload,\n BuildCreativeMultiPayload as CreativeAdServerBuildCreativeMultiPayload,\n PreviewCreativePayload as CreativeAdServerPreviewCreativePayload,\n ListCreativeFormatsPayload as CreativeAdServerListCreativeFormatsPayload,\n ListCreativesPayload as CreativeAdServerListCreativesPayload,\n GetCreativeDeliveryPayload as CreativeAdServerGetCreativeDeliveryPayload,\n} from './specialisms/creative-ad-server';\n\nexport type {\n CampaignGovernancePlatform,\n CheckGovernancePayload,\n SyncPlansPayload,\n ReportPlanOutcomePayload,\n GetPlanAuditLogsPayload,\n} from './specialisms/campaign-governance';\n\nexport type {\n ContentStandardsPlatform,\n ListContentStandardsPayload,\n GetContentStandardsPayload,\n CreateContentStandardsPayload,\n UpdateContentStandardsPayload,\n CalibrateContentPayload,\n ValidateContentDeliveryPayload,\n GetMediaBuyArtifactsPayload,\n GetCreativeFeaturesPayload,\n} from './specialisms/content-standards';\n\nexport type {\n PropertyListsPlatform,\n CollectionListsPlatform,\n CreatePropertyListPayload,\n UpdatePropertyListPayload,\n GetPropertyListPayload,\n ListPropertyListsPayload,\n DeletePropertyListPayload,\n CreateCollectionListPayload,\n UpdateCollectionListPayload,\n GetCollectionListPayload,\n ListCollectionListsPayload,\n DeleteCollectionListPayload,\n} from './specialisms/lists';\n\nexport type {\n SalesPlatform,\n SalesCorePlatform,\n SalesIngestionPlatform,\n GetProductsPayload,\n GetProductsHandlerResult,\n CreateMediaBuyPayload,\n CreateMediaBuyHandlerResult,\n UpdateMediaBuyPayload,\n GetMediaBuyDeliveryPayload,\n GetMediaBuysPayload,\n ProvidePerformanceFeedbackPayload,\n ListCreativeFormatsPayload,\n ListCreativesPayload,\n SyncCreativesPayload,\n SyncCreativesHandlerResult,\n SyncCatalogsPayload,\n LogEventPayload,\n SyncEventSourcesPayload,\n} from './specialisms/sales';\n\nexport type {\n AudiencePlatform,\n Audience,\n SyncAudiencesPayload,\n SyncAudiencesRow,\n SyncAudiencesHandlerResult,\n AudienceStatus,\n} from './specialisms/audiences';\n\nexport type {\n SignalsPlatform,\n GetSignalsPayload,\n GetSignalsHandlerResult,\n ActivateSignalPayload,\n} from './specialisms/signals';\n\nexport type {\n SponsoredIntelligencePlatform,\n SIGetOfferingPayload,\n SIInitiateSessionPayload,\n SISendMessagePayload,\n SITerminateSessionPayload,\n} from './specialisms/sponsored-intelligence';\n\nexport type {\n BrandRightsPlatform,\n GetBrandIdentityPayload,\n GetRightsPayload,\n AcquireRightsAcquiredPayload,\n AcquireRightsPendingApprovalPayload,\n AcquireRightsRejectedPayload,\n AcquireRightsPayload,\n UpdateRightsPayload,\n CreativeApprovedPayload,\n CreativeRejectedPayload,\n CreativePendingReviewPayload,\n CreativeApprovalPayload,\n} from './specialisms/brand-rights';\n\n// Brand-rights wire types — re-exported from `@adcp/sdk/server/decisioning`\n// because brand-rights is the only specialism whose wire types live in\n// `core.generated` (not `tools.generated`), and the public `@adcp/sdk/types`\n// barrel doesn't surface them. Adopters typing their own helper functions\n// import these from here, NOT from the deep `core.generated` path.\nexport type {\n GetBrandIdentityRequest,\n GetBrandIdentitySuccess,\n GetRightsRequest,\n GetRightsSuccess,\n AcquireRightsRequest,\n AcquireRightsAcquired,\n AcquireRightsPendingApproval,\n AcquireRightsRejected,\n AcquireRightsError,\n RightUse,\n RightType,\n RightsConstraint,\n RightsTerms,\n RightsPricingOption,\n GenerationCredential,\n} from '../../types/core.generated';\n\n// Runtime (v6.0 alpha) — preview surface for adopters spiking against the\n// new shape. Subject to change before 6.0 GA.\nexport {\n createAdcpServerFromPlatform,\n getAllAdcpMigrations,\n type CreateAdcpServerFromPlatformOptions,\n type RequiredOptsFor,\n type DecisioningAdcpServer,\n type DecisioningObservabilityHooks,\n} from './runtime/from-platform';\nexport { PlatformConfigError, validatePlatform } from './runtime/validate-platform';\nexport {\n createInMemoryTaskRegistry,\n type TaskRegistry,\n type TaskRecord,\n type TaskStatus,\n} from './runtime/task-registry';\nexport {\n createPostgresTaskRegistry,\n getDecisioningTaskRegistryMigration,\n type CreatePostgresTaskRegistryOptions,\n type PgQueryable,\n} from './runtime/postgres-task-registry';\n\n// Multi-tenant deployment helper — wraps createAdcpServerFromPlatform with\n// per-tenant config, health states (healthy/unverified/disabled), and JWKS\n// validation. Composes with the existing serve() host-routing surface.\nexport {\n createTenantRegistry,\n createDefaultJwksValidator,\n createSelfSignedTenantKey,\n createNoopJwksValidator,\n type TenantRegistry,\n type TenantConfig,\n type TenantSigningKey,\n type TenantStatus,\n type TenantHealth,\n type TenantRegistryOptions,\n type JwksValidator,\n type JwksValidationResult,\n} from './tenant-registry';\n\n// Manifest helpers — typed accessors for creative_manifest.assets values.\n// Save adopters from writing the same null-check + discriminator-check\n// boilerplate per call.\nexport { getAsset, requireAsset } from './manifest-helpers';\n\n// List helpers — wrap row arrays + pagination into the heavier wire shapes\n// (today: list_creatives, which carries query_summary alongside the rows).\nexport { buildListCreativesResponse, type BuildListCreativesResponseOpts } from './list-helpers';\n\n// Start-time helper — normalize the wire `start_time` union into a Date,\n// with platform-aware ASAP lead-time injection.\nexport { resolveStartTime, type ResolveStartTimeOptions } from './start-time';\n\n// Admin Express router for ops visibility into the TenantRegistry.\n// Mount on a separate port/path with operator auth.\nexport {\n createTenantAdminRouter,\n createTenantAdminHandlers,\n mountTenantAdmin,\n type TenantAdminHandlers,\n type RouterLike,\n} from './admin-router';\n\n// Adopter helpers — batchPoll, validationError, upstreamError, RequestShape.\n// All opt-in convenience; nothing in the framework calls these internally.\nexport { batchPoll, validationError, upstreamError } from './helpers';\nexport type { RequestShape } from './helpers';\n\n// Platform identity helpers — fix TypeScript's contextual-typing gap when\n// building a DecisioningPlatform (or sub-interface) as an object literal.\n// Without these, `createAdcpServerFromPlatform({ sales: { syncEventSources:\n// async (req, ctx) => {...} } })` gives `req: unknown` because the generic\n// `P extends DecisioningPlatform<any,any>` is inferred, not declared.\n// Wrapping the sub-object with e.g. `defineSalesPlatform<MyMeta>({...})`\n// forces the concrete type annotation TypeScript needs. The helpers are\n// pure identity functions — zero runtime cost.\nexport {\n definePlatform,\n defineSalesPlatform,\n defineSalesCorePlatform,\n defineSalesIngestionPlatform,\n defineAudiencePlatform,\n defineSignalsPlatform,\n defineSponsoredIntelligencePlatform,\n defineCreativeBuilderPlatform,\n defineCreativeAdServerPlatform,\n defineCampaignGovernancePlatform,\n defineContentStandardsPlatform,\n definePropertyListsPlatform,\n defineCollectionListsPlatform,\n defineBrandRightsPlatform,\n definePlatformWithCompliance,\n} from './platform-helpers';\n\n// ProposalManager — primitives for the two-platform composition (port of\n// adcp-client-python PRs #504 + #550). Splits proposal assembly from\n// media-buy execution; either side can be mock-backed independently.\n// Framework dispatch wiring lands in a follow-up release.\nexport type {\n ProposalManager,\n ProposalCapabilities,\n ProposalSalesSpecialism,\n Recipe,\n CapabilityOverlap,\n FinalizeProposalRequest,\n FinalizeProposalSuccess,\n ProposalState,\n ProposalRecord,\n ProposalStore,\n InMemoryProposalStoreOptions,\n MockProposalManagerOptions,\n} from './proposal';\nexport {\n validateProposalCapabilities,\n InMemoryProposalStore,\n MockProposalManager,\n enforceProposalExpiry,\n validateCapabilityOverlap,\n validateOverlapSubsetOfWire,\n detectFinalizeAction,\n setProposalLifecycleLogger,\n maybeInterceptFinalize,\n maybePersistDraftAfterGetProducts,\n maybeReserveProposalForCreateMediaBuy,\n finalizeProposalConsumption,\n releaseProposalReservation,\n maybeHydrateRecipesForMediaBuyId,\n} from './proposal';\nexport type { FinalizeActionRef, ProposalLifecycleLogger, FinalizeInterceptResult, ReservedProposal } from './proposal';\n\n// Wire-shape assembly helpers — emit correct Product / PricingOption /\n// package shapes from intent-shaped input. Reduces 30+ lines of wire\n// boilerplate per resource. Used in slim skill examples so LLMs scaffold\n// correct shapes from first attempt.\nexport { buildProduct, buildPricingOption, buildPackage } from './assembly-helpers';\nexport type { BuildProductInput, BuildPricingOptionInput, BuildPackageInput } from './assembly-helpers';\n"],"mappings":"AAsBA,SAAmD,iBAAiB;AAQpE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAUP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMK;AAWP,SAAS,4BAA4B,sCAAsC;AA8B3E,SAAS,sBAAsB,oBAAoB;AAMnD,SAAS,mBAAmB,wBAAwB;AAsBpD,SAAS,0BAA0B;AAInC,SAAS,6BAA6B;AAkBtC,SAAS,qBAAqB;AAM9B,SAAS,qBAAqB,wBAAwB,uBAAuB;AAsJ7E;AAAA,EACE;AAAA,EACA;AAAA,OAKK;AACP,SAAS,qBAAqB,wBAAwB;AACtD;AAAA,EACE;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAKP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OASK;AAKP,SAAS,UAAU,oBAAoB;AAIvC,SAAS,kCAAuE;AAIhF,SAAS,wBAAsD;AAI/D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAIP,SAAS,WAAW,iBAAiB,qBAAqB;AAW1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAoBP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAOP,SAAS,cAAc,oBAAoB,oBAAoB;","names":[]}
1
+ {"version":3,"sources":["../../../../src/lib/server/decisioning/index.ts"],"sourcesContent":["/**\n * DecisioningPlatform v1.0 — preview surface for the v6.0 architecture.\n *\n * Status: PREVIEW. Types only; not yet wired into the framework. Subject\n * to change before 6.0 ships. Don't build production adapters against this\n * yet — the framework still routes through the v5.x handler-style API.\n *\n * Design proposal: `.context/proposals/specialism-platform-interfaces-v3.md`\n *\n * @packageDocumentation\n */\n\n// Adopter-facing structured-error primitive.\n//\n// `AdcpError` is the canonical throwable for structured rejection. Specialism\n// methods return plain `T` for success or `throw new AdcpError(...)` to project\n// to the wire `adcp_error` envelope.\n//\n// HITL is expressed in the type system via the dual-method shape on each\n// spec-HITL tool (`xxx` for sync, `xxxTask` for HITL). No adopter-facing\n// task primitives — the framework owns task lifecycle and dispatches the\n// `*Task` method in the background.\nexport { type AdcpStructuredError, type ErrorCode, AdcpError } from './async-outcome';\nexport type { TaskHandoffOptions } from './async-outcome';\nexport type { ServerPayload } from '../../types/server-payload';\n\n// Typed `AdcpError` subclasses — adopter convenience for the highest-traffic\n// error codes. Each class encodes the canonical code/recovery/field shape.\n// LLM-generated platforms get autocomplete on the import; humans skim the\n// list to find the right class. See `errors-typed.ts`.\nexport {\n PackageNotFoundError,\n MediaBuyNotFoundError,\n ProductNotFoundError,\n CreativeNotFoundError,\n ProductUnavailableError,\n CreativeRejectedError,\n BudgetTooLowError,\n BudgetExhaustedError,\n IdempotencyConflictError,\n InvalidRequestError,\n InvalidStateError,\n BackwardsTimeRangeError,\n AuthMissingError,\n AuthInvalidError,\n AuthRequiredError,\n PermissionDeniedError,\n RateLimitedError,\n ServiceUnavailableError,\n UnsupportedFeatureError,\n ComplianceUnsatisfiedError,\n GovernanceDeniedError,\n PolicyViolationError,\n} from './errors-typed';\n\n// Cursor pagination\nexport type { CursorPage, CursorRequest } from './pagination';\n\n// Status-change event bus — adopter-facing primitive for spec-native\n// lifecycle channels (media_buy / creative / audience / signal / proposal /\n// plan / rights_grant / delivery_report). Module-level so adopters can\n// publish from webhook handlers, crons, in-process workers without holding\n// a server reference.\nexport {\n publishStatusChange,\n setStatusChangeBus,\n getStatusChangeBus,\n createInMemoryStatusChangeBus,\n type StatusChange,\n type StatusChangeBus,\n type StatusChangeResourceType,\n type StatusChangeListener,\n type PublishStatusChangeOpts,\n} from './status-changes';\n\n// Capabilities (single source of truth for get_adcp_capabilities)\nexport type {\n DecisioningCapabilities,\n ComplianceTestingCapabilities,\n CreativeAgentRef,\n TargetingCapabilities,\n TargetingPostalAreaSupport,\n ReportingCapabilities,\n} from './capabilities';\nexport { normalizePostalAreaSupport, normalizeTargetingCapabilities } from './capabilities';\n\n// Account model\nexport type {\n Account,\n AuthPrincipal,\n AccountStore,\n AccountFilter,\n ListAccountsPayload,\n SyncAccountsPayload,\n SyncAccountsSuccessPayload,\n SyncAccountsRow,\n SyncAccountsResultRow,\n SyncGovernancePayload,\n SyncGovernanceSuccessPayload,\n SyncGovernanceRow,\n ReportUsagePayload,\n GetAccountFinancialsPayload,\n GetAccountFinancialsSuccessPayload,\n ListAccountsHandlerResult,\n SyncAccountsHandlerResult,\n SyncGovernanceHandlerResult,\n ReportUsageHandlerResult,\n GetAccountFinancialsHandlerResult,\n AdcpAccountStatus,\n ResolveContext,\n AccountToolContext,\n ResolvedAuthInfo,\n} from './account';\n\nexport { AccountNotFoundError, refAccountId } from './account';\n\n// Multi-tenant AccountStore builder. Bakes in the two-path resolution\n// (operator-routed + auth-derived) and the per-entry tenant-isolation gate\n// that adopters historically had to hand-write — and silently fail to\n// hand-write — on `accounts.upsert` / `accounts.syncGovernance`.\nexport { createTenantStore, narrowAccountRef } from './tenant-store';\nexport type { TenantStoreConfig } from './tenant-store';\n\n// Buyer-agent identity surface — Phase 1 of #1269. Durable commercial\n// relationship records keyed off the request credential. Factory-pattern\n// registry (signing-only / bearer-only / mixed) encodes the implementer\n// posture at construction; framework calls `BuyerAgentRegistry.resolve`\n// once per request before `accounts.resolve`. Phase 1 ships the shape and\n// resolution; framework-level billing-capability enforcement and the\n// AdCP-3.1 error-code emission land in Phase 2 (#1292).\nexport type {\n BuyerAgent,\n BuyerAgentBillingMode,\n BuyerAgentStatus,\n BuyerAgentRegistry as BuyerAgentRegistryProtocol,\n BuyerAgentResolveInput,\n BuyerAgentCacheOptions,\n CachedBuyerAgentRegistry,\n AdcpCredential,\n ResolveBuyerAgentByAgentUrl,\n ResolveBuyerAgentByCredential,\n} from './buyer-agent';\nexport { BuyerAgentRegistry } from './buyer-agent';\n\n// Native status mapping\nexport type { StatusMappers, AdcpMediaBuyStatus, AdcpCreativeStatus, AdcpPlanStatus } from './status-mappers';\nexport { identityStatusMappers } from './status-mappers';\n\n// Request context (state + resolve)\nexport type {\n RequestContext,\n WorkflowStateReader,\n ResourceResolver,\n WorkflowObjectType,\n WorkflowStep,\n Proposal,\n GovernanceContextJWS,\n} from './context';\n\n// Top-level platform + compile-time capability enforcement\nexport type { DecisioningPlatform, RequiredPlatformsFor, RequiredCapabilitiesFor } from './platform';\n\n// Method-level composition (closes #1314) — wrap individual platform methods\n// with `before` / `after` hooks for short-circuit + enrichment patterns.\nexport { composeMethod } from './compose';\nexport type { ComposeHooks, ComposeShortCircuit } from './compose';\n\n// `accounts.resolve` security presets (closes #1339) — canonical post-resolve\n// guards that standardize the multi-tenant authorization pattern instead of\n// every adopter rolling their own.\nexport { requireAccountMatch, requireAdvertiserMatch, requireOrgScope } from './resolve-presets';\nexport type { ResolveAccountHooks, ResolveGuardOptions } from './resolve-presets';\n\n// Specialism interfaces (v1.0)\nexport type {\n CreativeBuilderPlatform,\n BuildCreativeReturn,\n BuildCreativePayload,\n BuildCreativeMultiPayload,\n PreviewCreativePayload as CreativePreviewCreativePayload,\n ListCreativeFormatsPayload as CreativeListCreativeFormatsPayload,\n // Deprecated aliases — kept for one-release source compat. Both\n // resolve to CreativeBuilderPlatform; see specialisms/creative.ts.\n CreativeTemplatePlatform,\n CreativeGenerativePlatform,\n RefinementMessage,\n SyncCreativesRow,\n} from './specialisms/creative';\n\nexport type {\n CreativeAdServerPlatform,\n BuildCreativeReturn as CreativeAdServerBuildCreativeReturn,\n BuildCreativePayload as CreativeAdServerBuildCreativePayload,\n BuildCreativeMultiPayload as CreativeAdServerBuildCreativeMultiPayload,\n PreviewCreativePayload as CreativeAdServerPreviewCreativePayload,\n ListCreativeFormatsPayload as CreativeAdServerListCreativeFormatsPayload,\n ListCreativesPayload as CreativeAdServerListCreativesPayload,\n GetCreativeDeliveryPayload as CreativeAdServerGetCreativeDeliveryPayload,\n} from './specialisms/creative-ad-server';\n\nexport type {\n CampaignGovernancePlatform,\n CheckGovernancePayload,\n SyncPlansPayload,\n ReportPlanOutcomePayload,\n GetPlanAuditLogsPayload,\n} from './specialisms/campaign-governance';\n\nexport type {\n ContentStandardsPlatform,\n ListContentStandardsPayload,\n GetContentStandardsPayload,\n CreateContentStandardsPayload,\n UpdateContentStandardsPayload,\n CalibrateContentPayload,\n ValidateContentDeliveryPayload,\n GetMediaBuyArtifactsPayload,\n GetCreativeFeaturesPayload,\n} from './specialisms/content-standards';\n\nexport type {\n PropertyListsPlatform,\n CollectionListsPlatform,\n CreatePropertyListPayload,\n UpdatePropertyListPayload,\n GetPropertyListPayload,\n ListPropertyListsPayload,\n DeletePropertyListPayload,\n CreateCollectionListPayload,\n UpdateCollectionListPayload,\n GetCollectionListPayload,\n ListCollectionListsPayload,\n DeleteCollectionListPayload,\n} from './specialisms/lists';\n\nexport type {\n SalesPlatform,\n SalesCorePlatform,\n SalesIngestionPlatform,\n GetProductsPayload,\n GetProductsHandlerResult,\n CreateMediaBuyPayload,\n CreateMediaBuyHandlerResult,\n UpdateMediaBuyPayload,\n UpdateMediaBuyHandlerResult,\n GetMediaBuyDeliveryPayload,\n GetMediaBuysPayload,\n ProvidePerformanceFeedbackPayload,\n ListCreativeFormatsPayload,\n ListCreativesPayload,\n SyncCreativesPayload,\n SyncCreativesHandlerResult,\n SyncCatalogsPayload,\n LogEventPayload,\n SyncEventSourcesPayload,\n} from './specialisms/sales';\n\nexport type {\n AudiencePlatform,\n Audience,\n SyncAudiencesPayload,\n SyncAudiencesRow,\n SyncAudiencesHandlerResult,\n AudienceStatus,\n} from './specialisms/audiences';\n\nexport type {\n SignalsPlatform,\n GetSignalsPayload,\n GetSignalsHandlerResult,\n ActivateSignalPayload,\n} from './specialisms/signals';\n\nexport type {\n SponsoredIntelligencePlatform,\n SIGetOfferingPayload,\n SIInitiateSessionPayload,\n SISendMessagePayload,\n SITerminateSessionPayload,\n} from './specialisms/sponsored-intelligence';\n\nexport type {\n BrandRightsPlatform,\n GetBrandIdentityPayload,\n GetRightsPayload,\n AcquireRightsAcquiredPayload,\n AcquireRightsPendingApprovalPayload,\n AcquireRightsRejectedPayload,\n AcquireRightsPayload,\n UpdateRightsPayload,\n CreativeApprovedPayload,\n CreativeRejectedPayload,\n CreativePendingReviewPayload,\n CreativeApprovalPayload,\n} from './specialisms/brand-rights';\n\n// Brand-rights wire types — re-exported from `@adcp/sdk/server/decisioning`\n// because brand-rights is the only specialism whose wire types live in\n// `core.generated` (not `tools.generated`), and the public `@adcp/sdk/types`\n// barrel doesn't surface them. Adopters typing their own helper functions\n// import these from here, NOT from the deep `core.generated` path.\nexport type {\n GetBrandIdentityRequest,\n GetBrandIdentitySuccess,\n GetRightsRequest,\n GetRightsSuccess,\n AcquireRightsRequest,\n AcquireRightsAcquired,\n AcquireRightsPendingApproval,\n AcquireRightsRejected,\n AcquireRightsError,\n RightUse,\n RightType,\n RightsConstraint,\n RightsTerms,\n RightsPricingOption,\n GenerationCredential,\n} from '../../types/core.generated';\n\n// Runtime (v6.0 alpha) — preview surface for adopters spiking against the\n// new shape. Subject to change before 6.0 GA.\nexport {\n createAdcpServerFromPlatform,\n getAllAdcpMigrations,\n type CreateAdcpServerFromPlatformOptions,\n type RequiredOptsFor,\n type DecisioningAdcpServer,\n type DecisioningObservabilityHooks,\n} from './runtime/from-platform';\nexport { PlatformConfigError, validatePlatform } from './runtime/validate-platform';\nexport {\n createInMemoryTaskRegistry,\n type TaskRegistry,\n type TaskRecord,\n type TaskStatus,\n} from './runtime/task-registry';\nexport {\n createPostgresTaskRegistry,\n getDecisioningTaskRegistryMigration,\n type CreatePostgresTaskRegistryOptions,\n type PgQueryable,\n} from './runtime/postgres-task-registry';\n\n// Multi-tenant deployment helper — wraps createAdcpServerFromPlatform with\n// per-tenant config, health states (healthy/unverified/disabled), and JWKS\n// validation. Composes with the existing serve() host-routing surface.\nexport {\n createTenantRegistry,\n createDefaultJwksValidator,\n createSelfSignedTenantKey,\n createNoopJwksValidator,\n type TenantRegistry,\n type TenantConfig,\n type TenantSigningKey,\n type TenantStatus,\n type TenantHealth,\n type TenantRegistryOptions,\n type JwksValidator,\n type JwksValidationResult,\n} from './tenant-registry';\n\n// Manifest helpers — typed accessors for creative_manifest.assets values.\n// Save adopters from writing the same null-check + discriminator-check\n// boilerplate per call.\nexport { getAsset, requireAsset } from './manifest-helpers';\n\n// List helpers — wrap row arrays + pagination into the heavier wire shapes\n// (today: list_creatives, which carries query_summary alongside the rows).\nexport { buildListCreativesResponse, type BuildListCreativesResponseOpts } from './list-helpers';\n\n// Start-time helper — normalize the wire `start_time` union into a Date,\n// with platform-aware ASAP lead-time injection.\nexport { resolveStartTime, type ResolveStartTimeOptions } from './start-time';\n\n// Admin Express router for ops visibility into the TenantRegistry.\n// Mount on a separate port/path with operator auth.\nexport {\n createTenantAdminRouter,\n createTenantAdminHandlers,\n mountTenantAdmin,\n type TenantAdminHandlers,\n type RouterLike,\n} from './admin-router';\n\n// Adopter helpers — batchPoll, validationError, upstreamError, RequestShape.\n// All opt-in convenience; nothing in the framework calls these internally.\nexport { batchPoll, validationError, upstreamError } from './helpers';\nexport type { RequestShape } from './helpers';\n\n// Platform identity helpers — fix TypeScript's contextual-typing gap when\n// building a DecisioningPlatform (or sub-interface) as an object literal.\n// Without these, `createAdcpServerFromPlatform({ sales: { syncEventSources:\n// async (req, ctx) => {...} } })` gives `req: unknown` because the generic\n// `P extends DecisioningPlatform<any,any>` is inferred, not declared.\n// Wrapping the sub-object with e.g. `defineSalesPlatform<MyMeta>({...})`\n// forces the concrete type annotation TypeScript needs. The helpers are\n// pure identity functions — zero runtime cost.\nexport {\n definePlatform,\n defineSalesPlatform,\n defineSalesCorePlatform,\n defineSalesIngestionPlatform,\n defineAudiencePlatform,\n defineSignalsPlatform,\n defineSponsoredIntelligencePlatform,\n defineCreativeBuilderPlatform,\n defineCreativeAdServerPlatform,\n defineCampaignGovernancePlatform,\n defineContentStandardsPlatform,\n definePropertyListsPlatform,\n defineCollectionListsPlatform,\n defineBrandRightsPlatform,\n definePlatformWithCompliance,\n} from './platform-helpers';\n\n// ProposalManager — primitives for the two-platform composition (port of\n// adcp-client-python PRs #504 + #550). Splits proposal assembly from\n// media-buy execution; either side can be mock-backed independently.\n// Framework dispatch wiring lands in a follow-up release.\nexport type {\n ProposalManager,\n ProposalCapabilities,\n ProposalSalesSpecialism,\n Recipe,\n CapabilityOverlap,\n FinalizeProposalRequest,\n FinalizeProposalSuccess,\n ProposalState,\n ProposalRecord,\n ProposalStore,\n InMemoryProposalStoreOptions,\n MockProposalManagerOptions,\n} from './proposal';\nexport {\n validateProposalCapabilities,\n InMemoryProposalStore,\n MockProposalManager,\n enforceProposalExpiry,\n validateCapabilityOverlap,\n validateOverlapSubsetOfWire,\n detectFinalizeAction,\n setProposalLifecycleLogger,\n maybeInterceptFinalize,\n maybePersistDraftAfterGetProducts,\n maybeReserveProposalForCreateMediaBuy,\n finalizeProposalConsumption,\n releaseProposalReservation,\n maybeHydrateRecipesForMediaBuyId,\n} from './proposal';\nexport type { FinalizeActionRef, ProposalLifecycleLogger, FinalizeInterceptResult, ReservedProposal } from './proposal';\n\n// Wire-shape assembly helpers — emit correct Product / PricingOption /\n// package shapes from intent-shaped input. Reduces 30+ lines of wire\n// boilerplate per resource. Used in slim skill examples so LLMs scaffold\n// correct shapes from first attempt.\nexport { buildProduct, buildPricingOption, buildPackage } from './assembly-helpers';\nexport type { BuildProductInput, BuildPricingOptionInput, BuildPackageInput } from './assembly-helpers';\n"],"mappings":"AAsBA,SAAmD,iBAAiB;AAQpE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAUP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMK;AAWP,SAAS,4BAA4B,sCAAsC;AA8B3E,SAAS,sBAAsB,oBAAoB;AAMnD,SAAS,mBAAmB,wBAAwB;AAsBpD,SAAS,0BAA0B;AAInC,SAAS,6BAA6B;AAkBtC,SAAS,qBAAqB;AAM9B,SAAS,qBAAqB,wBAAwB,uBAAuB;AAuJ7E;AAAA,EACE;AAAA,EACA;AAAA,OAKK;AACP,SAAS,qBAAqB,wBAAwB;AACtD;AAAA,EACE;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAKP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OASK;AAKP,SAAS,UAAU,oBAAoB;AAIvC,SAAS,kCAAuE;AAIhF,SAAS,wBAAsD;AAI/D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAIP,SAAS,WAAW,iBAAiB,qBAAqB;AAW1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAoBP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAOP,SAAS,cAAc,oBAAoB,oBAAoB;","names":[]}
@@ -2058,24 +2058,32 @@ function buildMediaBuyHandlers(platform, taskRegistry, taskWebhookEmit, observab
2058
2058
  allowPrivateWebhookUrls: pushOpts.allowPrivateWebhookUrls
2059
2059
  });
2060
2060
  const result = await sales.updateMediaBuy(media_buy_id, params, reqCtx);
2061
- await persistTargetingOverlayFromUpdate(mediaBuyStore, reqCtx.account?.id, media_buy_id, params, logger);
2062
- if (pushOpts.autoEmitCompletionWebhooks && push.url) {
2063
- const emitOpts = {
2061
+ return routeIfHandoff(
2062
+ taskRegistry,
2063
+ {
2064
2064
  tool: "update_media_buy",
2065
2065
  accountId: reqCtx.account.id,
2066
+ ownerScope: taskOwnerScopeFor(ctx, reqCtx.account.id),
2066
2067
  pushNotificationUrl: push.url,
2067
- ...push.token !== void 0 && { pushNotificationToken: push.token },
2068
- ...push.operationId !== void 0 && { pushNotificationOperationId: push.operationId },
2068
+ pushNotificationToken: push.token,
2069
+ pushNotificationOperationId: push.operationId,
2069
2070
  emitWebhook: taskWebhookEmit ?? ctx.emitWebhook,
2070
- ...observability && { observability },
2071
+ autoEmitCompletion: pushOpts.autoEmitCompletionWebhooks,
2072
+ observability,
2071
2073
  logger
2072
- };
2073
- void emitSyncCompletionWebhook(emitOpts, result).catch((err) => {
2074
- const msg = err instanceof Error ? err.message : String(err);
2075
- logger.warn(`[adcp/decisioning] sync completion webhook background-error: ${msg}`);
2076
- });
2077
- }
2078
- return result;
2074
+ },
2075
+ result,
2076
+ async (r) => {
2077
+ await persistTargetingOverlayFromUpdate(
2078
+ mediaBuyStore,
2079
+ reqCtx.account?.id,
2080
+ media_buy_id,
2081
+ params,
2082
+ logger
2083
+ );
2084
+ return r;
2085
+ }
2086
+ );
2079
2087
  },
2080
2088
  (r) => r
2081
2089
  );