@adport/provider-openai 0.0.0-stage → 0.11.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 +201 -0
- package/README.md +10 -2
- package/dist/index.d.ts +143 -0
- package/dist/index.js +645 -0
- package/dist/index.js.map +1 -0
- package/package.json +45 -3
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @adport/provider-openai
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
OpenAI Ads API provider (ads in ChatGPT) for adport.
|
|
4
|
+
|
|
5
|
+
This package is part of [Adport](https://github.com/ynnickw/adport), an open-source control plane for paid media. Most users should install the [`adport` CLI](https://www.npmjs.com/package/adport), which assembles the provider modules and shared policy engine.
|
|
6
|
+
|
|
7
|
+
Requires Node.js 22.13 or newer. Advertising mutations must use the shared preview/apply policy gate. Provider credentials and approvals are configured separately; package installation does not grant platform access.
|
|
8
|
+
|
|
9
|
+
[Documentation](https://github.com/ynnickw/adport/blob/main/docs/README.md) · [Contributing](https://github.com/ynnickw/adport/blob/main/CONTRIBUTING.md) · [Security](https://github.com/ynnickw/adport/blob/main/SECURITY.md)
|
|
10
|
+
|
|
11
|
+
Licensed under Apache-2.0.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { AdProvider, StandardActions, Account, NormalizedQuery, Report, WriteOperation, WriteGuard, WritePreview, WriteResult, AnyToolDefinition, CredentialStore, ProviderModule } from '@adport/core';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
declare const OPENAI_ADS_API_BASE = "https://api.ads.openai.com/v1/";
|
|
5
|
+
interface OpenAIAdsCredentials {
|
|
6
|
+
/** Advertiser API key from Ads Manager settings; each key is bound to one ad account. */
|
|
7
|
+
apiKey: string;
|
|
8
|
+
}
|
|
9
|
+
type Params = Record<string, string | string[]>;
|
|
10
|
+
declare class OpenAIAdsClient {
|
|
11
|
+
private readonly credentials;
|
|
12
|
+
private readonly fetchImpl;
|
|
13
|
+
constructor(credentials: OpenAIAdsCredentials, fetchImpl?: typeof fetch);
|
|
14
|
+
get<T>(path: string, schema: z.ZodType<T>, params?: Params): Promise<T>;
|
|
15
|
+
post<T>(path: string, schema: z.ZodType<T>, body?: unknown, idempotencyKey?: string): Promise<T>;
|
|
16
|
+
/** Follows `after` cursors until `has_more` is false or `max` rows were read. */
|
|
17
|
+
list<T extends z.ZodType>(path: string, item: T, params?: Params, max?: number): Promise<{
|
|
18
|
+
items: z.infer<T>[];
|
|
19
|
+
truncated: boolean;
|
|
20
|
+
}>;
|
|
21
|
+
private parse;
|
|
22
|
+
private url;
|
|
23
|
+
private redact;
|
|
24
|
+
private send;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
declare class OpenAIAdsProvider implements AdProvider {
|
|
28
|
+
private readonly client;
|
|
29
|
+
readonly id = "openai";
|
|
30
|
+
private account?;
|
|
31
|
+
constructor(client: OpenAIAdsClient);
|
|
32
|
+
/** API access for read tools (conversion insights is a read-only POST); callers check the account first. */
|
|
33
|
+
get api(): OpenAIAdsClient;
|
|
34
|
+
capabilities(): {
|
|
35
|
+
serverDryRun: boolean;
|
|
36
|
+
};
|
|
37
|
+
standardActions(): StandardActions;
|
|
38
|
+
/** Advertiser API keys are bound to exactly one ad account. */
|
|
39
|
+
private keyAccount;
|
|
40
|
+
private assertAccount;
|
|
41
|
+
listAccounts(): Promise<Account[]>;
|
|
42
|
+
accountMetadata(accountId: string): Promise<{
|
|
43
|
+
currency: string;
|
|
44
|
+
timezone: string;
|
|
45
|
+
}>;
|
|
46
|
+
listCampaigns(accountId: string): Promise<{
|
|
47
|
+
items: {
|
|
48
|
+
[x: string]: unknown;
|
|
49
|
+
id: string;
|
|
50
|
+
name: string;
|
|
51
|
+
status: string;
|
|
52
|
+
budget: {
|
|
53
|
+
[x: string]: unknown;
|
|
54
|
+
lifetime_spend_limit_micros?: number | undefined;
|
|
55
|
+
daily_spend_limit_micros?: number | undefined;
|
|
56
|
+
};
|
|
57
|
+
description?: string | null | undefined;
|
|
58
|
+
start_time?: number | null | undefined;
|
|
59
|
+
end_time?: number | null | undefined;
|
|
60
|
+
bidding_type?: string | undefined;
|
|
61
|
+
objective?: string | undefined;
|
|
62
|
+
}[];
|
|
63
|
+
truncated: boolean;
|
|
64
|
+
}>;
|
|
65
|
+
listAdGroups(accountId: string, campaignId?: string): Promise<{
|
|
66
|
+
items: {
|
|
67
|
+
[x: string]: unknown;
|
|
68
|
+
id: string;
|
|
69
|
+
name: string;
|
|
70
|
+
status: string;
|
|
71
|
+
}[];
|
|
72
|
+
truncated: boolean;
|
|
73
|
+
}>;
|
|
74
|
+
listAds(accountId: string, adGroupId?: string): Promise<{
|
|
75
|
+
items: {
|
|
76
|
+
[x: string]: unknown;
|
|
77
|
+
id: string;
|
|
78
|
+
name: string;
|
|
79
|
+
status: string;
|
|
80
|
+
review_status?: string | undefined;
|
|
81
|
+
}[];
|
|
82
|
+
truncated: boolean;
|
|
83
|
+
}>;
|
|
84
|
+
report(query: NormalizedQuery): Promise<Report>;
|
|
85
|
+
private row;
|
|
86
|
+
previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview>;
|
|
87
|
+
applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult>;
|
|
88
|
+
private plan;
|
|
89
|
+
private planCreate;
|
|
90
|
+
private planBudget;
|
|
91
|
+
private planStatus;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
declare function openaiTools(provider: OpenAIAdsProvider): AnyToolDefinition[];
|
|
95
|
+
|
|
96
|
+
declare const accountSchema: z.ZodObject<{
|
|
97
|
+
id: z.ZodString;
|
|
98
|
+
name: z.ZodString;
|
|
99
|
+
status: z.ZodOptional<z.ZodString>;
|
|
100
|
+
timezone: z.ZodString;
|
|
101
|
+
currency_code: z.ZodString;
|
|
102
|
+
}, z.core.$loose>;
|
|
103
|
+
declare const campaignSchema: z.ZodObject<{
|
|
104
|
+
id: z.ZodString;
|
|
105
|
+
name: z.ZodString;
|
|
106
|
+
status: z.ZodString;
|
|
107
|
+
description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
108
|
+
start_time: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
109
|
+
end_time: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
110
|
+
budget: z.ZodObject<{
|
|
111
|
+
lifetime_spend_limit_micros: z.ZodOptional<z.ZodNumber>;
|
|
112
|
+
daily_spend_limit_micros: z.ZodOptional<z.ZodNumber>;
|
|
113
|
+
}, z.core.$loose>;
|
|
114
|
+
bidding_type: z.ZodOptional<z.ZodString>;
|
|
115
|
+
objective: z.ZodOptional<z.ZodString>;
|
|
116
|
+
}, z.core.$loose>;
|
|
117
|
+
type OpenAICampaign = z.infer<typeof campaignSchema>;
|
|
118
|
+
declare const insightRowSchema: z.ZodObject<{
|
|
119
|
+
id: z.ZodString;
|
|
120
|
+
impressions: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
121
|
+
clicks: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
122
|
+
spend: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
123
|
+
conversions: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
124
|
+
order_created_attributed_sales: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
125
|
+
ad_account_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
126
|
+
ad_account_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
127
|
+
campaign_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
128
|
+
campaign_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
129
|
+
campaign_status: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
130
|
+
ad_group_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
131
|
+
ad_group_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
132
|
+
ad_group_status: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
133
|
+
ad_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
134
|
+
ad_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
135
|
+
ad_status: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
136
|
+
}, z.core.$loose>;
|
|
137
|
+
|
|
138
|
+
declare function openaiCredentialsFromData(data: Record<string, string> | undefined): OpenAIAdsCredentials | undefined;
|
|
139
|
+
declare function openaiEnvironmentData(): Record<string, string>;
|
|
140
|
+
declare function resolveOpenAICredentials(store: CredentialStore): Promise<OpenAIAdsCredentials | undefined>;
|
|
141
|
+
declare function createOpenAIModule(store: CredentialStore): Promise<ProviderModule | undefined>;
|
|
142
|
+
|
|
143
|
+
export { OPENAI_ADS_API_BASE, OpenAIAdsClient, type OpenAIAdsCredentials, OpenAIAdsProvider, type OpenAICampaign, accountSchema, campaignSchema, createOpenAIModule, insightRowSchema, openaiCredentialsFromData, openaiEnvironmentData, openaiTools, resolveOpenAICredentials };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,645 @@
|
|
|
1
|
+
// src/client.ts
|
|
2
|
+
import { AdportError } from "@adport/core";
|
|
3
|
+
|
|
4
|
+
// src/schemas.ts
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
var openaiId = z.string().regex(/^[A-Za-z0-9_-]{1,128}$/);
|
|
7
|
+
var openaiStatus = z.enum(["active", "paused"]);
|
|
8
|
+
var openaiBudgetMicros = z.number().int().min(1e6).max(Number.MAX_SAFE_INTEGER);
|
|
9
|
+
var unixSeconds = z.number().int().nonnegative();
|
|
10
|
+
var schedule = z.iso.datetime({ offset: true }).refine((value) => {
|
|
11
|
+
const seconds = Date.parse(value) / 1e3;
|
|
12
|
+
return seconds >= 946684800 && seconds <= 4102444800;
|
|
13
|
+
}, "Schedule must be between 2000-01-01 and 2100-01-01");
|
|
14
|
+
var metric = z.number().finite().nullable().optional();
|
|
15
|
+
var accountSchema = z.looseObject({
|
|
16
|
+
id: openaiId,
|
|
17
|
+
name: z.string(),
|
|
18
|
+
status: z.string().optional(),
|
|
19
|
+
timezone: z.string(),
|
|
20
|
+
currency_code: z.string()
|
|
21
|
+
});
|
|
22
|
+
var budgetSchema = z.looseObject({
|
|
23
|
+
lifetime_spend_limit_micros: z.number().int().nonnegative().optional(),
|
|
24
|
+
daily_spend_limit_micros: z.number().int().nonnegative().optional()
|
|
25
|
+
});
|
|
26
|
+
var campaignSchema = z.looseObject({
|
|
27
|
+
id: openaiId,
|
|
28
|
+
name: z.string(),
|
|
29
|
+
status: z.string(),
|
|
30
|
+
description: z.string().nullable().optional(),
|
|
31
|
+
start_time: unixSeconds.nullable().optional(),
|
|
32
|
+
end_time: unixSeconds.nullable().optional(),
|
|
33
|
+
budget: budgetSchema,
|
|
34
|
+
bidding_type: z.string().optional(),
|
|
35
|
+
objective: z.string().optional()
|
|
36
|
+
});
|
|
37
|
+
var adGroupSchema = z.looseObject({ id: openaiId, name: z.string(), status: z.string() });
|
|
38
|
+
var adSchema = z.looseObject({ id: openaiId, name: z.string(), status: z.string(), review_status: z.string().optional() });
|
|
39
|
+
var listEnvelope = (item) => z.looseObject({
|
|
40
|
+
data: z.array(item),
|
|
41
|
+
has_more: z.boolean(),
|
|
42
|
+
last_id: z.string().nullable().optional()
|
|
43
|
+
});
|
|
44
|
+
var insightRowSchema = z.looseObject({
|
|
45
|
+
id: z.string(),
|
|
46
|
+
impressions: metric,
|
|
47
|
+
clicks: metric,
|
|
48
|
+
spend: metric,
|
|
49
|
+
conversions: metric,
|
|
50
|
+
order_created_attributed_sales: metric,
|
|
51
|
+
ad_account_id: z.string().nullable().optional(),
|
|
52
|
+
ad_account_name: z.string().nullable().optional(),
|
|
53
|
+
campaign_id: z.string().nullable().optional(),
|
|
54
|
+
campaign_name: z.string().nullable().optional(),
|
|
55
|
+
campaign_status: z.string().nullable().optional(),
|
|
56
|
+
ad_group_id: z.string().nullable().optional(),
|
|
57
|
+
ad_group_name: z.string().nullable().optional(),
|
|
58
|
+
ad_group_status: z.string().nullable().optional(),
|
|
59
|
+
ad_id: z.string().nullable().optional(),
|
|
60
|
+
ad_name: z.string().nullable().optional(),
|
|
61
|
+
ad_status: z.string().nullable().optional()
|
|
62
|
+
});
|
|
63
|
+
var listCampaignsSchema = z.object({ account_id: openaiId });
|
|
64
|
+
var listAdGroupsSchema = z.object({ account_id: openaiId, campaign_id: openaiId.optional() });
|
|
65
|
+
var listAdsSchema = z.object({ account_id: openaiId, ad_group_id: openaiId.optional() });
|
|
66
|
+
var createCampaignSchema = z.object({
|
|
67
|
+
name: z.string().min(3).max(1e3).refine((value) => value.trim().length > 0, "Name cannot be blank"),
|
|
68
|
+
description: z.string().max(1e3).optional(),
|
|
69
|
+
status: openaiStatus.default("paused"),
|
|
70
|
+
lifetime_spend_limit_micros: openaiBudgetMicros.optional(),
|
|
71
|
+
daily_spend_limit_micros: openaiBudgetMicros.optional(),
|
|
72
|
+
bidding_type: z.enum(["impressions", "clicks", "conversions"]).optional(),
|
|
73
|
+
objective: z.enum(["reach", "clicks", "conversions"]).optional(),
|
|
74
|
+
billing_event_type: z.enum(["impression", "click"]).optional(),
|
|
75
|
+
conversion_event_setting_ids: z.array(openaiId).length(1).optional(),
|
|
76
|
+
start_time: schedule.optional(),
|
|
77
|
+
end_time: schedule.optional(),
|
|
78
|
+
target_countries: z.array(z.string().regex(/^[A-Z]{2}$/)).min(1).max(250).refine((ids) => new Set(ids).size === ids.length, "Use unique countries").optional(),
|
|
79
|
+
target_location_ids: z.array(z.string().regex(/^\d+$/)).min(1).max(250).refine((ids) => new Set(ids).size === ids.length, "Use unique location IDs").optional()
|
|
80
|
+
}).strict().refine((input) => Number(input.lifetime_spend_limit_micros !== void 0) + Number(input.daily_spend_limit_micros !== void 0) === 1, "Set exactly one lifetime or daily spend limit").refine((input) => input.objective !== void 0 === (input.billing_event_type !== void 0), "Supply objective and billing_event_type together, or omit both and use bidding_type").refine((input) => input.bidding_type === "conversions" || input.objective === "conversions" ? Boolean(input.conversion_event_setting_ids) : !input.conversion_event_setting_ids, {
|
|
81
|
+
message: "Conversion bidding requires exactly one conversion_event_setting_id; other bidding types must omit it"
|
|
82
|
+
});
|
|
83
|
+
var setCampaignStatusSchema = z.object({ campaign_id: openaiId, status: openaiStatus });
|
|
84
|
+
var setAdGroupStatusSchema = z.object({ ad_group_id: openaiId, status: openaiStatus });
|
|
85
|
+
var setAdStatusSchema = z.object({ ad_id: openaiId, status: openaiStatus });
|
|
86
|
+
var setBudgetSchema = z.object({
|
|
87
|
+
campaign_id: openaiId,
|
|
88
|
+
field: z.enum(["daily_spend_limit_micros", "lifetime_spend_limit_micros"]).default("daily_spend_limit_micros"),
|
|
89
|
+
budget_micros: openaiBudgetMicros
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
// src/client.ts
|
|
93
|
+
var OPENAI_ADS_API_BASE = "https://api.ads.openai.com/v1/";
|
|
94
|
+
var ORIGIN = "https://api.ads.openai.com";
|
|
95
|
+
var OpenAIAdsClient = class {
|
|
96
|
+
constructor(credentials, fetchImpl = fetch) {
|
|
97
|
+
this.credentials = credentials;
|
|
98
|
+
this.fetchImpl = fetchImpl;
|
|
99
|
+
if (!credentials.apiKey.trim()) throw new AdportError("INVALID_INPUT", "openai: API key is empty");
|
|
100
|
+
}
|
|
101
|
+
credentials;
|
|
102
|
+
fetchImpl;
|
|
103
|
+
async get(path, schema, params = {}) {
|
|
104
|
+
return this.parse(await this.send(this.url(path, params), "GET"), schema);
|
|
105
|
+
}
|
|
106
|
+
async post(path, schema, body, idempotencyKey) {
|
|
107
|
+
return this.parse(await this.send(this.url(path), "POST", body, idempotencyKey), schema);
|
|
108
|
+
}
|
|
109
|
+
/** Follows `after` cursors until `has_more` is false or `max` rows were read. */
|
|
110
|
+
async list(path, item, params = {}, max = 1e4) {
|
|
111
|
+
const envelope = listEnvelope(item), items = [], seen = /* @__PURE__ */ new Set();
|
|
112
|
+
let after;
|
|
113
|
+
while (true) {
|
|
114
|
+
const page = await this.get(path, envelope, { ...params, ...after ? { after } : {} });
|
|
115
|
+
items.push(...page.data);
|
|
116
|
+
if (!page.has_more) return { items: items.slice(0, max), truncated: items.length > max };
|
|
117
|
+
if (items.length >= max) return { items: items.slice(0, max), truncated: true };
|
|
118
|
+
const next = page.last_id ?? void 0;
|
|
119
|
+
if (!next || seen.has(next) || seen.size >= 1e3) throw new AdportError("PROVIDER_ERROR", "openai: pagination did not terminate; refusing incomplete results");
|
|
120
|
+
seen.add(next);
|
|
121
|
+
after = next;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
parse(data, schema) {
|
|
125
|
+
const parsed = schema.safeParse(data);
|
|
126
|
+
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "openai: malformed API response", { response_issues: parsed.error.issues.slice(0, 20).map((issue) => ({ path: issue.path, code: issue.code })) });
|
|
127
|
+
return parsed.data;
|
|
128
|
+
}
|
|
129
|
+
url(path, params = {}) {
|
|
130
|
+
const url = new URL(path, OPENAI_ADS_API_BASE);
|
|
131
|
+
if (url.origin !== ORIGIN || !url.pathname.startsWith("/v1/") || url.username || url.password || url.hash) throw new AdportError("INVALID_INPUT", "openai: invalid API URL");
|
|
132
|
+
for (const [key, value] of Object.entries(params)) {
|
|
133
|
+
if (Array.isArray(value)) for (const entry of value) url.searchParams.append(`${key}[]`, entry);
|
|
134
|
+
else url.searchParams.set(key, value);
|
|
135
|
+
}
|
|
136
|
+
return url;
|
|
137
|
+
}
|
|
138
|
+
redact(value) {
|
|
139
|
+
return value.replaceAll(this.credentials.apiKey, "[redacted]").replace(/Bearer\s+\S+/gi, "Bearer [redacted]").slice(0, 2e3);
|
|
140
|
+
}
|
|
141
|
+
async send(url, method, body, idempotencyKey) {
|
|
142
|
+
const response = await this.fetchImpl(url.href, {
|
|
143
|
+
method,
|
|
144
|
+
headers: {
|
|
145
|
+
authorization: `Bearer ${this.credentials.apiKey}`,
|
|
146
|
+
accept: "application/json",
|
|
147
|
+
...body !== void 0 ? { "content-type": "application/json" } : {},
|
|
148
|
+
...idempotencyKey ? { "idempotency-key": idempotencyKey } : {}
|
|
149
|
+
},
|
|
150
|
+
...body !== void 0 ? { body: JSON.stringify(body) } : {},
|
|
151
|
+
redirect: "error",
|
|
152
|
+
signal: AbortSignal.timeout(3e4)
|
|
153
|
+
});
|
|
154
|
+
const raw = await response.json().catch(() => void 0);
|
|
155
|
+
if (!response.ok) {
|
|
156
|
+
const advice = response.status === 401 ? " Use an active Advertiser API key from Ads Manager settings." : response.status === 429 ? " Rate limited (600 requests/minute per endpoint, 1,200 overall); retry later." : "";
|
|
157
|
+
const message = errorMessage(raw);
|
|
158
|
+
throw new AdportError("PROVIDER_ERROR", `openai: HTTP ${response.status}.${advice}${message ? ` ${this.redact(message)}` : ""}`, { http_status: response.status });
|
|
159
|
+
}
|
|
160
|
+
return raw;
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
function errorMessage(raw) {
|
|
164
|
+
if (!raw || typeof raw !== "object") return void 0;
|
|
165
|
+
const record = raw;
|
|
166
|
+
const error = record.error;
|
|
167
|
+
if (typeof error === "string") return error;
|
|
168
|
+
if (error && typeof error === "object" && typeof error.message === "string") return error.message;
|
|
169
|
+
return typeof record.message === "string" ? record.message : void 0;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// src/provider.ts
|
|
173
|
+
import { randomUUID } from "crypto";
|
|
174
|
+
import { z as z2 } from "zod";
|
|
175
|
+
import {
|
|
176
|
+
AdportError as AdportError2,
|
|
177
|
+
resolveDateRange
|
|
178
|
+
} from "@adport/core";
|
|
179
|
+
var LEVEL = { account: "ad_account", campaign: "campaign", ad_group: "ad_group", ad: "ad" };
|
|
180
|
+
var LEVEL_METRICS = ["impressions", "clicks", "spend"];
|
|
181
|
+
var ACCOUNT_METRICS = ["conversions", "order_created_attributed_sales"];
|
|
182
|
+
var STATUS_TOOLS = {
|
|
183
|
+
openai_set_campaign_status: { path: "campaigns", label: "campaign", schema: setCampaignStatusSchema, key: "campaign_id", entity: campaignSchema },
|
|
184
|
+
openai_set_ad_group_status: { path: "ad_groups", label: "ad group", schema: setAdGroupStatusSchema, key: "ad_group_id", entity: adGroupSchema },
|
|
185
|
+
openai_set_ad_status: { path: "ads", label: "ad", schema: setAdStatusSchema, key: "ad_id", entity: adSchema }
|
|
186
|
+
};
|
|
187
|
+
var OpenAIAdsProvider = class {
|
|
188
|
+
constructor(client) {
|
|
189
|
+
this.client = client;
|
|
190
|
+
}
|
|
191
|
+
client;
|
|
192
|
+
id = "openai";
|
|
193
|
+
account;
|
|
194
|
+
/** API access for read tools (conversion insights is a read-only POST); callers check the account first. */
|
|
195
|
+
get api() {
|
|
196
|
+
return this.client;
|
|
197
|
+
}
|
|
198
|
+
capabilities() {
|
|
199
|
+
return { serverDryRun: false };
|
|
200
|
+
}
|
|
201
|
+
standardActions() {
|
|
202
|
+
return { pauseCampaign: (accountId, campaignId) => ({
|
|
203
|
+
tool: "openai_set_campaign_status",
|
|
204
|
+
input: { account_id: accountId, campaign_id: campaignId, status: "paused" }
|
|
205
|
+
}) };
|
|
206
|
+
}
|
|
207
|
+
/** Advertiser API keys are bound to exactly one ad account. */
|
|
208
|
+
keyAccount() {
|
|
209
|
+
this.account ??= this.client.get("ad_account", accountSchema).catch((error) => {
|
|
210
|
+
this.account = void 0;
|
|
211
|
+
throw error;
|
|
212
|
+
});
|
|
213
|
+
return this.account;
|
|
214
|
+
}
|
|
215
|
+
async assertAccount(accountId) {
|
|
216
|
+
const account = await this.keyAccount();
|
|
217
|
+
if (openaiId.parse(accountId) !== account.id) throw new AdportError2("INVALID_INPUT", "openai: account_id does not match the ad account of the connected API key");
|
|
218
|
+
return account;
|
|
219
|
+
}
|
|
220
|
+
async listAccounts() {
|
|
221
|
+
const account = await this.keyAccount();
|
|
222
|
+
return [{ provider: this.id, id: account.id, name: account.name, currency: account.currency_code, timezone: account.timezone, ...account.status ? { status: account.status } : {} }];
|
|
223
|
+
}
|
|
224
|
+
async accountMetadata(accountId) {
|
|
225
|
+
const account = await this.assertAccount(accountId);
|
|
226
|
+
return { currency: account.currency_code, timezone: account.timezone };
|
|
227
|
+
}
|
|
228
|
+
async listCampaigns(accountId) {
|
|
229
|
+
await this.assertAccount(accountId);
|
|
230
|
+
return this.client.list("campaigns", campaignSchema, { limit: "500" });
|
|
231
|
+
}
|
|
232
|
+
async listAdGroups(accountId, campaignId) {
|
|
233
|
+
await this.assertAccount(accountId);
|
|
234
|
+
return this.client.list("ad_groups", adGroupSchema, { limit: "500", ...campaignId ? { campaign_id: campaignId } : {} });
|
|
235
|
+
}
|
|
236
|
+
async listAds(accountId, adGroupId) {
|
|
237
|
+
await this.assertAccount(accountId);
|
|
238
|
+
return this.client.list("ads", adSchema, { limit: "500", ...adGroupId ? { ad_group_id: adGroupId } : {} });
|
|
239
|
+
}
|
|
240
|
+
async report(query) {
|
|
241
|
+
const range = resolveDateRange(query.dateRange);
|
|
242
|
+
const limit = query.limit ?? 1e3;
|
|
243
|
+
if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError2("INVALID_INPUT", "openai: report limit must be a positive integer");
|
|
244
|
+
const account = await this.keyAccount();
|
|
245
|
+
const accountIds = [...new Set(query.accountIds ?? [account.id])];
|
|
246
|
+
const rows = [];
|
|
247
|
+
let truncated = false;
|
|
248
|
+
for (const id of accountIds) {
|
|
249
|
+
await this.assertAccount(id);
|
|
250
|
+
const level = LEVEL[query.level];
|
|
251
|
+
const entityFields = query.level === "account" ? ["ad_account.id", "ad_account.name"] : [`${level}.id`, `${level}.name`, `${level}.status`];
|
|
252
|
+
const { items, truncated: more } = await this.client.list("ad_account/insights", insightRowSchema, {
|
|
253
|
+
aggregation_level: level,
|
|
254
|
+
time_granularity: "none",
|
|
255
|
+
limit: "2000",
|
|
256
|
+
// date_range is inclusive and defaults to the ad account's time zone.
|
|
257
|
+
time_ranges: [JSON.stringify({ type: "date_range", since: range.start, until: range.end })],
|
|
258
|
+
fields: [...entityFields, ...LEVEL_METRICS.map((metric2) => `${level}.${metric2}`), ...ACCOUNT_METRICS]
|
|
259
|
+
}, limit + 1);
|
|
260
|
+
truncated ||= more;
|
|
261
|
+
for (const row of items) rows.push(this.row(row, query.level, account, query.metrics));
|
|
262
|
+
}
|
|
263
|
+
return { rows: rows.slice(0, limit), ...truncated || rows.length > limit ? { truncated: true } : {} };
|
|
264
|
+
}
|
|
265
|
+
row(row, level, account, metrics) {
|
|
266
|
+
const prefix = LEVEL[level];
|
|
267
|
+
const entityId = level === "account" ? row.ad_account_id ?? account.id : row[`${prefix}_id`];
|
|
268
|
+
if (typeof entityId !== "string" || !entityId) throw new AdportError2("PROVIDER_ERROR", `openai: insights row is missing ${prefix}_id`);
|
|
269
|
+
const name = level === "account" ? row.ad_account_name ?? account.name : row[`${prefix}_name`];
|
|
270
|
+
const status = level === "account" ? account.status : row[`${prefix}_status`];
|
|
271
|
+
return {
|
|
272
|
+
provider: this.id,
|
|
273
|
+
accountId: account.id,
|
|
274
|
+
currency: account.currency_code,
|
|
275
|
+
entity: { level, id: entityId, name: typeof name === "string" && name ? name : entityId, ...typeof status === "string" ? { status } : {} },
|
|
276
|
+
metrics: normalize(row, metrics)
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
async previewWrite(op, guard) {
|
|
280
|
+
const { execute: _execute, ...preview } = await this.plan(op, guard);
|
|
281
|
+
return { ...preview, serverValidated: false };
|
|
282
|
+
}
|
|
283
|
+
async applyWrite(op, guard) {
|
|
284
|
+
return (await this.plan(op, guard)).execute();
|
|
285
|
+
}
|
|
286
|
+
async plan(op, guard) {
|
|
287
|
+
if (op.provider !== this.id) throw new AdportError2("INVALID_INPUT", "openai: provider mismatch");
|
|
288
|
+
await this.assertAccount(op.accountId);
|
|
289
|
+
if (op.tool === "openai_create_campaign" && op.kind === "create") return this.planCreate(op, guard);
|
|
290
|
+
if (op.tool === "openai_set_budget" && op.kind === "update") return this.planBudget(op);
|
|
291
|
+
if (op.kind === "update" && Object.hasOwn(STATUS_TOOLS, op.tool)) return this.planStatus(op);
|
|
292
|
+
throw new AdportError2("INVALID_INPUT", `openai: unsupported write ${op.tool}`);
|
|
293
|
+
}
|
|
294
|
+
planCreate(op, guard) {
|
|
295
|
+
const input = createCampaignSchema.parse(op.payload);
|
|
296
|
+
const start = input.start_time ? Math.floor(Date.parse(input.start_time) / 1e3) : void 0;
|
|
297
|
+
const end = input.end_time ? Math.floor(Date.parse(input.end_time) / 1e3) : void 0;
|
|
298
|
+
if (start !== void 0 && end !== void 0 && end <= start) throw new AdportError2("INVALID_INPUT", "openai: end_time must be after start_time");
|
|
299
|
+
const status = guard.forcePausedCreation ? "paused" : input.status;
|
|
300
|
+
const budget = {
|
|
301
|
+
...input.lifetime_spend_limit_micros !== void 0 ? { lifetime_spend_limit_micros: input.lifetime_spend_limit_micros } : {},
|
|
302
|
+
...input.daily_spend_limit_micros !== void 0 ? { daily_spend_limit_micros: input.daily_spend_limit_micros } : {}
|
|
303
|
+
};
|
|
304
|
+
const body = {
|
|
305
|
+
name: input.name,
|
|
306
|
+
status,
|
|
307
|
+
budget,
|
|
308
|
+
...input.description !== void 0 ? { description: input.description } : {},
|
|
309
|
+
...input.bidding_type ? { bidding_type: input.bidding_type } : {},
|
|
310
|
+
...input.objective ? { objective: input.objective } : {},
|
|
311
|
+
...input.billing_event_type ? { billing_event_type: input.billing_event_type } : {},
|
|
312
|
+
...input.conversion_event_setting_ids ? { conversion_event_setting_ids: input.conversion_event_setting_ids } : {},
|
|
313
|
+
...start !== void 0 ? { start_time: start } : {},
|
|
314
|
+
...end !== void 0 ? { end_time: end } : {},
|
|
315
|
+
...input.target_location_ids || input.target_countries ? { targeting: { locations: {
|
|
316
|
+
...input.target_location_ids ? { include: input.target_location_ids.map((id) => ({ id })) } : {},
|
|
317
|
+
...input.target_countries ? { countries: input.target_countries } : {}
|
|
318
|
+
} } } : {}
|
|
319
|
+
};
|
|
320
|
+
return {
|
|
321
|
+
summary: `Create OpenAI Ads campaign "${input.name}"`,
|
|
322
|
+
changes: [`+ ${JSON.stringify(body)}`],
|
|
323
|
+
coercions: status !== input.status ? ["status coerced to paused by policy (paused_creation)"] : [],
|
|
324
|
+
budgetDeltas: Object.entries(budget).map(([field, value]) => ({ target: `new campaign ${field}`, toMicros: value })),
|
|
325
|
+
execute: async () => {
|
|
326
|
+
const created = await this.client.post("campaigns", campaignSchema, body, randomUUID());
|
|
327
|
+
const mismatch = !matchesCampaignReceipt(created, body);
|
|
328
|
+
if (mismatch) throw new AdportError2("PROVIDER_ERROR", "openai: campaign creation receipt mismatch; reconcile before retrying", { resource_ids: [created.id] });
|
|
329
|
+
return { applied: true, resourceIds: [created.id] };
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
async planBudget(op) {
|
|
334
|
+
const input = setBudgetSchema.parse(op.payload);
|
|
335
|
+
const current = await this.client.get(`campaigns/${input.campaign_id}`, campaignSchema);
|
|
336
|
+
if (current.id !== input.campaign_id) throw new AdportError2("PROVIDER_ERROR", "openai: campaign response does not match the requested campaign");
|
|
337
|
+
const previous = current.budget[input.field];
|
|
338
|
+
const otherField = input.field === "daily_spend_limit_micros" ? "lifetime_spend_limit_micros" : "daily_spend_limit_micros";
|
|
339
|
+
if (current.budget[otherField] !== void 0) throw new AdportError2("INVALID_INPUT", "openai: daily and lifetime campaign budgets are mutually exclusive; update the existing budget type instead of adding or replacing the other limit");
|
|
340
|
+
const budget = { ...pickBudget(current.budget), [input.field]: input.budget_micros };
|
|
341
|
+
return {
|
|
342
|
+
summary: `Change OpenAI Ads campaign "${current.name}" ${input.field}`,
|
|
343
|
+
changes: [`~ ${current.id} ${input.field}: ${previous ?? "unset"} \u2192 ${input.budget_micros}`],
|
|
344
|
+
fieldChanges: [{ field: input.field, before: previous === void 0 ? "unset" : String(previous), after: String(input.budget_micros) }],
|
|
345
|
+
coercions: [],
|
|
346
|
+
budgetDeltas: [{ target: `campaign ${current.id} ${input.field}`, ...previous !== void 0 ? { fromMicros: previous } : {}, toMicros: input.budget_micros }],
|
|
347
|
+
execute: async () => {
|
|
348
|
+
const updated = await this.client.post(`campaigns/${current.id}`, campaignSchema, { budget });
|
|
349
|
+
if (updated.id !== current.id || updated.budget[otherField] !== void 0 || !matchesRequested(updated.budget, budget)) throw new AdportError2("PROVIDER_ERROR", "openai: campaign budget receipt mismatch; reconcile before retrying", { resource_ids: [current.id] });
|
|
350
|
+
return { applied: true, resourceIds: [current.id] };
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
async planStatus(op) {
|
|
355
|
+
const spec = STATUS_TOOLS[op.tool];
|
|
356
|
+
const input = spec.schema.parse(op.payload);
|
|
357
|
+
const id = input[spec.key], status = input.status;
|
|
358
|
+
const current = await this.client.get(`${spec.path}/${id}`, spec.entity);
|
|
359
|
+
if (current.id !== id) throw new AdportError2("PROVIDER_ERROR", `openai: ${spec.label} response does not match the requested ${spec.label}`);
|
|
360
|
+
return {
|
|
361
|
+
summary: `${status === "active" ? "Activate" : "Pause"} OpenAI Ads ${spec.label} "${current.name}"`,
|
|
362
|
+
changes: [`~ ${id} status: ${current.status} \u2192 ${status}`],
|
|
363
|
+
fieldChanges: [{ field: "status", before: current.status, after: status }],
|
|
364
|
+
coercions: [],
|
|
365
|
+
budgetDeltas: [],
|
|
366
|
+
execute: async () => {
|
|
367
|
+
const updated = await this.client.post(`${spec.path}/${id}/${status === "active" ? "activate" : "pause"}`, spec.entity);
|
|
368
|
+
if (updated.id !== id || updated.status !== status) throw new AdportError2("PROVIDER_ERROR", `openai: ${spec.label} status receipt mismatch; reconcile before retrying`, { resource_ids: [id] });
|
|
369
|
+
return { applied: true, resourceIds: [id] };
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
function matchesCampaignReceipt(actual, expected) {
|
|
375
|
+
const expectedBudget = expected.budget;
|
|
376
|
+
const actualBudget = pickBudget(actual.budget);
|
|
377
|
+
if (Object.keys(actualBudget).length !== Object.keys(expectedBudget).length || !matchesRequested(actualBudget, expectedBudget)) return false;
|
|
378
|
+
const requestedTargeting = expected.targeting;
|
|
379
|
+
if (!requestedTargeting?.locations.countries) return matchesRequested(actual, expected);
|
|
380
|
+
const { targeting: _targeting, ...otherFields } = expected;
|
|
381
|
+
if (!matchesRequested(actual, otherFields)) return false;
|
|
382
|
+
const targeting = actual.targeting;
|
|
383
|
+
if (!targeting || Object.keys(targeting).some((key) => key !== "locations")) return false;
|
|
384
|
+
const locations = targeting.locations;
|
|
385
|
+
if (!locations) return false;
|
|
386
|
+
const requested = requestedTargeting.locations;
|
|
387
|
+
if (locations.countries !== void 0) return matchesRequested(locations.countries, requested.countries) && matchesRequested(locations.include ?? [], requested.include ?? []);
|
|
388
|
+
const parsed = z2.array(z2.object({ id: z2.string(), type: z2.string().optional(), country_code: z2.string().nullable().optional() })).safeParse(locations.include);
|
|
389
|
+
if (!parsed.success) return false;
|
|
390
|
+
const included = parsed.data, ids = requested.include?.map((location) => location.id) ?? [], countries = requested.countries;
|
|
391
|
+
return new Set(included.map((location) => location.id)).size === included.length && ids.every((id) => included.some((location) => location.id === id)) && countries.every((code) => included.filter((location) => location.type === "country" && location.country_code === code).length === 1) && included.every((location) => ids.includes(location.id) || location.type === "country" && countries.includes(location.country_code ?? ""));
|
|
392
|
+
}
|
|
393
|
+
function matchesRequested(actual, expected) {
|
|
394
|
+
if (Array.isArray(expected)) return Array.isArray(actual) && actual.length === expected.length && expected.every((value) => actual.some((candidate) => matchesRequested(candidate, value)));
|
|
395
|
+
if (expected && typeof expected === "object") return Boolean(actual && typeof actual === "object" && Object.entries(expected).every(([key, value]) => matchesRequested(actual[key], value)));
|
|
396
|
+
return actual === expected;
|
|
397
|
+
}
|
|
398
|
+
function pickBudget(budget) {
|
|
399
|
+
return {
|
|
400
|
+
...budget.lifetime_spend_limit_micros !== void 0 ? { lifetime_spend_limit_micros: budget.lifetime_spend_limit_micros } : {},
|
|
401
|
+
...budget.daily_spend_limit_micros !== void 0 ? { daily_spend_limit_micros: budget.daily_spend_limit_micros } : {}
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
function normalize(row, metrics) {
|
|
405
|
+
const mapped = {};
|
|
406
|
+
const fields = { spend: "spend", impressions: "impressions", clicks: "clicks", conversions: "conversions", conversion_value: "order_created_attributed_sales" };
|
|
407
|
+
for (const [metric2, field] of Object.entries(fields)) {
|
|
408
|
+
const value = row[field];
|
|
409
|
+
if (typeof value === "number") mapped[metric2] = value;
|
|
410
|
+
}
|
|
411
|
+
for (const [metric2, numerator, denominator, factor] of [
|
|
412
|
+
["ctr", "clicks", "impressions", 100],
|
|
413
|
+
["cpc", "spend", "clicks", 1],
|
|
414
|
+
["cpm", "spend", "impressions", 1e3],
|
|
415
|
+
["cpa", "spend", "conversions", 1],
|
|
416
|
+
["roas", "conversion_value", "spend", 1]
|
|
417
|
+
]) {
|
|
418
|
+
if (mapped[numerator] !== void 0 && mapped[denominator]) mapped[metric2] = mapped[numerator] / mapped[denominator] * factor;
|
|
419
|
+
}
|
|
420
|
+
return Object.fromEntries(metrics.filter((metric2) => mapped[metric2] !== void 0).map((metric2) => [metric2, mapped[metric2]]));
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// src/tools.ts
|
|
424
|
+
import { defineTool as defineTool2, guardedWriteTool } from "@adport/core";
|
|
425
|
+
|
|
426
|
+
// src/conversions.ts
|
|
427
|
+
import { AdportError as AdportError3, defineTool } from "@adport/core";
|
|
428
|
+
import { z as z3 } from "zod";
|
|
429
|
+
var isoDate = z3.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
|
430
|
+
var sourceSchema = z3.looseObject({ id: z3.string(), name: z3.string(), client_type: z3.string(), pixel_id: z3.string() });
|
|
431
|
+
var eventSettingSchema = z3.looseObject({
|
|
432
|
+
id: z3.string(),
|
|
433
|
+
name: z3.string(),
|
|
434
|
+
event_type: z3.string(),
|
|
435
|
+
custom_event_name: z3.string().nullable(),
|
|
436
|
+
attribution_window_days: z3.number().int(),
|
|
437
|
+
source_ids: z3.array(z3.string()),
|
|
438
|
+
campaigns: z3.array(z3.looseObject({ id: z3.string(), name: z3.string() })),
|
|
439
|
+
archived: z3.boolean()
|
|
440
|
+
});
|
|
441
|
+
var receivedEventSchema = z3.object({
|
|
442
|
+
data_source_id: z3.string(),
|
|
443
|
+
event_type: z3.string(),
|
|
444
|
+
custom_event_name: z3.string().nullable(),
|
|
445
|
+
action_source: z3.string().nullable(),
|
|
446
|
+
event_timestamp_ms: z3.number().int(),
|
|
447
|
+
received_at_ms: z3.number().int(),
|
|
448
|
+
api_channel: z3.string()
|
|
449
|
+
});
|
|
450
|
+
var conversionRowSchema = z3.looseObject({
|
|
451
|
+
entity_id: z3.string(),
|
|
452
|
+
conversions: z3.number().int(),
|
|
453
|
+
date: z3.string().optional(),
|
|
454
|
+
country: z3.string().optional(),
|
|
455
|
+
device: z3.string().optional(),
|
|
456
|
+
click_through_conversions: z3.number().int().optional(),
|
|
457
|
+
view_through_conversions: z3.number().int().optional(),
|
|
458
|
+
order_created_attributed_sales: z3.string().nullable().optional(),
|
|
459
|
+
order_created_attributed_sales_currency: z3.string().optional(),
|
|
460
|
+
attributed_events: z3.array(z3.looseObject({ entity_id: z3.string(), event_name: z3.string(), event_kind: z3.string(), attributed_event_count: z3.number().int() })).optional()
|
|
461
|
+
});
|
|
462
|
+
var insightsSchema = z3.looseObject({ data: z3.array(conversionRowSchema), count: z3.number().int(), account_currency: z3.string().optional() });
|
|
463
|
+
var conversionInsightsInput = z3.object({
|
|
464
|
+
account_id: openaiId,
|
|
465
|
+
since: isoDate.describe("First day, account time zone"),
|
|
466
|
+
until: isoDate.describe("Last day, inclusive, account time zone"),
|
|
467
|
+
aggregation_level: z3.enum(["campaign", "ad_group", "ad"]).default("campaign"),
|
|
468
|
+
entity_ids: z3.array(openaiId).min(1).max(500).optional().describe("Report per entity; omit for account totals"),
|
|
469
|
+
time_granularity: z3.enum(["none", "daily"]).default("none"),
|
|
470
|
+
breakdown: z3.enum(["device", "country"]).optional(),
|
|
471
|
+
attribution_window_days: z3.union([z3.literal(7), z3.literal(14), z3.literal(30)]).optional(),
|
|
472
|
+
view_through_attribution_window_days: z3.union([z3.literal(0), z3.literal(1)]).optional(),
|
|
473
|
+
include_events: z3.boolean().default(false).describe("Add attributed standard and custom events per row"),
|
|
474
|
+
event_names: z3.array(z3.string().min(1).max(256)).min(1).max(500).optional().describe("Requires include_events")
|
|
475
|
+
}).refine((input) => input.since <= input.until, "since must not be after until").refine((input) => !input.event_names || input.include_events, "event_names requires include_events");
|
|
476
|
+
async function conversionInsights(provider, input) {
|
|
477
|
+
await provider.accountMetadata(input.account_id);
|
|
478
|
+
const body = {
|
|
479
|
+
aggregation_level: input.aggregation_level,
|
|
480
|
+
time_granularity: input.time_granularity,
|
|
481
|
+
time_ranges: [JSON.stringify({ type: "date_range", since: input.since, until: input.until })],
|
|
482
|
+
...input.entity_ids ? { entity_ids: input.entity_ids, group_by_entity: true } : { group_by_entity: false },
|
|
483
|
+
...input.breakdown ? { breakdown: input.breakdown } : {},
|
|
484
|
+
...input.attribution_window_days !== void 0 ? { attribution_window_days: input.attribution_window_days } : {},
|
|
485
|
+
...input.view_through_attribution_window_days !== void 0 ? { view_through_attribution_window_days: input.view_through_attribution_window_days } : {},
|
|
486
|
+
...input.include_events ? { include: ["attributed_events"] } : {},
|
|
487
|
+
...input.event_names ? { event_names: input.event_names } : {}
|
|
488
|
+
};
|
|
489
|
+
const result = await provider.api.post("conversions/insights", insightsSchema, body);
|
|
490
|
+
if (result.count !== result.data.length) throw new AdportError3("PROVIDER_ERROR", "openai: conversion insights count does not match the returned rows");
|
|
491
|
+
return result;
|
|
492
|
+
}
|
|
493
|
+
function openaiConversionTools(provider) {
|
|
494
|
+
return [
|
|
495
|
+
defineTool({
|
|
496
|
+
name: "openai_conversion_sources",
|
|
497
|
+
namespace: "openai",
|
|
498
|
+
description: "List OpenAI Ads conversion data sources (pixel and Conversions API) with their pixel_id.",
|
|
499
|
+
input: z3.object({ account_id: openaiId }),
|
|
500
|
+
annotations: { readOnly: true },
|
|
501
|
+
handler: async (input) => {
|
|
502
|
+
await provider.accountMetadata(input.account_id);
|
|
503
|
+
return provider.api.list("conversions/pixels", sourceSchema, { limit: "500" });
|
|
504
|
+
}
|
|
505
|
+
}),
|
|
506
|
+
defineTool({
|
|
507
|
+
name: "openai_conversion_event_settings",
|
|
508
|
+
namespace: "openai",
|
|
509
|
+
description: "List OpenAI Ads conversion events (goals): event type, attribution window, sources and the campaigns optimizing on each.",
|
|
510
|
+
input: z3.object({ account_id: openaiId }),
|
|
511
|
+
annotations: { readOnly: true },
|
|
512
|
+
handler: async (input) => {
|
|
513
|
+
await provider.accountMetadata(input.account_id);
|
|
514
|
+
return provider.api.list("conversions/event_settings", eventSettingSchema, { limit: "500" });
|
|
515
|
+
}
|
|
516
|
+
}),
|
|
517
|
+
defineTool({
|
|
518
|
+
name: "openai_conversion_events",
|
|
519
|
+
namespace: "openai",
|
|
520
|
+
description: "Show the latest events received by one conversion source (type, channel, event and receipt times) to check that browser or server tracking arrives. Event payloads are not returned.",
|
|
521
|
+
input: z3.object({ account_id: openaiId, pixel_id: z3.string().min(1).max(256).describe("pixel_id from openai_conversion_sources"), limit: z3.number().int().min(1).max(50).default(50) }),
|
|
522
|
+
annotations: { readOnly: true },
|
|
523
|
+
handler: async (input) => {
|
|
524
|
+
await provider.accountMetadata(input.account_id);
|
|
525
|
+
const result = await provider.api.get("conversions/events", z3.looseObject({ data: z3.array(receivedEventSchema) }), { pid: input.pixel_id, limit: String(input.limit) });
|
|
526
|
+
return { pixel_id: input.pixel_id, events: result.data.map((event) => ({
|
|
527
|
+
...event,
|
|
528
|
+
event_time: new Date(event.event_timestamp_ms).toISOString(),
|
|
529
|
+
received_at: new Date(event.received_at_ms).toISOString()
|
|
530
|
+
})) };
|
|
531
|
+
}
|
|
532
|
+
}),
|
|
533
|
+
defineTool({
|
|
534
|
+
name: "openai_conversion_insights",
|
|
535
|
+
namespace: "openai",
|
|
536
|
+
description: "OpenAI Ads goal conversions (click-through and view-through), attributed sales and optional per-event counts for a date range, per entity or for the whole account.",
|
|
537
|
+
input: conversionInsightsInput,
|
|
538
|
+
annotations: { readOnly: true },
|
|
539
|
+
handler: (input) => conversionInsights(provider, input)
|
|
540
|
+
})
|
|
541
|
+
];
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// src/tools.ts
|
|
545
|
+
function openaiTools(provider) {
|
|
546
|
+
return [
|
|
547
|
+
...openaiConversionTools(provider),
|
|
548
|
+
defineTool2({
|
|
549
|
+
name: "openai_list_campaigns",
|
|
550
|
+
namespace: "openai",
|
|
551
|
+
description: "List OpenAI Ads (ChatGPT ads) campaigns in the connected ad account, with status and budgets in micros.",
|
|
552
|
+
input: listCampaignsSchema,
|
|
553
|
+
annotations: { readOnly: true },
|
|
554
|
+
handler: (input) => provider.listCampaigns(input.account_id)
|
|
555
|
+
}),
|
|
556
|
+
defineTool2({
|
|
557
|
+
name: "openai_ad_groups",
|
|
558
|
+
namespace: "openai",
|
|
559
|
+
description: "List OpenAI Ads ad groups, optionally for one campaign.",
|
|
560
|
+
input: listAdGroupsSchema,
|
|
561
|
+
annotations: { readOnly: true },
|
|
562
|
+
handler: (input) => provider.listAdGroups(input.account_id, input.campaign_id)
|
|
563
|
+
}),
|
|
564
|
+
defineTool2({
|
|
565
|
+
name: "openai_ads",
|
|
566
|
+
namespace: "openai",
|
|
567
|
+
description: "List OpenAI Ads ads with status and review status, optionally for one ad group.",
|
|
568
|
+
input: listAdsSchema,
|
|
569
|
+
annotations: { readOnly: true },
|
|
570
|
+
handler: (input) => provider.listAds(input.account_id, input.ad_group_id)
|
|
571
|
+
}),
|
|
572
|
+
guardedWriteTool({
|
|
573
|
+
name: "openai_create_campaign",
|
|
574
|
+
namespace: "openai",
|
|
575
|
+
provider: "openai",
|
|
576
|
+
kind: "create",
|
|
577
|
+
description: "Create a paused OpenAI Ads campaign. Spend limits use integer micros; platform currency minimums apply. Target countries or location IDs. Conversion bidding needs one event setting. Supply objective with billing_event_type, or use bidding_type. Preview is local.",
|
|
578
|
+
payload: createCampaignSchema
|
|
579
|
+
}),
|
|
580
|
+
guardedWriteTool({
|
|
581
|
+
name: "openai_set_campaign_status",
|
|
582
|
+
namespace: "openai",
|
|
583
|
+
provider: "openai",
|
|
584
|
+
kind: "update",
|
|
585
|
+
description: "Pause or activate an OpenAI Ads campaign; reads its current status first.",
|
|
586
|
+
payload: setCampaignStatusSchema
|
|
587
|
+
}),
|
|
588
|
+
guardedWriteTool({
|
|
589
|
+
name: "openai_set_ad_group_status",
|
|
590
|
+
namespace: "openai",
|
|
591
|
+
provider: "openai",
|
|
592
|
+
kind: "update",
|
|
593
|
+
description: "Pause or activate an OpenAI Ads ad group; reads its current status first.",
|
|
594
|
+
payload: setAdGroupStatusSchema
|
|
595
|
+
}),
|
|
596
|
+
guardedWriteTool({
|
|
597
|
+
name: "openai_set_ad_status",
|
|
598
|
+
namespace: "openai",
|
|
599
|
+
provider: "openai",
|
|
600
|
+
kind: "update",
|
|
601
|
+
description: "Pause or activate an OpenAI Ads ad; reads its current status first.",
|
|
602
|
+
payload: setAdStatusSchema
|
|
603
|
+
}),
|
|
604
|
+
guardedWriteTool({
|
|
605
|
+
name: "openai_set_budget",
|
|
606
|
+
namespace: "openai",
|
|
607
|
+
provider: "openai",
|
|
608
|
+
kind: "update",
|
|
609
|
+
description: "Update an OpenAI Ads campaign\u2019s existing daily or lifetime spend limit in integer micros; reads the current value for policy checks. Budget-type changes are not supported.",
|
|
610
|
+
payload: setBudgetSchema
|
|
611
|
+
})
|
|
612
|
+
];
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// src/index.ts
|
|
616
|
+
function openaiCredentialsFromData(data) {
|
|
617
|
+
const apiKey = data?.api_key?.trim();
|
|
618
|
+
return apiKey ? { apiKey } : void 0;
|
|
619
|
+
}
|
|
620
|
+
function openaiEnvironmentData() {
|
|
621
|
+
return { api_key: process.env.OPENAI_ADS_API_KEY ?? "" };
|
|
622
|
+
}
|
|
623
|
+
async function resolveOpenAICredentials(store) {
|
|
624
|
+
return openaiCredentialsFromData((await store.get("openai"))?.data) ?? openaiCredentialsFromData(openaiEnvironmentData());
|
|
625
|
+
}
|
|
626
|
+
async function createOpenAIModule(store) {
|
|
627
|
+
const credentials = await resolveOpenAICredentials(store);
|
|
628
|
+
if (!credentials) return void 0;
|
|
629
|
+
const provider = new OpenAIAdsProvider(new OpenAIAdsClient(credentials));
|
|
630
|
+
return { provider, tools: openaiTools(provider) };
|
|
631
|
+
}
|
|
632
|
+
export {
|
|
633
|
+
OPENAI_ADS_API_BASE,
|
|
634
|
+
OpenAIAdsClient,
|
|
635
|
+
OpenAIAdsProvider,
|
|
636
|
+
accountSchema,
|
|
637
|
+
campaignSchema,
|
|
638
|
+
createOpenAIModule,
|
|
639
|
+
insightRowSchema,
|
|
640
|
+
openaiCredentialsFromData,
|
|
641
|
+
openaiEnvironmentData,
|
|
642
|
+
openaiTools,
|
|
643
|
+
resolveOpenAICredentials
|
|
644
|
+
};
|
|
645
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/schemas.ts","../src/provider.ts","../src/tools.ts","../src/conversions.ts","../src/index.ts"],"sourcesContent":["import { AdportError } from '@adport/core';\nimport { z } from 'zod';\nimport { listEnvelope } from './schemas.js';\n\nexport const OPENAI_ADS_API_BASE = 'https://api.ads.openai.com/v1/';\nconst ORIGIN = 'https://api.ads.openai.com';\n\nexport interface OpenAIAdsCredentials {\n /** Advertiser API key from Ads Manager settings; each key is bound to one ad account. */\n apiKey: string;\n}\n\ntype Params = Record<string, string | string[]>;\n\nexport class OpenAIAdsClient {\n constructor(private readonly credentials: OpenAIAdsCredentials, private readonly fetchImpl: typeof fetch = fetch) {\n if (!credentials.apiKey.trim()) throw new AdportError('INVALID_INPUT', 'openai: API key is empty');\n }\n\n async get<T>(path: string, schema: z.ZodType<T>, params: Params = {}): Promise<T> {\n return this.parse(await this.send(this.url(path, params), 'GET'), schema);\n }\n\n async post<T>(path: string, schema: z.ZodType<T>, body?: unknown, idempotencyKey?: string): Promise<T> {\n return this.parse(await this.send(this.url(path), 'POST', body, idempotencyKey), schema);\n }\n\n /** Follows `after` cursors until `has_more` is false or `max` rows were read. */\n async list<T extends z.ZodType>(path: string, item: T, params: Params = {}, max = 10_000): Promise<{ items: z.infer<T>[]; truncated: boolean }> {\n const envelope = listEnvelope(item), items: z.infer<T>[] = [], seen = new Set<string>();\n let after: string | undefined;\n while (true) {\n const page = await this.get(path, envelope, { ...params, ...(after ? { after } : {}) });\n items.push(...page.data);\n if (!page.has_more) return { items: items.slice(0, max), truncated: items.length > max };\n if (items.length >= max) return { items: items.slice(0, max), truncated: true };\n const next = page.last_id ?? undefined;\n if (!next || seen.has(next) || seen.size >= 1000) throw new AdportError('PROVIDER_ERROR', 'openai: pagination did not terminate; refusing incomplete results');\n seen.add(next);\n after = next;\n }\n }\n\n private parse<T>(data: unknown, schema: z.ZodType<T>): T {\n const parsed = schema.safeParse(data);\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'openai: malformed API response', { response_issues: parsed.error.issues.slice(0, 20).map(issue => ({ path: issue.path, code: issue.code })) });\n return parsed.data;\n }\n\n private url(path: string, params: Params = {}): URL {\n const url = new URL(path, OPENAI_ADS_API_BASE);\n if (url.origin !== ORIGIN || !url.pathname.startsWith('/v1/') || url.username || url.password || url.hash) throw new AdportError('INVALID_INPUT', 'openai: invalid API URL');\n for (const [key, value] of Object.entries(params)) {\n if (Array.isArray(value)) for (const entry of value) url.searchParams.append(`${key}[]`, entry);\n else url.searchParams.set(key, value);\n }\n return url;\n }\n\n private redact(value: string): string {\n return value.replaceAll(this.credentials.apiKey, '[redacted]').replace(/Bearer\\s+\\S+/gi, 'Bearer [redacted]').slice(0, 2000);\n }\n\n private async send(url: URL, method: 'GET' | 'POST', body?: unknown, idempotencyKey?: string): Promise<unknown> {\n const response = await this.fetchImpl(url.href, {\n method,\n headers: {\n authorization: `Bearer ${this.credentials.apiKey}`,\n accept: 'application/json',\n ...(body !== undefined ? { 'content-type': 'application/json' } : {}),\n ...(idempotencyKey ? { 'idempotency-key': idempotencyKey } : {}),\n },\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n redirect: 'error', signal: AbortSignal.timeout(30_000),\n });\n const raw: unknown = await response.json().catch(() => undefined);\n if (!response.ok) {\n const advice = response.status === 401 ? ' Use an active Advertiser API key from Ads Manager settings.'\n : response.status === 429 ? ' Rate limited (600 requests/minute per endpoint, 1,200 overall); retry later.' : '';\n const message = errorMessage(raw);\n throw new AdportError('PROVIDER_ERROR', `openai: HTTP ${response.status}.${advice}${message ? ` ${this.redact(message)}` : ''}`, { http_status: response.status });\n }\n return raw;\n }\n}\n\nfunction errorMessage(raw: unknown): string | undefined {\n if (!raw || typeof raw !== 'object') return undefined;\n const record = raw as Record<string, unknown>;\n const error = record.error;\n if (typeof error === 'string') return error;\n if (error && typeof error === 'object' && typeof (error as Record<string, unknown>).message === 'string') return (error as Record<string, string>).message;\n return typeof record.message === 'string' ? record.message : undefined;\n}\n","import { z } from 'zod';\n\n// Official OpenAI Ads API v1 contracts (OpenAPI 2.3.0), reviewed 2026-11-17.\n// Source URLs and normalization decisions: docs/providers/openai.md.\nexport const openaiId = z.string().regex(/^[A-Za-z0-9_-]{1,128}$/);\nexport const openaiStatus = z.enum(['active', 'paused']);\n/** Campaign budgets are integer micros with a documented floor of one currency unit. */\nexport const openaiBudgetMicros = z.number().int().min(1_000_000).max(Number.MAX_SAFE_INTEGER);\nconst unixSeconds = z.number().int().nonnegative();\nconst schedule = z.iso.datetime({ offset: true }).refine(value => {\n const seconds = Date.parse(value) / 1000;\n return seconds >= 946684800 && seconds <= 4102444800;\n}, 'Schedule must be between 2000-01-01 and 2100-01-01');\nconst metric = z.number().finite().nullable().optional();\n\nexport const accountSchema = z.looseObject({\n id: openaiId, name: z.string(), status: z.string().optional(), timezone: z.string(), currency_code: z.string(),\n});\nexport type OpenAIAccount = z.infer<typeof accountSchema>;\n\nexport const budgetSchema = z.looseObject({\n lifetime_spend_limit_micros: z.number().int().nonnegative().optional(),\n daily_spend_limit_micros: z.number().int().nonnegative().optional(),\n});\nexport const campaignSchema = z.looseObject({\n id: openaiId, name: z.string(), status: z.string(), description: z.string().nullable().optional(),\n start_time: unixSeconds.nullable().optional(), end_time: unixSeconds.nullable().optional(),\n budget: budgetSchema, bidding_type: z.string().optional(), objective: z.string().optional(),\n});\nexport type OpenAICampaign = z.infer<typeof campaignSchema>;\nexport const adGroupSchema = z.looseObject({ id: openaiId, name: z.string(), status: z.string() });\nexport const adSchema = z.looseObject({ id: openaiId, name: z.string(), status: z.string(), review_status: z.string().optional() });\n\nexport const listEnvelope = <T extends z.ZodType>(item: T) => z.looseObject({\n data: z.array(item), has_more: z.boolean(), last_id: z.string().nullable().optional(),\n});\n\nexport const insightRowSchema = z.looseObject({\n id: z.string(),\n impressions: metric, clicks: metric, spend: metric, conversions: metric, order_created_attributed_sales: metric,\n ad_account_id: z.string().nullable().optional(), ad_account_name: z.string().nullable().optional(),\n campaign_id: z.string().nullable().optional(), campaign_name: z.string().nullable().optional(), campaign_status: z.string().nullable().optional(),\n ad_group_id: z.string().nullable().optional(), ad_group_name: z.string().nullable().optional(), ad_group_status: z.string().nullable().optional(),\n ad_id: z.string().nullable().optional(), ad_name: z.string().nullable().optional(), ad_status: z.string().nullable().optional(),\n});\nexport type OpenAIInsightRow = z.infer<typeof insightRowSchema>;\n\nexport const listCampaignsSchema = z.object({ account_id: openaiId });\nexport const listAdGroupsSchema = z.object({ account_id: openaiId, campaign_id: openaiId.optional() });\nexport const listAdsSchema = z.object({ account_id: openaiId, ad_group_id: openaiId.optional() });\n\nexport const createCampaignSchema = z.object({\n name: z.string().min(3).max(1000).refine(value => value.trim().length > 0, 'Name cannot be blank'),\n description: z.string().max(1000).optional(),\n status: openaiStatus.default('paused'),\n lifetime_spend_limit_micros: openaiBudgetMicros.optional(),\n daily_spend_limit_micros: openaiBudgetMicros.optional(),\n bidding_type: z.enum(['impressions', 'clicks', 'conversions']).optional(),\n objective: z.enum(['reach', 'clicks', 'conversions']).optional(),\n billing_event_type: z.enum(['impression', 'click']).optional(),\n conversion_event_setting_ids: z.array(openaiId).length(1).optional(),\n start_time: schedule.optional(),\n end_time: schedule.optional(),\n target_countries: z.array(z.string().regex(/^[A-Z]{2}$/)).min(1).max(250).refine(ids => new Set(ids).size === ids.length, 'Use unique countries').optional(),\n target_location_ids: z.array(z.string().regex(/^\\d+$/)).min(1).max(250).refine(ids => new Set(ids).size === ids.length, 'Use unique location IDs').optional(),\n}).strict().refine(input => Number(input.lifetime_spend_limit_micros !== undefined) + Number(input.daily_spend_limit_micros !== undefined) === 1, 'Set exactly one lifetime or daily spend limit')\n .refine(input => (input.objective !== undefined) === (input.billing_event_type !== undefined), 'Supply objective and billing_event_type together, or omit both and use bidding_type')\n .refine(input => input.bidding_type === 'conversions' || input.objective === 'conversions' ? Boolean(input.conversion_event_setting_ids) : !input.conversion_event_setting_ids, {\n message: 'Conversion bidding requires exactly one conversion_event_setting_id; other bidding types must omit it',\n});\nexport const setCampaignStatusSchema = z.object({ campaign_id: openaiId, status: openaiStatus });\nexport const setAdGroupStatusSchema = z.object({ ad_group_id: openaiId, status: openaiStatus });\nexport const setAdStatusSchema = z.object({ ad_id: openaiId, status: openaiStatus });\nexport const setBudgetSchema = z.object({\n campaign_id: openaiId,\n field: z.enum(['daily_spend_limit_micros', 'lifetime_spend_limit_micros']).default('daily_spend_limit_micros'),\n budget_micros: openaiBudgetMicros,\n});\n","import { randomUUID } from 'node:crypto';\nimport { z } from 'zod';\nimport {\n AdportError, resolveDateRange, type Account, type AdProvider, type EntityLevel, type MetricName,\n type NormalizedQuery, type Report, type ReportRow, type StandardActions,\n type WriteGuard, type WriteOperation, type WritePreview, type WriteResult,\n} from '@adport/core';\nimport type { OpenAIAdsClient } from './client.js';\nimport {\n accountSchema, adGroupSchema, adSchema, campaignSchema, createCampaignSchema, insightRowSchema,\n openaiId, setAdGroupStatusSchema, setAdStatusSchema, setBudgetSchema, setCampaignStatusSchema,\n type OpenAIAccount, type OpenAICampaign, type OpenAIInsightRow,\n} from './schemas.js';\n\nconst LEVEL = { account: 'ad_account', campaign: 'campaign', ad_group: 'ad_group', ad: 'ad' } as const;\n// Canonical request names; responses use flat keys (campaign.id → campaign_id, campaign.spend → spend).\nconst LEVEL_METRICS = ['impressions', 'clicks', 'spend'] as const;\nconst ACCOUNT_METRICS = ['conversions', 'order_created_attributed_sales'] as const;\nconst STATUS_TOOLS = {\n openai_set_campaign_status: { path: 'campaigns', label: 'campaign', schema: setCampaignStatusSchema, key: 'campaign_id', entity: campaignSchema },\n openai_set_ad_group_status: { path: 'ad_groups', label: 'ad group', schema: setAdGroupStatusSchema, key: 'ad_group_id', entity: adGroupSchema },\n openai_set_ad_status: { path: 'ads', label: 'ad', schema: setAdStatusSchema, key: 'ad_id', entity: adSchema },\n} as const;\n\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute: () => Promise<WriteResult> };\n\nexport class OpenAIAdsProvider implements AdProvider {\n readonly id = 'openai';\n private account?: Promise<OpenAIAccount>;\n constructor(private readonly client: OpenAIAdsClient) {}\n /** API access for read tools (conversion insights is a read-only POST); callers check the account first. */\n get api(): OpenAIAdsClient { return this.client; }\n\n capabilities() { return { serverDryRun: false }; }\n standardActions(): StandardActions {\n return { pauseCampaign: (accountId, campaignId) => ({\n tool: 'openai_set_campaign_status', input: { account_id: accountId, campaign_id: campaignId, status: 'paused' },\n }) };\n }\n\n /** Advertiser API keys are bound to exactly one ad account. */\n private keyAccount(): Promise<OpenAIAccount> {\n this.account ??= this.client.get('ad_account', accountSchema).catch(error => { this.account = undefined; throw error; });\n return this.account;\n }\n\n private async assertAccount(accountId: string): Promise<OpenAIAccount> {\n const account = await this.keyAccount();\n if (openaiId.parse(accountId) !== account.id) throw new AdportError('INVALID_INPUT', 'openai: account_id does not match the ad account of the connected API key');\n return account;\n }\n\n async listAccounts(): Promise<Account[]> {\n const account = await this.keyAccount();\n return [{ provider: this.id, id: account.id, name: account.name, currency: account.currency_code, timezone: account.timezone, ...(account.status ? { status: account.status } : {}) }];\n }\n\n async accountMetadata(accountId: string) {\n const account = await this.assertAccount(accountId);\n return { currency: account.currency_code, timezone: account.timezone };\n }\n\n async listCampaigns(accountId: string) {\n await this.assertAccount(accountId);\n return this.client.list('campaigns', campaignSchema, { limit: '500' });\n }\n async listAdGroups(accountId: string, campaignId?: string) {\n await this.assertAccount(accountId);\n return this.client.list('ad_groups', adGroupSchema, { limit: '500', ...(campaignId ? { campaign_id: campaignId } : {}) });\n }\n async listAds(accountId: string, adGroupId?: string) {\n await this.assertAccount(accountId);\n return this.client.list('ads', adSchema, { limit: '500', ...(adGroupId ? { ad_group_id: adGroupId } : {}) });\n }\n\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n const limit = query.limit ?? 1000;\n if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError('INVALID_INPUT', 'openai: report limit must be a positive integer');\n const account = await this.keyAccount();\n const accountIds = [...new Set(query.accountIds ?? [account.id])];\n const rows: ReportRow[] = [];\n let truncated = false;\n for (const id of accountIds) {\n await this.assertAccount(id);\n const level = LEVEL[query.level];\n const entityFields = query.level === 'account' ? ['ad_account.id', 'ad_account.name'] : [`${level}.id`, `${level}.name`, `${level}.status`];\n const { items, truncated: more } = await this.client.list('ad_account/insights', insightRowSchema, {\n aggregation_level: level, time_granularity: 'none', limit: '2000',\n // date_range is inclusive and defaults to the ad account's time zone.\n time_ranges: [JSON.stringify({ type: 'date_range', since: range.start, until: range.end })],\n fields: [...entityFields, ...LEVEL_METRICS.map(metric => `${level}.${metric}`), ...ACCOUNT_METRICS],\n }, limit + 1);\n truncated ||= more;\n for (const row of items) rows.push(this.row(row, query.level, account, query.metrics));\n }\n return { rows: rows.slice(0, limit), ...(truncated || rows.length > limit ? { truncated: true } : {}) };\n }\n\n private row(row: OpenAIInsightRow, level: EntityLevel, account: OpenAIAccount, metrics: MetricName[]): ReportRow {\n const prefix = LEVEL[level];\n const entityId = level === 'account' ? (row.ad_account_id ?? account.id) : row[`${prefix}_id` as keyof OpenAIInsightRow];\n if (typeof entityId !== 'string' || !entityId) throw new AdportError('PROVIDER_ERROR', `openai: insights row is missing ${prefix}_id`);\n const name = level === 'account' ? (row.ad_account_name ?? account.name) : row[`${prefix}_name` as keyof OpenAIInsightRow];\n const status = level === 'account' ? account.status : row[`${prefix}_status` as keyof OpenAIInsightRow];\n return {\n provider: this.id, accountId: account.id, currency: account.currency_code,\n entity: { level, id: entityId, name: typeof name === 'string' && name ? name : entityId, ...(typeof status === 'string' ? { status } : {}) },\n metrics: normalize(row, metrics),\n };\n }\n\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const { execute: _execute, ...preview } = await this.plan(op, guard);\n return { ...preview, serverValidated: false };\n }\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n return (await this.plan(op, guard)).execute();\n }\n\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n if (op.provider !== this.id) throw new AdportError('INVALID_INPUT', 'openai: provider mismatch');\n await this.assertAccount(op.accountId);\n if (op.tool === 'openai_create_campaign' && op.kind === 'create') return this.planCreate(op, guard);\n if (op.tool === 'openai_set_budget' && op.kind === 'update') return this.planBudget(op);\n if (op.kind === 'update' && Object.hasOwn(STATUS_TOOLS, op.tool)) return this.planStatus(op);\n throw new AdportError('INVALID_INPUT', `openai: unsupported write ${op.tool}`);\n }\n\n private planCreate(op: WriteOperation, guard: WriteGuard): Plan {\n const input = createCampaignSchema.parse(op.payload);\n const start = input.start_time ? Math.floor(Date.parse(input.start_time) / 1000) : undefined;\n const end = input.end_time ? Math.floor(Date.parse(input.end_time) / 1000) : undefined;\n if (start !== undefined && end !== undefined && end <= start) throw new AdportError('INVALID_INPUT', 'openai: end_time must be after start_time');\n const status = guard.forcePausedCreation ? 'paused' : input.status;\n const budget = {\n ...(input.lifetime_spend_limit_micros !== undefined ? { lifetime_spend_limit_micros: input.lifetime_spend_limit_micros } : {}),\n ...(input.daily_spend_limit_micros !== undefined ? { daily_spend_limit_micros: input.daily_spend_limit_micros } : {}),\n };\n const body = {\n name: input.name, status, budget,\n ...(input.description !== undefined ? { description: input.description } : {}),\n ...(input.bidding_type ? { bidding_type: input.bidding_type } : {}),\n ...(input.objective ? { objective: input.objective } : {}),\n ...(input.billing_event_type ? { billing_event_type: input.billing_event_type } : {}),\n ...(input.conversion_event_setting_ids ? { conversion_event_setting_ids: input.conversion_event_setting_ids } : {}),\n ...(start !== undefined ? { start_time: start } : {}),\n ...(end !== undefined ? { end_time: end } : {}),\n ...(input.target_location_ids || input.target_countries ? { targeting: { locations: {\n ...(input.target_location_ids ? { include: input.target_location_ids.map(id => ({ id })) } : {}),\n ...(input.target_countries ? { countries: input.target_countries } : {}),\n } } } : {}),\n };\n return {\n summary: `Create OpenAI Ads campaign \"${input.name}\"`,\n changes: [`+ ${JSON.stringify(body)}`],\n coercions: status !== input.status ? ['status coerced to paused by policy (paused_creation)'] : [],\n budgetDeltas: Object.entries(budget).map(([field, value]) => ({ target: `new campaign ${field}`, toMicros: value })),\n execute: async () => {\n const created = await this.client.post('campaigns', campaignSchema, body, randomUUID());\n const mismatch = !matchesCampaignReceipt(created, body);\n if (mismatch) throw new AdportError('PROVIDER_ERROR', 'openai: campaign creation receipt mismatch; reconcile before retrying', { resource_ids: [created.id] });\n return { applied: true, resourceIds: [created.id] };\n },\n };\n }\n\n private async planBudget(op: WriteOperation): Promise<Plan> {\n const input = setBudgetSchema.parse(op.payload);\n const current = await this.client.get(`campaigns/${input.campaign_id}`, campaignSchema);\n if (current.id !== input.campaign_id) throw new AdportError('PROVIDER_ERROR', 'openai: campaign response does not match the requested campaign');\n const previous = current.budget[input.field];\n const otherField = input.field === 'daily_spend_limit_micros' ? 'lifetime_spend_limit_micros' : 'daily_spend_limit_micros';\n if (current.budget[otherField] !== undefined) throw new AdportError('INVALID_INPUT', 'openai: daily and lifetime campaign budgets are mutually exclusive; update the existing budget type instead of adding or replacing the other limit');\n const budget = { ...pickBudget(current.budget), [input.field]: input.budget_micros };\n return {\n summary: `Change OpenAI Ads campaign \"${current.name}\" ${input.field}`,\n changes: [`~ ${current.id} ${input.field}: ${previous ?? 'unset'} → ${input.budget_micros}`],\n fieldChanges: [{ field: input.field, before: previous === undefined ? 'unset' : String(previous), after: String(input.budget_micros) }],\n coercions: [],\n budgetDeltas: [{ target: `campaign ${current.id} ${input.field}`, ...(previous !== undefined ? { fromMicros: previous } : {}), toMicros: input.budget_micros }],\n execute: async () => {\n const updated = await this.client.post(`campaigns/${current.id}`, campaignSchema, { budget });\n if (updated.id !== current.id || updated.budget[otherField] !== undefined || !matchesRequested(updated.budget, budget)) throw new AdportError('PROVIDER_ERROR', 'openai: campaign budget receipt mismatch; reconcile before retrying', { resource_ids: [current.id] });\n return { applied: true, resourceIds: [current.id] };\n },\n };\n }\n\n private async planStatus(op: WriteOperation): Promise<Plan> {\n const spec = STATUS_TOOLS[op.tool as keyof typeof STATUS_TOOLS];\n const input = spec.schema.parse(op.payload) as Record<string, string>;\n const id = input[spec.key]!, status = input.status!;\n const current = await this.client.get(`${spec.path}/${id}`, spec.entity);\n if (current.id !== id) throw new AdportError('PROVIDER_ERROR', `openai: ${spec.label} response does not match the requested ${spec.label}`);\n return {\n summary: `${status === 'active' ? 'Activate' : 'Pause'} OpenAI Ads ${spec.label} \"${current.name}\"`,\n changes: [`~ ${id} status: ${current.status} → ${status}`],\n fieldChanges: [{ field: 'status', before: current.status, after: status }],\n coercions: [], budgetDeltas: [],\n execute: async () => {\n const updated = await this.client.post(`${spec.path}/${id}/${status === 'active' ? 'activate' : 'pause'}`, spec.entity);\n if (updated.id !== id || updated.status !== status) throw new AdportError('PROVIDER_ERROR', `openai: ${spec.label} status receipt mismatch; reconcile before retrying`, { resource_ids: [id] });\n return { applied: true, resourceIds: [id] };\n },\n };\n }\n}\n\nfunction matchesCampaignReceipt(actual: OpenAICampaign, expected: Record<string, unknown>): boolean {\n const expectedBudget = expected.budget as Record<string, number>;\n const actualBudget = pickBudget(actual.budget);\n if (Object.keys(actualBudget).length !== Object.keys(expectedBudget).length || !matchesRequested(actualBudget, expectedBudget)) return false;\n const requestedTargeting = expected.targeting as { locations: { countries?: string[]; include?: { id: string }[] } } | undefined;\n if (!requestedTargeting?.locations.countries) return matchesRequested(actual, expected);\n const { targeting: _targeting, ...otherFields } = expected;\n if (!matchesRequested(actual, otherFields)) return false;\n const targeting = actual.targeting as { locations?: { countries?: unknown; include?: unknown } } | undefined;\n if (!targeting || Object.keys(targeting).some(key => key !== 'locations')) return false;\n const locations = targeting.locations;\n if (!locations) return false;\n const requested = requestedTargeting.locations;\n if (locations.countries !== undefined) return matchesRequested(locations.countries, requested.countries)\n && matchesRequested(locations.include ?? [], requested.include ?? []);\n // The live API expands country codes into country location records in its receipt.\n const parsed = z.array(z.object({ id: z.string(), type: z.string().optional(), country_code: z.string().nullable().optional() })).safeParse(locations.include);\n if (!parsed.success) return false;\n const included = parsed.data, ids = requested.include?.map(location => location.id) ?? [], countries = requested.countries!;\n return new Set(included.map(location => location.id)).size === included.length\n && ids.every(id => included.some(location => location.id === id))\n && countries.every(code => included.filter(location => location.type === 'country' && location.country_code === code).length === 1)\n && included.every(location => ids.includes(location.id) || location.type === 'country' && countries.includes(location.country_code ?? ''));\n}\n\nfunction matchesRequested(actual: unknown, expected: unknown): boolean {\n if (Array.isArray(expected)) return Array.isArray(actual) && actual.length === expected.length\n && expected.every(value => actual.some(candidate => matchesRequested(candidate, value)));\n if (expected && typeof expected === 'object') return Boolean(actual && typeof actual === 'object'\n && Object.entries(expected).every(([key, value]) => matchesRequested((actual as Record<string, unknown>)[key], value)));\n return actual === expected;\n}\n\nfunction pickBudget(budget: { lifetime_spend_limit_micros?: number; daily_spend_limit_micros?: number }) {\n return {\n ...(budget.lifetime_spend_limit_micros !== undefined ? { lifetime_spend_limit_micros: budget.lifetime_spend_limit_micros } : {}),\n ...(budget.daily_spend_limit_micros !== undefined ? { daily_spend_limit_micros: budget.daily_spend_limit_micros } : {}),\n };\n}\n\n/** Insights spend and sales are major currency units; null means unavailable, never zero. */\nfunction normalize(row: OpenAIInsightRow, metrics: MetricName[]): Partial<Record<MetricName, number>> {\n const mapped: Partial<Record<MetricName, number>> = {};\n const fields = { spend: 'spend', impressions: 'impressions', clicks: 'clicks', conversions: 'conversions', conversion_value: 'order_created_attributed_sales' } as const;\n for (const [metric, field] of Object.entries(fields)) {\n const value = row[field];\n if (typeof value === 'number') mapped[metric as MetricName] = value;\n }\n for (const [metric, numerator, denominator, factor] of [\n ['ctr', 'clicks', 'impressions', 100], ['cpc', 'spend', 'clicks', 1], ['cpm', 'spend', 'impressions', 1000],\n ['cpa', 'spend', 'conversions', 1], ['roas', 'conversion_value', 'spend', 1],\n ] as const) {\n // A zero denominator leaves the ratio absent rather than reporting a misleading 0.\n if (mapped[numerator] !== undefined && mapped[denominator]) mapped[metric] = mapped[numerator]! / mapped[denominator]! * factor;\n }\n return Object.fromEntries(metrics.filter(metric => mapped[metric] !== undefined).map(metric => [metric, mapped[metric]]));\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport {\n createCampaignSchema, listAdGroupsSchema, listAdsSchema, listCampaignsSchema,\n setAdGroupStatusSchema, setAdStatusSchema, setBudgetSchema, setCampaignStatusSchema,\n} from './schemas.js';\nimport type { OpenAIAdsProvider } from './provider.js';\nimport { openaiConversionTools } from './conversions.js';\n\nexport function openaiTools(provider: OpenAIAdsProvider): AnyToolDefinition[] {\n return [\n ...openaiConversionTools(provider),\n defineTool({ name: 'openai_list_campaigns', namespace: 'openai', description: 'List OpenAI Ads (ChatGPT ads) campaigns in the connected ad account, with status and budgets in micros.',\n input: listCampaignsSchema, annotations: { readOnly: true }, handler: input => provider.listCampaigns(input.account_id) }),\n defineTool({ name: 'openai_ad_groups', namespace: 'openai', description: 'List OpenAI Ads ad groups, optionally for one campaign.',\n input: listAdGroupsSchema, annotations: { readOnly: true }, handler: input => provider.listAdGroups(input.account_id, input.campaign_id) }),\n defineTool({ name: 'openai_ads', namespace: 'openai', description: 'List OpenAI Ads ads with status and review status, optionally for one ad group.',\n input: listAdsSchema, annotations: { readOnly: true }, handler: input => provider.listAds(input.account_id, input.ad_group_id) }),\n guardedWriteTool({ name: 'openai_create_campaign', namespace: 'openai', provider: 'openai', kind: 'create',\n description: 'Create a paused OpenAI Ads campaign. Spend limits use integer micros; platform currency minimums apply. Target countries or location IDs. Conversion bidding needs one event setting. Supply objective with billing_event_type, or use bidding_type. Preview is local.', payload: createCampaignSchema }),\n guardedWriteTool({ name: 'openai_set_campaign_status', namespace: 'openai', provider: 'openai', kind: 'update',\n description: 'Pause or activate an OpenAI Ads campaign; reads its current status first.', payload: setCampaignStatusSchema }),\n guardedWriteTool({ name: 'openai_set_ad_group_status', namespace: 'openai', provider: 'openai', kind: 'update',\n description: 'Pause or activate an OpenAI Ads ad group; reads its current status first.', payload: setAdGroupStatusSchema }),\n guardedWriteTool({ name: 'openai_set_ad_status', namespace: 'openai', provider: 'openai', kind: 'update',\n description: 'Pause or activate an OpenAI Ads ad; reads its current status first.', payload: setAdStatusSchema }),\n guardedWriteTool({ name: 'openai_set_budget', namespace: 'openai', provider: 'openai', kind: 'update',\n description: 'Update an OpenAI Ads campaign’s existing daily or lifetime spend limit in integer micros; reads the current value for policy checks. Budget-type changes are not supported.', payload: setBudgetSchema }),\n ];\n}\n","import { AdportError, defineTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { OpenAIAdsProvider } from './provider.js';\nimport { openaiId } from './schemas.js';\n\n// Conversions API reads, OpenAPI 2.3.0 (reviewed 2026-11-17). Raw event payloads are never returned.\nconst isoDate = z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/);\nexport const sourceSchema = z.looseObject({ id: z.string(), name: z.string(), client_type: z.string(), pixel_id: z.string() });\nexport const eventSettingSchema = z.looseObject({\n id: z.string(), name: z.string(), event_type: z.string(), custom_event_name: z.string().nullable(), attribution_window_days: z.number().int(),\n source_ids: z.array(z.string()), campaigns: z.array(z.looseObject({ id: z.string(), name: z.string() })), archived: z.boolean(),\n});\nexport const receivedEventSchema = z.object({\n data_source_id: z.string(), event_type: z.string(), custom_event_name: z.string().nullable(), action_source: z.string().nullable(),\n event_timestamp_ms: z.number().int(), received_at_ms: z.number().int(), api_channel: z.string(),\n});\nexport const conversionRowSchema = z.looseObject({\n entity_id: z.string(), conversions: z.number().int(), date: z.string().optional(), country: z.string().optional(), device: z.string().optional(),\n click_through_conversions: z.number().int().optional(), view_through_conversions: z.number().int().optional(),\n order_created_attributed_sales: z.string().nullable().optional(), order_created_attributed_sales_currency: z.string().optional(),\n attributed_events: z.array(z.looseObject({ entity_id: z.string(), event_name: z.string(), event_kind: z.string(), attributed_event_count: z.number().int() })).optional(),\n});\nconst insightsSchema = z.looseObject({ data: z.array(conversionRowSchema), count: z.number().int(), account_currency: z.string().optional() });\n\nexport const conversionInsightsInput = z.object({\n account_id: openaiId,\n since: isoDate.describe('First day, account time zone'),\n until: isoDate.describe('Last day, inclusive, account time zone'),\n aggregation_level: z.enum(['campaign', 'ad_group', 'ad']).default('campaign'),\n entity_ids: z.array(openaiId).min(1).max(500).optional().describe('Report per entity; omit for account totals'),\n time_granularity: z.enum(['none', 'daily']).default('none'),\n breakdown: z.enum(['device', 'country']).optional(),\n attribution_window_days: z.union([z.literal(7), z.literal(14), z.literal(30)]).optional(),\n view_through_attribution_window_days: z.union([z.literal(0), z.literal(1)]).optional(),\n include_events: z.boolean().default(false).describe('Add attributed standard and custom events per row'),\n event_names: z.array(z.string().min(1).max(256)).min(1).max(500).optional().describe('Requires include_events'),\n}).refine(input => input.since <= input.until, 'since must not be after until')\n .refine(input => !input.event_names || input.include_events, 'event_names requires include_events');\n\nexport async function conversionInsights(provider: OpenAIAdsProvider, input: z.infer<typeof conversionInsightsInput>) {\n await provider.accountMetadata(input.account_id);\n const body = {\n aggregation_level: input.aggregation_level, time_granularity: input.time_granularity,\n time_ranges: [JSON.stringify({ type: 'date_range', since: input.since, until: input.until })],\n ...(input.entity_ids ? { entity_ids: input.entity_ids, group_by_entity: true } : { group_by_entity: false }),\n ...(input.breakdown ? { breakdown: input.breakdown } : {}),\n ...(input.attribution_window_days !== undefined ? { attribution_window_days: input.attribution_window_days } : {}),\n ...(input.view_through_attribution_window_days !== undefined ? { view_through_attribution_window_days: input.view_through_attribution_window_days } : {}),\n ...(input.include_events ? { include: ['attributed_events'] } : {}),\n ...(input.event_names ? { event_names: input.event_names } : {}),\n };\n const result = await provider.api.post('conversions/insights', insightsSchema, body);\n if (result.count !== result.data.length) throw new AdportError('PROVIDER_ERROR', 'openai: conversion insights count does not match the returned rows');\n return result;\n}\n\nexport function openaiConversionTools(provider: OpenAIAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'openai_conversion_sources', namespace: 'openai', description: 'List OpenAI Ads conversion data sources (pixel and Conversions API) with their pixel_id.',\n input: z.object({ account_id: openaiId }), annotations: { readOnly: true },\n handler: async input => { await provider.accountMetadata(input.account_id); return provider.api.list('conversions/pixels', sourceSchema, { limit: '500' }); } }),\n defineTool({ name: 'openai_conversion_event_settings', namespace: 'openai', description: 'List OpenAI Ads conversion events (goals): event type, attribution window, sources and the campaigns optimizing on each.',\n input: z.object({ account_id: openaiId }), annotations: { readOnly: true },\n handler: async input => { await provider.accountMetadata(input.account_id); return provider.api.list('conversions/event_settings', eventSettingSchema, { limit: '500' }); } }),\n defineTool({ name: 'openai_conversion_events', namespace: 'openai', description: 'Show the latest events received by one conversion source (type, channel, event and receipt times) to check that browser or server tracking arrives. Event payloads are not returned.',\n input: z.object({ account_id: openaiId, pixel_id: z.string().min(1).max(256).describe('pixel_id from openai_conversion_sources'), limit: z.number().int().min(1).max(50).default(50) }), annotations: { readOnly: true },\n handler: async input => {\n await provider.accountMetadata(input.account_id);\n const result = await provider.api.get('conversions/events', z.looseObject({ data: z.array(receivedEventSchema) }), { pid: input.pixel_id, limit: String(input.limit) });\n return { pixel_id: input.pixel_id, events: result.data.map(event => ({\n ...event, event_time: new Date(event.event_timestamp_ms).toISOString(), received_at: new Date(event.received_at_ms).toISOString(),\n })) };\n } }),\n defineTool({ name: 'openai_conversion_insights', namespace: 'openai', description: 'OpenAI Ads goal conversions (click-through and view-through), attributed sales and optional per-event counts for a date range, per entity or for the whole account.',\n input: conversionInsightsInput, annotations: { readOnly: true }, handler: input => conversionInsights(provider, input) }),\n ];\n}\n","import type { CredentialStore, ProviderModule } from '@adport/core';\nimport { OpenAIAdsClient, type OpenAIAdsCredentials } from './client.js';\nimport { OpenAIAdsProvider } from './provider.js';\nimport { openaiTools } from './tools.js';\nexport { OpenAIAdsClient, OPENAI_ADS_API_BASE, type OpenAIAdsCredentials } from './client.js';\nexport { OpenAIAdsProvider } from './provider.js';\nexport { openaiTools } from './tools.js';\nexport { accountSchema, campaignSchema, insightRowSchema, type OpenAICampaign } from './schemas.js';\n\nexport function openaiCredentialsFromData(data: Record<string, string> | undefined): OpenAIAdsCredentials | undefined {\n const apiKey = data?.api_key?.trim();\n return apiKey ? { apiKey } : undefined;\n}\nexport function openaiEnvironmentData(): Record<string, string> {\n return { api_key: process.env.OPENAI_ADS_API_KEY ?? '' };\n}\nexport async function resolveOpenAICredentials(store: CredentialStore): Promise<OpenAIAdsCredentials | undefined> {\n return openaiCredentialsFromData((await store.get('openai'))?.data) ?? openaiCredentialsFromData(openaiEnvironmentData());\n}\nexport async function createOpenAIModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveOpenAICredentials(store);\n if (!credentials) return undefined;\n const provider = new OpenAIAdsProvider(new OpenAIAdsClient(credentials));\n return { provider, tools: openaiTools(provider) };\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;;;ACA5B,SAAS,SAAS;AAIX,IAAM,WAAW,EAAE,OAAO,EAAE,MAAM,wBAAwB;AAC1D,IAAM,eAAe,EAAE,KAAK,CAAC,UAAU,QAAQ,CAAC;AAEhD,IAAM,qBAAqB,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,GAAS,EAAE,IAAI,OAAO,gBAAgB;AAC7F,IAAM,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY;AACjD,IAAM,WAAW,EAAE,IAAI,SAAS,EAAE,QAAQ,KAAK,CAAC,EAAE,OAAO,WAAS;AAChE,QAAM,UAAU,KAAK,MAAM,KAAK,IAAI;AACpC,SAAO,WAAW,aAAa,WAAW;AAC5C,GAAG,oDAAoD;AACvD,IAAM,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAEhD,IAAM,gBAAgB,EAAE,YAAY;AAAA,EACzC,IAAI;AAAA,EAAU,MAAM,EAAE,OAAO;AAAA,EAAG,QAAQ,EAAE,OAAO,EAAE,SAAS;AAAA,EAAG,UAAU,EAAE,OAAO;AAAA,EAAG,eAAe,EAAE,OAAO;AAC/G,CAAC;AAGM,IAAM,eAAe,EAAE,YAAY;AAAA,EACxC,6BAA6B,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,SAAS;AAAA,EACrE,0BAA0B,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,SAAS;AACpE,CAAC;AACM,IAAM,iBAAiB,EAAE,YAAY;AAAA,EAC1C,IAAI;AAAA,EAA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CAAC;AAAA,IAC7H,iBAAiB;AAAA,MAAE,MAAM;AAAA,MAAwB,WAAW;AAAA,MAAU,UAAU;AAAA,MAAU,MAAM;AAAA,MAC9F,aAAa;AAAA,MAAuE,SAAS;AAAA,IAAkB,CAAC;AAAA,IAClH,iBAAiB;AAAA,MAAE,MAAM;AAAA,MAAqB,WAAW;AAAA,MAAU,UAAU;AAAA,MAAU,MAAM;AAAA,MAC3F,aAAa;AAAA,MAA+K,SAAS;AAAA,IAAgB,CAAC;AAAA,EAC1N;AACF;;;AEnBO,SAAS,0BAA0B,MAA4E;AACpH,QAAM,SAAS,MAAM,SAAS,KAAK;AACnC,SAAO,SAAS,EAAE,OAAO,IAAI;AAC/B;AACO,SAAS,wBAAgD;AAC9D,SAAO,EAAE,SAAS,QAAQ,IAAI,sBAAsB,GAAG;AACzD;AACA,eAAsB,yBAAyB,OAAmE;AAChH,SAAO,2BAA2B,MAAM,MAAM,IAAI,QAAQ,IAAI,IAAI,KAAK,0BAA0B,sBAAsB,CAAC;AAC1H;AACA,eAAsB,mBAAmB,OAA6D;AACpG,QAAM,cAAc,MAAM,yBAAyB,KAAK;AACxD,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,WAAW,IAAI,kBAAkB,IAAI,gBAAgB,WAAW,CAAC;AACvE,SAAO,EAAE,UAAU,OAAO,YAAY,QAAQ,EAAE;AAClD;","names":["z","AdportError","AdportError","metric","z","defineTool","AdportError","z","z","AdportError","defineTool"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adport/provider-openai",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.11.0",
|
|
4
|
+
"description": "OpenAI Ads API provider (ads in ChatGPT) for adport",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist"
|
|
17
|
+
],
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"zod": "^4.6.7",
|
|
20
|
+
"@adport/core": "0.11.0"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@types/node": "^26.6.6",
|
|
24
|
+
"tsup": "^8.3.0",
|
|
25
|
+
"typescript": "^5.8.0",
|
|
26
|
+
"vitest": "^4.1.10"
|
|
27
|
+
},
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "git+https://github.com/ynnickw/adport.git",
|
|
31
|
+
"directory": "packages/openai"
|
|
32
|
+
},
|
|
33
|
+
"homepage": "https://github.com/ynnickw/adport#readme",
|
|
34
|
+
"bugs": {
|
|
35
|
+
"url": "https://github.com/ynnickw/adport/issues"
|
|
36
|
+
},
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=22.13"
|
|
39
|
+
},
|
|
40
|
+
"publishConfig": {
|
|
41
|
+
"access": "public"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "tsup src/index.ts --format esm --dts --sourcemap --clean",
|
|
45
|
+
"test": "vitest run",
|
|
46
|
+
"typecheck": "tsc --noEmit"
|
|
47
|
+
}
|
|
6
48
|
}
|