@adport/provider-x 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/client.ts
2
- import { createHmac, randomBytes } from "crypto";
2
+ import { createHmac, randomBytes, timingSafeEqual } from "crypto";
3
3
  import OAuth from "oauth-1.0a";
4
4
  import { z } from "zod";
5
5
  import { AdportError } from "@adport/core";
@@ -21,30 +21,54 @@ var XAdsClient = class {
21
21
  }
22
22
  this.signer = createXSigner(credentials);
23
23
  this.token = { key: credentials.accessToken, secret: credentials.accessTokenSecret };
24
+ this.receiptKey = createHmac("sha256", credentials.consumerSecret).update(`adport.x.media.v1.${credentials.accessTokenSecret}`).digest();
24
25
  }
25
26
  fetchImpl;
26
27
  signer;
27
28
  token;
28
- async request(method, path, schema, params = {}) {
29
+ receiptKey;
30
+ async request(method, path, schema, params = {}, jsonBody) {
29
31
  if (!/^[a-z0-9_]+(?:\/[a-z0-9_]+)*$/.test(path)) throw new AdportError("INVALID_INPUT", "x: invalid API resource path");
30
- const url = new URL(path, X_ADS_API_BASE);
32
+ return this.send(method, new URL(path, X_ADS_API_BASE), schema, params, jsonBody);
33
+ }
34
+ async mediaRequest(method, path, schema, params = {}, jsonBody) {
35
+ if (!(method === "GET" ? path === "media/upload" : path === "media/upload/initialize" || /^media\/upload\/[1-9]\d{0,18}\/(?:append|finalize)$/.test(path))) throw new AdportError("INVALID_INPUT", "x: unsupported native media route");
36
+ return this.send(method, new URL(path, "https://api.x.com/2/"), schema, params, jsonBody);
37
+ }
38
+ resourceReceipt(value) {
39
+ const payload = Buffer.from(JSON.stringify(value)).toString("base64url");
40
+ return `${payload}.${createHmac("sha256", this.receiptKey).update(payload).digest("base64url")}`;
41
+ }
42
+ verifyResourceReceipt(receipt) {
43
+ const invalid = () => new AdportError("INVALID_INPUT", "x: invalid resource receipt; use the receipt from the approved upload");
44
+ if (receipt.length > 2048 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}$/.test(receipt)) throw invalid();
45
+ const [payload, signature] = receipt.split("."), expected = createHmac("sha256", this.receiptKey).update(payload).digest(), supplied = Buffer.from(signature, "base64url");
46
+ if (supplied.toString("base64url") !== signature || expected.length !== supplied.length || !timingSafeEqual(expected, supplied)) throw invalid();
47
+ try {
48
+ return JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
49
+ } catch {
50
+ throw invalid();
51
+ }
52
+ }
53
+ async send(method, url3, schema, params, jsonBody) {
54
+ const path = url3.pathname.replace(/^\/(?:12|2)\//, "");
31
55
  for (const [key, value] of Object.entries(params)) {
32
56
  if (!/^[a-z][a-z0-9_]*$/.test(key) || key.startsWith("oauth_") || typeof value === "number" && !Number.isFinite(value)) {
33
57
  throw new AdportError("INVALID_INPUT", "x: invalid API parameter");
34
58
  }
35
- url.searchParams.set(key, String(value));
59
+ url3.searchParams.set(key, String(value));
36
60
  }
37
- url.search = url.search.replace(/\+/g, "%20");
38
- const headers = this.signer.toHeader(this.signer.authorize({ url: url.href, method }, this.token));
61
+ url3.search = url3.search.replace(/\+/g, "%20");
62
+ const headers = this.signer.toHeader(this.signer.authorize({ url: url3.href, method }, this.token));
39
63
  let response;
40
64
  try {
41
- response = await this.fetchImpl(url.href, { method, headers: { ...headers, accept: "application/json" }, redirect: "error", signal: AbortSignal.timeout(3e4) });
65
+ response = await this.fetchImpl(url3.href, { method, headers: { ...headers, accept: "application/json", ...jsonBody !== void 0 ? { "content-type": "application/json" } : {} }, ...jsonBody !== void 0 ? { body: JSON.stringify(jsonBody) } : {}, redirect: "error", signal: AbortSignal.timeout(3e4) });
42
66
  } catch {
43
67
  throw new AdportError("PROVIDER_ERROR", `x: transport failed${method === "GET" ? "" : "; write outcome unknown, inspect the account before retrying"}`);
44
68
  }
45
69
  if (!response.ok) {
46
70
  const guidance = response.status === 403 ? "Check Ads API app approval and this user\u2019s ad-account permissions; reconnecting alone may not help." : response.status === 401 ? "Check OAuth 1.0a credentials, token permissions and the local clock. Regenerate user tokens after Ads API approval." : response.status === 429 ? "Rate limit reached; wait for the provider reset before retrying." : "Provider request failed.";
47
- throw new AdportError("PROVIDER_ERROR", `x: HTTP ${response.status}. ${guidance}${method === "GET" ? "" : " The write was not retried."}`);
71
+ throw new AdportError("PROVIDER_ERROR", `x: HTTP ${response.status}. ${guidance}${method === "GET" ? "" : " The write was not retried."}`, { http_status: response.status });
48
72
  }
49
73
  let body;
50
74
  try {
@@ -52,31 +76,54 @@ var XAdsClient = class {
52
76
  } catch {
53
77
  throw new AdportError("PROVIDER_ERROR", "x: invalid JSON response");
54
78
  }
55
- if (body && typeof body === "object" && "errors" in body && Array.isArray(body.errors) && body.errors.length) {
56
- throw new AdportError("PROVIDER_ERROR", "x: provider returned an error envelope");
79
+ const nonempty = (value) => Array.isArray(value) ? value.length > 0 : value && typeof value === "object" ? Object.keys(value).length > 0 : typeof value === "string" && value.length > 0;
80
+ if (body && typeof body === "object" && "errors" in body && nonempty(body.errors)) {
81
+ throw new AdportError("PROVIDER_ERROR", "x: provider returned an error envelope", mutationReceipt(method, path, body));
82
+ }
83
+ if (body && typeof body === "object" && "operation_errors" in body && nonempty(body.operation_errors)) {
84
+ const data = /^batch\/accounts\/[a-z0-9]+\/(?:targeting_criteria|line_items)$/.test(path) && "data" in body && Array.isArray(body.data) ? body.data : [];
85
+ const ids3 = data.flatMap((row) => row && typeof row === "object" && typeof row.id === "string" && /^[a-z0-9]{1,32}$/.test(row.id) ? [row.id] : []).slice(0, 500);
86
+ throw new AdportError("PROVIDER_ERROR", "x: provider rejected batch operations; inspect the account before retrying", { resource_ids: ids3 });
57
87
  }
58
88
  const parsed = schema.safeParse(body);
59
- if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "x: unexpected API response schema");
89
+ if (!parsed.success) {
90
+ throw new AdportError("PROVIDER_ERROR", `x: unexpected API response schema${method === "GET" ? "" : "; write may have succeeded, reconcile before retrying"}`, mutationReceipt(method, path, body));
91
+ }
60
92
  return parsed.data;
61
93
  }
62
94
  async list(path, item, params = {}) {
63
95
  const schema = z.object({ data: z.array(item), next_cursor: z.string().nullable().optional() });
64
- const rows = [], ids = /* @__PURE__ */ new Set(), cursors = /* @__PURE__ */ new Set();
65
- let cursor;
96
+ const rows2 = [], ids3 = /* @__PURE__ */ new Set(), cursors = /* @__PURE__ */ new Set();
97
+ let cursor2;
66
98
  while (true) {
67
- const page = await this.request("GET", path, schema, { ...params, count: 200, ...cursor ? { cursor } : {} });
68
- for (const row of page.data) {
69
- if (ids.has(row.id)) throw new AdportError("PROVIDER_ERROR", "x: pagination repeated an entity");
70
- ids.add(row.id);
71
- rows.push(row);
99
+ const page5 = await this.request("GET", path, schema, { ...params, count: 200, ...cursor2 ? { cursor: cursor2 } : {} });
100
+ for (const row of page5.data) {
101
+ if (ids3.has(row.id)) throw new AdportError("PROVIDER_ERROR", "x: pagination repeated an entity");
102
+ ids3.add(row.id);
103
+ rows2.push(row);
72
104
  }
73
- if (!page.next_cursor) return rows;
74
- if (cursors.has(page.next_cursor) || cursors.size >= 1e3) throw new AdportError("PROVIDER_ERROR", "x: cursor pagination did not terminate");
75
- cursors.add(page.next_cursor);
76
- cursor = page.next_cursor;
105
+ if (!page5.next_cursor) return rows2;
106
+ if (cursors.has(page5.next_cursor) || cursors.size >= 1e3) throw new AdportError("PROVIDER_ERROR", "x: cursor pagination did not terminate");
107
+ cursors.add(page5.next_cursor);
108
+ cursor2 = page5.next_cursor;
77
109
  }
78
110
  }
79
111
  };
112
+ function mutationReceipt(method, path, body) {
113
+ const ids3 = mutationIds(method, path, body);
114
+ const data = method === "POST" && /^accounts\/[a-z0-9]+\/promoted_tweets$/.test(path) && body && typeof body === "object" && "data" in body ? body.data : void 0;
115
+ const rows2 = Array.isArray(data) ? data : data && typeof data === "object" ? [data] : [];
116
+ const tweets = [...new Set(rows2.flatMap((row) => row && typeof row === "object" && typeof row.tweet_id === "string" && /^[1-9]\d{0,24}$/.test(row.tweet_id) ? [row.tweet_id] : []))].slice(0, 500);
117
+ return ids3.length || tweets.length ? { ...ids3.length ? { resource_ids: ids3 } : {}, ...tweets.length ? { reported_tweet_ids: tweets } : {} } : void 0;
118
+ }
119
+ function mutationIds(method, path, body) {
120
+ const data = method !== "GET" && /^(?:accounts\/[a-z0-9]+\/(?:(?:cards|draft_tweets|scheduled_tweets|scheduled_promoted_tweets|media_library|account_media|media_creatives|preroll_call_to_actions|line_items|campaigns|tracking_tags|promoted_tweets|promoted_accounts)(?:\/[a-z0-9_]+)?|tweet|tweets\/[1-9]\d{0,24}\/name)|media\/upload(?:\/[a-z0-9]+){1,2})$/.test(path) && body && typeof body === "object" && "data" in body ? body.data : void 0;
121
+ const rows2 = Array.isArray(data) ? data : data && typeof data === "object" ? [data] : [];
122
+ return [...new Set(rows2.flatMap((row) => row && typeof row === "object" ? ["id_str", "id", "media_key"].flatMap((key) => {
123
+ const value = row[key];
124
+ return typeof value === "string" && /^(?:[a-z0-9]{1,32}|\d{1,3}_[1-9]\d{0,24})$/.test(value) ? [value] : [];
125
+ }) : []))].slice(0, 500);
126
+ }
80
127
 
81
128
  // src/entities.ts
82
129
  import { z as z3 } from "zod";
@@ -116,16 +163,22 @@ var campaignSchema = z2.object({
116
163
  daily_budget_amount_local_micro: micros.nullable(),
117
164
  total_budget_amount_local_micro: micros.nullable()
118
165
  });
119
- var lineItemSchema = z2.object({
166
+ var lineItemSchema = z2.looseObject({
120
167
  id: xId,
121
- name: z2.string(),
168
+ name: z2.string().nullable(),
122
169
  campaign_id: xId,
123
170
  currency,
124
171
  entity_status: z2.string(),
125
172
  deleted: z2.boolean(),
126
173
  placements: z2.array(z2.string()),
127
174
  product_type: z2.string(),
128
- objective: z2.string()
175
+ objective: z2.string(),
176
+ bid_strategy: z2.string().optional(),
177
+ bid_amount_local_micro: micros.nullable().optional(),
178
+ daily_budget_amount_local_micro: micros.nullable().optional(),
179
+ total_budget_amount_local_micro: micros.nullable().optional(),
180
+ start_time: z2.string().nullable().optional(),
181
+ end_time: z2.string().nullable().optional()
129
182
  });
130
183
  var promotedTweetSchema = z2.object({
131
184
  id: xId,
@@ -181,6 +234,16 @@ var XAdsEntities = class {
181
234
  listLineItems(accountId) {
182
235
  return this.client.list(`accounts/${xId.parse(accountId)}/line_items`, lineItemSchema, { with_deleted: true, with_draft: true });
183
236
  }
237
+ async getLineItem(accountId, resourceId) {
238
+ const { data } = await this.client.request("GET", `accounts/${xId.parse(accountId)}/line_items/${xId.parse(resourceId)}`, z3.object({ data: lineItemSchema }));
239
+ if (data.id !== resourceId) throw new AdportError2("PROVIDER_ERROR", "x: line-item ID mismatch");
240
+ const campaign = await this.getCampaign(accountId, data.campaign_id);
241
+ if (campaign.currency !== data.currency) throw new AdportError2("PROVIDER_ERROR", "x: line-item currency differs from its campaign");
242
+ return data;
243
+ }
244
+ lineItemPlacements() {
245
+ return this.client.request("GET", "line_items/placements", z3.object({ data: z3.array(z3.object({ product_type: z3.string(), placements: z3.array(z3.array(z3.string())) })) }));
246
+ }
184
247
  listPromotedTweets(accountId) {
185
248
  return this.client.list(`accounts/${xId.parse(accountId)}/promoted_tweets`, promotedTweetSchema, { with_deleted: true });
186
249
  }
@@ -193,8 +256,8 @@ var XAdsEntities = class {
193
256
  };
194
257
 
195
258
  // src/provider.ts
196
- import { z as z6 } from "zod";
197
- import { AdportError as AdportError5, resolveDateRange } from "@adport/core";
259
+ import { z as z32 } from "zod";
260
+ import { AdportError as AdportError18, resolveDateRange } from "@adport/core";
198
261
 
199
262
  // src/analytics.ts
200
263
  import { gunzipSync } from "zlib";
@@ -210,8 +273,9 @@ var statsSchema = z4.object({
210
273
  billed_charge_local_micro: scalar,
211
274
  impressions: scalar,
212
275
  url_clicks: scalar
213
- }) })).length(1) })),
276
+ }).catchall(z4.json()) })).length(1) })),
214
277
  request: z4.object({ params: z4.object({
278
+ account_id: xId.optional(),
215
279
  start_time: z4.string(),
216
280
  end_time: z4.string(),
217
281
  entity: z4.string(),
@@ -260,7 +324,7 @@ var XAdsAnalytics = class {
260
324
  }
261
325
  async load(accountId, params, asynchronous, key) {
262
326
  xId.parse(accountId);
263
- if (!asynchronous) return validateStats(await this.client.request("GET", `stats/accounts/${accountId}`, statsSchema, params), params);
327
+ if (!asynchronous) return validateStats(await this.client.request("GET", `stats/accounts/${accountId}`, statsSchema, params), params, accountId);
264
328
  const path = `stats/jobs/accounts/${accountId}`;
265
329
  let job = this.jobs.get(key) ?? (await this.client.request("POST", path, z4.object({ data: jobSchema }), params)).data;
266
330
  validateJob(job, accountId, params);
@@ -272,7 +336,7 @@ var XAdsAnalytics = class {
272
336
  }
273
337
  if (job.status === "SUCCESS") {
274
338
  if (!job.url) throw new AdportError3("PROVIDER_ERROR", "x: successful analytics job has no download URL");
275
- const result = validateStats(await this.download(job.url, job.id_str), params);
339
+ const result = validateStats(await this.download(job.url, job.id_str), params, accountId);
276
340
  this.jobs.delete(key);
277
341
  return result;
278
342
  }
@@ -289,18 +353,18 @@ var XAdsAnalytics = class {
289
353
  throw new AdportError3("PROVIDER_ERROR", `x: analytics job ${job.id_str} is still processing; retry this report to resume polling`);
290
354
  }
291
355
  async download(raw, id) {
292
- let url;
356
+ let url3;
293
357
  try {
294
- url = new URL(raw);
358
+ url3 = new URL(raw);
295
359
  } catch {
296
360
  throw new AdportError3("PROVIDER_ERROR", "x: invalid analytics download URL");
297
361
  }
298
- if (url.origin !== "https://ton.twimg.com" || url.username || url.password || url.hash || url.pathname !== `/advertiser-api-async-analytics/stats_job_${id}.json.gz`) {
362
+ if (url3.origin !== "https://ton.twimg.com" || url3.username || url3.password || url3.hash || url3.pathname !== `/advertiser-api-async-analytics/stats_job_${id}.json.gz`) {
299
363
  throw new AdportError3("PROVIDER_ERROR", "x: untrusted analytics download URL");
300
364
  }
301
365
  let response;
302
366
  try {
303
- response = await this.fetchImpl(url.href, { redirect: "error", signal: AbortSignal.timeout(3e4) });
367
+ response = await this.fetchImpl(url3.href, { redirect: "error", signal: AbortSignal.timeout(3e4) });
304
368
  } catch {
305
369
  throw new AdportError3("PROVIDER_ERROR", "x: analytics download transport failed");
306
370
  }
@@ -336,31 +400,31 @@ function matches(data, params) {
336
400
  function validateJob(job, accountId, params) {
337
401
  if (job.account_id !== accountId || !matches(job, params)) throw new AdportError3("PROVIDER_ERROR", "x: analytics job scope does not match the report");
338
402
  }
339
- function validateStats(data, params) {
340
- const ids = String(params.entity_ids).split(","), returned = data.data.map((row) => row.id);
341
- if (!matches(data.request.params, params) || new Set(returned).size !== returned.length || returned.some((id) => !ids.includes(id)) || ids.some((id) => !returned.includes(id))) {
403
+ function validateStats(data, params, accountId) {
404
+ const ids3 = String(params.entity_ids).split(","), returned = data.data.map((row) => row.id);
405
+ if (data.request.params.account_id !== void 0 && data.request.params.account_id !== accountId || !matches(data.request.params, params) || new Set(returned).size !== returned.length || returned.some((id) => !ids3.includes(id)) || ids3.some((id) => !returned.includes(id))) {
342
406
  throw new AdportError3("PROVIDER_ERROR", "x: analytics returned incomplete, duplicate or incorrectly scoped data");
343
407
  }
344
408
  return data;
345
409
  }
346
410
  function xAccountMidnight(date, timezone) {
347
411
  z4.iso.date().parse(date);
348
- const target = Date.parse(`${date}T00:00:00Z`);
412
+ const target2 = Date.parse(`${date}T00:00:00Z`);
349
413
  let format;
350
414
  try {
351
415
  format = new Intl.DateTimeFormat("en-GB", { timeZone: timezone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" });
352
416
  } catch {
353
417
  throw new AdportError3("PROVIDER_ERROR", "x: invalid account timezone");
354
418
  }
355
- let value = target;
419
+ let value = target2;
356
420
  for (let i = 0; i < 5; i++) {
357
421
  const parts = Object.fromEntries(format.formatToParts(new Date(value)).map((p) => [p.type, p.value]));
358
422
  const rendered = Date.parse(`${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}Z`);
359
- if (rendered === target) {
423
+ if (rendered === target2) {
360
424
  if (value % 36e5 !== 0) throw new AdportError3("INVALID_INPUT", "x: account-local midnight is not a whole UTC hour; the API cannot represent this exact date boundary");
361
425
  return value;
362
426
  }
363
- value += target - rendered;
427
+ value += target2 - rendered;
364
428
  }
365
429
  throw new AdportError3("INVALID_INPUT", "x: no midnight exists for this account-local report date");
366
430
  }
@@ -434,15 +498,2792 @@ async function planXWrite(entities, op, guard) {
434
498
  throw new AdportError4("INVALID_INPUT", `x: unsupported write ${op.tool}`);
435
499
  }
436
500
 
501
+ // src/management.ts
502
+ import { AdportError as AdportError5 } from "@adport/core";
503
+ import { z as z7 } from "zod";
504
+
505
+ // src/management-tools.ts
506
+ import { defineTool, guardedWriteTool } from "@adport/core";
507
+ import { z as z6 } from "zod";
508
+ var micros2 = z6.number().int().positive().safe();
509
+ var objective = z6.enum(["APP_ENGAGEMENTS", "APP_INSTALLS", "REACH", "FOLLOWERS", "ENGAGEMENTS", "VIDEO_VIEWS", "PREROLL_VIEWS", "WEBSITE_CLICKS"]);
510
+ var placement = z6.enum(["ALL_ON_TWITTER", "PUBLISHER_NETWORK", "TAP_BANNER", "TAP_FULL", "TAP_FULL_LANDSCAPE", "TAP_NATIVE", "TAP_MRECT", "TWITTER_PROFILE", "TWITTER_REPLIES", "TWITTER_SEARCH", "TWITTER_TIMELINE"]);
511
+ var time = z6.iso.datetime({ offset: true });
512
+ var name = z6.string().min(1).max(255);
513
+ var goal = z6.enum(["APP_CLICKS", "APP_INSTALLS", "APP_PURCHASES", "ENGAGEMENT", "FOLLOWERS", "LINK_CLICKS", "MAX_REACH", "PREROLL", "PREROLL_STARTS", "REACH_WITH_ENGAGEMENT", "SITE_VISITS", "VIDEO_VIEW", "VIEW_3S_100PCT", "VIEW_6S", "VIEW_15S", "WEBSITE_CONVERSIONS"]);
514
+ var createLine = z6.object({ campaign_id: xId, name, objective, product_type: z6.enum(["MEDIA", "PROMOTED_ACCOUNT", "PROMOTED_TWEETS"]), placements: z6.array(placement).min(1).max(10).refine((v) => new Set(v).size === v.length, "Use unique placements"), start_time: time, end_time: time, status: z6.enum(["ACTIVE", "PAUSED"]).default("PAUSED"), bid_strategy: z6.enum(["AUTO", "MAX", "TARGET"]).default("AUTO"), bid_micros: micros2.optional(), daily_budget_micros: micros2.optional(), total_budget_micros: micros2.optional(), android_app_store_identifier: z6.string().min(1).optional(), ios_app_store_identifier: z6.string().regex(/^\d+$/).optional(), advertiser_domain: z6.string().regex(/^(?![.-])[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/).optional(), categories: z6.array(z6.string().min(1)).optional(), standard_delivery: z6.boolean().default(true), goal: goal.optional(), primary_web_event_tag: xId.optional(), expected_web_event_tag_hash: z6.string().regex(/^[a-f0-9]{64}$/).optional() }).refine((v) => Date.parse(v.end_time) > Date.parse(v.start_time), "End must follow start").refine((v) => v.daily_budget_micros === void 0 || v.total_budget_micros === void 0 || v.daily_budget_micros <= v.total_budget_micros, "Daily budget cannot exceed total").refine((v) => v.primary_web_event_tag !== void 0 === (v.expected_web_event_tag_hash !== void 0), "Provide both primary_web_event_tag and expected_web_event_tag_hash").refine((v) => v.goal !== "WEBSITE_CONVERSIONS" || v.primary_web_event_tag !== void 0, "WEBSITE_CONVERSIONS requires a primary_web_event_tag and its current hash");
515
+ var updateLine = z6.object({ line_item_id: xId, name: name.optional(), start_time: time.optional(), end_time: time.optional() }).refine((v) => Object.keys(v).length > 1, "Provide line-item changes");
516
+ var setLineBid = z6.object({ line_item_id: xId, bid_strategy: z6.enum(["AUTO", "MAX", "TARGET"]).optional(), bid_micros: micros2.optional() }).refine((v) => v.bid_strategy !== void 0 || v.bid_micros !== void 0, "Provide bid settings");
517
+ function xManagementTools(provider) {
518
+ const write = (name3, description, payload, kind = "update") => guardedWriteTool({ name: name3, namespace: "x", provider: "x", description, payload, kind });
519
+ return [
520
+ defineTool({ name: "x_line_item_placements", namespace: "x", description: "Read current native placement combinations by product type after verifying access to the selected account.", input: z6.object({ account_id: xId }), annotations: { readOnly: true }, handler: async (v) => {
521
+ await provider.getAccount(v.account_id);
522
+ return provider.lineItemPlacements();
523
+ } }),
524
+ write("x_create_line_item", "Create a paused X ad group with explicit objective, product, placements and flight. Budgets/bids use micros; AUTO cannot claim a monetary bid cap. Parent currency and sibling format are checked. Optional native goal and primary conversion tag require a fresh tag hash; native eligibility remains authoritative.", createLine, "create"),
525
+ write("x_update_line_item", "Edit supplied line-item name/start/end fields, preserving omitted schedule bounds and delivery status.", updateLine),
526
+ write("x_set_line_item_status", "Pause or activate a verified line item using native PUT. Draft/deleted line items are rejected.", z6.object({ line_item_id: xId, status: z6.enum(["PAUSED", "ACTIVE"]) })),
527
+ write("x_set_line_item_budget", "Change an existing line-item daily or total cap in integer micros, preserving the other cap and using current values for policy checks.", z6.object({ line_item_id: xId, budget_type: z6.enum(["DAILY", "TOTAL"]), budget_micros: micros2 })),
528
+ write("x_set_line_item_bidding", "Change native AUTO/MAX/TARGET bidding with current monetary values. Removing a bounded bid via AUTO is rejected because policy cannot represent an unbounded change.", setLineBid),
529
+ write("x_delete_line_item", "Delete a verified line item only after its promoted posts/accounts/media creatives are removed. Native receipt must confirm deletion.", z6.object({ line_item_id: xId }), "remove")
530
+ ];
531
+ }
532
+
533
+ // src/management.ts
534
+ var XManagementService = class {
535
+ constructor(entities, measurement) {
536
+ this.entities = entities;
537
+ this.measurement = measurement;
538
+ }
539
+ entities;
540
+ measurement;
541
+ bid(objective2, strategy, amount, create) {
542
+ if (strategy === "AUTO" && amount !== void 0) throw new AdportError5("INVALID_INPUT", "x: AUTO ignores bid amounts; do not supply a purported monetary cap");
543
+ if (strategy !== "AUTO" && !micros2.safeParse(amount).success) throw new AdportError5("INVALID_INPUT", "x: MAX/TARGET require a positive safe integer bid in micros");
544
+ if (strategy === "MAX" && ["REACH", "FOLLOWERS"].includes(objective2)) throw new AdportError5("INVALID_INPUT", "x: MAX is unavailable for REACH/FOLLOWERS");
545
+ if (strategy === "TARGET" && !(create ? ["REACH", "FOLLOWERS", "WEBSITE_CLICKS"] : ["REACH", "WEBSITE_CLICKS"]).includes(objective2)) throw new AdportError5("INVALID_INPUT", "x: TARGET is not documented for this objective/operation");
546
+ }
547
+ verify(data, currency2, expected) {
548
+ const matches2 = (key, value) => value === null ? data[key] === null : ["placements", "categories"].includes(key) ? Array.isArray(data[key]) && [...data[key]].sort().join(",") === String(value).split(",").sort().join(",") : ["start_time", "end_time"].includes(key) ? Date.parse(String(data[key])) === Date.parse(String(value)) : data[key] === value;
549
+ if (data.currency !== currency2 || Object.entries(expected).some(([key, value]) => !matches2(key, value))) throw new AdportError5("PROVIDER_ERROR", "x: line-item receipt ID/parent/status/money mismatch; reconcile before retrying", { resource_ids: [data.id] });
550
+ }
551
+ async receipt(method, path, params, currency2, expected) {
552
+ const { data } = await this.entities.client.request(method, path, z7.object({ data: lineItemSchema }), params);
553
+ this.verify(data, currency2, expected);
554
+ return [data.id];
555
+ }
556
+ async plan(op, guard) {
557
+ const account = xId.parse(op.accountId), create = op.tool === "x_create_line_item", remove = op.tool === "x_delete_line_item";
558
+ if (op.provider !== "x" || op.kind !== (create ? "create" : remove ? "remove" : "update")) throw new AdportError5("INVALID_INPUT", "x: provider or line-item operation kind mismatch");
559
+ const base = `accounts/${account}/line_items`, coercions = [], budgetDeltas = [];
560
+ let current, params = {}, expected, path = base, method = create ? "POST" : "PUT";
561
+ if (create) {
562
+ const input = createLine.parse(op.payload), campaign = await this.entities.getCampaign(account, input.campaign_id);
563
+ if (campaign.deleted || campaign.entity_status === "DRAFT" || campaign.budget_optimization !== "LINE_ITEM") throw new AdportError5("INVALID_INPUT", "x: creation requires an existing non-deleted/non-draft LINE_ITEM-budget campaign");
564
+ const choices = await this.entities.lineItemPlacements(), selected = [...input.placements].sort().join(",");
565
+ if (!choices.data.some((value2) => value2.product_type === input.product_type && value2.placements.some((placements) => [...placements].sort().join(",") === selected))) throw new AdportError5("INVALID_INPUT", "x: placement combination is unavailable for this product; inspect x_line_item_placements");
566
+ const siblings = (await this.entities.listLineItems(account)).filter((value2) => value2.campaign_id === input.campaign_id && !value2.deleted);
567
+ if (siblings.some((value2) => value2.objective !== input.objective || value2.product_type !== input.product_type)) throw new AdportError5("INVALID_INPUT", "x: all campaign line items must share product_type and objective");
568
+ this.bid(input.objective, input.bid_strategy, input.bid_micros, true);
569
+ if (["APP_INSTALLS", "APP_ENGAGEMENTS"].includes(input.objective) && !input.android_app_store_identifier && !input.ios_app_store_identifier) throw new AdportError5("INVALID_INPUT", "x: app objectives need an explicit app-store identifier; native platform targeting is added automatically");
570
+ if (input.placements.includes("PUBLISHER_NETWORK") && (!input.advertiser_domain || !input.categories?.length)) throw new AdportError5("INVALID_INPUT", "x: publisher placement needs advertiser_domain and IAB categories");
571
+ if (input.goal === "SITE_VISITS" && input.objective !== "WEBSITE_CLICKS" || input.goal === "APP_PURCHASES" && input.objective !== "APP_INSTALLS" || ["APP_CLICKS", "APP_INSTALLS"].includes(input.goal ?? "") && !["APP_INSTALLS", "APP_ENGAGEMENTS"].includes(input.objective)) throw new AdportError5("INVALID_INPUT", "x: goal is not documented for the selected objective");
572
+ const primary = input.primary_web_event_tag ? (await this.measurement.getWeb({ account_id: account, web_event_tag_id: input.primary_web_event_tag })).data : void 0;
573
+ if (primary && primary.configuration_hash !== input.expected_web_event_tag_hash) throw new AdportError5("INVALID_INPUT", "x: primary web event tag configuration changed; read and preview it again");
574
+ const status = guard.forcePausedCreation ? "PAUSED" : input.status;
575
+ if (status !== input.status) coercions.push("entity_status coerced to PAUSED by policy (paused_creation)");
576
+ params = { campaign_id: input.campaign_id, name: input.name, objective: input.objective, product_type: input.product_type, placements: input.placements.join(","), start_time: input.start_time, end_time: input.end_time, entity_status: status, bid_strategy: input.bid_strategy, standard_delivery: input.standard_delivery };
577
+ for (const key of ["android_app_store_identifier", "ios_app_store_identifier", "advertiser_domain", "goal", "primary_web_event_tag"]) if (input[key] !== void 0) params[key] = input[key];
578
+ if (input.categories) params.categories = input.categories.join(",");
579
+ for (const [source, target2] of [["bid_micros", "bid_amount_local_micro"], ["daily_budget_micros", "daily_budget_amount_local_micro"], ["total_budget_micros", "total_budget_amount_local_micro"]]) if (input[source] !== void 0) {
580
+ params[target2] = input[source];
581
+ budgetDeltas.push({ target: `new line item ${target2}`, toMicros: input[source] });
582
+ }
583
+ expected = { ...params, deleted: false };
584
+ const measurementNotes = ["Native objective/goal/account eligibility is checked by X on apply; this is a local preview.", "No pixel code is installed and no conversion event is sent. Event status does not prove current measurement accuracy."];
585
+ return {
586
+ summary: `Create X line item ${input.name}`,
587
+ changes: [`Native POST ${base}: ${JSON.stringify(params)}; currency ${campaign.currency}. ${input.android_app_store_identifier || input.ios_app_store_identifier ? "Native app-store parameters add platform targeting." : ""}`],
588
+ coercions,
589
+ budgetDeltas,
590
+ ...input.goal || primary ? { notes: measurementNotes, review: { provider: "x", accountId: account, kind: "create", title: "Create ad group", subject: input.name, fields: [{ label: "Campaign", after: campaign.name }, { label: "Objective", after: input.objective }, { label: "Goal", after: input.goal ?? "Native default" }, { label: "Status", after: status }, { label: "Placements", after: input.placements.join(", ") }, { label: "Start", after: input.start_time }, { label: "End", after: input.end_time }, { label: "Bid strategy", after: input.bid_strategy }, ...primary ? [{ label: "Primary event", after: `${primary.name} \xB7 ${primary.id}` }, { label: "Event type", after: primary.type }, { label: "Native event status", after: typeof primary.status === "string" ? primary.status : "Not reported" }] : [], ...budgetDeltas.map((value2) => ({ label: value2.target.endsWith("bid_amount_local_micro") ? "Bid" : value2.target.endsWith("daily_budget_amount_local_micro") ? "Daily budget" : "Total budget", after: value2.toMicros, format: "money", currency: campaign.currency }))], notices: measurementNotes } } : {},
591
+ execute: async () => {
592
+ let created;
593
+ try {
594
+ const ids3 = await this.receipt("POST", base, params, campaign.currency, expected);
595
+ created = ids3[0];
596
+ if (input.goal || primary) this.verify(await this.entities.getLineItem(account, created), campaign.currency, { ...expected, id: created });
597
+ return ids3;
598
+ } catch (error) {
599
+ if (!created) throw error;
600
+ throw new AdportError5("PROVIDER_ERROR", "x: created ad-group measurement configuration is unconfirmed; inspect the known ID before another create; do not replay automatically", { resource_ids: [created] });
601
+ }
602
+ }
603
+ };
604
+ }
605
+ current = await this.entities.getLineItem(account, xId.parse(op.payload.line_item_id));
606
+ if (current.deleted || current.entity_status === "DRAFT") throw new AdportError5("INVALID_INPUT", "x: deleted/draft line items are not editable through this workflow");
607
+ const parent = await this.entities.getCampaign(account, current.campaign_id);
608
+ if (!remove && (parent.deleted || parent.entity_status === "DRAFT")) throw new AdportError5("INVALID_INPUT", "x: parent campaign is deleted or draft");
609
+ path = `${base}/${current.id}`;
610
+ if (remove) {
611
+ if (!["PROMOTED_TWEETS", "PROMOTED_ACCOUNT", "MEDIA"].includes(current.product_type)) throw new AdportError5("INVALID_INPUT", "x: unsupported product type; child ownership cannot be proven for deletion");
612
+ const [posts, media, users] = await Promise.all([current.product_type !== "MEDIA" ? this.entities.listPromotedTweets(account) : [], current.product_type === "MEDIA" ? this.entities.listMediaCreatives(account) : [], current.product_type === "PROMOTED_ACCOUNT" ? this.entities.listPromotedAccounts(account) : []]);
613
+ if ([...posts, ...media, ...users].some((value2) => value2.line_item_id === current.id && !value2.deleted)) throw new AdportError5("INVALID_INPUT", "x: remove line-item promotions/media before deleting their parent");
614
+ method = "DELETE";
615
+ expected = { id: current.id, campaign_id: current.campaign_id, deleted: true };
616
+ } else {
617
+ switch (op.tool) {
618
+ case "x_update_line_item": {
619
+ const { line_item_id: _id, ...input } = updateLine.parse(op.payload);
620
+ params = input;
621
+ const start = String(input.start_time ?? current.start_time ?? ""), end = String(input.end_time ?? current.end_time ?? "");
622
+ if (end && (!start || Date.parse(end) <= Date.parse(start))) throw new AdportError5("INVALID_INPUT", "x: merged end time must follow start");
623
+ break;
624
+ }
625
+ case "x_set_line_item_status":
626
+ params = { entity_status: z7.enum(["ACTIVE", "PAUSED"]).parse(op.payload.status) };
627
+ break;
628
+ case "x_set_line_item_budget": {
629
+ const key = z7.enum(["DAILY", "TOTAL"]).parse(op.payload.budget_type) === "DAILY" ? "daily_budget_amount_local_micro" : "total_budget_amount_local_micro", previous = current[key], target2 = micros2.parse(op.payload.budget_micros);
630
+ if (!Number.isSafeInteger(previous) || previous === null || previous === void 0) throw new AdportError5("INVALID_INPUT", "x: an existing budget of the same type is required");
631
+ if (parent.budget_optimization !== "LINE_ITEM") throw new AdportError5("INVALID_INPUT", "x: line-item budgets require LINE_ITEM parent budget optimization");
632
+ const daily = key === "daily_budget_amount_local_micro" ? target2 : current.daily_budget_amount_local_micro, total = key === "total_budget_amount_local_micro" ? target2 : current.total_budget_amount_local_micro;
633
+ if (daily !== null && daily !== void 0 && total !== null && total !== void 0 && daily > total) throw new AdportError5("INVALID_INPUT", "x: daily budget cannot exceed total");
634
+ params = { [key]: target2 };
635
+ budgetDeltas.push({ target: `line item ${current.id} ${key}`, fromMicros: previous, toMicros: target2 });
636
+ break;
637
+ }
638
+ case "x_set_line_item_bidding": {
639
+ const input = setLineBid.parse(op.payload), strategy = input.bid_strategy ?? current.bid_strategy;
640
+ if (!strategy || !["AUTO", "MAX", "TARGET"].includes(strategy)) throw new AdportError5("INVALID_INPUT", "x: current bidding strategy is unavailable");
641
+ if (strategy === "AUTO" && current.bid_strategy !== "AUTO") throw new AdportError5("INVALID_INPUT", "x: removing a monetary bid cap via AUTO cannot be represented by current policy");
642
+ const previous = current.bid_strategy === "AUTO" ? void 0 : current.bid_amount_local_micro, amount = input.bid_micros ?? previous;
643
+ if (current.bid_strategy !== "AUTO" && (previous === void 0 || previous === null)) throw new AdportError5("INVALID_INPUT", "x: current monetary bid is unavailable");
644
+ this.bid(current.objective, strategy, amount, false);
645
+ params = { ...input.bid_strategy ? { bid_strategy: strategy } : {}, ...input.bid_micros !== void 0 ? { bid_amount_local_micro: input.bid_micros } : {} };
646
+ if (input.bid_micros !== void 0) budgetDeltas.push({ target: `line item ${current.id} bid`, ...previous !== void 0 && previous !== null ? { fromMicros: previous } : {}, toMicros: input.bid_micros });
647
+ break;
648
+ }
649
+ default:
650
+ throw new AdportError5("INVALID_INPUT", `x: unsupported management write ${op.tool}`);
651
+ }
652
+ const preserved = Object.fromEntries(["id", "campaign_id", "deleted", "entity_status", "name", "objective", "product_type", "placements", "bid_strategy", "bid_amount_local_micro", "daily_budget_amount_local_micro", "total_budget_amount_local_micro", "start_time", "end_time", "standard_delivery"].filter((key) => current[key] !== void 0).map((key) => [key, current[key]]));
653
+ expected = { ...preserved, ...params };
654
+ }
655
+ const value = current;
656
+ return { summary: `${remove ? "Delete" : "Update"} X line item ${value.name ?? value.id}`, changes: [`Native ${method} ${path}: ${JSON.stringify(params)}`], coercions, budgetDeltas, execute: () => this.receipt(method, path, params, value.currency, expected) };
657
+ }
658
+ };
659
+
660
+ // src/targeting.ts
661
+ import { AdportError as AdportError6 } from "@adport/core";
662
+ import { z as z9 } from "zod";
663
+
664
+ // src/targeting-tools.ts
665
+ import { defineTool as defineTool2, guardedWriteTool as guardedWriteTool2 } from "@adport/core";
666
+ import { z as z8 } from "zod";
667
+ var optionDimensions = z8.enum(["app_store_categories", "conversations", "devices", "events", "interests", "languages", "locations", "network_operators", "platform_versions", "platforms", "tv_markets", "tv_shows"]);
668
+ var optionsInput = z8.object({ account_id: xId, dimension: optionDimensions, count: z8.number().int().min(1).max(1e3).default(50), cursor: z8.string().optional(), q: z8.string().min(1).max(255).optional(), os_type: z8.enum(["ANDROID", "IOS"]).optional(), country_code: z8.string().regex(/^[A-Z]{2}$/).optional(), country_codes: z8.array(z8.string().regex(/^[A-Z]{2}$/)).min(1).max(100).optional(), location_type: z8.enum(["COUNTRIES", "REGIONS", "METROS", "CITIES", "POSTAL_CODES"]).optional(), conversation_type: z8.string().regex(/^[A-Z_]+$/).optional(), event_types: z8.array(z8.enum(["CONFERENCE", "HOLIDAY", "MUSIC_AND_ENTERTAINMENT", "OTHER", "POLITICS", "RECURRING", "SPORTS"])).min(1).optional(), start_time: z8.iso.datetime({ offset: true }).optional(), end_time: z8.iso.datetime({ offset: true }).optional(), locale: z8.string().regex(/^[a-z]{2}-[A-Z]{2}$/).optional(), lang: z8.string().regex(/^[a-z]{2}$/).optional() });
669
+ var criteriaInput = z8.object({ account_id: xId, line_item_ids: z8.array(xId).min(1).max(20), count: z8.number().int().min(1).max(1e3).default(100), cursor: z8.string().optional(), with_deleted: z8.boolean().default(false) });
670
+ var addCriterion = z8.object({ line_item_id: xId, targeting_type: z8.enum(["AGE", "DEVICE", "EVENT", "CAMPAIGN_ENGAGEMENT", "CAMPAIGN_ENGAGEMENT_LOOKALIKE", "CONVERSATION", "ENGAGEMENT_TYPE", "FOLLOWERS_OF_USER", "GENDER", "INTEREST", "LANGUAGE", "LIVE_TV_EVENT", "LOCATION", "NETWORK_ACTIVATION_DURATION", "NETWORK_OPERATOR", "PLATFORM", "PLATFORM_VERSION", "SIMILAR_TO_FOLLOWERS_OF_USER", "TV_SHOW", "USER_ENGAGEMENT", "USER_ENGAGEMENT_LOOKALIKE", "WIFI_ONLY", "BROAD_KEYWORD", "EXACT_KEYWORD", "PHRASE_KEYWORD", "UNORDERED_KEYWORD", "CUSTOM_AUDIENCE", "CUSTOM_AUDIENCE_EXPANDED", "APP_STORE_CATEGORY", "APP_STORE_CATEGORY_LOOKALIKE", "APP_LIST"]), targeting_value: z8.string().min(1).max(2e3), operator_type: z8.enum(["EQ", "NE", "GTE", "LT"]).default("EQ") });
671
+ var updateCriteria = z8.object({ line_item_id: xId, add: z8.array(addCriterion.omit({ line_item_id: true })).max(500).default([]), remove: z8.array(xId).max(500).default([]) }).refine((v) => v.add.length + v.remove.length >= 1 && v.add.length + v.remove.length <= 500, "Provide 1\u2013500 combined operations").refine((v) => new Set(v.remove).size === v.remove.length, "Use unique removal IDs");
672
+ function xTargetingTools(provider) {
673
+ return [
674
+ defineTool2({ name: "x_targeting_options", namespace: "x", description: "Read current native targeting choices. Filters are checked per dimension. Unpaged dimensions use count as a local limit and report potential truncation.", input: optionsInput, annotations: { readOnly: true }, handler: (v) => provider.targeting.options(v) }),
675
+ defineTool2({ name: "x_targeting_criteria", namespace: "x", description: "Read native criteria for selected verified line items, including type/value/operator and native cursor pagination.", input: criteriaInput, annotations: { readOnly: true }, handler: (v) => provider.targeting.criteria(v) }),
676
+ defineTool2({ name: "x_get_targeting_criterion", namespace: "x", description: "Read one criterion and verify its line-item/campaign account hierarchy.", input: z8.object({ account_id: xId, targeting_criterion_id: xId }), annotations: { readOnly: true }, handler: (v) => provider.targeting.owned(v.account_id, v.targeting_criterion_id) }),
677
+ guardedWriteTool2({ name: "x_add_targeting_criterion", namespace: "x", provider: "x", kind: "create", description: "Add one native criterion without replacing other dimensions. Referenced audiences/campaigns/users/apps are verified. Can change an active group\u2019s audience immediately.", payload: addCriterion }),
678
+ guardedWriteTool2({ name: "x_remove_targeting_criterion", namespace: "x", provider: "x", kind: "remove", description: "Remove one verified native criterion. Preview identifies removal of the last location bound. Multi-step replacements should be reviewed with the group paused.", payload: z8.object({ targeting_criterion_id: xId }) }),
679
+ guardedWriteTool2({ name: "x_update_targeting", namespace: "x", provider: "x", kind: "update", description: "Atomically add/remove 1\u2013500 criteria on one verified line item through native JSON batch. Checks final targeting dependencies, source availability and each ordered receipt; other dimensions remain unchanged.", payload: updateCriteria })
680
+ ];
681
+ }
682
+
683
+ // src/targeting.ts
684
+ var rows = z9.array(z9.record(z9.string(), z9.unknown()));
685
+ var criterion = z9.looseObject({ id: xId, line_item_id: xId, targeting_type: z9.string(), targeting_value: z9.string(), operator_type: z9.string().optional(), deleted: z9.boolean() });
686
+ var includedLocation = (value) => value.targeting_type === "LOCATION" && value.operator_type !== "NE";
687
+ var optionParams = { app_store_categories: ["q", "os_type"], conversations: ["conversation_type", "count", "cursor"], devices: ["count", "q"], events: ["event_types", "count", "country_codes", "cursor", "end_time", "start_time"], interests: ["count", "cursor", "q"], languages: ["count", "cursor", "q"], locations: ["count", "country_code", "cursor", "location_type", "q"], network_operators: ["count", "country_code", "cursor", "q"], platform_versions: ["q"], platforms: ["count", "q", "lang"], tv_markets: [], tv_shows: ["locale", "count", "cursor", "q"] };
688
+ var XTargetingService = class {
689
+ constructor(entities) {
690
+ this.entities = entities;
691
+ }
692
+ entities;
693
+ async options(value) {
694
+ const input = optionsInput.parse(value), allowed = optionParams[input.dimension];
695
+ if (input.dimension === "tv_shows" && (!input.locale || input.count > 50)) throw new AdportError6("INVALID_INPUT", "x: TV shows require locale and count <=50");
696
+ const params = {};
697
+ for (const [key, value2] of Object.entries(input)) {
698
+ if (["account_id", "dimension"].includes(key) || value2 === void 0 || key === "count" && !allowed.includes("count")) continue;
699
+ if (!allowed.includes(key)) throw new AdportError6("INVALID_INPUT", `x: ${key} is not supported for targeting ${input.dimension}`);
700
+ params[key] = Array.isArray(value2) ? value2.join(",") : value2;
701
+ }
702
+ await this.entities.getAccount(input.account_id);
703
+ const result = await this.entities.client.request("GET", `targeting_criteria/${input.dimension}`, z9.object({ data: rows, next_cursor: z9.string().nullable().optional() }), params), paged = allowed.includes("cursor"), next = paged ? result.next_cursor ?? void 0 : void 0;
704
+ if (next && next === input.cursor) throw new AdportError6("PROVIDER_ERROR", "x: targeting pagination repeated its cursor");
705
+ if (paged && result.data.length > 1e3) throw new AdportError6("PROVIDER_ERROR", "x: native targeting page exceeds its documented maximum");
706
+ const limited = !paged && (result.data.length > input.count || Boolean(result.next_cursor) || allowed.includes("count") && result.data.length >= input.count);
707
+ return { items: paged ? result.data : result.data.slice(0, input.count), truncated: Boolean(next) || limited, ...next ? { next_cursor: next } : {}, ...limited ? { warning: "Native endpoint has no documented usable continuation for this limit. Narrow the filter or increase count." } : paged && result.data.length > input.count ? { warning: "Native endpoint exceeded the requested count; the complete page is retained so continuation skips no choices." } : {} };
708
+ }
709
+ async criteria(value) {
710
+ const input = criteriaInput.parse(value), wanted = [...new Set(input.line_item_ids)];
711
+ let index = 0;
712
+ await Promise.all(Array.from({ length: Math.min(4, wanted.length) }, async () => {
713
+ while (index < wanted.length) await this.entities.getLineItem(input.account_id, wanted[index++]);
714
+ }));
715
+ const page5 = await this.entities.client.request("GET", `accounts/${input.account_id}/targeting_criteria`, z9.object({ data: z9.array(criterion), next_cursor: z9.string().nullable().optional() }), { line_item_ids: wanted.join(","), count: input.count, with_deleted: input.with_deleted, ...input.cursor ? { cursor: input.cursor } : {} });
716
+ if (page5.data.some((value2) => !wanted.includes(value2.line_item_id) || !input.with_deleted && value2.deleted)) throw new AdportError6("PROVIDER_ERROR", "x: criteria list returned another line item or an excluded deleted row");
717
+ if (new Set(page5.data.map((value2) => value2.id)).size !== page5.data.length) throw new AdportError6("PROVIDER_ERROR", "x: criteria list repeated an entity");
718
+ if (page5.next_cursor && page5.next_cursor === input.cursor) throw new AdportError6("PROVIDER_ERROR", "x: criteria pagination repeated its cursor");
719
+ return { items: page5.data, truncated: Boolean(page5.next_cursor), ...page5.next_cursor ? { next_cursor: page5.next_cursor } : {} };
720
+ }
721
+ async owned(account, resource) {
722
+ const { data } = await this.entities.client.request("GET", `accounts/${xId.parse(account)}/targeting_criteria/${xId.parse(resource)}`, z9.object({ data: criterion }));
723
+ if (data.id !== resource) throw new AdportError6("PROVIDER_ERROR", "x: criterion ID mismatch");
724
+ await this.entities.getLineItem(account, data.line_item_id);
725
+ return data;
726
+ }
727
+ async current(account, line) {
728
+ const items = [], seen = /* @__PURE__ */ new Set(), ids3 = /* @__PURE__ */ new Set();
729
+ let cursor2;
730
+ while (true) {
731
+ const page5 = await this.entities.client.request("GET", `accounts/${account}/targeting_criteria`, z9.object({ data: z9.array(criterion), next_cursor: z9.string().nullable().optional() }), { line_item_ids: line, with_deleted: false, count: 1e3, ...cursor2 ? { cursor: cursor2 } : {} });
732
+ if (page5.data.some((value) => value.line_item_id !== line || value.deleted)) throw new AdportError6("PROVIDER_ERROR", "x: current criteria scope/deletion mismatch");
733
+ if (page5.data.length > 1e3 || items.length + page5.data.length > 5e3) throw new AdportError6("INVALID_INPUT", "x: criteria context exceeds the safe mutation limit");
734
+ for (const value of page5.data) {
735
+ if (ids3.has(value.id)) throw new AdportError6("PROVIDER_ERROR", "x: criteria pagination repeated an entity");
736
+ ids3.add(value.id);
737
+ }
738
+ items.push(...page5.data);
739
+ if (!page5.next_cursor) return items;
740
+ if (items.length >= 5e3 || seen.has(page5.next_cursor) || seen.size >= 25) throw new AdportError6("INVALID_INPUT", "x: criteria context exceeds the safe mutation limit or repeats pages");
741
+ seen.add(page5.next_cursor);
742
+ cursor2 = page5.next_cursor;
743
+ }
744
+ }
745
+ async available(account, collection, find) {
746
+ const seen = /* @__PURE__ */ new Set();
747
+ let count = 0, cursor2;
748
+ while (true) {
749
+ const page5 = await this.entities.client.request("GET", `accounts/${account}/${collection}`, z9.object({ data: rows, next_cursor: z9.string().nullable().optional() }), { count: 200, ...cursor2 ? { cursor: cursor2 } : {} });
750
+ const found = page5.data.find(find);
751
+ if (found) return found;
752
+ count += page5.data.length;
753
+ if (!page5.next_cursor || count >= 5e3 || seen.has(page5.next_cursor) || seen.size >= 25) throw new AdportError6("INVALID_INPUT", `x: reference is not in the account\u2019s first 5,000 available ${collection}`);
754
+ seen.add(page5.next_cursor);
755
+ cursor2 = page5.next_cursor;
756
+ }
757
+ }
758
+ async source(account, input, lookup = (collection, find) => this.available(account, collection, find)) {
759
+ const type = input.targeting_type, value = input.targeting_value;
760
+ if (type.startsWith("CUSTOM_AUDIENCE")) {
761
+ const audience2 = await lookup("custom_audiences", (row) => row.id === value);
762
+ if (audience2.deleted !== false || audience2.targetable !== true) throw new AdportError6("INVALID_INPUT", "x: audience is deleted or not targetable");
763
+ } else if (type.startsWith("CAMPAIGN_ENGAGEMENT")) await this.entities.getCampaign(account, xId.parse(value));
764
+ else if (["USER_ENGAGEMENT", "USER_ENGAGEMENT_LOOKALIKE", "FOLLOWERS_OF_USER"].includes(type)) await lookup("promotable_users", (row) => row.user_id === value && row.promotable_user_type === "FULL" && row.deleted === false);
765
+ else if (type === "APP_LIST") {
766
+ if (input.operator_type !== "NE") throw new AdportError6("INVALID_INPUT", "x: APP_LIST is exclusion-only (NE)");
767
+ const list = await lookup("app_lists", (row) => row.id === value);
768
+ if (list.deleted === true) throw new AdportError6("INVALID_INPUT", "x: app list is deleted");
769
+ } else if (type === "ENGAGEMENT_TYPE" && !["IMPRESSION", "ENGAGEMENT"].includes(value)) throw new AdportError6("INVALID_INPUT", "x: ENGAGEMENT_TYPE must be IMPRESSION or ENGAGEMENT");
770
+ }
771
+ finalState(values2) {
772
+ const types = values2.map((value) => value.targeting_type), sources = ["CAMPAIGN_ENGAGEMENT", "CAMPAIGN_ENGAGEMENT_LOOKALIKE", "USER_ENGAGEMENT", "USER_ENGAGEMENT_LOOKALIKE"];
773
+ if (types.filter((type) => type === "AGE").length > 1) throw new AdportError6("INVALID_INPUT", "x: only one age bucket is allowed; use a batch replacement");
774
+ if (types.includes("TV_SHOW") && !values2.some(includedLocation)) throw new AdportError6("INVALID_INPUT", "x: TV shows require included location targeting; native provider also checks market compatibility");
775
+ if (types.includes("ENGAGEMENT_TYPE") !== types.some((type) => sources.includes(type))) throw new AdportError6("INVALID_INPUT", "x: engagement type and source must be configured together; use x_update_targeting for an atomic pair");
776
+ const keys = values2.map((value) => JSON.stringify([value.targeting_type, value.operator_type ?? "EQ", value.targeting_value]));
777
+ if (new Set(keys).size !== keys.length) throw new AdportError6("INVALID_INPUT", "x: identical targeting criteria would be duplicated");
778
+ }
779
+ async batch(op) {
780
+ const account = xId.parse(op.accountId), input = updateCriteria.parse(op.payload);
781
+ if (op.provider !== "x" || op.kind !== "update") throw new AdportError6("INVALID_INPUT", "x: batch targeting operation kind/provider mismatch");
782
+ const line = await this.entities.getLineItem(account, input.line_item_id);
783
+ if (line.deleted || line.entity_status === "DRAFT") throw new AdportError6("INVALID_INPUT", "x: deleted/draft line items cannot be changed");
784
+ const current = await this.current(account, line.id), removed = input.remove.map((id) => current.find((value) => value.id === id));
785
+ if (removed.some((value) => !value)) throw new AdportError6("INVALID_INPUT", "x: every removed criterion must currently belong to the selected line item");
786
+ const additions = input.add.map((value) => ({ ...value, line_item_id: line.id })), final = [...current.filter((value) => !input.remove.includes(value.id)), ...additions];
787
+ this.finalState(final);
788
+ const books = /* @__PURE__ */ new Map(), lookup = async (collection, find) => {
789
+ let loaded = books.get(collection);
790
+ if (!loaded) {
791
+ loaded = (async () => {
792
+ const all = [], seen = /* @__PURE__ */ new Set();
793
+ let cursor2;
794
+ while (true) {
795
+ const page5 = await this.entities.client.request("GET", `accounts/${account}/${collection}`, z9.object({ data: rows, next_cursor: z9.string().nullable().optional() }), { count: 200, ...cursor2 ? { cursor: cursor2 } : {} });
796
+ all.push(...page5.data.slice(0, 5e3 - all.length));
797
+ if (!page5.next_cursor || all.length >= 5e3) return all;
798
+ if (seen.has(page5.next_cursor) || seen.size >= 25) throw new AdportError6("PROVIDER_ERROR", "x: source availability pagination repeated");
799
+ seen.add(page5.next_cursor);
800
+ cursor2 = page5.next_cursor;
801
+ }
802
+ })();
803
+ books.set(collection, loaded);
804
+ }
805
+ const found = (await loaded).find(find);
806
+ if (!found) throw new AdportError6("INVALID_INPUT", `x: reference is not in the account\u2019s first 5,000 available ${collection}`);
807
+ return found;
808
+ };
809
+ for (const value of additions) await this.source(account, value, lookup);
810
+ const operations = [...input.remove.map((value) => ({ operation_type: "Delete", params: { targeting_criterion_id: value } })), ...additions.map((value) => ({ operation_type: "Create", params: value }))], expected = [...removed.map((value) => ({ ...value, deleted: true })), ...additions.map((value) => ({ ...value, deleted: false }))];
811
+ const lastLocation = current.some(includedLocation) && !final.some(includedLocation);
812
+ return { summary: `Atomically update X targeting for ${line.id}`, changes: [`Remove existing criteria: ${JSON.stringify(removed.map((value) => ({ id: value.id, type: value.targeting_type, value: value.targeting_value, operator: value.operator_type ?? "unavailable" })))}`, `Native batch: ${input.remove.length} removals, ${additions.length} additions. Group status ${line.entity_status}. ${JSON.stringify(operations)}`, ...lastLocation ? ["This removes the last LOCATION criterion and can broaden geographic delivery."] : []], coercions: [], budgetDeltas: [], execute: async () => {
813
+ const response = await this.entities.client.request("POST", `batch/accounts/${account}/targeting_criteria`, z9.object({ data: z9.array(criterion) }), {}, operations), ids3 = response.data.map((value) => value.id);
814
+ if (response.data.length !== expected.length || new Set(ids3).size !== ids3.length || response.data.some((value, index) => {
815
+ const wanted = expected[index];
816
+ return value.line_item_id !== line.id || value.deleted !== wanted.deleted || value.targeting_type !== wanted.targeting_type || value.targeting_value !== wanted.targeting_value || "id" in wanted && wanted.id !== value.id || !wanted.deleted && value.operator_type !== wanted.operator_type;
817
+ })) throw new AdportError6("PROVIDER_ERROR", "x: ordered batch targeting receipts differ from the approved plan; reconcile before retrying", { resource_ids: ids3 });
818
+ return ids3;
819
+ } };
820
+ }
821
+ async plan(op, _guard) {
822
+ if (op.tool === "x_update_targeting") return this.batch(op);
823
+ const account = xId.parse(op.accountId), add2 = op.tool === "x_add_targeting_criterion";
824
+ if (op.provider !== "x" || !["x_add_targeting_criterion", "x_remove_targeting_criterion"].includes(op.tool) || op.kind !== (add2 ? "create" : "remove")) throw new AdportError6("INVALID_INPUT", "x: provider or targeting operation kind mismatch");
825
+ const input = add2 ? addCriterion.parse(op.payload) : void 0, previous = add2 ? void 0 : await this.owned(account, xId.parse(op.payload.targeting_criterion_id)), line = await this.entities.getLineItem(account, input?.line_item_id ?? previous.line_item_id);
826
+ if (line.deleted || line.entity_status === "DRAFT" || previous?.deleted) throw new AdportError6("INVALID_INPUT", "x: deleted/draft line items or deleted criteria cannot be changed");
827
+ const current = await this.current(account, line.id);
828
+ if (!add2 && !current.some((value) => value.id === previous.id)) throw new AdportError6("INVALID_INPUT", "x: criterion is no longer current on the selected line item");
829
+ this.finalState(add2 ? [...current, input] : current.filter((value) => value.id !== previous.id));
830
+ if (input) {
831
+ await this.source(account, input);
832
+ if (current.some((value) => value.targeting_type === input.targeting_type && value.targeting_value === input.targeting_value && (value.operator_type ?? "EQ") === input.operator_type)) throw new AdportError6("INVALID_INPUT", "x: identical criterion already exists");
833
+ }
834
+ const item = input ?? previous, lastLocation = !add2 && includedLocation(item) && current.filter(includedLocation).length === 1, changes = [`${add2 ? "Add" : "Remove"} ${JSON.stringify(item)}; line item ${line.id}, status ${line.entity_status}; ${current.length} current criteria. Active group audience can change immediately.`, ...lastLocation ? ["This removes the last included LOCATION criterion and can broaden geographic delivery."] : []];
835
+ return { summary: `${add2 ? "Add" : "Remove"} X targeting criterion`, changes, coercions: [], budgetDeltas: [], execute: async () => {
836
+ const path = `accounts/${account}/targeting_criteria${add2 ? "" : `/${previous.id}`}`, params = input ? { line_item_id: input.line_item_id, targeting_type: input.targeting_type, targeting_value: input.targeting_value, operator_type: input.operator_type } : {};
837
+ const response = await this.entities.client.request(add2 ? "POST" : "DELETE", path, z9.object({ data: criterion }), params), value = response.data;
838
+ const expectedId = previous?.id ?? value.id;
839
+ if (value.id !== expectedId || value.line_item_id !== line.id || value.targeting_type !== item.targeting_type || value.targeting_value !== item.targeting_value || value.deleted !== !add2) throw new AdportError6("PROVIDER_ERROR", "x: criterion receipt differs from the approved plan; reconcile before retrying", { resource_ids: [value.id] });
840
+ if (input) {
841
+ let native = value;
842
+ try {
843
+ if (native.operator_type === void 0) native = (await this.entities.client.request("GET", `accounts/${account}/targeting_criteria/${value.id}`, z9.object({ data: criterion }))).data;
844
+ } catch {
845
+ throw new AdportError6("PROVIDER_ERROR", "x: criterion operator readback failed; reconcile before retrying", { resource_ids: [value.id] });
846
+ }
847
+ if (native.id !== value.id || native.line_item_id !== line.id || native.targeting_type !== input.targeting_type || native.targeting_value !== input.targeting_value || native.operator_type !== input.operator_type || native.deleted) throw new AdportError6("PROVIDER_ERROR", "x: criterion operator readback mismatch; reconcile before retrying", { resource_ids: [value.id] });
848
+ }
849
+ return [value.id];
850
+ } };
851
+ }
852
+ };
853
+
854
+ // src/creatives.ts
855
+ import { AdportError as AdportError7 } from "@adport/core";
856
+ import { z as z11 } from "zod";
857
+
858
+ // src/creative-tools.ts
859
+ import { creativesOutput, defineTool as defineTool3, guardedWriteTool as guardedWriteTool3 } from "@adport/core";
860
+ import { z as z10 } from "zod";
861
+ var snowflake = z10.string().regex(/^[1-9]\d{0,24}$/);
862
+ var mediaKey = z10.string().regex(/^\d+_[1-9]\d{0,24}$/);
863
+ var cardUri = z10.string().regex(/^card:\/\/[1-9]\d{0,24}$/);
864
+ var text = z10.string().max(1e4).describe("Native weighted-length/content validation happens on apply; local preview is not server validation.");
865
+ var mediaKeys = z10.array(mediaKey).max(4).refine((v) => new Set(v).size === v.length, "Use unique media keys");
866
+ var draftFields = { text: text.optional(), name: z10.string().min(1).max(80).optional(), media_keys: mediaKeys.optional(), card_uri: cardUri.nullable().optional() };
867
+ var createDraft = z10.object({ as_user_id: snowflake, ...draftFields });
868
+ var updateDraft = z10.object({ draft_tweet_id: snowflake, ...draftFields }).refine((v) => Object.keys(v).length > 1, "Provide draft changes");
869
+ var updateLibrary = z10.object({ media_key: mediaKey, name: z10.string().min(1).max(100).optional(), file_name: z10.string().min(1).max(255).optional(), title: z10.string().max(70).optional(), description: z10.string().max(200).optional(), poster_media_key: mediaKey.optional() }).refine((v) => Object.keys(v).length > 1, "Provide library changes");
870
+ var draftList = z10.object({ account_id: xId, count: z10.number().int().min(1).max(200).default(20), cursor: z10.string().optional(), user_id: snowflake.optional(), include_media: z10.boolean().default(true) });
871
+ var libraryList = z10.object({ account_id: xId, count: z10.number().int().min(1).max(50).default(20), cursor: z10.string().optional(), media_type: z10.enum(["IMAGE", "GIF", "VIDEO"]).optional(), q: z10.string().min(1).max(255).optional() });
872
+ function xCreativeTools(provider) {
873
+ const read = (name3, description, input, handler) => defineTool3({ name: name3, namespace: "x", description, input, annotations: { readOnly: true }, handler });
874
+ const write = (name3, description, payload, kind = "update") => guardedWriteTool3({ name: name3, namespace: "x", provider: "x", kind, description, payload });
875
+ return [
876
+ defineTool3({ name: "x_draft_tweets", namespace: "x", description: "View native account drafts with actual copy, media previews and guarded edit actions. Native draft state is separate from ad delivery.", input: draftList, output: creativesOutput.passthrough(), presentation: "creatives", pagination: { cursorInput: "cursor" }, annotations: { readOnly: true }, handler: (v) => provider.creatives.drafts(v) }),
877
+ read("x_get_draft_tweet", "Read a native draft through the selected account, keeping snowflake IDs as strings.", z10.object({ account_id: xId, draft_tweet_id: snowflake }), (v) => provider.creatives.draft(v.account_id, v.draft_tweet_id)),
878
+ defineTool3({ name: "x_media_library", namespace: "x", description: "View native account media-library images, GIFs and videos, processing state and metadata edit actions.", input: libraryList, output: creativesOutput.passthrough(), presentation: "creatives", pagination: { cursorInput: "cursor" }, annotations: { readOnly: true }, handler: (v) => provider.creatives.library(v) }),
879
+ read("x_get_media_library_item", "Read one account-scoped media-library item, including native processing readiness and preview URLs.", z10.object({ account_id: xId, media_key: mediaKey }), (v) => provider.creatives.media(v.account_id, v.media_key)),
880
+ read("x_promotable_users", "Read account-associated users and FULL/RETWEETS_ONLY eligibility for creative authoring.", z10.object({ account_id: xId }), (v) => provider.creatives.users(v.account_id)),
881
+ read("x_authenticated_user_access", "Read the authenticated actor and native account permissions, including TWEET_COMPOSER when granted.", z10.object({ account_id: xId }), (v) => provider.creatives.access(v.account_id)),
882
+ read("x_get_cards", "Read exact native cards by account-associated card URI, including legacy card content.", z10.object({ account_id: xId, card_uris: z10.array(cardUri).min(1).max(200), with_deleted: z10.boolean().default(false) }), (v) => provider.creatives.cards(v.account_id, v.card_uris, v.with_deleted)),
883
+ write("x_create_draft_tweet", "Create a promoted-only native draft; no post publication or ad association. Checks FULL advertiser/composer access and owned ready media/cards. Local preview is not native content validation.", createDraft, "create"),
884
+ write("x_update_draft_tweet", "Edit supplied native draft copy/name/media/card fields, preserving omitted values and nullcast state. Empty media_keys clears media; null card_uri clears the card.", updateDraft),
885
+ write("x_delete_draft_tweet", "Permanently delete one verified native draft. This cannot be undone and does not delete an already published post.", z10.object({ draft_tweet_id: snowflake }), "remove"),
886
+ write("x_update_media_library", "Edit native media-library metadata or a video poster, preserving omitted fields. Metadata can be shared with existing creatives; library status is separate from ad delivery.", updateLibrary),
887
+ write("x_delete_media_library_item", "Delete a verified native media-library record. Existing posts/ads may retain media; this is not an ad pause or proof of underlying byte deletion.", z10.object({ media_key: mediaKey }), "remove")
888
+ ];
889
+ }
890
+
891
+ // src/creatives.ts
892
+ var draftSchema = z11.looseObject({ id: snowflake, user_id: snowflake, text: z11.string(), name: z11.string().nullable(), nullcast: z11.boolean(), card_uri: cardUri.nullable(), media_keys: z11.array(mediaKey), status: z11.string().optional() });
893
+ var librarySchema = z11.looseObject({ media_key: mediaKey, media_type: z11.enum(["IMAGE", "VIDEO", "GIF"]), media_status: z11.string(), deleted: z11.boolean() });
894
+ var userSchema = z11.looseObject({ id: xId, user_id: snowflake, promotable_user_type: z11.string(), deleted: z11.boolean() });
895
+ var cardSchema = z11.looseObject({ id: xId, card_uri: cardUri, deleted: z11.boolean(), card_type: z11.string() });
896
+ var cursor = { next_cursor: z11.string().nullable().optional() };
897
+ var safeUrl = (value) => {
898
+ if (typeof value !== "string") return void 0;
899
+ try {
900
+ const url3 = new URL(value);
901
+ return url3.protocol === "https:" && !url3.username && !url3.password && ["pbs.twimg.com", "video.twimg.com", "ton.twimg.com"].includes(url3.hostname) ? value : void 0;
902
+ } catch {
903
+ return void 0;
904
+ }
905
+ };
906
+ var same = (left, right) => JSON.stringify(left) === JSON.stringify(right);
907
+ var fieldsMatch = (value, wanted) => Object.entries(wanted).every(([key, expected]) => same(value[key], expected));
908
+ var XCreativeService = class {
909
+ constructor(entities) {
910
+ this.entities = entities;
911
+ }
912
+ entities;
913
+ async users(account, requireComplete = false) {
914
+ await this.entities.getAccount(account);
915
+ const path = `accounts/${xId.parse(account)}/promotable_users`;
916
+ if (!requireComplete) return this.entities.client.list(path, userSchema);
917
+ const rows2 = [], ids3 = /* @__PURE__ */ new Set(), cursors = /* @__PURE__ */ new Set();
918
+ let cursor2;
919
+ for (let page5 = 0; page5 < 10; page5++) {
920
+ const result = await this.entities.client.request("GET", path, z11.object({ data: z11.array(userSchema).max(1e3), next_cursor: z11.string().nullable().optional() }), { count: 200, ...cursor2 ? { cursor: cursor2 } : {} });
921
+ for (const row of result.data) {
922
+ if (ids3.has(row.id)) throw new AdportError7("PROVIDER_ERROR", "x: promotable-user inventory repeated an ID");
923
+ ids3.add(row.id);
924
+ rows2.push(row);
925
+ }
926
+ if (result.next_cursor === null) return rows2;
927
+ if (!result.next_cursor || cursors.has(result.next_cursor)) break;
928
+ cursor2 = result.next_cursor;
929
+ cursors.add(cursor2);
930
+ }
931
+ throw new AdportError7("PROVIDER_ERROR", "x: promotable-user inventory is incomplete; receiving-author uniqueness is unconfirmed");
932
+ }
933
+ async access(account) {
934
+ await this.entities.getAccount(account);
935
+ return (await this.entities.client.request("GET", `accounts/${xId.parse(account)}/authenticated_user_access`, z11.object({ data: z11.object({ user_id: snowflake, permissions: z11.array(z11.string()) }) }))).data;
936
+ }
937
+ async verifyComposer(account, user2) {
938
+ if (!(await this.users(account)).some((v) => v.user_id === user2 && v.promotable_user_type === "FULL" && !v.deleted)) throw new AdportError7("INVALID_INPUT", "x: author must be a current FULL promotable user on the selected account");
939
+ const access = await this.access(account);
940
+ if (access.user_id !== user2 && !access.permissions.includes("TWEET_COMPOSER")) throw new AdportError7("INVALID_INPUT", "x: authenticated actor needs TWEET_COMPOSER to author for another user");
941
+ return access;
942
+ }
943
+ async draft(account, resource) {
944
+ await this.entities.getAccount(account);
945
+ const { data } = await this.entities.client.request("GET", `accounts/${xId.parse(account)}/draft_tweets/${snowflake.parse(resource)}`, z11.object({ data: draftSchema }));
946
+ if (data.id !== resource || data.status !== void 0 && data.status !== "DRAFT") throw new AdportError7("PROVIDER_ERROR", "x: draft ID/state mismatch");
947
+ return data;
948
+ }
949
+ async media(account, resource) {
950
+ await this.entities.getAccount(account);
951
+ const { data } = await this.entities.client.request("GET", `accounts/${xId.parse(account)}/media_library/${mediaKey.parse(resource)}`, z11.object({ data: librarySchema }));
952
+ if (data.media_key !== resource) throw new AdportError7("PROVIDER_ERROR", "x: media key mismatch");
953
+ return data;
954
+ }
955
+ async cards(account, values2, withDeleted = false) {
956
+ const wanted = [...new Set(values2.map((value) => cardUri.parse(value)))];
957
+ if (!wanted.length || wanted.length > 200) throw new AdportError7("INVALID_INPUT", "x: provide 1\u2013200 card URIs");
958
+ await this.entities.getAccount(account);
959
+ const { data } = await this.entities.client.request("GET", `accounts/${xId.parse(account)}/cards/all`, z11.object({ data: z11.array(cardSchema) }), { card_uris: wanted.join(","), with_deleted: withDeleted });
960
+ if (data.some((v) => !wanted.includes(v.card_uri) || !withDeleted && v.deleted) || new Set(data.map((v) => v.card_uri)).size !== data.length) throw new AdportError7("PROVIDER_ERROR", "x: card association/filter mismatch");
961
+ return { items: data, missing: wanted.filter((value) => !data.some((v) => v.card_uri === value)) };
962
+ }
963
+ async verifyAttachments(account, keys, card) {
964
+ const media = await Promise.all(keys.map((key) => this.media(account, key)));
965
+ if (media.some((value) => value.deleted || value.media_status !== "TRANSCODE_COMPLETED")) throw new AdportError7("INVALID_INPUT", "x: every media attachment must be ready and present in the selected account library");
966
+ if (media.length > 4 || media.some((value) => value.media_type !== "IMAGE") && media.length > 1) throw new AdportError7("INVALID_INPUT", "x: use up to four images, one GIF or one video");
967
+ const cards = card ? await this.cards(account, [card]) : { items: [], missing: [] };
968
+ if (cards.missing.length) throw new AdportError7("INVALID_INPUT", "x: card is not available in the selected account");
969
+ return { media, cards: cards.items };
970
+ }
971
+ page(ids3, next, previous) {
972
+ if (new Set(ids3).size !== ids3.length || next && next === previous) throw new AdportError7("PROVIDER_ERROR", "x: creative pagination repeated an entity or cursor");
973
+ return { truncated: Boolean(next), ...next ? { next_cursor: next } : {} };
974
+ }
975
+ visual(value) {
976
+ const url3 = safeUrl(value.media_url), poster = safeUrl(value.poster_media_url);
977
+ return [...url3 ? [{ type: value.media_type === "IMAGE" ? "image" : "video", url: url3, ...value.media_type !== "IMAGE" && poster ? { poster_url: poster } : {} }] : [], ...!url3 && poster ? [{ type: "image", url: poster, alt: "Video poster" }] : []];
978
+ }
979
+ async library(value) {
980
+ const input = libraryList.parse(value);
981
+ await this.entities.getAccount(input.account_id);
982
+ const params = { count: input.count, ...input.cursor ? { cursor: input.cursor } : {}, ...input.media_type ? { media_type: input.media_type } : {}, ...input.q ? { q: input.q } : {} };
983
+ const result = await this.entities.client.request("GET", `accounts/${input.account_id}/media_library`, z11.object({ data: z11.array(librarySchema), ...cursor }), params);
984
+ if (result.data.some((v) => v.deleted || input.media_type && v.media_type !== input.media_type)) throw new AdportError7("PROVIDER_ERROR", "x: media library filter/state mismatch");
985
+ const creatives = result.data.map((v) => ({ id: v.media_key, provider: "x", account_id: input.account_id, name: String(v.name ?? v.file_name ?? v.media_key), type: `${v.media_type}_ASSET`, status: v.media_status, headlines: typeof v.title === "string" && v.title ? [v.title] : [], descriptions: typeof v.description === "string" && v.description ? [v.description] : [], landing_urls: [], media: this.visual(v), actions: [{ label: "Rename library media", tool: "x_update_media_library", arguments: { account_id: input.account_id, media_key: v.media_key }, fields: [{ key: "name", label: "Name", type: "text", value: String(v.name ?? ""), max_length: 100 }] }] }));
986
+ return { items: result.data, creatives, ...this.page(result.data.map((v) => v.media_key), result.next_cursor, input.cursor) };
987
+ }
988
+ async drafts(value) {
989
+ const input = draftList.parse(value);
990
+ await this.entities.getAccount(input.account_id);
991
+ const result = await this.entities.client.request("GET", `accounts/${input.account_id}/draft_tweets`, z11.object({ data: z11.array(draftSchema), ...cursor }), { count: input.count, ...input.cursor ? { cursor: input.cursor } : {}, ...input.user_id ? { user_id: input.user_id } : {} });
992
+ if (result.data.some((v) => v.status !== void 0 && v.status !== "DRAFT" || input.user_id && v.user_id !== input.user_id)) throw new AdportError7("PROVIDER_ERROR", "x: draft author/state filter mismatch");
993
+ const sources = /* @__PURE__ */ new Map(), warnings = [], wanted = [...new Set(result.data.flatMap((v) => v.media_keys))].slice(0, 100);
994
+ let index = 0;
995
+ if (input.include_media) await Promise.all(Array.from({ length: Math.min(4, wanted.length) }, async () => {
996
+ while (index < wanted.length) {
997
+ const key = wanted[index++];
998
+ try {
999
+ const value2 = await this.media(input.account_id, key);
1000
+ if (!value2.deleted) sources.set(key, value2);
1001
+ else warnings.push(`Media ${key} was deleted from the library.`);
1002
+ } catch {
1003
+ warnings.push(`Media ${key} could not be read from this account.`);
1004
+ }
1005
+ }
1006
+ }));
1007
+ if (input.include_media && new Set(result.data.flatMap((v) => v.media_keys)).size > 100) warnings.push("Preview hydration is limited to 100 distinct media items; native references remain in items.");
1008
+ const creatives = result.data.map((v) => ({ id: v.id, provider: "x", account_id: input.account_id, name: v.name ?? `Draft ${v.id}`, type: v.nullcast ? "PROMOTED_ONLY_DRAFT" : "ORGANIC_DRAFT", status: "DRAFT", headlines: [], descriptions: [v.text], landing_urls: [], media: input.include_media ? v.media_keys.flatMap((key) => sources.has(key) ? this.visual(sources.get(key)) : []) : [], actions: [{ label: "Edit draft copy", tool: "x_update_draft_tweet", arguments: { account_id: input.account_id, draft_tweet_id: v.id }, fields: [{ key: "text", label: "Post text", type: "text", value: v.text }] }, { label: "Rename draft", tool: "x_update_draft_tweet", arguments: { account_id: input.account_id, draft_tweet_id: v.id }, fields: [{ key: "name", label: "Draft name", type: "text", value: v.name ?? "", max_length: 80 }] }] }));
1009
+ return { items: result.data, creatives, warnings, ...this.page(result.data.map((v) => v.id), result.next_cursor, input.cursor) };
1010
+ }
1011
+ async plan(op, _guard) {
1012
+ const account = xId.parse(op.accountId), create = op.tool === "x_create_draft_tweet", remove = ["x_delete_draft_tweet", "x_delete_media_library_item"].includes(op.tool);
1013
+ if (op.provider !== "x" || op.kind !== (create ? "create" : remove ? "remove" : "update")) throw new AdportError7("INVALID_INPUT", "x: creative operation provider/kind mismatch");
1014
+ const plan = (summary, changes, execute) => ({ summary, changes, execute, coercions: [], budgetDeltas: [] });
1015
+ if (["x_update_media_library", "x_delete_media_library_item"].includes(op.tool)) {
1016
+ const input2 = op.tool === "x_update_media_library" ? updateLibrary.parse(op.payload) : { media_key: mediaKey.parse(op.payload.media_key) }, current2 = await this.media(account, input2.media_key), { media_key: key, ...fields2 } = input2;
1017
+ if (current2.deleted) throw new AdportError7("INVALID_INPUT", "x: media library record is already deleted");
1018
+ if ("title" in fields2 || "description" in fields2 || "poster_media_key" in fields2) {
1019
+ if (current2.media_type === "IMAGE") throw new AdportError7("INVALID_INPUT", "x: title/description/poster changes need video or GIF media");
1020
+ if ("poster_media_key" in fields2) {
1021
+ if (current2.media_type !== "VIDEO") throw new AdportError7("INVALID_INPUT", "x: poster changes require VIDEO media");
1022
+ const poster = await this.media(account, fields2.poster_media_key);
1023
+ if (poster.deleted || poster.media_type !== "IMAGE" || poster.media_status !== "TRANSCODE_COMPLETED") throw new AdportError7("INVALID_INPUT", "x: poster must be a ready account-owned image");
1024
+ }
1025
+ }
1026
+ const expected2 = remove ? { deleted: true } : { ...fields2, deleted: false }, preserved = remove ? {} : Object.fromEntries(["name", "file_name", "title", "description", "poster_media_key"].filter((key2) => !(key2 in fields2) && key2 in current2).map((key2) => [key2, current2[key2]]));
1027
+ return plan(`${remove ? "Delete" : "Edit"} X media library ${key}`, [remove ? "Delete the library record. Existing posts/ads may retain media. This neither pauses delivery nor proves underlying bytes were deleted." : `Metadata can be shared by existing creatives. Change only ${JSON.stringify(fields2)}; preserve other metadata.`], async () => {
1028
+ try {
1029
+ const { data } = await this.entities.client.request(remove ? "DELETE" : "PUT", `accounts/${account}/media_library/${key}`, z11.object({ data: librarySchema.partial().required({ media_key: true }) }), fields2);
1030
+ if (data.media_key !== key || data.media_type !== void 0 && data.media_type !== current2.media_type || !fieldsMatch(data, Object.fromEntries(Object.entries({ ...preserved, ...expected2 }).filter(([key2]) => key2 in data))) || remove && data.deleted !== true) throw new AdportError7("PROVIDER_ERROR", "x: media-library receipt mismatch; reconcile before retrying", { resource_ids: [data.media_key, key] });
1031
+ if (!remove) {
1032
+ const observed = await this.media(account, key);
1033
+ if (observed.media_type !== current2.media_type || !fieldsMatch(observed, { ...preserved, ...expected2 })) throw new Error("x: media-library readback mismatch; reconcile before retrying");
1034
+ }
1035
+ return [key];
1036
+ } catch (error) {
1037
+ throw new AdportError7("PROVIDER_ERROR", error instanceof Error ? error.message : "x: media-library update failed; reconcile before retrying", { resource_ids: [key] });
1038
+ }
1039
+ });
1040
+ }
1041
+ if (!["x_create_draft_tweet", "x_update_draft_tweet", "x_delete_draft_tweet"].includes(op.tool)) throw new AdportError7("INVALID_INPUT", "x: unsupported creative operation");
1042
+ const current = create ? void 0 : await this.draft(account, snowflake.parse(op.payload.draft_tweet_id));
1043
+ if (remove) return plan(`Permanently delete X draft ${current.id}`, [`Hard delete draft authored by ${current.user_id}; this cannot be undone. Already published posts remain separate.`], async () => {
1044
+ const { data } = await this.entities.client.request("DELETE", `accounts/${account}/draft_tweets/${current.id}`, z11.object({ data: z11.looseObject({ id: snowflake, user_id: snowflake.optional(), status: z11.string() }) }));
1045
+ if (data.id !== current.id || data.user_id !== void 0 && data.user_id !== current.user_id || data.status !== "DELETED") throw new AdportError7("PROVIDER_ERROR", "x: draft-deletion receipt mismatch; reconcile before retrying", { resource_ids: [data.id] });
1046
+ return [data.id];
1047
+ });
1048
+ const input = create ? createDraft.parse(op.payload) : updateDraft.parse(op.payload), user2 = create ? createDraft.parse(input).as_user_id : current.user_id;
1049
+ await this.verifyComposer(account, user2);
1050
+ const expected = { text: input.text ?? current?.text ?? "", name: input.name ?? current?.name ?? null, media_keys: input.media_keys ?? current?.media_keys ?? [], card_uri: input.card_uri !== void 0 ? input.card_uri : current?.card_uri ?? null, nullcast: create ? true : current.nullcast, user_id: user2 };
1051
+ if (!expected.text.trim() && !expected.media_keys.length) throw new AdportError7("INVALID_INPUT", "x: final draft needs text or media");
1052
+ await this.verifyAttachments(account, input.media_keys ?? [], input.card_uri);
1053
+ const fields = { ...create ? { as_user_id: user2, nullcast: true } : {}, ...input.text !== void 0 ? { text: input.text } : {}, ...input.name !== void 0 ? { name: input.name } : {}, ...input.media_keys !== void 0 ? { media_keys: input.media_keys.join(",") } : {}, ...input.card_uri !== void 0 ? { card_uri: input.card_uri ?? "" } : {} };
1054
+ return plan(`${create ? "Create" : "Edit"} X native draft`, [`Author ${user2}; native draft only, no publication or ad association. ${JSON.stringify(expected)}`, "Native weighted text length and content eligibility are checked by X only on apply; this local preview is not server validation."], async () => {
1055
+ let data;
1056
+ try {
1057
+ if (create) ({ data } = await this.entities.client.request("POST", `accounts/${account}/draft_tweets`, z11.object({ data: draftSchema }), fields));
1058
+ else {
1059
+ const receipt = (await this.entities.client.request("PUT", `accounts/${account}/draft_tweets/${current.id}`, z11.object({ data: draftSchema.partial().required({ id: true }) }), fields)).data;
1060
+ if (receipt.id !== current.id || !fieldsMatch(receipt, Object.fromEntries(Object.entries(expected).filter(([key]) => key in receipt)))) throw new AdportError7("PROVIDER_ERROR", "x: partial draft receipt mismatch; reconcile before retrying", { resource_ids: [receipt.id, current.id] });
1061
+ data = await this.draft(account, current.id);
1062
+ }
1063
+ } catch (error) {
1064
+ if (!create) throw new AdportError7("PROVIDER_ERROR", error instanceof Error ? error.message : "x: draft update failed; reconcile before retrying", { resource_ids: [current.id] });
1065
+ throw error;
1066
+ }
1067
+ if (!create && data.id !== current.id || data.status !== void 0 && data.status !== "DRAFT" || !fieldsMatch(data, expected)) throw new AdportError7("PROVIDER_ERROR", "x: draft receipt differs from the approved content; reconcile before retrying", { resource_ids: [data.id] });
1068
+ return [data.id];
1069
+ });
1070
+ }
1071
+ };
1072
+
1073
+ // src/media.ts
1074
+ import { AdportError as AdportError8, LocalMediaResolver } from "@adport/core";
1075
+ import { z as z13 } from "zod";
1076
+
1077
+ // src/media-tools.ts
1078
+ import { defineTool as defineTool4, guardedWriteTool as guardedWriteTool4, mediaSourceFields } from "@adport/core";
1079
+ import { z as z12 } from "zod";
1080
+ var mediaReceipt = z12.string().min(1).max(2048);
1081
+ var uploadMedia = z12.object({ as_user_id: snowflake, ...mediaSourceFields }).refine((v) => Boolean(v.media_id) !== Boolean(v.file_path), "Choose project media_id or local file_path");
1082
+ var registerMedia = z12.object({ resource_receipt: mediaReceipt, name: z12.string().min(1).max(100), file_name: z12.string().min(1).max(255).optional(), title: z12.string().max(70).optional(), description: z12.string().max(200).optional() });
1083
+ function xMediaTools(provider) {
1084
+ return [
1085
+ guardedWriteTool4({ name: "x_upload_media", namespace: "x", provider: "x", kind: "create", description: "Upload SHA-256-bound image/GIF/video bytes through native v2 initialize/append/finalize with the existing OAuth1 grant. Returns a signed account/author-bound processing receipt; does not register, publish or attach an ad.", payload: uploadMedia }),
1086
+ defineTool4({ name: "x_media_upload_status", namespace: "x", description: "Read native upload processing only with the signed receipt from this account\u2019s approved upload. Native IDs alone do not authorize account-less status reads.", input: z12.object({ account_id: xId, resource_receipt: mediaReceipt }), annotations: { readOnly: true }, handler: (v) => provider.mediaUploads.status(v.account_id, v.resource_receipt) }),
1087
+ guardedWriteTool4({ name: "x_register_uploaded_media", namespace: "x", provider: "x", kind: "create", description: "Register an approved, processed upload in its account\u2019s native media library. Requires its unexpired signed receipt, checks current author/processing, and preserves upload IDs on a partial failure. No post publication or ad association.", payload: registerMedia })
1088
+ ];
1089
+ }
1090
+
1091
+ // src/media.ts
1092
+ var nativeId = snowflake.refine((v) => v.length <= 19, "Native media v2 ID exceeds 19 digits");
1093
+ var processing = z13.looseObject({ state: z13.enum(["pending", "in_progress", "succeeded", "failed"]), check_after_secs: z13.number().int().nonnegative().optional(), progress_percent: z13.number().min(0).max(100).optional() });
1094
+ var nativeMedia = z13.looseObject({ id: nativeId, media_key: mediaKey.optional(), expires_after_secs: z13.number().int().positive().optional(), size: z13.number().int().nonnegative().safe().optional(), processing_info: processing.optional() });
1095
+ var receiptSchema = z13.object({ kind: z13.literal("media_upload_v1"), account_id: xId, user_id: nativeId, media_id: nativeId, media_key: mediaKey.optional(), media_type: z13.enum(["IMAGE", "GIF", "VIDEO"]), sha256: z13.string().regex(/^[a-f0-9]{64}$/), byte_length: z13.number().int().positive().max(50 * 1024 * 1024), finalized: z13.boolean(), expires_at: z13.number().int().positive().safe() });
1096
+ var XMediaService = class {
1097
+ constructor(provider, media = new LocalMediaResolver()) {
1098
+ this.provider = provider;
1099
+ this.media = media;
1100
+ }
1101
+ provider;
1102
+ media;
1103
+ receipt(account, value) {
1104
+ const parsed = receiptSchema.safeParse(this.provider.client.verifyResourceReceipt(value)), now = Math.floor(Date.now() / 1e3);
1105
+ if (!parsed.success || parsed.data.account_id !== xId.parse(account) || parsed.data.expires_at <= now || parsed.data.expires_at > now + 86400 || parsed.data.media_key && parsed.data.media_key.split("_")[1] !== parsed.data.media_id) throw new AdportError8("INVALID_INPUT", "x: expired or mismatched account upload receipt");
1106
+ return parsed.data;
1107
+ }
1108
+ async author(account, user2, write) {
1109
+ if (!(await this.provider.creatives.users(account)).some((v) => v.user_id === user2 && v.promotable_user_type === "FULL" && !v.deleted)) throw new AdportError8("INVALID_INPUT", "x: upload author is not a current FULL promotable account user");
1110
+ if (write) {
1111
+ const access = await this.provider.creatives.access(account);
1112
+ if (access.user_id !== user2 && !access.permissions.includes("TWEET_COMPOSER")) throw new AdportError8("INVALID_INPUT", "x: upload author needs native composer access");
1113
+ }
1114
+ }
1115
+ checked(value, bound) {
1116
+ if (value.id !== bound.media_id || value.media_key && value.media_key.split("_")[1] !== value.id || bound.media_key && value.media_key && bound.media_key !== value.media_key || value.size !== void 0 && value.size !== bound.byte_length) throw new AdportError8("PROVIDER_ERROR", "x: upload processing ID/key/size mismatch");
1117
+ const updated = { ...bound, ...value.media_key ? { media_key: value.media_key } : {}, ...value.expires_after_secs ? { expires_at: Math.min(bound.expires_at, Math.floor(Date.now() / 1e3) + value.expires_after_secs) } : {} };
1118
+ return { native: value, bound: updated, state: value.processing_info?.state ?? "succeeded", resource_receipt: this.provider.client.resourceReceipt(updated) };
1119
+ }
1120
+ async nativeStatus(bound) {
1121
+ const { data } = await this.provider.client.mediaRequest("GET", "media/upload", z13.object({ data: nativeMedia }), { media_id: bound.media_id, command: "STATUS" });
1122
+ return this.checked(data, bound);
1123
+ }
1124
+ async status(account, value) {
1125
+ const bound = this.receipt(account, value);
1126
+ await this.author(account, bound.user_id, false);
1127
+ return this.nativeStatus(bound);
1128
+ }
1129
+ async plan(op) {
1130
+ const account = xId.parse(op.accountId);
1131
+ if (op.provider !== "x" || op.kind !== "create") throw new AdportError8("INVALID_INPUT", "x: media provider/kind mismatch");
1132
+ const plan = (summary, changes, execute, review) => ({ summary, changes, execute, review, coercions: [], budgetDeltas: [] });
1133
+ if (op.tool === "x_upload_media") {
1134
+ const input2 = uploadMedia.parse(op.payload);
1135
+ nativeId.parse(input2.as_user_id);
1136
+ await this.author(account, input2.as_user_id, true);
1137
+ const file = await this.media.read(input2, { maxBytes: 50 * 1024 * 1024, contentTypes: ["image/png", "image/jpeg", "image/gif", "video/mp4"] }), kind = file.contentType === "image/gif" ? "GIF" : file.contentType.startsWith("image/") ? "IMAGE" : "VIDEO";
1138
+ if (file.bytes.byteLength > (kind === "IMAGE" ? 5 : kind === "GIF" ? 15 : 50) * 1024 * 1024) throw new AdportError8("INVALID_INPUT", "x: media exceeds the image5MiB/GIF15MiB/video50MiB application limit");
1139
+ const category = kind === "IMAGE" ? "tweet_image" : kind === "GIF" ? "tweet_gif" : "amplify_video";
1140
+ return plan("Upload X native media bytes", [`${file.name}; ${file.contentType}; ${file.bytes.byteLength} bytes; SHA-256 ${file.sha256}. Author ${input2.as_user_id}, category ${category}.`, "Initialize, append 1MiB JSON/base64 chunks and finalize. Upload processing and library registration are separate. No post or ad is created; incomplete native uploads may remain until provider expiry."], async () => {
1141
+ const init = (await this.provider.client.mediaRequest("POST", "media/upload/initialize", z13.object({ data: nativeMedia }), {}, { additional_owners: [input2.as_user_id], media_category: category, media_type: file.contentType, total_bytes: file.bytes.byteLength })).data;
1142
+ let bound2 = { kind: "media_upload_v1", account_id: account, user_id: input2.as_user_id, media_id: init.id, ...init.media_key ? { media_key: init.media_key } : {}, media_type: kind, sha256: file.sha256, byte_length: file.bytes.byteLength, finalized: false, expires_at: Math.floor(Date.now() / 1e3) + Math.min(init.expires_after_secs ?? 3600, 86400) };
1143
+ try {
1144
+ this.checked(init, bound2);
1145
+ for (let offset = 0, segment = 0; offset < file.bytes.byteLength; offset += 1024 * 1024, segment++) await this.provider.client.mediaRequest("POST", `media/upload/${init.id}/append`, z13.object({ data: z13.object({ expires_at: z13.number().int().positive().safe().optional() }).optional() }), {}, { segment_index: segment, media: Buffer.from(file.bytes.subarray(offset, offset + 1024 * 1024)).toString("base64") });
1146
+ const final = (await this.provider.client.mediaRequest("POST", `media/upload/${init.id}/finalize`, z13.object({ data: nativeMedia }))).data;
1147
+ const result = this.checked(final, { ...bound2, finalized: true });
1148
+ bound2 = result.bound;
1149
+ if (result.state === "failed") throw new Error("x: native media processing failed");
1150
+ return { applied: true, resourceIds: [bound2.media_key ?? bound2.media_id], details: { upload_id: bound2.media_id, ...bound2.media_key ? { media_key: bound2.media_key } : {}, status: result.state, resource_receipt: result.resource_receipt, expires_at: new Date(bound2.expires_at * 1e3).toISOString(), next_tool: result.state === "succeeded" ? "x_register_uploaded_media" : "x_media_upload_status", note: "Upload finalized; this does not register a library entry, publish a post or prove ad eligibility." } };
1151
+ } catch (error) {
1152
+ throw new AdportError8("PROVIDER_ERROR", error instanceof Error ? error.message : "x: upload failed; reconcile before retrying", { resource_ids: [bound2.media_key ?? bound2.media_id], resource_receipt: this.provider.client.resourceReceipt(bound2), note: "Upload was not replayed. Native incomplete bytes may remain until provider expiry." });
1153
+ }
1154
+ }, { provider: "x", accountId: account, kind: "create", title: `Upload ${kind.toLowerCase()}`, subject: file.name, fields: [{ label: "Type", after: file.contentType }, { label: "Size", after: `${file.bytes.byteLength.toLocaleString("en-US")} bytes` }, { label: "Author", after: input2.as_user_id }, { label: "SHA-256", after: file.sha256 }], notices: ["X validates on apply. An incomplete upload may remain until it expires.", "Publishing and library registration are separate actions."] });
1155
+ }
1156
+ if (op.tool !== "x_register_uploaded_media") throw new AdportError8("INVALID_INPUT", "x: unsupported media operation");
1157
+ const input = registerMedia.parse(op.payload), bound = this.receipt(account, input.resource_receipt);
1158
+ await this.author(account, bound.user_id, true);
1159
+ if (!bound.finalized) throw new AdportError8("INVALID_INPUT", "x: incomplete upload cannot be registered; create a new approved upload after reconciling the incomplete session");
1160
+ const status = await this.nativeStatus(bound), key = status.bound.media_key;
1161
+ if (status.state !== "succeeded" || !key) throw new AdportError8("INVALID_INPUT", "x: upload is not processed or has no native media key; check x_media_upload_status");
1162
+ if (bound.media_type === "IMAGE" && (input.title !== void 0 || input.description !== void 0)) throw new AdportError8("INVALID_INPUT", "x: title/description require video or GIF media");
1163
+ try {
1164
+ const existing = await this.provider.creatives.media(account, key);
1165
+ if (!existing.deleted) throw new AdportError8("INVALID_INPUT", "x: media is already registered in this account");
1166
+ } catch (error) {
1167
+ if (!(error instanceof AdportError8) || !error.details || typeof error.details !== "object" || !("http_status" in error.details) || error.details.http_status !== 404) throw error;
1168
+ }
1169
+ const fields = { media_key: key, name: input.name, ...input.file_name !== void 0 ? { file_name: input.file_name } : {}, ...input.title !== void 0 ? { title: input.title } : {}, ...input.description !== void 0 ? { description: input.description } : {} };
1170
+ return plan(`Register X upload ${key}`, [`Associate this approved ${bound.media_type} upload with account ${account}; SHA-256 ${bound.sha256}. ${JSON.stringify(fields)}`, "No post publication or ad association. Native library and processing eligibility remain separate from campaign approval."], async () => {
1171
+ try {
1172
+ const { data } = await this.provider.client.request("POST", `accounts/${account}/media_library`, z13.object({ data: z13.looseObject({ media_key: mediaKey }) }), fields);
1173
+ if (data.media_key !== key) throw new Error("x: registered media key mismatch");
1174
+ const observed = await this.provider.creatives.media(account, key);
1175
+ if (observed.deleted || observed.media_type !== bound.media_type || Object.entries(fields).some(([field, value]) => observed[field] !== value)) throw new Error("x: registered media metadata readback mismatch");
1176
+ return { applied: true, resourceIds: [key], details: { status: observed.media_status, next_tool: "x_get_media_library_item" } };
1177
+ } catch (error) {
1178
+ throw new AdportError8("PROVIDER_ERROR", error instanceof Error ? error.message : "x: library registration failed; reconcile before retrying", { resource_ids: [key], resource_receipt: input.resource_receipt });
1179
+ }
1180
+ }, { provider: "x", accountId: account, kind: "create", title: "Add media to X library", subject: input.name, fields: [{ label: "Media", after: key }, ...input.file_name === void 0 ? [] : [{ label: "File name", after: input.file_name }], ...input.title === void 0 ? [] : [{ label: "Title", after: input.title }], ...input.description === void 0 ? [] : [{ label: "Description", after: input.description }], { label: "SHA-256", after: bound.sha256 }], notices: ["Adds the approved upload to this account\u2019s media library. Publishing is a separate action."] });
1181
+ }
1182
+ };
1183
+
1184
+ // src/cards.ts
1185
+ import { createHash } from "crypto";
1186
+ import { AdportError as AdportError9 } from "@adport/core";
1187
+ import { z as z15 } from "zod";
1188
+
1189
+ // src/card-schemas.ts
1190
+ import { z as z14 } from "zod";
1191
+ var cardTypes = z14.enum(["IMAGE_APP", "IMAGE_CAROUSEL_APP", "IMAGE_CAROUSEL_WEBSITE", "IMAGE_MULTI_DEST_CAROUSEL_WEBSITE", "IMAGE_WEBSITE", "MIXED_MEDIA_MULTI_DEST_CAROUSEL_WEBSITE", "MIXED_MEDIA_SINGLE_DEST_CAROUSEL_APP", "MIXED_MEDIA_SINGLE_DEST_CAROUSEL_WEBSITE", "VIDEO_APP", "VIDEO_CAROUSEL_APP", "VIDEO_CAROUSEL_WEBSITE", "VIDEO_MULTI_DEST_CAROUSEL_WEBSITE", "VIDEO_WEBSITE"]);
1192
+ var cardButtonLabel = z14.enum(["BOOK", "CONNECT", "INSTALL", "OPEN", "ORDER", "PLAY", "SHOP"]);
1193
+ var cardWebsite = z14.string().url().max(8192).refine((value) => {
1194
+ try {
1195
+ const url3 = new URL(value);
1196
+ return ["http:", "https:"].includes(url3.protocol) && !url3.username && !url3.password;
1197
+ } catch {
1198
+ return false;
1199
+ }
1200
+ }, "Use an HTTP or HTTPS destination without embedded credentials");
1201
+ var appId = z14.string().min(1).max(512);
1202
+ var appDestination = z14.object({ type: z14.literal("APP"), country_code: z14.string().regex(/^[A-Z]{2}$/), googleplay_app_id: appId.optional(), ios_app_store_identifier: appId.optional(), googleplay_deep_link: z14.string().url().max(8192).optional(), ios_deep_link: z14.string().url().max(8192).optional() }).strict().refine((v) => !!v.googleplay_app_id || !!v.ios_app_store_identifier, "Provide at least one app store identifier").refine((v) => !v.googleplay_deep_link || !!v.googleplay_app_id, "An Android deep link needs googleplay_app_id").refine((v) => !v.ios_deep_link || !!v.ios_app_store_identifier, "An iOS deep link needs ios_app_store_identifier");
1203
+ var cardComponent = z14.discriminatedUnion("type", [
1204
+ z14.object({ type: z14.literal("MEDIA"), media_key: mediaKey }).strict(),
1205
+ z14.object({ type: z14.literal("SWIPEABLE_MEDIA"), media_keys: z14.array(mediaKey).min(2).max(6) }).strict(),
1206
+ z14.object({ type: z14.literal("DETAILS"), title: z14.string().min(1).max(1e4).describe("Native title length and content eligibility are validated by X only on apply."), destination: z14.object({ type: z14.literal("WEBSITE"), url: cardWebsite }).strict() }).strict(),
1207
+ z14.object({ type: z14.literal("BUTTON"), label: z14.object({ type: z14.literal("ENUM"), value: cardButtonLabel }).strict(), destination: appDestination }).strict()
1208
+ ]);
1209
+ var cardComponents = z14.array(cardComponent).length(2).refine((v) => ["MEDIA", "SWIPEABLE_MEDIA"].includes(v[0].type) && ["DETAILS", "BUTTON"].includes(v[1].type), "Use one media component followed by one website-details or app-button component");
1210
+ var cardSlides = z14.array(cardComponents.refine((v) => v[0].type === "MEDIA" && v[1].type === "DETAILS", "Each multi-destination slide needs one MEDIA and one website DETAILS component")).min(2).max(6);
1211
+ var layout = { components: cardComponents.optional(), slides: cardSlides.optional() };
1212
+ var createCard = z14.object({ name: z14.string().trim().min(1).max(80), ...layout }).strict().refine((v) => !!v.components !== !!v.slides, "Provide components or slides, never both");
1213
+ var hash = z14.string().regex(/^[a-f0-9]{64}$/);
1214
+ var updateCard = z14.object({
1215
+ card_id: snowflake,
1216
+ expected_configuration_hash: hash,
1217
+ acknowledge_shared_creative_effects: z14.literal(true),
1218
+ name: z14.string().trim().min(1).max(80).optional(),
1219
+ ...layout,
1220
+ title: z14.string().min(1).max(1e4).optional(),
1221
+ website_url: cardWebsite.optional(),
1222
+ button_label: cardButtonLabel.optional(),
1223
+ slide_index: z14.number().int().min(0).max(5).optional()
1224
+ }).strict().refine((v) => !(v.components && v.slides), "Provide components or slides, never both").refine((v) => ["name", "components", "slides", "title", "website_url", "button_label"].some((key) => Object.hasOwn(v, key)), "Provide card changes").refine((v) => !(v.components || v.slides) || !["title", "website_url", "button_label", "slide_index"].some((key) => Object.hasOwn(v, key)), "Use a replacement layout or copy shortcuts, never both").refine((v) => v.slide_index === void 0 || v.title !== void 0 || v.website_url !== void 0 || v.button_label !== void 0, "A slide index requires a copy change");
1225
+ var deleteCard = z14.object({ card_id: snowflake, expected_configuration_hash: hash, acknowledge_shared_creative_effects: z14.literal(true) }).strict();
1226
+ var listCards = z14.object({ account_id: xId, count: z14.number().int().min(1).max(200).default(20), cursor: z14.string().min(1).max(4096).optional(), card_types: z14.array(cardTypes).min(1).max(13).optional(), card_ids: z14.array(snowflake).min(1).max(200).optional(), card_uris: z14.array(cardUri).min(1).max(200).optional(), q: z14.string().min(1).max(80).optional(), include_legacy_cards: z14.boolean().default(false), with_deleted: z14.boolean().default(false), include_media: z14.boolean().default(true) });
1227
+ var nativeCard = z14.looseObject({ id: xId, card_uri: cardUri, name: z14.string().nullish(), card_type: z14.string(), deleted: z14.boolean(), components: z14.array(z14.unknown()).max(100).nullish(), slides: z14.array(z14.array(z14.unknown()).max(100)).max(100).nullish() });
1228
+ var cardWrites = /* @__PURE__ */ new Set(["x_create_card", "x_update_card", "x_delete_card"]);
1229
+
1230
+ // src/cards.ts
1231
+ var canonical = (value) => Array.isArray(value) ? value.map(canonical) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, canonical(v)])) : value;
1232
+ var equal = (a, b) => JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));
1233
+ var layoutOf = (card) => ({ ...card.components?.length ? { components: card.components } : {}, ...card.slides?.length ? { slides: card.slides } : {} });
1234
+ var content = (card) => ({ id: card.id, card_uri: card.card_uri, name: card.name, card_type: card.card_type, deleted: card.deleted, ...layoutOf(card) });
1235
+ var mutationNotice = "Shared card edits or deletion can affect existing posts and ads. This operation does not publish a post, create an ad association or change delivery/budgets. Native content validation happens only on apply. No native write is retried automatically.";
1236
+ var XCardService = class {
1237
+ constructor(entities, creatives) {
1238
+ this.entities = entities;
1239
+ this.creatives = creatives;
1240
+ }
1241
+ entities;
1242
+ creatives;
1243
+ hash(account, card) {
1244
+ return createHash("sha256").update(JSON.stringify(canonical({ account_id: account, card }))).digest("hex");
1245
+ }
1246
+ decorate(account, card) {
1247
+ return { ...card, configuration_hash: this.hash(account, card) };
1248
+ }
1249
+ async owned(account, id, withDeleted = false) {
1250
+ await this.entities.getAccount(account);
1251
+ const result = await this.entities.client.request("GET", `accounts/${xId.parse(account)}/cards/${snowflake.parse(id)}`, z15.object({ data: z15.array(nativeCard).max(1) }), { with_deleted: withDeleted });
1252
+ const card = result.data[0];
1253
+ if (!card || card.id !== id || !withDeleted && card.deleted || card.account_id !== void 0 && card.account_id !== account) throw new AdportError9("PROVIDER_ERROR", "x: card ID, account or deletion state mismatch");
1254
+ return card;
1255
+ }
1256
+ async get(account, id, withDeleted = false) {
1257
+ return this.decorate(account, await this.owned(account, id, withDeleted));
1258
+ }
1259
+ keys(layout2) {
1260
+ return [...new Set((layout2.components ? [layout2.components] : layout2.slides ?? []).flatMap((row) => row.flatMap((v) => v.type === "MEDIA" ? [v.media_key] : v.type === "SWIPEABLE_MEDIA" ? v.media_keys : [])))];
1261
+ }
1262
+ supportedLayout(card) {
1263
+ const value = layoutOf(card);
1264
+ if (!!value.components === !!value.slides) throw new AdportError9("INVALID_INPUT", "x: current card layout is not representable by this authoring tool; no fields were discarded");
1265
+ if (value.components) {
1266
+ const parsed = cardComponents.safeParse(value.components);
1267
+ if (parsed.success) return { components: parsed.data };
1268
+ }
1269
+ if (value.slides) {
1270
+ const parsed = cardSlides.safeParse(value.slides);
1271
+ if (parsed.success) return { slides: parsed.data };
1272
+ }
1273
+ throw new AdportError9("INVALID_INPUT", "x: current card contains unsupported component fields; replace the complete layout explicitly or change only its name");
1274
+ }
1275
+ async mediaFor(account, layout2) {
1276
+ const sources = /* @__PURE__ */ new Map();
1277
+ for (const key of this.keys(layout2)) {
1278
+ const value = await this.creatives.media(account, key);
1279
+ if (value.deleted || value.media_status !== "TRANSCODE_COMPLETED" || !["IMAGE", "VIDEO"].includes(value.media_type) || value.account_id !== void 0 && value.account_id !== account) throw new AdportError9("INVALID_INPUT", "x: every card attachment must be a ready image or video in the selected account library");
1280
+ sources.set(key, value);
1281
+ }
1282
+ return sources;
1283
+ }
1284
+ cardType(layout2, media) {
1285
+ const kinds = new Set([...media.values()].map((v) => v.media_type)), kind = kinds.size > 1 ? "MIXED_MEDIA" : [...kinds][0];
1286
+ if (layout2.slides) return `${kind}_MULTI_DEST_CAROUSEL_WEBSITE`;
1287
+ const [asset, description] = layout2.components, destination3 = description.type === "DETAILS" ? "WEBSITE" : "APP";
1288
+ return asset.type === "MEDIA" ? `${kind}_${destination3}` : `${kind}${kind === "MIXED_MEDIA" ? "_SINGLE_DEST" : ""}_CAROUSEL_${destination3}`;
1289
+ }
1290
+ copyLayout(card, input) {
1291
+ const layout2 = this.supportedLayout(card);
1292
+ if (layout2.slides && input.slide_index === void 0) throw new AdportError9("INVALID_INPUT", "x: select slide_index for a multi-destination copy edit");
1293
+ if (layout2.components && input.slide_index !== void 0) throw new AdportError9("INVALID_INPUT", "x: slide_index is only valid for a multi-destination card");
1294
+ const row = layout2.components ?? layout2.slides?.[input.slide_index];
1295
+ if (!row) throw new AdportError9("INVALID_INPUT", "x: selected slide is not present in this card");
1296
+ const description = row[1];
1297
+ if (input.title !== void 0 || input.website_url !== void 0) {
1298
+ if (description.type !== "DETAILS") throw new AdportError9("INVALID_INPUT", "x: title/website_url shortcuts require website DETAILS");
1299
+ if (input.title !== void 0) description.title = input.title;
1300
+ if (input.website_url !== void 0) description.destination.url = input.website_url;
1301
+ }
1302
+ if (input.button_label !== void 0) {
1303
+ if (description.type !== "BUTTON") throw new AdportError9("INVALID_INPUT", "x: button_label requires an app BUTTON");
1304
+ description.label.value = input.button_label;
1305
+ }
1306
+ return layout2;
1307
+ }
1308
+ actions(account, card) {
1309
+ if (card.deleted || !snowflake.safeParse(card.id).success || !card.name) return [];
1310
+ const args = { account_id: account, card_id: card.id, expected_configuration_hash: this.hash(account, card), acknowledge_shared_creative_effects: true };
1311
+ const actions = [{ label: "Rename card", tool: "x_update_card", arguments: args, fields: [{ key: "name", label: "Card name", type: "text", value: card.name, max_length: 80 }] }];
1312
+ let layout2;
1313
+ try {
1314
+ layout2 = this.supportedLayout(card);
1315
+ } catch {
1316
+ return actions;
1317
+ }
1318
+ for (const [index, row] of (layout2.components ? [layout2.components] : layout2.slides).entries()) {
1319
+ const description = row[1], bound = { ...args, ...layout2.slides ? { slide_index: index } : {} };
1320
+ if (description.type === "DETAILS") actions.push({ label: layout2.slides ? `Edit slide ${index + 1} copy` : "Edit card copy", tool: "x_update_card", arguments: bound, fields: [{ key: "title", label: "Title", type: "text", value: description.title }, { key: "website_url", label: "Website URL", type: "text", value: description.destination.url }] });
1321
+ if (description.type === "BUTTON") actions.push({ label: "Edit app button", tool: "x_update_card", arguments: bound, fields: [{ key: "button_label", label: "Button", type: "select", value: description.label.value, options: cardButtonLabel.options.map((value) => ({ label: value, value })) }] });
1322
+ }
1323
+ return actions;
1324
+ }
1325
+ async list(value) {
1326
+ const input = listCards.parse(value);
1327
+ await this.entities.getAccount(input.account_id);
1328
+ const params = { count: input.count, include_legacy_cards: input.include_legacy_cards, with_deleted: input.with_deleted, ...input.cursor ? { cursor: input.cursor } : {}, ...input.q ? { q: input.q } : {}, ...input.card_types ? { card_types: input.card_types.join(",") } : {}, ...input.card_ids ? { card_id: input.card_ids.join(",") } : {}, ...input.card_uris ? { card_uris: input.card_uris.join(",") } : {} };
1329
+ const result = await this.entities.client.request("GET", `accounts/${input.account_id}/cards`, z15.object({ data: z15.array(nativeCard).max(1e3), next_cursor: z15.string().max(4096).nullish() }), params);
1330
+ if (new Set(result.data.map((v) => v.id)).size !== result.data.length || new Set(result.data.map((v) => v.card_uri)).size !== result.data.length || result.next_cursor && result.next_cursor === input.cursor || result.data.some((v) => !input.with_deleted && v.deleted || v.account_id !== void 0 && v.account_id !== input.account_id || input.card_ids && !input.card_ids.includes(v.id) || input.card_uris && !input.card_uris.includes(v.card_uri) || input.card_types && !input.card_types.some((t) => t === v.card_type))) throw new AdportError9("PROVIDER_ERROR", "x: card inventory repeated a resource/cursor or returned a conflicting account/filter");
1331
+ const warnings = [], media = /* @__PURE__ */ new Map(), keys = [];
1332
+ for (const card of result.data) {
1333
+ try {
1334
+ keys.push(...this.keys(this.supportedLayout(card)));
1335
+ } catch {
1336
+ warnings.push(`Card ${card.id} has a layout that cannot be hydrated by this tool; native content is retained in items.`);
1337
+ }
1338
+ }
1339
+ const unique3 = [...new Set(keys)];
1340
+ let offset = 0;
1341
+ if (input.include_media) await Promise.all(Array.from({ length: Math.min(4, unique3.length, 100) }, async () => {
1342
+ while (offset < Math.min(unique3.length, 100)) {
1343
+ const key = unique3[offset++];
1344
+ try {
1345
+ const source = await this.creatives.media(input.account_id, key);
1346
+ if (!source.deleted && (source.account_id === void 0 || source.account_id === input.account_id)) media.set(key, source);
1347
+ else warnings.push(`Media ${key} is deleted or unavailable in this account.`);
1348
+ } catch {
1349
+ warnings.push(`Media ${key} could not be read from this account.`);
1350
+ }
1351
+ }
1352
+ }));
1353
+ if (input.include_media && unique3.length > 100) warnings.push("Preview hydration is limited to 100 distinct media; native card references are retained in items.");
1354
+ const creatives = result.data.map((card) => {
1355
+ let layout2;
1356
+ try {
1357
+ layout2 = this.supportedLayout(card);
1358
+ } catch {
1359
+ }
1360
+ const rows2 = layout2?.components ? [layout2.components] : layout2?.slides ?? [], descriptions = rows2.map((v) => v[1]), headlines = descriptions.flatMap((v) => v.type === "DETAILS" ? [v.title] : []), urls = descriptions.flatMap((v) => v.type === "DETAILS" ? [v.destination.url] : []);
1361
+ return { id: card.id, provider: "x", account_id: input.account_id, name: card.name ?? card.id, type: card.card_type, status: card.deleted ? "DELETED" : "CARD", headlines, descriptions: descriptions.flatMap((v) => v.type === "BUTTON" ? [v.label.value] : []), landing_urls: urls, media: input.include_media && layout2 ? this.keys(layout2).flatMap((key) => media.has(key) ? this.creatives.visual(media.get(key)) : []) : [], actions: this.actions(input.account_id, card) };
1362
+ });
1363
+ return { items: result.data.map((v) => this.decorate(input.account_id, v)), creatives, warnings, truncated: Boolean(result.next_cursor), ...result.next_cursor ? { next_cursor: result.next_cursor } : {} };
1364
+ }
1365
+ layoutFields(layout2) {
1366
+ const fields = { Media: this.keys(layout2) };
1367
+ for (const [index, row] of (layout2.components ? [layout2.components] : layout2.slides ?? []).entries()) {
1368
+ const prefix = layout2.slides ? `Slide ${index + 1} ` : "", description = row[1];
1369
+ if (description.type === "DETAILS") {
1370
+ fields[`${prefix}title`] = description.title;
1371
+ fields[`${prefix}website`] = description.destination.url;
1372
+ }
1373
+ if (description.type === "BUTTON") {
1374
+ fields.Button = description.label.value;
1375
+ fields["App destination"] = description.destination;
1376
+ }
1377
+ }
1378
+ return fields;
1379
+ }
1380
+ async plan(op) {
1381
+ const creating = op.tool === "x_create_card", removing = op.tool === "x_delete_card", account = xId.parse(op.accountId);
1382
+ if (op.provider !== "x" || !cardWrites.has(op.tool) || op.kind !== (creating ? "create" : removing ? "remove" : "update")) throw new AdportError9("INVALID_INPUT", "x: card operation provider/kind mismatch");
1383
+ const input = creating ? createCard.parse(op.payload) : removing ? deleteCard.parse(op.payload) : updateCard.parse(op.payload);
1384
+ await this.entities.getAccount(account);
1385
+ const current = "card_id" in input ? await this.owned(account, input.card_id) : void 0;
1386
+ if (current && "expected_configuration_hash" in input && this.hash(account, current) !== input.expected_configuration_hash) throw new AdportError9("PENDING_MISMATCH", "x: card configuration changed; read x_get_card before requesting a new preview");
1387
+ let body = {}, expected, layout2;
1388
+ if (!removing) {
1389
+ if (creating) {
1390
+ const v = createCard.parse(input);
1391
+ body = v;
1392
+ layout2 = v;
1393
+ } else {
1394
+ const v = updateCard.parse(input);
1395
+ body = { ...v.name !== void 0 ? { name: v.name } : {} };
1396
+ layout2 = v.components ? { components: v.components } : v.slides ? { slides: v.slides } : v.title !== void 0 || v.website_url !== void 0 || v.button_label !== void 0 ? this.copyLayout(current, v) : void 0;
1397
+ if (layout2) body = { ...body, ...layout2 };
1398
+ }
1399
+ const sources = layout2 ? await this.mediaFor(account, layout2) : void 0;
1400
+ expected = { ...current ? content(current) : { id: "", card_uri: "", deleted: false }, name: typeof body.name === "string" ? body.name : current.name, card_type: layout2 ? this.cardType(layout2, sources) : current.card_type, ...layout2 ?? layoutOf(current) };
1401
+ if (layout2?.components) delete expected.slides;
1402
+ if (layout2?.slides) delete expected.components;
1403
+ }
1404
+ const title = `${creating ? "Create" : removing ? "Delete" : "Edit"} X card`, name3 = typeof body.name === "string" ? body.name : current.name ?? current.id;
1405
+ const fields = [{ label: "Card name", ...current ? { before: current.name ?? current.id } : {}, after: removing ? null : name3 }, ...current ? [{ label: "Card ID", after: current.id }] : []];
1406
+ if (removing) fields.push({ label: "Deleted", before: false, after: true });
1407
+ if (layout2) {
1408
+ let previous = {};
1409
+ try {
1410
+ if (current) previous = this.layoutFields(this.supportedLayout(current));
1411
+ } catch {
1412
+ }
1413
+ const proposed = this.layoutFields(layout2);
1414
+ fields.push({ label: "Card type", ...current ? { before: current.card_type } : {}, after: expected.card_type });
1415
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(proposed)])) if (!current || !equal(previous[key], proposed[key])) fields.push({ label: key, ...current ? { before: previous[key] } : {}, after: proposed[key] ?? null });
1416
+ }
1417
+ return {
1418
+ summary: `${title} "${name3}"`,
1419
+ changes: [removing ? `- Delete card ${current.id} (${current.card_uri}). No restore endpoint is established.` : `${creating ? "+" : "~"} ${JSON.stringify(body)}`, mutationNotice],
1420
+ notes: [creating ? "Creates an unattached card only. No post is published and no ad association is created." : mutationNotice],
1421
+ coercions: [],
1422
+ budgetDeltas: [],
1423
+ review: { provider: "x", accountId: account, kind: creating ? "create" : removing ? "remove" : "update", title, fields, notices: [mutationNotice] },
1424
+ execute: async () => {
1425
+ let knownId = current?.id;
1426
+ try {
1427
+ const base = `accounts/${account}/cards`;
1428
+ const receipt = creating ? (await this.entities.client.request("POST", base, z15.object({ data: nativeCard }), {}, body)).data : (await this.entities.client.request(removing ? "DELETE" : "PUT", `${base}/${current.id}`, z15.object({ data: z15.array(nativeCard).length(1) }), {}, removing ? void 0 : body)).data[0];
1429
+ knownId = receipt.id;
1430
+ if (current && (receipt.id !== current.id || receipt.card_uri !== current.card_uri)) throw new Error("x: card mutation receipt identity mismatch");
1431
+ if (removing ? !receipt.deleted : !equal(content(receipt), { ...expected, id: receipt.id, card_uri: receipt.card_uri })) throw new Error("x: card mutation receipt differs from the approved content");
1432
+ const observed = await this.owned(account, receipt.id, removing);
1433
+ if (observed.card_uri !== receipt.card_uri || (removing ? !observed.deleted : !equal(content(observed), { ...expected, id: receipt.id, card_uri: receipt.card_uri }))) throw new Error("x: independent card readback differs from the approved content");
1434
+ return [receipt.id];
1435
+ } catch (error) {
1436
+ const details = error instanceof AdportError9 && error.details && typeof error.details === "object" ? error.details : {};
1437
+ const previous = Array.isArray(details.resource_ids) ? details.resource_ids.filter((v) => typeof v === "string") : [];
1438
+ throw new AdportError9("PROVIDER_ERROR", `${error instanceof Error ? error.message : "x: card mutation was not confirmed"}. Reconcile the original card IDs before another mutation; no write was retried.`, { ...details, resource_ids: [.../* @__PURE__ */ new Set([...current ? [current.id] : [], ...knownId ? [knownId] : [], ...previous])] });
1439
+ }
1440
+ }
1441
+ };
1442
+ }
1443
+ };
1444
+
1445
+ // src/audiences.ts
1446
+ import { createHash as createHash2 } from "crypto";
1447
+ import { AdportError as AdportError10 } from "@adport/core";
1448
+ import { z as z17 } from "zod";
1449
+
1450
+ // src/audience-tools.ts
1451
+ import { defineTool as defineTool5, guardedWriteTool as guardedWriteTool5 } from "@adport/core";
1452
+ import { z as z16 } from "zod";
1453
+ var hash2 = z16.string().regex(/^[a-f0-9]{64}$/);
1454
+ var name2 = z16.string().trim().min(1).max(255);
1455
+ var ids = z16.array(xId).min(1).max(200).refine((values2) => new Set(values2).size === values2.length, "Use unique IDs");
1456
+ var page = { cursor: z16.string().min(1).max(4096).optional(), count: z16.number().int().min(1).max(1e3).default(200), with_total_count: z16.boolean().default(false).describe("Request a total on the initial page; cursor requests omit this native flag") };
1457
+ var audienceList = z16.object({ account_id: xId, ...page, permission_scope: z16.enum(["OWNER", "SHARED"]).default("OWNER"), custom_audience_ids: ids.optional(), q: z16.string().min(1).max(255).optional(), with_deleted: z16.boolean().default(false) }).strict();
1458
+ var audienceGet = z16.object({ account_id: xId, custom_audience_id: xId, with_deleted: z16.boolean().default(false) }).strict();
1459
+ var audiencePermissions = z16.object({ account_id: xId, custom_audience_id: xId, ...page, granted_account_ids: ids.optional(), custom_audience_permission_ids: ids.optional() }).strict();
1460
+ var createAudience = z16.object({ name: name2, description: z16.string().max(4096).optional() }).strict();
1461
+ var updateAudience = z16.object({ custom_audience_id: xId, expected_configuration_hash: hash2, name: name2.optional(), description: z16.string().max(4096).optional() }).strict().refine((value) => value.name !== void 0 || value.description !== void 0, "Provide a name or description");
1462
+ var deleteAudience = z16.object({ custom_audience_id: xId, expected_configuration_hash: hash2, expected_usage_hash: hash2 }).strict();
1463
+ var values = z16.array(hash2).min(1).max(100).refine((value) => new Set(value).size === value.length, "Identifiers must be unique within a user field");
1464
+ var user = z16.object({ email: values.optional(), device_id: values.optional(), handle: values.optional(), twitter_id: values.optional(), phone_number: values.optional(), partner_user_id: z16.array(z16.string().min(1).max(1024)).min(1).max(100).optional() }).strict().refine((value) => Object.keys(value).length > 0, "Each user needs an identifier");
1465
+ var operation = z16.object({ operation_type: z16.enum(["Update", "Delete"]), params: z16.object({ users: z16.array(user).min(1).max(2500), effective_at: z16.iso.datetime().optional(), expires_at: z16.iso.datetime().optional() }).strict().refine((value) => !value.expires_at || !value.effective_at || Date.parse(value.expires_at) > Date.parse(value.effective_at), "Expiry must follow the effective time") }).strict();
1466
+ var audienceUsers = z16.object({ custom_audience_id: xId, expected_configuration_hash: hash2, operations: z16.array(operation).min(1).max(2500) }).strict().refine((value) => value.operations.reduce((total, op) => total + op.params.users.length, 0) <= 2500, "Adport limit: 2500 total user records per approved call").refine((value) => Buffer.byteLength(JSON.stringify(value.operations)) <= 5e6, "Native JSON body must not exceed 5000000 bytes");
1467
+ function xAudienceTools(provider) {
1468
+ const output = z16.looseObject({ records: z16.array(z16.record(z16.string(), z16.unknown())) });
1469
+ const read = { namespace: "x", presentation: "records", output, annotations: { readOnly: true } };
1470
+ const write = { namespace: "x", provider: "x" };
1471
+ return [
1472
+ defineTool5({ ...read, name: "x_custom_audiences", description: "List owned or already shared X custom audiences with exact native cursor filters, targetability and configuration hashes. Load more retains selection; no members are returned.", input: audienceList, pagination: { cursorInput: "cursor" }, handler: (input) => provider.audiences.list(input) }),
1473
+ defineTool5({ ...read, name: "x_get_custom_audience", description: "Read one selected-account custom audience, ownership and configuration_hash. Processing/size/targetability are native diagnostics, not proof of exact member contents.", input: audienceGet, handler: (input) => provider.audiences.get(input) }),
1474
+ defineTool5({ ...read, name: "x_custom_audience_permissions", description: "Inspect existing audience sharing permissions with native cursor/ID filters; does not grant, revoke or expand access.", input: audiencePermissions, pagination: { cursorInput: "cursor" }, handler: (input) => provider.audiences.permissions(input) }),
1475
+ defineTool5({ ...read, name: "x_custom_audience_usage", description: "Inspect all targeted campaigns, including inactive groups, sharing permissions and direct audience inclusion/exclusion criteria. Bounded complete scan supplies usage_hash for deletion; incomplete scans fail.", input: z16.object({ account_id: xId, custom_audience_id: xId }).strict(), handler: (input) => provider.audiences.usage(input.account_id, input.custom_audience_id) }),
1476
+ guardedWriteTool5({ ...write, name: "x_create_custom_audience", kind: "create", destructive: false, description: "Create an empty owned CRM audience placeholder. Independently reads back ownership and approved metadata; no user upload, ad association, sharing or activation.", payload: createAudience }),
1477
+ guardedWriteTool5({ ...write, name: "x_update_custom_audience", kind: "update", destructive: false, description: "Edit an owned audience name or description using a fresh configuration_hash. Preserves omitted metadata and audience type; independently verifies native readback.", payload: updateAudience }),
1478
+ guardedWriteTool5({ ...write, name: "x_update_custom_audience_users", kind: "update", destructive: true, description: "Submit explicit Update/Delete member groups to an owned CRM audience. Identifiers must already be normalized SHA256, except native partner_user_id. Preview shows counts/digest; receipt confirms processing acceptance, not targeting readiness. No automatic retry.", payload: audienceUsers, sensitiveInputs: ["operations"] }),
1479
+ guardedWriteTool5({ ...write, name: "x_delete_custom_audience", kind: "remove", destructive: true, description: "Delete an owned unreferenced, unshared audience using current configuration and usage hashes. Checks inactive targeting and exclusions, then independently verifies deleted=true. No restore endpoint is claimed.", payload: deleteAudience })
1480
+ ];
1481
+ }
1482
+
1483
+ // src/audiences.ts
1484
+ var audience = z17.looseObject({ id: xId, name: z17.string(), description: z17.string().nullable(), audience_type: z17.string(), deleted: z17.boolean(), permission_level: z17.string(), owner_account_id: xId.optional(), is_owner: z17.boolean().optional(), targetable: z17.boolean().optional(), audience_size: z17.number().int().nonnegative().safe().nullable().optional(), partner_source: z17.string().optional() });
1485
+ var permission = z17.looseObject({ id: xId, custom_audience_id: xId, granted_account_id: xId, permission_level: z17.string(), deleted: z17.boolean() });
1486
+ var target = z17.looseObject({ campaign_id: xId, campaign_name: z17.string().nullable().optional(), line_items: z17.array(z17.looseObject({ id: xId, name: z17.string().nullable().optional(), servable: z17.boolean() })) });
1487
+ var criterion2 = z17.looseObject({ id: xId, line_item_id: xId, targeting_type: z17.string(), targeting_value: z17.string(), operator_type: z17.string().optional(), deleted: z17.boolean() });
1488
+ var canonical2 = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
1489
+ var digest = (value) => createHash2("sha256").update(canonical2(value)).digest("hex");
1490
+ var configuration = (value) => Object.fromEntries(["id", "name", "description", "audience_type", "permission_level", "owner_account_id", "is_owner", "partner_source", "deleted"].filter((key) => value[key] !== void 0).map((key) => [key, value[key]]));
1491
+ var snapshot = (account, value) => digest({ account_id: account, configuration: configuration(value) });
1492
+ var notes = ["Local preview only; X has no server dry run or conditional configuration update for this workflow.", "No automatic write retry. Reconcile known IDs and receipts after an uncertain result."];
1493
+ var rejection = (error) => error instanceof AdportError10 && error.details !== null && typeof error.details === "object" && "http_status" in error.details && [401, 403, 429].includes(Number(error.details.http_status));
1494
+ var XAudienceService = class {
1495
+ constructor(entities) {
1496
+ this.entities = entities;
1497
+ }
1498
+ entities;
1499
+ base(account) {
1500
+ return `accounts/${xId.parse(account)}/custom_audiences`;
1501
+ }
1502
+ scope(value, account, resource) {
1503
+ const params = value.request?.params;
1504
+ if (params && (params.account_id !== void 0 && params.account_id !== account || resource && params.custom_audience_id !== void 0 && params.custom_audience_id !== resource)) throw new AdportError10("PROVIDER_ERROR", "x: audience response scope differs from the selected account/ID");
1505
+ }
1506
+ owned(value, account) {
1507
+ if (value.owner_account_id !== void 0 && value.owner_account_id !== account || value.is_owner === false || value.owner_account_id === void 0 && value.is_owner !== true || value.permission_level !== "READ_WRITE") throw new AdportError10("INVALID_INPUT", "x: audience must be verifiably owned and writable by the selected account");
1508
+ if (value.deleted) throw new AdportError10("INVALID_INPUT", "x: deleted audiences cannot be modified");
1509
+ }
1510
+ async page(account, path, schema, params, resource) {
1511
+ const data = await this.entities.client.request("GET", path, z17.looseObject({ data: z17.array(schema), next_cursor: z17.string().nullable().optional(), total_count: z17.number().int().nonnegative().safe().optional(), request: z17.object({ params: z17.record(z17.string(), z17.unknown()).optional() }).optional() }), params);
1512
+ this.scope(data, account, resource);
1513
+ if (data.next_cursor && data.next_cursor === params.cursor) throw new AdportError10("PROVIDER_ERROR", "x: audience pagination repeated its cursor");
1514
+ const identities = data.data.map((value) => String(value.id ?? value.campaign_id));
1515
+ if (new Set(identities).size !== identities.length || data.data.length > 1e3) throw new AdportError10("PROVIDER_ERROR", "x: audience page exceeds its native limit or repeats entities");
1516
+ const complete = data.next_cursor === null ? true : data.next_cursor ? false : null;
1517
+ if (!params.cursor && data.total_count !== void 0 && (data.total_count < data.data.length || complete && data.total_count !== data.data.length)) throw new AdportError10("PROVIDER_ERROR", "x: audience total count contradicts the native page");
1518
+ return { ...data, complete, truncated: complete !== true, next_cursor: data.next_cursor || void 0 };
1519
+ }
1520
+ pageParams(input) {
1521
+ const params = Object.fromEntries(Object.entries(input).filter(([key, value]) => key !== "with_total_count" && value !== void 0));
1522
+ if (input.with_total_count && !input.cursor) params.with_total_count = true;
1523
+ return params;
1524
+ }
1525
+ record(value) {
1526
+ return {
1527
+ id: value.id,
1528
+ name: value.name,
1529
+ status: value.deleted ? "Deleted" : value.targetable === true ? "Targetable" : value.targetable === false ? "Not targetable" : "Targetability not reported",
1530
+ audience_type: value.audience_type,
1531
+ audience_size: value.audience_size ?? "Not reported",
1532
+ ...Array.isArray(value.reasons_not_targetable) && value.reasons_not_targetable.length ? { reasons_not_targetable: value.reasons_not_targetable } : {},
1533
+ permission_level: value.permission_level
1534
+ };
1535
+ }
1536
+ async list(raw) {
1537
+ const { account_id, custom_audience_ids, ...input } = audienceList.parse(raw);
1538
+ await this.entities.getAccount(account_id);
1539
+ const params = this.pageParams(input);
1540
+ if (custom_audience_ids) params.custom_audience_ids = custom_audience_ids.join(",");
1541
+ const page5 = await this.page(account_id, this.base(account_id), audience, params);
1542
+ if (page5.data.some((value) => custom_audience_ids && !custom_audience_ids.includes(value.id) || !input.with_deleted && value.deleted || input.q && !value.name.toLowerCase().startsWith(input.q.toLowerCase()) || input.permission_scope === "OWNER" && (value.owner_account_id !== void 0 && value.owner_account_id !== account_id || value.is_owner === false) || input.permission_scope === "SHARED" && (value.owner_account_id === account_id || value.is_owner === true))) throw new AdportError10("PROVIDER_ERROR", "x: audience list does not match its ID/deletion/ownership/name filters");
1543
+ const items = page5.data.map((value) => ({ ...value, configuration_hash: snapshot(account_id, value) }));
1544
+ return { ...page5, data: items, records: items.map((value) => this.record(value)), notes: [...page5.complete === null ? ["Native next_cursor is missing; completeness is unconfirmed."] : [], ...page5.data.length > input.count ? ["The native endpoint exceeded the requested count; the full page is retained."] : []] };
1545
+ }
1546
+ async get(raw) {
1547
+ const input = audienceGet.parse(raw);
1548
+ await this.entities.getAccount(input.account_id);
1549
+ const response = await this.entities.client.request("GET", `${this.base(input.account_id)}/${input.custom_audience_id}`, z17.looseObject({ data: audience, request: z17.object({ params: z17.record(z17.string(), z17.unknown()).optional() }).optional() }), { with_deleted: input.with_deleted });
1550
+ this.scope(response, input.account_id, input.custom_audience_id);
1551
+ if (response.data.id !== input.custom_audience_id || !input.with_deleted && response.data.deleted) throw new AdportError10("PROVIDER_ERROR", "x: audience ID/deletion filter mismatch");
1552
+ const value = { ...response.data, configuration_hash: snapshot(input.account_id, response.data) };
1553
+ return { audience: value, records: [this.record(value)] };
1554
+ }
1555
+ async permissions(raw) {
1556
+ const { account_id, custom_audience_id, granted_account_ids, custom_audience_permission_ids, ...input } = audiencePermissions.parse(raw);
1557
+ await this.get({ account_id, custom_audience_id });
1558
+ const params = this.pageParams(input);
1559
+ if (granted_account_ids) params.granted_account_ids = granted_account_ids.join(",");
1560
+ if (custom_audience_permission_ids) params.custom_audience_permission_ids = custom_audience_permission_ids.join(",");
1561
+ const page5 = await this.page(account_id, `${this.base(account_id)}/${custom_audience_id}/permissions`, permission, params, custom_audience_id);
1562
+ if (page5.data.some((value) => value.custom_audience_id !== custom_audience_id || granted_account_ids && !granted_account_ids.includes(value.granted_account_id) || custom_audience_permission_ids && !custom_audience_permission_ids.includes(value.id))) throw new AdportError10("PROVIDER_ERROR", "x: audience permission ID/filter mismatch");
1563
+ return { ...page5, records: page5.data };
1564
+ }
1565
+ async collect(account, resource, path, schema, params = {}) {
1566
+ const rows2 = [], seen = /* @__PURE__ */ new Set(), ids3 = /* @__PURE__ */ new Set();
1567
+ let cursor2;
1568
+ for (let pageIndex = 0; pageIndex < 25; pageIndex++) {
1569
+ const page5 = await this.page(account, path, schema, { ...params, ...cursor2 ? { cursor: cursor2 } : {} }, resource);
1570
+ for (const value of page5.data) {
1571
+ const identity = String(value.id ?? value.campaign_id);
1572
+ if (ids3.has(identity)) throw new AdportError10("PROVIDER_ERROR", "x: audience usage scan repeated an entity");
1573
+ ids3.add(identity);
1574
+ rows2.push(value);
1575
+ }
1576
+ if (rows2.length > 5e3 || page5.complete === null) throw new AdportError10("PROVIDER_ERROR", "x: audience usage completeness could not be verified within the 5000-record limit");
1577
+ if (page5.complete) return rows2;
1578
+ if (seen.has(page5.next_cursor)) break;
1579
+ seen.add(page5.next_cursor);
1580
+ cursor2 = page5.next_cursor;
1581
+ }
1582
+ throw new AdportError10("PROVIDER_ERROR", "x: audience usage paging is repeated or exceeds the 25-page limit");
1583
+ }
1584
+ async usage(account, resource) {
1585
+ const current = (await this.get({ account_id: account, custom_audience_id: resource })).audience, base = `${this.base(account)}/${xId.parse(resource)}`;
1586
+ const targeted = await this.collect(account, resource, `${base}/targeted`, target, { with_active: false });
1587
+ const permissions = await this.collect(account, resource, `${base}/permissions`, permission, { count: 1e3 });
1588
+ if (permissions.some((value) => value.custom_audience_id !== resource)) throw new AdportError10("PROVIDER_ERROR", "x: usage returned another audience permission");
1589
+ const lines = await this.collect(account, resource, `accounts/${account}/line_items`, lineItemSchema, { with_deleted: true, with_draft: true, count: 1e3 });
1590
+ const byLine = new Map(lines.map((value) => [value.id, value]));
1591
+ if (targeted.some((campaign) => campaign.line_items.some((line) => byLine.get(line.id)?.campaign_id !== campaign.campaign_id))) throw new AdportError10("PROVIDER_ERROR", "x: targeted audience groups do not match the selected account hierarchy");
1592
+ const criteria = [];
1593
+ let scannedCriteria = 0;
1594
+ for (let offset = 0; offset < lines.length; offset += 200) {
1595
+ const batch = lines.slice(offset, offset + 200), selected = new Set(batch.map((value) => value.id));
1596
+ const values2 = await this.collect(account, resource, `accounts/${account}/targeting_criteria`, criterion2, { line_item_ids: batch.map((value) => value.id).join(","), with_deleted: false, count: 1e3 });
1597
+ scannedCriteria += values2.length;
1598
+ if (scannedCriteria > 5e3) throw new AdportError10("PROVIDER_ERROR", "x: audience usage exceeds the 5000-criterion scan limit");
1599
+ if (values2.some((value) => !selected.has(value.line_item_id) || value.deleted)) throw new AdportError10("PROVIDER_ERROR", "x: usage criteria returned a different line item or deleted criterion");
1600
+ criteria.push(...values2.filter((value) => /AUDIENCE/.test(value.targeting_type) && value.targeting_value === resource));
1601
+ }
1602
+ const activePermissions = permissions.filter((value) => !value.deleted), references = targeted.flatMap((value) => value.line_items.map((line) => ({ campaign_id: value.campaign_id, ...line })));
1603
+ const normalized = { account_id: account, audience_id: resource, references: references.map((value) => ({ campaign_id: value.campaign_id, id: value.id, servable: value.servable })).sort((a, b) => canonical2(a).localeCompare(canonical2(b))), criteria: criteria.map((value) => ({ id: value.id, line_item_id: value.line_item_id, targeting_type: value.targeting_type, targeting_value: value.targeting_value, operator_type: value.operator_type })).sort((a, b) => a.id.localeCompare(b.id)), permissions: activePermissions.map((value) => ({ id: value.id, granted_account_id: value.granted_account_id, permission_level: value.permission_level })).sort((a, b) => a.id.localeCompare(b.id)) };
1604
+ const latest = (await this.get({ account_id: account, custom_audience_id: resource })).audience;
1605
+ if (latest.configuration_hash !== current.configuration_hash) throw new AdportError10("INVALID_INPUT", "x: audience configuration changed during usage inspection; read it again");
1606
+ return { audience: current, references, criteria, permissions: activePermissions, complete: true, usage_hash: digest(normalized), records: [{ id: resource, name: current.name, targeted_groups: references.length, direct_criteria: criteria.length, sharing_grants: activePermissions.length }], notes: ["Includes inactive targeting and direct inclusion/exclusion criteria. Native checks are not an atomic lock against changes in another client."] };
1607
+ }
1608
+ async plan(op) {
1609
+ const create = op.tool === "x_create_custom_audience", remove = op.tool === "x_delete_custom_audience", members = op.tool === "x_update_custom_audience_users";
1610
+ if (op.provider !== "x" || op.kind !== (create ? "create" : remove ? "remove" : "update")) throw new AdportError10("INVALID_INPUT", "x: audience provider/operation kind mismatch");
1611
+ const account = xId.parse(op.accountId), base = this.base(account);
1612
+ await this.entities.getAccount(account);
1613
+ if (create) {
1614
+ const input2 = createAudience.parse(op.payload);
1615
+ return { summary: `Create empty X audience "${input2.name}"`, changes: [`+ CRM placeholder ${JSON.stringify(input2)}`], notes: [...notes, "No members are uploaded and no targeting or sharing is added."], coercions: [], budgetDeltas: [], execute: async () => {
1616
+ let resource;
1617
+ try {
1618
+ const receipt = await this.entities.client.request("POST", base, z17.object({ data: z17.looseObject({ id: xId }) }), input2);
1619
+ resource = receipt.data.id;
1620
+ const actual = (await this.get({ account_id: account, custom_audience_id: resource })).audience;
1621
+ this.owned(actual, account);
1622
+ if (actual.name !== input2.name || actual.description !== (input2.description ?? null) || actual.audience_type !== "CRM" || actual.targetable === true || (actual.audience_size ?? 0) > 0) throw new Error("Metadata or empty-placeholder state differs");
1623
+ return { applied: true, resourceIds: [resource] };
1624
+ } catch (error) {
1625
+ if (!resource && rejection(error)) throw error;
1626
+ throw new AdportError10("PROVIDER_ERROR", "x: audience creation outcome unconfirmed; reconcile the owned inventory before another create", { ...resource ? { resource_ids: [resource] } : {} });
1627
+ }
1628
+ } };
1629
+ }
1630
+ const input = remove ? deleteAudience.parse(op.payload) : members ? audienceUsers.parse(op.payload) : op.tool === "x_update_custom_audience" ? updateAudience.parse(op.payload) : void 0;
1631
+ if (!input) throw new AdportError10("INVALID_INPUT", "x: unsupported audience mutation");
1632
+ const current = (await this.get({ account_id: account, custom_audience_id: input.custom_audience_id })).audience;
1633
+ this.owned(current, account);
1634
+ if (current.configuration_hash !== input.expected_configuration_hash) throw new AdportError10("INVALID_INPUT", "x: audience configuration changed; read and preview it again");
1635
+ const path = `${base}/${current.id}`;
1636
+ if ("operations" in input) {
1637
+ if (current.audience_type !== "CRM") throw new AdportError10("INVALID_INPUT", "x: native member updates require an owned CRM audience");
1638
+ for (const value of input.operations) if (value.params.expires_at && Date.parse(value.params.expires_at) <= (value.params.effective_at ? Date.parse(value.params.effective_at) : Date.now())) throw new AdportError10("INVALID_INPUT", "x: member expiry must follow its effective time");
1639
+ const count = input.operations.reduce((sum, value) => sum + value.params.users.length, 0), batchHash = digest(input.operations);
1640
+ const descriptions = input.operations.map((value) => `${value.params.users.length} user ${value.params.users.length === 1 ? "record" : "records"}${value.params.effective_at ? `; effective ${value.params.effective_at}` : ""}${value.params.expires_at ? `; expiry ${value.params.expires_at}` : ""}`), changes = input.operations.map((value, index) => `${value.operation_type}: ${descriptions[index]}`);
1641
+ const uploadNotes = [...notes, "Existing ads that use this audience can be affected. Native processing acceptance does not confirm audience readiness or exact membership. Native processing generally takes 6\u20138 hours."];
1642
+ return {
1643
+ summary: `Submit member changes for X audience "${current.name}"`,
1644
+ changes: [...changes, `SHA256 ${batchHash}`],
1645
+ notes: uploadNotes,
1646
+ coercions: [],
1647
+ budgetDeltas: [],
1648
+ review: { provider: "x", accountId: account, kind: op.kind, title: "Submit audience members", subject: current.name, fields: [...input.operations.map((value, index) => ({ label: value.operation_type, after: descriptions[index] })), { label: "Batch SHA256", after: batchHash }], notices: uploadNotes },
1649
+ execute: async () => {
1650
+ try {
1651
+ const receipt = await this.entities.client.request("POST", `${path}/users`, z17.object({ data: z17.object({ success_count: z17.number().int().nonnegative().safe(), total_count: z17.number().int().nonnegative().safe() }) }), {}, input.operations);
1652
+ if (receipt.data.success_count !== count || receipt.data.total_count !== count) throw new Error("Counts differ");
1653
+ return { applied: true, resourceIds: [current.id], details: { outcome: "ACCEPTED_FOR_PROCESSING", accepted_records: count, batch_sha256: batchHash, readiness_confirmed: false }, warnings: ["Native audience processing and targeting readiness remain unconfirmed."] };
1654
+ } catch (error) {
1655
+ if (rejection(error)) throw error;
1656
+ throw new AdportError10("PROVIDER_ERROR", "x: audience member submission outcome unconfirmed; do not replay the batch automatically", { resource_ids: [current.id], batch_sha256: batchHash, expected_records: count });
1657
+ }
1658
+ }
1659
+ };
1660
+ }
1661
+ if ("expected_usage_hash" in input) {
1662
+ const usage = await this.usage(account, current.id);
1663
+ if (usage.audience.configuration_hash !== input.expected_configuration_hash) throw new AdportError10("INVALID_INPUT", "x: audience configuration changed during deletion preflight");
1664
+ if (usage.usage_hash !== input.expected_usage_hash) throw new AdportError10("INVALID_INPUT", "x: audience usage changed; inspect it before another preview");
1665
+ if (usage.references.length || usage.criteria.length || usage.permissions.length) throw new AdportError10("INVALID_INPUT", "x: remove audience targeting, exclusions and sharing permissions before deletion");
1666
+ }
1667
+ const params = remove ? {} : Object.fromEntries(Object.entries(input).filter(([key, value]) => ["name", "description"].includes(key) && value !== void 0));
1668
+ const expected = { ...configuration(current), ...params, ...remove ? { deleted: true } : {} };
1669
+ return {
1670
+ summary: `${remove ? "Delete" : "Update"} X audience "${current.name}"`,
1671
+ changes: [remove ? `- Audience ${current.id}` : `~ Metadata ${JSON.stringify(params)}`],
1672
+ notes,
1673
+ coercions: [],
1674
+ budgetDeltas: [],
1675
+ ...!remove ? { review: { provider: "x", accountId: account, kind: op.kind, title: "Update audience", subject: current.name, fields: Object.entries(params).map(([key, value]) => ({ label: key === "name" ? "Name" : "Description", before: key === "name" ? current.name : current.description, after: value })), notices: notes } } : {},
1676
+ execute: async () => {
1677
+ let accepted = false;
1678
+ try {
1679
+ const receipt = await this.entities.client.request(remove ? "DELETE" : "PUT", path, z17.object({ data: z17.looseObject({ id: xId }) }), params);
1680
+ accepted = true;
1681
+ if (receipt.data.id !== current.id) throw new Error("ID differs");
1682
+ const actual = (await this.get({ account_id: account, custom_audience_id: current.id, with_deleted: remove })).audience;
1683
+ if (canonical2(configuration(actual)) !== canonical2(expected)) throw new Error("Metadata differs");
1684
+ return { applied: true, resourceIds: [current.id] };
1685
+ } catch (error) {
1686
+ if (!accepted && rejection(error)) throw error;
1687
+ throw new AdportError10("PROVIDER_ERROR", `x: audience ${remove ? "deletion" : "update"} outcome unconfirmed; reconcile this ID before another mutation`, { resource_ids: [current.id] });
1688
+ }
1689
+ }
1690
+ };
1691
+ }
1692
+ };
1693
+
1694
+ // src/measurement.ts
1695
+ import { createHash as createHash3 } from "crypto";
1696
+ import { AdportError as AdportError11 } from "@adport/core";
1697
+ import { z as z19 } from "zod";
1698
+
1699
+ // src/measurement-tools.ts
1700
+ import { defineTool as defineTool6, guardedWriteTool as guardedWriteTool6 } from "@adport/core";
1701
+ import { z as z18 } from "zod";
1702
+ var ids2 = z18.array(xId).min(1).max(200).refine((value) => new Set(value).size === value.length, "Use unique IDs");
1703
+ var page2 = { account_id: xId, count: z18.number().int().min(1).max(1e3).default(200), cursor: z18.string().min(1).max(4096).optional(), with_deleted: z18.boolean().default(false), with_total_count: z18.boolean().default(false).describe("Request a total on the initial page; native cursor requests omit this flag") };
1704
+ var webTags = z18.object({ account_id: xId, count: page2.count, cursor: page2.cursor, with_deleted: page2.with_deleted }).strict();
1705
+ var appTags = z18.object({ ...page2, app_event_tag_ids: ids2.optional() }).strict();
1706
+ var trackingTags = z18.object({ ...page2, tracking_tag_ids: ids2.optional(), line_item_ids: ids2.optional() }).strict();
1707
+ var webTag = z18.object({ account_id: xId, web_event_tag_id: xId, with_deleted: page2.with_deleted }).strict();
1708
+ var appTag = z18.object({ account_id: xId, app_event_tag_id: xId, with_deleted: page2.with_deleted }).strict();
1709
+ var trackingTag = z18.object({ account_id: xId, tracking_tag_id: xId, with_deleted: page2.with_deleted }).strict();
1710
+ var hash3 = z18.string().regex(/^[a-f0-9]{64}$/);
1711
+ var url = z18.url({ protocol: /^https$/ }).max(8192).refine((value) => {
1712
+ const parsed = new URL(value);
1713
+ return !parsed.username && !parsed.password && !parsed.hash;
1714
+ }, "Use an HTTPS tracking URL without credentials or a fragment");
1715
+ var createTrackingTag = z18.object({ line_item_id: xId, tracking_tag_type: z18.enum(["IMPRESSION_TAG", "CLICK_TRACKER"]), tracking_tag_url: url }).strict();
1716
+ var updateTrackingTag = z18.object({ tracking_tag_id: xId, expected_configuration_hash: hash3, tracking_tag_url: url }).strict();
1717
+ var deleteTrackingTag = z18.object({ tracking_tag_id: xId, expected_configuration_hash: hash3 }).strict();
1718
+ var conversionStats = z18.object({
1719
+ account_id: xId,
1720
+ entity: z18.enum(["CAMPAIGN", "LINE_ITEM", "PROMOTED_TWEET"]),
1721
+ entity_ids: z18.array(xId).min(1).max(20).refine((value) => new Set(value).size === value.length, "Use unique entity IDs"),
1722
+ start_date: z18.iso.date(),
1723
+ end_date: z18.iso.date(),
1724
+ placement: z18.enum(X_PLACEMENTS),
1725
+ metric_group: z18.enum(["WEB_CONVERSION", "MOBILE_CONVERSION"])
1726
+ }).strict().refine((value) => value.end_date >= value.start_date && Date.parse(value.end_date) - Date.parse(value.start_date) < 30 * 864e5, "Choose an inclusive range of at most 30 days");
1727
+ function xMeasurementTools(provider) {
1728
+ const read = { namespace: "x", presentation: "records", output: z18.looseObject({ records: z18.array(z18.record(z18.string(), z18.unknown())) }), annotations: { readOnly: true } };
1729
+ const write = { namespace: "x", provider: "x" };
1730
+ return [
1731
+ defineTool6({ ...read, name: "x_web_event_tags", description: "Inspect native account-scoped website conversion tags and embed code as inert data. Native cursors preserve pagination. This does not create events or install a pixel.", input: webTags, pagination: { cursorInput: "cursor" }, handler: (input) => provider.measurement.listWeb(input) }),
1732
+ defineTool6({ ...read, name: "x_get_web_event_tag", description: "Read one website conversion tag by exact account and ID, without executing embed code or sending an event.", input: webTag, handler: (input) => provider.measurement.getWeb(input) }),
1733
+ defineTool6({ ...read, name: "x_app_event_tags", description: "Inspect native app event tags, app identity, conversion type and attribution windows with exact ID filters and cursor pagination. Sends no app events.", input: appTags, pagination: { cursorInput: "cursor" }, handler: (input) => provider.measurement.listApp(input) }),
1734
+ defineTool6({ ...read, name: "x_get_app_event_tag", description: "Read one native app event tag and attribution windows in the selected account. Sends no events.", input: appTag, handler: (input) => provider.measurement.getApp(input) }),
1735
+ defineTool6({ ...read, name: "x_tracking_tags", description: "Inspect native impression/click tracking tags with account/line-item ownership checks, configuration hashes and native cursor/ID filters.", input: trackingTags, pagination: { cursorInput: "cursor" }, handler: (input) => provider.measurement.listTracking(input) }),
1736
+ defineTool6({ ...read, name: "x_get_tracking_tag", description: "Read one impression/click tracking tag and its configuration_hash after checking its line item and campaign in the selected account.", input: trackingTag, handler: (input) => provider.measurement.getTracking(input) }),
1737
+ guardedWriteTool6({ ...write, name: "x_create_tracking_tag", kind: "create", destructive: false, description: "Associate an HTTPS impression or click tracker with an existing non-draft line item. May immediately change measurement on an active ad group. Verifies native receipt/readback; sends no test event and never retries automatically.", payload: createTrackingTag }),
1738
+ guardedWriteTool6({ ...write, name: "x_update_tracking_tag", kind: "update", destructive: false, description: "Change only a tracking-tag URL using a current configuration_hash. Preserves its parent/type and independently reads back the result. May affect active measurement immediately; no automatic retry.", payload: updateTrackingTag }),
1739
+ guardedWriteTool6({ ...write, name: "x_delete_tracking_tag", kind: "remove", destructive: true, description: "Disassociate a tracking tag using a current configuration_hash. Verifies native deleted=true and independent readback. Can stop third-party measurement; does not pause ads or claim a restore endpoint.", payload: deleteTrackingTag }),
1740
+ defineTool6({ ...read, name: "x_conversion_stats", description: "Read native WEB_CONVERSION or separately requested MOBILE_CONVERSION objects for up to 20 verified entities and 30 account-local dates. Placement is explicit. Preserves native fields/units; does not label them normalized conversions, revenue, CPA or ROAS.", input: conversionStats, handler: (input) => provider.measurement.conversions(input) })
1741
+ ];
1742
+ }
1743
+
1744
+ // src/measurement.ts
1745
+ var web = z19.looseObject({ id: xId, name: z19.string(), type: z19.string(), deleted: z19.boolean() });
1746
+ var app = z19.looseObject({ id: xId, app_store_identifier: z19.string(), os_type: z19.string(), conversion_type: z19.string(), post_view_attribution_window: z19.number().int().nonnegative(), post_engagement_attribution_window: z19.number().int().nonnegative(), deleted: z19.boolean() });
1747
+ var tracking = z19.looseObject({ id: xId, line_item_id: xId, tracking_tag_type: z19.string(), tracking_tag_url: z19.string(), deleted: z19.boolean() });
1748
+ var request = z19.object({ params: z19.record(z19.string(), z19.unknown()).optional() }).optional();
1749
+ var canonical3 = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
1750
+ var configuration2 = (value) => Object.fromEntries(Object.entries(value).filter(([key]) => !["created_at", "updated_at", "configuration_hash"].includes(key)));
1751
+ var snapshot2 = (account, value) => createHash3("sha256").update(canonical3({ account_id: account, configuration: configuration2(value) })).digest("hex");
1752
+ var webSnapshot = (account, value) => createHash3("sha256").update(canonical3({ account_id: account, configuration: Object.fromEntries(["id", "name", "type", "retargeting_enabled", "click_window", "view_through_window", "deleted"].filter((key) => value[key] !== void 0).map((key) => [key, value[key]])) })).digest("hex");
1753
+ var day = 864e5;
1754
+ var notes2 = ["Local preview only; X has no server dry run or conditional update for this workflow.", "Measurement on active ads may change immediately. No events are sent by this tool, no ads are activated and no budget or bid is changed.", "No automatic write retry. Reconcile known IDs after an uncertain result."];
1755
+ var rejection2 = (error) => error instanceof AdportError11 && error.details !== null && typeof error.details === "object" && "http_status" in error.details && [401, 403, 429].includes(Number(error.details.http_status));
1756
+ var XMeasurementService = class {
1757
+ constructor(entities, analytics) {
1758
+ this.entities = entities;
1759
+ this.analytics = analytics;
1760
+ }
1761
+ entities;
1762
+ analytics;
1763
+ base(account, kind) {
1764
+ return `accounts/${xId.parse(account)}/${kind}`;
1765
+ }
1766
+ scope(value, account, kind, resource) {
1767
+ const params = value.request?.params;
1768
+ if (params && (params.account_id !== void 0 && params.account_id !== account || resource && params[`${kind.slice(0, -1)}_id`] !== void 0 && params[`${kind.slice(0, -1)}_id`] !== resource)) throw new AdportError11("PROVIDER_ERROR", "x: measurement response scope differs from the selected account/ID");
1769
+ }
1770
+ rowScope(value, account) {
1771
+ if (value.account_id !== void 0 && value.account_id !== account) throw new AdportError11("PROVIDER_ERROR", "x: measurement resource belongs to a different account");
1772
+ }
1773
+ async page(account, kind, schema, params, filters, lineIds) {
1774
+ await this.entities.getAccount(account);
1775
+ const result = await this.entities.client.request("GET", this.base(account, kind), z19.looseObject({ data: z19.array(schema).max(5e3), next_cursor: z19.string().min(1).max(4096).nullable().optional(), total_count: z19.number().int().nonnegative().safe().optional(), request }), params);
1776
+ this.scope(result, account, kind);
1777
+ if (result.next_cursor && result.next_cursor === params.cursor || new Set(result.data.map((value) => value.id)).size !== result.data.length) throw new AdportError11("PROVIDER_ERROR", "x: measurement page repeats a cursor or resource ID");
1778
+ for (const value of result.data) {
1779
+ this.rowScope(value, account);
1780
+ if (filters && !filters.includes(value.id) || !params.with_deleted && value.deleted || lineIds && !lineIds.includes(String(value.line_item_id))) throw new AdportError11("PROVIDER_ERROR", "x: measurement page differs from requested filters");
1781
+ }
1782
+ return { ...result, complete: result.next_cursor === null ? true : result.next_cursor === void 0 ? null : false, ...result.data.length > Number(params.count) ? { warnings: ["X returned more records than requested; the complete native page is retained."] } : {} };
1783
+ }
1784
+ async get(account, kind, resource, schema, withDeleted) {
1785
+ await this.entities.getAccount(account);
1786
+ const result = await this.entities.client.request("GET", `${this.base(account, kind)}/${xId.parse(resource)}`, z19.looseObject({ data: z19.unknown(), request }), { with_deleted: withDeleted });
1787
+ const parsed = schema.safeParse(result.data);
1788
+ if (!parsed.success) throw new AdportError11("PROVIDER_ERROR", "x: unexpected measurement resource schema");
1789
+ this.scope(result, account, kind, resource);
1790
+ this.rowScope(parsed.data, account);
1791
+ if (parsed.data.id !== resource || !withDeleted && parsed.data.deleted) throw new AdportError11("PROVIDER_ERROR", "x: measurement resource ID/deletion state differs from the request");
1792
+ return { ...result, data: parsed.data };
1793
+ }
1794
+ async listWeb(value) {
1795
+ const { account_id, ...params } = webTags.parse(value), result = await this.page(account_id, "web_event_tags", web, params);
1796
+ const data = result.data.map((value2) => ({ ...value2, configuration_hash: webSnapshot(account_id, value2) }));
1797
+ return { ...result, data, records: data.map((value2) => ({ id: value2.id, name: value2.name, type: value2.type, status: value2.deleted ? "Deleted" : value2.status ?? "Not reported", ...value2.click_window !== void 0 ? { click_window_days: value2.click_window } : {}, ...value2.view_through_window !== void 0 ? { view_through_window_days: value2.view_through_window } : {} })) };
1798
+ }
1799
+ async getWeb(value) {
1800
+ const input = webTag.parse(value), result = await this.get(input.account_id, "web_event_tags", input.web_event_tag_id, web, input.with_deleted);
1801
+ const data = { ...result.data, configuration_hash: webSnapshot(input.account_id, result.data) };
1802
+ return { ...result, data, records: [data], notes: ["Embed code is returned as inert data. This read does not install a pixel or send an event."] };
1803
+ }
1804
+ async listApp(value) {
1805
+ const { account_id, app_event_tag_ids, ...input } = appTags.parse(value), params = this.pageParams(input, { app_event_tag_ids });
1806
+ const result = await this.page(account_id, "app_event_tags", app, params, app_event_tag_ids);
1807
+ return { ...result, records: result.data.map((value2) => ({ id: value2.id, name: `${value2.conversion_type} \xB7 ${value2.app_store_identifier}`, status: value2.deleted ? "Deleted" : value2.status ?? "Not reported", os_type: value2.os_type, post_view_window_days: value2.post_view_attribution_window, post_engagement_window_days: value2.post_engagement_attribution_window })) };
1808
+ }
1809
+ async getApp(value) {
1810
+ const input = appTag.parse(value), result = await this.get(input.account_id, "app_event_tags", input.app_event_tag_id, app, input.with_deleted);
1811
+ return { ...result, records: [result.data] };
1812
+ }
1813
+ pageParams(value, filters) {
1814
+ const { with_total_count, ...params } = value;
1815
+ return { ...params, ...!params.cursor && with_total_count ? { with_total_count: true } : {}, ...Object.fromEntries(Object.entries(filters).filter(([, value2]) => value2 !== void 0).map(([key, value2]) => [key, value2.join(",")])) };
1816
+ }
1817
+ async listTracking(value) {
1818
+ const { account_id, tracking_tag_ids, line_item_ids, ...input } = trackingTags.parse(value), params = this.pageParams(input, { tracking_tag_ids, line_item_ids });
1819
+ const result = await this.page(account_id, "tracking_tags", tracking, params, tracking_tag_ids, line_item_ids);
1820
+ if (result.data.length) {
1821
+ const lineIds = [...new Set(result.data.map((value2) => value2.line_item_id))];
1822
+ const lines = new Map((await this.selectedParents(account_id, "line_items", "line_item_ids", lineItemSchema, lineIds)).map((value2) => [value2.id, value2]));
1823
+ const campaignIds = [...new Set([...lines.values()].map((value2) => value2.campaign_id))];
1824
+ const campaigns = new Map((await this.selectedParents(account_id, "campaigns", "campaign_ids", campaignSchema, campaignIds)).map((value2) => [value2.id, value2]));
1825
+ for (const tag of result.data) {
1826
+ const line = lines.get(tag.line_item_id), campaign = line && campaigns.get(line.campaign_id);
1827
+ if (!line || !campaign || campaign.currency !== line.currency) throw new AdportError11("PROVIDER_ERROR", "x: tracking-tag parent hierarchy is not verified in the selected account");
1828
+ }
1829
+ }
1830
+ const data = result.data.map((value2) => ({ ...value2, configuration_hash: snapshot2(account_id, value2) }));
1831
+ return { ...result, data, records: data.map((value2) => this.trackingRecord(value2)) };
1832
+ }
1833
+ async selectedParents(account, kind, filter, schema, ids3) {
1834
+ const rows2 = [];
1835
+ for (let offset = 0; offset < ids3.length; offset += 200) {
1836
+ const selected = ids3.slice(offset, offset + 200), result = await this.entities.client.request("GET", this.base(account, kind), z19.looseObject({ data: z19.array(schema).max(1e3), request }), { [filter]: selected.join(","), count: 1e3, with_deleted: true, with_draft: true });
1837
+ this.scope(result, account, kind);
1838
+ if (new Set(result.data.map((value) => value.id)).size !== result.data.length || result.data.some((value) => !selected.includes(value.id)) || selected.some((value) => !result.data.some((row) => row.id === value))) throw new AdportError11("PROVIDER_ERROR", "x: tracking-tag parent hierarchy is incomplete or differs from requested IDs");
1839
+ rows2.push(...result.data);
1840
+ }
1841
+ return rows2;
1842
+ }
1843
+ async getTracking(value) {
1844
+ const input = trackingTag.parse(value), result = await this.get(input.account_id, "tracking_tags", input.tracking_tag_id, tracking, input.with_deleted);
1845
+ await this.entities.getLineItem(input.account_id, result.data.line_item_id);
1846
+ const tag = { ...result.data, configuration_hash: snapshot2(input.account_id, result.data) };
1847
+ return { ...result, data: tag, records: [this.trackingRecord(tag)] };
1848
+ }
1849
+ trackingRecord(value) {
1850
+ return { id: value.id, name: value.tracking_tag_type === "IMPRESSION_TAG" ? "Impression tracker" : value.tracking_tag_type === "CLICK_TRACKER" ? "Click tracker" : value.tracking_tag_type, status: value.deleted ? "Deleted" : "Associated", line_item_id: value.line_item_id, tracking_url: value.tracking_tag_url };
1851
+ }
1852
+ async plan(op) {
1853
+ const create = op.tool === "x_create_tracking_tag", remove = op.tool === "x_delete_tracking_tag";
1854
+ if (op.provider !== "x" || op.kind !== (create ? "create" : remove ? "remove" : "update")) throw new AdportError11("INVALID_INPUT", "x: tracking-tag provider/operation kind mismatch");
1855
+ const account = xId.parse(op.accountId);
1856
+ await this.entities.getAccount(account);
1857
+ const input = create ? createTrackingTag.parse(op.payload) : remove ? deleteTrackingTag.parse(op.payload) : op.tool === "x_update_tracking_tag" ? updateTrackingTag.parse(op.payload) : void 0;
1858
+ if (!input) throw new AdportError11("INVALID_INPUT", "x: unsupported measurement mutation");
1859
+ const current = "tracking_tag_id" in input ? (await this.getTracking({ account_id: account, tracking_tag_id: input.tracking_tag_id })).data : void 0;
1860
+ if (current && ("expected_configuration_hash" in input && current.configuration_hash !== input.expected_configuration_hash || current.deleted)) throw new AdportError11("INVALID_INPUT", "x: tracking-tag configuration changed; read and preview it again");
1861
+ const line = await this.entities.getLineItem(account, "line_item_id" in input ? input.line_item_id : current.line_item_id), campaign = await this.entities.getCampaign(account, line.campaign_id);
1862
+ if (line.deleted || campaign.deleted || line.entity_status === "DRAFT" || campaign.entity_status === "DRAFT") throw new AdportError11("INVALID_INPUT", "x: tracking-tag writes require a non-deleted, non-draft line item and campaign");
1863
+ const params = create ? { line_item_id: line.id, tracking_tag_type: input.tracking_tag_type, tracking_tag_url: input.tracking_tag_url } : "tracking_tag_url" in input ? { tracking_tag_url: input.tracking_tag_url } : {};
1864
+ const title = `${create ? "Associate" : remove ? "Remove" : "Update"} ${create ? params.tracking_tag_type === "IMPRESSION_TAG" ? "impression" : "click" : current.tracking_tag_type === "IMPRESSION_TAG" ? "impression" : "click"} tracker`;
1865
+ const fields = [{ label: "Ad group", after: line.name ?? line.id }, { label: "Tracking URL", ...current ? { before: current.tracking_tag_url } : {}, after: remove ? null : params.tracking_tag_url }];
1866
+ return { summary: `${title} \xB7 ${line.name ?? line.id}`, changes: [`${remove ? "-" : create ? "+" : "~"} ${JSON.stringify(params)}${current ? ` \xB7 tag ${current.id}` : ""}`], notes: notes2, coercions: [], budgetDeltas: [], review: { provider: "x", accountId: account, kind: op.kind, title, subject: line.name ?? line.id, fields, notices: notes2 }, execute: async () => {
1867
+ let resource = current?.id, accepted = false;
1868
+ try {
1869
+ const receipt = await this.entities.client.request(create ? "POST" : remove ? "DELETE" : "PUT", `${this.base(account, "tracking_tags")}${current ? `/${current.id}` : ""}`, z19.looseObject({ data: z19.looseObject({ id: xId }), request }), params);
1870
+ accepted = true;
1871
+ const expectedId = resource;
1872
+ resource = receipt.data.id;
1873
+ if (expectedId && resource !== expectedId) throw new Error("ID differs");
1874
+ this.scope(receipt, account, "tracking_tags", resource);
1875
+ const actual = (await this.getTracking({ account_id: account, tracking_tag_id: resource, with_deleted: remove })).data;
1876
+ const expected = create ? { ...params, id: resource, deleted: false } : { ...configuration2(current), ...params, deleted: remove };
1877
+ if (Object.entries(expected).some(([key, value]) => canonical3(actual[key]) !== canonical3(value))) throw new Error("Configuration differs");
1878
+ return { applied: true, resourceIds: [resource] };
1879
+ } catch (error) {
1880
+ if (!accepted && rejection2(error)) throw error;
1881
+ const details = error instanceof AdportError11 && error.details && typeof error.details === "object" ? error.details : {};
1882
+ const ids3 = [...new Set([current?.id, resource, ...Array.isArray(details.resource_ids) ? details.resource_ids.filter((value) => typeof value === "string" && xId.safeParse(value).success) : []].filter((value) => !!value))];
1883
+ throw new AdportError11("PROVIDER_ERROR", "x: tracking-tag mutation outcome unconfirmed; inspect the selected account before another write; do not replay automatically", { resource_ids: ids3 });
1884
+ }
1885
+ } };
1886
+ }
1887
+ async conversions(value) {
1888
+ const input = conversionStats.parse(value), account = await this.entities.getAccount(input.account_id);
1889
+ const start = xAccountMidnight(input.start_date, account.timezone), endDate = new Date(Date.parse(`${input.end_date}T00:00:00Z`) + day).toISOString().slice(0, 10), end = xAccountMidnight(endDate, account.timezone);
1890
+ if (account.timezone_switch_at && (!Number.isFinite(Date.parse(account.timezone_switch_at)) || start < Date.parse(account.timezone_switch_at))) throw new AdportError11("INVALID_INPUT", "x: requested dates predate the account timezone switch; previous reporting timezone is unknown");
1891
+ for (const resource of input.entity_ids) {
1892
+ if (input.entity === "CAMPAIGN") await this.entities.getCampaign(input.account_id, resource);
1893
+ else if (input.entity === "LINE_ITEM") await this.entities.getLineItem(input.account_id, resource);
1894
+ else {
1895
+ const { data: data2 } = await this.entities.client.request("GET", `accounts/${input.account_id}/promoted_tweets/${resource}`, z19.object({ data: promotedTweetSchema }));
1896
+ if (data2.id !== resource) throw new AdportError11("PROVIDER_ERROR", "x: conversion entity ID mismatch");
1897
+ await this.entities.getLineItem(input.account_id, data2.line_item_id);
1898
+ }
1899
+ }
1900
+ const asynchronous = end - start > 7 * day || end < Date.now() - 7 * day;
1901
+ const result = await this.analytics.totals(input.account_id, { entity: input.entity, entity_ids: input.entity_ids.join(","), start_time: new Date(start).toISOString(), end_time: new Date(end).toISOString(), granularity: "TOTAL", placement: input.placement, metric_groups: input.metric_group }, asynchronous);
1902
+ const prefix = input.metric_group === "WEB_CONVERSION" ? "conversion_" : "mobile_conversion_";
1903
+ const data = result.data.map((row) => ({ ...row, id_data: row.id_data.map((value2) => ({ ...value2, metrics: Object.fromEntries(Object.entries(value2.metrics).filter(([key]) => key.startsWith(prefix))) })) }));
1904
+ return { ...result, data, records: data.map((value2) => ({ id: value2.id, name: `${input.entity} ${value2.id}`, metric_group: input.metric_group, placement: input.placement, native_metrics: value2.id_data[0].metrics })), normalized: false, placement: input.placement, metric_group: input.metric_group, notes: ["Native conversion objects are preserved without summing event types, attribution buckets or order quantities. Sale-amount currency/units are not normalized to revenue, CPA or ROAS.", "This report covers only the selected placement and provider attribution settings. It does not send events or change tracking configuration."] };
1905
+ }
1906
+ };
1907
+
1908
+ // src/posts.ts
1909
+ import { createHash as createHash4 } from "crypto";
1910
+ import { AdportError as AdportError12 } from "@adport/core";
1911
+ import { z as z21 } from "zod";
1912
+
1913
+ // src/post-schemas.ts
1914
+ import { z as z20 } from "zod";
1915
+ var unique = (values2) => new Set(values2).size === values2.length;
1916
+ var postHash = z20.string().regex(/^[a-f0-9]{64}$/);
1917
+ var postFields = z20.object({
1918
+ as_user_id: snowflake,
1919
+ text: z20.string().max(1e4).optional().describe("X validates native weighted length/content at apply."),
1920
+ name: z20.string().min(1).max(80).optional(),
1921
+ media_keys: z20.array(mediaKey).min(1).max(4).refine(unique, "Use unique media keys").optional(),
1922
+ card_uri: cardUri.optional(),
1923
+ conversation_settings: z20.enum(["EVERYONE", "FOLLOWING", "MENTIONED_USERS"]).default("EVERYONE"),
1924
+ video_cta: z20.enum(["VISIT_SITE", "WATCH_NOW"]).optional(),
1925
+ video_cta_value: z20.url().refine((value) => {
1926
+ const url3 = new URL(value);
1927
+ return ["http:", "https:"].includes(url3.protocol) && !url3.username && !url3.password;
1928
+ }, "Use an HTTP(S) URL without credentials").optional(),
1929
+ video_title: z20.string().max(70).optional(),
1930
+ video_description: z20.string().max(200).optional()
1931
+ }).strict().refine((value) => Boolean(value.text?.trim() || value.media_keys?.length), "Provide text or media").refine((value) => value.video_cta !== void 0 === (value.video_cta_value !== void 0), "Provide video_cta and video_cta_value together");
1932
+ var createPost = postFields.safeExtend({ expected_context_hash: postHash, confirm_publication: z20.literal(true) });
1933
+ var renamePost = z20.object({ user_id: snowflake, tweet_id: snowflake, expected_snapshot_hash: postHash, name: z20.string().min(1).max(80) }).strict();
1934
+ var postList = z20.object({ account_id: xId, user_id: snowflake, timeline_type: z20.enum(["NULLCAST", "ORGANIC", "ALL"]).default("NULLCAST"), include_mentions_and_replies: z20.boolean().default(false), name: z20.string().min(1).max(80).optional(), count: z20.number().int().min(1).max(200).default(20), cursor: z20.string().min(1).max(4096).optional() }).strict();
1935
+ var postReference = z20.object({ account_id: xId, user_id: snowflake, tweet_id: snowflake }).strict();
1936
+ var promotionSelection = z20.object({ line_item_id: xId, user_id: snowflake, tweet_ids: z20.array(snowflake).min(1).max(50).refine(unique, "Use unique post IDs") }).strict();
1937
+ var createPromotions = promotionSelection.safeExtend({ expected_context_hash: postHash, acknowledge_active_associations: z20.literal(true) });
1938
+ var createRepostPromotions = promotionSelection.safeExtend({ expected_context_hash: postHash, acknowledge_active_associations: z20.literal(true), acknowledge_new_published_copies: z20.literal(true) });
1939
+ var deletePromotion = z20.object({ promoted_tweet_id: xId, expected_context_hash: postHash }).strict();
1940
+ var promotionList = z20.object({ account_id: xId, line_item_id: xId, user_id: snowflake.optional(), count: z20.number().int().min(1).max(200).default(20), cursor: z20.string().min(1).max(4096).optional(), with_deleted: z20.boolean().default(false) }).strict();
1941
+ var urlEntity = z20.object({ url: z20.string(), expanded_url: z20.string().optional(), display_url: z20.string().optional(), indices: z20.array(z20.number().int().nonnegative()).length(2).optional() });
1942
+ var mediaEntity = z20.object({ id_str: snowflake, type: z20.string(), media_key: mediaKey.optional(), media_url_https: z20.string().optional(), url: z20.string().optional(), expanded_url: z20.string().optional(), video_info: z20.object({ variants: z20.array(z20.object({ content_type: z20.string(), url: z20.string(), bitrate: z20.number().nonnegative().optional() })).max(100) }).optional() });
1943
+ var nativePost = z20.object({
1944
+ id_str: snowflake,
1945
+ user: z20.object({ id_str: snowflake }),
1946
+ name: z20.string().nullable(),
1947
+ full_text: z20.string(),
1948
+ nullcast: z20.boolean(),
1949
+ tweet_type: z20.literal("PUBLISHED"),
1950
+ conversation_settings: z20.string().optional(),
1951
+ truncated: z20.boolean().optional(),
1952
+ entities: z20.object({ urls: z20.array(urlEntity).max(1e3).optional(), media: z20.array(mediaEntity).max(100).optional() }).optional(),
1953
+ extended_entities: z20.object({ media: z20.array(mediaEntity).max(100) }).optional()
1954
+ });
1955
+ var postWrites = /* @__PURE__ */ new Set(["x_create_promoted_only_post", "x_rename_published_post", "x_create_promoted_posts", "x_create_repost_promotions", "x_delete_promoted_post"]);
1956
+
1957
+ // src/posts.ts
1958
+ var nativePromotion = promotedTweetSchema.extend({ account_id: xId.optional(), approval_status: z21.string().optional() });
1959
+ var pageSchema = (item) => z21.object({ data: z21.array(item).max(1e3), next_cursor: z21.string().nullable().optional() });
1960
+ var canonical4 = (value) => Array.isArray(value) ? value.map(canonical4) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical4(item)])) : value;
1961
+ var hash4 = (value) => createHash4("sha256").update(JSON.stringify(canonical4(value))).digest("hex");
1962
+ var equal2 = (a, b) => hash4(a) === hash4(b);
1963
+ var sourceConfig = (value) => Object.fromEntries(Object.entries(value).filter(([key]) => !["created_at", "updated_at", "media_url", "poster_media_url"].includes(key)));
1964
+ var postContent = (post) => ({ ...post });
1965
+ var postSnapshot = (account, post) => hash4({ account_id: account, post: postContent(post) });
1966
+ var safeUrl2 = (value, cdn = false) => {
1967
+ if (typeof value !== "string") return void 0;
1968
+ try {
1969
+ const url3 = new URL(value);
1970
+ return url3.protocol === "https:" && !url3.username && !url3.password && (!url3.port || url3.port === "443") && (!cdn || ["pbs.twimg.com", "video.twimg.com", "ton.twimg.com"].includes(url3.hostname)) ? value : void 0;
1971
+ } catch {
1972
+ return void 0;
1973
+ }
1974
+ };
1975
+ var notice = "Native previews are local plans, not X validation. No write is retried automatically. Published posts, ad associations and actual delivery are separate states.";
1976
+ var XPostService = class {
1977
+ constructor(entities, creatives) {
1978
+ this.entities = entities;
1979
+ this.creatives = creatives;
1980
+ }
1981
+ entities;
1982
+ creatives;
1983
+ base(account) {
1984
+ return `accounts/${xId.parse(account)}`;
1985
+ }
1986
+ async author(account, user2, full = false) {
1987
+ const matches2 = (await this.creatives.users(account)).filter((row) => row.user_id === user2 && !row.deleted);
1988
+ if (matches2.length !== 1 || !["FULL", "RETWEETS_ONLY"].includes(matches2[0].promotable_user_type) || full && matches2[0].promotable_user_type !== "FULL") throw new AdportError12("INVALID_INPUT", full ? "x: this workflow requires a current FULL promotable author; RETWEETS_ONLY creates a different native post and needs its own receipt workflow" : "x: post author is not an unambiguous current promotable user in this account");
1989
+ return matches2[0];
1990
+ }
1991
+ paging(ids3, next, previous) {
1992
+ if (new Set(ids3).size !== ids3.length || next && next === previous) throw new AdportError12("PROVIDER_ERROR", "x: post pagination repeated an ID or cursor");
1993
+ return { truncated: next !== null, ...next ? { next_cursor: next } : {}, ...next === void 0 ? { notes: ["Native continuation marker is missing; completeness is unconfirmed."] } : {} };
1994
+ }
1995
+ async postPage(account, user2, params) {
1996
+ const result = await this.entities.client.request("GET", `${this.base(account)}/tweets`, pageSchema(nativePost), { tweet_type: "PUBLISHED", user_id: user2, trim_user: true, ...Object.fromEntries(Object.entries(params).filter(([, value]) => value !== void 0)) });
1997
+ if (result.data.some((post) => post.user.id_str !== user2)) throw new AdportError12("PROVIDER_ERROR", "x: published post author filter mismatch");
1998
+ this.paging(result.data.map((post) => post.id_str), result.next_cursor, typeof params.cursor === "string" ? params.cursor : void 0);
1999
+ return result;
2000
+ }
2001
+ async exactPosts(account, user2, ids3) {
2002
+ await this.author(account, user2);
2003
+ const found = /* @__PURE__ */ new Map(), cursors = /* @__PURE__ */ new Set();
2004
+ let cursor2;
2005
+ for (let page5 = 0; page5 < 10; page5++) {
2006
+ const result = await this.postPage(account, user2, { tweet_ids: ids3.join(","), timeline_type: "ALL", include_mentions_and_replies: true, count: 200, ...cursor2 ? { cursor: cursor2 } : {} });
2007
+ for (const post of result.data) {
2008
+ if (!ids3.includes(post.id_str) || found.has(post.id_str)) throw new AdportError12("PROVIDER_ERROR", "x: targeted post lookup returned duplicate or unrequested IDs");
2009
+ found.set(post.id_str, post);
2010
+ }
2011
+ if (result.next_cursor === null) {
2012
+ if (ids3.some((id) => !found.has(id))) throw new AdportError12("INVALID_INPUT", "x: not every requested published post was returned for this account/author; missing data does not prove global absence");
2013
+ return ids3.map((id) => found.get(id));
2014
+ }
2015
+ if (!result.next_cursor || cursors.has(result.next_cursor)) break;
2016
+ cursor2 = result.next_cursor;
2017
+ cursors.add(cursor2);
2018
+ }
2019
+ throw new AdportError12("PROVIDER_ERROR", "x: targeted post lookup is incomplete; no mutation submitted");
2020
+ }
2021
+ async get(account, user2, id) {
2022
+ const post = (await this.exactPosts(xId.parse(account), snowflake.parse(user2), [snowflake.parse(id)]))[0];
2023
+ return { ...post, snapshot_hash: postSnapshot(account, post) };
2024
+ }
2025
+ visual(post) {
2026
+ const media = post.extended_entities?.media ?? post.entities?.media ?? [];
2027
+ return media.flatMap((item) => {
2028
+ const poster = safeUrl2(item.media_url_https, true);
2029
+ if (item.type === "photo") return poster ? [{ type: "image", url: poster }] : [];
2030
+ const video = item.video_info?.variants.filter((variant) => variant.content_type === "video/mp4" && safeUrl2(variant.url, true)).sort((a, b) => (b.bitrate ?? 0) - (a.bitrate ?? 0))[0];
2031
+ return video ? [{ type: "video", url: video.url, ...poster ? { poster_url: poster } : {} }] : poster ? [{ type: "image", url: poster, alt: "Video poster" }] : [];
2032
+ });
2033
+ }
2034
+ creative(account, post, canRename = true) {
2035
+ return { id: post.id_str, provider: "x", account_id: account, name: post.name ?? `Post ${post.id_str}`, type: post.nullcast ? "PROMOTED_ONLY_POST" : "ORGANIC_POST", status: "PUBLISHED", headlines: [], descriptions: [post.full_text], landing_urls: (post.entities?.urls ?? []).flatMap((value) => {
2036
+ const url3 = safeUrl2(value.expanded_url);
2037
+ return url3 ? [url3] : [];
2038
+ }), media: this.visual(post), actions: canRename ? [{ label: "Rename post", tool: "x_rename_published_post", arguments: { account_id: account, user_id: post.user.id_str, tweet_id: post.id_str, expected_snapshot_hash: postSnapshot(account, post) }, fields: [{ key: "name", label: "Post name", type: "text", value: post.name ?? "", max_length: 80 }] }] : [] };
2039
+ }
2040
+ async list(raw) {
2041
+ const input = postList.parse(raw), author = await this.author(input.account_id, input.user_id);
2042
+ const { account_id, user_id, ...params } = input;
2043
+ const result = await this.postPage(account_id, user_id, params);
2044
+ if (result.data.some((post) => input.timeline_type !== "ALL" && post.nullcast !== (input.timeline_type === "NULLCAST"))) throw new AdportError12("PROVIDER_ERROR", "x: published timeline filter mismatch");
2045
+ return { items: result.data.map((post) => ({ ...post, snapshot_hash: postSnapshot(account_id, post) })), creatives: result.data.map((post) => this.creative(account_id, post, author.promotable_user_type === "FULL")), ...this.paging(result.data.map((post) => post.id_str), result.next_cursor, input.cursor), warnings: ["PUBLISHED describes post publication, not an ad association or delivery. Published copy is not editable through the native name route."] };
2046
+ }
2047
+ async creationContext(account, raw) {
2048
+ const input = postFields.parse(raw), actor = await this.creatives.verifyComposer(account, input.as_user_id), sources = await this.creatives.verifyAttachments(account, input.media_keys ?? [], input.card_uri);
2049
+ if (Object.keys(input).some((key) => key.startsWith("video_")) && !(sources.media.length === 1 && sources.media[0].media_type === "VIDEO")) throw new AdportError12("INVALID_INPUT", "x: video metadata requires one ready native VIDEO attachment");
2050
+ const context = { account_id: account, request: input, actor, sources: { media: sources.media.map(sourceConfig), cards: sources.cards.map(sourceConfig) } };
2051
+ return { ...context, context_hash: hash4(context), notes: ["Creates a distinct promoted-only published post, not an unpublished draft. Existing drafts are retained. It is not placed on the public timeline or served to followers by the nullcast endpoint, but remains published content usable by ads.", notice] };
2052
+ }
2053
+ async parents(account, lineId) {
2054
+ await this.entities.getAccount(account);
2055
+ const line = await this.entities.getLineItem(account, lineId), campaign = await this.entities.getCampaign(account, line.campaign_id);
2056
+ const lineConfig = Object.fromEntries(Object.entries(line).filter(([key]) => !["created_at", "updated_at", "approval_status", "reasons_not_servable", "servable"].includes(key)));
2057
+ return { line, campaign, snapshot: { line: lineConfig, campaign } };
2058
+ }
2059
+ scopedPromotion(account, row, line) {
2060
+ if (row.account_id !== void 0 && row.account_id !== account || line && row.line_item_id !== line) throw new AdportError12("PROVIDER_ERROR", "x: promoted-post account/line-item mismatch");
2061
+ return row;
2062
+ }
2063
+ async promotionPage(account, line, params) {
2064
+ const result = await this.entities.client.request("GET", `${this.base(account)}/promoted_tweets`, pageSchema(nativePromotion), { line_item_ids: line, ...params });
2065
+ result.data.forEach((row) => this.scopedPromotion(account, row, line));
2066
+ this.paging(result.data.map((row) => row.id), result.next_cursor, typeof params.cursor === "string" ? params.cursor : void 0);
2067
+ return result;
2068
+ }
2069
+ async existing(account, line) {
2070
+ const rows2 = [], cursors = /* @__PURE__ */ new Set(), ids3 = /* @__PURE__ */ new Set();
2071
+ let cursor2;
2072
+ for (let page5 = 0; page5 < 10; page5++) {
2073
+ const result = await this.promotionPage(account, line, { count: 200, with_deleted: false, ...cursor2 ? { cursor: cursor2 } : {} });
2074
+ for (const row of result.data) {
2075
+ if (row.deleted || ids3.has(row.id)) throw new AdportError12("PROVIDER_ERROR", "x: active promotion scan contains deleted/duplicate rows");
2076
+ ids3.add(row.id);
2077
+ rows2.push(row);
2078
+ }
2079
+ if (result.next_cursor === null) return rows2;
2080
+ if (!result.next_cursor || cursors.has(result.next_cursor)) break;
2081
+ cursor2 = result.next_cursor;
2082
+ cursors.add(cursor2);
2083
+ }
2084
+ throw new AdportError12("PROVIDER_ERROR", "x: promotion scan is incomplete; no mutation submitted");
2085
+ }
2086
+ promotionHash(account, row, parents) {
2087
+ return hash4({ account_id: account, promotion: row, parents });
2088
+ }
2089
+ async getPromotion(account, id) {
2090
+ await this.entities.getAccount(account);
2091
+ const row = this.scopedPromotion(account, (await this.entities.client.request("GET", `${this.base(account)}/promoted_tweets/${xId.parse(id)}`, z21.object({ data: nativePromotion }), { with_deleted: true })).data);
2092
+ if (row.id !== id) throw new AdportError12("PROVIDER_ERROR", "x: promoted-post ID mismatch");
2093
+ const parents = await this.parents(account, row.line_item_id);
2094
+ return { ...row, context_hash: this.promotionHash(account, row, parents.snapshot), parent: parents.snapshot };
2095
+ }
2096
+ async promotionContext(account, raw) {
2097
+ const input = promotionSelection.parse(raw);
2098
+ await this.author(account, input.user_id, true);
2099
+ const parents = await this.parents(account, input.line_item_id);
2100
+ if (parents.line.deleted || parents.campaign.deleted || !["ACTIVE", "PAUSED"].includes(parents.line.entity_status) || !["ACTIVE", "PAUSED"].includes(parents.campaign.entity_status) || !["PROMOTED_TWEETS", "PROMOTED_ACCOUNT"].includes(parents.line.product_type)) throw new AdportError12("INVALID_INPUT", "x: promotions require an existing supported non-draft campaign/ad group");
2101
+ const posts = await this.exactPosts(account, input.user_id, input.tweet_ids);
2102
+ if (posts.some((post) => post.truncated)) throw new AdportError12("INVALID_INPUT", "x: source copy is truncated; read complete post content before promotion");
2103
+ const existing = (await this.existing(account, input.line_item_id)).filter((row) => input.tweet_ids.includes(row.tweet_id));
2104
+ const context = { account_id: account, request: input, parent: parents.snapshot, posts, existing };
2105
+ return { ...context, context_hash: hash4(context), notes: ["New native associations are ACTIVE; there is no PUT status. Under paused_creation the ad group itself must be PAUSED. The native API has no atomic compare-and-set, so snapshots do not lock concurrent account changes.", "RETWEETS_ONLY copy promotion and scheduled associations are separate workflows.", notice] };
2106
+ }
2107
+ async repostAuthors(account, source) {
2108
+ const users = await this.creatives.users(account, true), sources = users.filter((row) => row.user_id === source && !row.deleted), receiving = users.filter((row) => row.promotable_user_type === "FULL" && !row.deleted);
2109
+ if (sources.length !== 1 || sources[0].promotable_user_type !== "RETWEETS_ONLY" || receiving.length !== 1 || receiving[0].user_id === source) throw new AdportError12("INVALID_INPUT", "x: repost promotion needs one current RETWEETS_ONLY source author and one unambiguous FULL receiving author; use ordinary promotion for FULL sources");
2110
+ return { source_author: sourceConfig(sources[0]), receiving_author: sourceConfig(receiving[0]) };
2111
+ }
2112
+ async repostState(account, input) {
2113
+ const authors = await this.repostAuthors(account, input.user_id);
2114
+ const parent = await this.parents(account, input.line_item_id);
2115
+ if (parent.line.deleted || parent.campaign.deleted || !["ACTIVE", "PAUSED"].includes(parent.line.entity_status) || !["ACTIVE", "PAUSED"].includes(parent.campaign.entity_status) || !["PROMOTED_TWEETS", "PROMOTED_ACCOUNT"].includes(parent.line.product_type)) throw new AdportError12("INVALID_INPUT", "x: repost promotion requires supported existing non-draft parents");
2116
+ const posts = await this.exactPosts(account, input.user_id, input.tweet_ids);
2117
+ if (posts.some((post) => post.truncated)) throw new AdportError12("INVALID_INPUT", "x: repost source copy is truncated; read complete content before promotion");
2118
+ const existing = (await this.existing(account, input.line_item_id)).sort((a, b) => a.id.localeCompare(b.id));
2119
+ return { account_id: account, request: input, ...authors, parent: parent.snapshot, posts, existing };
2120
+ }
2121
+ async repostContext(account, raw) {
2122
+ const input = promotionSelection.parse(raw), context = await this.repostState(xId.parse(account), input);
2123
+ return { ...context, context_hash: hash4(context), creatives: context.posts.map((post) => this.creative(account, post, false)), truncated: false, notes: ["Each selected original produces a new PUBLISHED nullcast repost plus a native ACTIVE association. This is not an unpublished draft or organic timeline publication.", "Existing reposts have different post IDs. Source-ID deduplication is not established by the native association inventory; approval explicitly permits new copies, including additional copies of previously promoted sources.", "The tool correlates one approved source with one native POST receipt. Batches use at most four concurrent requests and can stop partially; no native write is retried. Independently observed copy metadata does not certify source-content or attachment rendering equivalence.", "paused_creation requires a currently PAUSED ad group. No parent status or budget is changed; snapshots do not lock native concurrent changes.", notice] };
2124
+ }
2125
+ async promotions(raw) {
2126
+ const input = promotionList.parse(raw), parents = await this.parents(input.account_id, input.line_item_id);
2127
+ if (input.user_id) await this.author(input.account_id, input.user_id);
2128
+ const result = await this.promotionPage(input.account_id, input.line_item_id, { count: input.count, with_deleted: input.with_deleted, ...input.cursor ? { cursor: input.cursor } : {} });
2129
+ if (!input.with_deleted && result.data.some((row) => row.deleted)) throw new AdportError12("PROVIDER_ERROR", "x: native promotion deletion filter mismatch");
2130
+ const posts = /* @__PURE__ */ new Map(), warnings = ["Native ACTIVE is association state, not proof of delivery. Removing an association retains its published post."];
2131
+ if (input.user_id && result.data.length) {
2132
+ const wanted = [...new Set(result.data.map((row) => row.tweet_id))].slice(0, 100);
2133
+ try {
2134
+ (await this.exactPosts(input.account_id, input.user_id, wanted)).forEach((post) => posts.set(post.id_str, post));
2135
+ } catch {
2136
+ warnings.push("Published content was not verified for the selected author; native association references remain visible.");
2137
+ }
2138
+ if (new Set(result.data.map((row) => row.tweet_id)).size > 100) warnings.push("Content hydration is limited to100 distinct posts per page.");
2139
+ }
2140
+ const creatives = result.data.map((row) => {
2141
+ const post = posts.get(row.tweet_id), visual = post ? this.creative(input.account_id, post) : void 0;
2142
+ return { ...visual ?? { provider: "x", account_id: input.account_id, headlines: [], descriptions: [], landing_urls: [], media: [] }, id: row.id, name: post?.name ?? `Promoted post ${row.tweet_id}`, type: "PROMOTED_POST_ASSOCIATION", status: row.deleted ? "DISASSOCIATED" : row.entity_status, campaign_id: parents.campaign.id, ad_group_id: row.line_item_id, actions: row.deleted ? [] : [{ label: "Remove from ad group", tool: "x_delete_promoted_post", arguments: { account_id: input.account_id, promoted_tweet_id: row.id, expected_context_hash: this.promotionHash(input.account_id, row, parents.snapshot) }, fields: [] }] };
2143
+ });
2144
+ return { items: result.data.map((row) => ({ ...row, context_hash: this.promotionHash(input.account_id, row, parents.snapshot) })), parent: parents.snapshot, creatives, warnings, ...this.paging(result.data.map((row) => row.id), result.next_cursor, input.cursor) };
2145
+ }
2146
+ unconfirmed(error, known) {
2147
+ const previous = error instanceof AdportError12 && error.details && typeof error.details === "object" && "resource_ids" in error.details && Array.isArray(error.details.resource_ids) ? error.details.resource_ids.filter((value) => typeof value === "string") : [];
2148
+ throw new AdportError12("PROVIDER_ERROR", "x: post/promotion outcome was not confirmed. Reconcile known IDs and current inventory before another mutation; no write was retried.", { resource_ids: [.../* @__PURE__ */ new Set([...known, ...previous])] });
2149
+ }
2150
+ async plan(op, guard) {
2151
+ const account = xId.parse(op.accountId), create = ["x_create_promoted_only_post", "x_create_promoted_posts", "x_create_repost_promotions"].includes(op.tool), remove = op.tool === "x_delete_promoted_post";
2152
+ if (op.provider !== "x" || op.kind !== (create ? "create" : remove ? "remove" : "update")) throw new AdportError12("INVALID_INPUT", "x: post operation provider/kind mismatch");
2153
+ const review = (title, fields, notices3) => ({ summary: title, changes: fields.map((field) => `${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes: notices3, review: { provider: "x", accountId: account, kind: op.kind, title, fields, notices: notices3 } });
2154
+ if (op.tool === "x_create_repost_promotions") {
2155
+ const { expected_context_hash, acknowledge_active_associations: _active, acknowledge_new_published_copies: _copies, ...input2 } = createRepostPromotions.parse(op.payload), context = await this.repostContext(account, input2);
2156
+ if (context.context_hash !== expected_context_hash) throw new AdportError12("PENDING_MISMATCH", "x: repost source/author/parent/association context changed; read and preview again");
2157
+ if (guard.forcePausedCreation && context.parent.line.entity_status !== "PAUSED") throw new AdportError12("POLICY_VIOLATION", "x: native repost associations are ACTIVE; paused_creation requires a currently PAUSED ad group");
2158
+ const receivingUser = snowflake.parse(context.receiving_author.user_id), baselineIds = new Set(context.existing.map((row) => row.id)), baselineTweets = new Set(context.existing.map((row) => row.tweet_id));
2159
+ const budgetDeltas = [context.parent.line, context.parent.campaign].flatMap((entity) => ["daily_budget_amount_local_micro", "total_budget_amount_local_micro"].flatMap((key) => {
2160
+ const value = entity[key];
2161
+ return typeof value === "number" ? [{ target: `${entity.id} ${key} existing pool`, currency: context.parent.campaign.currency, fromMicros: value, toMicros: value }] : [];
2162
+ }));
2163
+ const fields = [{ label: "Source author", after: input2.user_id }, { label: "Receiving author", after: receivingUser }, { label: "Ad group", after: input2.line_item_id }, { label: "Ad-group status", after: context.parent.line.entity_status }, { label: "Campaign status", after: context.parent.campaign.entity_status }, { label: "New publication", after: `${input2.tweet_ids.length} promoted-only repost(s)` }, { label: "Association state", after: "ACTIVE" }, ...context.posts.map((post) => ({ label: `Source post ${post.id_str}`, after: post.full_text }))];
2164
+ return { ...review("Create promoted repost copies", fields, context.notes), budgetDeltas, execute: async () => {
2165
+ const mappings = /* @__PURE__ */ new Map(), knownIds = /* @__PURE__ */ new Set(), knownCopies = /* @__PURE__ */ new Set(), attempted = /* @__PURE__ */ new Set(), ambiguous = /* @__PURE__ */ new Set(), failures = [];
2166
+ const receiptSources = /* @__PURE__ */ new Map();
2167
+ let next = 0, stopped = false;
2168
+ const record = (kind, id, source) => {
2169
+ const key = `${kind}:${id}`, sources = receiptSources.get(key) ?? /* @__PURE__ */ new Set();
2170
+ sources.add(source);
2171
+ receiptSources.set(key, sources);
2172
+ if (sources.size > 1) {
2173
+ stopped = true;
2174
+ for (const value of sources) {
2175
+ ambiguous.add(value);
2176
+ mappings.delete(value);
2177
+ }
2178
+ }
2179
+ };
2180
+ const worker = async () => {
2181
+ while (!stopped && next < input2.tweet_ids.length) {
2182
+ const source = input2.tweet_ids[next++];
2183
+ try {
2184
+ const parent = await this.parents(account, input2.line_item_id), authors = await this.repostAuthors(account, input2.user_id), observedSource = (await this.exactPosts(account, input2.user_id, [source]))[0];
2185
+ if (!equal2(parent.snapshot, context.parent) || !equal2(authors.source_author, context.source_author) || !equal2(authors.receiving_author, context.receiving_author) || !equal2(observedSource, context.posts.find((row2) => row2.id_str === source))) throw new AdportError12("PENDING_MISMATCH", "x: repost preflight changed before the next native request");
2186
+ if (stopped) break;
2187
+ attempted.add(source);
2188
+ const body = await this.entities.client.request("POST", `${this.base(account)}/promoted_tweets`, z21.object({ data: z21.unknown() }), { line_item_id: input2.line_item_id, tweet_ids: source });
2189
+ const raw = Array.isArray(body.data) ? body.data : [body.data];
2190
+ for (const item of raw) if (item && typeof item === "object") {
2191
+ const row2 = item, id = xId.safeParse(row2.id), copy2 = snowflake.safeParse(row2.tweet_id);
2192
+ if (id.success) {
2193
+ knownIds.add(id.data);
2194
+ record("association", id.data, source);
2195
+ }
2196
+ if (copy2.success) {
2197
+ knownCopies.add(copy2.data);
2198
+ record("post", copy2.data, source);
2199
+ }
2200
+ }
2201
+ const rows2 = z21.array(nativePromotion.extend({ tweet_id: snowflake })).length(1).parse(body.data), row = rows2[0];
2202
+ if (ambiguous.has(source) || row.line_item_id !== input2.line_item_id || row.deleted || row.entity_status !== "ACTIVE" || row.account_id !== void 0 && row.account_id !== account || input2.tweet_ids.includes(row.tweet_id) || baselineIds.has(row.id) || baselineTweets.has(row.tweet_id)) throw new Error("repost receipt scope/state/mapping mismatch");
2203
+ const association = await this.getPromotion(account, row.id);
2204
+ if (!equal2(nativePromotion.parse(association), row) || !equal2(association.parent, context.parent)) throw new Error("repost association readback mismatch");
2205
+ const copy = (await this.exactPosts(account, receivingUser, [row.tweet_id]))[0];
2206
+ if (!copy.nullcast || copy.truncated) throw new Error("copied publication metadata mismatch");
2207
+ if (ambiguous.has(source)) throw new Error("duplicate repost mapping");
2208
+ mappings.set(source, { source_tweet_id: source, copied_tweet_id: row.tweet_id, promoted_tweet_id: row.id });
2209
+ } catch (error) {
2210
+ stopped = true;
2211
+ failures.push(source);
2212
+ if (error instanceof AdportError12 && error.details && typeof error.details === "object" && "resource_ids" in error.details && Array.isArray(error.details.resource_ids)) {
2213
+ for (const id of error.details.resource_ids) if (typeof id === "string" && xId.safeParse(id).success) {
2214
+ knownIds.add(id);
2215
+ record("association", id, source);
2216
+ }
2217
+ }
2218
+ if (error instanceof AdportError12 && error.details && typeof error.details === "object" && "reported_tweet_ids" in error.details && Array.isArray(error.details.reported_tweet_ids)) {
2219
+ for (const id of error.details.reported_tweet_ids) if (typeof id === "string" && snowflake.safeParse(id).success) {
2220
+ knownCopies.add(id);
2221
+ record("post", id, source);
2222
+ }
2223
+ }
2224
+ }
2225
+ }
2226
+ };
2227
+ await Promise.all(Array.from({ length: Math.min(4, input2.tweet_ids.length) }, worker));
2228
+ const confirmed = input2.tweet_ids.flatMap((id) => mappings.has(id) ? [mappings.get(id)] : []);
2229
+ if (failures.length || confirmed.length !== input2.tweet_ids.length) throw new AdportError12("PROVIDER_ERROR", "x: repost promotion was not fully confirmed. Reconcile the confirmed mappings and reported IDs before another preview; no request was retried and no rollback was attempted.", { resource_ids: [...knownIds], reported_tweet_ids: [...knownCopies], confirmed_source_copy_mappings: confirmed, ambiguous_source_ids: input2.tweet_ids.filter((id) => ambiguous.has(id)), source_outcomes: input2.tweet_ids.filter((id) => !mappings.has(id)).map((id) => ({ source_tweet_id: id, state: attempted.has(id) ? "UNCONFIRMED" : "NOT_STARTED" })), unattempted_source_ids: input2.tweet_ids.filter((id) => !attempted.has(id)) });
2230
+ return { applied: true, resourceIds: confirmed.map((row) => row.promoted_tweet_id), details: { source_copy_mappings: confirmed, mapping_basis: "ONE_SOURCE_PER_NATIVE_REQUEST", copied_post_metadata_verified: true, source_copy_content_equivalence_verified: false, parent_status_or_budget_changed: false, next_tool: "x_promoted_posts", next_arguments: { account_id: account, line_item_id: input2.line_item_id, user_id: receivingUser } }, warnings: ["Mapping follows the documented native copy-promotion request and independently observed association/copy metadata. Source-content and attachment rendering equivalence was not certified; inspect the copied posts before delivery."] };
2231
+ } };
2232
+ }
2233
+ if (op.tool === "x_create_promoted_only_post") {
2234
+ const { expected_context_hash, confirm_publication: _confirm, ...input2 } = createPost.parse(op.payload), context = await this.creationContext(account, input2);
2235
+ if (context.context_hash !== expected_context_hash) throw new AdportError12("INVALID_INPUT", "x: publication source context changed; read and preview it again");
2236
+ const params = { ...Object.fromEntries(Object.entries(input2).filter(([key, value]) => key !== "media_keys" && value !== void 0)), ...input2.media_keys ? { media_keys: input2.media_keys.join(",") } : {}, nullcast: true, trim_user: true, tweet_mode: "extended" };
2237
+ return { ...review("Create promoted-only post", [{ label: "Author", after: input2.as_user_id }, { label: "Text", after: input2.text ?? "(media only)" }, { label: "Name", after: input2.name ?? "(unnamed)" }, { label: "Media", after: input2.media_keys ?? [] }, { label: "Card", after: input2.card_uri ?? "(none)" }, { label: "Replies", after: input2.conversation_settings }, ...Object.entries(input2).filter(([key]) => key.startsWith("video_")).map(([key, value]) => ({ label: key, after: value })), { label: "Publication", after: "PUBLISHED \xB7 promoted-only \xB7 no ad association" }], context.notes), execute: async () => {
2238
+ let known;
2239
+ try {
2240
+ const receipt = (await this.entities.client.request("POST", `${this.base(account)}/tweet`, z21.object({ data: z21.object({ id_str: snowflake, user: z21.object({ id_str: snowflake }) }) }), params)).data;
2241
+ known = receipt.id_str;
2242
+ if (receipt.user.id_str !== input2.as_user_id) throw new Error("author mismatch");
2243
+ const observed = (await this.exactPosts(account, input2.as_user_id, [known]))[0];
2244
+ if (!observed.nullcast || observed.truncated || observed.conversation_settings !== input2.conversation_settings || input2.name !== void 0 && observed.name !== input2.name) throw new Error("publication readback mismatch");
2245
+ const textVerified = input2.text === void 0 || observed.full_text === input2.text;
2246
+ return { applied: true, resourceIds: [known], details: { publication_confirmed: true, nullcast: true, ad_association_created: false, requested_text_exactly_observed: input2.text === void 0 ? null : textVerified, attachment_readback_verified: input2.media_keys?.length || input2.card_uri ? false : null }, warnings: [...!textVerified ? ["Native published text differs from the submitted text, for example through URL rewriting. Inspect the exact post before promotion; requested text equivalence was not certified."] : [], ...input2.media_keys?.length || input2.card_uri ? ["Source ownership/readiness was checked; published attachment rendering was not independently certified. Inspect the published post before promotion."] : []] };
2247
+ } catch (error) {
2248
+ return this.unconfirmed(error, known ? [known] : []);
2249
+ }
2250
+ } };
2251
+ }
2252
+ if (op.tool === "x_rename_published_post") {
2253
+ const input2 = renamePost.parse(op.payload);
2254
+ await this.author(account, input2.user_id, true);
2255
+ const current2 = (await this.exactPosts(account, input2.user_id, [input2.tweet_id]))[0];
2256
+ if (postSnapshot(account, current2) !== input2.expected_snapshot_hash) throw new AdportError12("INVALID_INPUT", "x: published post snapshot changed; read and preview it again");
2257
+ const expected = { ...current2, name: input2.name };
2258
+ return { ...review("Rename published post", [{ label: "Post", after: current2.id_str }, { label: "Name", before: current2.name, after: input2.name }], ["Changes the advertiser label only. Published copy, attachments and ad associations remain separate.", notice]), execute: async () => {
2259
+ const known = [current2.id_str];
2260
+ try {
2261
+ const receipt = (await this.entities.client.request("PUT", `${this.base(account)}/tweets/${current2.id_str}/name`, z21.object({ data: nativePost }), { name: input2.name })).data;
2262
+ known.push(receipt.id_str);
2263
+ if (!equal2(postContent(receipt), expected) || !equal2(postContent((await this.exactPosts(account, input2.user_id, [current2.id_str]))[0]), expected)) throw new Error("name preservation mismatch");
2264
+ return [current2.id_str];
2265
+ } catch (error) {
2266
+ return this.unconfirmed(error, known);
2267
+ }
2268
+ } };
2269
+ }
2270
+ if (op.tool === "x_create_promoted_posts") {
2271
+ const { expected_context_hash, acknowledge_active_associations: _ack, ...input2 } = createPromotions.parse(op.payload), context = await this.promotionContext(account, input2);
2272
+ if (context.context_hash !== expected_context_hash) throw new AdportError12("INVALID_INPUT", "x: promotion context changed; read and preview it again");
2273
+ if (context.existing.length) throw new AdportError12("INVALID_INPUT", "x: selected post already has a live association in this ad group; do not replay promotion");
2274
+ if (guard.forcePausedCreation && context.parent.line.entity_status !== "PAUSED") throw new AdportError12("POLICY_VIOLATION", "x: native associations are ACTIVE; paused_creation requires a currently PAUSED ad group");
2275
+ const fields = [{ label: "Ad group", after: context.parent.line.name ?? input2.line_item_id }, { label: "Campaign", after: context.parent.campaign.name }, { label: "Ad-group status", after: context.parent.line.entity_status }, { label: "Campaign status", after: context.parent.campaign.entity_status }, { label: "Native association status", after: "ACTIVE" }, ...context.posts.map((post) => ({ label: `Post ${post.id_str}`, after: post.full_text }))];
2276
+ const base = review("Associate published posts with ad group", fields, [...context.notes, "An ACTIVE association can serve when its parents permit delivery. No campaign/ad-group status is changed. DELETE disassociates; there is no per-association PUT pause."]);
2277
+ const budgetDeltas = [context.parent.line, context.parent.campaign].flatMap((entity) => ["daily_budget_amount_local_micro", "total_budget_amount_local_micro"].flatMap((key) => {
2278
+ const value = entity[key];
2279
+ return typeof value === "number" ? [{ target: `${entity.id} ${key} existing pool`, currency: context.parent.campaign.currency, fromMicros: value, toMicros: value }] : [];
2280
+ }));
2281
+ return { ...base, budgetDeltas, execute: async () => {
2282
+ let known = [];
2283
+ try {
2284
+ const rows2 = (await this.entities.client.request("POST", `${this.base(account)}/promoted_tweets`, z21.object({ data: z21.array(nativePromotion).min(1).max(50) }), { line_item_id: input2.line_item_id, tweet_ids: input2.tweet_ids.join(",") })).data;
2285
+ known = rows2.map((row) => row.id);
2286
+ if (rows2.length !== input2.tweet_ids.length || new Set(known).size !== rows2.length || new Set(rows2.map((row) => row.tweet_id)).size !== rows2.length || rows2.some((row) => row.deleted || row.entity_status !== "ACTIVE" || row.line_item_id !== input2.line_item_id || !input2.tweet_ids.includes(row.tweet_id) || row.account_id !== void 0 && row.account_id !== account)) throw new Error("association receipt mismatch");
2287
+ for (const row of rows2) {
2288
+ const observed = await this.getPromotion(account, row.id);
2289
+ if (!equal2({ id: observed.id, line_item_id: observed.line_item_id, tweet_id: observed.tweet_id, entity_status: observed.entity_status, deleted: observed.deleted }, { id: row.id, line_item_id: row.line_item_id, tweet_id: row.tweet_id, entity_status: row.entity_status, deleted: row.deleted }) || !equal2(observed.parent, context.parent)) throw new Error("association readback mismatch");
2290
+ }
2291
+ return known;
2292
+ } catch (error) {
2293
+ return this.unconfirmed(error, known);
2294
+ }
2295
+ } };
2296
+ }
2297
+ if (op.tool !== "x_delete_promoted_post") throw new AdportError12("INVALID_INPUT", "x: unsupported post operation");
2298
+ const input = deletePromotion.parse(op.payload), current = await this.getPromotion(account, input.promoted_tweet_id);
2299
+ if (current.context_hash !== input.expected_context_hash || current.deleted) throw new AdportError12("INVALID_INPUT", "x: promotion context changed or is already deleted; read and preview it again");
2300
+ return { ...review("Remove post from ad group", [{ label: "Association", after: current.id }, { label: "Published post", after: current.tweet_id }, { label: "Ad group", after: current.line_item_id }, { label: "Deleted", before: false, after: true }], ["Disassociates this one ad. The published post, media and other associations remain. Native entity_status may remain ACTIVE on the deleted tombstone; this is not post deletion or a PUT pause.", notice]), execute: async () => {
2301
+ const known = [current.id];
2302
+ try {
2303
+ const receipt = (await this.entities.client.request("DELETE", `${this.base(account)}/promoted_tweets/${current.id}`, z21.object({ data: nativePromotion }))).data;
2304
+ known.push(receipt.id);
2305
+ this.scopedPromotion(account, receipt, current.line_item_id);
2306
+ const matches2 = (row) => row.id === current.id && row.tweet_id === current.tweet_id && row.line_item_id === current.line_item_id && row.deleted;
2307
+ if (!matches2(receipt) || !matches2(await this.getPromotion(account, current.id))) throw new Error("disassociation readback mismatch");
2308
+ return [current.id];
2309
+ } catch (error) {
2310
+ return this.unconfirmed(error, known);
2311
+ }
2312
+ } };
2313
+ }
2314
+ };
2315
+
2316
+ // src/scheduled.ts
2317
+ import { createHash as createHash5 } from "crypto";
2318
+ import { AdportError as AdportError13 } from "@adport/core";
2319
+ import { z as z23 } from "zod";
2320
+
2321
+ // src/scheduled-schemas.ts
2322
+ import { z as z22 } from "zod";
2323
+ var unique2 = (values2) => new Set(values2).size === values2.length;
2324
+ var mediaKeys2 = z22.array(mediaKey).max(4).refine(unique2, "Use unique media keys");
2325
+ var scheduledTime = z22.iso.datetime().regex(/T\d{2}:\d{2}:00Z$/, "Use a UTC minute, ending in :00Z");
2326
+ var scheduledFields = z22.object({
2327
+ as_user_id: snowflake,
2328
+ scheduled_at: scheduledTime,
2329
+ text: z22.string().max(1e4).optional(),
2330
+ name: z22.string().min(1).max(80).optional(),
2331
+ media_keys: mediaKeys2.optional(),
2332
+ card_uri: cardUri.optional()
2333
+ }).strict().refine((value) => Boolean(value.text?.trim() || value.media_keys?.length), "Provide text or media");
2334
+ var createScheduled = scheduledFields.safeExtend({ expected_context_hash: postHash, acknowledge_automatic_publication: z22.literal(true) });
2335
+ var updateScheduled = z22.object({
2336
+ user_id: snowflake,
2337
+ scheduled_tweet_id: snowflake,
2338
+ expected_snapshot_hash: postHash,
2339
+ scheduled_at: scheduledTime.optional(),
2340
+ text: z22.string().max(1e4).optional(),
2341
+ name: z22.string().max(80).optional(),
2342
+ media_keys: mediaKeys2.optional(),
2343
+ card_uri: cardUri.nullable().optional(),
2344
+ acknowledge_automatic_publication: z22.literal(true),
2345
+ acknowledge_shared_effects: z22.boolean().optional()
2346
+ }).strict().refine((value) => ["scheduled_at", "text", "name", "media_keys", "card_uri"].some((key) => value[key] !== void 0), "Provide a changed field");
2347
+ var deleteScheduled = z22.object({ user_id: snowflake, scheduled_tweet_id: snowflake, expected_snapshot_hash: postHash, acknowledge_permanent_deletion: z22.literal(true) }).strict();
2348
+ var scheduledReference = z22.object({ account_id: xId, user_id: snowflake, scheduled_tweet_id: snowflake }).strict();
2349
+ var scheduledList = z22.object({ account_id: xId, user_id: snowflake, count: z22.number().int().min(1).max(200).default(20), cursor: z22.string().min(1).max(4096).optional(), include_media: z22.boolean().default(true) }).strict();
2350
+ var nativeScheduled = z22.object({
2351
+ id: snowflake,
2352
+ user_id: snowflake,
2353
+ account_id: xId.optional(),
2354
+ name: z22.string().nullable(),
2355
+ text: z22.string(),
2356
+ scheduled_status: z22.string(),
2357
+ nullcast: z22.boolean(),
2358
+ scheduled_at: z22.iso.datetime(),
2359
+ card_uri: cardUri.nullable(),
2360
+ media_keys: mediaKeys2,
2361
+ tweet_id: snowflake.nullable(),
2362
+ completed_at: z22.iso.datetime().nullable().optional()
2363
+ });
2364
+ var nativeScheduledPromotion = z22.object({ id: xId, account_id: xId.optional(), line_item_id: xId, scheduled_tweet_id: snowflake, tweet_id: snowflake.nullable(), deleted: z22.boolean() });
2365
+ var scheduledPromotionList = z22.object({ account_id: xId, line_item_id: xId, count: z22.number().int().min(1).max(200).default(20), cursor: z22.string().min(1).max(4096).optional(), with_deleted: z22.boolean().default(false) }).strict();
2366
+ var scheduledPromotionSelection = z22.object({ user_id: snowflake, line_item_id: xId, scheduled_tweet_id: snowflake }).strict();
2367
+ var createScheduledPromotion = scheduledPromotionSelection.safeExtend({ expected_context_hash: postHash, acknowledge_automatic_promotion: z22.literal(true) });
2368
+ var deleteScheduledPromotion = z22.object({ scheduled_promoted_tweet_id: xId, expected_context_hash: postHash }).strict();
2369
+ var scheduledWrites = /* @__PURE__ */ new Set(["x_create_scheduled_post", "x_update_scheduled_post", "x_delete_scheduled_post", "x_create_scheduled_promoted_post", "x_delete_scheduled_promoted_post"]);
2370
+
2371
+ // src/scheduled.ts
2372
+ var canonical5 = (value) => Array.isArray(value) ? value.map(canonical5) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, canonical5(v)])) : value;
2373
+ var equal3 = (left, right) => JSON.stringify(canonical5(left)) === JSON.stringify(canonical5(right));
2374
+ var hash5 = (value) => createHash5("sha256").update(JSON.stringify(canonical5(value))).digest("hex");
2375
+ var config = (post) => {
2376
+ const { completed_at: _completed, ...rest } = post;
2377
+ return { ...rest, scheduled_at: new Date(post.scheduled_at).toISOString() };
2378
+ };
2379
+ var sourceConfig2 = (row) => Object.fromEntries(Object.entries(row).filter(([key]) => !["created_at", "updated_at", "media_url", "poster_media_url"].includes(key)));
2380
+ var pageSchema2 = (item) => z23.object({ data: z23.array(item).max(1e3), next_cursor: z23.string().min(1).max(4096).nullable().optional() });
2381
+ var notices = ["X publishes this promoted-only post automatically at its scheduled time. No parent delivery setting is changed.", "Previews are local plans, not native validation. Scheduling, publication, ad association and actual delivery are separate states. No write is retried automatically."];
2382
+ var XScheduledService = class {
2383
+ constructor(entities, creatives, posts) {
2384
+ this.entities = entities;
2385
+ this.creatives = creatives;
2386
+ this.posts = posts;
2387
+ }
2388
+ entities;
2389
+ creatives;
2390
+ posts;
2391
+ base(account) {
2392
+ return `accounts/${xId.parse(account)}`;
2393
+ }
2394
+ async author(account, user2) {
2395
+ snowflake.parse(user2);
2396
+ const matches2 = (await this.creatives.users(account)).filter((row) => row.user_id === user2 && !row.deleted);
2397
+ if (matches2.length !== 1 || !["FULL", "RETWEETS_ONLY"].includes(matches2[0].promotable_user_type)) throw new AdportError13("INVALID_INPUT", "x: schedule author must be an unambiguous current account-associated user");
2398
+ return matches2[0];
2399
+ }
2400
+ scoped(account, row, user2) {
2401
+ if (row.account_id !== void 0 && row.account_id !== account || user2 !== void 0 && row.user_id !== user2) throw new AdportError13("PROVIDER_ERROR", "x: scheduled-post account/author mismatch");
2402
+ return row;
2403
+ }
2404
+ paging(ids3, next, previous) {
2405
+ if (new Set(ids3).size !== ids3.length || next && next === previous) throw new AdportError13("PROVIDER_ERROR", "x: scheduled pagination repeated an ID or cursor");
2406
+ return { truncated: next !== null, ...next ? { next_cursor: next } : {}, ...next === void 0 ? { notes: ["Native continuation marker is missing; completeness is unconfirmed."] } : {} };
2407
+ }
2408
+ async raw(account, id, user2) {
2409
+ const row = (await this.entities.client.request("GET", `${this.base(account)}/scheduled_tweets/${snowflake.parse(id)}`, z23.object({ data: nativeScheduled }))).data;
2410
+ if (row.id !== id) throw new AdportError13("PROVIDER_ERROR", "x: scheduled-post ID mismatch");
2411
+ return this.scoped(account, row, user2);
2412
+ }
2413
+ async promotionPage(account, params, line) {
2414
+ const result = await this.entities.client.request("GET", `${this.base(account)}/scheduled_promoted_tweets`, pageSchema2(nativeScheduledPromotion), { ...params, ...line ? { line_item_ids: line } : {} });
2415
+ if (result.data.some((row) => row.account_id !== void 0 && row.account_id !== account || line && row.line_item_id !== line)) throw new AdportError13("PROVIDER_ERROR", "x: scheduled-ad account/parent mismatch");
2416
+ this.paging(result.data.map((row) => row.id), result.next_cursor, typeof params.cursor === "string" ? params.cursor : void 0);
2417
+ return result;
2418
+ }
2419
+ async associations(account, scheduledId) {
2420
+ const rows2 = [], ids3 = /* @__PURE__ */ new Set(), cursors = /* @__PURE__ */ new Set();
2421
+ let cursor2;
2422
+ for (let page5 = 0; page5 < 10; page5++) {
2423
+ const result = await this.promotionPage(account, { count: 200, with_deleted: false, ...cursor2 ? { cursor: cursor2 } : {} });
2424
+ for (const row of result.data) {
2425
+ if (row.deleted || ids3.has(row.id)) throw new AdportError13("PROVIDER_ERROR", "x: scheduled-ad inventory contains deleted/duplicate rows");
2426
+ ids3.add(row.id);
2427
+ if (row.scheduled_tweet_id === scheduledId) rows2.push(row);
2428
+ }
2429
+ if (result.next_cursor === null) return rows2.sort((a, b) => a.id.localeCompare(b.id));
2430
+ if (!result.next_cursor || cursors.has(result.next_cursor)) break;
2431
+ cursor2 = result.next_cursor;
2432
+ cursors.add(cursor2);
2433
+ }
2434
+ throw new AdportError13("INVALID_INPUT", "x: scheduled-ad inventory is incomplete; cannot prepare a safe mutation");
2435
+ }
2436
+ async get(account, user2, id) {
2437
+ const author = await this.author(account, user2), post = await this.raw(account, id, user2), associations = await this.associations(account, id);
2438
+ return { ...post, associations, snapshot_hash: hash5({ account, author: sourceConfig2(author), post: config(post), associations }) };
2439
+ }
2440
+ mutable(post) {
2441
+ if (post.scheduled_status !== "SCHEDULED" || post.tweet_id !== null || post.completed_at || !post.nullcast || Date.parse(post.scheduled_at) <= Date.now()) throw new AdportError13("INVALID_INPUT", "x: this mutation requires a still-future promoted-only SCHEDULED post; inspect published posts/ads after publication");
2442
+ }
2443
+ schedule(time2) {
2444
+ const now = Date.now(), last = new Date(now);
2445
+ last.setUTCFullYear(last.getUTCFullYear() + 1);
2446
+ if (Date.parse(time2) < now + 15 * 6e4 || Date.parse(time2) > last.getTime()) throw new AdportError13("INVALID_INPUT", "x: choose a UTC minute at least15minutes and at most one calendar year ahead");
2447
+ }
2448
+ async visualMedia(account, rows2, include) {
2449
+ const keys = include ? [...new Set(rows2.flatMap((row) => row.media_keys))] : [], values2 = /* @__PURE__ */ new Map();
2450
+ const pending = keys.slice(0, 40);
2451
+ let index = 0, failed = 0;
2452
+ await Promise.all(Array.from({ length: Math.min(4, pending.length) }, async () => {
2453
+ while (index < pending.length) {
2454
+ const key = pending[index++];
2455
+ try {
2456
+ const media = await this.creatives.media(account, key);
2457
+ if (!media.deleted) values2.set(key, this.creatives.visual(media));
2458
+ } catch {
2459
+ failed++;
2460
+ }
2461
+ }
2462
+ }));
2463
+ return { values: values2, notes: [...keys.length > 40 ? ["Media previews are limited to40unique library items per page. Use a smaller page for remaining previews."] : [], ...failed ? ["Some native media previews are unavailable; schedule copy and IDs are preserved."] : []] };
2464
+ }
2465
+ async list(value) {
2466
+ const input = scheduledList.parse(value);
2467
+ await this.author(input.account_id, input.user_id);
2468
+ const result = await this.entities.client.request("GET", `${this.base(input.account_id)}/scheduled_tweets`, pageSchema2(nativeScheduled), { user_id: input.user_id, count: input.count, ...input.cursor ? { cursor: input.cursor } : {} });
2469
+ result.data.forEach((row) => this.scoped(input.account_id, row, input.user_id));
2470
+ const page5 = this.paging(result.data.map((row) => row.id), result.next_cursor, input.cursor), media = await this.visualMedia(input.account_id, result.data, input.include_media);
2471
+ const creatives = result.data.map((row) => ({ id: row.id, provider: "x", account_id: input.account_id, name: row.name ?? `Scheduled post ${row.id}`, type: row.nullcast ? "SCHEDULED_PROMOTED_ONLY_POST" : "SCHEDULED_ORGANIC_POST", status: row.scheduled_status, headlines: [], descriptions: [row.text, `Scheduled: ${row.scheduled_at}`, ...row.tweet_id ? [`Published post: ${row.tweet_id}`] : []], landing_urls: [], media: row.media_keys.flatMap((key) => media.values.get(key) ?? []), actions: [] }));
2472
+ return { account_id: input.account_id, items: result.data, creatives, ...page5, notes: [...page5.notes ?? [], ...media.notes] };
2473
+ }
2474
+ async creationContext(account, value) {
2475
+ const input = scheduledFields.parse(value);
2476
+ this.schedule(input.scheduled_at);
2477
+ const author = await this.author(account, input.as_user_id), actor = await this.creatives.verifyComposer(account, input.as_user_id), sources = await this.creatives.verifyAttachments(account, input.media_keys ?? [], input.card_uri);
2478
+ return { context_hash: hash5({ account, input, author: sourceConfig2(author), actor, media: sources.media.map(sourceConfig2), cards: sources.cards.map(sourceConfig2) }), request: input, nullcast: true, ad_association_created: false, notes: notices };
2479
+ }
2480
+ async promotions(value) {
2481
+ const input = scheduledPromotionList.parse(value);
2482
+ await this.posts.parents(input.account_id, input.line_item_id);
2483
+ const result = await this.promotionPage(input.account_id, { count: input.count, with_deleted: input.with_deleted, ...input.cursor ? { cursor: input.cursor } : {} }, input.line_item_id);
2484
+ if (!input.with_deleted && result.data.some((row) => row.deleted)) throw new AdportError13("PROVIDER_ERROR", "x: scheduled-ad filter returned deleted rows");
2485
+ return { account_id: input.account_id, line_item_id: input.line_item_id, items: result.data, records: result.data, ...this.paging(result.data.map((row) => row.id), result.next_cursor, input.cursor) };
2486
+ }
2487
+ async getPromotion(account, id) {
2488
+ const row = (await this.entities.client.request("GET", `${this.base(account)}/scheduled_promoted_tweets/${xId.parse(id)}`, z23.object({ data: nativeScheduledPromotion }), { with_deleted: true })).data;
2489
+ if (row.id !== id || row.account_id !== void 0 && row.account_id !== account) throw new AdportError13("PROVIDER_ERROR", "x: scheduled-ad ID/account mismatch");
2490
+ const parent = await this.posts.parents(account, row.line_item_id);
2491
+ const source = row.deleted ? null : await this.raw(account, row.scheduled_tweet_id);
2492
+ if (source) await this.author(account, source.user_id);
2493
+ return { ...row, source, parent: parent.snapshot, context_hash: hash5({ account, row, source: source ? config(source) : null, parent: parent.snapshot }) };
2494
+ }
2495
+ async promotionContext(account, value) {
2496
+ const input = scheduledPromotionSelection.parse(value), post = await this.get(account, input.user_id, input.scheduled_tweet_id);
2497
+ await this.creatives.verifyComposer(account, input.user_id);
2498
+ this.mutable(post);
2499
+ const parent = await this.posts.parents(account, input.line_item_id);
2500
+ if (parent.line.deleted || parent.campaign.deleted || !["ACTIVE", "PAUSED"].includes(parent.line.entity_status) || !["ACTIVE", "PAUSED"].includes(parent.campaign.entity_status) || !["PROMOTED_TWEETS", "PROMOTED_ACCOUNT"].includes(parent.line.product_type)) throw new AdportError13("INVALID_INPUT", "x: scheduled promotion requires supported existing non-draft parents");
2501
+ const existing = post.associations.filter((row) => row.line_item_id === input.line_item_id);
2502
+ return { context_hash: hash5({ account, input, post, parent: parent.snapshot, existing }), post, parent: parent.snapshot, existing, notes: [...notices, "Native scheduled associations have no status field or PUT pause. They can promote after publication when parent settings allow."] };
2503
+ }
2504
+ unconfirmed(error, ids3) {
2505
+ const details = error instanceof AdportError13 ? error.details : void 0;
2506
+ const known = Array.isArray(details?.resource_ids) ? details.resource_ids.filter((value) => typeof value === "string") : [];
2507
+ throw new AdportError13("PROVIDER_ERROR", "x: scheduled write outcome was not confirmed. Reconcile known IDs and current inventory; do not replay the mutation.", { resource_ids: [.../* @__PURE__ */ new Set([...ids3, ...known])] });
2508
+ }
2509
+ async plan(op, guard) {
2510
+ const account = xId.parse(op.accountId), kind = op.tool.startsWith("x_create_") ? "create" : op.tool.startsWith("x_delete_") ? "remove" : "update";
2511
+ if (op.provider !== "x" || op.kind !== kind) throw new AdportError13("INVALID_INPUT", "x: scheduled operation provider/kind mismatch");
2512
+ const review = (title, fields, notes3 = notices) => ({ summary: title, changes: fields.map((field) => `${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes: notes3, review: { provider: "x", accountId: account, kind, title, fields, notices: notes3 } });
2513
+ if (op.tool === "x_create_scheduled_post") {
2514
+ const { expected_context_hash, acknowledge_automatic_publication: _ack, ...input2 } = createScheduled.parse(op.payload), context = await this.creationContext(account, input2);
2515
+ if (context.context_hash !== expected_context_hash) throw new AdportError13("INVALID_INPUT", "x: schedule source context changed; read and preview again");
2516
+ const wanted = { user_id: input2.as_user_id, text: input2.text ?? "", name: input2.name ?? null, scheduled_at: input2.scheduled_at, media_keys: input2.media_keys ?? [], card_uri: input2.card_uri ?? null, nullcast: true, scheduled_status: "SCHEDULED", tweet_id: null };
2517
+ const params = { ...Object.fromEntries(Object.entries(input2).filter(([key, v]) => key !== "media_keys" && v !== void 0)), ...input2.media_keys?.length ? { media_keys: input2.media_keys.join(",") } : {}, nullcast: true };
2518
+ return { ...review("Schedule promoted-only post", [{ label: "Author", after: input2.as_user_id }, { label: "Publish automatically at", after: input2.scheduled_at }, { label: "Copy", after: wanted.text }, { label: "Name", after: wanted.name }, { label: "Media", after: wanted.media_keys }, { label: "Card", after: wanted.card_uri }, { label: "Publication", after: "SCHEDULED \xB7 promoted-only \xB7 no ad association" }]), execute: async () => {
2519
+ const known = [];
2520
+ try {
2521
+ const row = (await this.entities.client.request("POST", `${this.base(account)}/scheduled_tweets`, z23.object({ data: nativeScheduled }), params)).data;
2522
+ known.push(row.id);
2523
+ this.scoped(account, row, input2.as_user_id);
2524
+ const observed = await this.raw(account, row.id, input2.as_user_id);
2525
+ for (const value of [row, observed]) if (!Object.entries(wanted).every(([key, v]) => key === "scheduled_at" ? Date.parse(value.scheduled_at) === Date.parse(String(v)) : equal3(value[key], v))) throw new Error("schedule receipt/readback mismatch");
2526
+ return { applied: true, resourceIds: known, details: { scheduled_status: "SCHEDULED", nullcast: true, scheduled_at: observed.scheduled_at, published_tweet_id: null, ad_association_created: false } };
2527
+ } catch (error) {
2528
+ return this.unconfirmed(error, known);
2529
+ }
2530
+ } };
2531
+ }
2532
+ if (op.tool === "x_update_scheduled_post" || op.tool === "x_delete_scheduled_post") {
2533
+ const input2 = op.tool === "x_update_scheduled_post" ? updateScheduled.parse(op.payload) : deleteScheduled.parse(op.payload), current2 = await this.get(account, input2.user_id, input2.scheduled_tweet_id);
2534
+ if (current2.snapshot_hash !== input2.expected_snapshot_hash) throw new AdportError13("INVALID_INPUT", "x: schedule snapshot changed; read and preview again");
2535
+ await this.creatives.verifyComposer(account, input2.user_id);
2536
+ this.mutable(current2);
2537
+ if (op.tool === "x_delete_scheduled_post") {
2538
+ if (current2.associations.length) throw new AdportError13("INVALID_INPUT", "x: remove live scheduled ad associations before deleting their source schedule");
2539
+ return { ...review("Permanently delete scheduled post", [{ label: "Scheduled post", after: current2.id }, { label: "Copy", before: current2.text, after: "(deleted)" }, { label: "Automatic publication", before: current2.scheduled_at, after: "Cancelled" }], ["Hard deletion cannot be undone. The schedule must remain unpublished and have no live scheduled ad associations. Existing published posts/media are separate.", notices[1]]), execute: async () => {
2540
+ const known = [current2.id];
2541
+ try {
2542
+ const receipt = (await this.entities.client.request("DELETE", `${this.base(account)}/scheduled_tweets/${current2.id}`, z23.object({ data: nativeScheduled }))).data;
2543
+ known.push(receipt.id);
2544
+ if (!equal3(config(receipt), { ...config(nativeScheduled.parse(current2)), scheduled_status: "DELETED" })) throw new Error("deletion receipt mismatch");
2545
+ try {
2546
+ await this.raw(account, current2.id, input2.user_id);
2547
+ throw new Error("deleted schedule still exists");
2548
+ } catch (error) {
2549
+ if (!(error instanceof AdportError13 && error.details?.http_status === 404)) throw error;
2550
+ }
2551
+ return [current2.id];
2552
+ } catch (error) {
2553
+ return this.unconfirmed(error, known);
2554
+ }
2555
+ } };
2556
+ }
2557
+ const parsed = updateScheduled.parse(input2), changed = Object.fromEntries(Object.entries(parsed).filter(([key, value]) => ["scheduled_at", "text", "name", "media_keys", "card_uri"].includes(key) && value !== void 0)), wanted = nativeScheduled.parse({ ...current2, ...changed });
2558
+ if (equal3(config(wanted), config(nativeScheduled.parse(current2)))) throw new AdportError13("INVALID_INPUT", "x: no scheduled-post configuration changed");
2559
+ if (!wanted.text.trim() && !wanted.media_keys.length) throw new AdportError13("INVALID_INPUT", "x: scheduled post requires text or media");
2560
+ this.schedule(wanted.scheduled_at);
2561
+ await this.creatives.verifyAttachments(account, wanted.media_keys, wanted.card_uri);
2562
+ if (current2.associations.length && parsed.acknowledge_shared_effects !== true) throw new AdportError13("INVALID_INPUT", "x: editing this schedule affects existing ad associations; acknowledge_shared_effects is required");
2563
+ const params = Object.fromEntries(Object.entries(changed).map(([key, value]) => [key, Array.isArray(value) ? value.join(",") : value === null ? "" : value]));
2564
+ return { ...review("Edit scheduled post", [...Object.entries(changed).map(([key, after]) => ({ label: key, before: current2[key], after })), { label: "Affected ad associations", after: current2.associations.map((row) => ({ id: row.id, line_item_id: row.line_item_id })) }]), execute: async () => {
2565
+ const known = [current2.id];
2566
+ try {
2567
+ const row = (await this.entities.client.request("PUT", `${this.base(account)}/scheduled_tweets/${current2.id}`, z23.object({ data: nativeScheduled }), params)).data;
2568
+ known.push(row.id);
2569
+ if (!equal3(config(row), config(wanted)) || !equal3(config(await this.raw(account, current2.id, input2.user_id)), config(wanted))) throw new Error("schedule edit preservation mismatch");
2570
+ return [current2.id];
2571
+ } catch (error) {
2572
+ return this.unconfirmed(error, known);
2573
+ }
2574
+ } };
2575
+ }
2576
+ if (op.tool === "x_create_scheduled_promoted_post") {
2577
+ const { expected_context_hash, acknowledge_automatic_promotion: _ack, ...input2 } = createScheduledPromotion.parse(op.payload), context = await this.promotionContext(account, input2);
2578
+ if (context.context_hash !== expected_context_hash || context.existing.length) throw new AdportError13("INVALID_INPUT", "x: scheduled promotion context changed or already associated; read again without replay");
2579
+ if (guard.forcePausedCreation && context.parent.line.entity_status !== "PAUSED") throw new AdportError13("POLICY_VIOLATION", "x: paused_creation requires a currently PAUSED ad group for automatic scheduled promotion");
2580
+ const budgetDeltas = [context.parent.line, context.parent.campaign].flatMap((entity) => ["daily_budget_amount_local_micro", "total_budget_amount_local_micro"].flatMap((key) => {
2581
+ const amount = entity[key];
2582
+ return typeof amount === "number" ? [{ target: `${entity.id} ${key} existing pool`, currency: context.parent.campaign.currency, fromMicros: amount, toMicros: amount }] : [];
2583
+ }));
2584
+ return { ...review("Associate scheduled post with ad group", [{ label: "Scheduled post", after: input2.scheduled_tweet_id }, { label: "Copy", after: context.post.text }, { label: "Publication time", after: context.post.scheduled_at }, { label: "Ad group", after: input2.line_item_id }, { label: "Ad-group status", after: context.parent.line.entity_status }, { label: "Campaign status", after: context.parent.campaign.entity_status }, { label: "Promotion", after: "Automatic after publication when parents permit delivery" }], context.notes), budgetDeltas, execute: async () => {
2585
+ const known = [];
2586
+ try {
2587
+ const row = (await this.entities.client.request("POST", `${this.base(account)}/scheduled_promoted_tweets`, z23.object({ data: nativeScheduledPromotion }), { line_item_id: input2.line_item_id, scheduled_tweet_id: input2.scheduled_tweet_id })).data;
2588
+ known.push(row.id);
2589
+ if (row.deleted || row.line_item_id !== input2.line_item_id || row.scheduled_tweet_id !== input2.scheduled_tweet_id || row.tweet_id !== null || row.account_id !== void 0 && row.account_id !== account) throw new Error("scheduled-ad receipt mismatch");
2590
+ const observed = await this.getPromotion(account, row.id);
2591
+ if (!equal3(nativeScheduledPromotion.parse(observed), row) || !equal3(observed.parent, context.parent)) throw new Error("scheduled-ad readback mismatch");
2592
+ const source2 = await this.raw(account, input2.scheduled_tweet_id, input2.user_id);
2593
+ if (!equal3(config(source2), config(nativeScheduled.parse(context.post)))) throw new Error("scheduled source changed");
2594
+ this.mutable(source2);
2595
+ return known;
2596
+ } catch (error) {
2597
+ return this.unconfirmed(error, known);
2598
+ }
2599
+ } };
2600
+ }
2601
+ if (op.tool !== "x_delete_scheduled_promoted_post") throw new AdportError13("INVALID_INPUT", "x: unsupported scheduled operation");
2602
+ const input = deleteScheduledPromotion.parse(op.payload), current = await this.getPromotion(account, input.scheduled_promoted_tweet_id);
2603
+ if (current.context_hash !== input.expected_context_hash || current.deleted || current.tweet_id !== null) throw new AdportError13("INVALID_INPUT", "x: scheduled association changed, is deleted or already published; inspect current ads");
2604
+ const source = await this.raw(account, current.scheduled_tweet_id);
2605
+ await this.author(account, source.user_id);
2606
+ this.mutable(source);
2607
+ return { ...review("Remove scheduled post from ad group", [{ label: "Association", after: current.id }, { label: "Scheduled post", after: source.id }, { label: "Ad group", after: current.line_item_id }, { label: "Deleted", before: false, after: true }], ["Removes this one ad association before publication. The scheduled post still publishes automatically. It is not schedule cancellation or published-post deletion.", notices[1]]), execute: async () => {
2608
+ const known = [current.id];
2609
+ try {
2610
+ const row = (await this.entities.client.request("DELETE", `${this.base(account)}/scheduled_promoted_tweets/${current.id}`, z23.object({ data: nativeScheduledPromotion }))).data, wanted = { ...nativeScheduledPromotion.parse(current), deleted: true };
2611
+ known.push(row.id);
2612
+ if (!equal3(row, wanted) || !equal3(nativeScheduledPromotion.parse(await this.getPromotion(account, current.id)), wanted)) throw new Error("scheduled-ad removal mismatch");
2613
+ return [current.id];
2614
+ } catch (error) {
2615
+ return this.unconfirmed(error, known);
2616
+ }
2617
+ } };
2618
+ }
2619
+ };
2620
+
2621
+ // src/direct-media.ts
2622
+ import { createHash as createHash6 } from "crypto";
2623
+ import { AdportError as AdportError14 } from "@adport/core";
2624
+ import { z as z25 } from "zod";
2625
+
2626
+ // src/direct-media-schemas.ts
2627
+ import { z as z24 } from "zod";
2628
+ var accountMediaTypes = ["BANNER", "BANNER_TABLET", "INTERSTITIAL", "INTERSTITIAL_LANDSCAPE", "INTERSTITIAL_LANDSCAPE_TABLET", "INTERSTITIAL_TABLET", "MEDIUM_RECTANGLE", "PREROLL", "VAST_PREROLL"];
2629
+ var hash6 = z24.string().regex(/^[a-f0-9]{64}$/);
2630
+ var page3 = { count: z24.number().int().min(1).max(50).default(20), cursor: z24.string().min(1).max(4096).optional(), with_deleted: z24.boolean().default(false) };
2631
+ var accountMediaList = z24.object({ account_id: xId, ...page3, creative_types: z24.array(z24.enum(accountMediaTypes)).min(1).max(accountMediaTypes.length).refine((values2) => new Set(values2).size === values2.length, "Use unique creative types").optional() }).strict();
2632
+ var directMediaList = z24.object({ account_id: xId, line_item_id: xId, ...page3, include_media: z24.boolean().default(true) }).strict();
2633
+ var nativeAccountMedia = z24.looseObject({ id: xId, creative_type: z24.string(), video_id: z24.string().nullable().optional(), media_url: z24.string().nullable().optional(), deleted: z24.boolean(), account_id: xId.optional() });
2634
+ var nativeDirectMedia = mediaCreativeSchema.extend({ creative_type: z24.string(), landing_url: z24.string().nullable().optional(), approval_status: z24.string().optional(), account_id: xId.optional() });
2635
+ var destination = z24.string().url().max(4096).refine((value) => {
2636
+ const url3 = new URL(value);
2637
+ return ["https:", "http:"].includes(url3.protocol) && !url3.username && !url3.password;
2638
+ }, "Use an HTTP(S) destination without embedded credentials");
2639
+ var directMediaSelection = z24.object({ line_item_id: xId, account_media_id: xId, landing_url: destination.optional() }).strict();
2640
+ var createDirectMedia = directMediaSelection.extend({ expected_context_hash: hash6, acknowledge_active_association: z24.literal(true) }).strict();
2641
+ var deleteDirectMedia = z24.object({ media_creative_id: xId, expected_context_hash: hash6 }).strict();
2642
+ var directMediaWrites = /* @__PURE__ */ new Set(["x_create_media_creative", "x_delete_media_creative"]);
2643
+
2644
+ // src/direct-media.ts
2645
+ var pageSchema3 = (item) => z25.object({ data: z25.array(item).max(1e3), next_cursor: z25.string().nullable().optional() });
2646
+ var canonical6 = (value) => Array.isArray(value) ? value.map(canonical6) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical6(item)])) : value;
2647
+ var hash7 = (value) => createHash6("sha256").update(JSON.stringify(canonical6(value))).digest("hex");
2648
+ var configuration3 = (value) => Object.fromEntries(Object.entries(value).filter(([key]) => !["created_at", "updated_at", "account_id", "configuration_hash"].includes(key)));
2649
+ var associationConfiguration = (row) => ({ id: row.id, line_item_id: row.line_item_id, account_media_id: row.account_media_id, creative_type: row.creative_type, landing_url: row.landing_url ?? null, entity_status: row.entity_status, deleted: row.deleted });
2650
+ var equal4 = (left, right) => hash7(left) === hash7(right);
2651
+ var sourceType = (type) => type === "PREROLL" ? "video" : accountMediaTypes.includes(type) && type !== "VAST_PREROLL" ? "image" : void 0;
2652
+ var url2 = (value, media = false) => {
2653
+ if (typeof value !== "string") return void 0;
2654
+ try {
2655
+ const parsed = new URL(value);
2656
+ return !parsed.username && !parsed.password && (media ? parsed.protocol === "https:" && (!parsed.port || parsed.port === "443") && ["pbs.twimg.com", "video.twimg.com", "ton.twimg.com"].includes(parsed.hostname) : ["https:", "http:"].includes(parsed.protocol)) ? value : void 0;
2657
+ } catch {
2658
+ return void 0;
2659
+ }
2660
+ };
2661
+ var notice2 = "Local preview is not native validation. Account Media assets, ad associations and actual delivery are separate. Native eligibility remains authoritative; no write is retried.";
2662
+ var XDirectMediaService = class {
2663
+ constructor(entities, posts) {
2664
+ this.entities = entities;
2665
+ this.posts = posts;
2666
+ }
2667
+ entities;
2668
+ posts;
2669
+ base(account) {
2670
+ return `accounts/${xId.parse(account)}`;
2671
+ }
2672
+ scope(account, row, id) {
2673
+ if (row.account_id !== void 0 && row.account_id !== account || id !== void 0 && row.id !== id) throw new AdportError14("PROVIDER_ERROR", "x: direct-media account or resource ID mismatch");
2674
+ return row;
2675
+ }
2676
+ paging(ids3, next, previous) {
2677
+ if (new Set(ids3).size !== ids3.length || next && next === previous) throw new AdportError14("PROVIDER_ERROR", "x: direct-media pagination repeated an ID or cursor");
2678
+ return { truncated: next !== null, ...next ? { next_cursor: next } : {}, ...next === void 0 || next === "" ? { notes: ["Native continuation marker is missing; completeness is unconfirmed."] } : {} };
2679
+ }
2680
+ visual(asset) {
2681
+ const type = sourceType(asset.creative_type), safe = url2(asset.media_url, true);
2682
+ return !asset.deleted && type && safe ? [{ type, url: safe }] : [];
2683
+ }
2684
+ assetCard(account, asset) {
2685
+ return { id: asset.id, provider: "x", account_id: account, name: `Account media ${asset.id}`, type: asset.creative_type, status: asset.deleted ? "DELETED" : "PRESENT", headlines: [], descriptions: [], landing_urls: [], media: this.visual(asset), actions: [] };
2686
+ }
2687
+ async getAsset(account, id) {
2688
+ await this.entities.getAccount(account);
2689
+ const row = this.scope(account, (await this.entities.client.request("GET", `${this.base(account)}/account_media/${xId.parse(id)}`, z25.object({ data: nativeAccountMedia }), { with_deleted: true })).data, id);
2690
+ return { ...row, configuration_hash: hash7({ account_id: account, asset: configuration3(row) }) };
2691
+ }
2692
+ async assets(raw) {
2693
+ const input = accountMediaList.parse(raw);
2694
+ await this.entities.getAccount(input.account_id);
2695
+ const result = await this.entities.client.request("GET", `${this.base(input.account_id)}/account_media`, pageSchema3(nativeAccountMedia), { count: input.count, with_deleted: input.with_deleted, ...input.cursor ? { cursor: input.cursor } : {}, ...input.creative_types ? { creative_types: input.creative_types.join(",") } : {} });
2696
+ for (const row of result.data) {
2697
+ this.scope(input.account_id, row);
2698
+ if (!input.with_deleted && row.deleted || input.creative_types && !input.creative_types.includes(row.creative_type)) throw new AdportError14("PROVIDER_ERROR", "x: Account Media native filter mismatch");
2699
+ }
2700
+ const paging = this.paging(result.data.map((row) => row.id), result.next_cursor, input.cursor);
2701
+ return { items: result.data, creatives: result.data.map((row) => this.assetCard(input.account_id, row)), ...paging, notes: ["Account Media IDs are not media-library keys. Presence does not establish processing readiness, byte identity or ad eligibility.", ...paging.notes ?? []] };
2702
+ }
2703
+ async page(account, line, params) {
2704
+ const result = await this.entities.client.request("GET", `${this.base(account)}/media_creatives`, pageSchema3(nativeDirectMedia), { line_item_ids: line, ...params });
2705
+ for (const row of result.data) {
2706
+ this.scope(account, row);
2707
+ if (row.line_item_id !== line || params.with_deleted === false && row.deleted) throw new AdportError14("PROVIDER_ERROR", "x: media-creative ad-group/deletion filter mismatch");
2708
+ }
2709
+ this.paging(result.data.map((row) => row.id), result.next_cursor, typeof params.cursor === "string" ? params.cursor : void 0);
2710
+ return result;
2711
+ }
2712
+ async existing(account, line) {
2713
+ const rows2 = [], ids3 = /* @__PURE__ */ new Set(), cursors = /* @__PURE__ */ new Set();
2714
+ let cursor2;
2715
+ for (let page5 = 0; page5 < 10; page5++) {
2716
+ const result = await this.page(account, line, { count: 200, with_deleted: false, ...cursor2 ? { cursor: cursor2 } : {} });
2717
+ for (const row of result.data) {
2718
+ if (ids3.has(row.id)) throw new AdportError14("PROVIDER_ERROR", "x: media-creative inventory repeated an ID");
2719
+ ids3.add(row.id);
2720
+ rows2.push(row);
2721
+ }
2722
+ if (result.next_cursor === null) return rows2.sort((a, b) => a.id.localeCompare(b.id));
2723
+ if (!result.next_cursor || cursors.has(result.next_cursor)) break;
2724
+ cursor2 = result.next_cursor;
2725
+ cursors.add(cursor2);
2726
+ }
2727
+ throw new AdportError14("PROVIDER_ERROR", "x: media-creative inventory is incomplete; no association was submitted");
2728
+ }
2729
+ associationHash(account, row, parent) {
2730
+ return hash7({ account_id: account, association: associationConfiguration(row), parent });
2731
+ }
2732
+ async get(account, id) {
2733
+ await this.entities.getAccount(account);
2734
+ const row = this.scope(account, (await this.entities.client.request("GET", `${this.base(account)}/media_creatives/${xId.parse(id)}`, z25.object({ data: nativeDirectMedia }), { with_deleted: true })).data, id);
2735
+ const parent = await this.posts.parents(account, row.line_item_id);
2736
+ return { ...row, parent: parent.snapshot, context_hash: this.associationHash(account, row, parent.snapshot) };
2737
+ }
2738
+ async context(account, raw) {
2739
+ const input = directMediaSelection.parse(raw), parent = await this.posts.parents(account, input.line_item_id), source = await this.getAsset(account, input.account_media_id);
2740
+ if (parent.line.deleted || parent.campaign.deleted || !["ACTIVE", "PAUSED"].includes(parent.line.entity_status) || !["ACTIVE", "PAUSED"].includes(parent.campaign.entity_status) || parent.line.product_type !== "MEDIA") throw new AdportError14("INVALID_INPUT", "x: direct media needs an existing non-draft MEDIA ad group and campaign");
2741
+ if (source.deleted || !sourceType(source.creative_type)) throw new AdportError14("INVALID_INPUT", "x: choose an existing PREROLL or documented TAP image asset; VAST/unknown authoring is not verified");
2742
+ if (source.creative_type === "PREROLL" && input.landing_url !== void 0) throw new AdportError14("INVALID_INPUT", "x: landing_url is ignored for preroll; use separate native preroll CTA settings");
2743
+ if (parent.line.objective === "WEBSITE_CLICKS" && !input.landing_url) throw new AdportError14("INVALID_INPUT", "x: WEBSITE_CLICKS requires an explicit landing_url");
2744
+ const existing = await this.existing(account, input.line_item_id), context = { account_id: account, request: input, source: configuration3(source), parent: parent.snapshot, existing: existing.map(associationConfiguration) };
2745
+ return { ...context, context_hash: hash7(context), creatives: [this.assetCard(account, source)], truncated: false, notes: ["Native creation adds an ACTIVE association. paused_creation requires a currently PAUSED ad group; parent delivery and budgets are preserved.", "The source is an existing native Account Media ID. No upload, media-library registration, post publication, CTA edit or source-byte verification is performed.", "Omitted display destinations may use native defaults. Preroll click destinations belong to separate line-item CTA settings. Format/objective/placement compatibility is checked by X.", "Snapshots do not atomically lock native concurrent changes. Reconcile unknown outcomes before any new association.", notice2] };
2746
+ }
2747
+ async list(raw) {
2748
+ const input = directMediaList.parse(raw), parent = await this.posts.parents(input.account_id, input.line_item_id), result = await this.page(input.account_id, input.line_item_id, { count: input.count, with_deleted: input.with_deleted, ...input.cursor ? { cursor: input.cursor } : {} });
2749
+ const sources = /* @__PURE__ */ new Map(), warnings = [], wanted = [...new Set(result.data.map((row) => row.account_media_id))];
2750
+ let index = 0;
2751
+ if (input.include_media) await Promise.all(Array.from({ length: Math.min(4, wanted.length) }, async () => {
2752
+ while (index < wanted.length) {
2753
+ const id = wanted[index++];
2754
+ try {
2755
+ sources.set(id, await this.getAsset(input.account_id, id));
2756
+ } catch {
2757
+ warnings.push(`Account Media ${id} could not be read; its association remains visible.`);
2758
+ }
2759
+ }
2760
+ }));
2761
+ const creatives = result.data.map((row) => {
2762
+ const source = sources.get(row.account_media_id), matching = source && !source.deleted && source.creative_type === row.creative_type;
2763
+ if (source && !matching) warnings.push(`Account Media ${row.account_media_id} is deleted or has a different format; its preview is unavailable.`);
2764
+ const destination3 = row.creative_type === "PREROLL" || row.creative_type === "VAST_PREROLL" ? void 0 : url2(row.landing_url);
2765
+ return { id: row.id, provider: "x", account_id: input.account_id, campaign_id: parent.campaign.id, ad_group_id: row.line_item_id, name: `Media ad ${row.id}`, type: `${row.creative_type}_ASSOCIATION`, status: row.deleted ? "DISASSOCIATED" : row.entity_status, headlines: [], descriptions: [], landing_urls: destination3 ? [destination3] : [], media: matching ? this.visual(source) : [], actions: row.deleted ? [] : [{ label: "Remove from ad group", tool: "x_delete_media_creative", arguments: { account_id: input.account_id, media_creative_id: row.id, expected_context_hash: this.associationHash(input.account_id, row, parent.snapshot) }, fields: [] }] };
2766
+ });
2767
+ return { items: result.data.map((row) => ({ ...row, context_hash: this.associationHash(input.account_id, row, parent.snapshot) })), parent: parent.snapshot, creatives, warnings, notes: ["Native ACTIVE is association state, not evidence of ad delivery. Removing an association retains its Account Media source.", "Preroll CTA settings are separate; this gallery does not infer a preroll destination from landing_url."], ...this.paging(result.data.map((row) => row.id), result.next_cursor, input.cursor) };
2768
+ }
2769
+ unconfirmed(error, known) {
2770
+ const previous = error instanceof AdportError14 && error.details && typeof error.details === "object" && "resource_ids" in error.details && Array.isArray(error.details.resource_ids) ? error.details.resource_ids.filter((value) => typeof value === "string" && xId.safeParse(value).success) : [];
2771
+ throw new AdportError14("PROVIDER_ERROR", "x: direct-media association outcome was not confirmed. Reconcile known IDs and current inventory before another mutation; no write was retried.", { resource_ids: [.../* @__PURE__ */ new Set([...known, ...previous])] });
2772
+ }
2773
+ async plan(op, guard) {
2774
+ const account = xId.parse(op.accountId), create = op.tool === "x_create_media_creative";
2775
+ if (op.provider !== "x" || op.kind !== (create ? "create" : "remove")) throw new AdportError14("INVALID_INPUT", "x: direct-media operation provider/kind mismatch");
2776
+ const review = (title, fields, notes3) => ({ summary: title, changes: fields.map((field) => `${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes: notes3, review: { provider: "x", accountId: account, kind: op.kind, title, fields, notices: notes3 } });
2777
+ if (create) {
2778
+ const { expected_context_hash, acknowledge_active_association: _ack, ...input2 } = createDirectMedia.parse(op.payload), context = await this.context(account, input2);
2779
+ if (context.context_hash !== expected_context_hash) throw new AdportError14("PENDING_MISMATCH", "x: media source/parent/destination/association context changed; read and preview again");
2780
+ if (context.existing.some((row) => row.account_media_id === input2.account_media_id)) throw new AdportError14("INVALID_INPUT", "x: this Account Media already has a live association in the ad group; do not replay creation");
2781
+ if (guard.forcePausedCreation && context.parent.line.entity_status !== "PAUSED") throw new AdportError14("POLICY_VIOLATION", "x: native associations are ACTIVE; paused_creation requires a currently PAUSED ad group");
2782
+ const preview = review("Associate direct media", [{ label: "Account Media", after: input2.account_media_id }, { label: "Format", after: String(context.source.creative_type) }, { label: "Ad group", after: input2.line_item_id }, { label: "Campaign", after: context.parent.campaign.id }, { label: "Native association status", after: "ACTIVE" }, { label: "Parent delivery", after: String(context.parent.line.entity_status) }, { label: "Display destination", after: input2.landing_url ?? (context.source.creative_type === "PREROLL" ? "Separate preroll CTA settings" : "Native default") }], context.notes);
2783
+ const budgetDeltas = [context.parent.campaign, context.parent.line].flatMap((entity) => ["daily_budget_amount_local_micro", "total_budget_amount_local_micro"].flatMap((key) => {
2784
+ const value = entity[key];
2785
+ return typeof value === "number" ? [{ target: `${entity.id} ${key} existing pool`, currency: context.parent.campaign.currency, fromMicros: value, toMicros: value }] : [];
2786
+ }));
2787
+ return { ...preview, budgetDeltas, execute: async () => {
2788
+ const known = [];
2789
+ try {
2790
+ const row = (await this.entities.client.request("POST", `${this.base(account)}/media_creatives`, z25.object({ data: nativeDirectMedia }), input2)).data;
2791
+ known.push(row.id);
2792
+ this.scope(account, row);
2793
+ if (context.existing.some((prior) => prior.id === row.id) || row.deleted || row.entity_status !== "ACTIVE" || row.line_item_id !== input2.line_item_id || row.account_media_id !== input2.account_media_id || row.creative_type !== context.source.creative_type || input2.landing_url !== void 0 && row.landing_url !== input2.landing_url) throw new Error("Association receipt differs");
2794
+ const observed = await this.get(account, row.id), afterSource = await this.getAsset(account, input2.account_media_id);
2795
+ if (!equal4(associationConfiguration(row), associationConfiguration(observed)) || !equal4(observed.parent, context.parent) || !equal4(configuration3(afterSource), context.source)) throw new Error("Association readback/source differs");
2796
+ return [row.id];
2797
+ } catch (error) {
2798
+ return this.unconfirmed(error, known);
2799
+ }
2800
+ } };
2801
+ }
2802
+ if (op.tool !== "x_delete_media_creative") throw new AdportError14("INVALID_INPUT", "x: unsupported direct-media operation");
2803
+ const input = deleteDirectMedia.parse(op.payload), current = await this.get(account, input.media_creative_id);
2804
+ if (current.deleted || current.context_hash !== input.expected_context_hash) throw new AdportError14("PENDING_MISMATCH", "x: media association/parent changed or was deleted; read and preview again");
2805
+ return { ...review("Remove media from ad group", [{ label: "Association", after: current.id }, { label: "Account Media retained", after: current.account_media_id }, { label: "Ad group", after: current.line_item_id }, { label: "Deleted", before: false, after: true }], ["Removes this one serving association. Its Account Media source, library media, posts, other associations and parent status/budgets are retained.", "Native entity_status may remain ACTIVE on the deleted tombstone. This is not source deletion or a PUT pause.", notice2]), execute: async () => {
2806
+ const known = [current.id];
2807
+ try {
2808
+ const receipt = (await this.entities.client.request("DELETE", `${this.base(account)}/media_creatives/${current.id}`, z25.object({ data: nativeDirectMedia }))).data;
2809
+ known.push(receipt.id);
2810
+ this.scope(account, receipt);
2811
+ const matches2 = (row) => row.id === current.id && row.line_item_id === current.line_item_id && row.account_media_id === current.account_media_id && row.creative_type === current.creative_type && (row.landing_url ?? null) === (current.landing_url ?? null) && row.deleted;
2812
+ const observed = await this.get(account, current.id);
2813
+ if (!matches2(receipt) || !matches2(observed) || !equal4(observed.parent, current.parent)) throw new Error("Disassociation receipt/readback differs");
2814
+ return [current.id];
2815
+ } catch (error) {
2816
+ return this.unconfirmed(error, known);
2817
+ }
2818
+ } };
2819
+ }
2820
+ };
2821
+
2822
+ // src/preroll-cta.ts
2823
+ import { createHash as createHash7 } from "crypto";
2824
+ import { AdportError as AdportError15 } from "@adport/core";
2825
+ import { z as z27 } from "zod";
2826
+
2827
+ // src/preroll-cta-schemas.ts
2828
+ import { z as z26 } from "zod";
2829
+ var prerollCtaValues = ["GO_TO", "SEE_MORE", "SHOP", "VISIT_SITE", "WATCH_NOW"];
2830
+ var prerollCtaLabels = { GO_TO: "Go to", SEE_MORE: "See more", SHOP: "Shop", VISIT_SITE: "Visit site", WATCH_NOW: "Watch now" };
2831
+ var hash8 = z26.string().regex(/^[a-f0-9]{64}$/);
2832
+ var button = z26.enum(prerollCtaValues);
2833
+ var destination2 = z26.string().url().max(4096).refine((value) => {
2834
+ const url3 = new URL(value);
2835
+ return ["http:", "https:"].includes(url3.protocol) && !url3.username && !url3.password && !/[\x00-\x1f\x7f]/.test(value);
2836
+ }, "Use an HTTP(S) destination without embedded credentials or control characters");
2837
+ var nativePrerollCta = z26.object({ id: xId, line_item_id: xId, call_to_action: z26.string().min(1), call_to_action_url: z26.string(), deleted: z26.boolean(), account_id: xId.optional() });
2838
+ var prerollCtaList = z26.object({ account_id: xId, line_item_id: xId.optional(), count: z26.number().int().min(1).max(50).default(20), cursor: z26.string().min(1).max(4096).optional(), with_deleted: z26.boolean().default(false) }).strict();
2839
+ var prerollCtaSelection = z26.object({ line_item_id: xId, call_to_action: button, call_to_action_url: destination2 }).strict();
2840
+ var createPrerollCta = prerollCtaSelection.extend({ expected_context_hash: hash8, acknowledge_ad_group_scope: z26.literal(true) }).strict();
2841
+ var updatePrerollCta = z26.object({ preroll_call_to_action_id: xId, expected_context_hash: hash8, acknowledge_ad_group_scope: z26.literal(true), call_to_action: button.optional(), call_to_action_url: destination2.optional() }).strict().refine((input) => input.call_to_action !== void 0 || input.call_to_action_url !== void 0, "Provide a CTA button or destination change");
2842
+ var deletePrerollCta = z26.object({ preroll_call_to_action_id: xId, expected_context_hash: hash8, acknowledge_ad_group_scope: z26.literal(true) }).strict();
2843
+ var prerollCtaWrites = /* @__PURE__ */ new Set(["x_create_preroll_cta", "x_update_preroll_cta", "x_delete_preroll_cta"]);
2844
+
2845
+ // src/preroll-cta.ts
2846
+ var pageSchema4 = z27.object({ data: z27.array(nativePrerollCta).max(1e3), next_cursor: z27.string().nullable().optional() });
2847
+ var canonical7 = (value) => Array.isArray(value) ? value.map(canonical7) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical7(item)])) : value;
2848
+ var hash9 = (value) => createHash7("sha256").update(JSON.stringify(canonical7(value))).digest("hex");
2849
+ var equal5 = (left, right) => hash9(left) === hash9(right);
2850
+ var config2 = (row) => ({ id: row.id, line_item_id: row.line_item_id, call_to_action: row.call_to_action, call_to_action_url: row.call_to_action_url, deleted: row.deleted });
2851
+ var configs = (rows2) => rows2.map(config2).sort((a, b) => a.id.localeCompare(b.id));
2852
+ var label = (value) => prerollCtaLabels[value] ?? value;
2853
+ var safeDestination = (value) => {
2854
+ try {
2855
+ const url3 = new URL(value);
2856
+ return ["http:", "https:"].includes(url3.protocol) && !url3.username && !url3.password && !/[\x00-\x1f\x7f]/.test(value) ? value : void 0;
2857
+ } catch {
2858
+ return void 0;
2859
+ }
2860
+ };
2861
+ var notices2 = ["CTA settings belong to the ad group and can affect all of its current and future preroll ads, not just one media association. Associated ads are not enumerated or frozen by this snapshot.", "CTA presence is not proof of ad delivery or native placement rendering. Parent status, budgets, bids, media and ad associations are preserved.", "Local preview is not native validation. Snapshots do not atomically lock native concurrent changes; no mutation is automatically retried."];
2862
+ var XPrerollCtaService = class {
2863
+ constructor(entities, posts) {
2864
+ this.entities = entities;
2865
+ this.posts = posts;
2866
+ }
2867
+ entities;
2868
+ posts;
2869
+ base(account) {
2870
+ return `accounts/${xId.parse(account)}/preroll_call_to_actions`;
2871
+ }
2872
+ scope(account, row, id, line) {
2873
+ if (row.account_id !== void 0 && row.account_id !== account || id !== void 0 && row.id !== id || line !== void 0 && row.line_item_id !== line) throw new AdportError15("PROVIDER_ERROR", "x: preroll CTA account/resource/ad-group mismatch");
2874
+ return row;
2875
+ }
2876
+ paging(ids3, next, previous) {
2877
+ if (new Set(ids3).size !== ids3.length || next && next === previous) throw new AdportError15("PROVIDER_ERROR", "x: preroll CTA pagination repeated an ID or cursor");
2878
+ return { truncated: next !== null, ...next ? { next_cursor: next } : {}, ...next === void 0 || next === "" ? { notes: ["Native continuation marker is missing; completeness is unconfirmed."] } : {} };
2879
+ }
2880
+ async page(account, line, count, withDeleted, cursor2) {
2881
+ const result = await this.entities.client.request("GET", this.base(account), pageSchema4, { ...line ? { line_item_ids: line } : {}, count, with_deleted: withDeleted, ...cursor2 ? { cursor: cursor2 } : {} });
2882
+ if (result.data.length > count) throw new AdportError15("PROVIDER_ERROR", "x: preroll CTA page exceeds its requested bound");
2883
+ for (const row of result.data) {
2884
+ this.scope(account, row, void 0, line);
2885
+ if (!withDeleted && row.deleted) throw new AdportError15("PROVIDER_ERROR", "x: preroll CTA deletion filter mismatch");
2886
+ }
2887
+ this.paging(result.data.map((row) => row.id), result.next_cursor, cursor2);
2888
+ return result;
2889
+ }
2890
+ async inventory(account, line) {
2891
+ const rows2 = [], ids3 = /* @__PURE__ */ new Set(), cursors = /* @__PURE__ */ new Set();
2892
+ let cursor2;
2893
+ for (let page5 = 0; page5 < 10; page5++) {
2894
+ const result = await this.page(account, line, 200, false, cursor2);
2895
+ for (const row of result.data) {
2896
+ if (ids3.has(row.id)) throw new AdportError15("PROVIDER_ERROR", "x: preroll CTA inventory repeated an ID");
2897
+ ids3.add(row.id);
2898
+ rows2.push(row);
2899
+ }
2900
+ if (result.next_cursor === null) return configs(rows2);
2901
+ if (!result.next_cursor || cursors.has(result.next_cursor)) break;
2902
+ cursor2 = result.next_cursor;
2903
+ cursors.add(cursor2);
2904
+ }
2905
+ throw new AdportError15("PROVIDER_ERROR", "x: preroll CTA inventory is incomplete; no mutation submitted");
2906
+ }
2907
+ contextHash(account, row, parent, active) {
2908
+ return hash9({ account_id: account, cta: config2(row), parent, active_ctas: configs(active) });
2909
+ }
2910
+ card(account, row, parent, contextHash) {
2911
+ const options = prerollCtaValues.map((value) => ({ value, label: prerollCtaLabels[value] }));
2912
+ const fields = [...prerollCtaValues.includes(row.call_to_action) ? [{ key: "call_to_action", label: "Button", type: "select", value: row.call_to_action, options }] : [], { key: "call_to_action_url", label: "Destination", type: "text", value: row.call_to_action_url, max_length: 4096 }];
2913
+ const args = { account_id: account, preroll_call_to_action_id: row.id, expected_context_hash: contextHash, acknowledge_ad_group_scope: true };
2914
+ const destination3 = safeDestination(row.call_to_action_url);
2915
+ const actions = row.deleted || !parent || !contextHash ? [] : [...this.canAuthor(parent) ? [{ label: "Edit CTA", tool: "x_update_preroll_cta", arguments: args, fields }] : [], { label: "Remove CTA", tool: "x_delete_preroll_cta", arguments: args, fields: [] }];
2916
+ return { id: row.id, provider: "x", account_id: account, ...parent ? { campaign_id: parent.campaign.id } : {}, ad_group_id: row.line_item_id, name: `Preroll CTA ${row.id}`, type: "PREROLL_CTA", status: row.deleted ? "DELETED" : "PRESENT", headlines: [label(row.call_to_action)], descriptions: [], landing_urls: destination3 ? [destination3] : [], media: [], actions };
2917
+ }
2918
+ canAuthor(parent) {
2919
+ return !parent.line.deleted && !parent.campaign.deleted && ["ACTIVE", "PAUSED"].includes(String(parent.line.entity_status)) && ["ACTIVE", "PAUSED"].includes(parent.campaign.entity_status) && parent.line.objective === "PREROLL_VIEWS";
2920
+ }
2921
+ eligible(parent) {
2922
+ if (!this.canAuthor(parent)) throw new AdportError15("INVALID_INPUT", "x: preroll CTA authoring needs an existing non-draft PREROLL_VIEWS ad group and campaign");
2923
+ }
2924
+ async context(account, raw) {
2925
+ const input = prerollCtaSelection.parse(raw), parent = (await this.posts.parents(account, input.line_item_id)).snapshot;
2926
+ this.eligible(parent);
2927
+ const active = await this.inventory(account, input.line_item_id), context = { account_id: account, request: input, parent, active_ctas: active };
2928
+ return { ...context, context_hash: hash9(context), cta_options: prerollCtaValues.map((value) => ({ value, label: label(value) })), notes: ["Native POST sets the ad group CTA. Existing active CTA settings must be updated explicitly; this workflow refuses an implicit replacement.", "Under paused_creation, setting a new CTA requires a currently PAUSED ad group.", ...notices2] };
2929
+ }
2930
+ async get(account, id) {
2931
+ await this.entities.getAccount(account);
2932
+ const row = this.scope(account, (await this.entities.client.request("GET", `${this.base(account)}/${xId.parse(id)}`, z27.object({ data: nativePrerollCta }), { with_deleted: true })).data, id);
2933
+ const parent = (await this.posts.parents(account, row.line_item_id)).snapshot, active = await this.inventory(account, row.line_item_id);
2934
+ if (!row.deleted && !active.some((item) => equal5(item, config2(row))) || row.deleted && active.some((item) => item.id === row.id)) throw new AdportError15("PROVIDER_ERROR", "x: preroll CTA exact record differs from its current active inventory");
2935
+ const contextHash = this.contextHash(account, row, parent, active);
2936
+ return { ...row, parent, active_ctas: active, context_hash: contextHash, creatives: [this.card(account, row, parent, contextHash)], truncated: false, notes: notices2 };
2937
+ }
2938
+ async list(raw) {
2939
+ const input = prerollCtaList.parse(raw), parent = input.line_item_id ? (await this.posts.parents(input.account_id, input.line_item_id)).snapshot : void 0;
2940
+ if (!parent) await this.entities.getAccount(input.account_id);
2941
+ const result = await this.page(input.account_id, input.line_item_id, input.count, input.with_deleted, input.cursor);
2942
+ const warnings = [];
2943
+ let active;
2944
+ if (parent && input.line_item_id && result.data.some((row) => !row.deleted)) try {
2945
+ active = await this.inventory(input.account_id, input.line_item_id);
2946
+ } catch {
2947
+ warnings.push("Complete CTA context could not be read. These settings remain visible without edit/removal actions; inspect the exact CTA before changing it.");
2948
+ }
2949
+ const records = result.data.map((row) => {
2950
+ const matched = active?.some((item) => equal5(item, config2(row))), contextHash = matched && active && parent ? this.contextHash(input.account_id, row, parent, active) : void 0;
2951
+ if (active && !row.deleted && !matched) warnings.push(`CTA ${row.id} changed during this read; its edit actions are unavailable.`);
2952
+ return { row, contextHash };
2953
+ });
2954
+ const paging = this.paging(result.data.map((row) => row.id), result.next_cursor, input.cursor);
2955
+ return { items: records.map(({ row, contextHash }) => ({ ...row, ...contextHash ? { context_hash: contextHash } : {} })), ...parent ? { parent } : {}, creatives: records.map(({ row, contextHash }) => this.card(input.account_id, row, parent, contextHash)), warnings, ...paging, notes: [...notices2, ...paging.notes ?? []] };
2956
+ }
2957
+ unconfirmed(error, known) {
2958
+ const prior = error instanceof AdportError15 && error.details && typeof error.details === "object" && "resource_ids" in error.details && Array.isArray(error.details.resource_ids) ? error.details.resource_ids.filter((id) => typeof id === "string" && xId.safeParse(id).success) : [];
2959
+ throw new AdportError15("PROVIDER_ERROR", "x: preroll CTA outcome was not confirmed. Reconcile known IDs and current ad-group settings before another mutation; no write was retried.", { resource_ids: [.../* @__PURE__ */ new Set([...known, ...prior])] });
2960
+ }
2961
+ async plan(op, guard) {
2962
+ const account = xId.parse(op.accountId), create = op.tool === "x_create_preroll_cta", update = op.tool === "x_update_preroll_cta", remove = op.tool === "x_delete_preroll_cta";
2963
+ if (op.provider !== "x" || !create && !update && !remove || op.kind !== (create ? "create" : update ? "update" : "remove")) throw new AdportError15("INVALID_INPUT", "x: preroll CTA operation provider/kind mismatch");
2964
+ const review = (title, parent, fields2) => {
2965
+ const scope = [{ label: "Ad group", after: String(parent.line.name ?? parent.line.id) }, { label: "Parent delivery", after: String(parent.line.entity_status) }, { label: "Scope", after: "All preroll ads in this ad group" }];
2966
+ const notes3 = remove ? ["Removing a CTA does not pause preroll ads. Media and ad associations remain.", ...notices2] : notices2;
2967
+ return { summary: title, changes: [...fields2, ...scope].map((field) => `${field.label}: ${JSON.stringify(field.before)} \u2192 ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes: notes3, review: { provider: "x", accountId: account, kind: op.kind, title, fields: [...fields2, ...scope], notices: notes3 } };
2968
+ };
2969
+ if (create) {
2970
+ const { expected_context_hash, acknowledge_ad_group_scope: _ack, ...input2 } = createPrerollCta.parse(op.payload), context = await this.context(account, input2);
2971
+ if (context.context_hash !== expected_context_hash) throw new AdportError15("PENDING_MISMATCH", "x: preroll CTA creation context changed; read and preview again");
2972
+ if (context.active_ctas.length) throw new AdportError15("INVALID_INPUT", "x: the ad group already has active CTA settings; use an explicit CTA update");
2973
+ if (guard.forcePausedCreation && context.parent.line.entity_status !== "PAUSED") throw new AdportError15("POLICY_VIOLATION", "x: paused_creation requires a currently PAUSED ad group before setting a new CTA");
2974
+ const preview = review("Set preroll CTA", context.parent, [{ label: "Button", after: label(input2.call_to_action) }, { label: "Destination", after: input2.call_to_action_url }]);
2975
+ const budgetDeltas = [context.parent.line, context.parent.campaign].flatMap((entity) => ["daily_budget_amount_local_micro", "total_budget_amount_local_micro"].flatMap((key) => {
2976
+ const amount = entity[key];
2977
+ return typeof amount === "number" ? [{ target: `${entity.id} ${key} existing pool`, currency: context.parent.campaign.currency, fromMicros: amount, toMicros: amount }] : [];
2978
+ }));
2979
+ return { ...preview, budgetDeltas, execute: async () => {
2980
+ const known = [];
2981
+ try {
2982
+ const row = (await this.entities.client.request("POST", this.base(account), z27.object({ data: nativePrerollCta }), input2)).data;
2983
+ known.push(row.id);
2984
+ this.scope(account, row);
2985
+ const expected2 = { ...input2, id: row.id, deleted: false };
2986
+ if (!equal5(config2(row), expected2)) throw new Error("CTA creation receipt differs");
2987
+ const observed = await this.get(account, row.id);
2988
+ if (!equal5(config2(observed), expected2) || !equal5(observed.parent, context.parent) || !equal5(observed.active_ctas, [expected2])) throw new Error("CTA creation readback differs");
2989
+ return [row.id];
2990
+ } catch (error) {
2991
+ return this.unconfirmed(error, known);
2992
+ }
2993
+ } };
2994
+ }
2995
+ const input = update ? updatePrerollCta.parse(op.payload) : deletePrerollCta.parse(op.payload), current = await this.get(account, input.preroll_call_to_action_id);
2996
+ if (current.deleted || current.context_hash !== input.expected_context_hash) throw new AdportError15("PENDING_MISMATCH", "x: preroll CTA or parent/inventory context changed or was deleted; read and preview again");
2997
+ if (update) this.eligible(current.parent);
2998
+ const patch = {};
2999
+ if (update) {
3000
+ const edit = updatePrerollCta.parse(op.payload);
3001
+ for (const key of ["call_to_action", "call_to_action_url"]) if (edit[key] !== void 0 && edit[key] !== current[key]) patch[key] = edit[key];
3002
+ if (!Object.keys(patch).length) throw new AdportError15("INVALID_INPUT", "x: change the CTA button or destination before requesting a preview");
3003
+ }
3004
+ const expected = { ...config2(current), ...patch, deleted: remove }, expectedActive = current.active_ctas.flatMap((row) => row.id === current.id ? remove ? [] : [expected] : [row]);
3005
+ const fields = update ? Object.entries(patch).map(([key, value]) => ({ label: key === "call_to_action" ? "Button" : "Destination", before: key === "call_to_action" ? label(current.call_to_action) : current.call_to_action_url, after: key === "call_to_action" ? label(value) : value })) : [{ label: "CTA", after: current.id }, { label: "Button", before: label(current.call_to_action), after: "(removed)" }, { label: "Destination", before: current.call_to_action_url, after: "(removed)" }];
3006
+ return { ...review(update ? "Edit preroll CTA" : "Remove preroll CTA", current.parent, fields), execute: async () => {
3007
+ const known = [current.id];
3008
+ try {
3009
+ const row = (await this.entities.client.request(update ? "PUT" : "DELETE", `${this.base(account)}/${current.id}`, z27.object({ data: nativePrerollCta }), patch)).data;
3010
+ known.push(row.id);
3011
+ this.scope(account, row);
3012
+ if (!equal5(config2(row), expected)) throw new Error("CTA edit/removal receipt differs");
3013
+ const observed = await this.get(account, current.id);
3014
+ if (!equal5(config2(observed), expected) || !equal5(observed.parent, current.parent) || !equal5(observed.active_ctas, configs(expectedActive))) throw new Error("CTA edit/removal readback differs");
3015
+ return [current.id];
3016
+ } catch (error) {
3017
+ return this.unconfirmed(error, known);
3018
+ }
3019
+ } };
3020
+ }
3021
+ };
3022
+
3023
+ // src/account-media.ts
3024
+ import { createHash as createHash8 } from "crypto";
3025
+ import { AdportError as AdportError16 } from "@adport/core";
3026
+ import { z as z29 } from "zod";
3027
+
3028
+ // src/account-media-schemas.ts
3029
+ import { z as z28 } from "zod";
3030
+ var accountMediaIdentity = z28.object({ account_id: xId, account_media_id: xId }).strict();
3031
+ var accountMediaUsage = accountMediaIdentity.extend({ reference_offset: z28.number().int().min(0).max(9999).default(0), reference_limit: z28.number().int().min(1).max(100).default(50), expected_context_hash: z28.string().regex(/^[a-f0-9]{64}$/).optional() }).strict().refine((input) => input.reference_offset === 0 || input.expected_context_hash !== void 0, "Later reference pages require the original context hash");
3032
+ var deleteAccountMedia = z28.object({ account_media_id: xId, expected_context_hash: z28.string().regex(/^[a-f0-9]{64}$/), acknowledge_source_deletion: z28.literal(true) }).strict();
3033
+
3034
+ // src/account-media.ts
3035
+ var page4 = z29.object({ data: z29.array(nativeDirectMedia).max(1e3), next_cursor: z29.string().nullable().optional() });
3036
+ var canonical8 = (value) => Array.isArray(value) ? value.map(canonical8) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical8(item)])) : value;
3037
+ var hash10 = (value) => createHash8("sha256").update(JSON.stringify(canonical8(value))).digest("hex");
3038
+ var configuration4 = (row) => Object.fromEntries(Object.entries(row).filter(([key]) => !["created_at", "updated_at", "account_id", "configuration_hash"].includes(key)));
3039
+ var reference = (row) => ({ id: row.id, line_item_id: row.line_item_id, account_media_id: row.account_media_id, creative_type: row.creative_type, landing_url: row.landing_url ?? null, entity_status: row.entity_status, deleted: row.deleted });
3040
+ var XAccountMediaService = class {
3041
+ constructor(entities, media) {
3042
+ this.entities = entities;
3043
+ this.media = media;
3044
+ }
3045
+ entities;
3046
+ media;
3047
+ async references(account, source) {
3048
+ const references = [], ids3 = /* @__PURE__ */ new Set(), cursors = /* @__PURE__ */ new Set();
3049
+ let cursor2;
3050
+ for (let index = 0; index < 10; index++) {
3051
+ const result = await this.entities.client.request("GET", `accounts/${account}/media_creatives`, page4, { count: 1e3, with_deleted: true, ...cursor2 ? { cursor: cursor2 } : {} });
3052
+ for (const row of result.data) {
3053
+ if (row.account_id !== void 0 && row.account_id !== account || ids3.has(row.id)) throw new AdportError16("PROVIDER_ERROR", "x: Account Media usage scan returned a different account or repeated association");
3054
+ ids3.add(row.id);
3055
+ if (row.account_media_id === source) references.push(row);
3056
+ }
3057
+ if (result.next_cursor === null) return { references: references.sort((a, b) => a.id.localeCompare(b.id)), scanned_associations: ids3.size };
3058
+ if (!result.next_cursor || cursors.has(result.next_cursor)) break;
3059
+ cursors.add(result.next_cursor);
3060
+ cursor2 = result.next_cursor;
3061
+ }
3062
+ throw new AdportError16("PROVIDER_ERROR", "x: Account Media usage is incomplete; no source deletion is permitted. Reconcile the account inventory before trying again.");
3063
+ }
3064
+ async context(account, id) {
3065
+ xId.parse(account);
3066
+ xId.parse(id);
3067
+ const asset = await this.media.getAsset(account, id), inventory = await this.references(account, id), references = inventory.references.map(reference), active = references.filter((row) => !row.deleted);
3068
+ const context_hash = hash10({ account_id: account, source: configuration4(asset), references }), can_delete = !asset.deleted && active.length === 0, creative = this.media.assetCard(account, asset);
3069
+ if (can_delete) creative.actions = [{ label: "Delete asset", tool: "x_delete_account_media", arguments: { account_id: account, account_media_id: id, expected_context_hash: context_hash, acknowledge_source_deletion: true }, fields: [] }];
3070
+ const notes3 = ["Account Media is a native source asset, distinct from media-library keys, upload receipts and Adport project files.", "Detach every non-deleted media_creative reference before source deletion, including references under deleted or paused parents. Each disassociation has its own preview/apply approval.", "The complete bounded account-wide association scan is a snapshot, not an atomic native lock. Reconcile unknown outcomes; no mutation is retried."];
3071
+ return { asset, references, non_deleted_references: active.length, can_delete, context_hash, scanned_associations: inventory.scanned_associations, truncated: false, creatives: [creative], notes: notes3 };
3072
+ }
3073
+ async usage(account, id, options = {}) {
3074
+ const input = accountMediaUsage.parse({ ...options, account_id: account, account_media_id: id }), context = await this.context(account, id);
3075
+ if (input.expected_context_hash !== void 0 && input.expected_context_hash !== context.context_hash) throw new AdportError16("PENDING_MISMATCH", "x: Account Media reference pages changed; inspect usage again from the first page");
3076
+ const end = input.reference_offset + input.reference_limit;
3077
+ return { ...context, references: context.references.slice(input.reference_offset, end), reference_total: context.references.length, reference_offset: input.reference_offset, usage_complete: true, references_truncated: end < context.references.length, ...end < context.references.length ? { next_reference_offset: end } : {} };
3078
+ }
3079
+ async plan(op) {
3080
+ if (op.provider !== "x" || op.kind !== "remove" || op.tool !== "x_delete_account_media") throw new AdportError16("INVALID_INPUT", "x: unsupported Account Media source operation");
3081
+ const account = xId.parse(op.accountId), input = deleteAccountMedia.parse(op.payload), context = await this.context(account, input.account_media_id);
3082
+ if (context.asset.deleted || context.context_hash !== input.expected_context_hash) throw new AdportError16("PENDING_MISMATCH", "x: Account Media source or usage changed; inspect usage and preview again");
3083
+ if (!context.can_delete) throw new AdportError16("INVALID_INPUT", "x: Account Media still has non-deleted ad associations. Review and detach each association before deleting its source.");
3084
+ const fields = [{ label: "Account Media", after: context.asset.id }, { label: "Format", after: context.asset.creative_type }, { label: "Non-deleted ad associations", after: 0 }, { label: "Deleted", before: false, after: true }];
3085
+ const notes3 = [...context.notes, "Deletes this one Account Media source. No media-library/project-file deletion, ad disassociation, parent status/budget change or publication request is sent. This is source deletion, not a reversible ad pause."];
3086
+ return { summary: `Delete Account Media ${context.asset.id}`, changes: fields.map((field) => `${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes: notes3, review: { provider: "x", accountId: account, kind: "remove", title: "Delete Account Media", fields, notices: notes3 }, execute: async () => {
3087
+ const known = [context.asset.id];
3088
+ try {
3089
+ const row = (await this.entities.client.request("DELETE", `accounts/${account}/account_media/${context.asset.id}`, z29.object({ data: nativeAccountMedia }))).data;
3090
+ known.push(row.id);
3091
+ if (row.account_id !== void 0 && row.account_id !== account || hash10(configuration4(row)) !== hash10(configuration4({ ...context.asset, deleted: true }))) throw new Error("Source deletion receipt differs");
3092
+ const after = await this.context(account, context.asset.id);
3093
+ if (hash10(configuration4(after.asset)) !== hash10(configuration4(row)) || hash10(after.references) !== hash10(context.references)) throw new Error("Source deletion readback or references differ");
3094
+ return [context.asset.id];
3095
+ } catch (error) {
3096
+ const prior = error instanceof AdportError16 && error.details && typeof error.details === "object" && "resource_ids" in error.details && Array.isArray(error.details.resource_ids) ? error.details.resource_ids.filter((id) => typeof id === "string" && xId.safeParse(id).success) : [];
3097
+ throw new AdportError16("PROVIDER_ERROR", "x: Account Media source deletion was not confirmed. Inspect the known source ID and association inventory before another mutation; no DELETE was retried.", { resource_ids: [.../* @__PURE__ */ new Set([...known, ...prior])] });
3098
+ }
3099
+ } };
3100
+ }
3101
+ };
3102
+
3103
+ // src/promoted-accounts.ts
3104
+ import { createHash as createHash9 } from "crypto";
3105
+ import { AdportError as AdportError17 } from "@adport/core";
3106
+ import { z as z31 } from "zod";
3107
+
3108
+ // src/promoted-account-schemas.ts
3109
+ import { z as z30 } from "zod";
3110
+ var hash11 = z30.string().regex(/^[a-f0-9]{64}$/);
3111
+ var nativePromotedAccount = promotedAccountSchema.extend({ user_id: snowflake, account_id: xId.optional(), approval_status: z30.string().optional() });
3112
+ var promotedAccountList = z30.object({ account_id: xId, line_item_id: xId, count: z30.number().int().min(1).max(50).default(20), cursor: z30.string().min(1).max(4096).optional(), with_deleted: z30.boolean().default(false) }).strict();
3113
+ var promotedAccountSelection = z30.object({ line_item_id: xId, user_id: snowflake }).strict();
3114
+ var createPromotedAccount = promotedAccountSelection.extend({ expected_context_hash: hash11, acknowledge_active_association: z30.literal(true), acknowledge_live_profile: z30.literal(true) }).strict();
3115
+ var deletePromotedAccount = z30.object({ promoted_account_id: xId, expected_context_hash: hash11 }).strict();
3116
+ var promotedAccountWrites = /* @__PURE__ */ new Set(["x_create_promoted_account", "x_delete_promoted_account"]);
3117
+
3118
+ // src/promoted-accounts.ts
3119
+ var pageSchema5 = z31.object({ data: z31.array(nativePromotedAccount).max(1e3), next_cursor: z31.string().nullable().optional() });
3120
+ var canonical9 = (value) => Array.isArray(value) ? value.map(canonical9) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical9(item)])) : value;
3121
+ var hash12 = (value) => createHash9("sha256").update(JSON.stringify(canonical9(value))).digest("hex");
3122
+ var configuration5 = (row) => ({ id: row.id, line_item_id: row.line_item_id, user_id: row.user_id, entity_status: row.entity_status, deleted: row.deleted });
3123
+ var equal6 = (a, b) => hash12(a) === hash12(b);
3124
+ var notice3 = "Local preview is not X validation. Native eligibility remains authoritative, and no write is retried automatically.";
3125
+ var XPromotedAccountService = class {
3126
+ constructor(entities, creatives, posts) {
3127
+ this.entities = entities;
3128
+ this.creatives = creatives;
3129
+ this.posts = posts;
3130
+ }
3131
+ entities;
3132
+ creatives;
3133
+ posts;
3134
+ base(account) {
3135
+ return `accounts/${xId.parse(account)}`;
3136
+ }
3137
+ scope(account, row, id, line) {
3138
+ if (row.account_id !== void 0 && row.account_id !== account || id !== void 0 && row.id !== id || line !== void 0 && row.line_item_id !== line) throw new AdportError17("PROVIDER_ERROR", "x: promoted-account resource/account/ad-group mismatch");
3139
+ return row;
3140
+ }
3141
+ paging(ids3, next, previous) {
3142
+ if (new Set(ids3).size !== ids3.length || next && next === previous) throw new AdportError17("PROVIDER_ERROR", "x: promoted-account pagination repeated an ID or cursor");
3143
+ return { truncated: next !== null, ...next ? { next_cursor: next } : {}, ...next === void 0 || next === "" ? { notes: ["Native continuation marker is missing; completeness is unconfirmed."] } : {} };
3144
+ }
3145
+ async page(account, line, params) {
3146
+ const result = await this.entities.client.request("GET", `${this.base(account)}/promoted_accounts`, pageSchema5, { line_item_ids: line, ...params });
3147
+ for (const row of result.data) {
3148
+ this.scope(account, row, void 0, line);
3149
+ if (params.with_deleted === false && row.deleted) throw new AdportError17("PROVIDER_ERROR", "x: promoted-account deletion filter mismatch");
3150
+ }
3151
+ this.paging(result.data.map((row) => row.id), result.next_cursor, typeof params.cursor === "string" ? params.cursor : void 0);
3152
+ return result;
3153
+ }
3154
+ async existing(account, line) {
3155
+ const rows2 = [], ids3 = /* @__PURE__ */ new Set(), cursors = /* @__PURE__ */ new Set();
3156
+ let cursor2;
3157
+ for (let page5 = 0; page5 < 10; page5++) {
3158
+ const result = await this.page(account, line, { count: 200, with_deleted: false, ...cursor2 ? { cursor: cursor2 } : {} });
3159
+ for (const row of result.data) {
3160
+ if (ids3.has(row.id)) throw new AdportError17("PROVIDER_ERROR", "x: promoted-account inventory repeated an ID");
3161
+ ids3.add(row.id);
3162
+ rows2.push(row);
3163
+ }
3164
+ if (result.next_cursor === null) return rows2.sort((a, b) => a.id.localeCompare(b.id));
3165
+ if (!result.next_cursor || cursors.has(result.next_cursor)) break;
3166
+ cursor2 = result.next_cursor;
3167
+ cursors.add(cursor2);
3168
+ }
3169
+ throw new AdportError17("PROVIDER_ERROR", "x: promoted-account inventory is incomplete; no association submitted");
3170
+ }
3171
+ associationHash(account, row, parent) {
3172
+ return hash12({ account_id: account, association: configuration5(row), parent });
3173
+ }
3174
+ async get(account, id) {
3175
+ await this.entities.getAccount(account);
3176
+ const row = this.scope(account, (await this.entities.client.request("GET", `${this.base(account)}/promoted_accounts/${xId.parse(id)}`, z31.object({ data: nativePromotedAccount }), { with_deleted: true })).data, id);
3177
+ const parent = await this.posts.parents(account, row.line_item_id);
3178
+ return { ...row, parent: parent.snapshot, context_hash: this.associationHash(account, row, parent.snapshot) };
3179
+ }
3180
+ card(account, row, parent, removable) {
3181
+ return { id: row.id, provider: "x", account_id: account, campaign_id: String(parent.campaign.id), ad_group_id: row.line_item_id, name: `Promoted account ${row.user_id}`, type: "PROMOTED_ACCOUNT_ASSOCIATION", status: row.deleted ? "DISASSOCIATED" : row.entity_status, headlines: [], descriptions: [`X profile ${row.user_id}`], landing_urls: [`https://x.com/i/user/${row.user_id}`], media: [], actions: removable && !row.deleted ? [{ label: "Remove from ad group", tool: "x_delete_promoted_account", arguments: { account_id: account, promoted_account_id: row.id, expected_context_hash: this.associationHash(account, row, parent) }, fields: [] }] : [] };
3182
+ }
3183
+ async list(raw) {
3184
+ const input = promotedAccountList.parse(raw), parent = await this.posts.parents(input.account_id, input.line_item_id);
3185
+ if (parent.line.product_type !== "PROMOTED_ACCOUNT") throw new AdportError17("INVALID_INPUT", "x: select a PROMOTED_ACCOUNT ad group");
3186
+ const result = await this.page(input.account_id, input.line_item_id, { count: input.count, with_deleted: input.with_deleted, ...input.cursor ? { cursor: input.cursor } : {} });
3187
+ return { items: result.data.map((row) => ({ ...row, context_hash: this.associationHash(input.account_id, row, parent.snapshot) })), parent: parent.snapshot, creatives: result.data.map((row) => this.card(input.account_id, row, parent.snapshot, true)), ...this.paging(result.data.map((row) => row.id), result.next_cursor, input.cursor), warnings: ["Native ACTIVE describes the association, not parent delivery. Profile content is live; this endpoint supplies identity references rather than profile artwork.", ...result.data.length > input.count ? ["X returned more rows than requested; all were retained."] : []] };
3188
+ }
3189
+ async context(account, raw) {
3190
+ const input = promotedAccountSelection.parse(raw), accountState = await this.entities.getAccount(account);
3191
+ if (accountState.deleted) throw new AdportError17("INVALID_INPUT", "x: the selected ad account is deleted");
3192
+ const parent = await this.posts.parents(account, input.line_item_id);
3193
+ if (parent.line.deleted || parent.campaign.deleted || !["ACTIVE", "PAUSED"].includes(parent.line.entity_status) || !["ACTIVE", "PAUSED"].includes(parent.campaign.entity_status) || parent.line.product_type !== "PROMOTED_ACCOUNT" || parent.line.objective !== "FOLLOWERS") throw new AdportError17("INVALID_INPUT", "x: choose an existing non-draft FOLLOWERS/PROMOTED_ACCOUNT ad group and campaign");
3194
+ const users = await this.creatives.users(account, true);
3195
+ if (users.some((row2) => row2.account_id !== void 0 && row2.account_id !== account)) throw new AdportError17("PROVIDER_ERROR", "x: promotable-user account echo mismatch");
3196
+ const matches2 = users.filter((row2) => row2.user_id === input.user_id && !row2.deleted);
3197
+ if (matches2.length !== 1 || matches2[0].promotable_user_type !== "FULL") throw new AdportError17("INVALID_INPUT", "x: select one unambiguous current FULL promotable user from this account");
3198
+ const row = matches2[0], user2 = { id: row.id, user_id: row.user_id, promotable_user_type: row.promotable_user_type, deleted: row.deleted }, existing = await this.existing(account, input.line_item_id);
3199
+ const context = { account_id: account, request: input, user: user2, parent: parent.snapshot, existing: existing.map(configuration5) };
3200
+ return { ...context, context_hash: hash12(context), creatives: [{ id: input.user_id, provider: "x", account_id: account, campaign_id: parent.campaign.id, ad_group_id: input.line_item_id, name: `Profile ${input.user_id}`, type: "PROMOTABLE_PROFILE", status: "FULL", headlines: [], descriptions: [], landing_urls: [`https://x.com/i/user/${input.user_id}`], media: [], actions: [] }], truncated: false, notes: ["Native creation adds an ACTIVE association. paused_creation requires a currently PAUSED ad group; parent delivery and budgets are preserved.", "The promoted identity is bound to this context; live X profile text/artwork is not snapshotted, uploaded or edited. No post is published and no new profile is created.", "Snapshots do not atomically lock concurrent native changes. Reconcile unknown outcomes before another request.", notice3] };
3201
+ }
3202
+ unconfirmed(error, known) {
3203
+ const previous = error instanceof AdportError17 && error.details && typeof error.details === "object" && "resource_ids" in error.details && Array.isArray(error.details.resource_ids) ? error.details.resource_ids.filter((id) => typeof id === "string" && xId.safeParse(id).success) : [];
3204
+ throw new AdportError17("PROVIDER_ERROR", "x: promoted-account association outcome unconfirmed. Inspect known IDs and current inventory before another mutation; no write was retried.", { resource_ids: [.../* @__PURE__ */ new Set([...known, ...previous])] });
3205
+ }
3206
+ async plan(op, guard) {
3207
+ const account = xId.parse(op.accountId), create = op.tool === "x_create_promoted_account";
3208
+ if (op.provider !== "x" || !["x_create_promoted_account", "x_delete_promoted_account"].includes(op.tool) || op.kind !== (create ? "create" : "remove")) throw new AdportError17("INVALID_INPUT", "x: promoted-account operation provider/kind mismatch");
3209
+ const review = (title, fields, notes3) => ({ summary: title, changes: fields.map((field) => `${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes: notes3, review: { provider: "x", accountId: account, kind: op.kind, title, fields, notices: notes3 } });
3210
+ if (create) {
3211
+ const { expected_context_hash, acknowledge_active_association: _active, acknowledge_live_profile: _profile, ...input2 } = createPromotedAccount.parse(op.payload), context = await this.context(account, input2);
3212
+ if (context.context_hash !== expected_context_hash) throw new AdportError17("PENDING_MISMATCH", "x: promoted identity/parent/association context changed; read and preview again");
3213
+ if (context.existing.some((row) => row.user_id === input2.user_id)) throw new AdportError17("INVALID_INPUT", "x: this user is already promoted in the ad group; do not replay creation");
3214
+ if (guard.forcePausedCreation && context.parent.line.entity_status !== "PAUSED") throw new AdportError17("POLICY_VIOLATION", "x: native profile associations are ACTIVE; paused_creation requires a currently PAUSED ad group");
3215
+ const budgetDeltas = [context.parent.campaign, context.parent.line].flatMap((entity) => ["daily_budget_amount_local_micro", "total_budget_amount_local_micro"].flatMap((key) => {
3216
+ const value = entity[key];
3217
+ return typeof value === "number" ? [{ target: `${entity.id} ${key} existing pool`, currency: context.parent.campaign.currency, fromMicros: value, toMicros: value }] : [];
3218
+ }));
3219
+ return { ...review("Promote X account", [{ label: "Profile user ID", after: input2.user_id }, { label: "Ad group", after: input2.line_item_id }, { label: "Campaign", after: context.parent.campaign.id }, { label: "Native association status", after: "ACTIVE" }, { label: "Parent delivery", after: String(context.parent.line.entity_status) }, { label: "Profile content", after: "Live X profile; not snapshotted or edited" }], context.notes), budgetDeltas, execute: async () => {
3220
+ const known = [];
3221
+ try {
3222
+ const row = (await this.entities.client.request("POST", `${this.base(account)}/promoted_accounts`, z31.object({ data: nativePromotedAccount }), input2)).data;
3223
+ known.push(row.id);
3224
+ this.scope(account, row, void 0, input2.line_item_id);
3225
+ if (context.existing.some((prior) => prior.id === row.id) || row.deleted || row.entity_status !== "ACTIVE" || row.user_id !== input2.user_id) throw new Error("Promoted-account receipt differs");
3226
+ const observed = await this.get(account, row.id);
3227
+ if (!equal6(configuration5(row), configuration5(observed)) || !equal6(observed.parent, context.parent)) throw new Error("Promoted-account readback/parent differs");
3228
+ return [row.id];
3229
+ } catch (error) {
3230
+ return this.unconfirmed(error, known);
3231
+ }
3232
+ } };
3233
+ }
3234
+ const input = deletePromotedAccount.parse(op.payload), current = await this.get(account, input.promoted_account_id);
3235
+ if (current.deleted || current.context_hash !== input.expected_context_hash) throw new AdportError17("PENDING_MISMATCH", "x: promoted-account association/parent changed or was deleted; read and preview again");
3236
+ return { ...review("Remove promoted account from ad group", [{ label: "Association", after: current.id }, { label: "Profile retained", after: current.user_id }, { label: "Ad group", after: current.line_item_id }, { label: "Deleted", before: false, after: true }], ["Removes this one ad association. The X profile, other associations, posts and parent delivery/budgets are retained.", "A deleted tombstone may retain native ACTIVE status. No PUT edit or profile deletion occurs.", notice3]), execute: async () => {
3237
+ const known = [current.id];
3238
+ try {
3239
+ const row = (await this.entities.client.request("DELETE", `${this.base(account)}/promoted_accounts/${current.id}`, z31.object({ data: nativePromotedAccount }))).data;
3240
+ known.push(row.id);
3241
+ this.scope(account, row, current.id, current.line_item_id);
3242
+ const observed = await this.get(account, current.id), matches2 = (value) => value.id === current.id && value.line_item_id === current.line_item_id && value.user_id === current.user_id && value.deleted;
3243
+ if (!matches2(row) || !matches2(observed) || !equal6(observed.parent, current.parent)) throw new Error("Promoted-account deletion/readback differs");
3244
+ return [current.id];
3245
+ } catch (error) {
3246
+ return this.unconfirmed(error, known);
3247
+ }
3248
+ } };
3249
+ }
3250
+ };
3251
+
437
3252
  // src/provider.ts
438
3253
  var DERIVED = { ctr: ["clicks", "impressions", 100], cpc: ["spend", "clicks", 1], cpm: ["spend", "impressions", 1e3] };
439
3254
  var DAY = 864e5;
440
3255
  var XAdsProvider = class extends XAdsEntities {
441
3256
  id = "x";
442
3257
  analytics;
443
- constructor(client, analytics) {
3258
+ management;
3259
+ targeting;
3260
+ creatives;
3261
+ mediaUploads;
3262
+ cards;
3263
+ audiences;
3264
+ measurement;
3265
+ posts;
3266
+ scheduled;
3267
+ directMedia;
3268
+ prerollCtas;
3269
+ accountMedia;
3270
+ promotedAccounts;
3271
+ constructor(client, analytics, media) {
444
3272
  super(client);
445
3273
  this.analytics = analytics ?? new XAdsAnalytics(client);
3274
+ this.measurement = new XMeasurementService(this, this.analytics);
3275
+ this.management = new XManagementService(this, this.measurement);
3276
+ this.targeting = new XTargetingService(this);
3277
+ this.creatives = new XCreativeService(this);
3278
+ this.mediaUploads = new XMediaService(this, media);
3279
+ this.cards = new XCardService(this, this.creatives);
3280
+ this.audiences = new XAudienceService(this);
3281
+ this.posts = new XPostService(this, this.creatives);
3282
+ this.scheduled = new XScheduledService(this, this.creatives, this.posts);
3283
+ this.directMedia = new XDirectMediaService(this, this.posts);
3284
+ this.prerollCtas = new XPrerollCtaService(this, this.posts);
3285
+ this.accountMedia = new XAccountMediaService(this, this.directMedia);
3286
+ this.promotedAccounts = new XPromotedAccountService(this, this.creatives, this.posts);
446
3287
  }
447
3288
  capabilities() {
448
3289
  return { serverDryRun: false };
@@ -451,38 +3292,54 @@ var XAdsProvider = class extends XAdsEntities {
451
3292
  return { pauseCampaign: (accountId, campaignId) => ({ tool: "x_set_campaign_status", input: { account_id: accountId, campaign_id: campaignId, status: "PAUSED" } }) };
452
3293
  }
453
3294
  async previewWrite(op, guard) {
454
- const { execute: _execute, ...preview } = await planXWrite(this, op, guard);
3295
+ const { execute: _execute, ...preview } = await this.writePlan(op, guard);
455
3296
  return { ...preview, serverValidated: false };
456
3297
  }
457
3298
  async applyWrite(op, guard) {
458
- return { applied: true, resourceIds: await (await planXWrite(this, op, guard)).execute() };
3299
+ const result = await (await this.writePlan(op, guard)).execute();
3300
+ return Array.isArray(result) ? { applied: true, resourceIds: result } : result;
3301
+ }
3302
+ writePlan(op, guard) {
3303
+ if (promotedAccountWrites.has(op.tool)) return this.promotedAccounts.plan(op, guard);
3304
+ if (op.tool === "x_delete_account_media") return this.accountMedia.plan(op);
3305
+ if (prerollCtaWrites.has(op.tool)) return this.prerollCtas.plan(op, guard);
3306
+ if (directMediaWrites.has(op.tool)) return this.directMedia.plan(op, guard);
3307
+ if (scheduledWrites.has(op.tool)) return this.scheduled.plan(op, guard);
3308
+ if (postWrites.has(op.tool)) return this.posts.plan(op, guard);
3309
+ if (/^x_(?:create|update|delete)_tracking_tag$/.test(op.tool)) return this.measurement.plan(op);
3310
+ if (/^x_(?:create_custom_audience|update_custom_audience|update_custom_audience_users|delete_custom_audience)$/.test(op.tool)) return this.audiences.plan(op);
3311
+ if (cardWrites.has(op.tool)) return this.cards.plan(op);
3312
+ if (["x_upload_media", "x_register_uploaded_media"].includes(op.tool)) return this.mediaUploads.plan(op);
3313
+ if (/^x_(?:create_draft_tweet|update_draft_tweet|delete_draft_tweet|update_media_library|delete_media_library_item)$/.test(op.tool)) return this.creatives.plan(op, guard);
3314
+ if (["x_add_targeting_criterion", "x_remove_targeting_criterion", "x_update_targeting"].includes(op.tool)) return this.targeting.plan(op, guard);
3315
+ return /^x_(?:create_line_item|update_line_item|set_line_item_(?:status|budget|bidding)|delete_line_item)$/.test(op.tool) ? this.management.plan(op, guard) : planXWrite(this, op, guard);
459
3316
  }
460
3317
  async report(query) {
461
3318
  const range = resolveDateRange(query.dateRange);
462
- z6.iso.date().parse(range.start);
463
- z6.iso.date().parse(range.end);
464
- if (range.end < range.start) throw new AdportError5("INVALID_INPUT", "x: report end precedes start");
3319
+ z32.iso.date().parse(range.start);
3320
+ z32.iso.date().parse(range.end);
3321
+ if (range.end < range.start) throw new AdportError18("INVALID_INPUT", "x: report end precedes start");
465
3322
  const needed = /* @__PURE__ */ new Set();
466
3323
  for (const metric of query.metrics) {
467
3324
  if (["spend", "impressions", "clicks"].includes(metric)) needed.add(metric);
468
3325
  else if (metric in DERIVED) for (const dep of DERIVED[metric].slice(0, 2)) needed.add(dep);
469
3326
  }
470
- if (!needed.size) throw new AdportError5("INVALID_INPUT", "x: supported normalized metrics are spend, impressions, link clicks, ctr, cpc and cpm; conversion normalization is not yet verified");
3327
+ if (!needed.size) throw new AdportError18("INVALID_INPUT", "x: supported normalized metrics are spend, impressions, link clicks, ctr, cpc and cpm; conversion normalization is not yet verified");
471
3328
  const limit = query.limit ?? 1e3;
472
- if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError5("INVALID_INPUT", "x: report limit must be a positive integer");
3329
+ if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError18("INVALID_INPUT", "x: report limit must be a positive integer");
473
3330
  const groups = [...needed.has("spend") ? ["BILLING"] : [], ...needed.has("clicks") || needed.has("impressions") ? ["ENGAGEMENT"] : []];
474
- const rows = [];
3331
+ const rows2 = [];
475
3332
  const accounts = [...new Set(query.accountIds ?? (await this.listAccounts()).map((a) => a.id))];
476
3333
  for (const accountId of accounts) {
477
3334
  const account = await this.getAccount(accountId);
478
3335
  const start = xAccountMidnight(range.start, account.timezone);
479
3336
  const endDate = new Date(Date.parse(`${range.end}T00:00:00Z`) + DAY).toISOString().slice(0, 10);
480
3337
  const end = xAccountMidnight(endDate, account.timezone);
481
- if (account.timezone_switch_at && (!Number.isFinite(Date.parse(account.timezone_switch_at)) || start < Date.parse(account.timezone_switch_at))) throw new AdportError5("INVALID_INPUT", "x: requested dates predate the account timezone switch; its previous reporting timezone is unknown");
3338
+ if (account.timezone_switch_at && (!Number.isFinite(Date.parse(account.timezone_switch_at)) || start < Date.parse(account.timezone_switch_at))) throw new AdportError18("INVALID_INPUT", "x: requested dates predate the account timezone switch; its previous reporting timezone is unknown");
482
3339
  let entities = await this.reportEntities(accountId, query.level);
483
- if (query.level === "account" && new Set(entities.map((e) => e.currency)).size > 1) throw new AdportError5("PROVIDER_ERROR", "x: cannot aggregate campaigns with different currencies into one account total");
484
- const truncated = query.level !== "account" && entities.length > limit - rows.length;
485
- if (query.level !== "account") entities = entities.slice(0, Math.max(0, limit - rows.length));
3340
+ if (query.level === "account" && new Set(entities.map((e) => e.currency)).size > 1) throw new AdportError18("PROVIDER_ERROR", "x: cannot aggregate campaigns with different currencies into one account total");
3341
+ const truncated = query.level !== "account" && entities.length > limit - rows2.length;
3342
+ if (query.level !== "account") entities = entities.slice(0, Math.max(0, limit - rows2.length));
486
3343
  const totals = /* @__PURE__ */ new Map();
487
3344
  const entityKey = (entity) => `${entity.type}:${entity.id}`;
488
3345
  for (const type of new Set(entities.map((e) => e.type))) {
@@ -493,8 +3350,8 @@ var XAdsProvider = class extends XAdsEntities {
493
3350
  for (let from = start; from < end; ) {
494
3351
  const asynchronous = end - start > 7 * DAY || end < Date.now() - 7 * DAY || type === "MEDIA_CREATIVE";
495
3352
  const to = Math.min(end, from + (asynchronous ? 30 : 7) * DAY);
496
- for (const placement of X_PLACEMENTS) {
497
- const stats = await this.analytics.totals(accountId, { entity: type, entity_ids: batch.map((e) => e.id).join(","), start_time: new Date(from).toISOString(), end_time: new Date(to).toISOString(), granularity: "TOTAL", placement, metric_groups: groups.join(",") }, asynchronous);
3353
+ for (const placement2 of X_PLACEMENTS) {
3354
+ const stats = await this.analytics.totals(accountId, { entity: type, entity_ids: batch.map((e) => e.id).join(","), start_time: new Date(from).toISOString(), end_time: new Date(to).toISOString(), granularity: "TOTAL", placement: placement2, metric_groups: groups.join(",") }, asynchronous);
498
3355
  for (const row of stats.data) {
499
3356
  const source = row.id_data[0].metrics, metrics = {};
500
3357
  for (const [key, field, divisor] of [["spend", "billed_charge_local_micro", 1e6], ["impressions", "impressions", 1], ["clicks", "url_clicks", 1]]) {
@@ -513,21 +3370,21 @@ var XAdsProvider = class extends XAdsEntities {
513
3370
  if (entities.length) {
514
3371
  let total;
515
3372
  for (const entity of entities) total = add(total, totals.get(entityKey(entity)));
516
- rows.push({ provider: this.id, accountId, entity: { level: "account", id: accountId, name: account.name, status: account.approval_status }, metrics: normalize(total ?? {}, query.metrics) });
3373
+ rows2.push({ provider: this.id, accountId, entity: { level: "account", id: accountId, name: account.name, status: account.approval_status }, metrics: normalize(total ?? {}, query.metrics) });
517
3374
  }
518
- } else for (const entity of entities) rows.push({ provider: this.id, accountId, entity: { level: query.level, id: query.level === "ad" ? entityKey(entity) : entity.id, name: entity.name, status: entity.status }, metrics: normalize(totals.get(entityKey(entity)), query.metrics) });
519
- if (truncated) return { rows, truncated: true };
520
- if (rows.length >= limit) {
521
- return { rows, ...accounts.indexOf(accountId) < accounts.length - 1 ? { truncated: true } : {} };
3375
+ } else for (const entity of entities) rows2.push({ provider: this.id, accountId, entity: { level: query.level, id: query.level === "ad" ? entityKey(entity) : entity.id, name: entity.name, status: entity.status }, metrics: normalize(totals.get(entityKey(entity)), query.metrics) });
3376
+ if (truncated) return { rows: rows2, truncated: true };
3377
+ if (rows2.length >= limit) {
3378
+ return { rows: rows2, ...accounts.indexOf(accountId) < accounts.length - 1 ? { truncated: true } : {} };
522
3379
  }
523
3380
  }
524
- return { rows };
3381
+ return { rows: rows2 };
525
3382
  }
526
3383
  async reportEntities(accountId, level) {
527
3384
  if (level === "account" || level === "campaign") return (await this.listCampaigns(accountId)).filter((c) => c.entity_status !== "DRAFT").map((c) => ({ id: c.id, name: c.name, currency: c.currency, status: c.entity_status, type: "CAMPAIGN" }));
528
3385
  const allLines = await this.listLineItems(accountId);
529
3386
  const lines = allLines.filter((l) => l.entity_status !== "DRAFT");
530
- if (level === "ad_group") return lines.map((l) => ({ id: l.id, name: l.name, currency: l.currency, status: l.entity_status, type: "LINE_ITEM" }));
3387
+ if (level === "ad_group") return lines.map((l) => ({ id: l.id, name: l.name ?? l.id, currency: l.currency, status: l.entity_status, type: "LINE_ITEM" }));
531
3388
  const lookup = new Map(allLines.map((l) => [l.id, l]));
532
3389
  const tweets = await this.listPromotedTweets(accountId), media = await this.listMediaCreatives(accountId);
533
3390
  const promoted = lines.some((l) => l.product_type === "PROMOTED_ACCOUNT") ? await this.listPromotedAccounts(accountId) : [];
@@ -536,11 +3393,11 @@ var XAdsProvider = class extends XAdsEntities {
536
3393
  ...media.map((t) => ({ ...t, type: "MEDIA_CREATIVE", name: `Media creative ${t.account_media_id}` })),
537
3394
  ...promoted.map((t) => ({ ...t, type: "PROMOTED_ACCOUNT", name: `Promoted account ${t.user_id}` }))
538
3395
  ].filter((t) => {
539
- if (!lookup.has(t.line_item_id)) throw new AdportError5("PROVIDER_ERROR", "x: ad references an unknown line item");
3396
+ if (!lookup.has(t.line_item_id)) throw new AdportError18("PROVIDER_ERROR", "x: ad references an unknown line item");
540
3397
  return lookup.get(t.line_item_id).entity_status !== "DRAFT";
541
3398
  }).map((t) => {
542
3399
  const parent = lookup.get(t.line_item_id);
543
- if (!parent) throw new AdportError5("PROVIDER_ERROR", "x: ad references an unknown or draft line item");
3400
+ if (!parent) throw new AdportError18("PROVIDER_ERROR", "x: ad references an unknown or draft line item");
544
3401
  return { id: t.id, name: t.name, status: t.entity_status, currency: parent.currency, type: t.type };
545
3402
  });
546
3403
  }
@@ -550,33 +3407,163 @@ function add(previous, next) {
550
3407
  const sum = {};
551
3408
  for (const key of ["spend", "impressions", "clicks"]) if (previous[key] !== void 0 && next[key] !== void 0) {
552
3409
  const value = previous[key] + next[key];
553
- if (!Number.isFinite(value) || value > Number.MAX_SAFE_INTEGER) throw new AdportError5("PROVIDER_ERROR", "x: report total exceeds safe numeric range");
3410
+ if (!Number.isFinite(value) || value > Number.MAX_SAFE_INTEGER) throw new AdportError18("PROVIDER_ERROR", "x: report total exceeds safe numeric range");
554
3411
  sum[key] = value;
555
3412
  }
556
3413
  return sum;
557
3414
  }
558
- function normalize(values, requested) {
559
- const all = { ...values };
560
- for (const [metric, [numerator, denominator, factor]] of Object.entries(DERIVED)) if (values[numerator] !== void 0 && values[denominator] !== void 0) all[metric] = values[denominator] ? values[numerator] / values[denominator] * factor : 0;
3415
+ function normalize(values2, requested) {
3416
+ const all = { ...values2 };
3417
+ for (const [metric, [numerator, denominator, factor]] of Object.entries(DERIVED)) if (values2[numerator] !== void 0 && values2[denominator] !== void 0) all[metric] = values2[denominator] ? values2[numerator] / values2[denominator] * factor : 0;
561
3418
  return Object.fromEntries(requested.filter((m) => all[m] !== void 0).map((m) => [m, all[m]]));
562
3419
  }
563
3420
 
564
3421
  // src/tools.ts
565
- import { z as z7 } from "zod";
566
- import { defineTool, guardedWriteTool } from "@adport/core";
3422
+ import { z as z39 } from "zod";
3423
+ import { defineTool as defineTool14, guardedWriteTool as guardedWriteTool14 } from "@adport/core";
3424
+
3425
+ // src/card-tools.ts
3426
+ import { creativesOutput as creativesOutput2, defineTool as defineTool7, guardedWriteTool as guardedWriteTool7 } from "@adport/core";
3427
+ import { z as z33 } from "zod";
3428
+ function xCardTools(provider) {
3429
+ const catalog = { category: "creatives", exposure: "standard" };
3430
+ return [
3431
+ defineTool7({ name: "x_cards", namespace: "x", description: "Browse native website/app/carousel cards with bounded media previews, copy edits and cursor pagination. Cards are separate from post publication and ad delivery. Legacy inclusion is explicit; this inventory does not replace exact-URI cards/all lookup.", input: listCards, output: creativesOutput2.passthrough(), presentation: "creatives", pagination: { cursorInput: "cursor" }, catalog, annotations: { readOnly: true, openWorld: false }, handler: (v) => provider.cards.list(v) }),
3432
+ defineTool7({ name: "x_get_card", namespace: "x", description: "Read one modern card by numeric ID within the selected account, including full native configuration and configuration_hash for edits/deletion.", input: z33.object({ account_id: xId, card_id: snowflake, with_deleted: z33.boolean().default(false) }), catalog, annotations: { readOnly: true, openWorld: false }, handler: (v) => provider.cards.get(v.account_id, v.card_id, v.with_deleted) }),
3433
+ guardedWriteTool7({ name: "x_create_card", namespace: "x", provider: "x", kind: "create", description: "Create an unattached website/app or carousel card from ready account-owned image/video media. Uses the native JSON body and independently verifies content. Does not publish posts or create ad associations. Local preview only; never repeat an unconfirmed creation.", payload: createCard, destructive: false, openWorld: false, catalog }),
3434
+ guardedWriteTool7({ name: "x_update_card", namespace: "x", provider: "x", kind: "update", description: "Edit one modern card using its current configuration hash. Omitted fields stay unchanged; components/slides replace their layout. Copy shortcuts edit a supported current layout and require slide_index for multi-destination cards. Shared changes can affect existing posts/ads immediately; acknowledgement required. No automatic retry.", payload: updateCard, destructive: true, openWorld: false, catalog }),
3435
+ guardedWriteTool7({ name: "x_delete_card", namespace: "x", provider: "x", kind: "remove", description: "Delete one modern card after a matching snapshot and shared-effects acknowledgement. Existing uses may be affected; no restore endpoint is established. Verifies exact native deletion/readback; does not pause an ad or campaign. No automatic retry.", payload: deleteCard, destructive: true, openWorld: false, catalog })
3436
+ ];
3437
+ }
3438
+
3439
+ // src/post-tools.ts
3440
+ import { creativesOutput as creativesOutput3, defineTool as defineTool8, guardedWriteTool as guardedWriteTool8 } from "@adport/core";
3441
+ import { z as z34 } from "zod";
3442
+ function xPostTools(provider) {
3443
+ const shared = { namespace: "x", catalog: { category: "creatives", exposure: "specialist" } };
3444
+ const read = { readOnly: true };
3445
+ return [
3446
+ defineTool8({ ...shared, name: "x_published_posts", description: "View published promoted-only/organic posts for an explicit account-associated author, with native media/copy and guarded name edits. PUBLISHED is not ad delivery. Native cursors support Load more; text edits use a new post.", input: postList, output: creativesOutput3.passthrough(), presentation: "creatives", pagination: { cursorInput: "cursor" }, annotations: read, handler: (input) => provider.posts.list(input) }),
3447
+ defineTool8({ ...shared, name: "x_get_published_post", description: "Read an exact published post for this account and current promotable author, including snapshot_hash. Never treats a missing response as global absence or substitutes rounded numeric IDs.", input: postReference, annotations: read, handler: (input) => provider.posts.get(input.account_id, input.user_id, input.tweet_id) }),
3448
+ defineTool8({ ...shared, name: "x_post_creation_context", description: "Check exact promoted-only post fields, FULL/composer authority and ready account-owned media/cards. Returns context_hash for publication. Creates nothing; existing drafts stay separate.", input: postFields.safeExtend({ account_id: xId }), annotations: read, handler: ({ account_id, ...input }) => provider.posts.creationContext(account_id, input) }),
3449
+ guardedWriteTool8({ ...shared, name: "x_create_promoted_only_post", provider: "x", kind: "create", destructive: false, description: "Create a distinct PUBLISHED promoted-only post with nullcast=true, expected_context_hash and confirm_publication. Does not publish organically, consume a draft or associate an ad. Native text/attachment rendering is qualified by independent readback; no replay.", payload: createPost }),
3450
+ guardedWriteTool8({ ...shared, name: "x_rename_published_post", provider: "x", kind: "update", description: "Rename an owned published post with expected_snapshot_hash. Uses native PUT tweets/id/name; published copy/media/status and associations are preserved and independently read back.", payload: renamePost }),
3451
+ defineTool8({ ...shared, name: "x_promoted_posts", description: "View one verified ad group\u2019s promoted-post associations with native cursor paging and guarded disassociation. Optional user_id hydrates published content for that associated author. ACTIVE is association state, not proof of delivery.", input: promotionList, output: creativesOutput3.passthrough(), presentation: "creatives", pagination: { cursorInput: "cursor" }, annotations: read, handler: (input) => provider.posts.promotions(input) }),
3452
+ defineTool8({ ...shared, name: "x_get_promoted_post", description: "Read an exact account-owned promoted-post association, its parent settings and context_hash. ID is the association ID, not the published tweet_id. Tombstone can retain native ACTIVE status.", input: z34.object({ account_id: xId, promoted_tweet_id: xId }).strict(), annotations: read, handler: (input) => provider.posts.getPromotion(input.account_id, input.promoted_tweet_id) }),
3453
+ defineTool8({ ...shared, name: "x_promotion_context", description: "Read complete current source/parent context for associating1\u201350 existing FULL-author posts to one ad group. Hash binds posts, parent delivery/money and matching existing associations. Does not promote; RETWEETS_ONLY copying is separate.", input: promotionSelection.safeExtend({ account_id: xId }), annotations: read, handler: ({ account_id, ...input }) => provider.posts.promotionContext(account_id, input) }),
3454
+ guardedWriteTool8({ ...shared, name: "x_create_promoted_posts", provider: "x", kind: "create", destructive: true, description: "Associate1\u201350 verified published FULL-author posts with one ad group. Requires context_hash and acknowledging native ACTIVE associations. paused_creation requires a currently PAUSED ad group. Existing posts/parents/budgets stay; no fictitious PUT pause.", payload: createPromotions }),
3455
+ defineTool8({ ...shared, name: "x_repost_promotion_context", description: "Review one to 50 published posts from a current RETWEETS_ONLY author for native copy promotion. Verifies unique FULL receiving author, complete source/parent/association inventory and context_hash. New nullcast copies get different IDs; existing reposts cannot be reliably deduplicated by source ID.", input: promotionSelection.safeExtend({ account_id: xId }), output: creativesOutput3.passthrough(), presentation: "creatives", annotations: read, handler: ({ account_id, ...input }) => provider.posts.repostContext(account_id, input) }),
3456
+ guardedWriteTool8({ ...shared, name: "x_create_repost_promotions", provider: "x", kind: "create", destructive: true, description: "Promote one to 50 authorized RETWEETS_ONLY source posts as new published nullcast copies and ACTIVE associations. Requires context_hash and both acknowledgements. Uses one source per native request, at most four concurrent; paused_creation requires a PAUSED ad group. Returns explicit source/copy/association mappings. Partial outcomes stop new writes, retain known IDs and are never replayed.", payload: createRepostPromotions }),
3457
+ guardedWriteTool8({ ...shared, name: "x_delete_promoted_post", provider: "x", kind: "remove", destructive: true, description: "Disassociate one exact promoted-post association with expected_context_hash, native DELETE and independent tombstone readback. Retains published post/media/other associations. This is the native ad-level removal/pause workflow; re-promotion needs a new preview.", payload: deletePromotion })
3458
+ ];
3459
+ }
3460
+
3461
+ // src/scheduled-tools.ts
3462
+ import { creativesOutput as creativesOutput4, defineTool as defineTool9, guardedWriteTool as guardedWriteTool9 } from "@adport/core";
3463
+ import { z as z35 } from "zod";
3464
+ function xScheduledTools(provider) {
3465
+ const shared = { namespace: "x", catalog: { category: "creatives", exposure: "specialist" } }, annotations = { readOnly: true };
3466
+ const write = { ...shared, provider: "x", destructive: true };
3467
+ return [
3468
+ defineTool9({ ...shared, name: "x_scheduled_posts", description: "View one account-associated author\u2019s scheduled posts, copy, native state and bounded media previews. Native cursors support Load more; SCHEDULED is automatic future publication, not a paused ad.", input: scheduledList, output: creativesOutput4.passthrough(), presentation: "creatives", pagination: { cursorInput: "cursor" }, annotations, handler: (input) => provider.scheduled.list(input) }),
3469
+ defineTool9({ ...shared, name: "x_get_scheduled_post", description: "Read an exact author/account-owned scheduled post, matching current ad associations and snapshot_hash. Scheduled ID and eventual published tweet_id are distinct. Complete association inventory is required for edit/delete context.", input: scheduledReference, annotations, handler: (input) => provider.scheduled.get(input.account_id, input.user_id, input.scheduled_tweet_id) }),
3470
+ defineTool9({ ...shared, name: "x_scheduled_post_context", description: "Check FULL/composer authority, owned ready attachments and a UTC-minute schedule,15minutes to one calendar year ahead. Returns context_hash without creating content. Only promoted-only nullcast publication is supported.", input: scheduledFields.safeExtend({ account_id: xId }), annotations, handler: ({ account_id, ...input }) => provider.scheduled.creationContext(account_id, input) }),
3471
+ guardedWriteTool9({ ...write, name: "x_create_scheduled_post", kind: "create", description: "Schedule a new promoted-only post with expected_context_hash and automatic-publication acknowledgement. Forces nullcast=true; no draft consumption or ad association. Independent native receipt/readback; uncertain writes are never replayed.", payload: createScheduled }),
3472
+ guardedWriteTool9({ ...write, name: "x_update_scheduled_post", kind: "update", description: "Edit a still-future, promoted-only SCHEDULED post with expected_snapshot_hash. Omitted fields remain; media_keys:[] and card_uri:null clear attachments. Existing associations require shared-effects acknowledgement. No organic-state change.", payload: updateScheduled }),
3473
+ guardedWriteTool9({ ...write, name: "x_delete_scheduled_post", kind: "remove", description: "Permanently cancel/delete a still-future promoted-only schedule after snapshot and deletion acknowledgement. Requires no live scheduled ad associations. Native DELETED receipt plus independent HTTP404; published posts are separate.", payload: deleteScheduled }),
3474
+ defineTool9({ ...shared, name: "x_scheduled_promoted_posts", description: "List one account-owned ad group\u2019s scheduled-post associations with native cursors. These have no native status/PUT pause; tweet_id appears after publication. Does not infer delivery from association existence.", input: scheduledPromotionList, output: z35.looseObject({ records: z35.array(z35.record(z35.string(), z35.unknown())) }), presentation: "records", annotations, pagination: { cursorInput: "cursor" }, handler: (input) => provider.scheduled.promotions(input) }),
3475
+ defineTool9({ ...shared, name: "x_get_scheduled_promoted_post", description: "Read an exact scheduled ad association, source schedule, parent configuration and context_hash. Uses the association ID, distinct from scheduled_tweet_id and eventual published tweet_id.", input: z35.object({ account_id: xId, scheduled_promoted_tweet_id: xId }).strict(), annotations, handler: (input) => provider.scheduled.getPromotion(input.account_id, input.scheduled_promoted_tweet_id) }),
3476
+ defineTool9({ ...shared, name: "x_scheduled_promotion_context", description: "Check exact future FULL-author schedule, complete matching association inventory and parent delivery/budget context. Returns context_hash for automatic promotion; creates nothing.", input: scheduledPromotionSelection.safeExtend({ account_id: xId }), annotations, handler: ({ account_id, ...input }) => provider.scheduled.promotionContext(account_id, input) }),
3477
+ guardedWriteTool9({ ...write, name: "x_create_scheduled_promoted_post", kind: "create", description: "Associate one still-future schedule with an ad group after context_hash and automatic-promotion acknowledgement. paused_creation requires a currently PAUSED ad group; native has no association status or PUT pause. Existing money pools remain policy-checked.", payload: createScheduledPromotion }),
3478
+ guardedWriteTool9({ ...write, name: "x_delete_scheduled_promoted_post", kind: "remove", description: "Remove one exact scheduled ad association before its publication time, with expected_context_hash and independent tombstone readback. Keeps the scheduled post; after publication inspect/remove the ordinary promoted-post association instead.", payload: deleteScheduledPromotion })
3479
+ ];
3480
+ }
3481
+
3482
+ // src/direct-media-tools.ts
3483
+ import { creativesOutput as creativesOutput5, defineTool as defineTool10, guardedWriteTool as guardedWriteTool10 } from "@adport/core";
3484
+ import { z as z36 } from "zod";
3485
+ function xDirectMediaTools(provider) {
3486
+ const shared = { namespace: "x", catalog: { category: "creatives", exposure: "specialist" } };
3487
+ const annotations = { readOnly: true };
3488
+ return [
3489
+ defineTool10({ ...shared, name: "x_account_media", description: "View native Account Media assets with cursor paging and safe image/video previews. These IDs are distinct from media-library keys and serving associations. Unknown or VAST formats retain native metadata without invented previews.", input: accountMediaList, output: creativesOutput5.passthrough(), presentation: "creatives", pagination: { cursorInput: "cursor" }, annotations, handler: (input) => provider.directMedia.assets(input) }),
3490
+ defineTool10({ ...shared, name: "x_get_account_media", description: "Read one exact account-owned Account Media asset and configuration hash. Does not turn a media-library key or upload receipt into an Account Media ID.", input: z36.object({ account_id: xId, account_media_id: xId }).strict(), annotations, handler: (input) => provider.directMedia.getAsset(input.account_id, input.account_media_id) }),
3491
+ defineTool10({ ...shared, name: "x_media_creatives", description: "View direct-media ad associations in one verified ad group, with native paging, source previews and guarded disassociation actions. Native ACTIVE association state is separate from parent delivery.", input: directMediaList, output: creativesOutput5.passthrough(), presentation: "creatives", pagination: { cursorInput: "cursor" }, annotations, handler: (input) => provider.directMedia.list(input) }),
3492
+ defineTool10({ ...shared, name: "x_get_media_creative", description: "Read an exact direct-media association, parent configuration and context_hash. Media-creative IDs are distinct from their source account_media_id. Deleted tombstones may retain ACTIVE.", input: z36.object({ account_id: xId, media_creative_id: xId }).strict(), annotations, handler: (input) => provider.directMedia.get(input.account_id, input.media_creative_id) }),
3493
+ defineTool10({ ...shared, name: "x_media_creative_context", description: "Review an existing Account Media asset, MEDIA ad group and complete bounded association inventory before linking. Binds source, parent, destination and existing associations in context_hash. Supports PREROLL and documented TAP image formats; VAST authoring is unverified.", input: directMediaSelection.extend({ account_id: xId }).strict(), output: creativesOutput5.passthrough(), presentation: "creatives", annotations, handler: ({ account_id, ...input }) => provider.directMedia.context(account_id, input) }),
3494
+ guardedWriteTool10({ ...shared, name: "x_create_media_creative", provider: "x", kind: "create", destructive: true, description: "Associate one verified Account Media asset with a MEDIA ad group using context_hash and explicit native ACTIVE acknowledgement. paused_creation requires a PAUSED ad group. WEBSITE_CLICKS needs landing_url; preroll destinations use separate native CTA settings. Checks receipt/readback; no upload, parent edit or replay.", payload: createDirectMedia }),
3495
+ guardedWriteTool10({ ...shared, name: "x_delete_media_creative", provider: "x", kind: "remove", destructive: true, description: "Disassociate one exact direct-media ad with expected_context_hash, native DELETE and independent tombstone readback. Preserves Account Media, library assets, other associations and parent status/budgets. No fictitious PUT pause or automatic replay.", payload: deleteDirectMedia })
3496
+ ];
3497
+ }
3498
+
3499
+ // src/preroll-cta-tools.ts
3500
+ import { creativesOutput as creativesOutput6, defineTool as defineTool11, guardedWriteTool as guardedWriteTool11 } from "@adport/core";
3501
+ import { z as z37 } from "zod";
3502
+ function xPrerollCtaTools(provider) {
3503
+ const shared = { namespace: "x", catalog: { category: "creatives", exposure: "specialist" } }, annotations = { readOnly: true };
3504
+ return [
3505
+ defineTool11({ ...shared, name: "x_preroll_ctas", description: "Browse native preroll CTA buttons/destinations with cursor paging. Account-wide browsing avoids parent fan-out; inspect an exact CTA for editing. Optional line_item_id enables scoped edit/removal actions bound to full inventory and parent settings. Incomplete edit context stays read-only.", input: prerollCtaList, output: creativesOutput6.passthrough(), presentation: "creatives", pagination: { cursorInput: "cursor" }, annotations, handler: (input) => provider.prerollCtas.list(input) }),
3506
+ defineTool11({ ...shared, name: "x_get_preroll_cta", description: "Read an exact account-owned preroll CTA, parent and complete active CTA inventory, with context_hash and guarded widget edits. CTA scope is the ad group, not one media association.", input: z37.object({ account_id: xId, preroll_call_to_action_id: xId }).strict(), output: creativesOutput6.passthrough(), presentation: "creatives", annotations, handler: (input) => provider.prerollCtas.get(input.account_id, input.preroll_call_to_action_id) }),
3507
+ defineTool11({ ...shared, name: "x_preroll_cta_context", description: "Review a new preroll button/destination and complete current ad-group CTA inventory before creation. Returns context_hash; requires an existing non-draft PREROLL_VIEWS ad group. Existing CTA settings need explicit update, not an implicit POST replacement.", input: prerollCtaSelection.extend({ account_id: xId }).strict(), annotations, handler: ({ account_id, ...input }) => provider.prerollCtas.context(account_id, input) }),
3508
+ guardedWriteTool11({ ...shared, name: "x_create_preroll_cta", provider: "x", kind: "create", destructive: true, description: "Set one native preroll CTA with context_hash and explicit ad-group scope acknowledgement. Refuses existing active CTAs; paused_creation requires a PAUSED ad group. Five native button presets; exact URL/receipt/readback checks. No ad creation, activation or replay.", payload: createPrerollCta }),
3509
+ guardedWriteTool11({ ...shared, name: "x_update_preroll_cta", provider: "x", kind: "update", destructive: true, description: "Edit supplied native CTA button/destination fields with expected_context_hash and ad-group scope acknowledgement. Sends only actual changes, preserves omitted fields and parent settings, and verifies the receipt plus independent readback. Affects the ad group\u2019s preroll ads.", payload: updatePrerollCta }),
3510
+ guardedWriteTool11({ ...shared, name: "x_delete_preroll_cta", provider: "x", kind: "remove", destructive: true, description: "Remove one exact preroll CTA with expected_context_hash and ad-group scope acknowledgement. Checks native tombstone and remaining CTA inventory; retains media, ads and parent delivery/budgets. Removing a CTA does not pause ads; no automatic replay.", payload: deletePrerollCta })
3511
+ ];
3512
+ }
3513
+
3514
+ // src/account-media-tools.ts
3515
+ import { creativesOutput as creativesOutput7, defineTool as defineTool12, guardedWriteTool as guardedWriteTool12 } from "@adport/core";
3516
+ function xAccountMediaTools(provider) {
3517
+ const shared = { namespace: "x", catalog: { category: "creatives", exposure: "specialist" } };
3518
+ return [
3519
+ defineTool12({ ...shared, name: "x_account_media_usage", description: "Inspect one Account Media source and complete bounded usage, including deleted-parent references. Reference details are paged; later offsets require the original context hash. Returns deletion eligibility; used sources need separately reviewed disassociation first.", input: accountMediaUsage, output: creativesOutput7.passthrough(), presentation: "creatives", annotations: { readOnly: true }, handler: ({ account_id, account_media_id, ...input }) => provider.accountMedia.usage(account_id, account_media_id, input) }),
3520
+ guardedWriteTool12({ ...shared, name: "x_delete_account_media", provider: "x", kind: "remove", destructive: true, description: "Delete one unused native Account Media source with expected_context_hash and explicit source-deletion acknowledgement. Requires a complete usage scan with no non-deleted ad associations; checks DELETE receipt and independent source/usage readback. No automatic detach, library deletion or retry.", payload: deleteAccountMedia })
3521
+ ];
3522
+ }
3523
+
3524
+ // src/promoted-account-tools.ts
3525
+ import { creativesOutput as creativesOutput8, defineTool as defineTool13, guardedWriteTool as guardedWriteTool13 } from "@adport/core";
3526
+ import { z as z38 } from "zod";
3527
+ function xPromotedAccountTools(provider) {
3528
+ const shared = { namespace: "x", catalog: { category: "creatives", exposure: "specialist" } };
3529
+ return [
3530
+ defineTool13({ ...shared, name: "x_promoted_accounts", description: "View profile-ad associations in one verified PROMOTED_ACCOUNT ad group, with cursor paging, profile links and guarded removal. Native ACTIVE is association state; parent delivery remains separate.", input: promotedAccountList, output: creativesOutput8.passthrough(), presentation: "creatives", pagination: { cursorInput: "cursor" }, annotations: { readOnly: true }, handler: (input) => provider.promotedAccounts.list(input) }),
3531
+ defineTool13({ ...shared, name: "x_get_promoted_account", description: "Read one exact promoted-account association, including deleted tombstones, verified parents and context_hash. Profile content is live and is not snapshotted by this Ads endpoint.", input: z38.object({ account_id: xId, promoted_account_id: xId }).strict(), annotations: { readOnly: true }, handler: (input) => provider.promotedAccounts.get(input.account_id, input.promoted_account_id) }),
3532
+ defineTool13({ ...shared, name: "x_promoted_account_context", description: "Review a current FULL promotable user, FOLLOWERS ad group and complete bounded association inventory before linking. Binds identity, parent configuration and existing associations to context_hash; no publication or profile edit.", input: promotedAccountSelection.extend({ account_id: xId }).strict(), output: creativesOutput8.passthrough(), presentation: "creatives", annotations: { readOnly: true }, handler: ({ account_id, ...input }) => provider.promotedAccounts.context(account_id, input) }),
3533
+ guardedWriteTool13({ ...shared, name: "x_create_promoted_account", provider: "x", kind: "create", destructive: true, description: "Associate one verified FULL promotable profile using expected_context_hash and explicit ACTIVE/live-profile acknowledgements. paused_creation requires a PAUSED ad group. Rejects duplicates, checks receipt and readback, and never retries an uncertain write.", payload: createPromotedAccount }),
3534
+ guardedWriteTool13({ ...shared, name: "x_delete_promoted_account", provider: "x", kind: "remove", destructive: true, description: "Disassociate one exact profile ad with expected_context_hash, native DELETE and independent tombstone readback. Preserves the X profile, other ads, parent delivery and budgets. No profile deletion or fictitious PUT status edit.", payload: deletePromotedAccount })
3535
+ ];
3536
+ }
3537
+
3538
+ // src/tools.ts
567
3539
  function xTools(provider) {
568
3540
  return [
569
- defineTool({ name: "x_list_campaigns", namespace: "x", description: "List X Ads campaigns including inactive, deleted and draft campaigns.", input: z7.object({ account_id: xId }), annotations: { readOnly: true }, handler: (input) => provider.listCampaigns(input.account_id) }),
570
- defineTool({ name: "x_list_funding_instruments", namespace: "x", description: "List existing funding instruments for campaign creation; does not create or change billing.", input: z7.object({ account_id: xId }), annotations: { readOnly: true }, handler: (input) => provider.listFundingInstruments(input.account_id) }),
571
- defineTool({ name: "x_list_line_items", namespace: "x", description: "List X Ads line items (ad groups).", input: z7.object({ account_id: xId }), annotations: { readOnly: true }, handler: (input) => provider.listLineItems(input.account_id) }),
572
- guardedWriteTool({ name: "x_create_campaign", namespace: "x", provider: "x", kind: "create", description: "Create a paused X Ads campaign with an existing funding instrument and account-currency budgets in integer micros. Preview is local.", payload: createCampaignSchema }),
573
- guardedWriteTool({ name: "x_set_campaign_status", namespace: "x", provider: "x", kind: "update", description: "Pause or activate an existing X Ads campaign.", payload: setStatusSchema }),
574
- guardedWriteTool({ name: "x_set_budget", namespace: "x", provider: "x", kind: "update", description: "Change an existing X Ads daily or total campaign budget in integer micros, preserving the other cap.", payload: setBudgetSchema })
3541
+ ...xManagementTools(provider),
3542
+ ...xTargetingTools(provider),
3543
+ ...xCreativeTools(provider),
3544
+ ...xMediaTools(provider),
3545
+ ...xCardTools(provider),
3546
+ ...xAudienceTools(provider),
3547
+ ...xMeasurementTools(provider),
3548
+ ...xPostTools(provider),
3549
+ ...xScheduledTools(provider),
3550
+ ...xDirectMediaTools(provider),
3551
+ ...xPrerollCtaTools(provider),
3552
+ ...xAccountMediaTools(provider),
3553
+ ...xPromotedAccountTools(provider),
3554
+ defineTool14({ name: "x_get_campaign", namespace: "x", description: "Read one campaign\u2019s native budget, funding, currency and delivery configuration within the selected account.", input: z39.object({ account_id: xId, campaign_id: xId }), annotations: { readOnly: true }, handler: (input) => provider.getCampaign(input.account_id, input.campaign_id) }),
3555
+ defineTool14({ name: "x_get_line_item", namespace: "x", description: "Read native line-item bid, budgets, schedule and other configuration, verifying its ID and account-scoped campaign/currency.", input: z39.object({ account_id: xId, line_item_id: xId }), annotations: { readOnly: true }, handler: (input) => provider.getLineItem(input.account_id, input.line_item_id) }),
3556
+ defineTool14({ name: "x_list_campaigns", namespace: "x", description: "List X Ads campaigns including inactive, deleted and draft campaigns.", input: z39.object({ account_id: xId }), annotations: { readOnly: true }, handler: (input) => provider.listCampaigns(input.account_id) }),
3557
+ defineTool14({ name: "x_list_funding_instruments", namespace: "x", description: "List existing funding instruments for campaign creation; does not create or change billing.", input: z39.object({ account_id: xId }), annotations: { readOnly: true }, handler: (input) => provider.listFundingInstruments(input.account_id) }),
3558
+ defineTool14({ name: "x_list_line_items", namespace: "x", description: "List X Ads line items (ad groups).", input: z39.object({ account_id: xId }), annotations: { readOnly: true }, handler: (input) => provider.listLineItems(input.account_id) }),
3559
+ guardedWriteTool14({ name: "x_create_campaign", namespace: "x", provider: "x", kind: "create", description: "Create a paused X Ads campaign with an existing funding instrument and account-currency budgets in integer micros. Preview is local.", payload: createCampaignSchema }),
3560
+ guardedWriteTool14({ name: "x_set_campaign_status", namespace: "x", provider: "x", kind: "update", description: "Pause or activate an existing X Ads campaign.", payload: setStatusSchema }),
3561
+ guardedWriteTool14({ name: "x_set_budget", namespace: "x", provider: "x", kind: "update", description: "Change an existing X Ads daily or total campaign budget in integer micros, preserving the other cap.", payload: setBudgetSchema })
575
3562
  ];
576
3563
  }
577
3564
 
578
3565
  // src/oauth.ts
579
- import { AdportError as AdportError6 } from "@adport/core";
3566
+ import { AdportError as AdportError19 } from "@adport/core";
580
3567
  var REQUEST_TOKEN_URL = "https://api.x.com/oauth/request_token";
581
3568
  var ACCESS_TOKEN_URL = "https://api.x.com/oauth/access_token";
582
3569
  var INVALIDATE_TOKEN_URL = "https://api.x.com/1.1/oauth/invalidate_token.json";
@@ -584,11 +3571,11 @@ var LIMIT = 16 * 1024;
584
3571
  function validToken(value) {
585
3572
  return typeof value === "string" && value.length > 0 && value.length <= 4096 && !/[\s\x00-\x1f\x7f]/.test(value);
586
3573
  }
587
- function requireValues(...values) {
588
- if (!values.every(validToken)) throw new AdportError6("INVALID_INPUT", "x: OAuth credentials or verifier are missing or malformed");
3574
+ function requireValues(...values2) {
3575
+ if (!values2.every(validToken)) throw new AdportError19("INVALID_INPUT", "x: OAuth credentials or verifier are missing or malformed");
589
3576
  }
590
3577
  function failure(message) {
591
- return new AdportError6("PROVIDER_ERROR", `x: ${message}`);
3578
+ return new AdportError19("PROVIDER_ERROR", `x: ${message}`);
592
3579
  }
593
3580
  async function textBody(response) {
594
3581
  const reader = response.body?.getReader();
@@ -613,13 +3600,13 @@ async function textBody(response) {
613
3600
  reader.releaseLock();
614
3601
  }
615
3602
  }
616
- async function signedPost(app, url, parameters, token, fetchImpl) {
617
- requireValues(app.consumerKey, app.consumerSecret);
618
- const signer = createXSigner(app);
619
- const authorization = signer.authorize({ method: "POST", url, data: parameters }, token);
3603
+ async function signedPost(app2, url3, parameters, token, fetchImpl) {
3604
+ requireValues(app2.consumerKey, app2.consumerSecret);
3605
+ const signer = createXSigner(app2);
3606
+ const authorization = signer.authorize({ method: "POST", url: url3, data: parameters }, token);
620
3607
  let response;
621
3608
  try {
622
- response = await fetchImpl(url, { method: "POST", headers: { ...signer.toHeader({ ...authorization, ...parameters }) }, redirect: "error", signal: AbortSignal.timeout(3e4) });
3609
+ response = await fetchImpl(url3, { method: "POST", headers: { ...signer.toHeader({ ...authorization, ...parameters }) }, redirect: "error", signal: AbortSignal.timeout(3e4) });
623
3610
  } catch {
624
3611
  throw failure("OAuth transport failed; restart authorization rather than replaying the exchange");
625
3612
  }
@@ -627,32 +3614,32 @@ async function signedPost(app, url, parameters, token, fetchImpl) {
627
3614
  return response;
628
3615
  }
629
3616
  async function tokens(response) {
630
- const values = new URLSearchParams(await textBody(response));
3617
+ const values2 = new URLSearchParams(await textBody(response));
631
3618
  for (const key of ["oauth_token", "oauth_token_secret"]) {
632
- if (values.getAll(key).length !== 1 || !validToken(values.get(key))) throw failure("malformed OAuth token response");
3619
+ if (values2.getAll(key).length !== 1 || !validToken(values2.get(key))) throw failure("malformed OAuth token response");
633
3620
  }
634
- return values;
3621
+ return values2;
635
3622
  }
636
- async function requestXToken(app, callback, fetchImpl = fetch) {
637
- let url;
3623
+ async function requestXToken(app2, callback, fetchImpl = fetch) {
3624
+ let url3;
638
3625
  try {
639
- url = new URL(callback);
3626
+ url3 = new URL(callback);
640
3627
  } catch {
641
- throw new AdportError6("INVALID_INPUT", "x: an exact registered HTTPS callback is required");
3628
+ throw new AdportError19("INVALID_INPUT", "x: an exact registered HTTPS callback is required");
642
3629
  }
643
- if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) throw new AdportError6("INVALID_INPUT", "x: an exact registered HTTPS callback without query or fragment is required");
644
- const values = await tokens(await signedPost(app, REQUEST_TOKEN_URL, { oauth_callback: url.href }, void 0, fetchImpl));
645
- if (values.getAll("oauth_callback_confirmed").length !== 1 || values.get("oauth_callback_confirmed") !== "true") throw failure("OAuth callback was not confirmed");
646
- return { requestToken: values.get("oauth_token"), requestTokenSecret: values.get("oauth_token_secret") };
3630
+ if (url3.protocol !== "https:" || url3.username || url3.password || url3.search || url3.hash) throw new AdportError19("INVALID_INPUT", "x: an exact registered HTTPS callback without query or fragment is required");
3631
+ const values2 = await tokens(await signedPost(app2, REQUEST_TOKEN_URL, { oauth_callback: url3.href }, void 0, fetchImpl));
3632
+ if (values2.getAll("oauth_callback_confirmed").length !== 1 || values2.get("oauth_callback_confirmed") !== "true") throw failure("OAuth callback was not confirmed");
3633
+ return { requestToken: values2.get("oauth_token"), requestTokenSecret: values2.get("oauth_token_secret") };
647
3634
  }
648
3635
  function buildXAuthorizationUrl(requestToken) {
649
3636
  requireValues(requestToken);
650
3637
  return `https://api.x.com/oauth/authorize?${new URLSearchParams({ oauth_token: requestToken })}`;
651
3638
  }
652
- async function exchangeXToken(app, request, verifier, fetchImpl = fetch) {
653
- requireValues(request.requestToken, request.requestTokenSecret, verifier);
654
- const values = await tokens(await signedPost(app, ACCESS_TOKEN_URL, { oauth_verifier: verifier }, { key: request.requestToken, secret: request.requestTokenSecret }, fetchImpl));
655
- return { accessToken: values.get("oauth_token"), accessTokenSecret: values.get("oauth_token_secret") };
3639
+ async function exchangeXToken(app2, request2, verifier, fetchImpl = fetch) {
3640
+ requireValues(request2.requestToken, request2.requestTokenSecret, verifier);
3641
+ const values2 = await tokens(await signedPost(app2, ACCESS_TOKEN_URL, { oauth_verifier: verifier }, { key: request2.requestToken, secret: request2.requestTokenSecret }, fetchImpl));
3642
+ return { accessToken: values2.get("oauth_token"), accessTokenSecret: values2.get("oauth_token_secret") };
656
3643
  }
657
3644
  async function revokeXToken(credentials, fetchImpl = fetch) {
658
3645
  requireValues(credentials.accessToken, credentials.accessTokenSecret);