adloop 0.44.1__tar.gz → 0.45.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. {adloop-0.44.1 → adloop-0.45.0}/PKG-INFO +1 -1
  2. {adloop-0.44.1 → adloop-0.45.0}/pyproject.toml +1 -1
  3. {adloop-0.44.1 → adloop-0.45.0}/pyproject.toml.orig +1 -1
  4. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ga4/audiences.py +261 -65
  5. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/rules/adloop.md +2 -2
  6. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/server.py +29 -6
  7. {adloop-0.44.1 → adloop-0.45.0}/README.md +0 -0
  8. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/__init__.py +0 -0
  9. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/__main__.py +0 -0
  10. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/_mcp_patches.py +0 -0
  11. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/__init__.py +0 -0
  12. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/ai_max.py +0 -0
  13. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/assets.py +0 -0
  14. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/audiences.py +0 -0
  15. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/brands.py +0 -0
  16. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/campaign_settings.py +0 -0
  17. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/client.py +0 -0
  18. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/conversion_actions.py +0 -0
  19. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/currency.py +0 -0
  20. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/custom_conversion_goals.py +0 -0
  21. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/enums.py +0 -0
  22. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/forecast.py +0 -0
  23. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/gaql.py +0 -0
  24. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/image_fetch.py +0 -0
  25. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/pmax.py +0 -0
  26. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/read.py +0 -0
  27. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/recommendation_subscriptions.py +0 -0
  28. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/recommendations.py +0 -0
  29. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/shopping.py +0 -0
  30. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/snippet_headers.py +0 -0
  31. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/validate_only.py +0 -0
  32. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ads/write.py +0 -0
  33. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/auth.py +0 -0
  34. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/cli.py +0 -0
  35. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/config.py +0 -0
  36. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/conversion_setup.py +0 -0
  37. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/crossref.py +0 -0
  38. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/diagnostics.py +0 -0
  39. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ga4/__init__.py +0 -0
  40. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ga4/admin.py +0 -0
  41. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ga4/annotations.py +0 -0
  42. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ga4/attribution.py +0 -0
  43. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ga4/audit.py +0 -0
  44. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ga4/client.py +0 -0
  45. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ga4/definitions.py +0 -0
  46. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ga4/funnels.py +0 -0
  47. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ga4/reports.py +0 -0
  48. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ga4/retention.py +0 -0
  49. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ga4/suggest.py +0 -0
  50. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ga4/tracking.py +0 -0
  51. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/ga4/write.py +0 -0
  52. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/gsc/__init__.py +0 -0
  53. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/gsc/client.py +0 -0
  54. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/gsc/reports.py +0 -0
  55. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/gtm/__init__.py +0 -0
  56. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/gtm/client.py +0 -0
  57. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/gtm/entities.py +0 -0
  58. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/gtm/read.py +0 -0
  59. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/gtm/write.py +0 -0
  60. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/merchant/__init__.py +0 -0
  61. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/merchant/client.py +0 -0
  62. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/merchant/read.py +0 -0
  63. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/microsoft_ads/__init__.py +0 -0
  64. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/microsoft_ads/auth.py +0 -0
  65. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/microsoft_ads/client.py +0 -0
  66. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/microsoft_ads/manage/__init__.py +0 -0
  67. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/microsoft_ads/manage/_common.py +0 -0
  68. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/microsoft_ads/manage/ad_groups.py +0 -0
  69. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/microsoft_ads/manage/ads.py +0 -0
  70. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/microsoft_ads/manage/campaigns.py +0 -0
  71. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/microsoft_ads/manage/extensions.py +0 -0
  72. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/microsoft_ads/manage/negatives.py +0 -0
  73. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/microsoft_ads/manage/removal.py +0 -0
  74. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/microsoft_ads/manage/targeting.py +0 -0
  75. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/microsoft_ads/read.py +0 -0
  76. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/microsoft_ads/write.py +0 -0
  77. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/oauth_redirect.py +0 -0
  78. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/pagespeed.py +0 -0
  79. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/reddit/__init__.py +0 -0
  80. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/reddit/auth.py +0 -0
  81. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/reddit/client.py +0 -0
  82. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/reddit/read.py +0 -0
  83. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/reddit/schedule.py +0 -0
  84. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/reddit/write.py +0 -0
  85. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/rules/__init__.py +0 -0
  86. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/rules/commands/analyze-performance.md +0 -0
  87. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/rules/commands/budget-plan.md +0 -0
  88. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/rules/commands/create-ad.md +0 -0
  89. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/rules/commands/create-campaign.md +0 -0
  90. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/rules/commands/diagnose-tracking.md +0 -0
  91. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/rules/commands/optimize-campaign.md +0 -0
  92. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/rules_install.py +0 -0
  93. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/runtime.py +0 -0
  94. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/safety/__init__.py +0 -0
  95. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/safety/approval.py +0 -0
  96. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/safety/approval_card.html +0 -0
  97. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/safety/audit.py +0 -0
  98. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/safety/guards.py +0 -0
  99. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/safety/outcomes.py +0 -0
  100. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/safety/preview.py +0 -0
  101. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/tracking.py +0 -0
  102. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/upload_card.html +0 -0
  103. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/uploads.py +0 -0
  104. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/views/__init__.py +0 -0
  105. {adloop-0.44.1 → adloop-0.45.0}/src/adloop/views/performance.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: adloop
