@adcp/client 4.8.0 → 4.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/bin/adcp.js +8 -0
  2. package/dist/lib/adapters/governance-adapter.d.ts +88 -0
  3. package/dist/lib/adapters/governance-adapter.d.ts.map +1 -0
  4. package/dist/lib/adapters/governance-adapter.js +96 -0
  5. package/dist/lib/adapters/governance-adapter.js.map +1 -0
  6. package/dist/lib/adapters/index.d.ts +1 -0
  7. package/dist/lib/adapters/index.d.ts.map +1 -1
  8. package/dist/lib/adapters/index.js +7 -1
  9. package/dist/lib/adapters/index.js.map +1 -1
  10. package/dist/lib/agents/index.generated.d.ts +33 -1
  11. package/dist/lib/agents/index.generated.d.ts.map +1 -1
  12. package/dist/lib/agents/index.generated.js +48 -0
  13. package/dist/lib/agents/index.generated.js.map +1 -1
  14. package/dist/lib/core/AgentClient.d.ts.map +1 -1
  15. package/dist/lib/core/AsyncHandler.d.ts +1 -1
  16. package/dist/lib/core/AsyncHandler.d.ts.map +1 -1
  17. package/dist/lib/core/AsyncHandler.js.map +1 -1
  18. package/dist/lib/core/ConversationTypes.d.ts +8 -2
  19. package/dist/lib/core/ConversationTypes.d.ts.map +1 -1
  20. package/dist/lib/core/GovernanceMiddleware.d.ts +86 -0
  21. package/dist/lib/core/GovernanceMiddleware.d.ts.map +1 -0
  22. package/dist/lib/core/GovernanceMiddleware.js +289 -0
  23. package/dist/lib/core/GovernanceMiddleware.js.map +1 -0
  24. package/dist/lib/core/GovernanceTypes.d.ts +118 -0
  25. package/dist/lib/core/GovernanceTypes.d.ts.map +1 -0
  26. package/dist/lib/core/GovernanceTypes.js +69 -0
  27. package/dist/lib/core/GovernanceTypes.js.map +1 -0
  28. package/dist/lib/core/SingleAgentClient.d.ts +35 -1
  29. package/dist/lib/core/SingleAgentClient.d.ts.map +1 -1
  30. package/dist/lib/core/SingleAgentClient.js +45 -0
  31. package/dist/lib/core/SingleAgentClient.js.map +1 -1
  32. package/dist/lib/core/TaskExecutor.d.ts +10 -0
  33. package/dist/lib/core/TaskExecutor.d.ts.map +1 -1
  34. package/dist/lib/core/TaskExecutor.js +95 -10
  35. package/dist/lib/core/TaskExecutor.js.map +1 -1
  36. package/dist/lib/index.d.ts +6 -2
  37. package/dist/lib/index.d.ts.map +1 -1
  38. package/dist/lib/index.js +22 -4
  39. package/dist/lib/index.js.map +1 -1
  40. package/dist/lib/observability/index.d.ts +8 -0
  41. package/dist/lib/observability/index.d.ts.map +1 -0
  42. package/dist/lib/observability/index.js +17 -0
  43. package/dist/lib/observability/index.js.map +1 -0
  44. package/dist/lib/observability/tracing.d.ts +42 -0
  45. package/dist/lib/observability/tracing.d.ts.map +1 -0
  46. package/dist/lib/observability/tracing.js +126 -0
  47. package/dist/lib/observability/tracing.js.map +1 -0
  48. package/dist/lib/protocols/a2a.d.ts.map +1 -1
  49. package/dist/lib/protocols/a2a.js +16 -1
  50. package/dist/lib/protocols/a2a.js.map +1 -1
  51. package/dist/lib/protocols/index.d.ts.map +1 -1
  52. package/dist/lib/protocols/index.js +37 -29
  53. package/dist/lib/protocols/index.js.map +1 -1
  54. package/dist/lib/protocols/mcp.d.ts.map +1 -1
  55. package/dist/lib/protocols/mcp.js +21 -1
  56. package/dist/lib/protocols/mcp.js.map +1 -1
  57. package/dist/lib/registry/types.generated.d.ts +750 -1
  58. package/dist/lib/registry/types.generated.d.ts.map +1 -1
  59. package/dist/lib/registry/types.generated.js +1 -1
  60. package/dist/lib/testing/agent-tester.d.ts +1 -1
  61. package/dist/lib/testing/agent-tester.d.ts.map +1 -1
  62. package/dist/lib/testing/agent-tester.js +36 -11
  63. package/dist/lib/testing/agent-tester.js.map +1 -1
  64. package/dist/lib/testing/orchestrator.d.ts +0 -2
  65. package/dist/lib/testing/orchestrator.d.ts.map +1 -1
  66. package/dist/lib/testing/orchestrator.js +14 -3
  67. package/dist/lib/testing/orchestrator.js.map +1 -1
  68. package/dist/lib/testing/scenarios/capabilities.d.ts.map +1 -1
  69. package/dist/lib/testing/scenarios/capabilities.js +64 -4
  70. package/dist/lib/testing/scenarios/capabilities.js.map +1 -1
  71. package/dist/lib/testing/scenarios/creative.d.ts +14 -0
  72. package/dist/lib/testing/scenarios/creative.d.ts.map +1 -1
  73. package/dist/lib/testing/scenarios/creative.js +241 -42
  74. package/dist/lib/testing/scenarios/creative.js.map +1 -1
  75. package/dist/lib/testing/scenarios/governance.d.ts +48 -0
  76. package/dist/lib/testing/scenarios/governance.d.ts.map +1 -1
  77. package/dist/lib/testing/scenarios/governance.js +675 -0
  78. package/dist/lib/testing/scenarios/governance.js.map +1 -1
  79. package/dist/lib/testing/scenarios/index.d.ts +3 -3
  80. package/dist/lib/testing/scenarios/index.d.ts.map +1 -1
  81. package/dist/lib/testing/scenarios/index.js +8 -1
  82. package/dist/lib/testing/scenarios/index.js.map +1 -1
  83. package/dist/lib/testing/scenarios/media-buy.d.ts +8 -0
  84. package/dist/lib/testing/scenarios/media-buy.d.ts.map +1 -1
  85. package/dist/lib/testing/scenarios/media-buy.js +225 -19
  86. package/dist/lib/testing/scenarios/media-buy.js.map +1 -1
  87. package/dist/lib/testing/types.d.ts +1 -1
  88. package/dist/lib/testing/types.d.ts.map +1 -1
  89. package/dist/lib/types/core.generated.d.ts +629 -5
  90. package/dist/lib/types/core.generated.d.ts.map +1 -1
  91. package/dist/lib/types/core.generated.js +1 -1
  92. package/dist/lib/types/schemas.generated.d.ts +13059 -11101
  93. package/dist/lib/types/schemas.generated.d.ts.map +1 -1
  94. package/dist/lib/types/schemas.generated.js +573 -107
  95. package/dist/lib/types/schemas.generated.js.map +1 -1
  96. package/dist/lib/types/tools.generated.d.ts +1827 -360
  97. package/dist/lib/types/tools.generated.d.ts.map +1 -1
  98. package/dist/lib/utils/capabilities.d.ts +17 -2
  99. package/dist/lib/utils/capabilities.d.ts.map +1 -1
  100. package/dist/lib/utils/capabilities.js +26 -2
  101. package/dist/lib/utils/capabilities.js.map +1 -1
  102. package/package.json +9 -2
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Buyer-side governance middleware.
3
+ *
4
+ * Intercepts tool calls in the execution path and checks them against
5
+ * a campaign governance agent before allowing execution. Handles:
6
+ * - approved: proceed with execution
7
+ * - denied: return denial to caller
8
+ * - conditions: auto-apply machine-actionable conditions and re-check
9
+ * - escalated: return escalation continuation to caller
10
+ *
11
+ * After execution, reports the outcome back to the governance agent.
12
+ */
13
+ import type { GovernanceContext, OutcomeType } from '../types/tools.generated';
14
+ import type { Activity } from './AsyncHandler';
15
+ import type { GovernanceConfig, CampaignGovernanceConfig, GovernanceCheckResult, GovernanceOutcome, GovernanceCondition } from './GovernanceTypes';
16
+ /**
17
+ * Typed debug log entries for governance operations.
18
+ */
19
+ export type GovernanceDebugEntry = {
20
+ type: 'governance_check';
21
+ iteration: number;
22
+ tool: string;
23
+ plan_id: string;
24
+ } | {
25
+ type: 'governance_conditions_applied';
26
+ iteration: number;
27
+ conditions: GovernanceCondition[];
28
+ } | {
29
+ type: 'governance_outcome_error';
30
+ check_id: string;
31
+ error: string;
32
+ };
33
+ /**
34
+ * Set a value at a dot-path in an object. Creates intermediate objects as needed.
35
+ * e.g., setAtPath(obj, 'packages.0.budget', 25000)
36
+ *
37
+ * Path segments are validated against a safe allowlist pattern and a forbidden
38
+ * set to prevent prototype pollution from external governance agent responses.
39
+ */
40
+ export declare function setAtPath(obj: Record<string, any>, path: string, value: unknown): void;
41
+ /**
42
+ * Extract structured governance context from tool call parameters.
43
+ *
44
+ * Extracts budget, countries, channels, flight dates, and seller URL from
45
+ * common AdCP tool parameter conventions. Override via
46
+ * CampaignGovernanceConfig.extractContext for custom tool schemas.
47
+ */
48
+ export declare function extractGovernanceContext(params: Record<string, unknown>, config: CampaignGovernanceConfig): GovernanceContext | undefined;
49
+ export declare class GovernanceMiddleware {
50
+ private governanceConfig;
51
+ private onActivity?;
52
+ constructor(governanceConfig: GovernanceConfig, onActivity?: ((activity: Activity) => void | Promise<void>) | undefined);
53
+ /**
54
+ * Check whether this tool requires a governance check.
55
+ */
56
+ requiresCheck(tool: string): boolean;
57
+ /**
58
+ * Get the campaign governance config. Returns undefined if not configured.
59
+ */
60
+ get campaign(): CampaignGovernanceConfig | undefined;
61
+ /**
62
+ * Run a proposed governance check before sending a tool call to a seller.
63
+ *
64
+ * Returns the governance result. The caller decides how to handle each status:
65
+ * - approved: proceed with execution (params may be modified by conditions)
66
+ * - denied: do not execute
67
+ * - escalated: do not execute, return continuation to caller
68
+ *
69
+ * When conditions are returned with required_value, this method auto-applies
70
+ * them and re-checks, up to maxConditionsIterations.
71
+ */
72
+ checkProposed(tool: string, params: Record<string, unknown>, debugLogs?: GovernanceDebugEntry[]): Promise<{
73
+ result: GovernanceCheckResult;
74
+ params: Record<string, unknown>;
75
+ }>;
76
+ /**
77
+ * Report the outcome of a tool execution to the governance agent.
78
+ * Called after the seller responds (success or failure).
79
+ */
80
+ reportOutcome(checkId: string, outcome: OutcomeType, sellerResponse?: Record<string, unknown>, error?: {
81
+ code?: string;
82
+ message: string;
83
+ }, debugLogs?: GovernanceDebugEntry[]): Promise<GovernanceOutcome | undefined>;
84
+ private emitGovernanceActivity;
85
+ }
86
+ //# sourceMappingURL=GovernanceMiddleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GovernanceMiddleware.d.ts","sourceRoot":"","sources":["../../../src/lib/core/GovernanceMiddleware.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,KAAK,EAGV,iBAAiB,EAGjB,WAAW,EACZ,MAAM,0BAA0B,CAAC;AAElC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,KAAK,EACV,gBAAgB,EAChB,wBAAwB,EACxB,qBAAqB,EACrB,iBAAiB,EAEjB,mBAAmB,EACpB,MAAM,mBAAmB,CAAC;AAI3B;;GAEG;AACH,MAAM,MAAM,oBAAoB,GAC5B;IAAE,IAAI,EAAE,k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CAAC,CAAA;KAAE,CAAC;IA4G9E;;;OAGG;IACG,aAAa,CACjB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,WAAW,EACpB,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACxC,KAAK,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,EAC1C,SAAS,GAAE,oBAAoB,EAAO,GACrC,OAAO,CAAC,iBAAiB,GAAG,SAAS,CAAC;YAyE3B,sBAAsB;CAerC"}
@@ -0,0 +1,289 @@
1
+ "use strict";
2
+ /**
3
+ * Buyer-side governance middleware.
4
+ *
5
+ * Intercepts tool calls in the execution path and checks them against
6
+ * a campaign governance agent before allowing execution. Handles:
7
+ * - approved: proceed with execution
8
+ * - denied: return denial to caller
9
+ * - conditions: auto-apply machine-actionable conditions and re-check
10
+ * - escalated: return escalation continuation to caller
11
+ *
12
+ * After execution, reports the outcome back to the governance agent.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.GovernanceMiddleware = void 0;
16
+ exports.setAtPath = setAtPath;
17
+ exports.extractGovernanceContext = extractGovernanceContext;
18
+ const protocols_1 = require("../protocols");
19
+ const GovernanceTypes_1 = require("./GovernanceTypes");
20
+ const response_unwrapper_1 = require("../utils/response-unwrapper");
21
+ /** Safe pattern for path segments: identifiers or numeric indices */
22
+ const SAFE_PATH_SEGMENT = /^[a-zA-Z_$][a-zA-Z0-9_$]*$|^\d+$/;
23
+ /** Path segments that would cause prototype pollution even though they match the safe pattern. */
24
+ const FORBIDDEN_PATH_SEGMENTS = new Set(['__proto__', 'constructor', 'prototype']);
25
+ /**
26
+ * Set a value at a dot-path in an object. Creates intermediate objects as needed.
27
+ * e.g., setAtPath(obj, 'packages.0.budget', 25000)
28
+ *
29
+ * Path segments are validated against a safe allowlist pattern and a forbidden
30
+ * set to prevent prototype pollution from external governance agent responses.
31
+ */
32
+ function setAtPath(obj, path, value) {
33
+ if (!path || path.trim() === '') {
34
+ throw new Error('Empty path is not allowed');
35
+ }
36
+ const parts = path.split('.');
37
+ for (const part of parts) {
38
+ if (FORBIDDEN_PATH_SEGMENTS.has(part)) {
39
+ throw new Error(`Invalid path segment: ${part}`);
40
+ }
41
+ if (!SAFE_PATH_SEGMENT.test(part)) {
42
+ throw new Error(`Invalid path segment: ${part}`);
43
+ }
44
+ }
45
+ let current = obj;
46
+ for (let i = 0; i < parts.length - 1; i++) {
47
+ const key = parts[i];
48
+ if (current[key] == null || typeof current[key] !== 'object') {
49
+ // Create array if next key is numeric, else object
50
+ current[key] = /^\d+$/.test(parts[i + 1]) ? [] : {};
51
+ }
52
+ current = current[key];
53
+ }
54
+ current[parts[parts.length - 1]] = value;
55
+ }
56
+ /**
57
+ * Extract structured governance context from tool call parameters.
58
+ *
59
+ * Extracts budget, countries, channels, flight dates, and seller URL from
60
+ * common AdCP tool parameter conventions. Override via
61
+ * CampaignGovernanceConfig.extractContext for custom tool schemas.
62
+ */
63
+ function extractGovernanceContext(params, config) {
64
+ const ctx = {};
65
+ let hasField = false;
66
+ // Extract budget from common locations
67
+ const budget = params.budget;
68
+ if (budget?.total != null && budget?.currency) {
69
+ ctx.total_budget = { amount: budget.total, currency: budget.currency };
70
+ hasField = true;
71
+ }
72
+ // Extract countries
73
+ if (Array.isArray(params.countries) && params.countries.length > 0) {
74
+ ctx.countries = params.countries;
75
+ hasField = true;
76
+ }
77
+ // Extract channels
78
+ const channel = params.channel;
79
+ if (channel) {
80
+ ctx.channels = [channel];
81
+ hasField = true;
82
+ }
83
+ else if (Array.isArray(params.channels) && params.channels.length > 0) {
84
+ ctx.channels = params.channels;
85
+ hasField = true;
86
+ }
87
+ // Extract flight dates
88
+ const flight = params.flight;
89
+ if (flight?.start && flight?.end) {
90
+ ctx.flight = { start: flight.start, end: flight.end };
91
+ hasField = true;
92
+ }
93
+ // Include seller URL if the agent config has it
94
+ if (config.callerUrl) {
95
+ ctx.seller_url = config.callerUrl;
96
+ hasField = true;
97
+ }
98
+ return hasField ? ctx : undefined;
99
+ }
100
+ class GovernanceMiddleware {
101
+ governanceConfig;
102
+ onActivity;
103
+ constructor(governanceConfig, onActivity) {
104
+ this.governanceConfig = governanceConfig;
105
+ this.onActivity = onActivity;
106
+ }
107
+ /**
108
+ * Check whether this tool requires a governance check.
109
+ */
110
+ requiresCheck(tool) {
111
+ return (0, GovernanceTypes_1.toolRequiresGovernance)(tool, this.governanceConfig);
112
+ }
113
+ /**
114
+ * Get the campaign governance config. Returns undefined if not configured.
115
+ */
116
+ get campaign() {
117
+ return this.governanceConfig.campaign;
118
+ }
119
+ /**
120
+ * Run a proposed governance check before sending a tool call to a seller.
121
+ *
122
+ * Returns the governance result. The caller decides how to handle each status:
123
+ * - approved: proceed with execution (params may be modified by conditions)
124
+ * - denied: do not execute
125
+ * - escalated: do not execute, return continuation to caller
126
+ *
127
+ * When conditions are returned with required_value, this method auto-applies
128
+ * them and re-checks, up to maxConditionsIterations.
129
+ */
130
+ async checkProposed(tool, params, debugLogs = []) {
131
+ const config = this.governanceConfig.campaign;
132
+ if (!config) {
133
+ throw new Error('Campaign governance not configured');
134
+ }
135
+ const maxReChecks = config.maxConditionsIterations ?? 0;
136
+ let currentParams = structuredClone(params);
137
+ let iteration = 0;
138
+ // Always make the initial governance check. maxConditionsIterations only
139
+ // controls how many times we re-apply conditions and re-check.
140
+ do {
141
+ const request = {
142
+ plan_id: config.planId,
143
+ buyer_campaign_ref: config.buyerCampaignRef ?? '',
144
+ binding: 'proposed',
145
+ caller: config.callerUrl ?? '',
146
+ tool,
147
+ payload: currentParams,
148
+ governance_context: config.extractContext
149
+ ? config.extractContext(currentParams)
150
+ : extractGovernanceContext(currentParams, config),
151
+ };
152
+ debugLogs.push({
153
+ type: 'governance_check',
154
+ iteration,
155
+ tool,
156
+ plan_id: config.planId,
157
+ });
158
+ const response = await protocols_1.ProtocolClient.callTool(config.agent, 'check_governance', request, debugLogs);
159
+ // Unwrap protocol response (MCP text content, structuredContent, A2A artifacts)
160
+ const responseData = (0, response_unwrapper_1.unwrapProtocolResponse)(response);
161
+ await this.emitGovernanceActivity('governance_check', {
162
+ tool,
163
+ binding: 'proposed',
164
+ iteration,
165
+ response: responseData,
166
+ });
167
+ const checkResult = (0, GovernanceTypes_1.parseCheckResponse)(responseData);
168
+ if (checkResult.status === 'approved') {
169
+ return { result: checkResult, params: currentParams };
170
+ }
171
+ if (checkResult.status === 'denied' || checkResult.status === 'escalated') {
172
+ return { result: checkResult, params: currentParams };
173
+ }
174
+ // status === 'conditions'
175
+ if (!checkResult.conditions || checkResult.conditions.length === 0) {
176
+ // Conditions status with no conditions — treat as advisory denial
177
+ return { result: checkResult, params: currentParams };
178
+ }
179
+ // Try to auto-apply machine-actionable conditions
180
+ const allApplicable = checkResult.conditions.every(c => c.requiredValue !== undefined);
181
+ if (!allApplicable) {
182
+ // Some conditions are advisory-only (no required_value) — can't auto-apply
183
+ return { result: checkResult, params: currentParams };
184
+ }
185
+ // If we've exhausted re-check iterations, return conditions to caller
186
+ if (iteration >= maxReChecks) {
187
+ return { result: checkResult, params: currentParams };
188
+ }
189
+ // Apply conditions and re-check
190
+ for (const condition of checkResult.conditions) {
191
+ setAtPath(currentParams, condition.field, condition.requiredValue);
192
+ }
193
+ checkResult.conditionsApplied = true;
194
+ checkResult.modifiedParams = currentParams;
195
+ debugLogs.push({
196
+ type: 'governance_conditions_applied',
197
+ iteration,
198
+ conditions: checkResult.conditions,
199
+ });
200
+ iteration++;
201
+ } while (iteration <= maxReChecks);
202
+ // Defensive: the early return at `iteration >= maxReChecks` inside the loop
203
+ // should always fire before this point. If we somehow reach here, treat it
204
+ // as an unresolvable condition so we fail closed.
205
+ return {
206
+ result: {
207
+ checkId: '',
208
+ status: 'denied',
209
+ binding: 'proposed',
210
+ explanation: `Governance conditions could not be resolved after ${maxReChecks} iterations`,
211
+ },
212
+ params: currentParams,
213
+ };
214
+ }
215
+ /**
216
+ * Report the outcome of a tool execution to the governance agent.
217
+ * Called after the seller responds (success or failure).
218
+ */
219
+ async reportOutcome(checkId, outcome, sellerResponse, error, debugLogs = []) {
220
+ const config = this.governanceConfig.campaign;
221
+ if (!config)
222
+ return undefined;
223
+ const request = {
224
+ plan_id: config.planId,
225
+ check_id: checkId,
226
+ buyer_campaign_ref: config.buyerCampaignRef ?? '',
227
+ outcome,
228
+ };
229
+ if (outcome === 'completed' && sellerResponse) {
230
+ request.seller_response = sellerResponse;
231
+ }
232
+ if (outcome === 'failed' && error) {
233
+ request.error = error;
234
+ }
235
+ try {
236
+ const response = await protocols_1.ProtocolClient.callTool(config.agent, 'report_plan_outcome', request, debugLogs);
237
+ const responseData = (0, response_unwrapper_1.unwrapProtocolResponse)(response);
238
+ await this.emitGovernanceActivity('governance_outcome', {
239
+ check_id: checkId,
240
+ outcome,
241
+ });
242
+ return {
243
+ outcomeId: responseData.outcome_id,
244
+ status: responseData.status,
245
+ committedBudget: responseData.committed_budget,
246
+ findings: responseData.findings?.map(f => ({
247
+ categoryId: f.category_id,
248
+ severity: f.severity,
249
+ explanation: f.explanation,
250
+ details: f.details,
251
+ })),
252
+ planSummary: responseData.plan_summary?.total_committed != null && responseData.plan_summary?.budget_remaining != null
253
+ ? {
254
+ totalCommitted: responseData.plan_summary.total_committed,
255
+ budgetRemaining: responseData.plan_summary.budget_remaining,
256
+ }
257
+ : undefined,
258
+ };
259
+ }
260
+ catch (err) {
261
+ // Outcome reporting failure shouldn't fail the task
262
+ debugLogs.push({
263
+ type: 'governance_outcome_error',
264
+ check_id: checkId,
265
+ error: err.message,
266
+ });
267
+ await this.emitGovernanceActivity('governance_outcome', {
268
+ check_id: checkId,
269
+ outcome,
270
+ error: err.message,
271
+ warning: 'Outcome reporting failed — governance agent may have stale state',
272
+ }, 'failed');
273
+ return undefined;
274
+ }
275
+ }
276
+ async emitGovernanceActivity(type, payload, status = 'completed') {
277
+ await this.onActivity?.({
278
+ type,
279
+ operation_id: '',
280
+ agent_id: this.governanceConfig.campaign?.agent.id ?? '',
281
+ task_type: 'governance',
282
+ status,
283
+ payload,
284
+ timestamp: new Date().toISOString(),
285
+ });
286
+ }
287
+ }
288
+ exports.GovernanceMiddleware = GovernanceMiddleware;
289
+ //# sourceMappingURL=GovernanceMiddleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GovernanceMiddleware.js","sourceRoot":"","sources":["../../../src/lib/core/GovernanceMiddleware.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;GAWG;;;AA6CH,8BAuBC;AASD,4DA4CC;AA9GD,4CAA8C;AAU9C,uDAA+E;AAC/E,oEAAqE;AAUrE,qEAAqE;AACrE,MAAM,iBAAiB,GAAG,kCAAkC,CAAC;AAE7D,kGAAkG;AAClG,MAAM,uBAAuB,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,aAAa,EAAE,WAAW,CAAC,CAAC,CAAC;AAEnF;;;;;;GAMG;AACH,SAAgB,SAAS,CAAC,GAAwB,EAAE,IAAY,EAAE,KAAc;IAC9E,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QAChC,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;IAC/C,CAAC;IACD,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC9B,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,IAAI,uBAAuB,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,yBAAyB,IAAI,EAAE,CAAC,CAAC;QACnD,CAAC;QACD,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YAClC,MAAM,IAAI,KAAK,CAAC,yBAAyB,IAAI,EAAE,CAAC,CAAC;QACnD,CAAC;IACH,CAAC;IACD,IAAI,OAAO,GAAG,GAAG,CAAC;IAClB,KAAK,IAAI,CA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,OAAO;aAC9B,CAAC,CAAC;YACH,MAAM,IAAI,CAAC,sBAAsB,CAC/B,oBAAoB,EACpB;gBACE,QAAQ,EAAE,OAAO;gBACjB,OAAO;gBACP,KAAK,EAAG,GAAa,CAAC,OAAO;gBAC7B,OAAO,EAAE,kEAAkE;aAC5E,EACD,QAAQ,CACT,CAAC;YACF,OAAO,SAAS,CAAC;QACnB,CAAC;IACH,CAAC;IAEO,KAAK,CAAC,sBAAsB,CAClC,IAAsB,EACtB,OAAgC,EAChC,SAAiB,WAAW;QAE5B,MAAM,IAAI,CAAC,UAAU,EAAE,CAAC;YACtB,IAAI;YACJ,YAAY,EAAE,EAAE;YAChB,QAAQ,EAAE,IAAI,CAAC,gBAAgB,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,IAAI,EAAE;YACxD,SAAS,EAAE,YAAY;YACvB,MAAM;YACN,OAAO;YACP,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;SACpC,CAAC,CAAC;IACL,CAAC;CACF;AAjPD,oDAiPC"}
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Governance middleware types for buyer-side campaign governance.
3
+ *
4
+ * The governance middleware intercepts tool calls and checks them against
5
+ * a campaign governance agent before execution. It handles the full lifecycle:
6
+ * check → execute → report outcome.
7
+ */
8
+ import type { AgentConfig } from '../types';
9
+ import type { CheckGovernanceResponse, EscalationSeverity, GovernanceMode } from '../types/tools.generated';
10
+ /**
11
+ * Campaign governance agent configuration.
12
+ * The campaign governance agent handles check_governance, sync_plans,
13
+ * report_plan_outcome, and get_plan_audit_logs.
14
+ */
15
+ export interface CampaignGovernanceConfig {
16
+ /** The governance agent to call */
17
+ agent: AgentConfig;
18
+ /** Plan ID for this advertiser's campaign */
19
+ planId: string;
20
+ /** Buyer's campaign reference (groups checks within a plan) */
21
+ buyerCampaignRef?: string;
22
+ /** Caller URL for the check_governance request */
23
+ callerUrl?: string;
24
+ /** Max re-check iterations after auto-applying conditions. Default: 0 (return conditions to caller without re-checking). The initial governance check always fires. */
25
+ maxConditionsIterations?: number;
26
+ /** Custom context extractor. Overrides the default extraction of budget, countries, channels, flight from tool params. Return undefined to send no context. */
27
+ extractContext?: (params: Record<string, unknown>) => import('../types/tools.generated').GovernanceContext | undefined;
28
+ }
29
+ /**
30
+ * Governance configuration.
31
+ *
32
+ * Campaign governance handles: check_governance, sync_plans,
33
+ * report_plan_outcome, get_plan_audit_logs.
34
+ */
35
+ export interface GovernanceConfig {
36
+ /** Campaign governance agent */
37
+ campaign?: CampaignGovernanceConfig;
38
+ /**
39
+ * Which tools require governance checks.
40
+ * - 'all': every tool including get_adcp_capabilities (governance tools themselves still excluded)
41
+ * - string[]: only listed tools
42
+ * - function: custom predicate
43
+ * - undefined (default): all tools except get_adcp_capabilities and governance tools
44
+ */
45
+ scope?: 'all' | string[] | ((tool: string) => boolean);
46
+ }
47
+ /**
48
+ * Determine whether a tool requires a governance check given the config.
49
+ */
50
+ export declare function toolRequiresGovernance(tool: string, config: GovernanceConfig): boolean;
51
+ /**
52
+ * A single finding from a governance check.
53
+ */
54
+ export interface GovernanceFinding {
55
+ categoryId: string;
56
+ policyId?: string;
57
+ severity: EscalationSeverity;
58
+ explanation: string;
59
+ confidence?: number;
60
+ uncertaintyReason?: string;
61
+ details?: Record<string, unknown>;
62
+ }
63
+ /**
64
+ * A condition that must be met before the action can proceed.
65
+ */
66
+ export interface GovernanceCondition {
67
+ /** Dot-path to the field that needs adjustment */
68
+ field: string;
69
+ /** The value the field must have for approval. When present, condition is machine-actionable. */
70
+ requiredValue?: unknown;
71
+ /** Why this condition is required */
72
+ reason: string;
73
+ }
74
+ /**
75
+ * Escalation details when a governance check requires human review.
76
+ */
77
+ export interface GovernanceEscalation {
78
+ reason: string;
79
+ severity: EscalationSeverity;
80
+ requiresHuman: boolean;
81
+ approvalTier?: string;
82
+ }
83
+ /**
84
+ * Governance check result attached to TaskResult.
85
+ */
86
+ export interface GovernanceCheckResult {
87
+ checkId: string;
88
+ status: 'approved' | 'denied' | 'conditions' | 'escalated';
89
+ binding: 'proposed' | 'committed';
90
+ explanation: string;
91
+ mode?: GovernanceMode;
92
+ findings?: GovernanceFinding[];
93
+ conditions?: GovernanceCondition[];
94
+ escalation?: GovernanceEscalation;
95
+ expiresAt?: string;
96
+ /** Whether conditions were auto-applied by the middleware */
97
+ conditionsApplied?: boolean;
98
+ /** The modified params after conditions were applied */
99
+ modifiedParams?: Record<string, unknown>;
100
+ }
101
+ /**
102
+ * Outcome metadata from report_plan_outcome, attached to TaskResult after completion.
103
+ */
104
+ export interface GovernanceOutcome {
105
+ outcomeId: string;
106
+ status: 'accepted' | 'findings';
107
+ committedBudget?: number;
108
+ findings?: GovernanceFinding[];
109
+ planSummary?: {
110
+ totalCommitted: number;
111
+ budgetRemaining: number;
112
+ };
113
+ }
114
+ /**
115
+ * Parse a CheckGovernanceResponse into GovernanceCheckResult.
116
+ */
117
+ export declare function parseCheckResponse(response: CheckGovernanceResponse): GovernanceCheckResult;
118
+ //# sourceMappingURL=GovernanceTypes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GovernanceTypes.d.ts","sourceRoot":"","sources":["../../../src/lib/core/GovernanceTypes.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,KAAK,EAAE,uBAAuB,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAE5G;;;;GAIG;AACH,MAAM,WAAW,wBAAwB;IACvC,mCAAmC;IACnC,KAAK,EAAE,WAAW,CAAC;IACnB,6CAA6C;IAC7C,MAAM,EAAE,MAAM,CAAC;IACf,+DAA+D;IAC/D,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,kDAAkD;IAClD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,uKAAuK;IACvK,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,+JAA+J;IAC/J,cAAc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,GAAG,YAAY,GAAG,WAAW,CAAC;IAC3D,OAAO,EAAE,UAAU,GAAG,WAAW,CAAC;IAClC,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,CAAC,EAAE,cAAc,CAAC;IACtB,QAAQ,CAAC,EAAE,iBAAiB,EAAE,CAAC;IAC/B,UAAU,CAAC,EAAE,mBAAmB,EAAE,CAAC;IACnC,UAAU,CAAC,EAAE,oBAAoB,CAAC;IAClC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,6DAA6D;IAC7D,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,wDAAwD;IACxD,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC1C;AAED;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,UAAU,GAAG,UAAU,CAAC;IAChC,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,EAAE,iBAAiB,EAAE,CAAC;IAC/B,WAAW,CAAC,EAAE;QACZ,cAAc,EAAE,MAAM,CAAC;QACvB,eAAe,EAAE,MAAM,CAAC;KACzB,CAAC;CACH;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,uBAAuB,GAAG,qBAAqB,CA+B3F"}
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ /**
3
+ * Governance middleware types for buyer-side campaign governance.
4
+ *
5
+ * The governance middleware intercepts tool calls and checks them against
6
+ * a campaign governance agent before execution. It handles the full lifecycle:
7
+ * check → execute → report outcome.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.toolRequiresGovernance = toolRequiresGovernance;
11
+ exports.parseCheckResponse = parseCheckResponse;
12
+ /** Governance tools that are always excluded (infinite recursion otherwise) */
13
+ const GOVERNANCE_SELF_TOOLS = new Set(['sync_plans', 'check_governance', 'report_plan_outcome', 'get_plan_audit_logs']);
14
+ /** Tools excluded by default (governance tools + capabilities) */
15
+ const DEFAULT_EXCLUDED_TOOLS = new Set([...GOVERNANCE_SELF_TOOLS, 'get_adcp_capabilities']);
16
+ /**
17
+ * Determine whether a tool requires a governance check given the config.
18
+ */
19
+ function toolRequiresGovernance(tool, config) {
20
+ if (!config.campaign)
21
+ return false;
22
+ // Governance tools are always excluded to prevent infinite recursion
23
+ if (GOVERNANCE_SELF_TOOLS.has(tool))
24
+ return false;
25
+ if (config.scope === 'all')
26
+ return true;
27
+ if (Array.isArray(config.scope))
28
+ return config.scope.includes(tool);
29
+ if (typeof config.scope === 'function')
30
+ return config.scope(tool);
31
+ // Default: all tools except excluded set
32
+ return !DEFAULT_EXCLUDED_TOOLS.has(tool);
33
+ }
34
+ /**
35
+ * Parse a CheckGovernanceResponse into GovernanceCheckResult.
36
+ */
37
+ function parseCheckResponse(response) {
38
+ return {
39
+ checkId: response.check_id,
40
+ status: response.status,
41
+ binding: response.binding,
42
+ explanation: response.explanation,
43
+ mode: response.mode,
44
+ findings: response.findings?.map(f => ({
45
+ categoryId: f.category_id,
46
+ policyId: f.policy_id,
47
+ severity: f.severity,
48
+ explanation: f.explanation,
49
+ confidence: f.confidence,
50
+ uncertaintyReason: f.uncertainty_reason,
51
+ details: f.details,
52
+ })),
53
+ conditions: response.conditions?.map(c => ({
54
+ field: c.field,
55
+ requiredValue: c.required_value,
56
+ reason: c.reason,
57
+ })),
58
+ escalation: response.escalation
59
+ ? {
60
+ reason: response.escalation.reason,
61
+ severity: response.escalation.severity,
62
+ requiresHuman: response.escalation.requires_human,
63
+ approvalTier: response.escalation.approval_tier,
64
+ }
65
+ : undefined,
66
+ expiresAt: response.expires_at,
67
+ };
68
+ }
69
+ //# sourceMappingURL=GovernanceTypes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GovernanceTypes.js","sourceRoot":"","sources":["../../../src/lib/core/GovernanceTypes.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAuDH,wDAcC;AAyED,gDA+BC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EAAE,CAAC,CAAC,SAAS;YACrB,QAAQ,EAAE,CAAC,CAAC,QAAQ;YACpB,WAAW,EAAE,CAAC,CAAC,WAAW;YAC1B,UAAU,EAAE,CAAC,CAAC,UAAU;YACxB,iBAAiB,EAAE,CAAC,CAAC,kBAAkB;YACvC,OAAO,EAAE,CAAC,CAAC,OAAO;SACnB,CAAC,CAAC;QACH,UAAU,EAAE,QAAQ,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;YACzC,KAAK,EAAE,CAAC,CAAC,KAAK;YACd,aAAa,EAAE,CAAC,CAAC,cAAc;YAC/B,MAAM,EAAE,CAAC,CAAC,MAAM;SACjB,CAAC,CAAC;QACH,UAAU,EAAE,QAAQ,CAAC,UAAU;YAC7B,CAAC,CAAC;gBACE,MAAM,EAAE,QAAQ,CAAC,UAAU,CAAC,MAAM;gBAClC,QAAQ,EAAE,QAAQ,CAAC,UAAU,CAAC,QAAQ;gBACtC,aAAa,EAAE,QAAQ,CAAC,UAAU,CAAC,cAAc;gBACjD,YAAY,EAAE,QAAQ,CAAC,UAAU,CAAC,aAAa;aAChD;YACH,CAAC,CAAC,SAAS;QACb,SAAS,EAAE,QAAQ,CAAC,UAAU;KAC/B,CAAC;AACJ,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import type { AgentConfig } from '../types';
2
- import type { GetProductsRequest, GetProductsResponse, ListCreativeFormatsRequest, ListCreativeFormatsResponse, CreateMediaBuyRequest, UpdateMediaBuyRequest, UpdateMediaBuyResponse, SyncCreativesRequest, SyncCreativesResponse, ListCreativesRequest, ListCreativesResponse, GetMediaBuysRequest, GetMediaBuysResponse, GetMediaBuyDeliveryRequest, GetMediaBuyDeliveryResponse, ProvidePerformanceFeedbackRequest, ProvidePerformanceFeedbackResponse, GetSignalsRequest, GetSignalsResponse, ActivateSignalRequest, ActivateSignalResponse, PreviewCreativeRequest, PreviewCreativeResponse, Format, GetAdCPCapabilitiesRequest, GetAdCPCapabilitiesResponse } from '../types/tools.generated';
2
+ import type { GetProductsRequest, GetProductsResponse, ListCreativeFormatsRequest, ListCreativeFormatsResponse, CreateMediaBuyRequest, UpdateMediaBuyRequest, UpdateMediaBuyResponse, SyncCreativesRequest, SyncCreativesResponse, ListCreativesRequest, ListCreativesResponse, GetMediaBuysRequest, GetMediaBuysResponse, GetMediaBuyDeliveryRequest, GetMediaBuyDeliveryResponse, ProvidePerformanceFeedbackRequest, ProvidePerformanceFeedbackResponse, GetSignalsRequest, GetSignalsResponse, ActivateSignalRequest, ActivateSignalResponse, PreviewCreativeRequest, PreviewCreativeResponse, Format, GetAdCPCapabilitiesRequest, GetAdCPCapabilitiesResponse, SyncPlansRequest, SyncPlansResponse, GetPlanAuditLogsRequest, GetPlanAuditLogsResponse, OutcomeType } from '../types/tools.generated';
3
3
  import type { MCPWebhookPayload, CreateMediaBuyResponse } from '../types/core.generated';
4
4
  import type { Task as A2ATask, TaskStatusUpdateEvent } from '@a2a-js/sdk';
5
5
  import type { InputHandler, TaskOptions, TaskResult, ConversationConfig, TaskInfo } from './ConversationTypes';
@@ -91,6 +91,8 @@ export interface SingleAgentClientConfig extends ConversationConfig {
91
91
  */
92
92
  logSchemaViolations?: boolean;
93
93
  };
94
+ /** Governance configuration for buyer-side campaign governance */
95
+ governance?: import('./GovernanceTypes').GovernanceConfig;
94
96
  }
95
97
  /**
96
98
  * Internal single-agent client implementation
@@ -438,6 +440,38 @@ export declare class SingleAgentClient {
438
440
  * @param options - Task execution options
439
441
  */
440
442
  activateSignal(params: ActivateSignalRequest, inputHandler?: InputHandler, options?: TaskOptions): Promise<TaskResult<ActivateSignalResponse>>;
443
+ /**
444
+ * Sync campaign plans to a governance agent.
445
+ * Plans define authorized parameters: budget, channels, flight dates, markets, policies, delegations.
446
+ *
447
+ * Uses the governance agent from config.governance.campaign.agent by default.
448
+ * Pass an explicit agent via options.agent to override.
449
+ */
450
+ syncPlans(params: SyncPlansRequest, inputHandler?: InputHandler, options?: TaskOptions & {
451
+ agent?: AgentConfig;
452
+ }): Promise<TaskResult<SyncPlansResponse>>;
453
+ /**
454
+ * Get governance audit logs for one or more plans.
455
+ * Returns budget state, channel allocation, per-campaign breakdown, and audit trail.
456
+ *
457
+ * Uses the governance agent from config.governance.campaign.agent by default.
458
+ * Pass an explicit agent via options.agent to override.
459
+ */
460
+ getPlanAuditLogs(params: GetPlanAuditLogsRequest, options?: TaskOptions & {
461
+ agent?: AgentConfig;
462
+ }): Promise<TaskResult<GetPlanAuditLogsResponse>>;
463
+ /**
464
+ * Report a governance outcome for an async task that has resolved.
465
+ *
466
+ * Use this when a task returned status 'submitted' or 'working' and
467
+ * later resolves via polling or webhooks. The checkId is available
468
+ * on the original TaskResult at result.governance.checkId.
469
+ */
470
+ reportGovernanceOutcome(checkId: string, outcome: OutcomeType, sellerResponse?: Record<string, unknown>, error?: {
471
+ code?: string;
472
+ message: string;
473
+ }): Promise<import('./GovernanceTypes').GovernanceOutcome | undefined>;
474
+ private getGovernanceAgent;
441
475
  /**
442
476
  * Get AdCP capabilities
443
477
  *