@adcp/sdk 14.0.0-beta.5 → 14.0.0-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/core/AgentClient.d.ts.map +1 -1
- package/dist/lib/core/AgentClient.js +26 -10
- package/dist/lib/core/AgentClient.js.map +1 -1
- package/dist/lib/core/AgentClient.mjs +26 -10
- package/dist/lib/core/AgentClient.mjs.map +1 -1
- package/dist/lib/core/AsyncHandler.d.mts +4 -2
- package/dist/lib/core/AsyncHandler.d.ts +4 -2
- package/dist/lib/core/AsyncHandler.d.ts.map +1 -1
- package/dist/lib/core/AsyncHandler.js +15 -1
- package/dist/lib/core/AsyncHandler.js.map +1 -1
- package/dist/lib/core/AsyncHandler.mjs +15 -1
- package/dist/lib/core/AsyncHandler.mjs.map +1 -1
- package/dist/lib/core/SingleAgentClient.d.mts +3 -1
- package/dist/lib/core/SingleAgentClient.d.ts +3 -1
- package/dist/lib/core/SingleAgentClient.d.ts.map +1 -1
- package/dist/lib/core/SingleAgentClient.js +158 -39
- package/dist/lib/core/SingleAgentClient.js.map +1 -1
- package/dist/lib/core/SingleAgentClient.mjs +167 -40
- package/dist/lib/core/SingleAgentClient.mjs.map +1 -1
- package/dist/lib/core/TaskExecutor.d.mts +57 -2
- package/dist/lib/core/TaskExecutor.d.ts +57 -2
- package/dist/lib/core/TaskExecutor.d.ts.map +1 -1
- package/dist/lib/core/TaskExecutor.js +382 -44
- package/dist/lib/core/TaskExecutor.js.map +1 -1
- package/dist/lib/core/TaskExecutor.mjs +382 -45
- package/dist/lib/core/TaskExecutor.mjs.map +1 -1
- package/dist/lib/core/request-proposals-guard.d.mts +11 -0
- package/dist/lib/core/request-proposals-guard.d.ts +12 -0
- package/dist/lib/core/request-proposals-guard.d.ts.map +1 -0
- package/dist/lib/core/request-proposals-guard.js +65 -0
- package/dist/lib/core/request-proposals-guard.js.map +1 -0
- package/dist/lib/core/request-proposals-guard.mjs +39 -0
- package/dist/lib/core/request-proposals-guard.mjs.map +1 -0
- package/dist/lib/core/webhook-registration.d.mts +5 -0
- package/dist/lib/core/webhook-registration.d.ts +5 -0
- package/dist/lib/core/webhook-registration.d.ts.map +1 -1
- package/dist/lib/core/webhook-registration.js +13 -0
- package/dist/lib/core/webhook-registration.js.map +1 -1
- package/dist/lib/core/webhook-registration.mjs +13 -0
- package/dist/lib/core/webhook-registration.mjs.map +1 -1
- package/dist/lib/media-buy/compatibility.d.mts +45 -10
- package/dist/lib/media-buy/compatibility.d.ts +45 -10
- package/dist/lib/media-buy/compatibility.d.ts.map +1 -1
- package/dist/lib/media-buy/compatibility.js +295 -113
- package/dist/lib/media-buy/compatibility.js.map +1 -1
- package/dist/lib/media-buy/compatibility.mjs +295 -113
- package/dist/lib/media-buy/compatibility.mjs.map +1 -1
- package/dist/lib/schemas-data/v2.5/_provenance.json +1 -1
- package/dist/lib/testing/storyboard/validations.d.mts +1 -1
- package/dist/lib/testing/storyboard/validations.d.ts +1 -1
- package/dist/lib/types/core.generated.d.mts +334 -85
- package/dist/lib/types/core.generated.d.ts +334 -85
- package/dist/lib/types/core.generated.d.ts.map +1 -1
- package/dist/lib/types/core.generated.js.map +1 -1
- package/dist/lib/types/decline-proposals.d.ts +0 -5
- package/dist/lib/types/index.d.mts +2 -0
- package/dist/lib/types/index.d.ts +2 -0
- package/dist/lib/types/index.d.ts.map +1 -1
- package/dist/lib/types/index.js.map +1 -1
- package/dist/lib/types/index.mjs.map +1 -1
- package/dist/lib/types/request-proposals.d.ts +254 -36
- package/dist/lib/types/schemas.generated.d.ts +3123 -835
- package/dist/lib/types/schemas.generated.d.ts.map +1 -1
- package/dist/lib/types/schemas.generated.js +192 -85
- package/dist/lib/types/schemas.generated.js.map +1 -1
- package/dist/lib/types/schemas.generated.mjs +192 -85
- package/dist/lib/types/schemas.generated.mjs.map +1 -1
- package/dist/lib/types/tools.generated.d.mts +1 -121
- package/dist/lib/types/tools.generated.d.ts +1 -121
- package/dist/lib/types/tools.generated.d.ts.map +1 -1
- package/dist/lib/types/tools.generated.js.map +1 -1
- package/dist/lib/version.d.mts +3 -3
- package/dist/lib/version.d.ts +3 -3
- package/dist/lib/version.js +3 -3
- package/dist/lib/version.js.map +1 -1
- package/dist/lib/version.mjs +3 -3
- package/dist/lib/version.mjs.map +1 -1
- package/docs/guides/MEDIA-BUY-3.2-COMPATIBILITY.md +28 -14
- package/docs/llms.txt +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/lib/core/TaskExecutor.ts"],"sourcesContent":["// Core task execution engine for ADCP conversation flow\n// Implements PR #78 async patterns: working/submitted/input-required/completed\n\nimport { randomUUID } from 'crypto';\nimport type { AgentConfig } from '../types';\nimport {\n ProtocolClient,\n normalizeTransportOptions,\n prepareProtocolToolCall,\n type PreparedProtocolToolCall,\n} from '../protocols';\nimport { listMCPTasks } from '../protocols/mcp-tasks';\nimport { withPreparedProtocolToolCall } from '../protocols/prepared-call-context';\nimport { getAuthToken } from '../auth';\nimport { is401Error, adcpErrorToTypedError, ConfigurationError } from '../errors';\nimport type { ADCPError } from '../errors';\nimport type { Storage } from '../storage/interfaces';\nimport {\n validateOutgoingRequest,\n validateIncomingResponse,\n resolveValidationModes,\n type ValidationHookConfig,\n type ValidationMode,\n} from '../validation/client-hooks';\nimport { formatIssues } from '../validation/schema-validator';\nimport { ADCP_VERSION } from '../version';\nimport { unwrapProtocolResponse, isAdcpOperationSuccess } from '../utils/response-unwrapper';\nimport { extractAdcpErrorInfo, extractCorrelationId } from '../utils/error-extraction';\nimport { generateIdempotencyKey, requestUsesIdempotency, redactIdempotencyKeyInArgs } from '../utils/idempotency';\nimport { normalizeGetProductsResponse } from '../utils/pricing-adapter';\nimport { normalizeLegacyMediaBuyStatusForReturn } from '../utils/envelope-status-compat';\nimport { canonicalize } from '../utils/jcs';\nimport { getLatestA2ADataPartFromResponse } from '../utils/a2a-artifacts';\nimport type { AdcpCapabilities } from '../utils/capabilities';\nimport { cancelA2ATask } from '../protocols/a2a';\nimport { isAbortOrTimeoutError, throwIfAborted } from '../protocols/abort';\nimport type {\n Message,\n InputRequest,\n InputHandler,\n ConversationContext,\n TaskOptions,\n TaskResult,\n TaskResultMetadata,\n TaskState,\n TaskStatus,\n TaskInfo,\n DeferredContinuation,\n SubmittedContinuation,\n WebhookUrlTemplate,\n} from './ConversationTypes';\nimport { normalizeHandlerResponse, isDeferResponse, isAbortResponse } from '../handlers/types';\nimport { ProtocolResponseParser, ADCP_STATUS, type ADCPStatus } from './ProtocolResponseParser';\nimport type { Activity } from './AsyncHandler';\nimport { GovernanceMiddleware } from './GovernanceMiddleware';\nimport type { GovernanceConfig, GovernanceCheckResult } from './GovernanceTypes';\nimport { targetDeclaresGovernanceEnforcement } from '../governance';\nimport { attachMatch } from './match';\nimport { resolveWebhookUrl } from './webhook-url';\nimport {\n attachTaskDeadlineGovernanceRecovery,\n attachTaskDeadlineIdempotencyKey,\n getTaskOperationId,\n withTaskDeadline,\n} from './task-deadline';\n\n// Keep the direct `core/TaskExecutor` export identical to the package-level\n// typed timeout error thrown by the deadline wrapper.\nexport { TaskTimeoutError } from '../errors';\n\n/**\n * Custom errors for task execution\n */\nexport class MaxClarificationError extends Error {\n constructor(taskId: string, maxAttempts: number) {\n super(`Task ${taskId} exceeded maximum clarification attempts: ${maxAttempts}`);\n this.name = 'MaxClarificationError';\n }\n}\n\nexport class DeferredTaskError extends Error {\n constructor(public token: string) {\n super(`Task deferred with token: ${token}`);\n this.name = 'DeferredTaskError';\n }\n}\n\nexport class InputRequiredError extends Error {\n constructor(question: string) {\n super(`Server requires input but no handler provided. Question: ${question}`);\n this.name = 'InputRequiredError';\n }\n}\n\n/** Supporting contract for the internal pre-dispatch boundary. */\nexport type BeforeProtocolDispatchHookResult<T> =\n | { action: 'dispatch_committed' }\n | { action: 'return'; result: TaskResult<T> };\n\n/** Context supplied to the internal pre-dispatch boundary. */\nexport interface BeforeProtocolDispatchContext {\n /** True when governance changed the payload rather than approving it unchanged. */\n governanceAdjusted: boolean;\n}\n\n/** Hook used by higher-level SDK coordinators at the final dispatch boundary. */\nexport type BeforeProtocolDispatchHook<T> = (\n effectiveParams: any,\n context: BeforeProtocolDispatchContext\n) => Promise<BeforeProtocolDispatchHookResult<T>>;\n\n/** Keeps internal dispatch-boundary failures out of the normal TaskResult error projection. */\n/** @internal */\nexport class BeforeProtocolDispatchHookError extends Error {\n constructor(readonly original: unknown) {\n super('An SDK pre-dispatch hook failed.', { cause: original });\n this.name = 'BeforeProtocolDispatchHookError';\n }\n}\n\nconst GOVERNED_CREDENTIAL_SCAN_MAX_NODES = 10_000;\nconst GOVERNED_CREDENTIAL_SCAN_MAX_DEPTH = 64;\nconst GOVERNED_CALLBACK_FIELDS = new Set(['push_notification_config', 'reporting_webhook', 'artifact_webhook']);\n\ntype GovernedCredentialScanResult =\n | { kind: 'credential'; path: string; callbackField: string }\n | { kind: 'limit'; limit: 'nodes' | 'depth' };\n\nfunction webhookRegistrationFromPreparedCall(\n agent: AgentConfig,\n preparedCall: PreparedProtocolToolCall\n): { callbackUrl: string; mode: 'rfc9421' | 'hmac-sha256' } | undefined {\n const candidate =\n agent.protocol === 'a2a'\n ? preparedCall.pushNotificationConfig\n : preparedCall.args.push_notification_config &&\n typeof preparedCall.args.push_notification_config === 'object' &&\n !Array.isArray(preparedCall.args.push_notification_config)\n ? (preparedCall.args.push_notification_config as Record<string, unknown>)\n : undefined;\n if (!candidate) return undefined;\n if (typeof candidate.url !== 'string') {\n throw new ConfigurationError('push_notification_config.url must be a string.', 'push_notification_config.url');\n }\n\n if (!Object.prototype.hasOwnProperty.call(candidate, 'authentication')) {\n return { callbackUrl: candidate.url, mode: 'rfc9421' };\n }\n const authentication = candidate.authentication;\n if (!authentication || typeof authentication !== 'object' || Array.isArray(authentication)) {\n throw new ConfigurationError(\n 'push_notification_config.authentication selects legacy verification and must be a supported object.',\n 'push_notification_config.authentication'\n );\n }\n const schemes = (authentication as Record<string, unknown>).schemes;\n const credentials = (authentication as Record<string, unknown>).credentials;\n if (\n !Array.isArray(schemes) ||\n schemes.length !== 1 ||\n schemes[0] !== 'HMAC-SHA256' ||\n typeof credentials !== 'string' ||\n credentials.length === 0\n ) {\n throw new ConfigurationError(\n 'This receiver supports legacy HMAC-SHA256 or RFC 9421 push notifications; Bearer and mixed schemes are not supported.',\n 'push_notification_config.authentication.schemes'\n );\n }\n return {\n callbackUrl: candidate.url,\n mode: 'hmac-sha256',\n };\n}\n\n/**\n * Find callback authentication credentials before an exact downstream payload\n * crosses the governance-agent boundary. AdCP 3.2 requires intent payloads to\n * match the seller arguments byte-for-byte at the JSON-data-model level, so\n * the SDK cannot safely redact a credential and reinsert it after approval:\n * doing so would invalidate the seller's authorized_payload_hash check.\n */\nfunction findGovernedAuthenticationCredential(value: unknown): GovernedCredentialScanResult | undefined {\n const stack: Array<{ value: unknown; depth: number }> = [{ value, depth: 0 }];\n const visited = new WeakSet<object>();\n let visitedNodes = 0;\n\n while (stack.length > 0) {\n const current = stack.pop()!;\n if (!current.value || typeof current.value !== 'object') continue;\n if (current.depth > GOVERNED_CREDENTIAL_SCAN_MAX_DEPTH) return { kind: 'limit', limit: 'depth' };\n if (visited.has(current.value)) continue;\n visited.add(current.value);\n if (++visitedNodes > GOVERNED_CREDENTIAL_SCAN_MAX_NODES) return { kind: 'limit', limit: 'nodes' };\n\n if (!Array.isArray(current.value)) {\n const record = current.value as Record<string, unknown>;\n for (const callbackField of GOVERNED_CALLBACK_FIELDS) {\n const callback = record[callbackField];\n if (!callback || typeof callback !== 'object' || Array.isArray(callback)) continue;\n const authentication = (callback as Record<string, unknown>).authentication;\n if (\n authentication &&\n typeof authentication === 'object' &&\n !Array.isArray(authentication) &&\n (authentication as Record<string, unknown>).credentials !== undefined\n ) {\n return {\n kind: 'credential',\n path: `${callbackField}.authentication.credentials`,\n callbackField,\n };\n }\n }\n }\n\n for (const key in current.value) {\n if (!Object.prototype.hasOwnProperty.call(current.value, key)) continue;\n const child = (current.value as Record<string, unknown>)[key];\n if (!child || typeof child !== 'object') continue;\n if (visitedNodes + stack.length >= GOVERNED_CREDENTIAL_SCAN_MAX_NODES) {\n return { kind: 'limit', limit: 'nodes' };\n }\n stack.push({ value: child, depth: current.depth + 1 });\n }\n }\n return undefined;\n}\n\nfunction assertGovernedPayloadHasNoCallbackCredentials(\n taskName: string,\n payload: Record<string, unknown>,\n options: { sdkInjectedPushConfig?: boolean } = {}\n): void {\n const scanResult = findGovernedAuthenticationCredential(payload);\n if (!scanResult) return;\n if (scanResult.kind === 'limit') {\n const limitDescription =\n scanResult.limit === 'nodes'\n ? `${GOVERNED_CREDENTIAL_SCAN_MAX_NODES.toLocaleString('en-US')} nested objects`\n : `${GOVERNED_CREDENTIAL_SCAN_MAX_DEPTH} object levels`;\n throw new ConfigurationError(\n `The SDK could not safely inspect the governed ${taskName} payload for callback credentials because it ` +\n `exceeds the ${limitDescription} safety limit. Simplify the payload or move deeply nested extension data ` +\n `out of the governed request before retrying.`,\n 'governance.payload'\n );\n }\n const remedy =\n scanResult.callbackField === 'push_notification_config'\n ? options.sdkInjectedPushConfig\n ? 'Retry with task options `{ disableWebhook: true }` and poll for completion, or use A2A task-status notifications.'\n : 'Remove the credential-bearing push notification config and poll for completion, or use A2A task-status notifications.'\n : `Remove the credential-bearing ${scanResult.callbackField} from this governed request and use a ` +\n `non-webhook delivery path.`;\n throw new ConfigurationError(\n `Governed ${taskName} cannot forward ${scanResult.path} to the governance agent. ` +\n `The SDK will not disclose receiver authentication credentials, and redacting modern AdCP 3.2 payloads ` +\n `would invalidate seller authorization. ${remedy}`,\n scanResult.path\n );\n}\n\n/**\n * Map an AdCP `tasks/get` response (post-unwrap) to the SDK's internal\n * `TaskInfo` shape. The AdCP 3.0 schema\n * (`schemas/cache/3.0.0/bundled/core/tasks-get-response.json`) is flat\n * snake_case: `{ task_id, task_type, protocol, status, created_at,\n * updated_at, error?, progress?, history?, completed_at?, has_webhook?,\n * context?, ext? }`. The internal `TaskInfo` is camelCase with a\n * superset of legacy fields some pre-3.0 sellers still emit.\n *\n * **Result-data extraction.** AdCP 3.1.0 defines a typed `result`\n * field on `tasks/get` responses (per adcontextprotocol/adcp#3126,\n * which closed adcp#3123). Sellers populate it when the buyer's\n * request set `include_result: true` and the task reached\n * `completed`. The mapper reads it directly into `TaskInfo.result`\n * so `pollTaskCompletion` surfaces it on the resolved\n * `TaskResult.data`. Pre-3.1.0 sellers that emitted `result` via\n * `additionalProperties: true` continue to work — the typed and\n * informal paths share the same field name.\n *\n * **Legacy nested shape.** Some pre-3.0 sellers and existing test\n * mocks emit `{ task: { ...TaskInfo } }` — a non-spec wrapper. We\n * unwrap it before the spec-shape mapping so the SDK stays\n * compatible with both surfaces during the transition.\n */\nfunction mapTasksGetResponseToTaskInfo(payload: unknown): TaskInfo {\n if (payload == null || typeof payload !== 'object') {\n return { taskId: '', status: 'unknown', taskType: 'unknown', createdAt: Date.now(), updatedAt: Date.now() };\n }\n const obj = payload as Record<string, unknown>;\n // Walk the transport-level wrappers in priority order:\n // 1. MCP `structuredContent` — the typed AdCP payload from `tools/call`\n // 2. A2A latest structured DataPart — the AdCP payload\n // surfaced via the artifact (per #899)\n // 3. Legacy nested `{ task: TaskInfo }` — pre-3.0 sellers and\n // existing test mocks\n // 4. Flat AdCP-spec shape — what AdCP 3.0 sellers emit directly\n const flat = unwrapTasksGetEnvelope(obj);\n const errorRaw = flat.error;\n const errorMessage =\n typeof errorRaw === 'string'\n ? errorRaw\n : errorRaw != null &&\n typeof errorRaw === 'object' &&\n typeof (errorRaw as { message?: unknown }).message === 'string'\n ? (errorRaw as { message: string }).message\n : undefined;\n const taskInfo: TaskInfo = {\n taskId: stringField(flat.task_id) ?? stringField(flat.taskId) ?? '',\n status: stringField(flat.status) ?? 'unknown',\n taskType: stringField(flat.task_type) ?? stringField(flat.taskType) ?? 'unknown',\n createdAt: parseTimestamp(flat.created_at ?? flat.createdAt),\n updatedAt: parseTimestamp(flat.updated_at ?? flat.updatedAt),\n };\n if (errorMessage !== undefined) taskInfo.error = errorMessage;\n // Top-level `message` field: the AdCP envelope's human-readable\n // status descriptor (advisory string accompanying any status —\n // e.g. \"Budget cap exceeded — task not started\" on a `rejected`\n // task). `pollTaskCompletion` falls back to this when the\n // `error.message` block is absent on a terminal failure. Distinct\n // from `error.message` (which lives under the structured `error`\n // object).\n const messageField = stringField(flat.message);\n if (messageField !== undefined) taskInfo.message = messageField;\n // Result extraction — see JSDoc. AdCP 3.1.0 defines `result` as\n // the canonical typed field; pre-3.1.0 sellers using\n // `additionalProperties: true` shared the same field name, so the\n // mapping is unchanged across versions.\n if (flat.result !== undefined) {\n taskInfo.result =\n flat.result != null && typeof flat.result === 'object' && !Array.isArray(flat.result)\n ? normalizeLegacyMediaBuyStatusForReturn(flat.result as Record<string, unknown>, {\n toolName: taskInfo.taskType,\n })\n : flat.result;\n }\n return taskInfo;\n}\n\nfunction stringField(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\n/**\n * Cap on the wrapper-unwrap recursion depth. Real-world responses\n * have at most two layers (MCP `structuredContent` OR A2A JSON-RPC →\n * Task → artifact → DataPart). The cap is a defense against a\n * malformed or hostile seller emitting a deeply-nested wrapper that\n * would otherwise stack-overflow the buyer.\n */\nconst TASKS_GET_UNWRAP_MAX_DEPTH = 8;\n\nfunction unwrapTasksGetEnvelope(obj: Record<string, unknown>, depth = 0, allowRawData = true): Record<string, unknown> {\n if (depth >= TASKS_GET_UNWRAP_MAX_DEPTH) return obj;\n // MCP: `tools/call` response carries the typed payload at\n // `structuredContent`.\n const sc = obj.structuredContent;\n if (sc != null && typeof sc === 'object' && !Array.isArray(sc)) {\n return unwrapTasksGetEnvelope(sc as Record<string, unknown>, depth + 1, false);\n }\n // A2A: `message/send` response is a JSON-RPC envelope wrapping a\n // Task; the AdCP payload sits on the latest structured DataPart.\n const result = obj.result;\n if (result != null && typeof result === 'object' && !Array.isArray(result)) {\n const r = result as Record<string, unknown>;\n if (r.kind === 'task') {\n const extracted = getLatestA2ADataPartFromResponse(obj);\n if (extracted) {\n return unwrapTasksGetEnvelope(extracted.data, depth + 1, false);\n }\n // adcp-client#1612: When the A2A Task has no DataPart artifacts (e.g. the\n // seller returns an A2A transport-level state without an AdCP DataPart\n // payload), surface the transport-layer status as a last-resort hint so\n // `mapTasksGetResponseToTaskInfo` can map terminal states to `failed` /\n // `completed` rather than falling through to `'unknown'`. The transport\n // state overlaps with AdCP status strings for all A2A-native values\n // (`completed`, `failed`, `rejected`, `canceled`, `working`, `submitted`).\n // Note: `auth-required` is an AdCP-layer concept; it won't surface via\n // this path (no A2A-native transport state carries that label) — those\n // responses reach the `unknown` exit branch instead. Also include the A2A\n // task handle (`result.id`) so polling error messages carry the real id.\n const transportStatus = (r.status as Record<string, unknown> | undefined)?.state;\n if (typeof transportStatus === 'string') {\n return { status: transportStatus, task_id: typeof r.id === 'string' ? r.id : undefined };\n }\n }\n }\n // Raw/in-process MCP wrappers sometimes carry the AdCP payload under\n // `data` rather than the official CallToolResult `structuredContent`.\n // Unwrap only when it looks like a task envelope and no official payload\n // has already been selected.\n const data = obj.data;\n if (allowRawData && data != null && typeof data === 'object' && !Array.isArray(data)) {\n const d = data as Record<string, unknown>;\n if ('status' in d || 'task_id' in d || 'taskId' in d) {\n return unwrapTasksGetEnvelope(d, depth + 1, true);\n }\n }\n // Legacy nested wrapper from pre-3.0 sellers and existing mocks.\n // TODO(adcp-client#967): remove once mock fixtures in\n // `test/lib/task-executor*.test.js` migrate to the AdCP-spec flat\n // shape. No real seller emits this; verified at PR review time.\n if (obj.task != null && typeof obj.task === 'object' && !Array.isArray(obj.task)) {\n return obj.task as Record<string, unknown>;\n }\n // Flat AdCP-spec shape — return as-is.\n return obj;\n}\n\nfunction parseTimestamp(value: unknown): number {\n if (typeof value === 'string') {\n const parsed = Date.parse(value);\n if (!Number.isNaN(parsed)) return parsed;\n }\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n return Date.now();\n}\n\n/**\n * Return the idempotency_key this task should use: the caller's value if\n * present, otherwise a fresh UUID v4 for mutating tasks, otherwise undefined.\n */\nfunction resolveIdempotencyKey(taskName: string, params: any, serverVersion?: 'v2' | 'v3'): string | undefined {\n const callerSupplied =\n params && typeof params === 'object' && typeof params.idempotency_key === 'string'\n ? params.idempotency_key\n : undefined;\n if (callerSupplied) return callerSupplied;\n // v2.5 mutations use buyer_ref as their stable replay identity. Request\n // adaptation has already derived it from the caller's canonical key. Do\n // not inject a fresh v3-only idempotency_key after adaptation: that makes\n // identical retries differ on the wire and can defeat legacy dedupe.\n if (serverVersion === 'v2') {\n return params && typeof params === 'object' && typeof params.buyer_ref === 'string' ? params.buyer_ref : undefined;\n }\n if (requestUsesIdempotency(taskName, params)) return generateIdempotencyKey();\n return undefined;\n}\n\n/**\n * Webhook manager for submitted tasks\n */\ninterface WebhookManager {\n generateUrl(taskId: string): string;\n registerWebhook(agent: AgentConfig, taskId: string, webhookUrl: string): Promise<void>;\n processWebhook(token: string, body: any): Promise<void>;\n}\n\n/**\n * Deferred task storage for client deferrals\n */\ninterface DeferredTaskState {\n taskId: string;\n contextId: string;\n agent: AgentConfig;\n taskName: string;\n params: any;\n messages: Message[];\n createdAt: number;\n}\n\ninterface TaskStatusPollResult {\n task: TaskInfo;\n rawResponse: Record<string, unknown>;\n}\n\nconst COMPACTED_TASK_STATE_LIMIT = 10_000;\nconst TERMINAL_TASK_STATUSES = new Set<TaskStatus>([\n 'completed',\n 'failed',\n 'rejected',\n 'canceled',\n 'governance-denied',\n 'aborted',\n]);\n\n/**\n * Core task execution engine that handles the conversation loop with agents\n */\nexport class TaskExecutor {\n private responseParser: ProtocolResponseParser;\n private activeTasks = new Map<string, TaskState>();\n private compactedTaskIds = new Map<string, true>();\n private conversationStorage?: Map<string, Message[]>;\n private governanceMiddleware?: GovernanceMiddleware;\n private lastKnownServerVersion?: 'v2' | 'v3';\n private requestValidationMode!: ValidationMode;\n private responseValidationMode!: ValidationMode;\n\n constructor(\n private config: {\n /** Default timeout for 'working' status (max 120s per PR #78) */\n workingTimeout?: number;\n /** Polling interval for 'working' status in milliseconds (default: 2000ms) */\n pollingInterval?: number;\n /** Default max clarification attempts */\n defaultMaxClarifications?: number;\n /** Enable conversation storage */\n enableConversationStorage?: boolean;\n /** Webhook manager for submitted tasks */\n webhookManager?: WebhookManager;\n /** Storage for deferred task state */\n deferredStorage?: Storage<DeferredTaskState>;\n /** Webhook URL template for protocol-level webhook support */\n webhookUrlTemplate?: WebhookUrlTemplate;\n /** Agent ID for webhook URL generation */\n agentId?: string;\n /** Webhook secret for legacy HMAC authentication. */\n webhookSecret?: string;\n /** Persist sanitized callback mode provenance before dispatch. */\n onWebhookRegistration?: (registration: {\n agent: AgentConfig;\n taskType: string;\n operationId: string;\n callbackUrl: string;\n mode: 'rfc9421' | 'hmac-sha256';\n }) => void | Promise<void>;\n /** Fail tasks when response schema validation fails (default: true) */\n strictSchemaValidation?: boolean;\n /** Emit schema validation violations to debug logs and the console (default: true) */\n logSchemaViolations?: boolean;\n /**\n * Schema-driven validation using the bundled AdCP JSON schemas.\n * Controls outgoing request and incoming response checks independently.\n * Defaults: strict in dev/test, warn in prod. Set a mode to `off` to\n * skip the validator entirely on that side (zero overhead).\n */\n validation?: ValidationHookConfig;\n /** Filter out invalid products from get_products responses instead of rejecting the entire response (default: false) */\n filterInvalidProducts?: boolean;\n /** Global activity callback for observability */\n onActivity?: (activity: Activity) => void | Promise<void>;\n /** Transport-level diagnostics callback for outbound HTTP requests. */\n onTransportActivity?: import('../protocols').TransportActivityHandler;\n /** Governance configuration for buyer-side campaign governance */\n governance?: GovernanceConfig;\n /**\n * AdCP version this executor speaks. Selects which schema bundle\n * `validateIncomingResponse` / `validateOutgoingRequest` validate\n * against, and which `adcp_major_version` value goes on the wire.\n * Defaults to the SDK-pinned `ADCP_VERSION` when omitted.\n *\n * Plumbed from `SingleAgentClient.resolvedAdcpVersion` so the\n * client/agent's `getAdcpVersion()` value is the single source of\n * truth for both validation and wire-level major.\n */\n adcpVersion?: string;\n wireAdcpVersion?: string;\n versionEnvelope?: import('../protocols').VersionEnvelopeMode;\n /**\n * Transport-level safeguards applied to every call this executor\n * dispatches. Per-call options can override individual fields.\n */\n transport?: import('../protocols').TransportOptions;\n } = {}\n ) {\n this.responseParser = new ProtocolResponseParser();\n if (config.enableConversationStorage) {\n this.conversationStorage = new Map();\n }\n if (config.governance) {\n this.governanceMiddleware = new GovernanceMiddleware(\n config.governance,\n config.onActivity,\n config.adcpVersion,\n config.versionEnvelope,\n config.onTransportActivity\n );\n }\n const modes = resolveValidationModes(config.validation);\n this.requestValidationMode = modes.requests;\n // Legacy `strictSchemaValidation: false` flips response-side enforcement\n // to warn mode — preserve that behaviour unless `validation.responses`\n // was set explicitly.\n if (config.validation?.responses !== undefined) {\n this.responseValidationMode = config.validation.responses;\n } else if (config.strictSchemaValidation === false) {\n this.responseValidationMode = 'warn';\n } else {\n this.responseValidationMode = modes.responses;\n }\n }\n\n /**\n * Access the governance middleware for direct outcome reporting (async tasks).\n */\n getGovernanceMiddleware(): GovernanceMiddleware | undefined {\n return this.governanceMiddleware;\n }\n\n getRequestParams(taskId: string): Record<string, unknown> | undefined {\n const params = this.activeTasks.get(taskId)?.params;\n return params && typeof params === 'object' && !Array.isArray(params)\n ? (params as Record<string, unknown>)\n : undefined;\n }\n\n /**\n * Reconcile a push-delivered terminal status with the local runner task.\n * Submitted task state is already compacted after dispatch; this schedules\n * the same short final-status retention used by synchronous completions.\n *\n * @internal\n */\n observeExternalTaskStatus(taskId: string, status: TaskStatus, result?: unknown): void {\n if (!['completed', 'failed', 'rejected', 'canceled'].includes(status)) return;\n this.updateTaskStatus(taskId, status, result);\n }\n\n /**\n * Run the configured pre-send schema check against the user-facing request\n * shape. Callers invoke this on the unadapted (v3) params before any wire\n * adaptation runs, so the validator sees the same object the caller wrote.\n * Throws in strict, logs to `debugLogs` in warn, no-ops in off.\n */\n validateRequest(taskName: string, params: unknown, debugLogs?: any[]): void {\n validateOutgoingRequest(taskName, params, this.requestValidationMode, debugLogs, this.config.adcpVersion);\n }\n\n /**\n * After `adaptRequestForServerVersion` has rewritten a v3 request into v2\n * wire format, validate the adapted shape against the cached v2.5 schema\n * bundle. Always warn-only — adapter bugs shouldn't break user requests,\n * and the v3 pre-send pass already vouched for the user-facing input.\n * This pass exists to surface drift between what the adapter emits and\n * what a v2.5 server expects on the wire (primarily as CI signal via the\n * adapter-conformance test suite).\n *\n * Skips silently for tasks without a v2.5 schema or when the v2.5 bundle\n * isn't cached. Caller is responsible for gating on `serverVersion === 'v2'`\n * so v3-targeted traffic doesn't pay the validation cost.\n */\n validateAdaptedRequestAgainstV2(taskName: string, adaptedParams: unknown, debugLogs?: any[]): void {\n validateOutgoingRequest(taskName, adaptedParams, 'warn', debugLogs, 'v2.5');\n }\n\n /**\n * Generate webhook URL for protocol-level webhook support\n */\n /**\n * Build TaskResultMetadata, including the idempotency fields. The key is\n * pulled from the tracked task state so every result reports the key that\n * was actually sent (auto-generated or caller-supplied); `replayed` is\n * extracted from the response envelope when a response is available.\n */\n private buildMetadata(args: {\n taskId: string;\n taskName: string;\n agent: AgentConfig | { id: string; name: string; protocol: 'mcp' | 'a2a' };\n startTime?: number;\n responseTimeMs?: number;\n status: TaskStatus;\n clarificationRounds?: number;\n response?: any;\n inputRequest?: InputRequest;\n }): TaskResultMetadata {\n const meta: TaskResultMetadata = {\n taskId: args.taskId,\n taskName: args.taskName,\n agent: { id: args.agent.id, name: args.agent.name, protocol: args.agent.protocol },\n responseTimeMs: args.responseTimeMs ?? (args.startTime !== undefined ? Date.now() - args.startTime : 0),\n timestamp: new Date().toISOString(),\n clarificationRounds: args.clarificationRounds ?? 0,\n status: args.status,\n };\n if (args.inputRequest) meta.inputRequest = args.inputRequest;\n const key = this.activeTasks.get(args.taskId)?.idempotencyKey;\n if (key) meta.idempotency_key = key;\n if (args.response !== undefined) {\n const replayed = this.responseParser.getReplayed(args.response);\n if (replayed !== undefined) meta.replayed = replayed;\n const adcpVersion = this.responseParser.getAdcpVersion(args.response);\n if (adcpVersion) meta.adcpVersion = adcpVersion;\n const serverContextId = this.responseParser.getContextId(args.response);\n if (serverContextId) meta.contextId = serverContextId;\n const serverTaskId = this.responseParser.getTaskId(args.response);\n if (serverTaskId) meta.serverTaskId = serverTaskId;\n }\n return meta;\n }\n\n /**\n * Map a task's structured AdCP error to a typed `ADCPError` subclass when\n * the code has a dedicated class (e.g., `IDEMPOTENCY_CONFLICT` →\n * `IdempotencyConflictError`). The idempotency key is pulled from tracked\n * task state because the server intentionally omits it from error bodies\n * (it's a read-oracle).\n */\n private buildErrorInstance(\n taskId: string,\n adcpError: ReturnType<typeof extractAdcpErrorInfo>\n ): ADCPError | undefined {\n if (!adcpError) return undefined;\n const key = this.activeTasks.get(taskId)?.idempotencyKey;\n return adcpErrorToTypedError(adcpError, key);\n }\n\n private generateWebhookUrl(taskName: string, operationId: string, options?: TaskOptions): string | undefined {\n return resolveWebhookUrl(this.config.webhookUrlTemplate, this.config.agentId, taskName, operationId, options);\n }\n\n /**\n * Execute a task with an agent using PR #78 async patterns\n * Handles: working (keep SSE open), submitted (webhook), input-required (handler), completed\n */\n async executeTask<T = any>(\n agent: AgentConfig,\n taskName: string,\n params: any,\n inputHandler?: InputHandler,\n options: TaskOptions = {},\n serverVersion?: 'v2' | 'v3',\n targetCapabilities?: AdcpCapabilities,\n beforeProtocolDispatch?: BeforeProtocolDispatchHook<T>\n ): Promise<TaskResult<T>> {\n return withTaskDeadline(options, effectiveOptions =>\n this.executeTaskWithinDeadline<T>(\n agent,\n taskName,\n params,\n inputHandler,\n effectiveOptions,\n serverVersion,\n targetCapabilities,\n beforeProtocolDispatch\n )\n );\n }\n\n private async executeTaskWithinDeadline<T = any>(\n agent: AgentConfig,\n taskName: string,\n params: any,\n inputHandler?: InputHandler,\n options: TaskOptions = {},\n serverVersion?: 'v2' | 'v3',\n targetCapabilities?: AdcpCapabilities,\n beforeProtocolDispatch?: BeforeProtocolDispatchHook<T>\n ): Promise<TaskResult<T>> {\n if (serverVersion) this.lastKnownServerVersion = serverVersion;\n // The client-minted `taskId` is a local correlation id for tracking this\n // call's lifecycle (activeTasks map, metadata, webhook URL macros). It is\n // NOT the same thing as the A2A `taskId` that the server assigns — that\n // flows in on the response and is surfaced via metadata.serverTaskId.\n // `options.contextId` / `options.taskId` ride on the A2A message envelope\n // and are threaded straight to the protocol adapter below.\n const taskId = getTaskOperationId(options) ?? randomUUID();\n const startTime = Date.now();\n const workingTimeout = this.config.workingTimeout || 120000; // 120s max per PR #78\n\n // Auto-generate idempotency_key for mutating tasks when the caller didn't\n // supply one. The key lives on TaskState so internal retries reuse it —\n // re-generating on retry defeats the whole point of the envelope.\n // `options.skipIdempotencyAutoInject` disables this for compliance testing\n // that needs to exercise server-side missing-key behavior.\n const idempotencyKey = options.skipIdempotencyAutoInject\n ? undefined\n : resolveIdempotencyKey(taskName, params, serverVersion);\n if (idempotencyKey) attachTaskDeadlineIdempotencyKey(options, idempotencyKey);\n if (serverVersion !== 'v2' && idempotencyKey && params && typeof params === 'object' && !params.idempotency_key) {\n params = { ...params, idempotency_key: idempotencyKey };\n }\n\n // Register task in active tasks\n const taskState: TaskState = {\n taskId,\n taskName,\n params,\n status: 'pending',\n messages: [],\n startTime,\n attempt: 0,\n maxAttempts: options.maxClarifications || this.config.defaultMaxClarifications || 3,\n options,\n agent: { id: agent.id, name: agent.name, protocol: agent.protocol },\n idempotencyKey,\n };\n this.activeTasks.set(taskId, taskState);\n\n // Compact task state as soon as cancellation fires, even if a protocol\n // adapter or caller callback never settles after receiving the signal.\n // The outer deadline race guarantees prompt rejection; this listener is\n // the matching resource-retention boundary for activeTasks.\n const taskAbortListener = options.signal\n ? () => {\n const currentStatus = this.activeTasks.get(taskId)?.status;\n if (currentStatus && !TERMINAL_TASK_STATUSES.has(currentStatus)) {\n const reason = options.signal?.reason;\n this.updateTaskStatus(\n taskId,\n 'aborted',\n undefined,\n reason instanceof Error ? reason.message : reason == null ? 'The operation was aborted' : String(reason)\n );\n }\n }\n : undefined;\n if (taskAbortListener) options.signal!.addEventListener('abort', taskAbortListener, { once: true });\n\n // Emit task creation event\n this.emitTaskEvent(\n {\n taskId,\n status: 'submitted',\n taskType: taskName,\n createdAt: startTime,\n updatedAt: startTime,\n },\n agent.id\n );\n\n // Start streaming connection\n const debugLogs: any[] = [];\n\n // Generate webhook URL if template is configured\n const webhookUrl = this.generateWebhookUrl(taskName, taskId, options);\n\n // Governance state (scoped outside try so catch can access)\n let governanceCheckId: string | undefined;\n let governanceResult: GovernanceCheckResult | undefined;\n let effectiveParams = params;\n let governanceAdjusted = false;\n\n try {\n // Emit protocol_request activity. The activity payload is the boundary\n // callers typically pipe into external observability stacks, so redact\n // the idempotency key — it's a retry-pattern oracle within the seller's\n // TTL. Full logging is opt-in via ADCP_LOG_IDEMPOTENCY_KEYS=1.\n await this.config.onActivity?.({\n type: 'protocol_request',\n operation_id: taskId,\n agent_id: agent.id,\n context_id: options.contextId,\n task_id: taskId,\n task_type: taskName,\n status: 'pending',\n payload: { params: redactIdempotencyKeyInArgs(params) },\n timestamp: new Date().toISOString(),\n });\n throwIfAborted(options.signal);\n\n // Run governance check if configured for this tool\n const governanceMiddleware = this.governanceMiddleware;\n if (governanceMiddleware) {\n const modernGovernance =\n targetCapabilities !== undefined && targetDeclaresGovernanceEnforcement(targetCapabilities, taskName);\n // Modern authorization binds the exact argument object the seller\n // receives, including protocol-owned fields and MCP webhook\n // registration. Legacy governance retains its historical application\n // payload and must not receive SDK-injected callback credentials.\n const governableParams = modernGovernance\n ? prepareProtocolToolCall(agent, params, {\n toolName: taskName,\n webhookUrl,\n webhookSecret: this.config.webhookSecret,\n serverVersion,\n adcpVersion: this.config.adcpVersion,\n wireAdcpVersion: this.config.wireAdcpVersion,\n versionEnvelope: this.config.versionEnvelope,\n }).args\n : params;\n if (await governanceMiddleware.shouldCheck(taskName, governableParams, targetCapabilities)) {\n const sdkInjectedPushConfig =\n modernGovernance &&\n agent.protocol === 'mcp' &&\n webhookUrl !== undefined &&\n this.config.webhookSecret !== undefined;\n assertGovernedPayloadHasNoCallbackCredentials(taskName, governableParams, { sdkInjectedPushConfig });\n const { result: govResult, params: adjustedParams } = await governanceMiddleware.checkProposed(\n agent,\n targetCapabilities!,\n taskName,\n governableParams,\n debugLogs,\n options.signal\n );\n throwIfAborted(options.signal);\n assertGovernedPayloadHasNoCallbackCredentials(taskName, adjustedParams, { sdkInjectedPushConfig });\n governanceAdjusted = canonicalize(adjustedParams) !== canonicalize(governableParams);\n\n // Governance always blocks on denial/unapplied conditions.\n const isBlocking = true;\n\n if (govResult.status === 'denied' && isBlocking) {\n const denied = this.buildGovernanceResult<T>(govResult, taskId, taskName, agent, startTime, debugLogs);\n this.updateTaskStatus(taskId, 'governance-denied', undefined, denied.error);\n return attachMatch(denied);\n }\n\n if (govResult.status === 'conditions' && !govResult.conditionsApplied && isBlocking) {\n const denied = this.buildGovernanceResult<T>(govResult, taskId, taskName, agent, startTime, debugLogs);\n this.updateTaskStatus(taskId, 'governance-denied', undefined, denied.error);\n return attachMatch(denied);\n }\n\n // Approved, or non-blocking mode (advisory/audit) allows execution to proceed\n governanceCheckId = govResult.checkId;\n governanceResult = govResult;\n if (governanceCheckId) {\n // Preserve the approved check identity as soon as the seller may be\n // dispatched. If the deadline fires during response processing,\n // callers can still reconcile the seller mutation against the\n // original governance decision after restart.\n attachTaskDeadlineGovernanceRecovery(options, { checkId: governanceCheckId });\n }\n effectiveParams = adjustedParams;\n }\n }\n\n // Create initial message (uses effectiveParams which may have governance-applied conditions)\n const initialMessage: Message = {\n id: randomUUID(),\n role: 'user',\n content: { tool: taskName, params: effectiveParams },\n timestamp: new Date().toISOString(),\n metadata: { toolName: taskName, type: 'request' },\n };\n\n // Materialize once, persist callback provenance, and dispatch this same\n // prepared object. A seller can post immediately after receiving the\n // request, so the registration write must complete before the network\n // boundary is crossed.\n const preparedCall = prepareProtocolToolCall(agent, effectiveParams, {\n toolName: taskName,\n webhookUrl,\n webhookSecret: this.config.webhookSecret,\n serverVersion,\n adcpVersion: this.config.adcpVersion,\n wireAdcpVersion: this.config.wireAdcpVersion,\n versionEnvelope: this.config.versionEnvelope,\n });\n if (webhookUrl && this.config.onWebhookRegistration) {\n const registration = webhookRegistrationFromPreparedCall(agent, preparedCall);\n if (registration) {\n await this.config.onWebhookRegistration({\n agent,\n taskType: taskName,\n operationId: taskId,\n ...registration,\n });\n }\n }\n\n // This is the final awaited preflight boundary. A durable mutation claim\n // made by the hook must be followed immediately by the official protocol\n // call; callers can therefore distinguish deterministic preflight failure\n // from transport uncertainty after the commit point.\n throwIfAborted(options.signal);\n let dispatchCommitted = false;\n if (beforeProtocolDispatch) {\n let decision: BeforeProtocolDispatchHookResult<T>;\n try {\n decision = await beforeProtocolDispatch(effectiveParams, { governanceAdjusted });\n } catch (error) {\n throw new BeforeProtocolDispatchHookError(error);\n }\n if (decision.action === 'return') {\n const earlyResult = decision.result;\n if (\n ['completed', 'failed', 'rejected', 'canceled', 'governance-denied', 'aborted'].includes(earlyResult.status)\n ) {\n this.updateTaskStatus(taskId, earlyResult.status as TaskStatus, earlyResult.data, earlyResult.error);\n }\n return attachMatch(earlyResult);\n }\n dispatchCommitted = true;\n }\n\n // Send initial request and get streaming response with webhook URL.\n // Pass the caller's A2A session ids (contextId for conversation binding,\n // taskId for resuming a non-terminal server-side task). The adapter\n // drops these on the wire for MCP (no session concept there).\n const callOptions = {\n debugLogs,\n webhookUrl,\n webhookSecret: this.config.webhookSecret,\n serverVersion,\n session: { contextId: options.contextId, taskId: options.taskId },\n adcpVersion: this.config.adcpVersion,\n ...(this.config.wireAdcpVersion !== undefined && { wireAdcpVersion: this.config.wireAdcpVersion }),\n ...(this.config.versionEnvelope !== undefined && { versionEnvelope: this.config.versionEnvelope }),\n transport: options.transport ?? this.config.transport,\n // Once a durable continuation claim commits, the seller call itself\n // must cross the network boundary even if the caller's deadline fired\n // while the atomic store operation was pending. The outer deadline\n // still rejects promptly and post-call handling marks the outcome\n // ambiguous for reconciliation.\n signal: dispatchCommitted ? undefined : options.signal,\n onTransportActivity: this.config.onTransportActivity,\n transportActivityContext: {\n operationId: taskId,\n taskId: options.taskId ?? taskId,\n contextId: options.contextId,\n idempotencyKey,\n },\n };\n const response = await withPreparedProtocolToolCall(\n { agent, toolName: taskName, args: effectiveParams, preparedCall },\n () => ProtocolClient.callTool(agent, taskName, effectiveParams, callOptions)\n );\n throwIfAborted(options.signal);\n\n // Emit protocol_response activity\n const respStatus = this.responseParser.getStatus(response) as string | undefined;\n await this.config.onActivity?.({\n type: 'protocol_response',\n operation_id: taskId,\n agent_id: agent.id,\n context_id: options.contextId,\n task_id: taskId,\n task_type: taskName,\n status: respStatus,\n payload: response,\n timestamp: new Date().toISOString(),\n });\n throwIfAborted(options.signal);\n\n // Add initial response message\n const responseMessage: Message = {\n id: randomUUID(),\n role: 'agent',\n content: response,\n timestamp: new Date().toISOString(),\n metadata: { toolName: taskName, type: 'response' },\n };\n\n const messages = [initialMessage, responseMessage];\n\n // Handle response based on status\n const result = await this.handleAsyncResponse<T>(\n agent,\n taskId,\n taskName,\n effectiveParams,\n response,\n messages,\n inputHandler,\n options,\n debugLogs,\n startTime\n );\n throwIfAborted(options.signal);\n\n // Attach governance check result to the task result\n if (governanceResult) {\n result.governance = governanceResult;\n }\n\n // Report governance outcome if we had a governance check.\n // For async tasks (submitted/working), outcome reporting is deferred —\n // the caller reports via client.reportGovernanceOutcome() when the\n // task resolves through polling or webhooks.\n if (governanceCheckId && this.governanceMiddleware) {\n const govCtx = governanceResult?.governanceContext;\n if (result.status === 'completed' && govCtx) {\n const outcomeIdempotencyKey = this.governanceMiddleware.getOutcomeIdempotencyKey(\n governanceCheckId,\n 'completed'\n );\n attachTaskDeadlineGovernanceRecovery(options, {\n checkId: governanceCheckId,\n outcome: 'completed',\n outcomeIdempotencyKey,\n });\n result.governanceOutcome = await this.governanceMiddleware.reportOutcome(\n governanceCheckId,\n 'completed',\n result.data as Record<string, unknown> | undefined,\n undefined,\n debugLogs,\n govCtx,\n options.signal,\n outcomeIdempotencyKey\n );\n throwIfAborted(options.signal);\n if (!result.governanceOutcome) {\n result.governanceOutcomeError = 'Outcome reporting to governance agent failed';\n }\n } else if (result.error && govCtx) {\n const outcomeIdempotencyKey = this.governanceMiddleware.getOutcomeIdempotencyKey(governanceCheckId, 'failed');\n attachTaskDeadlineGovernanceRecovery(options, {\n checkId: governanceCheckId,\n outcome: 'failed',\n outcomeIdempotencyKey,\n });\n result.governanceOutcome = await this.governanceMiddleware.reportOutcome(\n governanceCheckId,\n 'failed',\n undefined,\n { message: result.error },\n debugLogs,\n govCtx,\n options.signal,\n outcomeIdempotencyKey\n );\n throwIfAborted(options.signal);\n if (!result.governanceOutcome) {\n result.governanceOutcomeError = 'Outcome reporting to governance agent failed';\n }\n } else if (result.status === 'submitted' || result.status === 'working') {\n // Attach the check ID so callers can report outcome after async resolution\n result.governance = { ...(result.governance ?? {}), checkId: governanceCheckId } as GovernanceCheckResult;\n }\n }\n\n if (\n ['completed', 'failed', 'rejected', 'canceled', 'governance-denied', 'aborted'].includes(result.status) &&\n this.activeTasks.get(taskId)?.status !== result.status\n ) {\n this.updateTaskStatus(taskId, result.status as TaskStatus, result.data, result.error);\n }\n return attachMatch(result);\n } catch (error) {\n if (error instanceof BeforeProtocolDispatchHookError) {\n // Hook failures happen before seller dispatch. Preserve the original\n // exception for the compatibility coordinator, but terminalize the\n // local task so repeated invalid redemption attempts cannot retain\n // full request payloads and options in activeTasks.\n this.updateTaskStatus(taskId, 'failed', undefined, error.message);\n throw error;\n }\n if (isAbortOrTimeoutError(error)) {\n if (idempotencyKey && error && typeof error === 'object') {\n (error as Error & { idempotency_key?: string; idempotencyKey?: string }).idempotency_key = idempotencyKey;\n (error as Error & { idempotency_key?: string; idempotencyKey?: string }).idempotencyKey = idempotencyKey;\n }\n const currentStatus = this.activeTasks.get(taskId)?.status;\n if (currentStatus && !TERMINAL_TASK_STATUSES.has(currentStatus)) {\n this.updateTaskStatus(taskId, 'aborted', undefined, error instanceof Error ? error.message : String(error));\n }\n throw error;\n }\n\n // Report failed outcome on error\n if (governanceCheckId && this.governanceMiddleware && governanceResult?.governanceContext) {\n const outcomeIdempotencyKey = this.governanceMiddleware.getOutcomeIdempotencyKey(governanceCheckId, 'failed');\n attachTaskDeadlineGovernanceRecovery(options, {\n checkId: governanceCheckId,\n outcome: 'failed',\n outcomeIdempotencyKey,\n });\n await this.governanceMiddleware.reportOutcome(\n governanceCheckId,\n 'failed',\n undefined,\n { message: (error as Error).message },\n debugLogs,\n governanceResult.governanceContext,\n options.signal,\n outcomeIdempotencyKey\n );\n }\n const failed = this.createErrorResult<T>(taskId, agent, error, debugLogs, startTime);\n this.updateTaskStatus(taskId, 'failed', undefined, failed.error);\n return attachMatch(failed);\n } finally {\n if (taskAbortListener) options.signal!.removeEventListener('abort', taskAbortListener);\n }\n }\n\n /**\n * Handle agent response based on ADCP status (PR #78)\n */\n private buildGovernanceResult<T>(\n govResult: GovernanceCheckResult,\n taskId: string,\n taskName: string,\n agent: AgentConfig,\n startTime: number,\n debugLogs: any[]\n ): TaskResult<T> {\n return {\n success: false,\n status: 'governance-denied',\n error: govResult.explanation || 'Governance governance-denied',\n governance: govResult,\n metadata: this.buildMetadata({ taskId, taskName, agent, startTime, status: 'governance-denied' }),\n conversation: [],\n debug_logs: debugLogs,\n };\n }\n\n private async handleAsyncResponse<T>(\n agent: AgentConfig,\n taskId: string,\n taskName: string,\n params: any,\n response: any,\n messages: Message[],\n inputHandler?: InputHandler,\n options: TaskOptions = {},\n debugLogs: any[] = [],\n startTime: number = Date.now()\n ): Promise<TaskResult<T>> {\n const status = this.responseParser.getStatus(response) as ADCPStatus;\n\n switch (status) {\n case ADCP_STATUS.COMPLETED:\n // Task completed immediately\n const completedData = this.extractResponseData(response, debugLogs, taskName);\n this.updateTaskStatus(taskId, 'completed', completedData);\n\n const operationSuccess = this.isOperationSuccess(completedData, taskName);\n\n // Validate response against AdCP schema - validate extracted data, not protocol wrapper\n const validationResult = this.validateResponseSchema(completedData, taskName, debugLogs);\n\n // In strict mode, schema validation failures cause task to fail\n const finalSuccess = operationSuccess && validationResult.valid;\n const finalError = !finalSuccess\n ? validationResult.errors.length > 0\n ? `Schema validation failed: ${validationResult.errors.join('; ')}`\n : this.extractOperationError(completedData)\n : undefined;\n\n if (finalSuccess) {\n return {\n success: true as const,\n status: 'completed' as const,\n data: completedData,\n metadata: this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'completed',\n response,\n }),\n conversation: messages,\n debug_logs: debugLogs,\n };\n }\n const completedAdcpError = extractAdcpErrorInfo(completedData);\n return {\n success: false as const,\n status: 'failed' as const,\n data: completedData,\n error: finalError ?? 'Unknown error',\n adcpError: completedAdcpError,\n errorInstance: this.buildErrorInstance(taskId, completedAdcpError),\n correlationId: extractCorrelationId(completedData),\n metadata: this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'failed',\n response,\n }),\n conversation: messages,\n debug_logs: debugLogs,\n };\n\n case ADCP_STATUS.WORKING:\n // Server is processing - keep connection open for up to 120s\n return this.waitForWorkingCompletion<T>(\n agent,\n taskId,\n taskName,\n params,\n response,\n messages,\n inputHandler,\n options,\n debugLogs,\n startTime\n );\n\n case ADCP_STATUS.SUBMITTED:\n // Long-running task - set up webhook\n return this.setupSubmittedTask<T>(agent, taskId, taskName, response, messages, options, debugLogs, startTime);\n\n case ADCP_STATUS.INPUT_REQUIRED:\n // Server needs input - handler is mandatory\n return this.handleInputRequired<T>(\n agent,\n taskId,\n taskName,\n params,\n response,\n messages,\n inputHandler,\n options,\n debugLogs,\n startTime\n );\n\n case ADCP_STATUS.FAILED:\n case ADCP_STATUS.REJECTED:\n case ADCP_STATUS.CANCELED: {\n const failedData = this.extractResponseData(response, debugLogs, taskName);\n // Raw/in-process protocol clients may wrap the tool payload under\n // `data` while carrying the task lifecycle status at the top level.\n // The generic unwrapper intentionally preserves that wrapper, so\n // select its nested payload here before extracting business errors.\n const failedPayload =\n response?.structuredContent === undefined &&\n response?.content === undefined &&\n response?.result === undefined &&\n response?.data != null &&\n typeof response.data === 'object'\n ? response.data\n : failedData;\n const adcpErrorInfo = extractAdcpErrorInfo(failedPayload);\n const hasStructuredError = !!adcpErrorInfo;\n // Preserve failedData whenever the server returned a structured\n // payload — not just when extractAdcpErrorInfo recognizes an\n // `adcp_error`/`errors` envelope. Tool-level error shapes like\n // `comply_test_controller`'s `{ success: false, error: 'UNKNOWN_SCENARIO' }`\n // don't match that extractor but still carry the information\n // storyboard validators read (`success`, `error_code`, etc.).\n // Only drop `data` when there's literally no structured payload —\n // i.e. falsy or an empty object.\n const hasStructuredPayload =\n failedPayload != null &&\n typeof failedPayload === 'object' &&\n (Array.isArray(failedPayload) || Object.keys(failedPayload).length > 0);\n const structuredMessage = hasStructuredPayload ? this.extractOperationError(failedPayload) : undefined;\n const failedError =\n structuredMessage && structuredMessage !== 'Operation failed'\n ? structuredMessage\n : response.error || response.message || structuredMessage || `Task ${status}`;\n return {\n success: false as const,\n status: 'failed' as const,\n data: hasStructuredError || hasStructuredPayload ? failedPayload : undefined,\n error: typeof failedError === 'string' ? failedError : `Task ${status}`,\n adcpError: adcpErrorInfo,\n errorInstance: this.buildErrorInstance(taskId, adcpErrorInfo),\n correlationId: extractCorrelationId(failedPayload),\n metadata: this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'failed',\n response,\n }),\n conversation: messages,\n debug_logs: debugLogs,\n };\n }\n\n default:\n // Unknown status - treat as completed if we have data\n const defaultData = this.extractResponseData(response, debugLogs, taskName);\n if (\n defaultData &&\n (defaultData !== response || response.structuredContent || response.result || response.data)\n ) {\n const defaultSuccess = this.isOperationSuccess(defaultData, taskName);\n\n // Validate response against AdCP schema - validate extracted data, not protocol wrapper\n const defaultValidation = this.validateResponseSchema(defaultData, taskName, debugLogs);\n\n // In strict mode, schema validation failures cause task to fail\n const defaultFinalSuccess = defaultSuccess && defaultValidation.valid;\n const defaultFinalError = !defaultFinalSuccess\n ? defaultValidation.errors.length > 0\n ? `Schema validation failed: ${defaultValidation.errors.join('; ')}`\n : this.extractOperationError(defaultData)\n : undefined;\n\n if (defaultFinalSuccess) {\n return {\n success: true as const,\n status: 'completed' as const,\n data: defaultData,\n metadata: this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'completed',\n response,\n }),\n conversation: messages,\n debug_logs: debugLogs,\n };\n }\n const defaultAdcpError = extractAdcpErrorInfo(defaultData);\n return {\n success: false as const,\n status: 'failed' as const,\n data: defaultData,\n error: defaultFinalError!,\n adcpError: defaultAdcpError,\n errorInstance: this.buildErrorInstance(taskId, defaultAdcpError),\n correlationId: extractCorrelationId(defaultData),\n metadata: this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'failed',\n response,\n }),\n conversation: messages,\n debug_logs: debugLogs,\n };\n } else {\n throw new Error(`Unknown status: ${status || 'undefined'}`);\n }\n }\n }\n\n /**\n * Extract response data from different protocol formats\n *\n * @internal Exposed for testing purposes\n */\n public extractResponseData(response: any, debugLogs?: any[], toolName?: string): any {\n // MCP error responses (isError: true) flow through here — the response unwrapper\n // extracts structured data (adcp_error, context, ext) from structuredContent or text\n\n // Use the shared response unwrapper utility\n // This handles MCP structuredContent, A2A artifacts (including HITL multi-artifact responses),\n // and various edge cases consistently\n try {\n // Log what type of response we're processing BEFORE unwrapping\n // This ensures we have debug visibility even if unwrapping fails\n if (response?.structuredContent) {\n this.logDebug(debugLogs, 'info', 'Processing MCP structuredContent response');\n } else if (response?.result?.artifacts) {\n const artifacts = response.result.artifacts;\n if (artifacts.length === 0) {\n this.logDebug(debugLogs, 'info', 'Processing A2A response with empty artifacts array');\n } else {\n // Calculate total part count across all artifacts\n const totalParts = artifacts.reduce((sum: number, artifact: any) => {\n return sum + (artifact.parts?.length || 0);\n }, 0);\n\n // Extract canonical DataPart keys for debugging.\n const latestDataPart = getLatestA2ADataPartFromResponse(response);\n const dataKeys = latestDataPart?.data ? Object.keys(latestDataPart.data) : [];\n\n this.logDebug(debugLogs, 'info', 'Processing A2A artifact structure', {\n artifactCount: artifacts.length,\n partCount: totalParts,\n extractedFrom: artifacts.length > 1 ? 'multi-artifact (HITL)' : 'single-artifact',\n dataKeys,\n });\n }\n } else if (response?.data) {\n this.logDebug(debugLogs, 'info', 'Processing response.data field');\n } else {\n this.logDebug(debugLogs, 'info', 'Processing response without standard structure', {\n responseKeys: Object.keys(response || {}),\n });\n }\n\n // Now unwrap the response\n const unwrapped = unwrapProtocolResponse(response, toolName, undefined, {\n filterInvalidProducts: this.config.filterInvalidProducts,\n responseAdcpVersion: this.effectiveResponseAdcpVersion(),\n });\n\n // Log successful extraction with result details\n if (response?.structuredContent) {\n this.logDebug(debugLogs, 'info', 'Successfully extracted MCP data', {\n dataKeys: Object.keys(unwrapped || {}),\n });\n } else if (response?.result?.artifacts && response.result.artifacts.length > 0) {\n this.logDebug(debugLogs, 'info', 'Successfully extracted A2A data', {\n dataKeys: Object.keys(unwrapped || {}),\n });\n }\n\n return unwrapped;\n } catch (error) {\n this.logDebug(debugLogs, 'warning', 'Response unwrapper failed', {\n error: error instanceof Error ? error.message : String(error),\n toolName,\n responseKeys: Object.keys(response || {}),\n });\n\n // If toolName was provided, schema validation may have caused the failure.\n // Retry without toolName to extract the payload without schema checks.\n if (toolName) {\n try {\n return unwrapProtocolResponse(response);\n } catch {\n // Unwrapping itself failed — fall through to raw response\n }\n }\n\n return response;\n }\n }\n\n /**\n * Check if extracted response data represents a successful operation.\n * Handles singular `error`, plural `errors` (AdCP schema), and `success: false`.\n */\n private isOperationSuccess(data: any, taskName?: string): boolean {\n return isAdcpOperationSuccess(data, taskName, this.effectiveResponseAdcpVersion());\n }\n\n /**\n * Extract a human-readable error message from response data.\n * Handles singular `error`, plural `errors` array, and `message` field.\n */\n private extractOperationError(data: any): string {\n if (data?.adcp_error) {\n const ae = data.adcp_error;\n return ae.message ? `${ae.code}: ${ae.message}` : ae.code;\n }\n const pluralError = Array.isArray(data?.errors)\n ? data.errors\n .map((error: any) => error?.message || error?.code)\n .filter((value: unknown): value is string => typeof value === 'string' && value.length > 0)\n .join('; ')\n : undefined;\n return (\n data?.error ||\n pluralError ||\n data?.error_detail ||\n data?.reason ||\n data?.rejection_reason ||\n data?.message ||\n 'Operation failed'\n );\n }\n\n /**\n * Helper to add debug logs safely\n */\n private logDebug(debugLogs: any[] | undefined, type: string, message: string, details?: any) {\n if (debugLogs && Array.isArray(debugLogs)) {\n debugLogs.push({\n type,\n message,\n timestamp: new Date().toISOString(),\n details,\n });\n }\n }\n\n /**\n * Handle 'working' status - return as valid intermediate state\n */\n private async waitForWorkingCompletion<T>(\n agent: AgentConfig,\n taskId: string,\n taskName: string,\n params: any,\n initialResponse: any,\n messages: Message[],\n inputHandler?: InputHandler,\n options: TaskOptions = {},\n debugLogs: any[] = [],\n startTime: number = Date.now()\n ): Promise<TaskResult<T>> {\n // Extract any data that came with the working response\n const partialData = this.extractResponseData(initialResponse, debugLogs, taskName);\n const metadata = this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'working',\n response: initialResponse,\n });\n this.compactIntermediateTaskState(taskId, 'working');\n\n // Return working status immediately - this is a valid intermediate state\n // Callers can use the taskId to poll for completion or set up webhooks\n return {\n success: true, // The task is progressing, not failed\n status: 'working',\n data: partialData,\n metadata,\n conversation: messages,\n debug_logs: debugLogs,\n };\n }\n\n /**\n * Set up submitted task with webhook\n */\n private async setupSubmittedTask<T>(\n agent: AgentConfig,\n taskId: string,\n taskName: string,\n response: any,\n messages: Message[],\n options: TaskOptions = {},\n debugLogs: any[] = [],\n startTime: number = Date.now()\n ): Promise<TaskResult<T>> {\n // Extract any data that came with the submitted response\n const partialData = this.extractResponseData(response, debugLogs, taskName);\n\n let webhookUrl = response.webhookUrl;\n\n // If no webhook URL provided by server, generate one. The webhook URL\n // macro path uses the local `taskId` (the runner-side correlation id\n // that doubles as the `{operation_id}` macro value), not the server\n // handle — webhook URLs identify the buyer-side request, not the\n // seller-side task.\n if (!webhookUrl && this.config.webhookManager) {\n webhookUrl = this.config.webhookManager.generateUrl(taskId);\n await this.config.webhookManager.registerWebhook(agent, taskId, webhookUrl);\n }\n\n // Polling and the buyer-facing `SubmittedContinuation.taskId` use the\n // SERVER-assigned task handle, not the runner's local UUID. The local\n // UUID is the `activeTasks` map key and the `{operation_id}` webhook\n // macro value — it never reaches the seller. The server handle comes\n // from `response.task_id` / `response.data.task_id` (AdCP submitted-arm\n // wire fields) or, for A2A responses, the same handle surfaced via\n // metadata (`adcp_task_id` / `serverTaskId`) before falling back to the\n // transport `result.id` / `taskId`. `responseParser.getTaskId` walks these\n // shapes.\n //\n // When the seller violated the spec and didn't include a task handle\n // we fall back to the local UUID so the buyer at least gets a\n // non-undefined `taskId` field. The polling cycle won't be able to\n // locate the work in this state — log an advisory so operators\n // grepping debug logs can pinpoint the seller-side spec violation.\n const extractedServerTaskId = this.responseParser.getTaskId(response);\n const serverTaskId = extractedServerTaskId ?? taskId;\n // Snapshot only what continuations need. Referencing `options.transport`\n // inside either closure would retain the entire per-call options object,\n // including unrelated adopter metadata, for as long as the continuation\n // remains reachable.\n const pollingTransport = options.transport;\n if (!extractedServerTaskId) {\n debugLogs.push({\n type: 'warning',\n message:\n 'Submitted-arm response omitted task_id (spec violation). Polling will use the runner-side ' +\n 'correlation id as a fallback; the seller will not recognize it. ' +\n 'Expected: response.task_id / response.data.task_id (AdCP), A2A metadata.serverTaskId, ' +\n 'A2A metadata.adcp_task_id, or result.id with kind === \"task\" (A2A wrapped).',\n timestamp: new Date().toISOString(),\n taskName,\n runnerTaskId: taskId,\n });\n }\n\n const submitted: SubmittedContinuation<T> = {\n taskId: serverTaskId,\n webhookUrl,\n track: async (transport?: import('../protocols').TransportOptions) => {\n const task = await this.getTaskStatus(agent, serverTaskId, transport ?? pollingTransport);\n if (['completed', 'failed', 'rejected', 'canceled'].includes(task.status)) {\n this.updateTaskStatus(taskId, task.status as TaskStatus, task.result, task.error);\n }\n return task;\n },\n waitForCompletion: async (pollInterval = 60000, signal?: AbortSignal) => {\n const completed = await this.pollTaskCompletion<T>(agent, serverTaskId, pollInterval, pollingTransport, signal);\n // `pollTaskCompletion` also returns paused input-required/auth-required\n // states. Preserve that status so callers can resume the seller task;\n // only genuinely terminal statuses trigger delayed state eviction.\n this.updateTaskStatus(taskId, completed.status as TaskStatus, completed.data, completed.error);\n return completed;\n },\n };\n\n const metadata = this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'submitted',\n response,\n });\n this.compactIntermediateTaskState(taskId, 'submitted');\n\n return {\n success: true, // The task is progressing, not failed\n status: 'submitted',\n submitted,\n data: partialData,\n metadata,\n conversation: messages,\n debug_logs: debugLogs,\n };\n }\n\n /**\n * A working/submitted response carries everything needed to poll externally.\n * Keeping the original request in activeTasks after dispatch would pin\n * inline assets, webhook credentials, conversation payloads, and per-call\n * options for an unbounded amount of time while the seller works. Retain\n * only lifecycle metadata and the separately tracked idempotency key.\n */\n private compactIntermediateTaskState(\n taskId: string,\n status: 'working' | 'submitted' | 'input-required' | 'auth-required' | 'deferred'\n ): void {\n const task = this.activeTasks.get(taskId);\n if (!task) return;\n task.status = status;\n task.params = undefined;\n task.messages = [];\n task.options = {};\n delete task.pendingInput;\n this.compactedTaskIds.delete(taskId);\n this.compactedTaskIds.set(taskId, true);\n while (this.compactedTaskIds.size > COMPACTED_TASK_STATE_LIMIT) {\n const oldest = this.compactedTaskIds.keys().next().value;\n if (oldest === undefined) break;\n this.compactedTaskIds.delete(oldest);\n this.activeTasks.delete(oldest);\n }\n }\n\n /**\n * Handle input-required status\n *\n * Some agents (like Yahoo) return input-required status. THIS IS TOTALLY VALID AND IS AN INTERMEDIATE STATE.\n * IT SHOULD NOT BE THROWING AN ERROR. IT DOES NOT ALWAYS REQUIRE an input handler.\n * This is common for HITL (human-in-the-loop) workflows where the agent has already processed\n * the request and is just signaling that async approval may be needed.\n */\n private async handleInputRequired<T>(\n agent: AgentConfig,\n taskId: string,\n taskName: string,\n params: any,\n response: any,\n messages: Message[],\n inputHandler?: InputHandler,\n options: TaskOptions = {},\n debugLogs: any[] = [],\n startTime: number = Date.now()\n ): Promise<TaskResult<T>> {\n const inputRequest = this.responseParser.parseInputRequest(response);\n\n // If no handler provided, return input-required status as a valid intermediate state\n // This allows callers to handle the input-required state themselves (e.g., HITL workflows)\n if (!inputHandler) {\n // Extract any data that came with the response (some agents include partial results)\n const partialData = this.extractResponseData(response, debugLogs, taskName);\n const metadata = this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'input-required',\n response,\n inputRequest,\n });\n this.compactIntermediateTaskState(taskId, 'input-required');\n\n return {\n success: true, // The task is progressing, not failed\n status: 'input-required',\n data: partialData,\n metadata,\n conversation: messages,\n debug_logs: debugLogs,\n };\n }\n\n // Build context for handler\n const context: ConversationContext = {\n messages,\n inputRequest,\n taskId,\n agent: { id: agent.id, name: agent.name, protocol: agent.protocol },\n attempt: 1,\n maxAttempts: options.maxClarifications || 3,\n deferToHuman: async () => ({ defer: true, token: randomUUID() }),\n abort: reason => {\n throw new Error(reason || 'Task aborted');\n },\n getSummary: () => messages.map(m => `${m.role}: ${JSON.stringify(m.content)}`).join('\\n'),\n wasFieldDiscussed: field =>\n // Check if any agent message requested this field via input-required\n messages.some(\n m =>\n m.role === 'agent' &&\n m.content &&\n typeof m.content === 'object' &&\n 'field' in m.content &&\n (m.content as Record<string, unknown>).field === field\n ),\n getPreviousResponse: field => {\n // Find the agent message that requested this field\n const fieldRequestIndex = messages.findIndex(\n m =>\n m.role === 'agent' &&\n m.content &&\n typeof m.content === 'object' &&\n 'field' in m.content &&\n (m.content as Record<string, unknown>).field === field\n );\n // The response is the next user message after the field request\n if (fieldRequestIndex >= 0) {\n const responseMsg = messages\n .slice(fieldRequestIndex + 1)\n .find(m => m.role === 'user' && m.metadata?.type === 'input_response');\n return responseMsg?.content;\n }\n return undefined;\n },\n };\n\n // Call handler\n const handlerResponse = await inputHandler(context);\n throwIfAborted(options.signal);\n\n // Check if handler wants to defer\n if (isDeferResponse(handlerResponse)) {\n const token = handlerResponse.token;\n\n // Save deferred state for later resumption\n if (this.config.deferredStorage) {\n await this.config.deferredStorage.set(token, {\n taskId,\n contextId: response.contextId || taskId,\n agent,\n taskName,\n params,\n messages,\n createdAt: Date.now(),\n });\n try {\n throwIfAborted(options.signal);\n } catch (error) {\n // Cancellation may race a storage adapter that ignores the signal.\n // Remove the just-written resume record before propagating it.\n await this.config.deferredStorage.delete(token);\n throw error;\n }\n }\n // Deferred storage is the resume source of truth. Avoid retaining a\n // duplicate full request (including assets/credentials) in activeTasks.\n this.compactIntermediateTaskState(taskId, 'deferred');\n\n const deferred: DeferredContinuation<T> = {\n token,\n question: inputRequest.question,\n resume: input => this.resumeDeferredTask<T>(token, input),\n };\n\n return {\n success: true, // The task is progressing, not failed\n status: 'deferred',\n deferred,\n metadata: this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'deferred',\n clarificationRounds: 1,\n response,\n }),\n conversation: messages,\n debug_logs: debugLogs,\n };\n }\n\n // Handler provided input - continue with the task\n throwIfAborted(options.signal);\n return this.continueTaskWithInput<T>(\n agent,\n taskId,\n taskName,\n params,\n response.contextId,\n handlerResponse,\n messages,\n inputHandler, // Pass handler for multi-round clarification\n options,\n debugLogs,\n startTime\n );\n }\n\n /**\n * List tasks for an agent, preferring MCP Tasks protocol when available.\n */\n private async listTasksForAgent(\n agent: AgentConfig,\n transport?: import('../protocols').TransportOptions\n ): Promise<TaskInfo[]> {\n // Try MCP Tasks protocol method first\n if (agent.protocol === 'mcp') {\n const authToken = getAuthToken(agent);\n try {\n return await listMCPTasks(agent.agent_uri, authToken, undefined, {\n transport: transport ?? this.config.transport,\n onTransportActivity: this.config.onTransportActivity,\n transportActivityContext: {\n agentId: agent.id,\n },\n });\n } catch (err) {\n if (is401Error(err)) throw err;\n // Fall through to tool call if protocol method is not supported\n }\n }\n const response = (await ProtocolClient.callTool(\n agent,\n 'tasks/list',\n {},\n {\n serverVersion: this.lastKnownServerVersion,\n adcpVersion: this.config.adcpVersion,\n ...(this.config.wireAdcpVersion !== undefined && { wireAdcpVersion: this.config.wireAdcpVersion }),\n ...(this.config.versionEnvelope !== undefined && { versionEnvelope: this.config.versionEnvelope }),\n transport: transport ?? this.config.transport,\n onTransportActivity: this.config.onTransportActivity,\n }\n )) as Record<string, unknown>;\n return (response.tasks as TaskInfo[]) || [];\n }\n\n /**\n * Task tracking methods (PR #78)\n */\n async listTasks(agent: AgentConfig, transport?: import('../protocols').TransportOptions): Promise<TaskInfo[]> {\n try {\n return await this.listTasksForAgent(agent, transport);\n } catch {\n // Static message only — CodeQL's taint analysis treats `error` and\n // every property of it as sensitive once it originates from an\n // operation that touched `agent.oauth_client_credentials`. Surfaces\n // the failure occurred; full detail is available via DEBUG=adcp:*.\n console.warn('Failed to list tasks (see DEBUG=adcp:* logs for detail)');\n return [];\n }\n }\n\n private async getTaskStatusWithRawResponse(\n agent: AgentConfig,\n taskId: string,\n transport?: import('../protocols').TransportOptions,\n signal?: AbortSignal\n ): Promise<TaskStatusPollResult> {\n // AdCP `tasks/get` is the cross-protocol work-status interface\n // (`schemas/cache/<v>/bundled/core/tasks-get-{request,response}.json`).\n // MCP tool names cannot contain `/`, so MCP servers advertise the\n // SDK-owned `tasks_get` alias; A2A continues to use the spec slash name.\n //\n // The previous implementation tried MCP's `experimental.tasks.getTask`\n // first for MCP agents and fell through to the AdCP tool path on\n // capability-missing. The native MCP path tracks the TRANSPORT-call\n // lifecycle (MCP analog of A2A `Task.state`) — not AdCP work\n // lifecycle. For submitted-arm polling we need work status; the\n // two interfaces are not substitutes, so we always use the AdCP\n // tool here. MCP sellers that haven't registered `tasks_get` as\n // an AdCP tool will surface a tool-not-found error rather than\n // silently polling the wrong lifecycle.\n //\n // The request param is `task_id` (snake_case per AdCP 3.0); the\n // response is the spec's flat shape, mapped to `TaskInfo` via\n // {@link mapTasksGetResponseToTaskInfo}.\n //\n //\n // Request includes `include_result: true` so spec-conformant\n // sellers (AdCP 3.1.0+) populate the typed `result` field on\n // `completed` responses (per adcontextprotocol/adcp#3126). Older\n // sellers ignore the unknown request field; the response mapper\n // falls back to the informal `additionalProperties` passthrough\n // for those.\n const toolName = agent.protocol === 'mcp' ? 'tasks_get' : 'tasks/get';\n const response = (await ProtocolClient.callTool(\n agent,\n toolName,\n { task_id: taskId, include_result: true },\n {\n serverVersion: this.lastKnownServerVersion,\n adcpVersion: this.config.adcpVersion,\n ...(this.config.wireAdcpVersion !== undefined && { wireAdcpVersion: this.config.wireAdcpVersion }),\n ...(this.config.versionEnvelope !== undefined && { versionEnvelope: this.config.versionEnvelope }),\n transport: transport ?? this.config.transport,\n signal,\n onTransportActivity: this.config.onTransportActivity,\n transportActivityContext: {\n taskId,\n },\n }\n )) as Record<string, unknown>;\n // We don't run `extractResponseData` here: that helper's\n // generic AdCP-error-arm detection treats any top-level\n // `error: { code, message }` as an error envelope and shreds the\n // response into `{ errors: [...] }`. For `tasks/get` the `error`\n // block is informational (the failed task's reason, not a\n // request rejection), so we map the raw response directly. The\n // mapper handles the AdCP-spec flat shape, the legacy\n // `{ task: ... }` nested wrapper, and MCP `structuredContent` /\n // A2A latest structured DataPart envelopes.\n return {\n task: mapTasksGetResponseToTaskInfo(response),\n rawResponse: response,\n };\n }\n\n async getTaskStatus(\n agent: AgentConfig,\n taskId: string,\n transport?: import('../protocols').TransportOptions,\n signal?: AbortSignal\n ): Promise<TaskInfo> {\n return (await this.getTaskStatusWithRawResponse(agent, taskId, transport, signal)).task;\n }\n\n async pollTaskCompletion<T>(\n agent: AgentConfig,\n taskId: string,\n pollInterval = 60000,\n transport?: import('../protocols').TransportOptions,\n signal?: AbortSignal\n ): Promise<TaskResult<T>> {\n const pollStartTime = Date.now();\n while (true) {\n // adcp-client#1612: When the outer storyboard race timer fires, the\n // caller's AbortSignal is already aborted. Exit cleanly rather than\n // continuing to send `tasks/get` requests that nobody is waiting for.\n if (signal?.aborted) {\n const reason =\n signal.reason instanceof Error ? signal.reason.message : String(signal.reason ?? 'polling cancelled');\n // adcp-client#1617: Phase 1 — notify the seller so it can stop doing\n // work for a buyer that has already given up. A2A 0.3.0 §7.4 defines\n // tasks/cancel for exactly this case. Fire-and-forget: cancel failure\n // (TaskNotCancelable, network error, terminal-state race) is non-fatal.\n // TODO(adcp-client#1617-phase2): upgrade to awaited cancel once AdCP\n // spec defines a cross-protocol cancel verb.\n //\n // SECURITY: silent on rejection. The orphan rejection's `Error.message`\n // can carry an echoed transport response body — same trust-boundary\n // concern as `raceWithSignal` in `src/lib/testing/client.ts`. A buyer\n // who has already aborted MUST NOT see seller-controlled text leak\n // into their logs/telemetry. The outer try AND the `.catch(() => {})`\n // are both intentional: a malformed `agent_uri` could throw\n // synchronously from `fetch(...)` before the promise chain catches\n // it, so the try guards the dispatch path; the `.catch()` guards the\n // async settlement path.\n if (agent.protocol === 'a2a' && taskId && agent.agent_uri) {\n try {\n // adcp-client#1617 Phase 2: pass the full agent so cancelA2ATask\n // can sign the POST when agent.request_signing is configured.\n // signed-requests sellers no longer 401 the cancel.\n const cancelTransport = normalizeTransportOptions(transport ?? this.config.transport);\n void cancelA2ATask(agent, taskId, cancelTransport?.trustedFetchFn, cancelTransport?.allowPrivateIp).catch(\n () => {\n /* see SECURITY note above */\n }\n );\n } catch {\n /* see SECURITY note above */\n }\n }\n return attachMatch({\n success: false as const,\n status: 'failed' as const,\n error: `tasks/get polling was cancelled before a terminal state was observed: ${reason}`,\n metadata: this.buildMetadata({\n taskId,\n taskName: 'unknown',\n agent,\n startTime: pollStartTime,\n status: 'failed',\n }),\n });\n }\n\n // adcp-client#1585: A2A 0.3.x defines no minimum retention TTL for\n // completed tasks. A seller may evict a task between the buyer\n // observing the working-state response and the first explicit\n // `tasks/get` poll firing — `getTaskStatus` then throws with a\n // \"Task <id> not found\" message. Surface a descriptive `failed`\n // `TaskResult` so the caller sees an actionable error instead of an\n // opaque uncaught exception escaping from the polling loop.\n let status: TaskInfo;\n let rawResponse: Record<string, unknown> | undefined;\n try {\n const pollResult = await this.getTaskStatusWithRawResponse(agent, taskId, transport, signal);\n status = pollResult.task;\n rawResponse = pollResult.rawResponse;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n // Bounded `\\S{1,128}` task-id segment (no `.*`) keeps the match\n // linear-time on adversarial inputs — CodeQL flags unbounded\n // polynomial regex on uncontrolled error strings.\n if (/\\btask\\s+\\S{1,128}\\s+not found\\b/i.test(msg)) {\n return attachMatch({\n success: false as const,\n status: 'failed' as const,\n error: `Task ${taskId} is no longer queryable — it may have been completed and evicted by the seller before this poll arrived. Consider using push notifications (reporting_webhook) instead of polling, or configuring a longer task retention TTL on the seller.`,\n metadata: this.buildMetadata({\n taskId,\n taskName: 'unknown',\n agent,\n startTime: pollStartTime,\n status: 'failed',\n }),\n });\n }\n throw err;\n }\n\n if (status.status === ADCP_STATUS.COMPLETED) {\n const pollSuccess = this.isOperationSuccess(status.result, status.taskType);\n\n if (pollSuccess) {\n return attachMatch({\n success: true as const,\n status: 'completed' as const,\n data: status.result,\n metadata: this.buildMetadata({\n taskId,\n taskName: status.taskType,\n agent,\n responseTimeMs: Date.now() - status.createdAt,\n status: 'completed',\n response: rawResponse,\n }),\n });\n }\n const asyncResultErr = extractAdcpErrorInfo(status.result);\n return attachMatch({\n success: false as const,\n status: 'failed' as const,\n data: status.result,\n error: this.extractOperationError(status.result),\n adcpError: asyncResultErr,\n errorInstance: this.buildErrorInstance(taskId, asyncResultErr),\n correlationId: extractCorrelationId(status.result),\n metadata: this.buildMetadata({\n taskId,\n taskName: status.taskType,\n agent,\n responseTimeMs: Date.now() - status.createdAt,\n status: 'failed',\n response: rawResponse,\n }),\n });\n }\n\n if (\n status.status === ADCP_STATUS.FAILED ||\n status.status === ADCP_STATUS.CANCELED ||\n status.status === ADCP_STATUS.REJECTED\n ) {\n const asyncFailedErr = extractAdcpErrorInfo(status.result);\n return attachMatch({\n success: false as const,\n status: 'failed' as const,\n data: status.result,\n error: status.error || status.message || `Task ${status.status}`,\n adcpError: asyncFailedErr,\n errorInstance: this.buildErrorInstance(taskId, asyncFailedErr),\n correlationId: extractCorrelationId(status.result),\n metadata: this.buildMetadata({\n taskId,\n taskName: status.taskType,\n agent,\n responseTimeMs: Date.now() - status.createdAt,\n status: 'failed',\n response: rawResponse,\n }),\n });\n }\n\n // Paused states: `input-required` and `auth-required`. Polling\n // alone can't advance these — the buyer must satisfy the paused\n // condition (supply input / refresh auth) and retry the\n // original tool call. Return a `TaskResultIntermediate` so the\n // caller can branch on `result.status`; this mirrors the\n // synchronous `handleInputRequired` no-handler path\n // (`success: true` because the task is progressing, not failed).\n // Without this branch the loop would spin until timeout — the\n // paused-state regression class flagged by adcp-client#977.\n if (status.status === ADCP_STATUS.INPUT_REQUIRED || status.status === ADCP_STATUS.AUTH_REQUIRED) {\n return attachMatch({\n success: true as const,\n status: status.status,\n data: status.result as T,\n metadata: this.buildMetadata({\n taskId,\n taskName: status.taskType,\n agent,\n responseTimeMs: Date.now() - status.createdAt,\n status: status.status,\n response: rawResponse,\n }),\n });\n }\n\n // adcp-client#1612: `status: 'unknown'` means `mapTasksGetResponseToTaskInfo`\n // could not extract a recognizable status string from the response — the\n // seller's `tasks/get` response did not conform to any expected envelope\n // shape (flat AdCP, MCP structuredContent, or A2A DataPart artifact).\n // Continuing to poll would spin forever since the shape won't change.\n // Surface a descriptive failure so the storyboard runner reports the\n // seller's non-conformance rather than burning the outer timeout budget.\n if (status.status === 'unknown') {\n return attachMatch({\n success: false as const,\n status: 'failed' as const,\n error:\n `tasks/get returned an unrecognizable response (parsed status: \"unknown\", taskId: \"${status.taskId}\"). ` +\n `The seller may not implement tasks/get as an AdCP skill, or its response did not match any ` +\n `supported envelope shape (flat AdCP, MCP structuredContent, or A2A DataPart artifact).`,\n metadata: this.buildMetadata({\n taskId,\n taskName: 'unknown',\n agent,\n startTime: pollStartTime,\n status: 'failed',\n response: rawResponse,\n }),\n });\n }\n\n await this.sleep(pollInterval);\n // Re-check after sleep so a signal that fired mid-sleep exits at the top\n // of the next iteration rather than issuing one more `getTaskStatus` call.\n if (signal?.aborted) continue;\n }\n }\n\n /**\n * Resume a deferred task (client deferral)\n */\n async resumeDeferredTask<T>(token: string, input: any): Promise<TaskResult<T>> {\n if (!this.config.deferredStorage) {\n throw new Error('Deferred storage not configured');\n }\n\n const state = await this.config.deferredStorage.get(token);\n if (!state) {\n throw new Error(`Deferred task not found: ${token}`);\n }\n\n try {\n // Continue task with the provided input (no handler for resumed deferred tasks)\n const resumed = await this.continueTaskWithInput<T>(\n state.agent,\n state.taskId,\n state.taskName,\n state.params,\n state.contextId,\n input,\n state.messages,\n undefined // No handler for deferred tasks - input was provided by human\n );\n const remainsPaused = ['input-required', 'auth-required', 'deferred'].includes(resumed.status);\n if (\n ['completed', 'failed', 'rejected', 'canceled', 'governance-denied', 'aborted'].includes(resumed.status) &&\n this.activeTasks.get(state.taskId)?.status !== resumed.status\n ) {\n this.updateTaskStatus(state.taskId, resumed.status as TaskStatus, resumed.data, resumed.error);\n }\n if (!remainsPaused) {\n await this.config.deferredStorage.delete(token);\n }\n return attachMatch(resumed);\n } catch (error) {\n // A thrown continuation failure is terminal for this deferred token.\n // Release both persistence and the in-memory request payload before the\n // error escapes to the caller.\n this.updateTaskStatus(state.taskId, 'failed', undefined, error instanceof Error ? error.message : String(error));\n try {\n await this.config.deferredStorage.delete(token);\n } catch {\n // Local request compaction above is the safety boundary. Preserve the\n // original continuation/delete error if external cleanup also fails.\n }\n throw error;\n }\n }\n\n /**\n * Continue a task after receiving input\n */\n private async continueTaskWithInput<T>(\n agent: AgentConfig,\n taskId: string,\n taskName: string,\n params: any,\n contextId: string,\n input: any,\n messages: Message[],\n inputHandler: InputHandler | undefined,\n options: TaskOptions = {},\n debugLogs: any[] = [],\n startTime: number = Date.now()\n ): Promise<TaskResult<T>> {\n // Add user input message\n const inputMessage: Message = {\n id: randomUUID(),\n role: 'user',\n content: input,\n timestamp: new Date().toISOString(),\n metadata: { type: 'input_response' },\n };\n messages.push(inputMessage);\n\n // Continue the task with input\n const response = await ProtocolClient.callTool(\n agent,\n 'continue_task',\n {\n contextId,\n input,\n },\n {\n debugLogs,\n serverVersion: this.lastKnownServerVersion,\n adcpVersion: this.config.adcpVersion,\n ...(this.config.wireAdcpVersion !== undefined && { wireAdcpVersion: this.config.wireAdcpVersion }),\n ...(this.config.versionEnvelope !== undefined && { versionEnvelope: this.config.versionEnvelope }),\n transport: options.transport ?? this.config.transport,\n signal: options.signal,\n onTransportActivity: this.config.onTransportActivity,\n transportActivityContext: {\n operationId: taskId,\n taskId,\n contextId,\n },\n }\n );\n\n // Add response message\n const responseMessage: Message = {\n id: randomUUID(),\n role: 'agent',\n content: response,\n timestamp: new Date().toISOString(),\n metadata: { type: 'continued_response' },\n };\n messages.push(responseMessage);\n\n // Handle the continued response (pass inputHandler for multi-round clarification)\n return this.handleAsyncResponse<T>(\n agent,\n taskId,\n taskName,\n params,\n response,\n messages,\n inputHandler,\n options,\n debugLogs,\n startTime\n );\n }\n\n /**\n * Utility methods\n */\n private sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n private createErrorResult<T>(\n taskId: string,\n agent: AgentConfig,\n error: any,\n debugLogs: any[] = [],\n startTime: number = Date.now()\n ): TaskResult<T> {\n // Try to extract structured error info from transport exceptions\n // (e.g., JSON-RPC errors with data.adcp_error)\n const transportData = error?.data || error?.response?.data;\n const adcpErrorInfo = extractAdcpErrorInfo(transportData);\n const correlationId = extractCorrelationId(transportData);\n\n return {\n success: false as const,\n status: 'failed' as const,\n error: error.message || String(error),\n adcpError: adcpErrorInfo,\n errorInstance: this.buildErrorInstance(taskId, adcpErrorInfo),\n correlationId,\n metadata: this.buildMetadata({\n taskId,\n taskName: 'unknown',\n agent,\n startTime,\n status: 'failed',\n }),\n debug_logs: debugLogs,\n };\n }\n\n /**\n * Legacy methods for backward compatibility\n */\n getConversationHistory(taskId: string): Message[] | undefined {\n return this.conversationStorage?.get(taskId);\n }\n\n clearConversationHistory(taskId: string): void {\n this.conversationStorage?.delete(taskId);\n }\n\n getActiveTasks(): TaskState[] {\n return Array.from(this.activeTasks.values());\n }\n\n // ====== TASK MANAGEMENT & NOTIFICATION METHODS ======\n\n private taskEventListeners = new Map<\n string,\n {\n callback: (task: TaskInfo) => void;\n agentId?: string;\n }[]\n >();\n\n private webhookRegistrations = new Map<\n string,\n {\n agent: AgentConfig;\n webhookUrl: string;\n taskTypes?: string[];\n }\n >();\n\n /**\n * Get task list for a specific agent\n */\n async getTaskList(agentId: string, transport?: import('../protocols').TransportOptions): Promise<TaskInfo[]> {\n // First try to get from agent via protocol\n const agent = this.findAgentById(agentId);\n if (agent) {\n try {\n return await this.listTasksForAgent(agent, transport);\n } catch {\n // Static message — see comment on listTasks above.\n console.warn('Failed to get remote task list (see DEBUG=adcp:* logs for detail)');\n }\n }\n\n // Fall back to local active tasks\n return Array.from(this.activeTasks.values())\n .filter(task => task.agent.id === agentId)\n .map(task => ({\n taskId: task.taskId,\n status: task.status,\n taskType: task.taskName,\n createdAt: task.startTime,\n updatedAt: task.startTime, // TODO: track updates\n }));\n }\n\n /**\n * Get detailed information about a specific task\n */\n async getTaskInfo(taskId: string): Promise<TaskInfo | null> {\n const localTask = this.activeTasks.get(taskId);\n if (localTask) {\n if (this.compactedTaskIds.has(taskId)) {\n this.compactedTaskIds.delete(taskId);\n this.compactedTaskIds.set(taskId, true);\n }\n return {\n taskId: localTask.taskId,\n status: localTask.status,\n taskType: localTask.taskName,\n createdAt: localTask.startTime,\n updatedAt: localTask.startTime,\n };\n }\n\n // Try to get from agent\n // Note: Would need to know which agent to query\n return null;\n }\n\n /**\n * Subscribe to task updates for a specific agent\n */\n onTaskUpdate(agentId: string, callback: (task: TaskInfo) => void): () => void {\n const listenerId = randomUUID();\n const listeners = this.taskEventListeners.get(listenerId) || [];\n listeners.push({ callback, agentId });\n this.taskEventListeners.set(listenerId, listeners);\n\n return () => {\n this.taskEventListeners.delete(listenerId);\n };\n }\n\n /**\n * Subscribe to task events with detailed callbacks\n */\n onTaskEvents(\n agentId: string,\n callbacks: {\n onTaskCreated?: (task: TaskInfo) => void;\n onTaskUpdated?: (task: TaskInfo) => void;\n onTaskCompleted?: (task: TaskInfo) => void;\n onTaskFailed?: (task: TaskInfo, error: string) => void;\n }\n ): () => void {\n const unsubscribeFns: (() => void)[] = [];\n\n // Create combined handler that routes to specific callbacks\n const handler = (task: TaskInfo) => {\n switch (task.status) {\n case 'submitted':\n case 'working':\n callbacks.onTaskCreated?.(task);\n break;\n case 'input-required':\n callbacks.onTaskUpdated?.(task);\n break;\n case 'completed':\n callbacks.onTaskCompleted?.(task);\n break;\n case 'failed':\n case 'rejected':\n case 'canceled':\n callbacks.onTaskFailed?.(task, task.error || `Task ${task.status}`);\n break;\n default:\n callbacks.onTaskUpdated?.(task);\n }\n };\n\n unsubscribeFns.push(this.onTaskUpdate(agentId, handler));\n\n return () => {\n unsubscribeFns.forEach(fn => fn());\n };\n }\n\n /**\n * Register webhook for task notifications\n */\n async registerWebhook(agent: AgentConfig, webhookUrl: string, taskTypes?: string[]): Promise<void> {\n this.webhookRegistrations.set(agent.id, {\n agent,\n webhookUrl,\n taskTypes,\n });\n\n // TODO: Register with remote agent if it supports webhooks\n console.log(`Webhook registered for agent ${agent.id}: ${webhookUrl}`);\n }\n\n /**\n * Unregister webhook notifications\n */\n async unregisterWebhook(agent: AgentConfig): Promise<void> {\n this.webhookRegistrations.delete(agent.id);\n console.log(`Webhook unregistered for agent ${agent.id}`);\n }\n\n /**\n * Emit task event to listeners\n */\n private emitTaskEvent(task: TaskInfo, agentId?: string): void {\n this.taskEventListeners.forEach(listeners => {\n listeners.forEach(({ callback, agentId: listenerAgentId }) => {\n if (!listenerAgentId || listenerAgentId === agentId) {\n try {\n callback(task);\n } catch (error) {\n console.error('Error in task event callback:', error instanceof Error ? error.message : 'unknown error');\n }\n }\n });\n });\n }\n\n /**\n * Normalize response data for schema validation\n *\n * Converts v2-style responses to v3 format before validation.\n * This ensures validation passes for both v2 and v3 server responses.\n */\n private normalizeResponseForValidation(response: any, taskName: string, legacyWire = false): any {\n if (!response) return response;\n\n // Strip underscore-prefixed client-side annotations (`_message` is added\n // by the response unwrapper, others may follow). Schemas with\n // `additionalProperties: false` (create-property-list-response, etc.)\n // would otherwise reject every response that reaches the grader's\n // schema check — the annotation is not part of the wire protocol.\n const stripped: Record<string, unknown> = {};\n if (typeof response === 'object' && !Array.isArray(response)) {\n for (const [k, v] of Object.entries(response)) {\n if (!k.startsWith('_')) stripped[k] = v;\n }\n } else {\n return taskName === 'get_products' && !legacyWire ? normalizeGetProductsResponse(response) : response;\n }\n\n // Validate v2.5 against the exact response that crossed the wire. Public\n // canonicalization happens later in SingleAgentClient; applying it here\n // would compare canonical `fixed_price`/`format_options` fields to the\n // legacy schema that correctly requires `rate`/`is_fixed`/`format_ids`.\n if (legacyWire) return stripped;\n\n switch (taskName) {\n case 'get_products':\n return normalizeGetProductsResponse(stripped);\n default:\n return stripped;\n }\n }\n\n /**\n * Validate an incoming response against the bundled AdCP JSON schema for\n * `taskName`. Strict mode fails the task; warn mode logs and returns\n * valid so the caller can continue. Off mode short-circuits before\n * AJV runs.\n */\n private validateResponseSchema(\n response: any,\n taskName: string,\n debugLogs: any[]\n ): { valid: boolean; errors: string[] } {\n const mode = this.responseValidationMode;\n const logViolations = this.config.logSchemaViolations !== false;\n\n try {\n // Validate against the version the agent actually spoke. Without\n // this, v2.5 sellers (e.g. Wonderstruck) return valid v2.5-shaped\n // responses and the SDK rejects them as malformed v3 — surfaces as\n // `pricing_options must NOT have fewer than 1 items` and similar\n // shape mismatches that don't exist in v2.5. The v3 → v2 path is\n // already correctly version-pinned via lastKnownServerVersion.\n const validationVersion =\n this.lastKnownServerVersion === 'v2'\n ? 'v2.5'\n : (this.responseAdcpVersionForValidation() ?? this.config.adcpVersion ?? ADCP_VERSION);\n const normalizedResponse = this.normalizeResponseForValidation(response, taskName, validationVersion === 'v2.5');\n // TaskExecutor owns the user-facing log entry below. Passing debugLogs\n // into the lower-level hook would emit a second, unversioned duplicate.\n const outcome = validateIncomingResponse(taskName, normalizedResponse, mode, undefined, validationVersion);\n if (outcome.valid) return { valid: true, errors: [] };\n\n const errorStrings = outcome.issues.map(i => `${i.pointer}: ${i.message}`);\n\n if (logViolations) {\n debugLogs.push({\n timestamp: new Date().toISOString(),\n type: mode === 'strict' ? 'error' : 'warning',\n message: `Schema validation ${mode === 'strict' ? 'failed' : 'warning'} for ${taskName}: ${formatIssues(\n outcome.issues\n )}`,\n errors: errorStrings,\n issues: outcome.issues,\n schemaVariant: outcome.variant,\n schemaVersion: validationVersion,\n mode,\n });\n }\n\n if (mode === 'warn') {\n if (logViolations) {\n console.warn(\n `Schema validation failed for ${taskName} against AdCP ${validationVersion} (non-blocking):`,\n errorStrings\n );\n }\n return { valid: true, errors: [] };\n }\n\n if (logViolations) {\n console.error(`Schema validation failed for ${taskName} against AdCP ${validationVersion}:`, errorStrings);\n }\n return { valid: false, errors: errorStrings };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'unknown error';\n console.error('Error during schema validation:', errorMessage);\n return {\n valid: mode !== 'strict',\n errors: mode === 'strict' ? [`Validation error: ${errorMessage}`] : [],\n };\n }\n }\n\n private responseAdcpVersionForValidation(): string | undefined {\n if (this.config.versionEnvelope === 'major-only') return '3.0';\n return undefined;\n }\n\n private effectiveResponseAdcpVersion(): string {\n if (this.lastKnownServerVersion === 'v2') return 'v2.5';\n return this.responseAdcpVersionForValidation() ?? this.config.adcpVersion ?? ADCP_VERSION;\n }\n\n /**\n * Update task status and emit events\n */\n private updateTaskStatus(taskId: string, status: TaskStatus, result?: any, error?: string): void {\n const task = this.activeTasks.get(taskId);\n if (task) {\n // Once cancellation has released request state, late work must not\n // resurrect the task or emit completion after the caller has retried.\n if (task.status === 'aborted' && status !== 'aborted') return;\n const previousStatus = task.status;\n task.status = status;\n\n const taskInfo: TaskInfo = {\n taskId: task.taskId,\n status: status,\n taskType: task.taskName,\n createdAt: task.startTime,\n updatedAt: Date.now(),\n result,\n error,\n };\n\n this.emitTaskEvent(taskInfo, task.agent.id);\n\n this.config.onActivity?.({\n type: 'status_change',\n operation_id: task.taskId,\n agent_id: task.agent.id,\n context_id: undefined,\n task_id: task.taskId,\n task_type: task.taskName,\n status: status,\n payload: result ?? (error ? { error } : undefined),\n timestamp: new Date().toISOString(),\n });\n\n if (status === 'input-required' || status === 'auth-required') {\n this.compactIntermediateTaskState(taskId, status);\n }\n\n // If task is finished, remove from active tasks after a delay.\n // unref() ensures this timer doesn't prevent the process from exiting.\n if (TERMINAL_TASK_STATUSES.has(status)) {\n // Keep lifecycle metadata briefly for status inspection, but release\n // request/conversation/options immediately. These may contain inline\n // creative assets and webhook or transport credentials.\n task.params = undefined;\n task.messages = [];\n task.options = {};\n delete task.pendingInput;\n setTimeout(() => {\n this.activeTasks.delete(taskId);\n this.compactedTaskIds.delete(taskId);\n }, 30000).unref(); // Keep for 30 seconds for final status checks\n }\n }\n }\n\n /**\n * Helper to find agent config by ID\n */\n private findAgentById(agentId: string): AgentConfig | undefined {\n // This would ideally be passed in or stored in the executor\n // For now, return undefined and fall back to local tasks\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,oBAA2B;AAE3B,uBAKO;AACP,uBAA6B;AAC7B,mCAA6C;AAC7C,kBAA6B;AAC7B,oBAAsE;AAGtE,0BAMO;AACP,8BAA6B;AAC7B,qBAA6B;AAC7B,gCAA+D;AAC/D,8BAA2D;AAC3D,yBAA2F;AAC3F,6BAA6C;AAC7C,oCAAuD;AACvD,iBAA6B;AAC7B,2BAAiD;AAEjD,iBAA8B;AAC9B,mBAAsD;AAgBtD,mBAA2E;AAC3E,oCAAqE;AAErE,kCAAqC;AAErC,wBAAoD;AACpD,mBAA4B;AAC5B,yBAAkC;AAClC,2BAKO;AAIP,IAAAA,iBAAiC;AAK1B,MAAM,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AAAA,QACzB,QAAQ,KAAK;AAAA,QACb;AAAA,QACA,UAAU,KAAK;AAAA,QACf,WAAW,KAAK;AAAA,QAChB,WAAW,KAAK,IAAI;AAAA,QACpB;AAAA,QACA;AAAA,MACF;AAEA,WAAK,cAAc,UAAU,KAAK,MAAM,EAAE;AAE1C,WAAK,OAAO,aAAa;AAAA,QACvB,MAAM;AAAA,QACN,cAAc,KAAK;AAAA,QACnB,UAAU,KAAK,MAAM;AAAA,QACrB,YAAY;AAAA,QACZ,SAAS,KAAK;AAAA,QACd,WAAW,KAAK;AAAA,QAChB;AAAA,QACA,SAAS,WAAW,QAAQ,EAAE,MAAM,IAAI;AAAA,QACxC,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MACpC,CAAC;AAED,UAAI,WAAW,oBAAoB,WAAW,iBAAiB;AAC7D,aAAK,6BAA6B,QAAQ,MAAM;AAAA,MAClD;AAIA,UAAI,uBAAuB,IAAI,MAAM,GAAG;AAItC,aAAK,SAAS;AACd,aAAK,WAAW,CAAC;AACjB,aAAK,UAAU,CAAC;AAChB,eAAO,KAAK;AACZ,mBAAW,MAAM;AACf,eAAK,YAAY,OAAO,MAAM;AAC9B,eAAK,iBAAiB,OAAO,MAAM;AAAA,QACrC,GAAG,GAAK,EAAE,MAAM;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKQ,cAAc,SAA0C;AAG9D,WAAO;AAAA,EACT;AACF;","names":["import_errors"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/core/TaskExecutor.ts"],"sourcesContent":["// Core task execution engine for ADCP conversation flow\n// Implements PR #78 async patterns: working/submitted/input-required/completed\n\nimport { createHash, randomUUID } from 'crypto';\nimport type { AgentConfig } from '../types';\nimport {\n ProtocolClient,\n normalizeTransportOptions,\n prepareProtocolToolCall,\n type PreparedProtocolToolCall,\n} from '../protocols';\nimport { listMCPTasks } from '../protocols/mcp-tasks';\nimport { withPreparedProtocolToolCall } from '../protocols/prepared-call-context';\nimport { getAuthToken } from '../auth';\nimport { is401Error, adcpErrorToTypedError, ConfigurationError } from '../errors';\nimport type { ADCPError } from '../errors';\nimport type { Storage } from '../storage/interfaces';\nimport {\n validateOutgoingRequest,\n validateIncomingResponse,\n resolveValidationModes,\n type ValidationHookConfig,\n type ValidationMode,\n} from '../validation/client-hooks';\nimport { formatIssues } from '../validation/schema-validator';\nimport { ADCP_VERSION } from '../version';\nimport { unwrapProtocolResponse, isAdcpOperationSuccess } from '../utils/response-unwrapper';\nimport { extractAdcpErrorInfo, extractCorrelationId } from '../utils/error-extraction';\nimport { generateIdempotencyKey, requestUsesIdempotency, redactIdempotencyKeyInArgs } from '../utils/idempotency';\nimport { normalizeGetProductsResponse } from '../utils/pricing-adapter';\nimport { normalizeLegacyMediaBuyStatusForReturn } from '../utils/envelope-status-compat';\nimport { canonicalize } from '../utils/jcs';\nimport { getLatestA2ADataPartFromResponse } from '../utils/a2a-artifacts';\nimport type { AdcpCapabilities } from '../utils/capabilities';\nimport { cancelA2ATask } from '../protocols/a2a';\nimport { isAbortOrTimeoutError, throwIfAborted } from '../protocols/abort';\nimport type {\n Message,\n InputRequest,\n InputHandler,\n ConversationContext,\n TaskOptions,\n TaskResult,\n TaskResultMetadata,\n TaskState,\n TaskStatus,\n TaskInfo,\n DeferredContinuation,\n SubmittedContinuation,\n WebhookUrlTemplate,\n} from './ConversationTypes';\nimport { normalizeHandlerResponse, isDeferResponse, isAbortResponse } from '../handlers/types';\nimport { ProtocolResponseParser, ADCP_STATUS, type ADCPStatus } from './ProtocolResponseParser';\nimport type { Activity } from './AsyncHandler';\nimport { GovernanceMiddleware } from './GovernanceMiddleware';\nimport type { GovernanceConfig, GovernanceCheckResult } from './GovernanceTypes';\nimport { targetDeclaresGovernanceEnforcement } from '../governance';\nimport { attachMatch } from './match';\nimport { resolveWebhookUrl } from './webhook-url';\nimport {\n attachTaskDeadlineGovernanceRecovery,\n attachTaskDeadlineIdempotencyKey,\n getTaskOperationId,\n withTaskDeadline,\n} from './task-deadline';\n\n// Keep the direct `core/TaskExecutor` export identical to the package-level\n// typed timeout error thrown by the deadline wrapper.\nexport { TaskTimeoutError } from '../errors';\n\n/**\n * Custom errors for task execution\n */\nexport class MaxClarificationError extends Error {\n constructor(taskId: string, maxAttempts: number) {\n super(`Task ${taskId} exceeded maximum clarification attempts: ${maxAttempts}`);\n this.name = 'MaxClarificationError';\n }\n}\n\nexport class DeferredTaskError extends Error {\n constructor(public token: string) {\n super(`Task deferred with token: ${token}`);\n this.name = 'DeferredTaskError';\n }\n}\n\nexport class InputRequiredError extends Error {\n constructor(question: string) {\n super(`Server requires input but no handler provided. Question: ${question}`);\n this.name = 'InputRequiredError';\n }\n}\n\n/** Supporting contract for the internal pre-dispatch boundary. */\nexport type BeforeProtocolDispatchHookResult<T> =\n | {\n action: 'dispatch_committed';\n /** Persist or otherwise settle the seller result inside the executor-owned dispatch lifetime. */\n onResult?: (result: TaskResult<T>) => Promise<TaskResult<T>>;\n /** Fence transport/parser uncertainty inside the executor-owned dispatch lifetime. */\n onError?: (error: unknown) => Promise<never>;\n }\n | { action: 'return'; result: TaskResult<T> };\n\n/** Context supplied to the internal pre-dispatch boundary. */\nexport interface BeforeProtocolDispatchContext {\n /** True when governance changed the payload rather than approving it unchanged. */\n governanceAdjusted: boolean;\n /** Publish a terminal continuation result after its durable settlement succeeds. */\n publishSettledTaskStatus: (status: TaskStatus, data?: unknown, error?: string) => void;\n /** Register durable settlement for an authoritative terminal push notification. */\n registerExternalTaskSettlement: (handler: ExternalTaskSettlementHandler) => void;\n}\n\nexport interface ExternalTaskSettlementObservation {\n status: TaskStatus;\n result?: unknown;\n serverTaskId?: string;\n taskType?: string;\n}\n\nexport type ExternalTaskSettlementHandler = (\n observation: ExternalTaskSettlementObservation\n) => Promise<TaskResult<unknown>>;\n\nexport interface ExternalTaskStatusResult {\n settled: boolean;\n /** Exact retry of a terminal observation that already completed durable settlement. */\n duplicate?: boolean;\n result?: unknown;\n status?: TaskStatus;\n error?: string;\n}\n\ninterface SettledExternalTaskObservation {\n key: string;\n status: TaskStatus;\n error?: string;\n}\n\ninterface ExternalTaskSettlementInFlight {\n observationKey: string;\n settlement: Promise<ExternalTaskStatusResult>;\n waiterCount: number;\n}\n\n/** Hook used by higher-level SDK coordinators at the final dispatch boundary. */\nexport type BeforeProtocolDispatchHook<T> = (\n effectiveParams: any,\n context: BeforeProtocolDispatchContext\n) => Promise<BeforeProtocolDispatchHookResult<T>>;\n\n/** Keeps internal dispatch-boundary failures out of the normal TaskResult error projection. */\n/** @internal */\nexport class BeforeProtocolDispatchHookError extends Error {\n constructor(readonly original: unknown) {\n super('An SDK pre-dispatch hook failed.', { cause: original });\n this.name = 'BeforeProtocolDispatchHookError';\n }\n}\n\n/** Keeps internal post-dispatch settlement failures out of normal TaskResult error projection. */\n/** @internal */\nexport class AfterProtocolDispatchHookError extends Error {\n constructor(readonly original: unknown) {\n super('An SDK post-dispatch settlement hook failed.', { cause: original });\n this.name = 'AfterProtocolDispatchHookError';\n }\n}\n\nconst GOVERNED_CREDENTIAL_SCAN_MAX_NODES = 10_000;\nconst GOVERNED_CREDENTIAL_SCAN_MAX_DEPTH = 64;\nconst GOVERNED_CALLBACK_FIELDS = new Set(['push_notification_config', 'reporting_webhook', 'artifact_webhook']);\n\ntype GovernedCredentialScanResult =\n | { kind: 'credential'; path: string; callbackField: string }\n | { kind: 'limit'; limit: 'nodes' | 'depth' };\n\nfunction webhookRegistrationFromPreparedCall(\n agent: AgentConfig,\n preparedCall: PreparedProtocolToolCall\n): { callbackUrl: string; mode: 'rfc9421' | 'hmac-sha256' } | undefined {\n const candidate =\n agent.protocol === 'a2a'\n ? preparedCall.pushNotificationConfig\n : preparedCall.args.push_notification_config &&\n typeof preparedCall.args.push_notification_config === 'object' &&\n !Array.isArray(preparedCall.args.push_notification_config)\n ? (preparedCall.args.push_notification_config as Record<string, unknown>)\n : undefined;\n if (!candidate) return undefined;\n if (typeof candidate.url !== 'string') {\n throw new ConfigurationError('push_notification_config.url must be a string.', 'push_notification_config.url');\n }\n\n if (!Object.prototype.hasOwnProperty.call(candidate, 'authentication')) {\n return { callbackUrl: candidate.url, mode: 'rfc9421' };\n }\n const authentication = candidate.authentication;\n if (!authentication || typeof authentication !== 'object' || Array.isArray(authentication)) {\n throw new ConfigurationError(\n 'push_notification_config.authentication selects legacy verification and must be a supported object.',\n 'push_notification_config.authentication'\n );\n }\n const schemes = (authentication as Record<string, unknown>).schemes;\n const credentials = (authentication as Record<string, unknown>).credentials;\n if (\n !Array.isArray(schemes) ||\n schemes.length !== 1 ||\n schemes[0] !== 'HMAC-SHA256' ||\n typeof credentials !== 'string' ||\n credentials.length === 0\n ) {\n throw new ConfigurationError(\n 'This receiver supports legacy HMAC-SHA256 or RFC 9421 push notifications; Bearer and mixed schemes are not supported.',\n 'push_notification_config.authentication.schemes'\n );\n }\n return {\n callbackUrl: candidate.url,\n mode: 'hmac-sha256',\n };\n}\n\n/**\n * Find callback authentication credentials before an exact downstream payload\n * crosses the governance-agent boundary. AdCP 3.2 requires intent payloads to\n * match the seller arguments byte-for-byte at the JSON-data-model level, so\n * the SDK cannot safely redact a credential and reinsert it after approval:\n * doing so would invalidate the seller's authorized_payload_hash check.\n */\nfunction findGovernedAuthenticationCredential(value: unknown): GovernedCredentialScanResult | undefined {\n const stack: Array<{ value: unknown; depth: number }> = [{ value, depth: 0 }];\n const visited = new WeakSet<object>();\n let visitedNodes = 0;\n\n while (stack.length > 0) {\n const current = stack.pop()!;\n if (!current.value || typeof current.value !== 'object') continue;\n if (current.depth > GOVERNED_CREDENTIAL_SCAN_MAX_DEPTH) return { kind: 'limit', limit: 'depth' };\n if (visited.has(current.value)) continue;\n visited.add(current.value);\n if (++visitedNodes > GOVERNED_CREDENTIAL_SCAN_MAX_NODES) return { kind: 'limit', limit: 'nodes' };\n\n if (!Array.isArray(current.value)) {\n const record = current.value as Record<string, unknown>;\n for (const callbackField of GOVERNED_CALLBACK_FIELDS) {\n const callback = record[callbackField];\n if (!callback || typeof callback !== 'object' || Array.isArray(callback)) continue;\n const authentication = (callback as Record<string, unknown>).authentication;\n if (\n authentication &&\n typeof authentication === 'object' &&\n !Array.isArray(authentication) &&\n (authentication as Record<string, unknown>).credentials !== undefined\n ) {\n return {\n kind: 'credential',\n path: `${callbackField}.authentication.credentials`,\n callbackField,\n };\n }\n }\n }\n\n for (const key in current.value) {\n if (!Object.prototype.hasOwnProperty.call(current.value, key)) continue;\n const child = (current.value as Record<string, unknown>)[key];\n if (!child || typeof child !== 'object') continue;\n if (visitedNodes + stack.length >= GOVERNED_CREDENTIAL_SCAN_MAX_NODES) {\n return { kind: 'limit', limit: 'nodes' };\n }\n stack.push({ value: child, depth: current.depth + 1 });\n }\n }\n return undefined;\n}\n\nfunction assertGovernedPayloadHasNoCallbackCredentials(\n taskName: string,\n payload: Record<string, unknown>,\n options: { sdkInjectedPushConfig?: boolean } = {}\n): void {\n const scanResult = findGovernedAuthenticationCredential(payload);\n if (!scanResult) return;\n if (scanResult.kind === 'limit') {\n const limitDescription =\n scanResult.limit === 'nodes'\n ? `${GOVERNED_CREDENTIAL_SCAN_MAX_NODES.toLocaleString('en-US')} nested objects`\n : `${GOVERNED_CREDENTIAL_SCAN_MAX_DEPTH} object levels`;\n throw new ConfigurationError(\n `The SDK could not safely inspect the governed ${taskName} payload for callback credentials because it ` +\n `exceeds the ${limitDescription} safety limit. Simplify the payload or move deeply nested extension data ` +\n `out of the governed request before retrying.`,\n 'governance.payload'\n );\n }\n const remedy =\n scanResult.callbackField === 'push_notification_config'\n ? options.sdkInjectedPushConfig\n ? 'Retry with task options `{ disableWebhook: true }` and poll for completion, or use A2A task-status notifications.'\n : 'Remove the credential-bearing push notification config and poll for completion, or use A2A task-status notifications.'\n : `Remove the credential-bearing ${scanResult.callbackField} from this governed request and use a ` +\n `non-webhook delivery path.`;\n throw new ConfigurationError(\n `Governed ${taskName} cannot forward ${scanResult.path} to the governance agent. ` +\n `The SDK will not disclose receiver authentication credentials, and redacting modern AdCP 3.2 payloads ` +\n `would invalidate seller authorization. ${remedy}`,\n scanResult.path\n );\n}\n\n/**\n * Map an AdCP `tasks/get` response (post-unwrap) to the SDK's internal\n * `TaskInfo` shape. The AdCP 3.0 schema\n * (`schemas/cache/3.0.0/bundled/core/tasks-get-response.json`) is flat\n * snake_case: `{ task_id, task_type, protocol, status, created_at,\n * updated_at, error?, progress?, history?, completed_at?, has_webhook?,\n * context?, ext? }`. The internal `TaskInfo` is camelCase with a\n * superset of legacy fields some pre-3.0 sellers still emit.\n *\n * **Result-data extraction.** AdCP 3.1.0 defines a typed `result`\n * field on `tasks/get` responses (per adcontextprotocol/adcp#3126,\n * which closed adcp#3123). Sellers populate it when the buyer's\n * request set `include_result: true` and the task reached\n * `completed`. The mapper reads it directly into `TaskInfo.result`\n * so `pollTaskCompletion` surfaces it on the resolved\n * `TaskResult.data`. Pre-3.1.0 sellers that emitted `result` via\n * `additionalProperties: true` continue to work — the typed and\n * informal paths share the same field name.\n *\n * **Legacy nested shape.** Some pre-3.0 sellers and existing test\n * mocks emit `{ task: { ...TaskInfo } }` — a non-spec wrapper. We\n * unwrap it before the spec-shape mapping so the SDK stays\n * compatible with both surfaces during the transition.\n */\nfunction mapTasksGetResponseToTaskInfo(payload: unknown): TaskInfo {\n if (payload == null || typeof payload !== 'object') {\n return { taskId: '', status: 'unknown', taskType: 'unknown', createdAt: Date.now(), updatedAt: Date.now() };\n }\n const obj = payload as Record<string, unknown>;\n // Walk the transport-level wrappers in priority order:\n // 1. MCP `structuredContent` — the typed AdCP payload from `tools/call`\n // 2. A2A latest structured DataPart — the AdCP payload\n // surfaced via the artifact (per #899)\n // 3. Legacy nested `{ task: TaskInfo }` — pre-3.0 sellers and\n // existing test mocks\n // 4. Flat AdCP-spec shape — what AdCP 3.0 sellers emit directly\n const flat = unwrapTasksGetEnvelope(obj);\n const errorRaw = flat.error;\n const errorMessage =\n typeof errorRaw === 'string'\n ? errorRaw\n : errorRaw != null &&\n typeof errorRaw === 'object' &&\n typeof (errorRaw as { message?: unknown }).message === 'string'\n ? (errorRaw as { message: string }).message\n : undefined;\n const taskInfo: TaskInfo = {\n taskId: stringField(flat.task_id) ?? stringField(flat.taskId) ?? '',\n status: stringField(flat.status) ?? 'unknown',\n taskType: stringField(flat.task_type) ?? stringField(flat.taskType) ?? 'unknown',\n createdAt: parseTimestamp(flat.created_at ?? flat.createdAt),\n updatedAt: parseTimestamp(flat.updated_at ?? flat.updatedAt),\n };\n if (errorMessage !== undefined) taskInfo.error = errorMessage;\n // Top-level `message` field: the AdCP envelope's human-readable\n // status descriptor (advisory string accompanying any status —\n // e.g. \"Budget cap exceeded — task not started\" on a `rejected`\n // task). `pollTaskCompletion` falls back to this when the\n // `error.message` block is absent on a terminal failure. Distinct\n // from `error.message` (which lives under the structured `error`\n // object).\n const messageField = stringField(flat.message);\n if (messageField !== undefined) taskInfo.message = messageField;\n // Result extraction — see JSDoc. AdCP 3.1.0 defines `result` as\n // the canonical typed field; pre-3.1.0 sellers using\n // `additionalProperties: true` shared the same field name, so the\n // mapping is unchanged across versions.\n if (flat.result !== undefined) {\n taskInfo.result =\n flat.result != null && typeof flat.result === 'object' && !Array.isArray(flat.result)\n ? normalizeLegacyMediaBuyStatusForReturn(flat.result as Record<string, unknown>, {\n toolName: taskInfo.taskType,\n })\n : flat.result;\n }\n return taskInfo;\n}\n\nfunction stringField(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\n/**\n * Cap on the wrapper-unwrap recursion depth. Real-world responses\n * have at most two layers (MCP `structuredContent` OR A2A JSON-RPC →\n * Task → artifact → DataPart). The cap is a defense against a\n * malformed or hostile seller emitting a deeply-nested wrapper that\n * would otherwise stack-overflow the buyer.\n */\nconst TASKS_GET_UNWRAP_MAX_DEPTH = 8;\n\nfunction unwrapTasksGetEnvelope(obj: Record<string, unknown>, depth = 0, allowRawData = true): Record<string, unknown> {\n if (depth >= TASKS_GET_UNWRAP_MAX_DEPTH) return obj;\n // MCP: `tools/call` response carries the typed payload at\n // `structuredContent`.\n const sc = obj.structuredContent;\n if (sc != null && typeof sc === 'object' && !Array.isArray(sc)) {\n return unwrapTasksGetEnvelope(sc as Record<string, unknown>, depth + 1, false);\n }\n // A2A: `message/send` response is a JSON-RPC envelope wrapping a\n // Task; the AdCP payload sits on the latest structured DataPart.\n const result = obj.result;\n if (result != null && typeof result === 'object' && !Array.isArray(result)) {\n const r = result as Record<string, unknown>;\n if (r.kind === 'task') {\n const extracted = getLatestA2ADataPartFromResponse(obj);\n if (extracted) {\n return unwrapTasksGetEnvelope(extracted.data, depth + 1, false);\n }\n // adcp-client#1612: When the A2A Task has no DataPart artifacts (e.g. the\n // seller returns an A2A transport-level state without an AdCP DataPart\n // payload), surface the transport-layer status as a last-resort hint so\n // `mapTasksGetResponseToTaskInfo` can map terminal states to `failed` /\n // `completed` rather than falling through to `'unknown'`. The transport\n // state overlaps with AdCP status strings for all A2A-native values\n // (`completed`, `failed`, `rejected`, `canceled`, `working`, `submitted`).\n // Note: `auth-required` is an AdCP-layer concept; it won't surface via\n // this path (no A2A-native transport state carries that label) — those\n // responses reach the `unknown` exit branch instead. Also include the A2A\n // task handle (`result.id`) so polling error messages carry the real id.\n const transportStatus = (r.status as Record<string, unknown> | undefined)?.state;\n if (typeof transportStatus === 'string') {\n return { status: transportStatus, task_id: typeof r.id === 'string' ? r.id : undefined };\n }\n }\n }\n // Raw/in-process MCP wrappers sometimes carry the AdCP payload under\n // `data` rather than the official CallToolResult `structuredContent`.\n // Unwrap only when it looks like a task envelope and no official payload\n // has already been selected.\n const data = obj.data;\n if (allowRawData && data != null && typeof data === 'object' && !Array.isArray(data)) {\n const d = data as Record<string, unknown>;\n if ('status' in d || 'task_id' in d || 'taskId' in d) {\n return unwrapTasksGetEnvelope(d, depth + 1, true);\n }\n }\n // Legacy nested wrapper from pre-3.0 sellers and existing mocks.\n // TODO(adcp-client#967): remove once mock fixtures in\n // `test/lib/task-executor*.test.js` migrate to the AdCP-spec flat\n // shape. No real seller emits this; verified at PR review time.\n if (obj.task != null && typeof obj.task === 'object' && !Array.isArray(obj.task)) {\n return obj.task as Record<string, unknown>;\n }\n // Flat AdCP-spec shape — return as-is.\n return obj;\n}\n\nfunction parseTimestamp(value: unknown): number {\n if (typeof value === 'string') {\n const parsed = Date.parse(value);\n if (!Number.isNaN(parsed)) return parsed;\n }\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n return Date.now();\n}\n\n/**\n * Return the idempotency_key this task should use: the caller's value if\n * present, otherwise a fresh UUID v4 for mutating tasks, otherwise undefined.\n */\nfunction resolveIdempotencyKey(taskName: string, params: any, serverVersion?: 'v2' | 'v3'): string | undefined {\n const callerSupplied =\n params && typeof params === 'object' && typeof params.idempotency_key === 'string'\n ? params.idempotency_key\n : undefined;\n if (callerSupplied) return callerSupplied;\n // v2.5 mutations use buyer_ref as their stable replay identity. Request\n // adaptation has already derived it from the caller's canonical key. Do\n // not inject a fresh v3-only idempotency_key after adaptation: that makes\n // identical retries differ on the wire and can defeat legacy dedupe.\n if (serverVersion === 'v2') {\n return params && typeof params === 'object' && typeof params.buyer_ref === 'string' ? params.buyer_ref : undefined;\n }\n if (requestUsesIdempotency(taskName, params)) return generateIdempotencyKey();\n return undefined;\n}\n\n/**\n * Webhook manager for submitted tasks\n */\ninterface WebhookManager {\n generateUrl(taskId: string): string;\n registerWebhook(agent: AgentConfig, taskId: string, webhookUrl: string): Promise<void>;\n processWebhook(token: string, body: any): Promise<void>;\n}\n\n/**\n * Deferred task storage for client deferrals\n */\ninterface DeferredTaskState {\n taskId: string;\n contextId: string;\n agent: AgentConfig;\n taskName: string;\n params: any;\n messages: Message[];\n createdAt: number;\n}\n\ninterface TaskStatusPollResult {\n task: TaskInfo;\n rawResponse: Record<string, unknown>;\n}\n\nconst COMPACTED_TASK_STATE_LIMIT = 10_000;\nconst DEFAULT_EXTERNAL_TASK_SETTLEMENT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;\nconst MAX_TIMER_DELAY_MS = 2_147_483_647;\nconst TERMINAL_TASK_STATUSES = new Set<TaskStatus>([\n 'completed',\n 'failed',\n 'rejected',\n 'canceled',\n 'governance-denied',\n 'aborted',\n]);\nconst MAX_PENDING_EXTERNAL_TASK_OBSERVATIONS = 8;\nconst MAX_RETAINED_EXTERNAL_TASK_ERROR_CHARS = 1_024;\n\n/**\n * Core task execution engine that handles the conversation loop with agents\n */\nexport class TaskExecutor {\n private readonly deferredTerminalPublicationTaskIds = new Set<string>();\n private readonly settlementCapacityReservations = new Set<string>();\n private readonly closedExternalTaskSettlementTaskIds = new Set<string>();\n private readonly externalTaskSettlementHandlers = new Map<string, ExternalTaskSettlementHandler>();\n private readonly externalTaskSettlementInFlight = new Map<string, ExternalTaskSettlementInFlight>();\n private readonly settledExternalTaskObservationKeys = new Map<string, SettledExternalTaskObservation>();\n private readonly externalTaskSettlementExpiry = new Map<string, number>();\n private readonly pendingExternalTaskObservations = new Map<\n string,\n Array<{\n observation: ExternalTaskSettlementObservation;\n resolve: (result: ExternalTaskStatusResult) => void;\n reject: (error: unknown) => void;\n }>\n >();\n private responseParser: ProtocolResponseParser;\n private activeTasks = new Map<string, TaskState>();\n private compactedTaskIds = new Map<string, true>();\n private conversationStorage?: Map<string, Message[]>;\n private governanceMiddleware?: GovernanceMiddleware;\n private lastKnownServerVersion?: 'v2' | 'v3';\n private requestValidationMode!: ValidationMode;\n private responseValidationMode!: ValidationMode;\n\n constructor(\n private config: {\n /** Default timeout for 'working' status (max 120s per PR #78) */\n workingTimeout?: number;\n /** Polling interval for 'working' status in milliseconds (default: 2000ms) */\n pollingInterval?: number;\n /** Default max clarification attempts */\n defaultMaxClarifications?: number;\n /** Enable conversation storage */\n enableConversationStorage?: boolean;\n /** Webhook manager for submitted tasks */\n webhookManager?: WebhookManager;\n /** Storage for deferred task state */\n deferredStorage?: Storage<DeferredTaskState>;\n /** Webhook URL template for protocol-level webhook support */\n webhookUrlTemplate?: WebhookUrlTemplate;\n /** Agent ID for webhook URL generation */\n agentId?: string;\n /** Webhook secret for legacy HMAC authentication. */\n webhookSecret?: string;\n /** Persist sanitized callback mode provenance before dispatch. */\n onWebhookRegistration?: (registration: {\n agent: AgentConfig;\n taskType: string;\n operationId: string;\n callbackUrl: string;\n mode: 'rfc9421' | 'hmac-sha256';\n }) => void | Promise<void>;\n /** Persist fail-closed routing provenance before a durable mutation claim can run. */\n onDurableSettlementRequired?: (operationId: string) => void | Promise<void>;\n /** Retain durable push-settlement fences for at least the callback registration lifetime. */\n externalTaskSettlementRetentionMs?: number;\n /** Fail tasks when response schema validation fails (default: true) */\n strictSchemaValidation?: boolean;\n /** Emit schema validation violations to debug logs and the console (default: true) */\n logSchemaViolations?: boolean;\n /**\n * Schema-driven validation using the bundled AdCP JSON schemas.\n * Controls outgoing request and incoming response checks independently.\n * Defaults: strict in dev/test, warn in prod. Set a mode to `off` to\n * skip the validator entirely on that side (zero overhead).\n */\n validation?: ValidationHookConfig;\n /** Filter out invalid products from get_products responses instead of rejecting the entire response (default: false) */\n filterInvalidProducts?: boolean;\n /** Global activity callback for observability */\n onActivity?: (activity: Activity) => void | Promise<void>;\n /** Transport-level diagnostics callback for outbound HTTP requests. */\n onTransportActivity?: import('../protocols').TransportActivityHandler;\n /** Governance configuration for buyer-side campaign governance */\n governance?: GovernanceConfig;\n /**\n * AdCP version this executor speaks. Selects which schema bundle\n * `validateIncomingResponse` / `validateOutgoingRequest` validate\n * against, and which `adcp_major_version` value goes on the wire.\n * Defaults to the SDK-pinned `ADCP_VERSION` when omitted.\n *\n * Plumbed from `SingleAgentClient.resolvedAdcpVersion` so the\n * client/agent's `getAdcpVersion()` value is the single source of\n * truth for both validation and wire-level major.\n */\n adcpVersion?: string;\n wireAdcpVersion?: string;\n versionEnvelope?: import('../protocols').VersionEnvelopeMode;\n /**\n * Transport-level safeguards applied to every call this executor\n * dispatches. Per-call options can override individual fields.\n */\n transport?: import('../protocols').TransportOptions;\n } = {}\n ) {\n if (\n config.externalTaskSettlementRetentionMs !== undefined &&\n (!Number.isSafeInteger(config.externalTaskSettlementRetentionMs) || config.externalTaskSettlementRetentionMs < 1)\n ) {\n throw new ConfigurationError('externalTaskSettlementRetentionMs must be a positive safe integer.');\n }\n this.responseParser = new ProtocolResponseParser();\n if (config.enableConversationStorage) {\n this.conversationStorage = new Map();\n }\n if (config.governance) {\n this.governanceMiddleware = new GovernanceMiddleware(\n config.governance,\n config.onActivity,\n config.adcpVersion,\n config.versionEnvelope,\n config.onTransportActivity\n );\n }\n const modes = resolveValidationModes(config.validation);\n this.requestValidationMode = modes.requests;\n // Legacy `strictSchemaValidation: false` flips response-side enforcement\n // to warn mode — preserve that behaviour unless `validation.responses`\n // was set explicitly.\n if (config.validation?.responses !== undefined) {\n this.responseValidationMode = config.validation.responses;\n } else if (config.strictSchemaValidation === false) {\n this.responseValidationMode = 'warn';\n } else {\n this.responseValidationMode = modes.responses;\n }\n }\n\n /**\n * Access the governance middleware for direct outcome reporting (async tasks).\n */\n getGovernanceMiddleware(): GovernanceMiddleware | undefined {\n return this.governanceMiddleware;\n }\n\n getRequestParams(taskId: string): Record<string, unknown> | undefined {\n const params = this.activeTasks.get(taskId)?.params;\n return params && typeof params === 'object' && !Array.isArray(params)\n ? (params as Record<string, unknown>)\n : undefined;\n }\n\n /**\n * Reconcile a push-delivered terminal status with the local runner task.\n * Submitted task state is already compacted after dispatch; this schedules\n * the same short final-status retention used by synchronous completions.\n *\n * @internal\n */\n async observeExternalTaskStatus(\n taskId: string,\n status: TaskStatus,\n result?: unknown,\n identity: { serverTaskId?: string; taskType?: string } = {}\n ): Promise<ExternalTaskStatusResult> {\n if (!['completed', 'failed', 'rejected', 'canceled', 'governance-denied', 'aborted'].includes(status)) {\n return { settled: false, result };\n }\n const observation: ExternalTaskSettlementObservation = { status, result, ...identity };\n const observationKey = this.externalTaskObservationKey(observation);\n if (this.closedExternalTaskSettlementTaskIds.has(taskId)) {\n const accepted = this.settledExternalTaskObservationKeys.get(taskId);\n if (accepted?.key === observationKey) {\n return {\n settled: true,\n duplicate: true,\n status: accepted.status,\n ...(accepted.error !== undefined && { error: accepted.error }),\n };\n }\n throw new Error('This task already completed durable settlement; the pushed result was not accepted.');\n }\n if (this.deferredTerminalPublicationTaskIds.has(taskId)) {\n const handler = this.externalTaskSettlementHandlers.get(taskId);\n if (handler) return this.settleExternalTaskStatus(taskId, handler, observation);\n return new Promise((resolve, reject) => {\n const pending = this.pendingExternalTaskObservations.get(taskId) ?? [];\n if (pending.length >= MAX_PENDING_EXTERNAL_TASK_OBSERVATIONS) {\n reject(new Error('Too many terminal push notifications are awaiting durable task settlement.'));\n return;\n }\n pending.push({ observation, resolve, reject });\n this.pendingExternalTaskObservations.set(taskId, pending);\n });\n }\n this.updateTaskStatus(taskId, status, result);\n return { settled: false, result };\n }\n\n /** Whether this process can safely settle or reject a durable callback for the operation. */\n hasExternalTaskSettlementRoute(taskId: string): boolean {\n return (\n this.deferredTerminalPublicationTaskIds.has(taskId) ||\n this.closedExternalTaskSettlementTaskIds.has(taskId) ||\n this.externalTaskSettlementHandlers.has(taskId)\n );\n }\n\n /**\n * Run the configured pre-send schema check against the user-facing request\n * shape. Callers invoke this on the unadapted (v3) params before any wire\n * adaptation runs, so the validator sees the same object the caller wrote.\n * Throws in strict, logs to `debugLogs` in warn, no-ops in off.\n */\n validateRequest(taskName: string, params: unknown, debugLogs?: any[]): void {\n validateOutgoingRequest(taskName, params, this.requestValidationMode, debugLogs, this.config.adcpVersion);\n }\n\n /**\n * After `adaptRequestForServerVersion` has rewritten a v3 request into v2\n * wire format, validate the adapted shape against the cached v2.5 schema\n * bundle. Always warn-only — adapter bugs shouldn't break user requests,\n * and the v3 pre-send pass already vouched for the user-facing input.\n * This pass exists to surface drift between what the adapter emits and\n * what a v2.5 server expects on the wire (primarily as CI signal via the\n * adapter-conformance test suite).\n *\n * Skips silently for tasks without a v2.5 schema or when the v2.5 bundle\n * isn't cached. Caller is responsible for gating on `serverVersion === 'v2'`\n * so v3-targeted traffic doesn't pay the validation cost.\n */\n validateAdaptedRequestAgainstV2(taskName: string, adaptedParams: unknown, debugLogs?: any[]): void {\n validateOutgoingRequest(taskName, adaptedParams, 'warn', debugLogs, 'v2.5');\n }\n\n /**\n * Generate webhook URL for protocol-level webhook support\n */\n /**\n * Build TaskResultMetadata, including the idempotency fields. The key is\n * pulled from the tracked task state so every result reports the key that\n * was actually sent (auto-generated or caller-supplied); `replayed` is\n * extracted from the response envelope when a response is available.\n */\n private buildMetadata(args: {\n taskId: string;\n taskName: string;\n agent: AgentConfig | { id: string; name: string; protocol: 'mcp' | 'a2a' };\n startTime?: number;\n responseTimeMs?: number;\n status: TaskStatus;\n clarificationRounds?: number;\n response?: any;\n inputRequest?: InputRequest;\n }): TaskResultMetadata {\n const meta: TaskResultMetadata = {\n taskId: args.taskId,\n taskName: args.taskName,\n agent: { id: args.agent.id, name: args.agent.name, protocol: args.agent.protocol },\n responseTimeMs: args.responseTimeMs ?? (args.startTime !== undefined ? Date.now() - args.startTime : 0),\n timestamp: new Date().toISOString(),\n clarificationRounds: args.clarificationRounds ?? 0,\n status: args.status,\n };\n if (args.inputRequest) meta.inputRequest = args.inputRequest;\n const key = this.activeTasks.get(args.taskId)?.idempotencyKey;\n if (key) meta.idempotency_key = key;\n if (args.response !== undefined) {\n const replayed = this.responseParser.getReplayed(args.response);\n if (replayed !== undefined) meta.replayed = replayed;\n const adcpVersion = this.responseParser.getAdcpVersion(args.response);\n if (adcpVersion) meta.adcpVersion = adcpVersion;\n const serverContextId = this.responseParser.getContextId(args.response);\n if (serverContextId) meta.contextId = serverContextId;\n const serverTaskId = this.responseParser.getTaskId(args.response);\n if (serverTaskId) meta.serverTaskId = serverTaskId;\n }\n return meta;\n }\n\n /**\n * Map a task's structured AdCP error to a typed `ADCPError` subclass when\n * the code has a dedicated class (e.g., `IDEMPOTENCY_CONFLICT` →\n * `IdempotencyConflictError`). The idempotency key is pulled from tracked\n * task state because the server intentionally omits it from error bodies\n * (it's a read-oracle).\n */\n private buildErrorInstance(\n taskId: string,\n adcpError: ReturnType<typeof extractAdcpErrorInfo>\n ): ADCPError | undefined {\n if (!adcpError) return undefined;\n const key = this.activeTasks.get(taskId)?.idempotencyKey;\n return adcpErrorToTypedError(adcpError, key);\n }\n\n private generateWebhookUrl(taskName: string, operationId: string, options?: TaskOptions): string | undefined {\n return resolveWebhookUrl(this.config.webhookUrlTemplate, this.config.agentId, taskName, operationId, options);\n }\n\n /**\n * Execute a task with an agent using PR #78 async patterns\n * Handles: working (keep SSE open), submitted (webhook), input-required (handler), completed\n */\n async executeTask<T = any>(\n agent: AgentConfig,\n taskName: string,\n params: any,\n inputHandler?: InputHandler,\n options: TaskOptions = {},\n serverVersion?: 'v2' | 'v3',\n targetCapabilities?: AdcpCapabilities,\n beforeProtocolDispatch?: BeforeProtocolDispatchHook<T>\n ): Promise<TaskResult<T>> {\n return withTaskDeadline(options, effectiveOptions =>\n this.executeTaskWithinDeadline<T>(\n agent,\n taskName,\n params,\n inputHandler,\n effectiveOptions,\n serverVersion,\n targetCapabilities,\n beforeProtocolDispatch\n )\n );\n }\n\n private async executeTaskWithinDeadline<T = any>(\n agent: AgentConfig,\n taskName: string,\n params: any,\n inputHandler?: InputHandler,\n options: TaskOptions = {},\n serverVersion?: 'v2' | 'v3',\n targetCapabilities?: AdcpCapabilities,\n beforeProtocolDispatch?: BeforeProtocolDispatchHook<T>\n ): Promise<TaskResult<T>> {\n if (serverVersion) this.lastKnownServerVersion = serverVersion;\n // Own the request graph before the first awaited activity/governance\n // boundary. This executor is internal, but direct callers and higher\n // layers may still retain the original nested objects.\n params = structuredClone(params);\n // The client-minted `taskId` is a local correlation id for tracking this\n // call's lifecycle (activeTasks map, metadata, webhook URL macros). It is\n // NOT the same thing as the A2A `taskId` that the server assigns — that\n // flows in on the response and is surfaced via metadata.serverTaskId.\n // `options.contextId` / `options.taskId` ride on the A2A message envelope\n // and are threaded straight to the protocol adapter below.\n const taskId = getTaskOperationId(options) ?? randomUUID();\n const startTime = Date.now();\n const workingTimeout = this.config.workingTimeout || 120000; // 120s max per PR #78\n\n // Auto-generate idempotency_key for mutating tasks when the caller didn't\n // supply one. The key lives on TaskState so internal retries reuse it —\n // re-generating on retry defeats the whole point of the envelope.\n // `options.skipIdempotencyAutoInject` disables this for compliance testing\n // that needs to exercise server-side missing-key behavior.\n const idempotencyKey = options.skipIdempotencyAutoInject\n ? undefined\n : resolveIdempotencyKey(taskName, params, serverVersion);\n if (idempotencyKey) attachTaskDeadlineIdempotencyKey(options, idempotencyKey);\n if (serverVersion !== 'v2' && idempotencyKey && params && typeof params === 'object' && !params.idempotency_key) {\n params = { ...params, idempotency_key: idempotencyKey };\n }\n\n // Register task in active tasks\n const taskState: TaskState = {\n taskId,\n taskName,\n params,\n status: 'pending',\n messages: [],\n startTime,\n attempt: 0,\n maxAttempts: options.maxClarifications || this.config.defaultMaxClarifications || 3,\n options,\n agent: { id: agent.id, name: agent.name, protocol: agent.protocol },\n idempotencyKey,\n };\n this.activeTasks.set(taskId, taskState);\n\n // Once the final compatibility boundary starts, an abort may race a\n // durable claim that has committed but whose hook has not returned yet.\n // In that window the boundary, not the caller signal, owns publication of\n // terminal state. The abort listener still compacts retained request data.\n let dispatchBoundaryOwnsTerminalState = false;\n\n // Compact task state as soon as cancellation fires, even if a protocol\n // adapter or caller callback never settles after receiving the signal.\n // The outer deadline race guarantees prompt rejection; this listener is\n // the matching resource-retention boundary for activeTasks.\n const taskAbortListener = options.signal\n ? () => {\n const currentStatus = this.activeTasks.get(taskId)?.status;\n if (currentStatus && !TERMINAL_TASK_STATUSES.has(currentStatus)) {\n if (dispatchBoundaryOwnsTerminalState) {\n this.compactAbandonedObserverTaskState(taskId);\n return;\n }\n const reason = options.signal?.reason;\n this.updateTaskStatus(\n taskId,\n 'aborted',\n undefined,\n reason instanceof Error ? reason.message : reason == null ? 'The operation was aborted' : String(reason)\n );\n }\n }\n : undefined;\n if (taskAbortListener) options.signal!.addEventListener('abort', taskAbortListener, { once: true });\n\n // Emit task creation event\n this.emitTaskEvent(\n {\n taskId,\n status: 'submitted',\n taskType: taskName,\n createdAt: startTime,\n updatedAt: startTime,\n },\n agent.id\n );\n\n // Start streaming connection\n const debugLogs: any[] = [];\n\n // Generate webhook URL if template is configured\n const webhookUrl = this.generateWebhookUrl(taskName, taskId, options);\n\n // Governance state (scoped outside try so catch can access)\n let governanceCheckId: string | undefined;\n let governanceResult: GovernanceCheckResult | undefined;\n let effectiveParams = params;\n let governanceAdjusted = false;\n let dispatchCommitted = false;\n let dispatchSettlement:\n | Pick<Extract<BeforeProtocolDispatchHookResult<T>, { action: 'dispatch_committed' }>, 'onResult' | 'onError'>\n | undefined;\n let dispatchSettlementStarted = false;\n\n try {\n // Emit protocol_request activity. The activity payload is the boundary\n // callers typically pipe into external observability stacks, so redact\n // the idempotency key — it's a retry-pattern oracle within the seller's\n // TTL. Full logging is opt-in via ADCP_LOG_IDEMPOTENCY_KEYS=1.\n await this.config.onActivity?.({\n type: 'protocol_request',\n operation_id: taskId,\n agent_id: agent.id,\n context_id: options.contextId,\n task_id: taskId,\n task_type: taskName,\n status: 'pending',\n payload: { params: redactIdempotencyKeyInArgs(params) },\n timestamp: new Date().toISOString(),\n });\n throwIfAborted(options.signal);\n\n // Run governance check if configured for this tool\n const governanceMiddleware = this.governanceMiddleware;\n if (governanceMiddleware) {\n const modernGovernance =\n targetCapabilities !== undefined && targetDeclaresGovernanceEnforcement(targetCapabilities, taskName);\n // Modern authorization binds the exact argument object the seller\n // receives, including protocol-owned fields and MCP webhook\n // registration. Legacy governance retains its historical application\n // payload and must not receive SDK-injected callback credentials.\n const governableParams = modernGovernance\n ? prepareProtocolToolCall(agent, params, {\n toolName: taskName,\n webhookUrl,\n webhookSecret: this.config.webhookSecret,\n serverVersion,\n adcpVersion: this.config.adcpVersion,\n wireAdcpVersion: this.config.wireAdcpVersion,\n versionEnvelope: this.config.versionEnvelope,\n }).args\n : params;\n if (await governanceMiddleware.shouldCheck(taskName, governableParams, targetCapabilities)) {\n const sdkInjectedPushConfig =\n modernGovernance &&\n agent.protocol === 'mcp' &&\n webhookUrl !== undefined &&\n this.config.webhookSecret !== undefined;\n assertGovernedPayloadHasNoCallbackCredentials(taskName, governableParams, { sdkInjectedPushConfig });\n const { result: govResult, params: adjustedParams } = await governanceMiddleware.checkProposed(\n agent,\n targetCapabilities!,\n taskName,\n governableParams,\n debugLogs,\n options.signal\n );\n throwIfAborted(options.signal);\n assertGovernedPayloadHasNoCallbackCredentials(taskName, adjustedParams, { sdkInjectedPushConfig });\n governanceAdjusted = canonicalize(adjustedParams) !== canonicalize(governableParams);\n\n // Governance always blocks on denial/unapplied conditions.\n const isBlocking = true;\n\n if (govResult.status === 'denied' && isBlocking) {\n const denied = this.buildGovernanceResult<T>(govResult, taskId, taskName, agent, startTime, debugLogs);\n this.updateTaskStatus(taskId, 'governance-denied', undefined, denied.error);\n return attachMatch(denied);\n }\n\n if (govResult.status === 'conditions' && !govResult.conditionsApplied && isBlocking) {\n const denied = this.buildGovernanceResult<T>(govResult, taskId, taskName, agent, startTime, debugLogs);\n this.updateTaskStatus(taskId, 'governance-denied', undefined, denied.error);\n return attachMatch(denied);\n }\n\n // Approved, or non-blocking mode (advisory/audit) allows execution to proceed\n governanceCheckId = govResult.checkId;\n governanceResult = govResult;\n if (governanceCheckId) {\n // Preserve the approved check identity as soon as the seller may be\n // dispatched. If the deadline fires during response processing,\n // callers can still reconcile the seller mutation against the\n // original governance decision after restart.\n attachTaskDeadlineGovernanceRecovery(options, { checkId: governanceCheckId });\n }\n effectiveParams = adjustedParams;\n }\n }\n\n // Detach the final request graph before the durable claim boundary. The\n // caller may still hold and mutate nested account/brand/targeting values;\n // validation, claim verification, the prepared wire call, and dispatch\n // must all observe one immutable-by-ownership snapshot.\n const dispatchParams = structuredClone(effectiveParams);\n\n // Create initial message (uses dispatchParams which may have governance-applied conditions)\n const initialMessage: Message = {\n id: randomUUID(),\n role: 'user',\n content: { tool: taskName, params: dispatchParams },\n timestamp: new Date().toISOString(),\n metadata: { toolName: taskName, type: 'request' },\n };\n\n // Materialize once, persist callback provenance, and dispatch this same\n // prepared object. A seller can post immediately after receiving the\n // request, so the registration write must complete before the network\n // boundary is crossed.\n const preparedCall = prepareProtocolToolCall(agent, dispatchParams, {\n toolName: taskName,\n webhookUrl,\n webhookSecret: this.config.webhookSecret,\n serverVersion,\n adcpVersion: this.config.adcpVersion,\n wireAdcpVersion: this.config.wireAdcpVersion,\n versionEnvelope: this.config.versionEnvelope,\n });\n let webhookRegistrationPersisted = false;\n if (webhookUrl && this.config.onWebhookRegistration) {\n const registration = webhookRegistrationFromPreparedCall(agent, preparedCall);\n if (registration) {\n await this.config.onWebhookRegistration({\n agent,\n taskType: taskName,\n operationId: taskId,\n ...registration,\n });\n webhookRegistrationPersisted = true;\n }\n }\n\n // This is the final awaited preflight boundary. A durable mutation claim\n // made by the hook must be followed immediately by the official protocol\n // call; callers can therefore distinguish deterministic preflight failure\n // from transport uncertainty after the commit point.\n throwIfAborted(options.signal);\n if (beforeProtocolDispatch) {\n let decision: BeforeProtocolDispatchHookResult<T>;\n dispatchBoundaryOwnsTerminalState = true;\n try {\n if (\n this.deferredTerminalPublicationTaskIds.size + this.settlementCapacityReservations.size >=\n COMPACTED_TASK_STATE_LIMIT\n ) {\n throw new Error('The durable task-settlement capacity is exhausted; no mutation claim was attempted.');\n }\n this.settlementCapacityReservations.add(taskId);\n if (webhookRegistrationPersisted) {\n await this.config.onDurableSettlementRequired?.(taskId);\n throwIfAborted(options.signal);\n }\n decision = await beforeProtocolDispatch(dispatchParams, {\n governanceAdjusted,\n publishSettledTaskStatus: (status, data, error) =>\n this.publishSettledTaskStatus(taskId, status, data, error),\n registerExternalTaskSettlement: handler => this.registerExternalTaskSettlement(taskId, handler),\n });\n if (decision.action === 'dispatch_committed') {\n this.deferredTerminalPublicationTaskIds.add(taskId);\n this.retainExternalTaskSettlementState(taskId);\n }\n } catch (error) {\n throw new BeforeProtocolDispatchHookError(error);\n } finally {\n this.settlementCapacityReservations.delete(taskId);\n }\n if (decision.action === 'return') {\n const earlyResult = decision.result;\n if (\n ['completed', 'failed', 'rejected', 'canceled', 'governance-denied', 'aborted'].includes(earlyResult.status)\n ) {\n this.updateTaskStatus(taskId, earlyResult.status as TaskStatus, earlyResult.data, earlyResult.error);\n }\n return attachMatch(earlyResult);\n }\n dispatchCommitted = true;\n dispatchSettlement = decision;\n }\n\n // A claim that completes after the caller deadline must be fenced, not\n // turned into a hidden seller mutation after the caller has already\n // received a timeout and may have replanned. The catch path invokes the\n // committed hook's onError settlement before any protocol call begins.\n throwIfAborted(options.signal);\n\n // Once a durable claim commits, the caller-facing signal may already be\n // aborted after seller dispatch begins. Never let that abandoned\n // observer prevent response parsing or durable settlement.\n const postDispatchOptions = dispatchCommitted ? { ...options, signal: undefined } : options;\n\n // Send initial request and get streaming response with webhook URL.\n // Pass the caller's A2A session ids (contextId for conversation binding,\n // taskId for resuming a non-terminal server-side task). The adapter\n // drops these on the wire for MCP (no session concept there).\n const callOptions = {\n debugLogs,\n webhookUrl,\n webhookSecret: this.config.webhookSecret,\n serverVersion,\n session: { contextId: options.contextId, taskId: options.taskId },\n adcpVersion: this.config.adcpVersion,\n ...(this.config.wireAdcpVersion !== undefined && { wireAdcpVersion: this.config.wireAdcpVersion }),\n ...(this.config.versionEnvelope !== undefined && { versionEnvelope: this.config.versionEnvelope }),\n transport: options.transport ?? this.config.transport,\n // Once dispatch begins for a live committed claim, post-call handling\n // owns durable settlement even if the caller's deadline fires later.\n signal: postDispatchOptions.signal,\n onTransportActivity: this.config.onTransportActivity,\n transportActivityContext: {\n operationId: taskId,\n taskId: options.taskId ?? taskId,\n contextId: options.contextId,\n idempotencyKey,\n },\n };\n const response = await withPreparedProtocolToolCall(\n { agent, toolName: taskName, args: dispatchParams, preparedCall },\n () => ProtocolClient.callTool(agent, taskName, dispatchParams, callOptions)\n );\n throwIfAborted(postDispatchOptions.signal);\n\n // Emit protocol_response activity\n const respStatus = this.responseParser.getStatus(response) as string | undefined;\n await this.config.onActivity?.({\n type: 'protocol_response',\n operation_id: taskId,\n agent_id: agent.id,\n context_id: options.contextId,\n task_id: taskId,\n task_type: taskName,\n status: respStatus,\n payload: response,\n timestamp: new Date().toISOString(),\n });\n throwIfAborted(postDispatchOptions.signal);\n\n // Add initial response message\n const responseMessage: Message = {\n id: randomUUID(),\n role: 'agent',\n content: response,\n timestamp: new Date().toISOString(),\n metadata: { toolName: taskName, type: 'response' },\n };\n\n const messages = [initialMessage, responseMessage];\n\n // Handle response based on status\n let result = await this.handleAsyncResponse<T>(\n agent,\n taskId,\n taskName,\n dispatchParams,\n response,\n messages,\n inputHandler,\n postDispatchOptions,\n debugLogs,\n startTime,\n dispatchCommitted\n );\n throwIfAborted(postDispatchOptions.signal);\n\n // Attach governance check result to the task result\n if (governanceResult) {\n result.governance = governanceResult;\n }\n\n if (dispatchSettlement?.onResult) {\n dispatchSettlementStarted = true;\n try {\n result = await dispatchSettlement.onResult(attachMatch(result));\n } catch (error) {\n // A committed mutation is not terminal from the SDK's perspective\n // until its durable settlement succeeds. Publish only the failed\n // local coordinator state here; never leak the seller's earlier\n // completed response through task events or retained task state.\n this.closeExternalTaskSettlement(taskId, error);\n this.updateTaskStatus(taskId, 'failed', undefined, error instanceof Error ? error.message : String(error));\n throw new AfterProtocolDispatchHookError(error);\n }\n }\n\n // Report governance only after a committed compatibility mutation has\n // durably settled. A seller terminal response is not authoritative if\n // the coordinator subsequently fails to persist it.\n // For async tasks (submitted/working), outcome reporting is deferred —\n // the caller reports via client.reportGovernanceOutcome() when the\n // task resolves through polling or webhooks.\n if (governanceCheckId && this.governanceMiddleware) {\n const govCtx = governanceResult?.governanceContext;\n if (result.status === 'completed' && govCtx) {\n const outcomeIdempotencyKey = this.governanceMiddleware.getOutcomeIdempotencyKey(\n governanceCheckId,\n 'completed'\n );\n attachTaskDeadlineGovernanceRecovery(options, {\n checkId: governanceCheckId,\n outcome: 'completed',\n outcomeIdempotencyKey,\n });\n result.governanceOutcome = await this.governanceMiddleware.reportOutcome(\n governanceCheckId,\n 'completed',\n result.data as Record<string, unknown> | undefined,\n undefined,\n debugLogs,\n govCtx,\n postDispatchOptions.signal,\n outcomeIdempotencyKey\n );\n throwIfAborted(postDispatchOptions.signal);\n if (!result.governanceOutcome) {\n result.governanceOutcomeError = 'Outcome reporting to governance agent failed';\n }\n } else if (result.error && govCtx) {\n const outcomeIdempotencyKey = this.governanceMiddleware.getOutcomeIdempotencyKey(governanceCheckId, 'failed');\n attachTaskDeadlineGovernanceRecovery(options, {\n checkId: governanceCheckId,\n outcome: 'failed',\n outcomeIdempotencyKey,\n });\n result.governanceOutcome = await this.governanceMiddleware.reportOutcome(\n governanceCheckId,\n 'failed',\n undefined,\n { message: result.error },\n debugLogs,\n govCtx,\n postDispatchOptions.signal,\n outcomeIdempotencyKey\n );\n throwIfAborted(postDispatchOptions.signal);\n if (!result.governanceOutcome) {\n result.governanceOutcomeError = 'Outcome reporting to governance agent failed';\n }\n } else if (result.status === 'submitted' || result.status === 'working') {\n // Attach the check ID so callers can report outcome after async resolution\n result.governance = { ...(result.governance ?? {}), checkId: governanceCheckId } as GovernanceCheckResult;\n }\n }\n\n if (dispatchCommitted) {\n result = this.attachSettledContinuationTaskStatus(taskId, result);\n if (TERMINAL_TASK_STATUSES.has(result.status as TaskStatus)) {\n this.publishSettledTaskStatus(taskId, result.status as TaskStatus, result.data, result.error);\n }\n }\n\n if (\n ['completed', 'failed', 'rejected', 'canceled', 'governance-denied', 'aborted'].includes(result.status) &&\n this.activeTasks.get(taskId)?.status !== result.status\n ) {\n this.updateTaskStatus(taskId, result.status as TaskStatus, result.data, result.error);\n }\n return attachMatch(result);\n } catch (error) {\n if (error instanceof BeforeProtocolDispatchHookError) {\n // Hook failures happen before seller dispatch. Preserve the original\n // exception for the compatibility coordinator, but terminalize the\n // local task so repeated invalid redemption attempts cannot retain\n // full request payloads and options in activeTasks.\n this.updateTaskStatus(taskId, 'failed', undefined, error.message);\n throw error;\n }\n if (error instanceof AfterProtocolDispatchHookError) throw error;\n if (dispatchCommitted && dispatchSettlement?.onError && !dispatchSettlementStarted) {\n try {\n await dispatchSettlement.onError(error);\n } catch (settlementError) {\n this.closeExternalTaskSettlement(taskId, settlementError);\n this.updateTaskStatus(\n taskId,\n 'failed',\n undefined,\n settlementError instanceof Error ? settlementError.message : String(settlementError)\n );\n throw new AfterProtocolDispatchHookError(settlementError);\n }\n this.closeExternalTaskSettlement(taskId, error);\n }\n if (isAbortOrTimeoutError(error)) {\n if (idempotencyKey && error && typeof error === 'object') {\n (error as Error & { idempotency_key?: string; idempotencyKey?: string }).idempotency_key = idempotencyKey;\n (error as Error & { idempotency_key?: string; idempotencyKey?: string }).idempotencyKey = idempotencyKey;\n }\n const currentStatus = this.activeTasks.get(taskId)?.status;\n if (currentStatus && !TERMINAL_TASK_STATUSES.has(currentStatus)) {\n this.updateTaskStatus(taskId, 'aborted', undefined, error instanceof Error ? error.message : String(error));\n }\n throw error;\n }\n\n // Report failed outcome on error\n if (governanceCheckId && this.governanceMiddleware && governanceResult?.governanceContext) {\n const outcomeIdempotencyKey = this.governanceMiddleware.getOutcomeIdempotencyKey(governanceCheckId, 'failed');\n attachTaskDeadlineGovernanceRecovery(options, {\n checkId: governanceCheckId,\n outcome: 'failed',\n outcomeIdempotencyKey,\n });\n await this.governanceMiddleware.reportOutcome(\n governanceCheckId,\n 'failed',\n undefined,\n { message: (error as Error).message },\n debugLogs,\n governanceResult.governanceContext,\n options.signal,\n outcomeIdempotencyKey\n );\n }\n const failed = this.createErrorResult<T>(taskId, agent, error, debugLogs, startTime);\n this.updateTaskStatus(taskId, 'failed', undefined, failed.error);\n return attachMatch(failed);\n } finally {\n if (taskAbortListener) options.signal!.removeEventListener('abort', taskAbortListener);\n }\n }\n\n /**\n * Handle agent response based on ADCP status (PR #78)\n */\n private buildGovernanceResult<T>(\n govResult: GovernanceCheckResult,\n taskId: string,\n taskName: string,\n agent: AgentConfig,\n startTime: number,\n debugLogs: any[]\n ): TaskResult<T> {\n return {\n success: false,\n status: 'governance-denied',\n error: govResult.explanation || 'Governance governance-denied',\n governance: govResult,\n metadata: this.buildMetadata({ taskId, taskName, agent, startTime, status: 'governance-denied' }),\n conversation: [],\n debug_logs: debugLogs,\n };\n }\n\n private async handleAsyncResponse<T>(\n agent: AgentConfig,\n taskId: string,\n taskName: string,\n params: any,\n response: any,\n messages: Message[],\n inputHandler?: InputHandler,\n options: TaskOptions = {},\n debugLogs: any[] = [],\n startTime: number = Date.now(),\n deferTerminalTaskStatus = false\n ): Promise<TaskResult<T>> {\n const status = this.responseParser.getStatus(response) as ADCPStatus;\n\n switch (status) {\n case ADCP_STATUS.COMPLETED:\n // Task completed immediately\n const completedData = this.extractResponseData(response, debugLogs, taskName);\n // Ordinary calls retain the historical behavior of publishing seller\n // completion before optional governance postflight work. A committed\n // compatibility mutation defers this until durable settlement.\n if (!deferTerminalTaskStatus) this.updateTaskStatus(taskId, 'completed', completedData);\n\n const operationSuccess = this.isOperationSuccess(completedData, taskName);\n\n // Validate response against AdCP schema - validate extracted data, not protocol wrapper\n const validationResult = this.validateResponseSchema(completedData, taskName, debugLogs);\n\n // In strict mode, schema validation failures cause task to fail\n const finalSuccess = operationSuccess && validationResult.valid;\n const finalError = !finalSuccess\n ? validationResult.errors.length > 0\n ? `Schema validation failed: ${validationResult.errors.join('; ')}`\n : this.extractOperationError(completedData)\n : undefined;\n\n if (finalSuccess) {\n return {\n success: true as const,\n status: 'completed' as const,\n data: completedData,\n metadata: this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'completed',\n response,\n }),\n conversation: messages,\n debug_logs: debugLogs,\n };\n }\n const completedAdcpError = extractAdcpErrorInfo(completedData);\n return {\n success: false as const,\n status: 'failed' as const,\n data: completedData,\n error: finalError ?? 'Unknown error',\n adcpError: completedAdcpError,\n errorInstance: this.buildErrorInstance(taskId, completedAdcpError),\n correlationId: extractCorrelationId(completedData),\n metadata: this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'failed',\n response,\n }),\n conversation: messages,\n debug_logs: debugLogs,\n };\n\n case ADCP_STATUS.WORKING:\n // Server is processing - keep connection open for up to 120s\n return this.waitForWorkingCompletion<T>(\n agent,\n taskId,\n taskName,\n params,\n response,\n messages,\n inputHandler,\n options,\n debugLogs,\n startTime\n );\n\n case ADCP_STATUS.SUBMITTED:\n // Long-running task - set up webhook\n return this.setupSubmittedTask<T>(\n agent,\n taskId,\n taskName,\n response,\n messages,\n options,\n debugLogs,\n startTime,\n deferTerminalTaskStatus\n );\n\n case ADCP_STATUS.INPUT_REQUIRED:\n // Server needs input - handler is mandatory\n return this.handleInputRequired<T>(\n agent,\n taskId,\n taskName,\n params,\n response,\n messages,\n inputHandler,\n options,\n debugLogs,\n startTime,\n deferTerminalTaskStatus\n );\n\n case ADCP_STATUS.FAILED:\n case ADCP_STATUS.REJECTED:\n case ADCP_STATUS.CANCELED: {\n const failedData = this.extractResponseData(response, debugLogs, taskName);\n // Raw/in-process protocol clients may wrap the tool payload under\n // `data` while carrying the task lifecycle status at the top level.\n // The generic unwrapper intentionally preserves that wrapper, so\n // select its nested payload here before extracting business errors.\n const failedPayload =\n response?.structuredContent === undefined &&\n response?.content === undefined &&\n response?.result === undefined &&\n response?.data != null &&\n typeof response.data === 'object'\n ? response.data\n : failedData;\n const adcpErrorInfo = extractAdcpErrorInfo(failedPayload);\n const hasStructuredError = !!adcpErrorInfo;\n // Preserve failedData whenever the server returned a structured\n // payload — not just when extractAdcpErrorInfo recognizes an\n // `adcp_error`/`errors` envelope. Tool-level error shapes like\n // `comply_test_controller`'s `{ success: false, error: 'UNKNOWN_SCENARIO' }`\n // don't match that extractor but still carry the information\n // storyboard validators read (`success`, `error_code`, etc.).\n // Only drop `data` when there's literally no structured payload —\n // i.e. falsy or an empty object.\n const hasStructuredPayload =\n failedPayload != null &&\n typeof failedPayload === 'object' &&\n (Array.isArray(failedPayload) || Object.keys(failedPayload).length > 0);\n const structuredMessage = hasStructuredPayload ? this.extractOperationError(failedPayload) : undefined;\n const failedError =\n structuredMessage && structuredMessage !== 'Operation failed'\n ? structuredMessage\n : response.error || response.message || structuredMessage || `Task ${status}`;\n return {\n success: false as const,\n status: 'failed' as const,\n data: hasStructuredError || hasStructuredPayload ? failedPayload : undefined,\n error: typeof failedError === 'string' ? failedError : `Task ${status}`,\n adcpError: adcpErrorInfo,\n errorInstance: this.buildErrorInstance(taskId, adcpErrorInfo),\n correlationId: extractCorrelationId(failedPayload),\n metadata: this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'failed',\n response,\n }),\n conversation: messages,\n debug_logs: debugLogs,\n };\n }\n\n default:\n // Unknown status - treat as completed if we have data\n const defaultData = this.extractResponseData(response, debugLogs, taskName);\n if (\n defaultData &&\n (defaultData !== response || response.structuredContent || response.result || response.data)\n ) {\n const defaultSuccess = this.isOperationSuccess(defaultData, taskName);\n\n // Validate response against AdCP schema - validate extracted data, not protocol wrapper\n const defaultValidation = this.validateResponseSchema(defaultData, taskName, debugLogs);\n\n // In strict mode, schema validation failures cause task to fail\n const defaultFinalSuccess = defaultSuccess && defaultValidation.valid;\n const defaultFinalError = !defaultFinalSuccess\n ? defaultValidation.errors.length > 0\n ? `Schema validation failed: ${defaultValidation.errors.join('; ')}`\n : this.extractOperationError(defaultData)\n : undefined;\n\n if (defaultFinalSuccess) {\n return {\n success: true as const,\n status: 'completed' as const,\n data: defaultData,\n metadata: this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'completed',\n response,\n }),\n conversation: messages,\n debug_logs: debugLogs,\n };\n }\n const defaultAdcpError = extractAdcpErrorInfo(defaultData);\n return {\n success: false as const,\n status: 'failed' as const,\n data: defaultData,\n error: defaultFinalError!,\n adcpError: defaultAdcpError,\n errorInstance: this.buildErrorInstance(taskId, defaultAdcpError),\n correlationId: extractCorrelationId(defaultData),\n metadata: this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'failed',\n response,\n }),\n conversation: messages,\n debug_logs: debugLogs,\n };\n } else {\n throw new Error(`Unknown status: ${status || 'undefined'}`);\n }\n }\n }\n\n /**\n * Extract response data from different protocol formats\n *\n * @internal Exposed for testing purposes\n */\n public extractResponseData(response: any, debugLogs?: any[], toolName?: string): any {\n // MCP error responses (isError: true) flow through here — the response unwrapper\n // extracts structured data (adcp_error, context, ext) from structuredContent or text\n\n // Use the shared response unwrapper utility\n // This handles MCP structuredContent, A2A artifacts (including HITL multi-artifact responses),\n // and various edge cases consistently\n try {\n // Log what type of response we're processing BEFORE unwrapping\n // This ensures we have debug visibility even if unwrapping fails\n if (response?.structuredContent) {\n this.logDebug(debugLogs, 'info', 'Processing MCP structuredContent response');\n } else if (response?.result?.artifacts) {\n const artifacts = response.result.artifacts;\n if (artifacts.length === 0) {\n this.logDebug(debugLogs, 'info', 'Processing A2A response with empty artifacts array');\n } else {\n // Calculate total part count across all artifacts\n const totalParts = artifacts.reduce((sum: number, artifact: any) => {\n return sum + (artifact.parts?.length || 0);\n }, 0);\n\n // Extract canonical DataPart keys for debugging.\n const latestDataPart = getLatestA2ADataPartFromResponse(response);\n const dataKeys = latestDataPart?.data ? Object.keys(latestDataPart.data) : [];\n\n this.logDebug(debugLogs, 'info', 'Processing A2A artifact structure', {\n artifactCount: artifacts.length,\n partCount: totalParts,\n extractedFrom: artifacts.length > 1 ? 'multi-artifact (HITL)' : 'single-artifact',\n dataKeys,\n });\n }\n } else if (response?.data) {\n this.logDebug(debugLogs, 'info', 'Processing response.data field');\n } else {\n this.logDebug(debugLogs, 'info', 'Processing response without standard structure', {\n responseKeys: Object.keys(response || {}),\n });\n }\n\n // Now unwrap the response\n const unwrapped = unwrapProtocolResponse(response, toolName, undefined, {\n filterInvalidProducts: this.config.filterInvalidProducts,\n responseAdcpVersion: this.effectiveResponseAdcpVersion(),\n });\n\n // Log successful extraction with result details\n if (response?.structuredContent) {\n this.logDebug(debugLogs, 'info', 'Successfully extracted MCP data', {\n dataKeys: Object.keys(unwrapped || {}),\n });\n } else if (response?.result?.artifacts && response.result.artifacts.length > 0) {\n this.logDebug(debugLogs, 'info', 'Successfully extracted A2A data', {\n dataKeys: Object.keys(unwrapped || {}),\n });\n }\n\n return unwrapped;\n } catch (error) {\n this.logDebug(debugLogs, 'warning', 'Response unwrapper failed', {\n error: error instanceof Error ? error.message : String(error),\n toolName,\n responseKeys: Object.keys(response || {}),\n });\n\n // If toolName was provided, schema validation may have caused the failure.\n // Retry without toolName to extract the payload without schema checks.\n if (toolName) {\n try {\n return unwrapProtocolResponse(response);\n } catch {\n // Unwrapping itself failed — fall through to raw response\n }\n }\n\n return response;\n }\n }\n\n /**\n * Check if extracted response data represents a successful operation.\n * Handles singular `error`, plural `errors` (AdCP schema), and `success: false`.\n */\n private isOperationSuccess(data: any, taskName?: string): boolean {\n return isAdcpOperationSuccess(data, taskName, this.effectiveResponseAdcpVersion());\n }\n\n /**\n * Extract a human-readable error message from response data.\n * Handles singular `error`, plural `errors` array, and `message` field.\n */\n private extractOperationError(data: any): string {\n if (data?.adcp_error) {\n const ae = data.adcp_error;\n return ae.message ? `${ae.code}: ${ae.message}` : ae.code;\n }\n const pluralError = Array.isArray(data?.errors)\n ? data.errors\n .map((error: any) => error?.message || error?.code)\n .filter((value: unknown): value is string => typeof value === 'string' && value.length > 0)\n .join('; ')\n : undefined;\n return (\n data?.error ||\n pluralError ||\n data?.error_detail ||\n data?.reason ||\n data?.rejection_reason ||\n data?.message ||\n 'Operation failed'\n );\n }\n\n /**\n * Helper to add debug logs safely\n */\n private logDebug(debugLogs: any[] | undefined, type: string, message: string, details?: any) {\n if (debugLogs && Array.isArray(debugLogs)) {\n debugLogs.push({\n type,\n message,\n timestamp: new Date().toISOString(),\n details,\n });\n }\n }\n\n /**\n * Handle 'working' status - return as valid intermediate state\n */\n private async waitForWorkingCompletion<T>(\n agent: AgentConfig,\n taskId: string,\n taskName: string,\n params: any,\n initialResponse: any,\n messages: Message[],\n inputHandler?: InputHandler,\n options: TaskOptions = {},\n debugLogs: any[] = [],\n startTime: number = Date.now()\n ): Promise<TaskResult<T>> {\n // Extract any data that came with the working response\n const partialData = this.extractResponseData(initialResponse, debugLogs, taskName);\n const metadata = this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'working',\n response: initialResponse,\n });\n this.compactIntermediateTaskState(taskId, 'working');\n\n // Return working status immediately - this is a valid intermediate state\n // Callers can use the taskId to poll for completion or set up webhooks\n return {\n success: true, // The task is progressing, not failed\n status: 'working',\n data: partialData,\n metadata,\n conversation: messages,\n debug_logs: debugLogs,\n };\n }\n\n /**\n * Set up submitted task with webhook\n */\n private async setupSubmittedTask<T>(\n agent: AgentConfig,\n taskId: string,\n taskName: string,\n response: any,\n messages: Message[],\n options: TaskOptions = {},\n debugLogs: any[] = [],\n startTime: number = Date.now(),\n deferTerminalTaskStatus = false\n ): Promise<TaskResult<T>> {\n // Extract any data that came with the submitted response\n const partialData = this.extractResponseData(response, debugLogs, taskName);\n\n let webhookUrl = response.webhookUrl;\n\n // If no webhook URL provided by server, generate one. The webhook URL\n // macro path uses the local `taskId` (the runner-side correlation id\n // that doubles as the `{operation_id}` macro value), not the server\n // handle — webhook URLs identify the buyer-side request, not the\n // seller-side task.\n if (!webhookUrl && this.config.webhookManager) {\n webhookUrl = this.config.webhookManager.generateUrl(taskId);\n await this.config.webhookManager.registerWebhook(agent, taskId, webhookUrl);\n }\n\n // Polling and the buyer-facing `SubmittedContinuation.taskId` use the\n // SERVER-assigned task handle, not the runner's local UUID. The local\n // UUID is the `activeTasks` map key and the `{operation_id}` webhook\n // macro value — it never reaches the seller. The server handle comes\n // from `response.task_id` / `response.data.task_id` (AdCP submitted-arm\n // wire fields) or, for A2A responses, the same handle surfaced via\n // metadata (`adcp_task_id` / `serverTaskId`) before falling back to the\n // transport `result.id` / `taskId`. `responseParser.getTaskId` walks these\n // shapes.\n //\n // When the seller violated the spec and didn't include a task handle\n // we fall back to the local UUID so the buyer at least gets a\n // non-undefined `taskId` field. The polling cycle won't be able to\n // locate the work in this state — log an advisory so operators\n // grepping debug logs can pinpoint the seller-side spec violation.\n const extractedServerTaskId = this.responseParser.getTaskId(response);\n const serverTaskId = extractedServerTaskId ?? taskId;\n // Snapshot only what continuations need. Referencing `options.transport`\n // inside either closure would retain the entire per-call options object,\n // including unrelated adopter metadata, for as long as the continuation\n // remains reachable.\n const pollingTransport = options.transport;\n if (!extractedServerTaskId) {\n debugLogs.push({\n type: 'warning',\n message:\n 'Submitted-arm response omitted task_id (spec violation). Polling will use the runner-side ' +\n 'correlation id as a fallback; the seller will not recognize it. ' +\n 'Expected: response.task_id / response.data.task_id (AdCP), A2A metadata.serverTaskId, ' +\n 'A2A metadata.adcp_task_id, or result.id with kind === \"task\" (A2A wrapped).',\n timestamp: new Date().toISOString(),\n taskName,\n runnerTaskId: taskId,\n });\n }\n\n const submitted: SubmittedContinuation<T> = {\n taskId: serverTaskId,\n webhookUrl,\n track: async (transport?: import('../protocols').TransportOptions) => {\n const task = await this.getTaskStatus(agent, serverTaskId, transport ?? pollingTransport);\n if (!deferTerminalTaskStatus && ['completed', 'failed', 'rejected', 'canceled'].includes(task.status)) {\n this.updateTaskStatus(taskId, task.status as TaskStatus, task.result, task.error);\n }\n return task;\n },\n waitForCompletion: async (pollInterval = 60000, signal?: AbortSignal) => {\n const completed = await this.pollTaskCompletion<T>(agent, serverTaskId, pollInterval, pollingTransport, signal);\n // `pollTaskCompletion` also returns paused input-required/auth-required\n // states. Preserve that status so callers can resume the seller task;\n // only genuinely terminal statuses trigger delayed state eviction.\n if (!deferTerminalTaskStatus || !TERMINAL_TASK_STATUSES.has(completed.status as TaskStatus)) {\n this.updateTaskStatus(taskId, completed.status as TaskStatus, completed.data, completed.error);\n }\n return completed;\n },\n };\n\n const metadata = this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'submitted',\n response,\n });\n this.compactIntermediateTaskState(taskId, 'submitted');\n\n return {\n success: true, // The task is progressing, not failed\n status: 'submitted',\n submitted,\n data: partialData,\n metadata,\n conversation: messages,\n debug_logs: debugLogs,\n };\n }\n\n /**\n * A committed compatibility hook may replace resumable continuations with\n * wrappers that validate and durably persist their terminal result. Attach\n * local task publication only after those final wrappers return.\n */\n private attachSettledContinuationTaskStatus<T>(taskId: string, result: TaskResult<T>): TaskResult<T> {\n const publish = (status: TaskStatus, data?: unknown, error?: string) => {\n this.publishSettledTaskStatus(taskId, status, data, error);\n };\n\n if (result.submitted) {\n const submitted = result.submitted;\n result.submitted = {\n ...submitted,\n track: async transport => {\n const task = await submitted.track(transport);\n publish(task.status as TaskStatus, task.result, task.error);\n return task;\n },\n waitForCompletion: async (pollInterval, signal) => {\n const completion = this.attachSettledContinuationTaskStatus(\n taskId,\n await submitted.waitForCompletion(pollInterval, signal)\n );\n publish(completion.status as TaskStatus, completion.data, completion.error);\n return completion;\n },\n };\n }\n\n if (result.deferred) {\n const deferred = result.deferred;\n result.deferred = {\n ...deferred,\n resume: async input => {\n const completion = this.attachSettledContinuationTaskStatus(taskId, await deferred.resume(input));\n publish(completion.status as TaskStatus, completion.data, completion.error);\n return completion;\n },\n };\n }\n\n return result;\n }\n\n private publishSettledTaskStatus(\n taskId: string,\n status: TaskStatus,\n data?: unknown,\n error?: string,\n fromExternalObservation = false\n ): void {\n if (!TERMINAL_TASK_STATUSES.has(status)) return;\n const task = this.activeTasks.get(taskId);\n if (!task) return;\n if (!fromExternalObservation) {\n this.closeExternalTaskSettlement(\n taskId,\n new Error('The task settled through its direct response; a racing pushed result was not accepted.')\n );\n }\n if (task.status !== status) this.updateTaskStatus(taskId, status, data, error);\n }\n\n private rejectPendingExternalTaskObservations(taskId: string, error: unknown): void {\n const pending = this.pendingExternalTaskObservations.get(taskId);\n this.pendingExternalTaskObservations.delete(taskId);\n for (const waiter of pending ?? []) waiter.reject(error);\n }\n\n private closeExternalTaskSettlement(taskId: string, error: unknown): void {\n this.externalTaskSettlementHandlers.delete(taskId);\n this.externalTaskSettlementInFlight.delete(taskId);\n this.closedExternalTaskSettlementTaskIds.add(taskId);\n this.rejectPendingExternalTaskObservations(taskId, error);\n }\n\n private clearExternalTaskSettlementState(taskId: string): void {\n this.deferredTerminalPublicationTaskIds.delete(taskId);\n this.closedExternalTaskSettlementTaskIds.delete(taskId);\n this.externalTaskSettlementHandlers.delete(taskId);\n this.externalTaskSettlementInFlight.delete(taskId);\n this.settledExternalTaskObservationKeys.delete(taskId);\n this.externalTaskSettlementExpiry.delete(taskId);\n this.rejectPendingExternalTaskObservations(\n taskId,\n new Error('The durable push-settlement retention window expired before the observation was accepted.')\n );\n }\n\n private retainExternalTaskSettlementState(taskId: string): void {\n const retentionMs = this.config.externalTaskSettlementRetentionMs ?? DEFAULT_EXTERNAL_TASK_SETTLEMENT_RETENTION_MS;\n const expiry = Date.now() + retentionMs;\n if ((this.externalTaskSettlementExpiry.get(taskId) ?? 0) >= expiry) return;\n this.externalTaskSettlementExpiry.set(taskId, expiry);\n const expire = () => {\n if (this.externalTaskSettlementExpiry.get(taskId) !== expiry) return;\n const remaining = expiry - Date.now();\n if (remaining > 0) {\n const timer = setTimeout(expire, Math.min(remaining, MAX_TIMER_DELAY_MS));\n timer.unref?.();\n return;\n }\n this.clearExternalTaskSettlementState(taskId);\n };\n const timer = setTimeout(expire, Math.min(retentionMs, MAX_TIMER_DELAY_MS));\n timer.unref?.();\n }\n\n /** Release short-lived task inspection state without dropping a live durable push fence. */\n private cleanupTerminalTaskInspectionState(taskId: string): void {\n this.activeTasks.delete(taskId);\n this.compactedTaskIds.delete(taskId);\n if (\n this.deferredTerminalPublicationTaskIds.has(taskId) ||\n this.closedExternalTaskSettlementTaskIds.has(taskId) ||\n this.externalTaskSettlementHandlers.has(taskId)\n ) {\n if (this.externalTaskSettlementExpiry.has(taskId)) return;\n }\n this.clearExternalTaskSettlementState(taskId);\n }\n\n private registerExternalTaskSettlement(taskId: string, handler: ExternalTaskSettlementHandler): void {\n this.externalTaskSettlementHandlers.set(taskId, handler);\n const pending = this.pendingExternalTaskObservations.get(taskId);\n if (!pending) return;\n this.pendingExternalTaskObservations.delete(taskId);\n for (const waiter of pending) {\n void this.settleExternalTaskStatus(taskId, handler, waiter.observation).then(waiter.resolve, waiter.reject);\n }\n }\n\n private externalTaskObservationKey(observation: ExternalTaskSettlementObservation): string {\n return createHash('sha256')\n .update(\n canonicalize({\n status: observation.status,\n serverTaskId: observation.serverTaskId ?? null,\n taskType: observation.taskType ?? null,\n result: observation.result ?? null,\n })\n )\n .digest('base64url');\n }\n\n private async settleExternalTaskStatus(\n taskId: string,\n handler: ExternalTaskSettlementHandler,\n observation: ExternalTaskSettlementObservation\n ): Promise<ExternalTaskStatusResult> {\n const observationKey = this.externalTaskObservationKey(observation);\n const existing = this.externalTaskSettlementInFlight.get(taskId);\n if (existing) {\n if (existing.waiterCount >= MAX_PENDING_EXTERNAL_TASK_OBSERVATIONS) {\n throw new Error('Too many terminal push notifications are undergoing durable task settlement.');\n }\n existing.waiterCount += 1;\n try {\n const accepted = await existing.settlement;\n if (existing.observationKey !== observationKey) {\n throw new Error('This task already completed durable settlement; the pushed result was not accepted.');\n }\n return { ...accepted, duplicate: true };\n } finally {\n existing.waiterCount -= 1;\n }\n }\n const settlement = (async () => {\n const settled = await handler(observation);\n const settledStatus = settled.status as TaskStatus;\n if (this.closedExternalTaskSettlementTaskIds.has(taskId)) {\n throw new Error('The task settled through its direct response; the racing pushed result was not accepted.');\n }\n if (this.settledExternalTaskObservationKeys.has(taskId)) {\n throw new Error('This task already completed durable settlement; the pushed result was not accepted.');\n }\n this.publishSettledTaskStatus(taskId, settledStatus, settled.data, settled.error, true);\n this.settledExternalTaskObservationKeys.set(taskId, {\n key: observationKey,\n status: settledStatus,\n ...(settled.error !== undefined && {\n error: settled.error.slice(0, MAX_RETAINED_EXTERNAL_TASK_ERROR_CHARS),\n }),\n });\n this.closeExternalTaskSettlement(\n taskId,\n new Error('The task already completed durable external settlement; a later pushed result was not accepted.')\n );\n return {\n settled: true,\n result: settled.data,\n status: settled.status as TaskStatus,\n ...(settled.error !== undefined && { error: settled.error }),\n };\n })();\n const inFlight = { observationKey, settlement, waiterCount: 1 };\n this.externalTaskSettlementInFlight.set(taskId, inFlight);\n try {\n return await settlement;\n } finally {\n if (this.externalTaskSettlementInFlight.get(taskId) === inFlight) {\n this.externalTaskSettlementInFlight.delete(taskId);\n }\n }\n }\n\n /** Release abandoned caller data without publishing a premature terminal state. */\n private compactAbandonedObserverTaskState(taskId: string): void {\n const task = this.activeTasks.get(taskId);\n if (!task) return;\n task.params = undefined;\n task.messages = [];\n task.options = {};\n delete task.pendingInput;\n }\n\n /**\n * A working/submitted response carries everything needed to poll externally.\n * Keeping the original request in activeTasks after dispatch would pin\n * inline assets, webhook credentials, conversation payloads, and per-call\n * options for an unbounded amount of time while the seller works. Retain\n * only lifecycle metadata and the separately tracked idempotency key.\n */\n private compactIntermediateTaskState(\n taskId: string,\n status: 'working' | 'submitted' | 'input-required' | 'auth-required' | 'deferred'\n ): void {\n const task = this.activeTasks.get(taskId);\n if (!task) return;\n task.status = status;\n task.params = undefined;\n task.messages = [];\n task.options = {};\n delete task.pendingInput;\n this.compactedTaskIds.delete(taskId);\n this.compactedTaskIds.set(taskId, true);\n while (this.compactedTaskIds.size > COMPACTED_TASK_STATE_LIMIT) {\n const oldest = [...this.compactedTaskIds.keys()].find(\n candidate =>\n !this.deferredTerminalPublicationTaskIds.has(candidate) &&\n !this.externalTaskSettlementHandlers.has(candidate) &&\n !this.externalTaskSettlementInFlight.has(candidate)\n );\n if (oldest === undefined) break;\n this.compactedTaskIds.delete(oldest);\n this.activeTasks.delete(oldest);\n this.closeExternalTaskSettlement(oldest, new Error('The compacted task was evicted before push settlement.'));\n this.closedExternalTaskSettlementTaskIds.delete(oldest);\n }\n }\n\n /**\n * Handle input-required status\n *\n * Some agents (like Yahoo) return input-required status. THIS IS TOTALLY VALID AND IS AN INTERMEDIATE STATE.\n * IT SHOULD NOT BE THROWING AN ERROR. IT DOES NOT ALWAYS REQUIRE an input handler.\n * This is common for HITL (human-in-the-loop) workflows where the agent has already processed\n * the request and is just signaling that async approval may be needed.\n */\n private async handleInputRequired<T>(\n agent: AgentConfig,\n taskId: string,\n taskName: string,\n params: any,\n response: any,\n messages: Message[],\n inputHandler?: InputHandler,\n options: TaskOptions = {},\n debugLogs: any[] = [],\n startTime: number = Date.now(),\n deferTerminalTaskStatus = false\n ): Promise<TaskResult<T>> {\n const inputRequest = this.responseParser.parseInputRequest(response);\n\n // If no handler provided, return input-required status as a valid intermediate state\n // This allows callers to handle the input-required state themselves (e.g., HITL workflows)\n if (!inputHandler) {\n // Extract any data that came with the response (some agents include partial results)\n const partialData = this.extractResponseData(response, debugLogs, taskName);\n const metadata = this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'input-required',\n response,\n inputRequest,\n });\n this.compactIntermediateTaskState(taskId, 'input-required');\n\n return {\n success: true, // The task is progressing, not failed\n status: 'input-required',\n data: partialData,\n metadata,\n conversation: messages,\n debug_logs: debugLogs,\n };\n }\n\n // Build context for handler\n const context: ConversationContext = {\n messages,\n inputRequest,\n taskId,\n agent: { id: agent.id, name: agent.name, protocol: agent.protocol },\n attempt: 1,\n maxAttempts: options.maxClarifications || 3,\n deferToHuman: async () => ({ defer: true, token: randomUUID() }),\n abort: reason => {\n throw new Error(reason || 'Task aborted');\n },\n getSummary: () => messages.map(m => `${m.role}: ${JSON.stringify(m.content)}`).join('\\n'),\n wasFieldDiscussed: field =>\n // Check if any agent message requested this field via input-required\n messages.some(\n m =>\n m.role === 'agent' &&\n m.content &&\n typeof m.content === 'object' &&\n 'field' in m.content &&\n (m.content as Record<string, unknown>).field === field\n ),\n getPreviousResponse: field => {\n // Find the agent message that requested this field\n const fieldRequestIndex = messages.findIndex(\n m =>\n m.role === 'agent' &&\n m.content &&\n typeof m.content === 'object' &&\n 'field' in m.content &&\n (m.content as Record<string, unknown>).field === field\n );\n // The response is the next user message after the field request\n if (fieldRequestIndex >= 0) {\n const responseMsg = messages\n .slice(fieldRequestIndex + 1)\n .find(m => m.role === 'user' && m.metadata?.type === 'input_response');\n return responseMsg?.content;\n }\n return undefined;\n },\n };\n\n // Call handler\n const handlerResponse = await inputHandler(context);\n throwIfAborted(options.signal);\n\n // Check if handler wants to defer\n if (isDeferResponse(handlerResponse)) {\n const token = handlerResponse.token;\n\n // Save deferred state for later resumption\n if (this.config.deferredStorage) {\n await this.config.deferredStorage.set(token, {\n taskId,\n contextId: response.contextId || taskId,\n agent,\n taskName,\n params,\n messages,\n createdAt: Date.now(),\n });\n try {\n throwIfAborted(options.signal);\n } catch (error) {\n // Cancellation may race a storage adapter that ignores the signal.\n // Remove the just-written resume record before propagating it.\n await this.config.deferredStorage.delete(token);\n throw error;\n }\n }\n // Deferred storage is the resume source of truth. Avoid retaining a\n // duplicate full request (including assets/credentials) in activeTasks.\n this.compactIntermediateTaskState(taskId, 'deferred');\n\n const deferred: DeferredContinuation<T> = {\n token,\n question: inputRequest.question,\n resume: input => this.resumeDeferredTask<T>(token, input, !deferTerminalTaskStatus),\n };\n\n return {\n success: true, // The task is progressing, not failed\n status: 'deferred',\n deferred,\n metadata: this.buildMetadata({\n taskId,\n taskName,\n agent,\n startTime,\n status: 'deferred',\n clarificationRounds: 1,\n response,\n }),\n conversation: messages,\n debug_logs: debugLogs,\n };\n }\n\n // Handler provided input - continue with the task\n throwIfAborted(options.signal);\n return this.continueTaskWithInput<T>(\n agent,\n taskId,\n taskName,\n params,\n response.contextId,\n handlerResponse,\n messages,\n inputHandler, // Pass handler for multi-round clarification\n options,\n debugLogs,\n startTime,\n deferTerminalTaskStatus\n );\n }\n\n /**\n * List tasks for an agent, preferring MCP Tasks protocol when available.\n */\n private async listTasksForAgent(\n agent: AgentConfig,\n transport?: import('../protocols').TransportOptions\n ): Promise<TaskInfo[]> {\n // Try MCP Tasks protocol method first\n if (agent.protocol === 'mcp') {\n const authToken = getAuthToken(agent);\n try {\n return await listMCPTasks(agent.agent_uri, authToken, undefined, {\n transport: transport ?? this.config.transport,\n onTransportActivity: this.config.onTransportActivity,\n transportActivityContext: {\n agentId: agent.id,\n },\n });\n } catch (err) {\n if (is401Error(err)) throw err;\n // Fall through to tool call if protocol method is not supported\n }\n }\n const response = (await ProtocolClient.callTool(\n agent,\n 'tasks/list',\n {},\n {\n serverVersion: this.lastKnownServerVersion,\n adcpVersion: this.config.adcpVersion,\n ...(this.config.wireAdcpVersion !== undefined && { wireAdcpVersion: this.config.wireAdcpVersion }),\n ...(this.config.versionEnvelope !== undefined && { versionEnvelope: this.config.versionEnvelope }),\n transport: transport ?? this.config.transport,\n onTransportActivity: this.config.onTransportActivity,\n }\n )) as Record<string, unknown>;\n return (response.tasks as TaskInfo[]) || [];\n }\n\n /**\n * Task tracking methods (PR #78)\n */\n async listTasks(agent: AgentConfig, transport?: import('../protocols').TransportOptions): Promise<TaskInfo[]> {\n try {\n return await this.listTasksForAgent(agent, transport);\n } catch {\n // Static message only — CodeQL's taint analysis treats `error` and\n // every property of it as sensitive once it originates from an\n // operation that touched `agent.oauth_client_credentials`. Surfaces\n // the failure occurred; full detail is available via DEBUG=adcp:*.\n console.warn('Failed to list tasks (see DEBUG=adcp:* logs for detail)');\n return [];\n }\n }\n\n private async getTaskStatusWithRawResponse(\n agent: AgentConfig,\n taskId: string,\n transport?: import('../protocols').TransportOptions,\n signal?: AbortSignal\n ): Promise<TaskStatusPollResult> {\n // AdCP `tasks/get` is the cross-protocol work-status interface\n // (`schemas/cache/<v>/bundled/core/tasks-get-{request,response}.json`).\n // MCP tool names cannot contain `/`, so MCP servers advertise the\n // SDK-owned `tasks_get` alias; A2A continues to use the spec slash name.\n //\n // The previous implementation tried MCP's `experimental.tasks.getTask`\n // first for MCP agents and fell through to the AdCP tool path on\n // capability-missing. The native MCP path tracks the TRANSPORT-call\n // lifecycle (MCP analog of A2A `Task.state`) — not AdCP work\n // lifecycle. For submitted-arm polling we need work status; the\n // two interfaces are not substitutes, so we always use the AdCP\n // tool here. MCP sellers that haven't registered `tasks_get` as\n // an AdCP tool will surface a tool-not-found error rather than\n // silently polling the wrong lifecycle.\n //\n // The request param is `task_id` (snake_case per AdCP 3.0); the\n // response is the spec's flat shape, mapped to `TaskInfo` via\n // {@link mapTasksGetResponseToTaskInfo}.\n //\n //\n // Request includes `include_result: true` so spec-conformant\n // sellers (AdCP 3.1.0+) populate the typed `result` field on\n // `completed` responses (per adcontextprotocol/adcp#3126). Older\n // sellers ignore the unknown request field; the response mapper\n // falls back to the informal `additionalProperties` passthrough\n // for those.\n const toolName = agent.protocol === 'mcp' ? 'tasks_get' : 'tasks/get';\n const response = (await ProtocolClient.callTool(\n agent,\n toolName,\n { task_id: taskId, include_result: true },\n {\n serverVersion: this.lastKnownServerVersion,\n adcpVersion: this.config.adcpVersion,\n ...(this.config.wireAdcpVersion !== undefined && { wireAdcpVersion: this.config.wireAdcpVersion }),\n ...(this.config.versionEnvelope !== undefined && { versionEnvelope: this.config.versionEnvelope }),\n transport: transport ?? this.config.transport,\n signal,\n onTransportActivity: this.config.onTransportActivity,\n transportActivityContext: {\n taskId,\n },\n }\n )) as Record<string, unknown>;\n // We don't run `extractResponseData` here: that helper's\n // generic AdCP-error-arm detection treats any top-level\n // `error: { code, message }` as an error envelope and shreds the\n // response into `{ errors: [...] }`. For `tasks/get` the `error`\n // block is informational (the failed task's reason, not a\n // request rejection), so we map the raw response directly. The\n // mapper handles the AdCP-spec flat shape, the legacy\n // `{ task: ... }` nested wrapper, and MCP `structuredContent` /\n // A2A latest structured DataPart envelopes.\n return {\n task: mapTasksGetResponseToTaskInfo(response),\n rawResponse: response,\n };\n }\n\n async getTaskStatus(\n agent: AgentConfig,\n taskId: string,\n transport?: import('../protocols').TransportOptions,\n signal?: AbortSignal\n ): Promise<TaskInfo> {\n return (await this.getTaskStatusWithRawResponse(agent, taskId, transport, signal)).task;\n }\n\n async pollTaskCompletion<T>(\n agent: AgentConfig,\n taskId: string,\n pollInterval = 60000,\n transport?: import('../protocols').TransportOptions,\n signal?: AbortSignal\n ): Promise<TaskResult<T>> {\n const pollStartTime = Date.now();\n while (true) {\n // adcp-client#1612: When the outer storyboard race timer fires, the\n // caller's AbortSignal is already aborted. Exit cleanly rather than\n // continuing to send `tasks/get` requests that nobody is waiting for.\n if (signal?.aborted) {\n const reason =\n signal.reason instanceof Error ? signal.reason.message : String(signal.reason ?? 'polling cancelled');\n // adcp-client#1617: Phase 1 — notify the seller so it can stop doing\n // work for a buyer that has already given up. A2A 0.3.0 §7.4 defines\n // tasks/cancel for exactly this case. Fire-and-forget: cancel failure\n // (TaskNotCancelable, network error, terminal-state race) is non-fatal.\n // TODO(adcp-client#1617-phase2): upgrade to awaited cancel once AdCP\n // spec defines a cross-protocol cancel verb.\n //\n // SECURITY: silent on rejection. The orphan rejection's `Error.message`\n // can carry an echoed transport response body — same trust-boundary\n // concern as `raceWithSignal` in `src/lib/testing/client.ts`. A buyer\n // who has already aborted MUST NOT see seller-controlled text leak\n // into their logs/telemetry. The outer try AND the `.catch(() => {})`\n // are both intentional: a malformed `agent_uri` could throw\n // synchronously from `fetch(...)` before the promise chain catches\n // it, so the try guards the dispatch path; the `.catch()` guards the\n // async settlement path.\n if (agent.protocol === 'a2a' && taskId && agent.agent_uri) {\n try {\n // adcp-client#1617 Phase 2: pass the full agent so cancelA2ATask\n // can sign the POST when agent.request_signing is configured.\n // signed-requests sellers no longer 401 the cancel.\n const cancelTransport = normalizeTransportOptions(transport ?? this.config.transport);\n void cancelA2ATask(agent, taskId, cancelTransport?.trustedFetchFn, cancelTransport?.allowPrivateIp).catch(\n () => {\n /* see SECURITY note above */\n }\n );\n } catch {\n /* see SECURITY note above */\n }\n }\n return attachMatch({\n success: false as const,\n status: 'failed' as const,\n error: `tasks/get polling was cancelled before a terminal state was observed: ${reason}`,\n metadata: this.buildMetadata({\n taskId,\n taskName: 'unknown',\n agent,\n startTime: pollStartTime,\n status: 'failed',\n }),\n });\n }\n\n // adcp-client#1585: A2A 0.3.x defines no minimum retention TTL for\n // completed tasks. A seller may evict a task between the buyer\n // observing the working-state response and the first explicit\n // `tasks/get` poll firing — `getTaskStatus` then throws with a\n // \"Task <id> not found\" message. Surface a descriptive `failed`\n // `TaskResult` so the caller sees an actionable error instead of an\n // opaque uncaught exception escaping from the polling loop.\n let status: TaskInfo;\n let rawResponse: Record<string, unknown> | undefined;\n try {\n const pollResult = await this.getTaskStatusWithRawResponse(agent, taskId, transport, signal);\n status = pollResult.task;\n rawResponse = pollResult.rawResponse;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n // Bounded `\\S{1,128}` task-id segment (no `.*`) keeps the match\n // linear-time on adversarial inputs — CodeQL flags unbounded\n // polynomial regex on uncontrolled error strings.\n if (/\\btask\\s+\\S{1,128}\\s+not found\\b/i.test(msg)) {\n return attachMatch({\n success: false as const,\n status: 'failed' as const,\n error: `Task ${taskId} is no longer queryable — it may have been completed and evicted by the seller before this poll arrived. Consider using push notifications (reporting_webhook) instead of polling, or configuring a longer task retention TTL on the seller.`,\n metadata: this.buildMetadata({\n taskId,\n taskName: 'unknown',\n agent,\n startTime: pollStartTime,\n status: 'failed',\n }),\n });\n }\n throw err;\n }\n\n if (status.status === ADCP_STATUS.COMPLETED) {\n const pollSuccess = this.isOperationSuccess(status.result, status.taskType);\n\n if (pollSuccess) {\n return attachMatch({\n success: true as const,\n status: 'completed' as const,\n data: status.result,\n metadata: this.buildMetadata({\n taskId,\n taskName: status.taskType,\n agent,\n responseTimeMs: Date.now() - status.createdAt,\n status: 'completed',\n response: rawResponse,\n }),\n });\n }\n const asyncResultErr = extractAdcpErrorInfo(status.result);\n return attachMatch({\n success: false as const,\n status: 'failed' as const,\n data: status.result,\n error: this.extractOperationError(status.result),\n adcpError: asyncResultErr,\n errorInstance: this.buildErrorInstance(taskId, asyncResultErr),\n correlationId: extractCorrelationId(status.result),\n metadata: this.buildMetadata({\n taskId,\n taskName: status.taskType,\n agent,\n responseTimeMs: Date.now() - status.createdAt,\n status: 'failed',\n response: rawResponse,\n }),\n });\n }\n\n if (\n status.status === ADCP_STATUS.FAILED ||\n status.status === ADCP_STATUS.CANCELED ||\n status.status === ADCP_STATUS.REJECTED\n ) {\n const asyncFailedErr = extractAdcpErrorInfo(status.result);\n return attachMatch({\n success: false as const,\n status: 'failed' as const,\n data: status.result,\n error: status.error || status.message || `Task ${status.status}`,\n adcpError: asyncFailedErr,\n errorInstance: this.buildErrorInstance(taskId, asyncFailedErr),\n correlationId: extractCorrelationId(status.result),\n metadata: this.buildMetadata({\n taskId,\n taskName: status.taskType,\n agent,\n responseTimeMs: Date.now() - status.createdAt,\n status: 'failed',\n response: rawResponse,\n }),\n });\n }\n\n // Paused states: `input-required` and `auth-required`. Polling\n // alone can't advance these — the buyer must satisfy the paused\n // condition (supply input / refresh auth) and retry the\n // original tool call. Return a `TaskResultIntermediate` so the\n // caller can branch on `result.status`; this mirrors the\n // synchronous `handleInputRequired` no-handler path\n // (`success: true` because the task is progressing, not failed).\n // Without this branch the loop would spin until timeout — the\n // paused-state regression class flagged by adcp-client#977.\n if (status.status === ADCP_STATUS.INPUT_REQUIRED || status.status === ADCP_STATUS.AUTH_REQUIRED) {\n return attachMatch({\n success: true as const,\n status: status.status,\n data: status.result as T,\n metadata: this.buildMetadata({\n taskId,\n taskName: status.taskType,\n agent,\n responseTimeMs: Date.now() - status.createdAt,\n status: status.status,\n response: rawResponse,\n }),\n });\n }\n\n // adcp-client#1612: `status: 'unknown'` means `mapTasksGetResponseToTaskInfo`\n // could not extract a recognizable status string from the response — the\n // seller's `tasks/get` response did not conform to any expected envelope\n // shape (flat AdCP, MCP structuredContent, or A2A DataPart artifact).\n // Continuing to poll would spin forever since the shape won't change.\n // Surface a descriptive failure so the storyboard runner reports the\n // seller's non-conformance rather than burning the outer timeout budget.\n if (status.status === 'unknown') {\n return attachMatch({\n success: false as const,\n status: 'failed' as const,\n error:\n `tasks/get returned an unrecognizable response (parsed status: \"unknown\", taskId: \"${status.taskId}\"). ` +\n `The seller may not implement tasks/get as an AdCP skill, or its response did not match any ` +\n `supported envelope shape (flat AdCP, MCP structuredContent, or A2A DataPart artifact).`,\n metadata: this.buildMetadata({\n taskId,\n taskName: 'unknown',\n agent,\n startTime: pollStartTime,\n status: 'failed',\n response: rawResponse,\n }),\n });\n }\n\n await this.sleep(pollInterval);\n // Re-check after sleep so a signal that fired mid-sleep exits at the top\n // of the next iteration rather than issuing one more `getTaskStatus` call.\n if (signal?.aborted) continue;\n }\n }\n\n /**\n * Resume a deferred task (client deferral)\n */\n async resumeDeferredTask<T>(token: string, input: any, publishTerminalTaskStatus = true): Promise<TaskResult<T>> {\n if (!this.config.deferredStorage) {\n throw new Error('Deferred storage not configured');\n }\n\n const state = await this.config.deferredStorage.get(token);\n if (!state) {\n throw new Error(`Deferred task not found: ${token}`);\n }\n\n try {\n // Continue task with the provided input (no handler for resumed deferred tasks)\n const resumed = await this.continueTaskWithInput<T>(\n state.agent,\n state.taskId,\n state.taskName,\n state.params,\n state.contextId,\n input,\n state.messages,\n undefined, // No handler for deferred tasks - input was provided by human\n {},\n [],\n Date.now(),\n !publishTerminalTaskStatus\n );\n const remainsPaused = ['input-required', 'auth-required', 'deferred'].includes(resumed.status);\n if (\n publishTerminalTaskStatus &&\n ['completed', 'failed', 'rejected', 'canceled', 'governance-denied', 'aborted'].includes(resumed.status) &&\n this.activeTasks.get(state.taskId)?.status !== resumed.status\n ) {\n this.updateTaskStatus(state.taskId, resumed.status as TaskStatus, resumed.data, resumed.error);\n }\n if (!remainsPaused) {\n await this.config.deferredStorage.delete(token);\n }\n return attachMatch(resumed);\n } catch (error) {\n // A thrown continuation failure is terminal for this deferred token.\n // Release both persistence and the in-memory request payload before the\n // error escapes to the caller.\n if (publishTerminalTaskStatus) {\n this.updateTaskStatus(\n state.taskId,\n 'failed',\n undefined,\n error instanceof Error ? error.message : String(error)\n );\n }\n try {\n await this.config.deferredStorage.delete(token);\n } catch {\n // Local request compaction above is the safety boundary. Preserve the\n // original continuation/delete error if external cleanup also fails.\n }\n throw error;\n }\n }\n\n /**\n * Continue a task after receiving input\n */\n private async continueTaskWithInput<T>(\n agent: AgentConfig,\n taskId: string,\n taskName: string,\n params: any,\n contextId: string,\n input: any,\n messages: Message[],\n inputHandler: InputHandler | undefined,\n options: TaskOptions = {},\n debugLogs: any[] = [],\n startTime: number = Date.now(),\n deferTerminalTaskStatus = false\n ): Promise<TaskResult<T>> {\n // Add user input message\n const inputMessage: Message = {\n id: randomUUID(),\n role: 'user',\n content: input,\n timestamp: new Date().toISOString(),\n metadata: { type: 'input_response' },\n };\n messages.push(inputMessage);\n\n // Continue the task with input\n const response = await ProtocolClient.callTool(\n agent,\n 'continue_task',\n {\n contextId,\n input,\n },\n {\n debugLogs,\n serverVersion: this.lastKnownServerVersion,\n adcpVersion: this.config.adcpVersion,\n ...(this.config.wireAdcpVersion !== undefined && { wireAdcpVersion: this.config.wireAdcpVersion }),\n ...(this.config.versionEnvelope !== undefined && { versionEnvelope: this.config.versionEnvelope }),\n transport: options.transport ?? this.config.transport,\n signal: options.signal,\n onTransportActivity: this.config.onTransportActivity,\n transportActivityContext: {\n operationId: taskId,\n taskId,\n contextId,\n },\n }\n );\n\n // Add response message\n const responseMessage: Message = {\n id: randomUUID(),\n role: 'agent',\n content: response,\n timestamp: new Date().toISOString(),\n metadata: { type: 'continued_response' },\n };\n messages.push(responseMessage);\n\n // Handle the continued response (pass inputHandler for multi-round clarification)\n return this.handleAsyncResponse<T>(\n agent,\n taskId,\n taskName,\n params,\n response,\n messages,\n inputHandler,\n options,\n debugLogs,\n startTime,\n deferTerminalTaskStatus\n );\n }\n\n /**\n * Utility methods\n */\n private sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n private createErrorResult<T>(\n taskId: string,\n agent: AgentConfig,\n error: any,\n debugLogs: any[] = [],\n startTime: number = Date.now()\n ): TaskResult<T> {\n // Try to extract structured error info from transport exceptions\n // (e.g., JSON-RPC errors with data.adcp_error)\n const transportData = error?.data || error?.response?.data;\n const adcpErrorInfo = extractAdcpErrorInfo(transportData);\n const correlationId = extractCorrelationId(transportData);\n\n return {\n success: false as const,\n status: 'failed' as const,\n error: error.message || String(error),\n adcpError: adcpErrorInfo,\n errorInstance: this.buildErrorInstance(taskId, adcpErrorInfo),\n correlationId,\n metadata: this.buildMetadata({\n taskId,\n taskName: 'unknown',\n agent,\n startTime,\n status: 'failed',\n }),\n debug_logs: debugLogs,\n };\n }\n\n /**\n * Legacy methods for backward compatibility\n */\n getConversationHistory(taskId: string): Message[] | undefined {\n return this.conversationStorage?.get(taskId);\n }\n\n clearConversationHistory(taskId: string): void {\n this.conversationStorage?.delete(taskId);\n }\n\n getActiveTasks(): TaskState[] {\n return Array.from(this.activeTasks.values());\n }\n\n // ====== TASK MANAGEMENT & NOTIFICATION METHODS ======\n\n private taskEventListeners = new Map<\n string,\n {\n callback: (task: TaskInfo) => void;\n agentId?: string;\n }[]\n >();\n\n private webhookRegistrations = new Map<\n string,\n {\n agent: AgentConfig;\n webhookUrl: string;\n taskTypes?: string[];\n }\n >();\n\n /**\n * Get task list for a specific agent\n */\n async getTaskList(agentId: string, transport?: import('../protocols').TransportOptions): Promise<TaskInfo[]> {\n // First try to get from agent via protocol\n const agent = this.findAgentById(agentId);\n if (agent) {\n try {\n return await this.listTasksForAgent(agent, transport);\n } catch {\n // Static message — see comment on listTasks above.\n console.warn('Failed to get remote task list (see DEBUG=adcp:* logs for detail)');\n }\n }\n\n // Fall back to local active tasks\n return Array.from(this.activeTasks.values())\n .filter(task => task.agent.id === agentId)\n .map(task => ({\n taskId: task.taskId,\n status: task.status,\n taskType: task.taskName,\n createdAt: task.startTime,\n updatedAt: task.startTime, // TODO: track updates\n }));\n }\n\n /**\n * Get detailed information about a specific task\n */\n async getTaskInfo(taskId: string): Promise<TaskInfo | null> {\n const localTask = this.activeTasks.get(taskId);\n if (localTask) {\n if (this.compactedTaskIds.has(taskId)) {\n this.compactedTaskIds.delete(taskId);\n this.compactedTaskIds.set(taskId, true);\n }\n return {\n taskId: localTask.taskId,\n status: localTask.status,\n taskType: localTask.taskName,\n createdAt: localTask.startTime,\n updatedAt: localTask.startTime,\n };\n }\n\n // Try to get from agent\n // Note: Would need to know which agent to query\n return null;\n }\n\n /**\n * Subscribe to task updates for a specific agent\n */\n onTaskUpdate(agentId: string, callback: (task: TaskInfo) => void): () => void {\n const listenerId = randomUUID();\n const listeners = this.taskEventListeners.get(listenerId) || [];\n listeners.push({ callback, agentId });\n this.taskEventListeners.set(listenerId, listeners);\n\n return () => {\n this.taskEventListeners.delete(listenerId);\n };\n }\n\n /**\n * Subscribe to task events with detailed callbacks\n */\n onTaskEvents(\n agentId: string,\n callbacks: {\n onTaskCreated?: (task: TaskInfo) => void;\n onTaskUpdated?: (task: TaskInfo) => void;\n onTaskCompleted?: (task: TaskInfo) => void;\n onTaskFailed?: (task: TaskInfo, error: string) => void;\n }\n ): () => void {\n const unsubscribeFns: (() => void)[] = [];\n\n // Create combined handler that routes to specific callbacks\n const handler = (task: TaskInfo) => {\n switch (task.status) {\n case 'submitted':\n case 'working':\n callbacks.onTaskCreated?.(task);\n break;\n case 'input-required':\n callbacks.onTaskUpdated?.(task);\n break;\n case 'completed':\n callbacks.onTaskCompleted?.(task);\n break;\n case 'failed':\n case 'rejected':\n case 'canceled':\n callbacks.onTaskFailed?.(task, task.error || `Task ${task.status}`);\n break;\n default:\n callbacks.onTaskUpdated?.(task);\n }\n };\n\n unsubscribeFns.push(this.onTaskUpdate(agentId, handler));\n\n return () => {\n unsubscribeFns.forEach(fn => fn());\n };\n }\n\n /**\n * Register webhook for task notifications\n */\n async registerWebhook(agent: AgentConfig, webhookUrl: string, taskTypes?: string[]): Promise<void> {\n this.webhookRegistrations.set(agent.id, {\n agent,\n webhookUrl,\n taskTypes,\n });\n\n // TODO: Register with remote agent if it supports webhooks\n console.log(`Webhook registered for agent ${agent.id}: ${webhookUrl}`);\n }\n\n /**\n * Unregister webhook notifications\n */\n async unregisterWebhook(agent: AgentConfig): Promise<void> {\n this.webhookRegistrations.delete(agent.id);\n console.log(`Webhook unregistered for agent ${agent.id}`);\n }\n\n /**\n * Emit task event to listeners\n */\n private emitTaskEvent(task: TaskInfo, agentId?: string): void {\n this.taskEventListeners.forEach(listeners => {\n listeners.forEach(({ callback, agentId: listenerAgentId }) => {\n if (!listenerAgentId || listenerAgentId === agentId) {\n try {\n callback(task);\n } catch (error) {\n console.error('Error in task event callback:', error instanceof Error ? error.message : 'unknown error');\n }\n }\n });\n });\n }\n\n /**\n * Normalize response data for schema validation\n *\n * Converts v2-style responses to v3 format before validation.\n * This ensures validation passes for both v2 and v3 server responses.\n */\n private normalizeResponseForValidation(response: any, taskName: string, legacyWire = false): any {\n if (!response) return response;\n\n // Strip underscore-prefixed client-side annotations (`_message` is added\n // by the response unwrapper, others may follow). Schemas with\n // `additionalProperties: false` (create-property-list-response, etc.)\n // would otherwise reject every response that reaches the grader's\n // schema check — the annotation is not part of the wire protocol.\n const stripped: Record<string, unknown> = {};\n if (typeof response === 'object' && !Array.isArray(response)) {\n for (const [k, v] of Object.entries(response)) {\n if (!k.startsWith('_')) stripped[k] = v;\n }\n } else {\n return taskName === 'get_products' && !legacyWire ? normalizeGetProductsResponse(response) : response;\n }\n\n // Validate v2.5 against the exact response that crossed the wire. Public\n // canonicalization happens later in SingleAgentClient; applying it here\n // would compare canonical `fixed_price`/`format_options` fields to the\n // legacy schema that correctly requires `rate`/`is_fixed`/`format_ids`.\n if (legacyWire) return stripped;\n\n switch (taskName) {\n case 'get_products':\n return normalizeGetProductsResponse(stripped);\n default:\n return stripped;\n }\n }\n\n /**\n * Validate an incoming response against the bundled AdCP JSON schema for\n * `taskName`. Strict mode fails the task; warn mode logs and returns\n * valid so the caller can continue. Off mode short-circuits before\n * AJV runs.\n */\n private validateResponseSchema(\n response: any,\n taskName: string,\n debugLogs: any[]\n ): { valid: boolean; errors: string[] } {\n const mode = this.responseValidationMode;\n const logViolations = this.config.logSchemaViolations !== false;\n\n try {\n // Validate against the version the agent actually spoke. Without\n // this, v2.5 sellers (e.g. Wonderstruck) return valid v2.5-shaped\n // responses and the SDK rejects them as malformed v3 — surfaces as\n // `pricing_options must NOT have fewer than 1 items` and similar\n // shape mismatches that don't exist in v2.5. The v3 → v2 path is\n // already correctly version-pinned via lastKnownServerVersion.\n const validationVersion =\n this.lastKnownServerVersion === 'v2'\n ? 'v2.5'\n : (this.responseAdcpVersionForValidation() ?? this.config.adcpVersion ?? ADCP_VERSION);\n const normalizedResponse = this.normalizeResponseForValidation(response, taskName, validationVersion === 'v2.5');\n // TaskExecutor owns the user-facing log entry below. Passing debugLogs\n // into the lower-level hook would emit a second, unversioned duplicate.\n const outcome = validateIncomingResponse(taskName, normalizedResponse, mode, undefined, validationVersion);\n if (outcome.valid) return { valid: true, errors: [] };\n\n const errorStrings = outcome.issues.map(i => `${i.pointer}: ${i.message}`);\n\n if (logViolations) {\n debugLogs.push({\n timestamp: new Date().toISOString(),\n type: mode === 'strict' ? 'error' : 'warning',\n message: `Schema validation ${mode === 'strict' ? 'failed' : 'warning'} for ${taskName}: ${formatIssues(\n outcome.issues\n )}`,\n errors: errorStrings,\n issues: outcome.issues,\n schemaVariant: outcome.variant,\n schemaVersion: validationVersion,\n mode,\n });\n }\n\n if (mode === 'warn') {\n if (logViolations) {\n console.warn(\n `Schema validation failed for ${taskName} against AdCP ${validationVersion} (non-blocking):`,\n errorStrings\n );\n }\n return { valid: true, errors: [] };\n }\n\n if (logViolations) {\n console.error(`Schema validation failed for ${taskName} against AdCP ${validationVersion}:`, errorStrings);\n }\n return { valid: false, errors: errorStrings };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'unknown error';\n console.error('Error during schema validation:', errorMessage);\n return {\n valid: mode !== 'strict',\n errors: mode === 'strict' ? [`Validation error: ${errorMessage}`] : [],\n };\n }\n }\n\n private responseAdcpVersionForValidation(): string | undefined {\n if (this.config.versionEnvelope === 'major-only') return '3.0';\n return undefined;\n }\n\n private effectiveResponseAdcpVersion(): string {\n if (this.lastKnownServerVersion === 'v2') return 'v2.5';\n return this.responseAdcpVersionForValidation() ?? this.config.adcpVersion ?? ADCP_VERSION;\n }\n\n /**\n * Update task status and emit events\n */\n private updateTaskStatus(taskId: string, status: TaskStatus, result?: any, error?: string): void {\n const task = this.activeTasks.get(taskId);\n if (task) {\n // Once cancellation has released request state, late work must not\n // resurrect the task or emit completion after the caller has retried.\n if (task.status === 'aborted' && status !== 'aborted') return;\n const previousStatus = task.status;\n task.status = status;\n\n const taskInfo: TaskInfo = {\n taskId: task.taskId,\n status: status,\n taskType: task.taskName,\n createdAt: task.startTime,\n updatedAt: Date.now(),\n result,\n error,\n };\n\n this.emitTaskEvent(taskInfo, task.agent.id);\n\n this.config.onActivity?.({\n type: 'status_change',\n operation_id: task.taskId,\n agent_id: task.agent.id,\n context_id: undefined,\n task_id: task.taskId,\n task_type: task.taskName,\n status: status,\n payload: result ?? (error ? { error } : undefined),\n timestamp: new Date().toISOString(),\n });\n\n if (status === 'input-required' || status === 'auth-required') {\n this.compactIntermediateTaskState(taskId, status);\n }\n\n // If task is finished, remove from active tasks after a delay.\n // unref() ensures this timer doesn't prevent the process from exiting.\n if (TERMINAL_TASK_STATUSES.has(status)) {\n // Keep lifecycle metadata briefly for status inspection, but release\n // request/conversation/options immediately. These may contain inline\n // creative assets and webhook or transport credentials.\n task.params = undefined;\n task.messages = [];\n task.options = {};\n delete task.pendingInput;\n setTimeout(() => {\n this.cleanupTerminalTaskInspectionState(taskId);\n }, 30000).unref(); // Keep for 30 seconds for final status checks\n }\n }\n }\n\n /**\n * Helper to find agent config by ID\n */\n private findAgentById(agentId: string): AgentConfig | undefined {\n // This would ideally be passed in or stored in the executor\n // For now, return undefined and fall back to local tasks\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,oBAAuC;AAEvC,uBAKO;AACP,uBAA6B;AAC7B,mCAA6C;AAC7C,kBAA6B;AAC7B,oBAAsE;AAGtE,0BAMO;AACP,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