3
- Version: 0.44.1
3
+ Version: 0.45.0
4
4
  Summary: Google Ads MCP server for Claude, ChatGPT and Cursor, with Reddit Ads, GA4 and Tag Manager. Every change is previewed first.
5
5
  Keywords: mcp,mcp-server,google-ads,google-ads-mcp,reddit-ads,google-analytics,ga4,claude,chatgpt,cursor,marketing
6
6
  Author: Daniel Klose
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "adloop"
3
- version = "0.44.1"
3
+ version = "0.45.0"
4
4
  description = "Google Ads MCP server for Claude, ChatGPT and Cursor, with Reddit Ads, GA4 and Tag Manager. Every change is previewed first."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "adloop"
3
- version = "0.44.1"
3
+ version = "0.45.0"
4
4
  description = "Google Ads MCP server for Claude, ChatGPT and Cursor, with Reddit Ads, GA4 and Tag Manager. Every change is previewed first."
5
5
  readme = "README.md"
6
6
  authors = [
@@ -1,7 +1,7 @@
1
1
  """GA4 audiences: list them, create, rename or archive one.
2
2
 
3
- An audience is a group of users defined by what they did (the events they
4
- sent). GA4 shares its audiences with every linked Google Ads account that
3
+ An audience is a group of users defined by what they did: the events they
4
+ sent, the pages they viewed, or a sequence of both in order. GA4 shares its audiences with every linked Google Ads account that
5
5
  allows personalized advertising, where they show up as remarketing lists
6
6
  (get_audience_lists) and can be attached to campaigns
7
7
  (draft_audience_attachment). That makes a GA4 audience the way to build a
@@ -28,6 +28,12 @@ ADS_MIN_ACTIVE_USERS = 100
28
28
  _EVENT = re.compile(r"^[A-Za-z][A-Za-z0-9_]{0,39}$")
29
29
  _ACTIONS = ("create", "update", "archive")
30
30
  _SCOPE = "AUDIENCE_FILTER_SCOPE_ACROSS_ALL_SESSIONS"
31
+ # A page condition is a page_view event whose page_location (the full URL)
32
+ # contains the text. GA4 names an event parameter by its plain name here.
33
+ _PAGE_EVENT, _PAGE_FIELD = "page_view", "page_location"
34
+ MAX_PAGE_LENGTH = 100
35
+ MAX_SEQUENCE_STEPS = 10
36
+ _STEP_KEYS = {"event", "page", "directly_followed", "within_minutes"}
31
37
  OPERATIONS = {action: f"ga4_{action}_audience" for action in _ACTIONS}
32
38
 
33
39
 
@@ -35,26 +41,60 @@ def _enum(value) -> str:
35
41
  return getattr(value, "name", "") or str(value or "")
36
42
 
37
43
 
38
- def _clause_events(clause) -> list[str] | None:
39
- """Event names of a clause this module could have written, else None.
44
+ def _condition(expression) -> dict | None:
45
+ """``{"event": name}`` or ``{"page": text}`` for a filter this module writes, else None."""
46
+ event = getattr(expression, "event_filter", None)
47
+ name = getattr(event, "event_name", "")
48
+ if not name:
49
+ return None
50
+ params = getattr(getattr(event, "event_parameter_filter_expression", None), "and_group", None)
51
+ groups = list(getattr(params, "filter_expressions", None) or [])
52
+ if not groups:
53
+ return {"event": name}
54
+ inner = list(getattr(getattr(groups[0], "or_group", None), "filter_expressions", None) or [])
55
+ if name != _PAGE_EVENT or len(groups) != 1 or len(inner) != 1:
56
+ return None
57
+ field = getattr(inner[0], "dimension_or_metric_filter", None)
58
+ text = getattr(field, "string_filter", None)
59
+ if getattr(field, "field_name", "") != _PAGE_FIELD or _enum(getattr(text, "match_type", "")) != "CONTAINS":
60
+ return None
61
+ return {"page": text.value} if text.value else None
40
62
 
41
- The shape is one AND group of one OR group of plain event filters.
42
- Anything else (sequences, parameter or dimension filters) is an
43
- audience built elsewhere, reported as ``custom_conditions``.
44
- """
45
- simple = getattr(clause, "simple_filter", None)
46
- expression = getattr(simple, "filter_expression", None)
63
+
64
+ def _any_of(expression) -> list[dict] | None:
65
+ """The conditions of one AND group holding one OR group, else None."""
47
66
  groups = list(getattr(getattr(expression, "and_group", None), "filter_expressions", None) or [])
48
67
  if len(groups) != 1:
49
68
  return None
50
- events = []
51
- for item in list(getattr(getattr(groups[0], "or_group", None), "filter_expressions", None) or []):
52
- event = getattr(item, "event_filter", None)
53
- name = getattr(event, "event_name", "")
54
- if not name or getattr(getattr(event, "event_parameter_filter_expression", None), "and_group", None):
69
+ items = list(getattr(getattr(groups[0], "or_group", None), "filter_expressions", None) or [])
70
+ conditions = [_condition(item) for item in items]
71
+ return conditions if conditions and all(conditions) else None
72
+
73
+
74
+ def _clause_sequence(clause) -> list[dict] | None:
75
+ """The steps of a sequence clause this module could have written, else None."""
76
+ steps = []
77
+ for position, step in enumerate(getattr(getattr(clause, "sequence_filter", None), "sequence_steps", None) or []):
78
+ conditions = _any_of(getattr(step, "filter_expression", None))
79
+ if not conditions or len(conditions) != 1:
55
80
  return None
56
- events.append(name)
57
- return events or None
81
+ entry = dict(conditions[0])
82
+ if position and getattr(step, "immediately_follows", False):
83
+ entry["directly_followed"] = True
84
+ within = getattr(step, "constraint_duration", None)
85
+ seconds = within.total_seconds() if hasattr(within, "total_seconds") else getattr(within, "seconds", 0)
86
+ if position and seconds:
87
+ entry["within_minutes"] = int(seconds // 60)
88
+ steps.append(entry)
89
+ return steps or None
90
+
91
+
92
+ def _is_sequence(clause) -> bool:
93
+ return bool(list(getattr(getattr(clause, "sequence_filter", None), "sequence_steps", None) or []))
94
+
95
+
96
+ def _split(conditions: list[dict]) -> tuple[list[str], list[str]]:
97
+ return [c["event"] for c in conditions if "event" in c], [c["page"] for c in conditions if "page" in c]
58
98
 
59
99
 
60
100
  def audience_entry(audience) -> dict:
@@ -65,24 +105,35 @@ def audience_entry(audience) -> dict:
65
105
  "membership_duration_days": int(audience.membership_duration_days or 0),
66
106
  "ads_personalization_enabled": bool(audience.ads_personalization_enabled),
67
107
  }
68
- include: list[str] = []
69
- exclude: list[str] = []
108
+ include: list[dict] | None = None
109
+ sequence: list[dict] | None = None
110
+ exclude: list[dict] = []
70
111
  custom = False
71
112
  for clause in audience.filter_clauses or []:
72
- events = _clause_events(clause)
73
- if events is None:
113
+ excluded = _enum(clause.clause_type) == "EXCLUDE"
114
+ if _is_sequence(clause):
115
+ steps = _clause_sequence(clause)
116
+ # This module writes one sequence, as the include clause.
117
+ if steps is None or excluded or sequence is not None or include is not None:
118
+ custom = True
119
+ else:
120
+ sequence = steps
121
+ continue
122
+ conditions = _any_of(getattr(getattr(clause, "simple_filter", None), "filter_expression", None))
123
+ if conditions is None:
74
124
  custom = True
75
- elif _enum(clause.clause_type) == "EXCLUDE":
76
- exclude += events
77
- else:
125
+ elif excluded:
126
+ exclude += conditions
127
+ elif include is not None or sequence is not None:
78
128
  # Clauses are AND'ed; this module only ever writes one include clause.
79
- custom = custom or bool(include)
80
- include += events
129
+ custom = True
130
+ else:
131
+ include = conditions
81
132
  if not audience.filter_clauses:
82
133
  # "All Users" and "Purchasers", which GA4 creates itself: the API
83
134
  # returns no conditions for them.
84
135
  entry["predefined"] = True
85
- elif custom or not include:
136
+ elif custom or (include is None and sequence is None):
86
137
  # Built in GA4's own editor with conditions this module does not write.
87
138
  entry["custom_conditions"] = True
88
139
  try:
@@ -90,9 +141,20 @@ def audience_entry(audience) -> dict:
90
141
  except Exception: # noqa: BLE001 - only there to show what the audience matches
91
142
  pass
92
143
  else:
93
- entry["include_events"] = include
144
+ if sequence is not None:
145
+ entry["sequence"] = sequence
146
+ else:
147
+ events, pages = _split(include)
148
+ if events:
149
+ entry["include_events"] = events
150
+ if pages:
151
+ entry["include_pages"] = pages
94
152
  if exclude:
95
- entry["exclude_events"] = exclude
153
+ events, pages = _split(exclude)
154
+ if events:
155
+ entry["exclude_events"] = events
156
+ if pages:
157
+ entry["exclude_pages"] = pages
96
158
  entry["exclude_permanently"] = _enum(audience.exclusion_duration_mode) == "EXCLUDE_PERMANENTLY"
97
159
  return entry
98
160
 
@@ -189,6 +251,60 @@ def _events(label: str, values: list[str] | None, errors: list[str]) -> list[str
189
251
  return names
190
252
 
191
253
 
254
+ def _pages(label: str, values: list[str] | None, errors: list[str]) -> list[str]:
255
+ pages = list(dict.fromkeys(str(v).strip() for v in values or [] if str(v).strip()))
256
+ for page in pages:
257
+ if len(page) > MAX_PAGE_LENGTH:
258
+ errors.append(f"{label} '{page[:40]}...' is longer than {MAX_PAGE_LENGTH} characters")
259
+ elif page == "/":
260
+ errors.append(f"{label} '/' is part of every URL; use include_events=['session_start'] for every visitor")
261
+ return pages
262
+
263
+
264
+ def _steps(values: list | None, errors: list[str]) -> list[dict]:
265
+ """Sequence steps as ``{"event" | "page", directly_followed?, within_minutes?}``."""
266
+ steps: list[dict] = []
267
+ for position, raw in enumerate(values or []):
268
+ where = f"sequence step {position + 1}"
269
+ step = {"event": raw} if isinstance(raw, str) else raw
270
+ if not isinstance(step, dict):
271
+ errors.append(f"{where}: an event name, or an object with event or page")
272
+ continue
273
+ unknown = set(step) - _STEP_KEYS
274
+ if unknown:
275
+ errors.append(f"{where}: unknown key(s) {sorted(unknown)}; use event, page, directly_followed, within_minutes")
276
+ continue
277
+ event, page = str(step.get("event") or "").strip(), str(step.get("page") or "").strip()
278
+ if bool(event) == bool(page):
279
+ errors.append(f"{where}: give exactly one of event or page")
280
+ continue
281
+ entry = {"event": _events(f"{where}:", [event], errors)[0]} if event else {"page": page}
282
+ if page:
283
+ _pages(f"{where}:", [page], errors)
284
+ if step.get("directly_followed"):
285
+ if position == 0:
286
+ errors.append(f"{where}: directly_followed applies from the second step on")
287
+ entry["directly_followed"] = True
288
+ within = step.get("within_minutes")
289
+ if within is not None:
290
+ if position == 0 or isinstance(within, bool) or not isinstance(within, int) or within < 1:
291
+ errors.append(f"{where}: within_minutes is a whole number of minutes, from the second step on")
292
+ else:
293
+ entry["within_minutes"] = within
294
+ steps.append(entry)
295
+ if values and not errors and not 2 <= len(steps) <= MAX_SEQUENCE_STEPS:
296
+ errors.append(f"sequence needs 2 to {MAX_SEQUENCE_STEPS} steps")
297
+ return steps
298
+
299
+
300
+ def _label(condition: dict) -> str:
301
+ return f"viewed a page containing '{condition['page']}'" if "page" in condition else f"sent {condition['event']}"
302
+
303
+
304
+ def _conditions(events: list[str], pages: list[str]) -> list[dict]:
305
+ return [{"event": e} for e in events] + [{"page": p} for p in pages]
306
+
307
+
192
308
  def _find(audiences: list[dict], audience: str) -> list[dict]:
193
309
  wanted = audience.strip()
194
310
  by_resource = [a for a in audiences if a["audience"] == wanted or a["audience"].rsplit("/", 1)[-1] == wanted]
@@ -199,11 +315,28 @@ def _editable(entry: dict) -> dict:
199
315
  return {"display_name": entry["display_name"], "description": entry["description"]}
200
316
 
201
317
 
202
- def _generated_description(include: list[str], exclude: list[str], days: int) -> str:
203
- text = f"Users who sent {' or '.join(include)}"
204
- if exclude:
205
- text += f", without {' or '.join(exclude)}"
206
- return f"{text}; {days} days."
318
+ def _phrase(conditions: list[dict]) -> str:
319
+ events, pages = _split(conditions)
320
+ parts = []
321
+ if events:
322
+ parts.append(f"sent {' or '.join(events)}")
323
+ if pages:
324
+ quoted = " or ".join(f"'{page}'" for page in pages)
325
+ parts.append(f"viewed a page containing {quoted}")
326
+ return " or ".join(parts)
327
+
328
+
329
+ def _generated_description(include: list[dict], exclude: list[dict], sequence: list[dict], days: int) -> str:
330
+ if sequence:
331
+ text = "Users who " + ", then ".join(_label(step) for step in sequence)
332
+ else:
333
+ text = f"Users who {_phrase(include)}"
334
+ if exclude and not _split(exclude)[1]:
335
+ text += f", without {' or '.join(_split(exclude)[0])}"
336
+ elif exclude:
337
+ text += f"; not those who {_phrase(exclude)}"
338
+ # GA4 caps the description at 150 characters.
339
+ return f"{text[:138].rstrip()}; {days} days."
207
340
 
208
341
 
209
342
  def draft_ga4_audience(
@@ -218,6 +351,9 @@ def draft_ga4_audience(
218
351
  membership_duration_days: int = 30,
219
352
  exclude_permanently: bool = False,
220
353
  audience: str = "",
354
+ include_pages: list[str] | None = None,
355
+ exclude_pages: list[str] | None = None,
356
+ sequence: list | None = None,
221
357
  ) -> dict:
222
358
  """Draft creating, renaming or archiving a GA4 audience: returns a PREVIEW."""
223
359
  from adloop.ga4.admin import check_property, fingerprint, service_level
@@ -241,16 +377,22 @@ def draft_ga4_audience(
241
377
  description = description.strip()
242
378
  include = _events("include_events:", include_events, errors)
243
379
  exclude = _events("exclude_events:", exclude_events, errors)
380
+ in_pages = _pages("include_pages:", include_pages, errors)
381
+ out_pages = _pages("exclude_pages:", exclude_pages, errors)
382
+ steps = _steps(sequence, errors)
383
+ has_exclusion = bool(exclude or out_pages)
244
384
 
245
385
  if action == "create":
246
386
  if not display_name:
247
387
  errors.append("display_name is required")
248
- if not include:
388
+ if steps and (include or in_pages):
389
+ errors.append("pass either sequence or include_events / include_pages, not both")
390
+ elif not (include or in_pages or sequence):
249
391
  errors.append(
250
- "include_events is required: the events that put a user in the audience, e.g. "
251
- "['session_start'] for every visitor or ['purchase'] for buyers"
392
+ "say who joins: include_events (e.g. ['session_start'] for every visitor, ['purchase'] for "
393
+ "buyers), include_pages (e.g. ['/pricing']) or a sequence of steps"
252
394
  )
253
- overlap = sorted(set(include) & set(exclude))
395
+ overlap = sorted(set(include) & set(exclude)) + sorted(set(in_pages) & set(out_pages))
254
396
  if overlap:
255
397
  errors.append(f"{', '.join(overlap)} cannot be both included and excluded")
256
398
  try:
@@ -259,8 +401,8 @@ def draft_ga4_audience(
259
401
  days = 0
260
402
  if not 1 <= days <= MAX_MEMBERSHIP_DAYS:
261
403
  errors.append(f"membership_duration_days must be between 1 and {MAX_MEMBERSHIP_DAYS}")
262
- if exclude_permanently and not exclude:
263
- errors.append("exclude_permanently needs exclude_events")
404
+ if exclude_permanently and not has_exclusion:
405
+ errors.append("exclude_permanently needs exclude_events or exclude_pages")
264
406
  elif not audience:
265
407
  errors.append(f"name the audience to {action}: its display name or its resource name (list_ga4_audiences)")
266
408
  if errors:
@@ -280,23 +422,35 @@ def draft_ga4_audience(
280
422
  changes = {
281
423
  "property_id": pid,
282
424
  "display_name": display_name,
283
- "description": description or _generated_description(include, exclude, days),
284
- "include_events": include,
425
+ "description": description or _generated_description(
426
+ _conditions(include, in_pages), _conditions(exclude, out_pages), steps, days),
285
427
  "membership_duration_days": days,
286
428
  }
287
- if exclude:
288
- changes["exclude_events"] = exclude
429
+ for key, value in (("sequence", steps), ("include_events", include), ("include_pages", in_pages),
430
+ ("exclude_events", exclude), ("exclude_pages", out_pages)):
431
+ if value:
432
+ changes[key] = value
433
+ if has_exclusion:
289
434
  changes["exclude_permanently"] = bool(exclude_permanently)
290
435
  warnings += [
291
- "The events and the membership duration cannot be changed after creation; only the name and "
436
+ "The conditions and the membership duration cannot be changed after creation; only the name and "
292
437
  "description can. A wrong audience has to be archived and created again.",
293
438
  "GA4 fills it from now on, and adds users who met the conditions in the last 30 days for its use "
294
439
  "in Google Ads. It takes one to two days to appear in a linked Google Ads account.",
295
440
  ]
296
- if exclude and exclude_permanently:
441
+ if in_pages or out_pages or any("page" in step for step in steps):
442
+ warnings.append(
443
+ "A page matches when its full URL contains the text, without regard to upper and lower case: "
444
+ "'/pricing' also matches '/pricing/enterprise' and '/en/pricing'. Page views are counted from "
445
+ "GA4's page_view event."
446
+ )
447
+ if steps:
297
448
  warnings.append(
298
- f"Users who ever sent {' or '.join(exclude)} are kept out for good, also after they stop."
449
+ "The steps have to happen in this order; a user who did them in another order does not join."
299
450
  )
451
+ if has_exclusion and exclude_permanently:
452
+ kept_out = " or ".join(_label(c) for c in _conditions(exclude, out_pages))
453
+ warnings.append(f"Users who ever {kept_out} are kept out for good, also after they stop.")
300
454
  warnings += [c["detail"] for c in ads_readiness(config, pid) if c["status"] == "warn" or c["check"] == "consent"]
301
455
  plan = ChangePlan(operation=operation, entity_type="ga4_audience", entity_id=display_name, changes=changes)
302
456
  else:
@@ -328,9 +482,9 @@ def draft_ga4_audience(
328
482
  if not description:
329
483
  return {"error": "GA4 requires a description; it cannot be emptied."}
330
484
  after["description"] = description
331
- if include or exclude:
332
- return {"error": "GA4 fixes an audience's events at creation. Only display_name and description "
333
- "can change; archive the audience and create a new one for other events."}
485
+ if include or exclude or in_pages or out_pages or steps:
486
+ return {"error": "GA4 fixes an audience's conditions at creation. Only display_name and description "
487
+ "can change; archive the audience and create a new one for other conditions."}
334
488
  changed = [k for k in after if after[k] != before[k]]
335
489
  if not changed:
336
490
  return {"status": "NO_CHANGE", "message": f"The audience '{current['display_name']}' already has these values.",
@@ -379,25 +533,62 @@ def preflight(config: AdLoopConfig, plan) -> dict:
379
533
  return {"slots_left_after_apply": limit - len(audiences) - 1}
380
534
 
381
535
 
382
- def _clause(types, clause_type: str, events: list[str]):
383
- """One clause: users who sent any of ``events``, at any time.
536
+ def _expression(types, conditions: list[dict]):
537
+ """Users who met any of ``conditions``, at any time.
384
538
 
385
539
  GA4 wants an AND group at the top that holds OR groups, and event
386
540
  filters only inside an OR group.
387
541
  """
542
+ def group(kind: str, items: list):
543
+ return types.AudienceFilterExpression(**{kind: types.AudienceFilterExpressionList(filter_expressions=items)})
544
+
545
+ def event_filter(condition: dict):
546
+ if "event" in condition:
547
+ return types.AudienceEventFilter(event_name=condition["event"])
548
+ field = types.AudienceDimensionOrMetricFilter(
549
+ field_name=_PAGE_FIELD,
550
+ string_filter=types.AudienceDimensionOrMetricFilter.StringFilter(
551
+ match_type=types.AudienceDimensionOrMetricFilter.StringFilter.MatchType.CONTAINS,
552
+ value=condition["page"],
553
+ ),
554
+ at_any_point_in_time=True,
555
+ )
556
+ return types.AudienceEventFilter(
557
+ event_name=_PAGE_EVENT,
558
+ event_parameter_filter_expression=group("and_group", [
559
+ group("or_group", [types.AudienceFilterExpression(dimension_or_metric_filter=field)])
560
+ ]),
561
+ )
562
+
563
+ return group("and_group", [
564
+ group("or_group", [types.AudienceFilterExpression(event_filter=event_filter(c)) for c in conditions])
565
+ ])
566
+
567
+
568
+ def _clause(types, clause_type: str, conditions: list[dict]):
388
569
  return types.AudienceFilterClause(
389
570
  clause_type=types.AudienceFilterClause.AudienceClauseType[clause_type],
390
571
  simple_filter=types.AudienceSimpleFilter(
391
- scope=types.AudienceFilterScope[_SCOPE],
392
- filter_expression=types.AudienceFilterExpression(
393
- and_group=types.AudienceFilterExpressionList(filter_expressions=[
394
- types.AudienceFilterExpression(or_group=types.AudienceFilterExpressionList(filter_expressions=[
395
- types.AudienceFilterExpression(event_filter=types.AudienceEventFilter(event_name=name))
396
- for name in events
397
- ]))
398
- ])
399
- ),
400
- ),
572
+ scope=types.AudienceFilterScope[_SCOPE], filter_expression=_expression(types, conditions)),
573
+ )
574
+
575
+
576
+ def _sequence_clause(types, steps: list[dict]):
577
+ from datetime import timedelta
578
+
579
+ scope = types.AudienceFilterScope[_SCOPE]
580
+ built = []
581
+ for step in steps:
582
+ kwargs = {}
583
+ if step.get("directly_followed"):
584
+ kwargs["immediately_follows"] = True
585
+ if step.get("within_minutes"):
586
+ kwargs["constraint_duration"] = timedelta(minutes=step["within_minutes"])
587
+ built.append(types.AudienceSequenceFilter.AudienceSequenceStep(
588
+ scope=scope, filter_expression=_expression(types, [step]), **kwargs))
589
+ return types.AudienceFilterClause(
590
+ clause_type=types.AudienceFilterClause.AudienceClauseType["INCLUDE"],
591
+ sequence_filter=types.AudienceSequenceFilter(scope=scope, sequence_steps=built),
401
592
  )
