ads-mcp-for-snapchat 0.9.7 → 0.9.9
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/ARCHITECTURE.md +1 -1
- package/CHANGELOG.md +19 -1
- package/README.md +12 -5
- package/SECURITY.md +9 -0
- package/package.json +1 -1
- package/src/activation.js +43 -4
- package/src/approval.js +1 -1
- package/src/apps/advice.html +140 -0
- package/src/apps/board.html +134 -95
- package/src/apps/bridge.js +15 -0
- package/src/apps/dashboard.html +19 -0
- package/src/apps/history.html +151 -0
- package/src/apps/preview.html +148 -47
- package/src/apps/setup.html +107 -0
- package/src/apps.js +8 -2
- package/src/async-report.js +34 -3
- package/src/broker.js +3 -1
- package/src/changes.js +12 -4
- package/src/checks.js +30 -5
- package/src/cli.js +0 -0
- package/src/creative-tools.js +5 -1
- package/src/customer-list.js +2 -3
- package/src/dashboard.js +55 -22
- package/src/env.js +3 -0
- package/src/index.js +6 -3
- package/src/interactive.js +114 -0
- package/src/policy.js +1 -1
- package/src/readers.js +3 -2
- package/src/snap.js +16 -1
- package/src/tool-docs.js +5 -4
- package/src/tools.js +103 -16
- package/src/toolsets.js +2 -2
package/ARCHITECTURE.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Architecture and design notes
|
|
2
2
|
|
|
3
|
-
For contributors. Unofficial local MCP server (Node ESM, stdio) for the Snapchat Marketing API:
|
|
3
|
+
For contributors. Unofficial local MCP server (Node ESM, stdio) for the Snapchat Marketing API: 80 tools, all tests mocked (`npm test`). Read `README.md` first for setup and the tool table.
|
|
4
4
|
|
|
5
5
|
## Architecture (src/)
|
|
6
6
|
- `portfolio.js`: several accounts side by side, from the settings files the owner lists in SNAP_PORTFOLIO_FILES (read-only).
|
package/CHANGELOG.md
CHANGED
|
@@ -1,6 +1,24 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
##
|
|
3
|
+
## 0.9.9 (2026-11-21)
|
|
4
|
+
|
|
5
|
+
Fixes from an independent security audit of 0.9.6 (every finding was reproduced with a test first):
|
|
6
|
+
- **Forged login values (F2, high).** The local login listener accepts only a value shaped like a token, and writing a settings value with a line break or control character is refused, so a sealed value can no longer add lines such as `SNAP_HUMAN_APPROVAL=off` to the settings file.
|
|
7
|
+
- **Stale updates (F1, high).** After you answer the "ask before every change" question, the item is read again and nothing is sent if it changed meanwhile; an update is also refused when the item changed since the preview, so a rename can no longer re-enable a campaign you paused.
|
|
8
|
+
- **Campaign-level daily budgets (F3).** Enabling a campaign that has its own daily budget counts and limits that budget (against `SNAP_MAX_DAILY_BUDGET`, the per-call and the 24-hour limits). The first ad squad to deliver under such a campaign counts it too.
|
|
9
|
+
- **`snap_api_get` (F5):** `%2e%2e` and other encoded paths are refused. **Undo (F8):** a forced undo can no longer restore a daily budget above the ceiling when the item has no daily budget now. **Dynamic templates (F9):** one without an ad account is refused. **Ad schedule (F15):** naming only some days works, as documented.
|
|
10
|
+
- **`snap_connect` (F6):** marked destructive; once an ad account is set, read-only mode refuses to switch the account or login, and with human approval on the person is asked first.
|
|
11
|
+
- **Desktop extension (F7):** new optional setting "Ask me before every change"; the wording no longer says a person approves every change when that is off.
|
|
12
|
+
- **Link checker (F11):** connects to the address it checked (no second DNS lookup), still verifying the certificate for the real name; NAT64 addresses count as private. **Customer lists (F12):** an error about a missing column no longer repeats the file's header text. **Approval question (F14):** names are shown on one line, so a name cannot add fake lines.
|
|
13
|
+
- **Ids (F10):** pixel and audience ids given as arguments must belong to the ad account. **Dates (F16):** a plain end date includes that whole day; a refresh token that Snap rotates is saved.
|
|
14
|
+
- **Smaller:** report downloads are not saved when they redirect or exceed 200 MB; auto-strip never drops a field you chose (link, headline, budget, media); the approval store keeps 2000 previews; copying into an existing campaign shows the ad squads already in it.
|
|
15
|
+
- **Documented, not fixed:** the shared login's renew endpoint has no rate limit and the refresh token is a bearer secret; the 24-hour limit lives in one log file; see SECURITY.md "Known limits".
|
|
16
|
+
|
|
17
|
+
- **More interactive tools** (from an independent patch, reviewed and tested here). New read-only tools `snap_change_history` (a filterable timeline of changes with before and after values and Undo buttons) and `snap_setup_check` (a checklist of the login, account, pixel, profile, country, change log and safety settings, with how to fix each). `snap_campaign_board` takes `level` (campaigns or ad squads, with -20% and +20% budget buttons) and `days` (1-30). The budget advice shows as a card where you tick suggestions and apply them together; each one is previewed and uses its own approval token, and a warning in any preview stops the batch instead of applying it. Every preview now starts with `impact_line`, one sentence about the spending effect. Names are shown with `dir="auto"` so Arabic names read correctly; amounts use the account currency (three decimals for KWD, BHD, OMR, JOD). 78 tools became 80; the core set is 48.
|
|
18
|
+
|
|
19
|
+
## 0.9.8 (2026-11-21)
|
|
20
|
+
|
|
21
|
+
- **Fix: the Claude Desktop extension did not start after upgrading to 0.9.7.** 0.9.7 added a required setting (Tool set); an upgraded install has no saved value for it, and Desktop then reports "No MCP config found" and never starts the server. The setting is now optional, the extension passes `SNAP_TOOLSETS_DEFAULT=core`, and the server uses it when the Tool set is empty or was never saved. Tests start the server in every state of the setting and keep new extension settings optional.
|
|
4
22
|
|
|
5
23
|
## 0.9.7 (2026-11-21)
|
|
6
24
|
|
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@ A local [MCP](https://modelcontextprotocol.io) server that lets an AI assistant
|
|
|
5
5
|
> **Unofficial.** Not affiliated with or endorsed by Snap Inc. This tool can change real ad campaigns that spend real money. You use it at your own risk (see LICENSE). Check Snap's developer terms for your own use. Review every preview before approving.
|
|
6
6
|
|
|
7
7
|
## Get started in 2 minutes
|
|
8
|
-
**Claude Desktop (no terminal):** download `ads-mcp-for-snapchat-<version>.mcpb` from the [latest release](https://github.com/Usame794/snapchat-ads-mcp/releases/latest), open it, leave Client ID and secret empty, then ask Claude: "Connect my Snapchat ad account." Log in with Snapchat and pick the ad account. In the Desktop extension, changes are **allowed from the start** (Read-only is off by default): each one is previewed and needs your approval, everything created starts paused, and the daily budget limit starts at 500 (change it in the extension's settings). Switch Read-only on there if you only want to look. It also starts with the **core** tool set (
|
|
8
|
+
**Claude Desktop (no terminal):** download `ads-mcp-for-snapchat-<version>.mcpb` from the [latest release](https://github.com/Usame794/snapchat-ads-mcp/releases/latest), open it, leave Client ID and secret empty, then ask Claude: "Connect my Snapchat ad account." Log in with Snapchat and pick the ad account. In the Desktop extension, changes are **allowed from the start** (Read-only is off by default): each one is previewed and needs your approval, everything created starts paused, and the daily budget limit starts at 500 (change it in the extension's settings). Switch Read-only on there if you only want to look. It also starts with the **core** tool set (48 everyday tools); type `all` in its Tool set field to see all 80.
|
|
9
9
|
|
|
10
10
|
**Claude Code, Cursor, VS Code or a terminal:**
|
|
11
11
|
```bash
|
|
@@ -104,6 +104,7 @@ With this setting the server asks **you**, through the MCP client's own dialog (
|
|
|
104
104
|
| `SNAP_MAX_DAILY_BUDGET` | 1000 | Highest daily budget any single campaign or ad squad may be given or enabled with |
|
|
105
105
|
| `SNAP_MAX_RESPONSE_CHARS` | 100000 | Longest answer a tool returns; longer ones are cut with a note saying how to ask for less. |
|
|
106
106
|
| `SNAP_LEGACY_TOOLS` | off | Set to 1 to also show the old tool names that were merged into other tools (for example `snap_set_status_bulk`, `snap_bulk_set_budget`, `snap_report_daily`). They work as before and say which tool replaced them. Off by default, so the assistant sees fewer tools. |
|
|
107
|
+
| `SNAP_TOOLSETS_DEFAULT` | (none) | Set by the Claude Desktop extension to `core`: used only when `SNAP_TOOLSETS` is empty or was never saved, so upgraded installs start with the core tool set. A real `SNAP_TOOLSETS` value always wins. |
|
|
107
108
|
| `SNAP_MEDIA_DIR` | (none) | Optional folder allow-list: when set, `snap_upload_media` and `snap_upload_customer_list` only read files inside this folder (symbolic links are resolved first). Recommended, so the server cannot be steered into reading other files on your computer. |
|
|
108
109
|
| `SNAP_WARN_DAILY_BUDGET` | (none) | Optional **warning** level, not a limit: a change that adds more than this daily budget shows a `budget_warning` in the preview. Without it, the preview still warns when a change adds more than twice your largest running ad squad (or, on an account with none running, more than half of `SNAP_MAX_DAILY_BUDGET`). |
|
|
109
110
|
| `SNAP_MIN_DAILY_BUDGET` | 5 | Lowest daily budget |
|
|
@@ -119,7 +120,7 @@ With this setting the server asks **you**, through the MCP client's own dialog (
|
|
|
119
120
|
| `SNAP_BROKER_URL` | the maintainer's login service (`off` turns the shared login off) | The shared login service: connect with a normal Snapchat login and no OAuth app. https only. A refresh token is sent there, so use only a service you trust (see `PRIVACY.md`, `broker/README.md`). `setup` saves it for you. |
|
|
120
121
|
| `SNAP_HOME` | `~/.ads-mcp-for-snapchat` for an npm install, the project folder for a git checkout | Where the settings file, the change log and `exports/` live. Set it to keep them somewhere else. |
|
|
121
122
|
| `SNAP_PORTFOLIO_FILES` | (none) | Absolute paths of the settings files of the accounts for `snap_portfolio_summary`, comma-separated (up to 10). Only you can set it: the AI app cannot pick files. |
|
|
122
|
-
| `SNAP_TOOLSETS` | all | Show only some tool groups to the AI app: `core` (
|
|
123
|
+
| `SNAP_TOOLSETS` | all | Show only some tool groups to the AI app: `core` (48 everyday tools: read, check and launch campaigns), or `setup, read, reports, checks, changes, create` (comma-separated, can be combined with core). The Claude Desktop extension starts with `core`; type `all` in its Tool set field to see every tool. Fewer tools make some apps faster and less error-prone, e.g. `setup,reports,checks` for an analyst. It only hides tools. |
|
|
123
124
|
| `SNAP_HUMAN_APPROVAL` | off | `elicit` = ask the user through the MCP client before every write |
|
|
124
125
|
| `SNAP_APPROVAL_TTL_SECONDS` | 600 | Lifetime of an approval token |
|
|
125
126
|
| `SNAP_REPEAT_WINDOW_SECONDS` | 600 | An identical create, copy, claim or upload is refused within this time |
|
|
@@ -171,7 +172,7 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
|
|
|
171
172
|
| `snap_portfolio_summary` | read: all your ad accounts side by side (yesterday and last 7 days, what needs attention, totals per currency). Reads the settings files you list in `SNAP_PORTFOLIO_FILES`; the AI app cannot choose files. |
|
|
172
173
|
| `snap_connect` | connect an ad account from inside the chat (link, pasted address, account choice); saves access on this computer, changes no ads |
|
|
173
174
|
| `snap_list_campaigns`, `snap_list_adsquads`, `snap_list_ads`, `snap_list_creatives`, `snap_get_entity`, `snap_get_media`, `snap_get_stats` | read |
|
|
174
|
-
| `snap_dashboard`, `snap_campaign_board` | read: interactive cards (see "Interactive cards" below): an account dashboard (spend, ROAS, purchases, pacing, 7/14/30 days) and a campaign
|
|
175
|
+
| `snap_dashboard`, `snap_campaign_board` | read: interactive cards (see "Interactive cards" below): an account dashboard (spend, ROAS, purchases, pacing, alerts, 7/14/30 days) and a campaign or ad squad board with Pause, Resume and budget buttons. Without card support the same numbers come back as data |
|
|
175
176
|
| `snap_report` | read: performance reports. `view` = `table` (ROAS, CPA, swipe rate, frequency by ad squad or ad; the default), `daily` (day by day, up to 31 days), `hourly` (by local hour of the day, last 1-7 days, best and worst hours), `compare` (two time windows side by side) or `audience` (by country, gender, age, region, dma or make) |
|
|
176
177
|
| `snap_health_check` | read: audits every active squad for missing buyer exclusion, high frequency, low swipe rate, low ROAS, spend with no purchases, paused parents |
|
|
177
178
|
| `snap_review_issues` | read: rejected / pending ads with Snap's reasons |
|
|
@@ -181,6 +182,8 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
|
|
|
181
182
|
| `snap_api_get` | read-only GET for anything else (allow-listed paths, never writes) |
|
|
182
183
|
| `snap_list_segments`, `snap_list_pixels`, `snap_list_catalogs`, `snap_list_product_sets`, `snap_targeting_options` | read: audiences, pixels, catalogs, product sets, interest/region/language ids |
|
|
183
184
|
| `snap_change_log` | read the local log |
|
|
185
|
+
| `snap_change_history` | read: the changes made through this server, newest first, with before and after values and an Undo button for each one that can be reverted (interactive card) |
|
|
186
|
+
| `snap_setup_check` | read: a checklist of the login, ad account, pixel, brand profile, main country, change log and human approval, plus the money limits in use (interactive card) |
|
|
184
187
|
| `snap_set_status` | pause / enable one item (`id`) or up to 20 (`ids`; skips items already in that state, warns when a parent is paused) |
|
|
185
188
|
| `snap_set_daily_budget`, `snap_set_bid`, `snap_rename` | edit. `snap_set_daily_budget` also takes `adsquad_ids` with `mode` set or scale for up to 20 ad squads; `snap_rename` takes `ids` with `find` and `replace` for up to 20 items |
|
|
186
189
|
| `snap_set_targeting` | change countries, age, gender, interests, device OS, include segments, stop excluding segments; everything else is kept |
|
|
@@ -209,8 +212,12 @@ Ready-made instructions in Claude's prompt menu (the "+" or "/" menu). They only
|
|
|
209
212
|
## Interactive cards (MCP Apps)
|
|
210
213
|
In AI apps that support [MCP Apps](https://modelcontextprotocol.io) (for example Claude), some tools show a small interactive card inside the chat instead of only text:
|
|
211
214
|
- **`snap_dashboard`**: spend, ROAS, purchases, cost per purchase and swipe rate for 7, 14 or 30 days (switch with the buttons), spend by day, and this month's pacing.
|
|
212
|
-
- **`
|
|
213
|
-
-
|
|
215
|
+
- **`snap_dashboard`** also lists alerts from the same days (a spend spike or drop, missing purchases, ROAS or cost per purchase moving sharply), each one dismissible.
|
|
216
|
+
- **`snap_campaign_board`**: campaigns or ad squads (switch with the buttons) with spend, ROAS and purchases for 7, 14 or 30 days, sorting and a "needs a look" filter. **Pause**, **Resume** and, on ad squads, **−20% / +20%** budget buttons first show the change and its spending effect (the daily budget that would start delivering, and the 24-hour total), and nothing happens until you press **Confirm**.
|
|
217
|
+
- **`snap_budget_advice`**: the suggested budget moves as a list to tick; the net change updates as you tick, and **Apply** previews and applies each selected move with its own approval token, one by one, stopping at the first refusal.
|
|
218
|
+
- **`snap_change_history`**: a filterable timeline of changes with before and after values and an **Undo** button that previews the undo first.
|
|
219
|
+
- **`snap_setup_check`**: what is connected and what is missing, the money limits, and whether you are asked before every change.
|
|
220
|
+
- **Preview card**: every tool that previews a change shows its preview as a card that leads with the spending effect in one line, then what changes, a countdown until the approval expires, **Apply** and **Cancel**, and after a single-item edit an **Undo** button (which previews the undo first).
|
|
214
221
|
|
|
215
222
|
How they stay safe: the buttons call the same tools with the same previews, approval tokens, spend limits and read-only setting as before; with `SNAP_READ_ONLY` on, Confirm and Apply stay disabled. The cards have no network access, show names from your account as plain text (never as code), and follow the app's light or dark theme. In apps without card support nothing changes: the same answers arrive as text and data.
|
|
216
223
|
|
package/SECURITY.md
CHANGED
|
@@ -28,3 +28,12 @@ Text that comes back from outside (competitors' ads, page contents, ad review re
|
|
|
28
28
|
|
|
29
29
|
## Safety design
|
|
30
30
|
Write tools need the approval token of a preview of the exact same request, create objects paused, enforce absolute and relative money limits that fail closed, only touch the configured ad account, and record every write in an audit log. The approval token is not a human signature: keep your MCP client's permission prompt on for write tools (see README, "What the approval token is not"). This tool edits real campaigns: review each preview before approving.
|
|
31
|
+
|
|
32
|
+
## Known limits (from the independent audit of 0.9.6)
|
|
33
|
+
These are real and not fixed in code. Know them before you rely on the guards.
|
|
34
|
+
- **Shared login: your refresh token is a bearer secret.** In shared-login mode the login service swaps any refresh token issued to the shared app for an access token, without needing a secret from your computer. Anyone who copies the token out of your settings file can use it until you revoke the app in Snapchat Business Manager. The service has **no rate limit yet**, so heavy use of its renew endpoint could get the shared app limited for everyone. A per-address and per-token limit (a Cloudflare Workers rate limit) is the fix and has to be set up in the deployed service. If this matters to you, use your own Snapchat OAuth app.
|
|
35
|
+
- **The 24-hour spending limit is kept in one change log file.** Two server processes for the same account with different log files each get a full allowance, deleting the log (or pointing `SNAP_LOG_FILE` at `/dev/null`) resets it, and entries dated more than a minute in the future are ignored, so setting the clock back also resets it. The limit protects against mistakes and a misled assistant, not against someone who can edit files on your computer.
|
|
36
|
+
- **Asking you is optional.** `SNAP_HUMAN_APPROVAL` (the Desktop extension's "Ask me before every change") is off by default, because an app that cannot show the question would refuse every change. With it off, the assistant previews and applies changes itself, inside your limits. Turn it on if you want to be asked.
|
|
37
|
+
- **Card pages talk to the chat app with `postMessage(..., "*")`.** Incoming messages are accepted only from the window that embeds the card, so this is safe while the chat app is the only parent; the target origin cannot be narrowed because the app's origin is not known to the card.
|
|
38
|
+
- **Settings in your environment win over the settings file for limits** that the Desktop extension sets itself, and a person or program that can edit your settings file can change limits after a restart.
|
|
39
|
+
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ads-mcp-for-snapchat",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.9",
|
|
4
4
|
"description": "Unofficial local MCP server for the Snapchat Marketing API: reports, audits and safe, previewed changes to campaigns, ad squads and ads.",
|
|
5
5
|
"mcpName": "io.github.Usame794/ads-mcp-for-snapchat",
|
|
6
6
|
"adsMcpBroker": "https://ads-mcp-for-snapchat-login.ads-mcp.workers.dev",
|
package/src/activation.js
CHANGED
|
@@ -39,6 +39,7 @@ export function scheduleOpensDelivery(current, patch, now = Date.now()) {
|
|
|
39
39
|
export async function activationImpact(client, entity, items, policy, { now = Date.now() } = {}) {
|
|
40
40
|
const line = (squad, why) => squadLine(squad, why, now);
|
|
41
41
|
const started = new Map(); // squad id -> line
|
|
42
|
+
const squadCampaign = new Map(); // squad id -> campaign id
|
|
42
43
|
const later = [];
|
|
43
44
|
const campaignCaps = [];
|
|
44
45
|
const campaigns = new Map();
|
|
@@ -50,12 +51,18 @@ export async function activationImpact(client, entity, items, policy, { now = Da
|
|
|
50
51
|
if (entity === "campaign") {
|
|
51
52
|
campaigns.set(obj.id, obj);
|
|
52
53
|
const squads = (await client.listChildren("campaign", obj.id, "adsquad")).filter((s) => s.status === "ACTIVE");
|
|
53
|
-
for (const s of squads)
|
|
54
|
+
for (const s of squads) {
|
|
55
|
+
started.set(s.id, line(s, `ACTIVE ad squad of campaign "${obj.name}"`));
|
|
56
|
+
squadCampaign.set(s.id, obj.id);
|
|
57
|
+
}
|
|
54
58
|
if (obj.daily_budget_micro != null) campaignCaps.push({ campaign_id: obj.id, name: obj.name, campaign_daily_budget: money(obj.daily_budget_micro) });
|
|
55
59
|
if (obj.lifetime_spend_cap_micro != null) campaignCaps.push({ campaign_id: obj.id, name: obj.name, campaign_lifetime_spend_cap: money(obj.lifetime_spend_cap_micro) });
|
|
56
60
|
} else if (entity === "adsquad") {
|
|
57
61
|
const parent = await campaign(obj.campaign_id);
|
|
58
|
-
if (parent.status === "ACTIVE")
|
|
62
|
+
if (parent.status === "ACTIVE") {
|
|
63
|
+
started.set(obj.id, line(obj, "its campaign is ACTIVE"));
|
|
64
|
+
squadCampaign.set(obj.id, obj.campaign_id);
|
|
65
|
+
}
|
|
59
66
|
else later.push({ ...line(obj, `campaign "${parent.name}" is ${parent.status}`), starts: "when the campaign is enabled" });
|
|
60
67
|
} else if (entity === "ad") {
|
|
61
68
|
const squad = await client.getEntity("adsquad", obj.ad_squad_id);
|
|
@@ -63,14 +70,45 @@ export async function activationImpact(client, entity, items, policy, { now = Da
|
|
|
63
70
|
if (squad.status === "ACTIVE" && parent.status === "ACTIVE") {
|
|
64
71
|
const siblings = await client.listChildren("adsquad", squad.id, "ad");
|
|
65
72
|
const alreadyDelivering = siblings.some((a) => a.id !== obj.id && a.status === "ACTIVE");
|
|
66
|
-
if (!alreadyDelivering)
|
|
73
|
+
if (!alreadyDelivering) {
|
|
74
|
+
started.set(squad.id, line(squad, `ad "${obj.name}" would be its first ACTIVE ad`));
|
|
75
|
+
squadCampaign.set(squad.id, squad.campaign_id);
|
|
76
|
+
}
|
|
67
77
|
} else {
|
|
68
78
|
later.push({ ...line(squad, `ad squad is ${squad.status}, campaign is ${parent.status}`), starts: "when its ad squad and campaign are enabled" });
|
|
69
79
|
}
|
|
70
80
|
}
|
|
71
81
|
}
|
|
72
82
|
const lines = [...started.values()];
|
|
73
|
-
const
|
|
83
|
+
const counted = (l) => l.counted_per_day ?? l.daily_budget;
|
|
84
|
+
// Campaign-level daily budgets (the campaign has one budget and its ad squads have none). They start spending too, so they are
|
|
85
|
+
// counted and limited like an ad squad's: a campaign being enabled counts max(its squads' budgets, its own budget); an ad squad or
|
|
86
|
+
// ad that would be the first to deliver under an ACTIVE campaign with its own budget and no budget of its own counts that budget.
|
|
87
|
+
const campaignLines = [];
|
|
88
|
+
if (entity === "campaign") {
|
|
89
|
+
for (const obj of items) {
|
|
90
|
+
const cb = obj.daily_budget_micro > 0 ? money(obj.daily_budget_micro) : 0;
|
|
91
|
+
if (!cb) continue;
|
|
92
|
+
const squadsSum = lines.filter((l) => squadCampaign.get(l.adsquad_id) === obj.id).reduce((n, l) => n + counted(l), 0);
|
|
93
|
+
campaignLines.push({ campaign_id: obj.id, name: obj.name, campaign_daily_budget: cb, counted: round2(Math.max(0, cb - squadsSum)) });
|
|
94
|
+
}
|
|
95
|
+
} else {
|
|
96
|
+
const done = new Set();
|
|
97
|
+
for (const l of lines) {
|
|
98
|
+
const cid = squadCampaign.get(l.adsquad_id);
|
|
99
|
+
const camp = campaigns.get(cid);
|
|
100
|
+
const cb = camp?.daily_budget_micro > 0 ? money(camp.daily_budget_micro) : 0;
|
|
101
|
+
if (!cb || counted(l) > 0 || done.has(cid) || camp.status !== "ACTIVE") continue;
|
|
102
|
+
done.add(cid);
|
|
103
|
+
const others = (await client.listChildren("campaign", cid, "adsquad")).some((s) => s.status === "ACTIVE" && s.id !== l.adsquad_id);
|
|
104
|
+
campaignLines.push({ campaign_id: cid, name: camp.name, campaign_daily_budget: cb, counted: others ? 0 : cb });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const overCampaign = campaignLines.filter((c) => c.campaign_daily_budget > policy.maxDailyBudget && (entity === "campaign" || c.counted > 0));
|
|
108
|
+
if (overCampaign.length) {
|
|
109
|
+
throw new Error(`Refusing to enable: ${overCampaign.map((c) => `campaign "${c.name}" has a daily budget of ${c.campaign_daily_budget}`).join("; ")}, above the absolute limit of ${policy.maxDailyBudget} (SNAP_MAX_DAILY_BUDGET). Only the account owner can raise that limit, in .env, followed by a restart.`);
|
|
110
|
+
}
|
|
111
|
+
const total = round2(lines.reduce((n, l) => n + counted(l), 0) + campaignLines.reduce((n, c) => n + c.counted, 0));
|
|
74
112
|
const lifetime = round2(lines.reduce((n, l) => n + (l.lifetime_budget ?? 0), 0));
|
|
75
113
|
const over = lines.filter((l) => l.daily_budget > policy.maxDailyBudget);
|
|
76
114
|
if (over.length) {
|
|
@@ -89,6 +127,7 @@ export async function activationImpact(client, entity, items, policy, { now = Da
|
|
|
89
127
|
ad_squads_that_start_delivering: lines,
|
|
90
128
|
starts_later: later.length ? later : undefined,
|
|
91
129
|
campaign_level_budgets: campaignCaps.length ? campaignCaps : undefined,
|
|
130
|
+
campaign_budgets_counted: campaignLines.some((c) => c.counted > 0) ? campaignLines : undefined,
|
|
92
131
|
limit_per_call: policy.maxActivationDailyBudget,
|
|
93
132
|
note: "Amounts are in account currency. Ad squads that are already delivering are not counted. A squad with only a lifetime budget is counted at its pace per day (counted_per_day).",
|
|
94
133
|
};
|
package/src/approval.js
CHANGED
|
@@ -58,7 +58,7 @@ export function explainChange(before, after) {
|
|
|
58
58
|
}
|
|
59
59
|
|
|
60
60
|
export class ApprovalStore {
|
|
61
|
-
constructor({ ttlMs = 600_000, repeatWindowMs = 600_000, now = Date.now, max =
|
|
61
|
+
constructor({ ttlMs = 600_000, repeatWindowMs = 600_000, now = Date.now, max = 2000 } = {}) {
|
|
62
62
|
this.ttlMs = ttlMs;
|
|
63
63
|
this.repeatWindowMs = repeatWindowMs;
|
|
64
64
|
this.now = now;
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<title>Budget suggestions</title>
|
|
7
|
+
<style>
|
|
8
|
+
:root{--fb-bg:#fff;--fb-bg2:#f4f5f7;--fb-text:#14171c;--fb-muted:#5b6270;--fb-border:#d9dce2;--fb-good:#1a8a5a;--fb-bad:#c92a2a;--fb-warn:#9a5b00;--accent:#3b5bdb;--fb-warnbg:#fff7e8;--fb-warnline:#f0d9ad}
|
|
9
|
+
@media (prefers-color-scheme:dark){:root{--fb-bg:#1b1d22;--fb-bg2:#252830;--fb-text:#eceef2;--fb-muted:#9aa1ad;--fb-border:#3a3e48;--fb-good:#4cd38e;--fb-bad:#ff7b7b;--fb-warn:#ffc15a;--accent:#8aa0ff;--fb-warnbg:#3a2f1c;--fb-warnline:#6b5527}}
|
|
10
|
+
:root[data-theme=light]{--fb-bg:#fff;--fb-bg2:#f4f5f7;--fb-text:#14171c;--fb-muted:#5b6270;--fb-border:#d9dce2;--fb-good:#1a8a5a;--fb-bad:#c92a2a;--fb-warn:#9a5b00;--accent:#3b5bdb;--fb-warnbg:#fff7e8;--fb-warnline:#f0d9ad}
|
|
11
|
+
:root[data-theme=dark]{--fb-bg:#1b1d22;--fb-bg2:#252830;--fb-text:#eceef2;--fb-muted:#9aa1ad;--fb-border:#3a3e48;--fb-good:#4cd38e;--fb-bad:#ff7b7b;--fb-warn:#ffc15a;--accent:#8aa0ff;--fb-warnbg:#3a2f1c;--fb-warnline:#6b5527}
|
|
12
|
+
:root{--bg:var(--color-background-primary,var(--fb-bg));--bg2:var(--color-background-secondary,var(--fb-bg2));--text:var(--color-text-primary,var(--fb-text));--muted:var(--color-text-secondary,var(--fb-muted));--border:var(--color-border-primary,var(--fb-border));--good:var(--color-text-success,var(--fb-good));--bad:var(--color-text-danger,var(--fb-bad));--warn:var(--color-text-warning,var(--fb-warn));--warnbg:var(--fb-warnbg);--warnline:var(--fb-warnline)}
|
|
13
|
+
*{box-sizing:border-box}
|
|
14
|
+
body{margin:0;padding:16px;background:var(--bg);color:var(--text);font:14px/1.45 var(--font-sans,system-ui,-apple-system,"Segoe UI",sans-serif)}
|
|
15
|
+
h1{font-size:17px;margin:0}.sub{color:var(--muted);font-size:12px}
|
|
16
|
+
.card{background:var(--bg2);border:1px solid var(--border);border-radius:12px;padding:14px}
|
|
17
|
+
.badge{display:inline-block;padding:1px 10px;border-radius:999px;font-size:11px;border:1px solid var(--warn);color:var(--warn)}
|
|
18
|
+
.badge.done{border-color:var(--good);color:var(--good)}.badge.off{border-color:var(--border);color:var(--muted)}
|
|
19
|
+
.pill{display:inline-block;padding:1px 8px;border-radius:999px;font-size:11px;border:1px solid var(--border);margin-right:6px}
|
|
20
|
+
.pill.on{color:var(--good);border-color:var(--good)}.pill.flag{border-color:var(--warn);color:var(--warn)}
|
|
21
|
+
.impact{background:var(--warnbg);border:1px solid var(--warnline);border-radius:10px;padding:10px 12px;font-weight:600;margin:10px 0}
|
|
22
|
+
.impact.calm{background:var(--bg);border-color:var(--border);font-weight:500}
|
|
23
|
+
dl{margin:10px 0;display:grid;grid-template-columns:max-content 1fr;gap:4px 14px}
|
|
24
|
+
dt{color:var(--muted)}dd{margin:0;overflow-wrap:anywhere}
|
|
25
|
+
pre{margin:6px 0 0;white-space:pre-wrap;overflow-wrap:anywhere;font:12px/1.4 ui-monospace,Menlo,monospace;background:var(--bg);border:1px solid var(--border);border-radius:8px;padding:8px}
|
|
26
|
+
.track{height:10px;background:var(--border);border-radius:999px;overflow:hidden;display:flex}
|
|
27
|
+
.track span{display:block;height:100%}
|
|
28
|
+
.warn{color:var(--warn);margin:6px 0}.err{color:var(--bad);margin:6px 0}.ok{color:var(--good);margin:6px 0}
|
|
29
|
+
.btns{display:flex;gap:8px;flex-wrap:wrap;margin-top:12px;align-items:center}
|
|
30
|
+
button{min-height:44px;min-width:44px;padding:0 16px;border-radius:10px;border:1px solid var(--border);background:var(--bg);color:var(--text);font:inherit;cursor:pointer}
|
|
31
|
+
button.primary{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:600}
|
|
32
|
+
button.link{border:0;background:none;color:var(--accent);padding:0;min-height:32px}
|
|
33
|
+
button.chip{min-height:36px;border-radius:999px;padding:0 12px}
|
|
34
|
+
button[aria-pressed=true]{background:var(--accent);border-color:var(--accent);color:#fff}
|
|
35
|
+
button:disabled{opacity:.55;cursor:default}
|
|
36
|
+
button:focus-visible,input:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
|
|
37
|
+
.row{background:var(--bg2);border:1px solid var(--border);border-radius:12px;padding:12px;margin-bottom:10px}
|
|
38
|
+
.row.open{border-color:var(--accent)}
|
|
39
|
+
.top{display:flex;gap:10px;align-items:center;justify-content:space-between;flex-wrap:wrap}
|
|
40
|
+
.name{font-weight:650;overflow-wrap:anywhere}.meta{color:var(--muted);font-size:12px;margin-top:2px}
|
|
41
|
+
.panel{margin-top:10px;border-top:1px dashed var(--border);padding-top:10px}
|
|
42
|
+
.bar{display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:space-between;margin-bottom:12px}
|
|
43
|
+
.seg{display:flex;gap:6px;flex-wrap:wrap}
|
|
44
|
+
.stepper{display:flex;align-items:center;border:1px solid var(--border);border-radius:10px;background:var(--bg)}
|
|
45
|
+
.stepper button{border:0;background:none;font-size:18px}
|
|
46
|
+
.skeleton{background:linear-gradient(90deg,var(--bg2),var(--border),var(--bg2));background-size:200% 100%;animation:sk 1.2s linear infinite;border-radius:12px;min-height:72px;margin-bottom:10px}
|
|
47
|
+
@keyframes sk{to{background-position:-200% 0}}
|
|
48
|
+
@media (prefers-reduced-motion:reduce){.skeleton{animation:none}}
|
|
49
|
+
|
|
50
|
+
</style>
|
|
51
|
+
</head>
|
|
52
|
+
<body>
|
|
53
|
+
<main id="app"><div class="skeleton"></div><div class="skeleton"></div></main>
|
|
54
|
+
<!--BRIDGE-->
|
|
55
|
+
<script>
|
|
56
|
+
(function () {
|
|
57
|
+
const { el, num } = window.snapApp;
|
|
58
|
+
const $ = (id) => document.getElementById(id);
|
|
59
|
+
const state = { items: [], on: {}, status: {}, running: false, note: null, base: null };
|
|
60
|
+
|
|
61
|
+
function load(d) {
|
|
62
|
+
state.base = d;
|
|
63
|
+
state.items = [...(d.decreases || []), ...(d.increases || [])].map((x) => Object.assign({}, x, { diff: Math.round((x.to - x.from) * 100) / 100 }));
|
|
64
|
+
state.on = Object.fromEntries(state.items.map((x) => [x.adsquad_id, true]));
|
|
65
|
+
state.status = {};
|
|
66
|
+
render();
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function render() {
|
|
70
|
+
const root = $("app"); root.textContent = "";
|
|
71
|
+
const d = state.base;
|
|
72
|
+
if (!d) return;
|
|
73
|
+
if (!state.items.length) { root.append(el("div", { class: "card" }, el("h1", null, "Budget suggestions"), el("div", { class: "sub" }, d.note || "Nothing to move right now."))); window.snapApp.resize(); return; }
|
|
74
|
+
const sel = state.items.filter((x) => state.on[x.adsquad_id]);
|
|
75
|
+
const net = sel.reduce((n, x) => n + x.diff, 0);
|
|
76
|
+
const adds = sel.reduce((n, x) => n + Math.max(0, x.diff), 0);
|
|
77
|
+
const card = el("div", { class: "card" });
|
|
78
|
+
card.append(el("h1", null, "Budget suggestions"), el("div", { class: "sub" }, "Median ROAS " + num(d.median_roas) + " over " + (d.window ? d.window.days : "?") + " days · " + d.squads_compared + " ad squads compared"));
|
|
79
|
+
card.append(el("div", { class: "impact" + (adds > 0 ? "" : " calm") }, sel.length + " of " + state.items.length + " selected · net " + (net > 0 ? "+" : "") + num(net) + " per day" + (adds > 0 ? " · adds " + num(adds) + " per day before cuts" : "")));
|
|
80
|
+
const quick = el("div", { class: "seg", style: "margin-bottom:8px" },
|
|
81
|
+
el("button", { type: "button", class: "chip", disabled: state.running, onclick: () => setAll(() => true) }, "Select all"),
|
|
82
|
+
el("button", { type: "button", class: "chip", disabled: state.running, onclick: () => setAll((x) => x.diff < 0) }, "Only cuts"),
|
|
83
|
+
el("button", { type: "button", class: "chip", disabled: state.running, onclick: () => setAll(() => false) }, "None"));
|
|
84
|
+
card.append(quick);
|
|
85
|
+
for (const x of state.items) {
|
|
86
|
+
const id = "s-" + x.adsquad_id;
|
|
87
|
+
const st = state.status[x.adsquad_id];
|
|
88
|
+
const box = el("input", { type: "checkbox", id, disabled: state.running || !!(st && st.ok) , onchange: () => { state.on[x.adsquad_id] = !state.on[x.adsquad_id]; render(); } });
|
|
89
|
+
box.checked = !!state.on[x.adsquad_id];
|
|
90
|
+
box.style.cssText = "width:20px;height:20px;accent-color:var(--accent)";
|
|
91
|
+
const diff = el("div", { style: "font-weight:650" }, (x.diff > 0 ? "+" : "") + num(x.diff) + "/day");
|
|
92
|
+
diff.style.color = x.diff > 0 ? "var(--warn)" : "var(--good)";
|
|
93
|
+
card.append(el("label", { for: id, style: "display:grid;grid-template-columns:28px minmax(0,1fr) auto;gap:10px;align-items:center;padding:10px 0;border-top:1px solid var(--border);cursor:pointer" }, box,
|
|
94
|
+
el("div", { style: "min-width:0" }, el("div", { class: "name", dir: "auto" }, x.adsquad), el("div", { class: "sub" }, x.why), st ? el("div", { class: st.ok ? "ok" : st.err ? "err" : "sub" }, st.text) : null),
|
|
95
|
+
el("div", { style: "text-align:right;white-space:nowrap" }, el("div", { style: "font-size:13px" }, num(x.from) + " → " + num(x.to)), diff)));
|
|
96
|
+
}
|
|
97
|
+
if (state.note) card.append(el("div", { class: state.note.err ? "err" : "ok" }, state.note.text));
|
|
98
|
+
card.append(el("div", { class: "btns" }, el("button", { type: "button", class: "primary", disabled: state.running || !sel.some((x) => !(state.status[x.adsquad_id] || {}).ok), onclick: () => applyAll() }, state.running ? "Applying…" : "Apply " + sel.length + " change" + (sel.length === 1 ? "" : "s"))));
|
|
99
|
+
card.append(el("div", { class: "sub" }, "Each one is previewed and applied with its own approval token, one after another, stopping at the first refusal. Changing a budget can restart Snap's learning."));
|
|
100
|
+
root.append(card);
|
|
101
|
+
window.snapApp.resize();
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function setAll(fn) { if (state.running) return; state.on = Object.fromEntries(state.items.map((x) => [x.adsquad_id, fn(x)])); render(); }
|
|
105
|
+
|
|
106
|
+
async function applyAll() {
|
|
107
|
+
const todo = state.items.filter((x) => state.on[x.adsquad_id] && !(state.status[x.adsquad_id] || {}).ok);
|
|
108
|
+
state.running = true; state.note = null; render();
|
|
109
|
+
let done = 0;
|
|
110
|
+
for (const x of todo) {
|
|
111
|
+
const args = { entity: "adsquad", id: x.adsquad_id, daily_budget: x.to };
|
|
112
|
+
state.status[x.adsquad_id] = { text: "Previewing…" }; render();
|
|
113
|
+
try {
|
|
114
|
+
const p = await window.snapApp.run("snap_set_daily_budget", args);
|
|
115
|
+
if (!p.ok || !p.data || !p.data.approval_token) { state.status[x.adsquad_id] = { err: true, text: p.text || "No approval token in the preview." }; break; }
|
|
116
|
+
// A warning in the preview (an unusual amount, a repeat of a recent change, read-only) is never applied unseen: stop and say so.
|
|
117
|
+
const warning = (p.data.budget_warning && p.data.budget_warning.message) || p.data.duplicate_warning || p.data.read_only;
|
|
118
|
+
if (warning) { state.status[x.adsquad_id] = { err: true, text: "Not applied: " + warning + " Change this one from its own preview in the chat." }; break; }
|
|
119
|
+
state.status[x.adsquad_id] = { text: "Applying…" }; render();
|
|
120
|
+
const r = await window.snapApp.run("snap_set_daily_budget", Object.assign({}, args, { confirm: true, approval_token: p.data.approval_token }));
|
|
121
|
+
if (!r.ok) { state.status[x.adsquad_id] = { err: true, text: r.text }; break; }
|
|
122
|
+
state.status[x.adsquad_id] = { ok: true, text: "Applied." };
|
|
123
|
+
done++;
|
|
124
|
+
} catch (e) { state.status[x.adsquad_id] = { err: true, text: e.message }; break; }
|
|
125
|
+
render();
|
|
126
|
+
}
|
|
127
|
+
state.running = false;
|
|
128
|
+
state.note = done === todo.length ? { text: done + " budget" + (done === 1 ? "" : "s") + " changed. Undo any of them from the change history." } : { err: true, text: "Stopped after " + done + " of " + todo.length + ". The rest were not sent." };
|
|
129
|
+
render();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
window.snapApp.connect({
|
|
133
|
+
"ui/notifications/tool-result": (r) => { if (r && r.isError) { $("app").textContent = window.snapApp.textOf(r); return; } load(window.snapApp.dataOf(r) || {}); },
|
|
134
|
+
error: (e) => { $("app").textContent = "Not connected to the chat app: " + e.message; },
|
|
135
|
+
});
|
|
136
|
+
})();
|
|
137
|
+
|
|
138
|
+
</script>
|
|
139
|
+
</body>
|
|
140
|
+
</html>
|