@adport/core 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Yannick Westermann
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,494 @@
1
+ import { z } from 'zod';
2
+
3
+ type AdportErrorCode = 'POLICY_VIOLATION' | 'PENDING_NOT_FOUND' | 'PENDING_EXPIRED' | 'PENDING_MISMATCH' | 'PROVIDER_ERROR' | 'INVALID_INPUT' | 'NOT_CONNECTED' | 'UNKNOWN_TOOL';
4
+ declare class AdportError extends Error {
5
+ readonly code: AdportErrorCode;
6
+ readonly details?: unknown | undefined;
7
+ constructor(code: AdportErrorCode, message: string, details?: unknown | undefined);
8
+ toJSON(): {
9
+ error: AdportErrorCode;
10
+ message: string;
11
+ details: unknown;
12
+ };
13
+ }
14
+
15
+ /**
16
+ * All adport state (credentials, pending operations, audit log, policy) lives
17
+ * under this directory. ADPORT_HOME overrides it — used by tests and CI.
18
+ */
19
+ declare function adportHome(): string;
20
+
21
+ declare const METRICS: readonly ["spend", "impressions", "clicks", "conversions", "conversion_value", "ctr", "cpc", "cpm", "cpa", "roas"];
22
+ type MetricName = (typeof METRICS)[number];
23
+ declare const ENTITY_LEVELS: readonly ["account", "campaign", "ad_group", "ad"];
24
+ type EntityLevel = (typeof ENTITY_LEVELS)[number];
25
+ declare const DATE_PRESETS: readonly ["today", "yesterday", "last_7_days", "last_30_days", "this_month"];
26
+ type DatePreset = (typeof DATE_PRESETS)[number];
27
+ /** ISO dates, inclusive on both ends. */
28
+ interface DateRange {
29
+ start: string;
30
+ end: string;
31
+ }
32
+ interface NormalizedQuery {
33
+ /** Provider ids to query; omit for all connected providers. */
34
+ providers?: string[];
35
+ /** Account ids to include; omit for all accounts of the selected providers. */
36
+ accountIds?: string[];
37
+ level: EntityLevel;
38
+ metrics: MetricName[];
39
+ dateRange: DateRange | DatePreset;
40
+ limit?: number;
41
+ }
42
+ interface ReportRow {
43
+ provider: string;
44
+ accountId: string;
45
+ entity: {
46
+ level: EntityLevel;
47
+ id: string;
48
+ name: string;
49
+ status?: string;
50
+ };
51
+ metrics: Partial<Record<MetricName, number>>;
52
+ }
53
+ interface Report {
54
+ rows: ReportRow[];
55
+ truncated?: boolean;
56
+ }
57
+ declare function resolveDateRange(range: DateRange | DatePreset, now?: Date): DateRange;
58
+ declare function rangeDayCount(range: DateRange): number;
59
+
60
+ interface Account {
61
+ provider: string;
62
+ id: string;
63
+ name: string;
64
+ currency?: string;
65
+ status?: string;
66
+ }
67
+ type WriteKind = 'create' | 'update' | 'remove';
68
+ interface WriteOperation {
69
+ /** Tool name that produced this operation — part of the audit trail. */
70
+ tool: string;
71
+ provider: string;
72
+ accountId: string;
73
+ kind: WriteKind;
74
+ payload: Record<string, unknown>;
75
+ }
76
+ interface BudgetDelta {
77
+ /** Human-readable target, e.g. "campaign c1 daily budget". */
78
+ target: string;
79
+ fromMicros?: number;
80
+ toMicros: number;
81
+ }
82
+ interface WritePreview {
83
+ summary: string;
84
+ changes: string[];
85
+ /** Adjustments the guard forced (e.g. "status coerced to PAUSED"). Never silent. */
86
+ coercions: string[];
87
+ budgetDeltas: BudgetDelta[];
88
+ /** True when the platform validated the operation server-side (dry run). */
89
+ serverValidated: boolean;
90
+ }
91
+ interface WriteResult {
92
+ applied: true;
93
+ resourceIds: string[];
94
+ details?: unknown;
95
+ }
96
+ /** Policy-derived constraints handed to providers on every preview/apply. */
97
+ interface WriteGuard {
98
+ forcePausedCreation: boolean;
99
+ }
100
+ interface ProviderCapabilities {
101
+ serverDryRun: boolean;
102
+ }
103
+ /** A ready-to-call tool invocation (flows through the normal validate→apply gate). */
104
+ interface StandardAction {
105
+ tool: string;
106
+ input: Record<string, unknown>;
107
+ }
108
+ /**
109
+ * Provider-declared mappings for cross-platform actions the audit harness can
110
+ * propose (each provider knows its own tool names and native status values).
111
+ */
112
+ interface StandardActions {
113
+ pauseCampaign?: (accountId: string, campaignId: string) => StandardAction;
114
+ }
115
+ interface AdProvider {
116
+ readonly id: string;
117
+ capabilities(): ProviderCapabilities;
118
+ listAccounts(): Promise<Account[]>;
119
+ report(query: NormalizedQuery): Promise<Report>;
120
+ /** Dry-run the operation (server-side where supported, client-side diff otherwise). */
121
+ previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview>;
122
+ /** Execute the operation for real. Only the policy engine may call this. */
123
+ applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult>;
124
+ /** Optional cross-platform action mappings used by the recommendation harness. */
125
+ standardActions?(): StandardActions;
126
+ }
127
+ declare class ProviderRegistry {
128
+ private providers;
129
+ register(provider: AdProvider): void;
130
+ get(id: string): AdProvider;
131
+ list(): AdProvider[];
132
+ }
133
+
134
+ type FindingSeverity = 'info' | 'warn' | 'critical';
135
+ type FindingStatus = 'open' | 'dismissed' | 'applied';
136
+ /**
137
+ * A single audit finding. Deliberately NOT aggregated into any kind of
138
+ * "account score": interaction-based scores are gameable and distrusted
139
+ * (Google's optimization score reaches 100% by dismissing everything).
140
+ */
141
+ interface AuditFinding {
142
+ /** Deterministic: ruleId:provider:accountId:entityId — reruns update, not duplicate. */
143
+ id: string;
144
+ ruleId: string;
145
+ severity: FindingSeverity;
146
+ provider: string;
147
+ accountId: string;
148
+ entity: {
149
+ level: string;
150
+ id: string;
151
+ name: string;
152
+ status?: string;
153
+ };
154
+ title: string;
155
+ detail: string;
156
+ recommendation: string;
157
+ /** Ready-to-run tool call; flows through the normal validate→apply gate. */
158
+ proposedAction?: StandardAction;
159
+ metrics: Partial<Record<MetricName, number>>;
160
+ dateRange: DateRange;
161
+ status: FindingStatus;
162
+ createdAt: string;
163
+ updatedAt: string;
164
+ }
165
+ /** What a rule emits; the runner adds ids, timestamps, and status. */
166
+ interface RuleFinding {
167
+ entity: AuditFinding['entity'];
168
+ severity: FindingSeverity;
169
+ title: string;
170
+ detail: string;
171
+ recommendation: string;
172
+ proposedAction?: StandardAction;
173
+ metrics: AuditFinding['metrics'];
174
+ }
175
+ interface RuleContext {
176
+ provider: string;
177
+ accountId: string;
178
+ /** Campaign-level normalized rows for this account over the range. */
179
+ rows: ReportRow[];
180
+ range: DateRange;
181
+ /** Provider-declared action mappings (may be empty). */
182
+ actions: StandardActions;
183
+ /** Pack-level thresholds, overridable per run. */
184
+ config: Record<string, number>;
185
+ }
186
+ interface Rule {
187
+ id: string;
188
+ title: string;
189
+ description: string;
190
+ evaluate(ctx: RuleContext): RuleFinding[];
191
+ }
192
+ /** OPA-style pack: rules are data-driven and decoupled from provider code. */
193
+ interface RulePack {
194
+ name: string;
195
+ version: string;
196
+ rules: Rule[];
197
+ /** Default thresholds; merged with per-run overrides. */
198
+ defaults: Record<string, number>;
199
+ }
200
+
201
+ declare const corePerformancePack: RulePack;
202
+
203
+ /**
204
+ * Findings persist on disk with their approval lifecycle — the durable side of
205
+ * the recommendation harness: a recommendation can wait for a human decision
206
+ * across restarts, indefinitely, at zero cost.
207
+ */
208
+ declare class FindingsStore {
209
+ private readonly dir;
210
+ constructor(dir?: string);
211
+ private file;
212
+ list(filter?: {
213
+ status?: FindingStatus;
214
+ provider?: string;
215
+ }): Promise<AuditFinding[]>;
216
+ get(id: string): Promise<AuditFinding | undefined>;
217
+ save(finding: AuditFinding): Promise<void>;
218
+ setStatus(id: string, status: FindingStatus): Promise<AuditFinding>;
219
+ }
220
+
221
+ interface AuditRunOptions {
222
+ provider?: string;
223
+ accountIds?: string[];
224
+ dateRange?: DateRange | DatePreset;
225
+ packs?: RulePack[];
226
+ configOverrides?: Record<string, number>;
227
+ }
228
+ interface AuditRunResult {
229
+ findings: AuditFinding[];
230
+ counts: {
231
+ critical: number;
232
+ warn: number;
233
+ info: number;
234
+ };
235
+ evaluatedAccounts: number;
236
+ range: DateRange;
237
+ }
238
+ /**
239
+ * The audit engine (OPA pattern): providers supply normalized state as input,
240
+ * rule packs supply the checks, the runner evaluates and returns structured
241
+ * findings. Rules never call provider APIs directly.
242
+ */
243
+ declare class AuditRunner {
244
+ private readonly providers;
245
+ private readonly store;
246
+ constructor(providers: ProviderRegistry, store?: FindingsStore);
247
+ run(options?: AuditRunOptions): Promise<AuditRunResult>;
248
+ }
249
+
250
+ type CredentialSource = 'byo' | 'broker';
251
+ interface CredentialRecord {
252
+ provider: string;
253
+ source: CredentialSource;
254
+ /** Provider-specific key/value secrets (tokens, client ids, ...). */
255
+ data: Record<string, string>;
256
+ createdAt: string;
257
+ updatedAt: string;
258
+ }
259
+ /**
260
+ * File-backed credential store: ${ADPORT_HOME}/credentials.json, chmod 600.
261
+ * OS keychain support may come later; the interface is deliberately async.
262
+ */
263
+ declare class CredentialStore {
264
+ private readonly dir;
265
+ constructor(dir?: string);
266
+ private file;
267
+ private read;
268
+ private write;
269
+ get(provider: string): Promise<CredentialRecord | undefined>;
270
+ list(): Promise<CredentialRecord[]>;
271
+ set(record: Omit<CredentialRecord, 'createdAt' | 'updatedAt'>): Promise<CredentialRecord>;
272
+ delete(provider: string): Promise<boolean>;
273
+ }
274
+
275
+ interface AuditEntry {
276
+ ts: string;
277
+ /** 'note' records external/manual changes made outside adport's write path. */
278
+ event: 'validated' | 'applied' | 'rejected' | 'note';
279
+ provider: string;
280
+ tool: string;
281
+ accountId: string;
282
+ pendingId?: string;
283
+ summary: string;
284
+ details?: unknown;
285
+ }
286
+ /** Append-only JSONL, one file per month: ${ADPORT_HOME}/audit/audit-YYYY-MM.jsonl */
287
+ declare class AuditLog {
288
+ private readonly dir;
289
+ constructor(dir?: string);
290
+ private file;
291
+ append(entry: Omit<AuditEntry, 'ts'>): Promise<void>;
292
+ /** Most recent entries, newest last. Reads across all monthly files. */
293
+ read(limit?: number): Promise<AuditEntry[]>;
294
+ }
295
+
296
+ interface PendingOperation {
297
+ id: string;
298
+ provider: string;
299
+ opHash: string;
300
+ op: WriteOperation;
301
+ preview: WritePreview;
302
+ createdAt: string;
303
+ expiresAt: string;
304
+ }
305
+ /**
306
+ * File-backed store so validate and apply can happen in different processes
307
+ * (CLI invocations, MCP server restarts).
308
+ */
309
+ declare class PendingStore {
310
+ private readonly dir;
311
+ constructor(dir?: string);
312
+ private file;
313
+ put(op: PendingOperation): Promise<void>;
314
+ get(id: string): Promise<PendingOperation | undefined>;
315
+ delete(id: string): Promise<void>;
316
+ /** Remove expired entries. Called opportunistically; never throws on races. */
317
+ sweep(now?: Date): Promise<void>;
318
+ }
319
+
320
+ declare const policySchema: z.ZodObject<{
321
+ /** Writes must be validated (dry-run) before they can be applied. */
322
+ require_validation: z.ZodDefault<z.ZodBoolean>;
323
+ /** Created campaigns/ad groups/ads are coerced to PAUSED. */
324
+ paused_creation: z.ZodDefault<z.ZodBoolean>;
325
+ /** Reject budget changes exceeding this percentage of the current value. null = no cap. */
326
+ max_budget_delta_pct: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
327
+ /** Reject any budget set above this absolute value (micros). null = no cap. */
328
+ max_daily_budget_micros: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
329
+ /** Account ids that no write may touch. */
330
+ protected_accounts: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
331
+ /** How long a validated pending operation stays applicable. */
332
+ pending_ttl_minutes: z.ZodDefault<z.ZodNumber>;
333
+ }, "strip", z.ZodTypeAny, {
334
+ require_validation: boolean;
335
+ paused_creation: boolean;
336
+ max_budget_delta_pct: number | null;
337
+ max_daily_budget_micros: number | null;
338
+ protected_accounts: string[];
339
+ pending_ttl_minutes: number;
340
+ }, {
341
+ require_validation?: boolean | undefined;
342
+ paused_creation?: boolean | undefined;
343
+ max_budget_delta_pct?: number | null | undefined;
344
+ max_daily_budget_micros?: number | null | undefined;
345
+ protected_accounts?: string[] | undefined;
346
+ pending_ttl_minutes?: number | undefined;
347
+ }>;
348
+ type Policy = z.infer<typeof policySchema>;
349
+ declare const DEFAULT_POLICY: Policy;
350
+ interface LoadedPolicy {
351
+ policy: Policy;
352
+ /** Where the policy came from: a file path or "defaults". */
353
+ source: string;
354
+ }
355
+ /**
356
+ * Resolution order: explicit path → $ADPORT_POLICY → ./adport.policy.yaml →
357
+ * ${ADPORT_HOME}/policy.yaml → built-in defaults.
358
+ * A file that exists but fails validation is a hard error — never silently
359
+ * fall back to weaker rails.
360
+ */
361
+ declare function loadPolicy(explicitPath?: string): Promise<LoadedPolicy>;
362
+
363
+ interface ValidationOutcome {
364
+ pendingOperationId: string;
365
+ preview: WritePreview;
366
+ expiresAt: string;
367
+ }
368
+ interface ApplyOutcome {
369
+ result: WriteResult;
370
+ preview: WritePreview;
371
+ }
372
+ declare function hashOperation(op: WriteOperation): string;
373
+ /**
374
+ * The single gate for all mutations. Enforces the two-step contract:
375
+ * validate() dry-runs the operation and issues a pending-operation id;
376
+ * apply() only executes an operation whose id, hash, and expiry check out.
377
+ */
378
+ declare class PolicyEngine {
379
+ readonly policy: Policy;
380
+ private readonly pending;
381
+ private readonly audit;
382
+ constructor(policy: Policy, pending?: PendingStore, audit?: AuditLog);
383
+ guard(): WriteGuard;
384
+ validate(provider: AdProvider, op: WriteOperation): Promise<ValidationOutcome>;
385
+ apply(provider: AdProvider, op: WriteOperation, pendingId: string): Promise<ApplyOutcome>;
386
+ private checkStaticPolicy;
387
+ private checkBudgetPolicy;
388
+ private reject;
389
+ }
390
+
391
+ interface ToolAnnotations {
392
+ readOnly?: boolean;
393
+ destructive?: boolean;
394
+ }
395
+ interface ToolContext {
396
+ providers: ProviderRegistry;
397
+ engine: PolicyEngine;
398
+ credentials: CredentialStore;
399
+ /** Set by createContext; lets tools invoke other tools (e.g. recommendation_apply). */
400
+ registry?: ToolRegistry;
401
+ }
402
+ interface AnyToolDefinition {
403
+ name: string;
404
+ /** Grouping key used for config-based enable/disable ("core", "mock", "google", ...). */
405
+ namespace: string;
406
+ description: string;
407
+ input: z.ZodObject<z.ZodRawShape>;
408
+ annotations: ToolAnnotations;
409
+ handler: (input: never, ctx: ToolContext) => Promise<unknown>;
410
+ }
411
+ declare function defineTool<S extends z.ZodObject<z.ZodRawShape>>(def: {
412
+ name: string;
413
+ namespace: string;
414
+ description: string;
415
+ input: S;
416
+ annotations?: ToolAnnotations;
417
+ handler: (input: z.infer<S>, ctx: ToolContext) => Promise<unknown>;
418
+ }): AnyToolDefinition;
419
+ declare class ToolRegistry {
420
+ private tools;
421
+ register(tools: AnyToolDefinition | AnyToolDefinition[]): void;
422
+ list(): AnyToolDefinition[];
423
+ get(name: string): AnyToolDefinition;
424
+ call(name: string, rawInput: unknown, ctx: ToolContext): Promise<unknown>;
425
+ }
426
+
427
+ declare function auditTools(): AnyToolDefinition[];
428
+
429
+ /**
430
+ * Wrap a provider mutation as a two-step (validate → apply) tool.
431
+ * This is the only sanctioned way to expose a write; the handler always goes
432
+ * through the policy engine, so rails and audit logging cannot be skipped.
433
+ */
434
+ declare function guardedWriteTool<S extends z.ZodObject<z.ZodRawShape>>(def: {
435
+ name: string;
436
+ namespace: string;
437
+ description: string;
438
+ provider: string;
439
+ kind: WriteKind;
440
+ payload: S;
441
+ destructive?: boolean;
442
+ }): AnyToolDefinition;
443
+
444
+ declare function builtinTools(): AnyToolDefinition[];
445
+
446
+ interface MockCampaign {
447
+ id: string;
448
+ name: string;
449
+ status: 'ENABLED' | 'PAUSED' | 'REMOVED';
450
+ dailyBudgetMicros: number;
451
+ }
452
+ /**
453
+ * In-memory provider for tests, demos, and trying adport without credentials.
454
+ * Deterministic: same inputs always produce the same report numbers.
455
+ */
456
+ declare class MockProvider implements AdProvider {
457
+ readonly id = "mock";
458
+ private accounts;
459
+ capabilities(): ProviderCapabilities;
460
+ standardActions(): StandardActions;
461
+ listAccounts(): Promise<Account[]>;
462
+ listCampaigns(accountId: string): MockCampaign[];
463
+ report(query: NormalizedQuery): Promise<Report>;
464
+ previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview>;
465
+ applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult>;
466
+ private account;
467
+ private campaign;
468
+ /** Compute preview and applier together so dry-run and apply can never drift. */
469
+ private plan;
470
+ }
471
+ declare function mockTools(): AnyToolDefinition[];
472
+
473
+ interface ProviderModule {
474
+ provider: AdProvider;
475
+ tools: AnyToolDefinition[];
476
+ }
477
+ interface CreateContextOptions {
478
+ policyPath?: string;
479
+ /** Extra providers with their tools (e.g. the Google provider from @adport/provider-google). */
480
+ providerModules?: ProviderModule[];
481
+ /**
482
+ * Include the credential-free mock provider. Defaults to true when no real
483
+ * provider module is passed, so a fresh install always has something to try.
484
+ */
485
+ includeMock?: boolean;
486
+ }
487
+ interface AdportRuntime {
488
+ ctx: ToolContext;
489
+ registry: ToolRegistry;
490
+ policySource: string;
491
+ }
492
+ declare function createContext(options?: CreateContextOptions): Promise<AdportRuntime>;
493
+
494
+ export { type Account, type AdProvider, AdportError, type AdportErrorCode, type AdportRuntime, type AnyToolDefinition, type ApplyOutcome, type AuditEntry, type AuditFinding, AuditLog, type AuditRunOptions, type AuditRunResult, AuditRunner, type BudgetDelta, type CreateContextOptions, type CredentialRecord, type CredentialSource, CredentialStore, DATE_PRESETS, DEFAULT_POLICY, type DatePreset, type DateRange, ENTITY_LEVELS, type EntityLevel, type FindingSeverity, type FindingStatus, FindingsStore, type LoadedPolicy, METRICS, type MetricName, MockProvider, type NormalizedQuery, type PendingOperation, PendingStore, type Policy, PolicyEngine, type ProviderCapabilities, type ProviderModule, ProviderRegistry, type Report, type ReportRow, type Rule, type RuleContext, type RuleFinding, type RulePack, type StandardAction, type StandardActions, type ToolAnnotations, type ToolContext, ToolRegistry, type ValidationOutcome, type WriteGuard, type WriteKind, type WriteOperation, type WritePreview, type WriteResult, adportHome, auditTools, builtinTools, corePerformancePack, createContext, defineTool, guardedWriteTool, hashOperation, loadPolicy, mockTools, policySchema, rangeDayCount, resolveDateRange };