402
593
 
403
594
 
@@ -405,10 +596,15 @@ def build_audience(changes: dict):
405
596
  """The Audience message for a create plan."""
406
597
  from google.analytics.admin_v1alpha import types
407
598
 
408
- clauses = [_clause(types, "INCLUDE", changes["include_events"])]
599
+ if changes.get("sequence"):
600
+ clauses = [_sequence_clause(types, changes["sequence"])]
601
+ else:
602
+ clauses = [_clause(types, "INCLUDE", _conditions(changes.get("include_events") or [],
603
+ changes.get("include_pages") or []))]
409
604
  kwargs = {}
410
- if changes.get("exclude_events"):
411
- clauses.append(_clause(types, "EXCLUDE", changes["exclude_events"]))
605
+ excluded = _conditions(changes.get("exclude_events") or [], changes.get("exclude_pages") or [])
606
+ if excluded:
607
+ clauses.append(_clause(types, "EXCLUDE", excluded))
412
608
  mode = "EXCLUDE_PERMANENTLY" if changes.get("exclude_permanently") else "EXCLUDE_TEMPORARILY"
413
609
  kwargs["exclusion_duration_mode"] = types.Audience.AudienceExclusionDurationMode[mode]
414
610
  return types.Audience(
@@ -115,12 +115,12 @@ Same draft → preview → `confirm_and_apply` gate as Google Ads. The GA4 Admin
115
115
  | `draft_ga4_annotation` | Create, change or delete an annotation (a note on a date or range in GA4's charts). Google's own annotations cannot be changed | `action` (create/update/delete), `title` (≤60), `date` (+ `end_date` for a range), `description` (≤150), `color`, `annotation` (ID for update/delete) |
116
116
  | `draft_ga4_custom_dimension` | Register an event parameter, user property or item parameter as a dimension; rename or archive one (archive cannot be undone) | `action` (create/update/archive), `parameter_name`, `scope` (EVENT/USER/ITEM), `display_name`, `description` |
117
117
  | `draft_ga4_custom_metric` | Register a numeric event parameter as a metric; change or archive one | `action`, `parameter_name`, `display_name`, `measurement_unit` (STANDARD, CURRENCY, ...), `restricted_metric_type` (required for CURRENCY) |
118
- | `draft_ga4_audience` | Create an audience from events (visitors, buyers, visitors who did not buy); rename or archive one. Linked Google Ads accounts receive it as a remarketing list | `action`, `display_name`, `include_events`, `exclude_events`, `membership_duration_days` (1-540), `exclude_permanently`, `audience` (for update/archive) |
118
+ | `draft_ga4_audience` | Create an audience from events, pages or a sequence (visitors, buyers, visitors who did not buy, pricing-page visitors who did not sign up, people who started checkout after viewing a product); rename or archive one. Linked Google Ads accounts receive it as a remarketing list | `action`, `display_name`, `include_events`, `exclude_events`, `include_pages` / `exclude_pages` (URL contains), `sequence` (2-10 ordered steps: event names or `{"page": "/pricing"}`, optional `directly_followed`, `within_minutes`), `membership_duration_days` (1-540), `exclude_permanently`, `audience` (for update/archive) |
119
119
  | `draft_ga4_data_retention` | Change how long GA4 keeps event- and user-level data (default 2 months; standard properties allow 14, GA4 360 up to 50). Shortening deletes older data and needs a double confirmation | `event_data_retention` / `user_data_retention` (months: 2, 14, 26, 38, 50), `reset_user_data_on_new_activity` |
120
120
 
121
121
  - A new custom dimension or metric is filled only from now on: events sent before stay without it, and data can take a day or two to show. Say so before the user approves. `parameter_name` and scope cannot change later, so check the spelling against the code that sends the parameter.
122
122
  - Check `list_ga4_custom_definitions` before creating: the draft refuses a full property, a duplicate parameter and a taken display name, but the user should hear about the limit before asking.
123
- - **Remarketing lists come from GA4 audiences.** To retarget site visitors: `list_ga4_audiences` first (GA4 creates "All Users" and "Purchasers" by default, so the list may exist already, and `google_ads_readiness` says whether audiences reach Google Ads at all), then `draft_ga4_audience` for what is missing, then after one to two days `get_audience_lists` in Google Ads and `draft_audience_attachment` on the campaign. On Search this needs no display ads: attach the list as observation to bid on past visitors, or exclude buyers. Tell the user before they approve: an audience's events and duration cannot be edited later, a list serves only from 100 active users in 30 days (a small site may never get there), and visitors who declined the consent banner never join. Advertisers in sensitive categories (health, finances, and similar) may not use their own audiences for ads at all.
123
+ - **Remarketing lists come from GA4 audiences.** To retarget site visitors: `list_ga4_audiences` first (GA4 creates "All Users" and "Purchasers" by default, so the list may exist already, and `google_ads_readiness` says whether audiences reach Google Ads at all), then `draft_ga4_audience` for what is missing, then after one to two days `get_audience_lists` in Google Ads and `draft_audience_attachment` on the campaign. On Search this needs no display ads: attach the list as observation to bid on past visitors, or exclude buyers. Tell the user before they approve: an audience's conditions and duration cannot be edited later, a list serves only from 100 active users in 30 days (a small site may never get there), and visitors who declined the consent banner never join. Advertisers in sensitive categories (health, finances, and similar) may not use their own audiences for ads at all. Pages match when the full URL contains the text (`/pricing` also matches `/en/pricing` and `/pricing/enterprise`), so check the site's real paths (`run_ga4_report` with `pagePath`) before drafting, and pass every language variant of a page. Use `sequence` only when the order matters; "visited A and did not do B" is `include_pages` plus `exclude_events`, which fills faster than a sequence.
124
124
  - Key events feed Google Ads. Before removing one, or changing how it counts, check with `check_key_event_imports` whether Google Ads imports it: that conversion action changes with it.
125
125
  - Data retention only limits explorations, funnels and other user-level reports; standard reports are not affected. Longer retention helps from now on only. Before the user approves, remind them that a privacy policy naming a retention period must match the new one.
126
126
 
@@ -1511,8 +1511,10 @@ def list_ga4_audiences(property_id: str = "") -> dict:
1511
1511
  allows personalized advertising; there they are remarketing lists
1512
1512
  (get_audience_lists) that draft_audience_attachment puts on a campaign.
1513
1513
  Returns each audience's resource name, display name, description,
1514
- membership duration and the events that include or exclude users
1515
- (audiences built with other conditions in GA4's editor carry
1514
+ membership duration and what includes or excludes users: events,
1515
+ pages (include_pages / exclude_pages: the URL contains the text) or
1516
+ a sequence of steps (audiences built with other conditions in GA4's
1517
+ editor carry
1516
1518
  custom_conditions and the raw conditions; "All Users" and "Purchasers",
1517
1519
  which GA4 creates itself, carry predefined), the audience slots used
1518
1520
  against the limit (100, or 400 on a 360 property), and
@@ -8493,14 +8495,19 @@ def draft_ga4_audience(
8493
8495
  description: str | None = None,
8494
8496
  audience: str = "",
8495
8497
  property_id: str = "",
8498
+ include_pages: _StrList = [], # noqa: B006
8499
+ exclude_pages: _StrList = [], # noqa: B006
8500
+ sequence: _StrOrDictListOpt = None,
8496
8501
  ) -> dict:
8497
8502
  """Draft creating, renaming or archiving a GA4 audience — returns a PREVIEW.
8498
8503
 
8499
- An audience is the users who sent certain events. A linked Google Ads
8504
+ An audience is the users who sent certain events, viewed certain
8505
+ pages, or did a sequence of both in order. A linked Google Ads
8500
8506
  account receives it as a remarketing list within one to two days, to
8501
8507
  attach to campaigns with draft_audience_attachment: this is how to
8502
- build a list of site visitors, of buyers, or of visitors who did not
8503
- buy. GA4 fixes the events and the membership duration at creation;
8508
+ build a list of site visitors, of buyers, of visitors who did not
8509
+ buy, or of people who saw the pricing page without signing up. GA4
8510
+ fixes the conditions and the membership duration at creation;
8504
8511
  afterwards only the name and description can change, and archiving is
8505
8512
  permanent (it needs a double confirmation). The draft refuses a taken
8506
8513
  name and a full property, and the preview warns when the property's
@@ -8514,10 +8521,23 @@ def draft_ga4_audience(
8514
8521
  name for update.
8515
8522
  include_events: Create only. Users who sent ANY of these events
8516
8523
  join, e.g. ["session_start"] for every visitor, ["purchase"]
8517
- for buyers, ["sign_up", "generate_lead"] for leads.
8524
+ for buyers, ["sign_up", "generate_lead"] for leads. Together
8525
+ with include_pages it is still "any of".
8518
8526
  exclude_events: Create only. Users who sent any of these are kept
8519
8527
  out, e.g. include ["session_start"] and exclude ["purchase"]
8520
8528
  for visitors who did not buy.
8529
+ include_pages: Create only. Users who viewed a page whose full
8530
+ URL contains ANY of these texts join, e.g. ["/pricing"]
8531
+ (also matches /pricing/enterprise and /en/pricing). Not case
8532
+ sensitive.
8533
+ exclude_pages: Create only. Users who viewed such a page are kept
8534
+ out, e.g. ["/thank-you"].
8535
+ sequence: Create only, instead of include_events / include_pages.
8536
+ 2 to 10 steps the user must do in this order. Each is an event
8537
+ name ("begin_checkout") or an object: {"event": "..."} or
8538
+ {"page": "/pricing"}, optionally with "directly_followed": true
8539
+ (no other event in between) and "within_minutes": 30 (after
8540
+ the step before). Exclusions can be added as usual.
8521
8541
  membership_duration_days: Create only. Days a user stays after
8522
8542
  last meeting the conditions, 1 to 540 (default 30).
8523
8543
  exclude_permanently: Create only. True keeps users out for good
@@ -8543,6 +8563,9 @@ def draft_ga4_audience(
8543
8563
  membership_duration_days=membership_duration_days,
8544
8564
  exclude_permanently=exclude_permanently,
8545
8565
  audience=audience,
8566
+ include_pages=include_pages,
8567
+ exclude_pages=exclude_pages,
8568
+ sequence=sequence,
8546
8569
  )
8547
8570
 
8548
8571
 
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes