Schedule ads

From aaronjmars/aeon · View interactive version

Schedule ads is an AI agent skill from the GitHub repository aaronjmars/aeon. Manage paid ads on AdManage.ai from declarative config - default schedules launches across Meta/TikTok/Snapchat/Pinterest/LinkedIn (always PAUSED); create provisions Meta campaigns and ad sets.

How to use this skill

Skill file

${var} selects the flow. Empty/unset = schedule (launch ads into existing ad sets). create = create-campaign (provision Meta campaigns + ad sets). Both are config-driven, PAUSED-by-default, and make the AdManage API calls in-run via ./secretcurl (the {ADMANAGE_API_KEY} placeholder keeps the key off the command line), behind fail-closed spend guardrails.

Reads a declarative config, computes what to do, and makes the AdManage.ai API calls in-run via ./secretcurl. The calls are an irreversible outbound side-effect (real ad spend), so they are each branch's final actions and run only behind the guardrails below (PAUSED-by-default, dailySpendCap circuit-breaker, dry-run). ADMANAGE_API_KEY is injected in-run via this skill's requires: — always write it as the {ADMANAGE_API_KEY} placeholder, never a bare $ADMANAGE_API_KEY (the Bash permission layer refuses that).

Preamble (both branches)

  1. Read memory/MEMORY.md for context. Read the last ~3 days of memory/logs/ for recent launch / provisioning activity — don't re-report a signal already logged.
  2. Parse ${var}:
  1. Both branches spend real money on ad platforms. The shared safety posture (see each branch) is: PAUSED by default, config-only (never invent campaigns/creative/targeting), dry-run available, and exit silently when there's nothing to do.

Schedule branch (default — empty `${var}`)

Reads skills/schedule-ads/config.yaml, picks schedule entries matching today, and launches those ads in-run via AdManage.ai (POST /v1/launch through ./secretcurl), behind the spend guardrails below.

Safety defaults (schedule)

This branch spends real money on ad platforms. Guardrails, in priority order:

  1. PAUSED by default. Every launch request sets the entity to PAUSED. The operator has to resume manually in the AdManage dashboard before spend starts. launchPaused: false in config is the explicit opt-out.
  2. Daily spend cap. Before launching, the branch checks GET /v1/spend/daily for today. If spend ≥ dailySpendCap in the config, all launches are skipped and a warning is notified. If the spend figure can't be verified (malformed / empty response), fail closed — skip and notify, don't launch. This is a circuit breaker, not a budget enforcer — platform budgets still apply.
  3. Dry-run mode. If DRY_RUN=true in env or dryRun: true in config, the branch builds the payloads, writes them to .pending-admanage/dryrun/, notifies what would launch, and exits without calling the API.
  4. Config-only. The branch does not invent campaigns, creative, or targeting. If there's no schedule for today, it exits cleanly with no API calls.
  5. Single source of truth. All ads/campaigns/targeting live in config.yaml. The branch never generates new creative on the fly.

Network note (schedule)

Launching ads is an irreversible outbound side-effect (real ad spend), so it is the branch's final action and runs only after the guardrails above pass:

Steps (schedule)

  1. Load config. Read skills/schedule-ads/config.yaml. If the file doesn't exist, log SCHEDULE_ADS_NOT_CONFIGURED and exit cleanly (no notify, no error). The example template lives next to this file as config.example.yaml.
  1. Validate config shape. Required top-level keys: defaults (with adAccountId, workspaceId, page), and schedules (array). If either is missing, file an issue in memory/issues/ per the CLAUDE.md issue tracker convention, notify once, and exit.
  1. Pick today's schedule entries. For each entry in schedules, match against today's date:

If no entries match today, log SCHEDULE_ADS_NOTHING_TODAY and exit cleanly (no notify).

  1. Build launch payloads. For each matching schedule entry, construct the AdManage POST /v1/launch body:

```json

{

"ads": [

{

"adName": "<templated from ad.adName, {date} replaced>",

"adAccountId": "<from defaults or entry override>",

"workspaceId": "<from defaults or entry override>",

"title": "<from ad>",

"description": "<from ad>",

"cta": "<from ad or defaults.cta>",

"link": "<from ad>",

"page": "<from defaults>",

"insta": "<from defaults, Meta only>",

"adSets": [ { "value": "<id>", "label": "<name>" } ],

"media": [ { "url": "<media url>" } ],

"status": "PAUSED"

}

]

}

```

Enforce status: PAUSED on every ad unless defaults.launchPaused is explicitly false. Never strip it silently.

Template substitutions inside string fields:

  1. Pre-flight validation. For each payload:

Drop invalid entries, keep going. Log which ones were skipped and why.

  1. Handle dry-run. If DRY_RUN=true or config.dryRun: true:
  1. Launch in-run. This is the branch's final action — spends real money, so run the guardrails first. Only ./secretcurl, jq, date, echo, mkdir, grep, python3, and the Write tool are available.

a. Config check. Read the "Keys set for this run" line in your run notes, never a shell test (those are refused and cost a turn). If ADMANAGE_API_KEY is not on that line → notify "ads computed but ADMANAGE_API_KEY missing — nothing launched" and stop.

b. Daily spend circuit-breaker (once). Take the strictest dailySpendCap (CAP) across today's payloads. If set, read today's spend and fail closed unless it's a clean number below the cap. Each step is its own Bash call:

```bash

date -u +%Y-%m-%d

```

It prints TODAY. Then, with TODAY written in literally:

```bash

./secretcurl -sS --max-time 30 -H "Authorization: Bearer {ADMANAGE_API_KEY}" \

"https://api.admanage.ai/v1/spend/daily?startDate=<TODAY>&endDate=<TODAY>" | jq -r '.metadata.totalSpend // ""'

```

It prints SPEND. Check that it is a clean number:

```bash

echo "<SPEND>" | grep -E '^[0-9]+(\.[0-9]+)?$'

```

If that prints nothing, say "spend unverifiable - fail closed" and stop (launch nothing). Check CAP the same way:

```bash

echo "<CAP>" | grep -E '^[0-9]+(\.[0-9]+)?$'

```

If that prints nothing, say "dailySpendCap not numeric - fail closed" and stop. Then compare:

```bash

python3 -c "import sys; print('TRIPPED' if float(sys.argv[1])>=float(sys.argv[2]) else 'UNDER_CAP')" "<SPEND>" "<CAP>"

```

If it prints TRIPPED, say "daily spend cap tripped (today=<SPEND> cap=<CAP>) - launching nothing" and stop. Only UNDER_CAP goes on to step c.

c. Per batch: launch, then poll. For each payload { ads: [ ... ] }, write it with Write to /tmp/schedule-ads-launch.json (overwrite per batch), then one call:

```bash

./secretcurl -sS --max-time 60 -w 'http=%{http_code}\n' -X POST "https://api.admanage.ai/v1/launch" \

-H "Authorization: Bearer {ADMANAGE_API_KEY}" -H "Content-Type: application/json" -d @/tmp/schedule-ads-launch.json

```

It prints the response (RESP) and an http= line. Success => .success==true and .adBatchId set; else record FAILED (.message/.error) and continue. Then poll the batch (~90s, 5s interval): repeat this one call, with BATCH_ID written in literally, until .summaryStatus is success or error, at most 18 times, waiting 5 s between calls with one python3 -c "import time; time.sleep(5)" call:

```bash

./secretcurl -sS --max-time 30 -H "Authorization: Bearer {ADMANAGE_API_KEY}" "https://api.admanage.ai/v1/batch-status/<BATCH_ID>"

```

Record each batch's outcome (ok / error / still-running-after-timeout) for the notify. Ads launch PAUSED (the payload sets it) unless launchPaused: false.

  1. Write artifact to output/.chains/schedule-ads.md so downstream chain consumers can read what was queued. Format:

```markdown

# Schedule Ads - ${today}

Queued: N launches across M schedules.

Dry-run: yes|no.

## Entries

```

  1. Notify via ./notify. Keep it tight:

```

Ads queued - ${today}${dryRunSuffix}

<N> launches queued from <M> schedules.

"<first adName>"

<if dry-run>

no API calls made - remove DRY_RUN to arm.

<else>

launched via AdManage (PAUSED) - resume in the dashboard to start delivery.

```

If nothing matched today (no launches), don't notify at all.

  1. Log — see the shared Log section below (discriminator: schedule).

Config schema (schedule)

See skills/schedule-ads/config.example.yaml for a filled-in template. Minimum viable config:

defaults:
  adAccountId: act_XXXXXXXXXX
  workspaceId: XXXXXXXXXXXX
  page: XXXXXXXXXXXX         # Meta Page ID
  insta: XXXXXXXXXXXX        # Instagram user ID
  cta: LEARN_MORE
  launchPaused: true         # NEVER change this without thought
  dailySpendCap: 50          # USD. Circuit breaker.
  dryRun: false

schedules:
  - name: weekly-promo
    platform: meta
    when: { dayOfWeek: monday }
    adSets:
      - { value: "120xxxxxxxxxxxxx", label: "US Broad 25-55" }
    ads:
      - adName: "Weekly promo — {date}"
        title: "Headline copy here"
        description: "Supporting copy in a sentence or two."
        cta: LEARN_MORE
        link: https://example.com
        media:
          - url: https://media.admanage.ai/your-account/hero.mp4

What the schedule branch does NOT do


Create branch (`${var}=create`)

Reads skills/schedule-ads/config.create.yaml, figures out which campaigns/ad sets don't exist yet, and creates them in-run via AdManage.ai (/v1/manage/create-* through ./secretcurl) — campaigns first, then ad sets referencing the returned campaign IDs — writing the new IDs back to .admanage-state/campaigns.json.

This branch is on-demand — invoke it manually when you want to provision new campaigns, then reference the returned IDs in skills/schedule-ads/config.yaml (schedule branch) to launch creatives into them.

Read .admanage-state/campaigns.json (if it exists) to see what's already created.

What this branch provisions

Two entity types only:

  1. Meta campaigns — name, objective, budget, bid strategy, promoted object.
  2. Meta ad sets — name, budget, optimization goal, targeting (geo/age/platforms), destination.

Everything else (TikTok/Snapchat/Pinterest/LinkedIn campaigns, advanced Meta fields like valueRuleSetId or Advantage+ catalog) is v2+. The shape below is intentionally minimal.

Safety defaults (create)

Same posture as the schedule branch:

  1. PAUSED by default. Every campaign + ad set is created with status: PAUSED. No surprise spend.
  2. Idempotent. The branch tracks created entities in .admanage-state/campaigns.json. If a campaign name already exists in state, it's skipped. Run it twice → no duplicates.
  3. Dry-run mode. DRY_RUN=true or config.dryRun: true → payloads written to .pending-admanage/dryrun-create/, notified, no API calls.
  4. Config-only. No config file → exit silently. No invented campaigns, no autonomous provisioning.

Network note (create)

Provisioning campaigns and ad sets is an irreversible outbound side-effect, so it is the branch's final action and runs in-run only after the diff + validation pass:

Steps (create)

  1. Load config. Read skills/schedule-ads/config.create.yaml. If it doesn't exist, log CREATE_CAMPAIGN_NOT_CONFIGURED and exit cleanly (no notify). The example template lives next to this file as config.create.example.yaml.
  1. Load state. Read .admanage-state/campaigns.json. If it doesn't exist, treat as empty. Shape:

```json

{

"campaigns": [

{

"configName": "Prospecting — Q2 2026",

"campaignId": "120251616228380456",

"adAccountId": "act_xxx",

"createdAt": "2026-04-21T08:00:00Z",

"adSets": [

{

"configName": "US Broad 25-54",

"adSetId": "120251616242460456",

"createdAt": "2026-04-21T08:00:04Z"

}

]

}

]

}

```

  1. Validate config shape. Required: defaults.adAccountId, defaults.workspaceId, campaigns[]. Each campaign needs name and objective. Each ad set needs name, and either optimizationGoal (explicit) or a compatible parent objective. If validation fails, file an issue in memory/issues/ and exit.
  1. Compute diff. For each campaign in config:

If nothing is new, log CREATE_CAMPAIGN_ALL_EXIST and exit without notify.

  1. Build campaign create payloads. Per the AdManage POST /v1/manage/create-campaign shape:

```json

{

"businessId": "<adAccountId>",

"workspaceId": "<workspaceId>",

"name": "<campaign.name>",

"objective": "<campaign.objective>",

"status": "PAUSED",

"buyingType": "AUCTION",

"specialAdCategories": [],

"dailyBudget": <number>,

"bidStrategy": "<LOWEST_COST_WITHOUT_CAP | LOWEST_COST_WITH_BID_CAP | COST_CAP | ...>",

"promotedObject": { ... }

}

```

Skip keys that are null/absent in config — don't send empty strings. Always force status: PAUSED unless defaults.launchPaused: false is set explicitly.

  1. Build ad-set create payloads. Per POST /v1/manage/create-adset:

```json

{

"businessId": "<adAccountId>",

"workspaceId": "<workspaceId>",

"campaignId": "RESOLVE_FROM_PARENT",

"parentCampaignConfigName": "<campaign.name>",

"name": "<adSet.name>",

"status": "PAUSED",

"dailyBudget": <number>,

"billingEvent": "IMPRESSIONS",

"optimizationGoal": "<LANDING_PAGE_VIEWS | OFFSITE_CONVERSIONS | ...>",

"destinationType": "<WEBSITE | PHONE_CALL | MESSAGING_... | ...>",

"targeting": { ... },

"promotedObject": { ... }

}

```

The __RESOLVE_FROM_PARENT__ sentinel + parentCampaignConfigName marks an ad set whose campaignId you fill in-run, from the map built as each campaign create returns (step 9b). If the parent campaign was existing (already in state), write the real campaign ID directly and drop the sentinel.

  1. Pre-flight validation.

Drop invalid entries, keep going, log what was skipped and why.

  1. Handle dry-run. If DRY_RUN=true or config.dryRun: true: write payloads to .pending-admanage/dryrun-create/ instead, notify with a [DRY RUN] prefix, skip step 9.
  1. Create in-run. This is the branch's final action — provisions real entities, so run only after the diff + pre-flight pass. Only ./secretcurl, jq, date, echo, python3, and the Write tool are available (no mv). Seed .admanage-state/campaigns.json to {"campaigns":[]} if missing.

a. Config check. Read the "Keys set for this run" line in your run notes, never a shell test (those are refused and cost a turn). If ADMANAGE_API_KEY is not on that line, notify "campaigns computed but ADMANAGE_API_KEY missing — nothing created" and stop (state unchanged).

b. Campaigns first. For each new campaign, write its payload with Write to /tmp/schedule-ads-create.json (overwrite per campaign), then one POST /v1/manage/create-campaign call:

```bash

./secretcurl -sS --max-time 60 -w 'http=%{http_code}\n' -X POST \

"https://api.admanage.ai/v1/manage/create-campaign" \

-H "Authorization: Bearer {ADMANAGE_API_KEY}" -H "Content-Type: application/json" -d @/tmp/schedule-ads-create.json

```

It prints the response (RESP) and an http= line. Success => .success==true and .campaignId set. On success: remember configName → campaignId (for step 9c) and append {configName, campaignId, adAccountId, createdAt, adSets:[]} to .admanage-state/campaigns.json. On failure: record the error, skip this campaign's ad sets.

c. Then ad sets. For each new ad set, resolve campaignId: if it's __RESOLVE_FROM_PARENT__, look it up by parentCampaignConfigName in the map from 9b or existing state - if the parent isn't found (its create failed), skip the ad set with a warning. Then POST /v1/manage/create-adset (same ./secretcurl shape: payload written to /tmp/schedule-ads-create.json with Write, sent with -d @/tmp/schedule-ads-create.json, one call per ad set). On success: append {configName, adSetId, createdAt} under the parent campaign in .admanage-state/campaigns.json (via python3/Write - no mv).

Ordering is explicit here (campaigns loop fully before the ad-sets loop), so children always reference a resolved parent ID.

  1. Write artifact to output/.chains/create-campaign.md so chain consumers can see what was queued:

```markdown

# Create Campaign - ${today}

New campaigns: N.

New ad sets: M.

Dry-run: yes|no.

## Campaigns

## Skipped (already exist)

```

  1. Notify via ./notify. Tight format:

```

Campaigns queued - ${today}${dryRunSuffix}

<N> campaigns, <M> ad sets queued for creation.

<if dry-run>

no API calls made - remove DRY_RUN to arm.

<else>

created via AdManage (PAUSED); new IDs written to .admanage-state/campaigns.json.

```

If nothing is new, don't notify at all.

  1. Log — see the shared Log section below (discriminator: create).

Config schema (create)

See skills/schedule-ads/config.create.example.yaml for a filled-in template. Minimum viable config:

defaults:
  adAccountId: act_XXXXXXXXXX
  workspaceId: XXXXXXXXXXXX
  launchPaused: true               # never flip without a reason
  dryRun: false                    # true = build, don't call

campaigns:
  - name: "Prospecting — Q2 2026"
    objective: OUTCOME_TRAFFIC
    dailyBudget: 50
    bidStrategy: LOWEST_COST_WITHOUT_CAP
    promotedObject:
      pixel_id: "123456789012345"
    adSets:
      - name: "US Broad 25-54"
        dailyBudget: 15
        optimizationGoal: LANDING_PAGE_VIEWS
        destinationType: WEBSITE
        targeting:
          geo_locations: { countries: ["US"] }
          age_min: 25
          age_max: 54
          publisher_platforms: [facebook, instagram]

Interaction with the schedule branch

The create branch writes new IDs to .admanage-state/campaigns.json within the same run; from there they're yours to reference in skills/schedule-ads/config.yaml (schedule branch) under adSets[].value. The two flows are intentionally decoupled:

They still don't auto-chain — the schedule branch reads config.yaml, which you edit by hand. Pattern is: run ${var}=create (provisions + writes IDs in-run) → read the new IDs from .admanage-state/campaigns.json / the create-run notify → copy them into config.yaml → next default (schedule) run launches into them.

What the create branch does NOT do


Log (both branches)

Append to memory/logs/${today}.md under ONE ### schedule-ads heading. First bullet is a discriminator naming which branch ran.

Schedule branch:

### schedule-ads
- Branch: schedule
- Schedules matching today: <names>
- Launches: <count> (dry-run: <bool>)
- Batch results: <ok/error/timeout summary> (live) | dry-run preview in .pending-admanage/dryrun/

Create branch:

### schedule-ads
- Branch: create
- New campaigns created: <count> (ok/fail)
- New ad sets created: <count> (ok/fail)
- State: new IDs written to .admanage-state/campaigns.json (live) | dry-run preview in .pending-admanage/dryrun-create/

Environment Variables

Output

End with a ## Summary block naming the branch that ran:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.