From 3c6ab072030dfee0c37b3478c2a676bb232c3bc3 Mon Sep 17 00:00:00 2001 From: sebastianekstrom Date: Wed, 11 Nov 2026 16:59:25 +0100 Subject: [PATCH 01/10] Add config skill --- README.md | 1 + skills/polar-config/SKILL.md | 171 +++++++++++++++++++++++++++++++++++ 2 files changed, 172 insertions(+) create mode 100644 skills/polar-config/SKILL.md diff --git a/README.md b/README.md index ba7d1b3..b7aea98 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ Both servers use OAuth. Nothing connects until you sign in to Polar and authoriz | --- | --- | | `setup-polar` | Guided setup from scratch: connects the MCP server, creates an organization and a first product, then hands off to `polar-integration`. | | `polar-integration` | Adds Checkout, Customer Portal and Webhooks endpoints with `@polar-sh/sdk` to any TS/JS framework, including Next.js, Express, Hono, Astro, SvelteKit, Remix, Nuxt and Cloudflare Workers. | +| `polar-config` | Manages the catalog as code: writes and edits a billing config file in TypeScript, Python or JSON, and previews, applies and publishes it with the Polar CLI (`polar config plan`, `polar config apply`, `polar config publish`). | | `polar-testing` | Tests an integration against the sandbox: test cards, local webhooks with the Polar CLI (`polar webhook listen`, `polar webhook trigger`), mocks and CI. | | `polar-migration` | Guides a migration to Polar: Polar's assisted migration from Stripe Billing, or recreating the catalog and moving customers from Paddle, Lemon Squeezy and others. | diff --git a/skills/polar-config/SKILL.md b/skills/polar-config/SKILL.md new file mode 100644 index 0000000..e13f0f6 --- /dev/null +++ b/skills/polar-config/SKILL.md @@ -0,0 +1,171 @@ +--- +name: polar-config +description: | + Manage a Polar catalog as code with a billing config file (polar.config.ts, polar_config.py or polar.config.json) and the "polar config" commands of the Polar CLI. Use this skill whenever the user wants to: (1) create or edit a Polar billing config; (2) add or change meters, benefits, products or prices in it; (3) write the config from their app's pricing; (4) preview or apply it with polar config plan, apply or publish; (5) fix an issue those commands report; (6) retire a meter, benefit or product with deprecated and polar config prune. +--- + +# Polar billing config + +A billing config is one file that declares an organization's meters, benefits and products. The Polar CLI compares the file with what is on Polar and applies the difference, so a pricing change is reviewed like any other code change. + +| File | Language | +| --- | --- | +| `polar.config.ts` | TypeScript | +| `polar_config.py` | Python. Meters only for now. | +| `polar.config.json` | JSON, for any other project | + +## Who decides what + +You do the engineering: write the file, run the commands, fix what they report. The user decides the business. + +- Never invent a product, a price, a currency, a billing interval or a benefit. Take them from the app (the pricing page, plan constants, existing checkout code) or from the user. If the app shows no pricing, ask. +- `polar config plan` changes nothing. Run it as often as you need. +- `polar config init`, `apply`, `publish` and `disable` change the organization. Run each only after the user has said yes to what it will do. +- Work in sandbox until the user asks for production. + +## Step 1: Find the config + +Look for `polar.config.ts`, `polar_config.py` or `polar.config.json` in the project. If there is one, go to Step 2. + +If there is none, `polar config init` writes it from the organization's existing meters, benefits and products. Tell the user what it does and wait for a yes: + +- It turns on config for the organization. From then on products and benefits are edited in the file, not in the dashboard. `polar config disable` undoes this, but only until a second catalog version is published. +- Existing meters, benefits and products without an external ID get one. The config refers to them by that ID from then on. + +```bash +polar auth whoami --json +polar config init --sandbox --json +``` + +`whoami` shows the active organization and environment. If the CLI is not signed in, ask the user to run `polar auth login --sandbox`, which opens a browser. Pass `--org ` when the account has several organizations. + +`init` picks the language from the project: TypeScript with a `package.json`, Python with a `pyproject.toml`, JSON otherwise. Pass `--format ts`, `--format py` or `--format json` when the project has both or the user wants another one. For TypeScript it also installs the package the config imports. + +Read the result: + +| `status` | What to do | +| --- | --- | +| `written` | The file is at `file`. Tell the user what `imported` counts and list everything in `skipped`: those resources stay on Polar as they are and are not in the file. | +| `external_ids_required` | Nothing was written. Show the user the suggested IDs in `external_ids`. Run `polar config init --json --confirm` to accept them all, or pass `--external-id =` for each one they want to name. | + +## Step 2: Edit the file + +Three rules hold in every language: + +- **The key is the external ID.** It is how Polar matches an entry to an existing resource. Changing a key creates a new resource, so never rename one. To change what customers see, change the name. +- **External IDs** start with a letter or digit and contain only letters, digits, `.`, `_`, `:` and `-`. In Python the attribute name is the ID, so use snake_case. +- **A section you leave out is left alone. A products section you include is the whole catalog:** a live product missing from it is left out of the next catalog version. Meters and benefits missing from their section stay on Polar untouched. + +### TypeScript + +Each section is a function that receives its helpers and returns the entries by key. Amounts are in the currency's major unit: `usd(29)` is $29.00. Every price in a product must list the same currencies. + +```ts +import { defineConfig, eq, eur, perThousand, usd } from '@polar-sh/polar' + +export default defineConfig({ + meters: ({ meter }) => ({ + api_calls: meter('API calls').where(eq('name', 'api_call')).count(), + tokens: meter('Output tokens') + .where(eq('name', 'completion')) + .unit('token') + .sum('output_tokens'), + }), + benefits: ({ flag, credits }) => ({ + priority_support: flag('Priority support'), + included_calls: credits('Included API calls').meter('api_calls').units(1000), + }), + products: ({ product, free, fixed, meter }) => ({ + free: product('Free').prices(free()).recurring('monthly'), + pro: product('Pro') + .prices( + fixed().amount(usd(29), eur(27)), + meter('api_calls') + .flat() + .amount(perThousand(usd(2)), perThousand(eur(1.9))), + ) + .recurring('monthly') + .grants(['priority_support', 'included_calls']), + }), +}) +``` + +- **Meters** filter events with `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `like`, `notLike`, `and`, `or`, then aggregate with `.count()`, `.sum(property)`, `.avg(property)`, `.min(property)`, `.max(property)` or `.unique(property)`. `eq('name', 'api_call')` matches the event name. A config with an `events` section, which gives each event a schema, selects events with `.on(events.api_call)` instead; follow whichever the file already uses. +- **Benefits** are `flag(name)`, a feature the app checks, or `credits(name).meter(key).units(n)`, usage included before a metered price charges. Add `.rollover()` to carry unused credits over. +- **Products** take `.prices(...)`, then `.recurring('monthly')`, `.recurring('yearly')`, `.recurring(3, 'months')` or `.once()`, and optionally `.grants([...])`, `.trial(14, 'days')` and `.description(text)`. +- **Prices** are `free()`, `fixed()`, `seats()`, `units()` and `meter(key)`. Tiered prices use `.graduated(...)` or `.volume(...)` with `tier()`. + +The package is fully typed. For anything not shown here, read its type declarations in `node_modules` rather than guessing: a wrong helper is a type error, and a reference to a meter or benefit key that does not exist is one too. + +### Python + +Declare the meters as attributes of a `MeterSet` subclass and assign the config to a module-level variable named `config`. The attribute name is the external ID. + +```python +from polar.config import Config, Meter, MeterSet, Sum, eq + + +class Meters(MeterSet): + api_calls = Meter("API calls", on="api_call") + tokens = Meter( + "Output tokens", + on="completion", + where=eq("status", "ok"), + aggregate=Sum("output_tokens"), + unit="token", + ) + + +config = Config(meters=Meters) +``` + +`on` is the event name. `where` takes `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `like`, `not_like`, `and_` and `or_`. `aggregate` takes `Count()` (the default), `Sum`, `Avg`, `Min`, `Max` and `Unique`. The CLI loads the file with `uv run` when the project has a `uv.lock`, and with `python3` otherwise, so `polar-sdk` must be installed in that environment. + +### JSON + +The file has the sections as lists, and each entry carries its `external_id`. Don't write the shape from memory: read an entry `init` wrote and follow it. + +## Step 3: Plan, fix, show + +```bash +polar config plan --json +``` + +- `entries` lists each resource with an `action` of `created`, `updated`, `unchanged` or `removed`, and for a change the `diff` of each field, `before` and `after`. +- `issues` lists problems with a `severity`, the `path` of the entry (`meters.tokens.name`), a `message` and the `location` in the file. + +Fix every issue with severity `error` in the file and plan again. Show warnings to the user. "No events with this name have been received yet" is expected until the app sends that event; check the event name for a typo, then move on. + +If the plan changes something you did not touch, the file is out of date with Polar. Stop and show the user instead of applying over it. + +Then tell the user in plain words what would be created, updated and removed, with the old and new value of every price that changes. + +## Step 4: Apply, then publish + +Ask before each command. `--confirm` skips the CLI's own question, which a shell without a terminal cannot answer, so the user's yes to you is the confirmation. + +```bash +polar config apply --confirm --json +polar config publish --confirm --json +``` + +- `apply` changes meters right away. Products and benefits are saved to a draft catalog, and nothing a customer sees changes yet. Until the draft is published, `plan` keeps listing them. +- `publish` makes the draft live: new checkouts sell it. Existing customers stay on the version they bought. + +Production is a separate organization with its own catalog. When the user asks for it, have them run `polar auth login --production`, check `polar auth whoami --json`, then repeat Step 3 and Step 4 with the same file. + +## Changing and retiring + +| The user wants to | Do this | +| --- | --- | +| Rename what customers see | Change the name. Keep the key. | +| Change a price | Edit it, apply and publish. Existing subscribers keep their price. | +| Stop selling a product | Mark it deprecated, apply and publish. Don't delete the entry: a product with active subscriptions that is missing from the file is an error. | +| Change what a meter counts | Once a meter has billed usage, Polar rejects a change to its filter or aggregation, and `plan` reports it. Add a new meter under a new key and deprecate the old one. | +| Clean up the file | Run `polar config prune`. It removes deprecated entries nothing uses any more and changes nothing on Polar. | + +Deprecate with `.deprecated()` in TypeScript, `deprecated=True` in Python and `"deprecated": true` in JSON. A deprecated entry stays for the customers who have it, and nothing new can use it. + +## After the catalog is live + +To sell the products, hand off to the `polar-integration` skill for the Checkout, Customer Portal and Webhooks endpoints, and to `polar-testing` to try them in sandbox. From 8454e1deef0891ec967e4850136ec869658a197f Mon Sep 17 00:00:00 2001 From: sebastianekstrom Date: Wed, 25 Nov 2026 12:19:29 +0100 Subject: [PATCH 02/10] Drop the Python config format from the config skill A Python project uses polar.config.json, which declares meters, benefits and products like the TypeScript file. The skill still described a Python format limited to meters, and agents repeated that. Describe the two formats that exist, show a full JSON example with its money rules, and add polar config generate for typed names in application code. --- skills/polar-config/SKILL.md | 156 +++++++++++++++++++++++++++-------- 1 file changed, 121 insertions(+), 35 deletions(-) diff --git a/skills/polar-config/SKILL.md b/skills/polar-config/SKILL.md index e13f0f6..2773c5c 100644 --- a/skills/polar-config/SKILL.md +++ b/skills/polar-config/SKILL.md @@ -1,18 +1,19 @@ --- name: polar-config description: | - Manage a Polar catalog as code with a billing config file (polar.config.ts, polar_config.py or polar.config.json) and the "polar config" commands of the Polar CLI. Use this skill whenever the user wants to: (1) create or edit a Polar billing config; (2) add or change meters, benefits, products or prices in it; (3) write the config from their app's pricing; (4) preview or apply it with polar config plan, apply or publish; (5) fix an issue those commands report; (6) retire a meter, benefit or product with deprecated and polar config prune. + Manage a Polar catalog as code with a billing config file (polar.config.ts or polar.config.json) and the "polar config" commands of the Polar CLI. Use this skill whenever the user wants to: (1) create or edit a Polar billing config; (2) add or change meters, benefits, products or prices in it; (3) write the config from their app's pricing; (4) preview or apply it with polar config plan, apply or publish; (5) fix an issue those commands report; (6) retire a meter, benefit or product with deprecated and polar config prune; (7) generate the config's names for application code with polar config generate. --- # Polar billing config A billing config is one file that declares an organization's meters, benefits and products. The Polar CLI compares the file with what is on Polar and applies the difference, so a pricing change is reviewed like any other code change. -| File | Language | +| File | For | | --- | --- | -| `polar.config.ts` | TypeScript | -| `polar_config.py` | Python. Meters only for now. | -| `polar.config.json` | JSON, for any other project | +| `polar.config.ts` | JavaScript and TypeScript projects | +| `polar.config.json` | Every other project: Python, Go, Ruby, PHP and so on | + +There is no config language per programming language. A Python project uses the JSON file, plus a generated file of names for its code (Step 5). ## Who decides what @@ -25,7 +26,7 @@ You do the engineering: write the file, run the commands, fix what they report. ## Step 1: Find the config -Look for `polar.config.ts`, `polar_config.py` or `polar.config.json` in the project. If there is one, go to Step 2. +Look for `polar.config.ts` or `polar.config.json` in the project. If there is one, go to Step 2. If there is none, `polar config init` writes it from the organization's existing meters, benefits and products. Tell the user what it does and wait for a yes: @@ -39,22 +40,24 @@ polar config init --sandbox --json `whoami` shows the active organization and environment. If the CLI is not signed in, ask the user to run `polar auth login --sandbox`, which opens a browser. Pass `--org ` when the account has several organizations. -`init` picks the language from the project: TypeScript with a `package.json`, Python with a `pyproject.toml`, JSON otherwise. Pass `--format ts`, `--format py` or `--format json` when the project has both or the user wants another one. For TypeScript it also installs the package the config imports. +`init` picks the format from the nearest project file: TypeScript with a `package.json`, JSON with a `pyproject.toml` or with neither. Pass `--format ts` or `--format json` when the project has both or the user wants the other one. For TypeScript it also installs the package the config imports. + +`init` fails with "already exists" when the config file is there. That is not an error to work around: the file is the config, go to Step 2. Read the result: | `status` | What to do | | --- | --- | -| `written` | The file is at `file`. Tell the user what `imported` counts and list everything in `skipped`: those resources stay on Polar as they are and are not in the file. | +| `written` | The file is at `file`. Tell the user what `imported` counts and list everything in `skipped`: those resources stay on Polar as they are and are not in the file. For a new organization the sections are empty; Step 2 shows what goes in them. | | `external_ids_required` | Nothing was written. Show the user the suggested IDs in `external_ids`. Run `polar config init --json --confirm` to accept them all, or pass `--external-id =` for each one they want to name. | ## Step 2: Edit the file -Three rules hold in every language: +Three rules hold in both formats: -- **The key is the external ID.** It is how Polar matches an entry to an existing resource. Changing a key creates a new resource, so never rename one. To change what customers see, change the name. -- **External IDs** start with a letter or digit and contain only letters, digits, `.`, `_`, `:` and `-`. In Python the attribute name is the ID, so use snake_case. -- **A section you leave out is left alone. A products section you include is the whole catalog:** a live product missing from it is left out of the next catalog version. Meters and benefits missing from their section stay on Polar untouched. +- **The external ID is the identity.** It is the key in TypeScript and the `external_id` field in JSON, and it is how Polar matches an entry to an existing resource. Changing it removes the old resource and creates a new one, so never rename one. To change what customers see, change the name. +- **External IDs** start with a letter or digit and contain only letters, digits, `.`, `_`, `:` and `-`. Prefer snake_case: it stays a valid name in generated code. +- **A section you leave out is left alone. A products section you include is the whole catalog:** an entry missing from a section you include is left out of the next catalog version, and `"products": []` takes every product off sale. `plan` lists these as removed, "not in config". Nothing is deleted on Polar and customers keep what they have, but treat every removal in a plan as something the user must have asked for. ### TypeScript @@ -97,33 +100,82 @@ export default defineConfig({ The package is fully typed. For anything not shown here, read its type declarations in `node_modules` rather than guessing: a wrong helper is a type error, and a reference to a meter or benefit key that does not exist is one too. -### Python - -Declare the meters as attributes of a `MeterSet` subclass and assign the config to a module-level variable named `config`. The attribute name is the external ID. - -```python -from polar.config import Config, Meter, MeterSet, Sum, eq - +### JSON -class Meters(MeterSet): - api_calls = Meter("API calls", on="api_call") - tokens = Meter( - "Output tokens", - on="completion", - where=eq("status", "ok"), - aggregate=Sum("output_tokens"), - unit="token", - ) +The file is one object. Each section is a list, and each entry carries its `external_id`. Entries refer to each other by external ID: a benefit names its `meter`, a product lists its `benefits`. + +```json +{ + "meters": [ + { + "external_id": "api_calls", + "name": "API calls", + "filter": { + "conjunction": "and", + "clauses": [{ "property": "name", "operator": "eq", "value": "api_call" }] + }, + "aggregation": { "func": "count" } + } + ], + "benefits": [ + { + "external_id": "priority_support", + "description": "Priority support", + "type": "feature_flag" + }, + { + "external_id": "included_calls", + "description": "1,000 API calls a month", + "type": "meter_credit", + "properties": { "meter": "api_calls", "units": 1000, "rollover": false } + } + ], + "products": [ + { + "external_id": "free", + "name": "Free", + "recurring_interval": "month", + "prices": [{ "amount_type": "fixed", "price_currency": "usd", "price_amount": 0 }], + "benefits": [] + }, + { + "external_id": "pro", + "name": "Pro", + "recurring_interval": "month", + "prices": [ + { "amount_type": "fixed", "price_currency": "usd", "price_amount": 2900 }, + { "amount_type": "metered_unit", "price_currency": "usd", "meter": "api_calls", "unit_amount": "0.2" } + ], + "benefits": ["priority_support", "included_calls"] + }, + { + "external_id": "credit_pack", + "name": "5,000 API calls", + "prices": [{ "amount_type": "fixed", "price_currency": "usd", "price_amount": 900 }], + "benefits": [] + } + ] +} +``` +**Money is in cents, and this is where JSON configs go wrong.** There are no helpers like `usd(29)`, so check every amount twice. -config = Config(meters=Meters) -``` +| Field | Written as | Example | +| --- | --- | --- | +| `price_amount` on a fixed price | Whole cents, a number. `0` is free. | `2900` is $29.00 | +| `unit_amount` on a metered or tiered price | Cents per unit, a string, fractions allowed | `"0.2"` is $0.002 per call, so $2 per 1,000 | +| `cap_amount` | Whole cents, a number | `10000` caps the charge at $100.00 | -`on` is the event name. `where` takes `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `like`, `not_like`, `and_` and `or_`. `aggregate` takes `Count()` (the default), `Sum`, `Avg`, `Min`, `Max` and `Unique`. The CLI loads the file with `uv run` when the project has a `uv.lock`, and with `python3` otherwise, so `polar-sdk` must be installed in that environment. +The plan prints amounts as money (`$29 per month`, `$2 per 1,000`). Run `polar config plan` without `--json` once to see them, and read each one back against what the user said: the JSON output only has the raw numbers. -### JSON +- **Meters.** `filter` holds `clauses` joined by `conjunction` (`and` or `or`). A clause has a `property`, an `operator` (`eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `like`, `not_like`) and a `value`. The property `name` is the event name; any other property is read from the event's metadata. `aggregation` is `{ "func": "count" }`, or `sum`, `avg`, `min`, `max` or `unique` with a `"property"`. +- **Benefits.** `type` is `feature_flag`, a feature the app checks, or `meter_credit`, usage included before a metered price charges, with `properties` naming the `meter`, the `units` and whether unused units `rollover`. +- **Products.** `recurring_interval` is `day`, `week`, `month` or `year`; add `recurring_interval_count` for every 3 months. Leave `recurring_interval` out for a one-time purchase. It cannot change once the product exists. Optional: `description`, and a trial with `trial_interval` and `trial_interval_count`. +- **Prices.** `amount_type` is `fixed`, `metered_unit`, `metered_tiers`, `seat_based` or `unit_based`. A free plan is a fixed price of `0`. A metered price needs a recurring product. +- **Tiers** (for `metered_tiers`, `seat_based` and `unit_based`) go in `"tiers": { "type": "graduated", "tiers": [...] }`, with `volume` as the other type. Each tier has a `unit_amount` and a `bound`, the last unit it covers; the last tier has no `bound`. +- **Several currencies.** Add one price object per currency. Every currency must have the same set of price types. -The file has the sections as lists, and each entry carries its `external_id`. Don't write the shape from memory: read an entry `init` wrote and follow it. +Keys the format does not know are rejected, and so are comments and trailing commas. For anything not shown here, write your best guess and run `polar config plan`: an error names the field and lists the values it accepts. When the organization already has resources, the entries `init` wrote are the most reliable examples. ## Step 3: Plan, fix, show @@ -149,9 +201,17 @@ polar config apply --confirm --json polar config publish --confirm --json ``` -- `apply` changes meters right away. Products and benefits are saved to a draft catalog, and nothing a customer sees changes yet. Until the draft is published, `plan` keeps listing them. +- `apply` saves meters, benefits, products and settings to a draft catalog, and nothing a customer sees changes yet. Webhooks apply right away. - `publish` makes the draft live: new checkouts sell it. Existing customers stay on the version they bought. +Between `apply` and `publish`, three things look wrong and are not: + +- `plan` still lists the applied changes and still says to run `apply`. It compares the file with the live catalog, not with the draft. The next step is `publish`. +- `apply` run again reports the same entries as created or updated. +- Each `publish` makes a new catalog version (`v1`, `v2`, ...). A product that changed gets a new ID on Polar and the old one stays for the customers who bought it, which is why application code uses external IDs (Step 5). + +`publish` ships the draft, not the file. If the file changed after the last `apply`, run `apply` again first. To check, run `polar config publish` without `--confirm` and without `--json`: it prints a "Not in the draft" section listing what differs, then stops for confirmation. Publish with `--confirm` only when that section is absent. If the user took a change back after it was applied, say so and show them that section; do not publish over it. + Production is a separate organization with its own catalog. When the user asks for it, have them run `polar auth login --production`, check `polar auth whoami --json`, then repeat Step 3 and Step 4 with the same file. ## Changing and retiring @@ -164,7 +224,33 @@ Production is a separate organization with its own catalog. When the user asks f | Change what a meter counts | Once a meter has billed usage, Polar rejects a change to its filter or aggregation, and `plan` reports it. Add a new meter under a new key and deprecate the old one. | | Clean up the file | Run `polar config prune`. It removes deprecated entries nothing uses any more and changes nothing on Polar. | -Deprecate with `.deprecated()` in TypeScript, `deprecated=True` in Python and `"deprecated": true` in JSON. A deprecated entry stays for the customers who have it, and nothing new can use it. +Deprecate with `.deprecated()` in TypeScript and `"deprecated": true` in JSON. A deprecated entry stays for the customers who have it, and nothing new can use it. A live product cannot grant a deprecated benefit: take the benefit out of the product's list first. + +## Step 5: Names for application code + +Application code refers to the config by external ID: the product to sell, the benefit to check, the meter to read, the event to send. A typo in one of those strings fails silently at run time. + +With a TypeScript config the package types these for you. With a JSON config, generate them: + +```bash +polar config generate +``` + +It writes one file next to the config with the external IDs and event names as constants and types. For a Python project that is `polar_types.py`: + +```python +from polar_types import Benefits, Events, Meters, Products + +Products.pro # "pro" +Events.api_call # "api_call", from the meters' filters +``` + +- The language comes from the project (`pyproject.toml`, `requirements.txt`, `setup.py` or `Pipfile` means Python). Pass `--language py` when it cannot tell. Python is the only language so far; in another language, use the external IDs as plain strings. +- `--out src/myapp/polar_types.py` puts the file elsewhere. It never replaces a file it did not write. +- Run it again after every change to the config, and commit the file. `polar config generate --check` writes nothing and fails when the file is missing or out of date; add it to CI. +- Never edit the generated file. + +The API takes external IDs directly from version 2027-01, so the app never stores Polar's own IDs. In Python that is `from polar.v2027_01 import Polar`, then for example `external_products=[Products.pro]` when creating a checkout, `external_benefit_id=Benefits.priority_support` when listing a customer's benefit grants and `external_meter_id=Meters.api_calls` when reading a customer's meter. ## After the catalog is live From 22223ce67d542813bd4b3d35b47f8d79f0dcb8f0 Mon Sep 17 00:00:00 2001 From: sebastianekstrom Date: Wed, 25 Nov 2026 13:16:31 +0100 Subject: [PATCH 03/10] Say config is one of two ways and sell by external ID with it A catalog is managed in the dashboard unless the organization turns config on, and the skills did not say so. With a config file, publishing gives a changed product a new ID, so an app that stores the product ID breaks on the next price change. Tell agents to use external IDs through the 2027-01 API in that case, and keep setup-polar from creating products through the API for a config organization. --- skills/polar-config/SKILL.md | 8 ++++++-- skills/polar-integration/SKILL.md | 12 +++++++++++- skills/setup-polar/SKILL.md | 4 +++- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/skills/polar-config/SKILL.md b/skills/polar-config/SKILL.md index 2773c5c..ff6cc05 100644 --- a/skills/polar-config/SKILL.md +++ b/skills/polar-config/SKILL.md @@ -15,6 +15,8 @@ A billing config is one file that declares an organization's meters, benefits an There is no config language per programming language. A Python project uses the JSON file, plus a generated file of names for its code (Step 5). +A config file is one of two ways to manage a catalog. The other is the dashboard, which is how every organization works until `polar config init` turns config on. Use this skill when the project already has a config file or the user asks to manage the catalog in code. Don't move an organization to a config file on your own: suggest it when it fits, and let the user choose. + ## Who decides what You do the engineering: write the file, run the commands, fix what they report. The user decides the business. @@ -250,8 +252,10 @@ Events.api_call # "api_call", from the meters' filters - Run it again after every change to the config, and commit the file. `polar config generate --check` writes nothing and fails when the file is missing or out of date; add it to CI. - Never edit the generated file. -The API takes external IDs directly from version 2027-01, so the app never stores Polar's own IDs. In Python that is `from polar.v2027_01 import Polar`, then for example `external_products=[Products.pro]` when creating a checkout, `external_benefit_id=Benefits.priority_support` when listing a customer's benefit grants and `external_meter_id=Meters.api_calls` when reading a customer's meter. +The API takes external IDs directly from version 2027-01, so the app never stores Polar's own IDs. In Python that is `from polar.v2027_01 import Polar`, then for example `external_products=[Products.pro]` when creating a checkout, `external_benefit_id=Benefits.priority_support` when listing a customer's benefit grants and `external_meter_id=Meters.api_calls` when reading a customer's meter. In TypeScript, import the client from `@polar-sh/sdk/2027-01` and pass `external_products: ["pro"]` to `polar.checkouts.create`. + +Never put a Polar product ID in the app's code or env file. Each publish gives a changed product a new ID, and a checkout created with the old one fails with "Product is no longer sold". ## After the catalog is live -To sell the products, hand off to the `polar-integration` skill for the Checkout, Customer Portal and Webhooks endpoints, and to `polar-testing` to try them in sandbox. +To sell the products, hand off to the `polar-integration` skill for the Checkout, Customer Portal and Webhooks endpoints, and to `polar-testing` to try them in sandbox. Follow "Projects with a billing config" in its Checkout recipe, so the app sells by external ID. diff --git a/skills/polar-integration/SKILL.md b/skills/polar-integration/SKILL.md index 0dd6d79..526f496 100644 --- a/skills/polar-integration/SKILL.md +++ b/skills/polar-integration/SKILL.md @@ -28,7 +28,7 @@ Required environment variables (use whatever loader your framework provides — - `POLAR_WEBHOOK_SECRET` — only needed for the webhook recipe. - `POLAR_ENVIRONMENT` — `sandbox` while developing; omit it or set `production` in production. Sandbox and production are separate, so each needs its own token. -The SDK is versioned by API version: the import path pins it. Use `2026-10`, the current version, unless the project already imports another one. Construct one client in a server-only module and reuse it: +The SDK is versioned by API version: the import path pins it. Use `2026-10`, the current version, unless the project already imports another one or has a billing config (see "Projects with a billing config" in Recipe 1). Construct one client in a server-only module and reuse it: ```ts import { createPolar, type Environment } from "@polar-sh/sdk/2026-10"; @@ -145,6 +145,16 @@ export async function handleCheckout(request: Request): Promise { This handler accepts a GET request with `?products=`. Drop fields you don't need and add fields from the table above (`metadata`, `embed_origin`, `locale`, ...) as needed. +### Projects with a billing config + +Most organizations manage products in the dashboard. Their product IDs never change, and the handler above is right as it is. + +If the project has a `polar.config.ts` or `polar.config.json` (see the `polar-config` skill), the catalog is managed in that file instead, and publishing a change gives the changed product a new ID. A product ID kept in the app's code or env file then stops working: the checkout fails with "Product is no longer sold". Refer to products by their external ID from the config, which never changes: + +- Import the client from `@polar-sh/sdk/2027-01`, the first API version that takes external IDs. +- Pass `external_products` in place of `products`: `polar.checkouts.create({ external_products: ["pro"], ... })`. The handler above then takes `?products=pro`. +- Sell through this endpoint, which creates a checkout session for each purchase, rather than through a checkout link created once. + ### Framework variations The body of the handler is identical — only the entry point changes: diff --git a/skills/setup-polar/SKILL.md b/skills/setup-polar/SKILL.md index a2b63e5..000b58d 100644 --- a/skills/setup-polar/SKILL.md +++ b/skills/setup-polar/SKILL.md @@ -87,7 +87,9 @@ List the organizations with MCP. If there are several, ask which one to use. Not ### Step 5: Create First Product -Create the product with MCP (`POST /v1/products/`). The price must be in the organization's `default_presentment_currency`, and the billing interval is fixed per product. Example for a monthly subscription: +If the project has a `polar.config.ts` or `polar.config.json`, the catalog is managed in that file and Polar rejects products created any other way. Add the product with the `polar-config` skill instead, and pass its external ID, not a product ID, on to Step 6. + +Otherwise, create the product with MCP (`POST /v1/products/`). The price must be in the organization's `default_presentment_currency`, and the billing interval is fixed per product. Example for a monthly subscription: ```json { From 99e3796515be261be348d44171785c329d627cbd Mon Sep 17 00:00:00 2001 From: sebastianekstrom Date: Wed, 25 Nov 2026 13:21:27 +0100 Subject: [PATCH 04/10] Ask dashboard or config file at the start of setup-polar A first-time setup only followed the dashboard way and met a config file by accident. Ask up front which way the user wants to manage the catalog, describe both, and send the config choice to the polar-config skill. --- skills/setup-polar/SKILL.md | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/skills/setup-polar/SKILL.md b/skills/setup-polar/SKILL.md index 000b58d..283861d 100644 --- a/skills/setup-polar/SKILL.md +++ b/skills/setup-polar/SKILL.md @@ -8,9 +8,9 @@ description: | Interactive setup guide to get Polar payments working in your project. -## Start here: organization and environment +## Start here: organization, environment and catalog -Ask these two questions before anything else, and wait for the answers. +Ask these three questions before anything else, and wait for the answers. **1. Which organization?** @@ -22,6 +22,15 @@ Ask these two questions before anything else, and wait for the answers. Suggest sandbox. It is a separate copy of Polar where checkout takes test cards, so you can make a test purchase and check the whole flow end to end (checkout, webhook, access) before real money is involved. Start in production only when the user asks for it; Step 9 covers going live. +**3. Dashboard or config file?** + +There are two ways to manage products, prices and benefits, and the user chooses. If the project already has a `polar.config.ts` or `polar.config.json`, it uses a config file: don't ask. + +- **Dashboard.** Products are created and edited in the Polar dashboard, or by you through the API. Product IDs never change. This is how every organization starts, and it is what the steps below follow. +- **Config file.** The catalog lives in a file in the repository. A pricing change is reviewed like any other code change and applied with the Polar CLI. Once it is turned on, products are edited in the file and no longer in the dashboard. + +For a config file, use the `polar-config` skill in place of Step 5, and refer to products by their external ID from then on. + ## Setup Flow Follow these steps in order: @@ -87,7 +96,7 @@ List the organizations with MCP. If there are several, ask which one to use. Not ### Step 5: Create First Product -If the project has a `polar.config.ts` or `polar.config.json`, the catalog is managed in that file and Polar rejects products created any other way. Add the product with the `polar-config` skill instead, and pass its external ID, not a product ID, on to Step 6. +If the user chose a config file at the start, or the project has a `polar.config.ts` or `polar.config.json`, the catalog is managed in that file and Polar rejects products created any other way. Add the product with the `polar-config` skill instead, and pass its external ID, not a product ID, on to Step 6. Otherwise, create the product with MCP (`POST /v1/products/`). The price must be in the organization's `default_presentment_currency`, and the billing interval is fixed per product. Example for a monthly subscription: @@ -127,7 +136,7 @@ token=$(polar auth token --scope checkouts:write --scope customer_sessions:write Without the CLI, create the token in the sandbox or production dashboard: Settings → Access Tokens → Create token. -Pass along the product ID from Step 5 so checkout links can be tested in Step 8. +Pass along the product ID from Step 5, or the product's external ID with a config file, so checkout links can be tested in Step 8. ### Step 7: Set Up Webhooks @@ -142,7 +151,7 @@ When deploying, create a webhook endpoint for the public URL in the dashboard (S ### Step 8: Test the Integration -1. Visit the checkout URL with the product ID from Step 5 (path and query shape come from the route generated in Step 6). +1. Visit the checkout URL with the product ID from Step 5, or the external ID with a config file (path and query shape come from the route generated in Step 6). 2. Complete checkout using test card: `4242 4242 4242 4242`. 3. Verify that `polar webhook listen` shows `order.paid` with a 2xx status from the handler. 4. Check the success page displays correctly. From 8a4cdb8d96bc8917387d06fcac47ab5b350e83ff Mon Sep 17 00:00:00 2001 From: sebastianekstrom Date: Wed, 25 Nov 2026 13:42:11 +0100 Subject: [PATCH 05/10] Fix stale and missing guidance in the config skill Drop the claim that webhooks apply right away, explain the settings section init writes, and say that a new meter does not count usage until publish. When the CLI is signed out, ask whether the user has an organization, wants the agent to create one, or will create it themselves. Cover config projects in the checkout test of polar-testing, the production step of setup-polar and the webhook import of polar-integration. --- skills/polar-config/SKILL.md | 17 ++++++++++++++--- skills/polar-integration/SKILL.md | 1 + skills/polar-testing/SKILL.md | 2 ++ skills/setup-polar/SKILL.md | 2 +- 4 files changed, 18 insertions(+), 4 deletions(-) diff --git a/skills/polar-config/SKILL.md b/skills/polar-config/SKILL.md index ff6cc05..2791c46 100644 --- a/skills/polar-config/SKILL.md +++ b/skills/polar-config/SKILL.md @@ -40,7 +40,13 @@ polar auth whoami --json polar config init --sandbox --json ``` -`whoami` shows the active organization and environment. If the CLI is not signed in, ask the user to run `polar auth login --sandbox`, which opens a browser. Pass `--org ` when the account has several organizations. +`whoami` shows the active organization and environment. Pass `--org ` when the account has several organizations. + +If the CLI is not signed in, ask the user which of these applies before going further: + +- **They have a Polar organization.** They run `polar auth login --sandbox`, which opens a browser. +- **They want you to create one.** Polar supports the [auth.md](https://polar.sh/auth.md) spec: read for sandbox or for production, sign up on your own and create the organization. Then run the commands in this skill with your access token in place of a login: `POLAR_ACCESS_TOKEN= POLAR_ENVIRONMENT=sandbox polar config init --json`. Hand the organization over with a claim once the catalog is in place, and put the full `verification_uri` and the `user_code` in your reply to the user, copied exactly. +- **They will create it themselves.** Send them to , then they run `polar auth login --sandbox`. `init` picks the format from the nearest project file: TypeScript with a `package.json`, JSON with a `pyproject.toml` or with neither. Pass `--format ts` or `--format json` when the project has both or the user wants the other one. For TypeScript it also installs the package the config imports. @@ -102,6 +108,10 @@ export default defineConfig({ The package is fully typed. For anything not shown here, read its type declarations in `node_modules` rather than guessing: a wrong helper is a type error, and a reference to a meter or benefit key that does not exist is one too. +### Settings + +`init` also writes a `settings` section with the organization's default currency and tax behavior: `settings: { payments: { currency: 'usd', tax: 'location' } }` in TypeScript, and the same object under `"settings"` in JSON. `tax` is `location`, `inclusive` or `exclusive`. It applies to the whole organization and takes effect on `publish`, so leave it as `init` wrote it unless the user asks for a change. + ### JSON The file is one object. Each section is a list, and each entry carries its `external_id`. Entries refer to each other by external ID: a benefit names its `meter`, a product lists its `benefits`. @@ -203,13 +213,14 @@ polar config apply --confirm --json polar config publish --confirm --json ``` -- `apply` saves meters, benefits, products and settings to a draft catalog, and nothing a customer sees changes yet. Webhooks apply right away. +- `apply` saves meters, benefits, products and settings to a draft catalog, and nothing a customer sees changes yet. - `publish` makes the draft live: new checkouts sell it. Existing customers stay on the version they bought. -Between `apply` and `publish`, three things look wrong and are not: +Between `apply` and `publish`, four things look wrong and are not: - `plan` still lists the applied changes and still says to run `apply`. It compares the file with the live catalog, not with the draft. The next step is `publish`. - `apply` run again reports the same entries as created or updated. +- A meter that is new in the draft does not count usage until `publish`. A customer's balance for it does not move while the catalog is only a draft, so publish before you test usage. - Each `publish` makes a new catalog version (`v1`, `v2`, ...). A product that changed gets a new ID on Polar and the old one stays for the customers who bought it, which is why application code uses external IDs (Step 5). `publish` ships the draft, not the file. If the file changed after the last `apply`, run `apply` again first. To check, run `polar config publish` without `--confirm` and without `--json`: it prints a "Not in the draft" section listing what differs, then stops for confirmation. Publish with `--confirm` only when that section is absent. If the user took a change back after it was applied, say so and show them that section; do not publish over it. diff --git a/skills/polar-integration/SKILL.md b/skills/polar-integration/SKILL.md index 526f496..307438a 100644 --- a/skills/polar-integration/SKILL.md +++ b/skills/polar-integration/SKILL.md @@ -153,6 +153,7 @@ If the project has a `polar.config.ts` or `polar.config.json` (see the `polar-co - Import the client from `@polar-sh/sdk/2027-01`, the first API version that takes external IDs. - Pass `external_products` in place of `products`: `polar.checkouts.create({ external_products: ["pro"], ... })`. The handler above then takes `?products=pro`. +- Import `webhooks` from `@polar-sh/sdk/2027-01` as well in Recipe 3, and set the webhook endpoint to the same API version, so payloads match the client's types. - Sell through this endpoint, which creates a checkout session for each purchase, rather than through a checkout link created once. ### Framework variations diff --git a/skills/polar-testing/SKILL.md b/skills/polar-testing/SKILL.md index 1652d28..aea9db0 100644 --- a/skills/polar-testing/SKILL.md +++ b/skills/polar-testing/SKILL.md @@ -134,6 +134,8 @@ polar webhook trigger order.paid --seed 7 # the same IDs on every Use an organization access token with the `products:write` and `checkouts:write` scopes. Organization tokens already imply the organization, so don't pass `organization_id`. +If the project has a `polar.config.ts` or `polar.config.json`, skip the `beforeAll` below: Polar rejects products created outside the config file. Test with a product from the config instead, by its external ID and the `2027-01` client: `external_products: ["pro"]` in place of `products`. + ```typescript import { describe, it, expect, beforeAll } from "vitest"; import { createPolar } from "@polar-sh/sdk/2026-10"; diff --git a/skills/setup-polar/SKILL.md b/skills/setup-polar/SKILL.md index c160bbe..2e846c4 100644 --- a/skills/setup-polar/SKILL.md +++ b/skills/setup-polar/SKILL.md @@ -150,4 +150,4 @@ Once basic setup works, suggest: 1. **Link to your auth** - Pass `external_customer_id` from the logged-in user when creating checkouts. 2. **Add benefits** - License keys, file downloads, Discord roles. -3. **Go production** - Production is separate from sandbox: set up the organization at polar.sh, re-create the product (it gets a new ID), create a production access token and webhook endpoint, and set `POLAR_ENVIRONMENT=production`. Then submit the organization for review in the dashboard; checkouts are blocked until it can accept payments. +3. **Go production** - Production is separate from sandbox: set up the organization at polar.sh, re-create the product (it gets a new ID; with a config file, apply and publish the same file there instead, and the external IDs stay the same), create a production access token and webhook endpoint, and set `POLAR_ENVIRONMENT=production`. Then submit the organization for review in the dashboard; checkouts are blocked until it can accept payments. From ae58713d75542db627004cb4dbd7282026b2ddb8 Mon Sep 17 00:00:00 2001 From: sebastianekstrom Date: Wed, 25 Nov 2026 14:31:38 +0100 Subject: [PATCH 06/10] Update commands --- README.md | 2 +- skills/polar-config/SKILL.md | 59 +++++++++++++++++-------------- skills/polar-integration/SKILL.md | 2 +- skills/setup-polar/SKILL.md | 12 ++++--- 4 files changed, 42 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index 15473e7..2a26470 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ Both servers use OAuth. Nothing connects until you sign in to Polar and authoriz | --- | --- | | `setup-polar` | Guided setup from scratch: connects the MCP server, creates an organization and a first product, then hands off to `polar-integration`. | | `polar-integration` | Adds Checkout, Customer Portal and Webhooks endpoints with `@polar-sh/sdk` to any TS/JS framework, including Next.js, Express, Hono, Astro, SvelteKit, Remix, Nuxt and Cloudflare Workers. | -| `polar-config` | Manages the catalog as code: writes and edits a billing config file in TypeScript, Python or JSON, and previews, applies and publishes it with the Polar CLI (`polar config plan`, `polar config apply`, `polar config publish`). | +| `polar-config` | Manages the catalog as code: writes and edits a billing config file in TypeScript or JSON, and validates, drafts and publishes it with the Polar CLI (`polar config validate`, `polar config draft`, `polar config publish`). | | `polar-testing` | Tests an integration against the sandbox: test cards, local webhooks with the Polar CLI (`polar webhook listen`, `polar webhook trigger`), mocks and CI. | | `polar-migration` | Guides a migration to Polar: Polar's assisted migration from Stripe Billing, or recreating the catalog and moving customers from Paddle, Lemon Squeezy and others. | diff --git a/skills/polar-config/SKILL.md b/skills/polar-config/SKILL.md index 2791c46..46e41c8 100644 --- a/skills/polar-config/SKILL.md +++ b/skills/polar-config/SKILL.md @@ -1,12 +1,12 @@ --- name: polar-config description: | - Manage a Polar catalog as code with a billing config file (polar.config.ts or polar.config.json) and the "polar config" commands of the Polar CLI. Use this skill whenever the user wants to: (1) create or edit a Polar billing config; (2) add or change meters, benefits, products or prices in it; (3) write the config from their app's pricing; (4) preview or apply it with polar config plan, apply or publish; (5) fix an issue those commands report; (6) retire a meter, benefit or product with deprecated and polar config prune; (7) generate the config's names for application code with polar config generate. + Manage a Polar catalog as code with a billing config file (polar.config.ts or polar.config.json) and the "polar config" commands of the Polar CLI. Use this skill whenever the user wants to: (1) create or edit a Polar billing config; (2) add or change meters, benefits, products or prices in it; (3) write the config from their app's pricing; (4) check what would change, save it to the draft or publish it with polar config validate, draft or publish; (5) fix an issue those commands report; (6) retire a meter, benefit or product with deprecated and polar config prune; (7) generate the config's names for application code with polar config generate. --- # Polar billing config -A billing config is one file that declares an organization's meters, benefits and products. The Polar CLI compares the file with what is on Polar and applies the difference, so a pricing change is reviewed like any other code change. +A billing config is one file that declares an organization's meters, benefits and products. The Polar CLI compares the file with what is on Polar, then drafts and publishes the difference, so a pricing change is reviewed like any other code change. | File | For | | --- | --- | @@ -22,8 +22,8 @@ A config file is one of two ways to manage a catalog. The other is the dashboard You do the engineering: write the file, run the commands, fix what they report. The user decides the business. - Never invent a product, a price, a currency, a billing interval or a benefit. Take them from the app (the pricing page, plan constants, existing checkout code) or from the user. If the app shows no pricing, ask. -- `polar config plan` changes nothing. Run it as often as you need. -- `polar config init`, `apply`, `publish` and `disable` change the organization. Run each only after the user has said yes to what it will do. +- `polar config validate` changes nothing. Run it as often as you need. +- `polar config init`, `draft`, `publish` and `disable` change the organization. Run each only after the user has said yes to what it will do. - Work in sandbox until the user asks for production. ## Step 1: Find the config @@ -35,6 +35,8 @@ If there is none, `polar config init` writes it from the organization's existing - It turns on config for the organization. From then on products and benefits are edited in the file, not in the dashboard. `polar config disable` undoes this, but only until a second catalog version is published. - Existing meters, benefits and products without an external ID get one. The config refers to them by that ID from then on. +The commands in this skill need the Polar CLI. If `polar` is not installed, install it with `npm install -g @polar-sh/cli`. + ```bash polar auth whoami --json polar config init --sandbox --json @@ -42,10 +44,10 @@ polar config init --sandbox --json `whoami` shows the active organization and environment. Pass `--org ` when the account has several organizations. -If the CLI is not signed in, ask the user which of these applies before going further: +If the CLI is not signed in, and the user has not already told you in `setup-polar`, ask which of these applies before going further: - **They have a Polar organization.** They run `polar auth login --sandbox`, which opens a browser. -- **They want you to create one.** Polar supports the [auth.md](https://polar.sh/auth.md) spec: read for sandbox or for production, sign up on your own and create the organization. Then run the commands in this skill with your access token in place of a login: `POLAR_ACCESS_TOKEN= POLAR_ENVIRONMENT=sandbox polar config init --json`. Hand the organization over with a claim once the catalog is in place, and put the full `verification_uri` and the `user_code` in your reply to the user, copied exactly. +- **They want you to create one.** Polar supports the [auth.md](https://polar.sh/auth.md) spec: read for sandbox or for production, sign up on your own, ask what to call the organization and create it with `POST /v1/organizations/` (a `name` and a `slug`). Then run the commands in this skill with your access token in place of a login: `POLAR_ACCESS_TOKEN= POLAR_ENVIRONMENT=sandbox polar config init --json`. Hand the organization over with a claim once the catalog is in place: ask the user for the email address they will sign in to Polar with, and put the full `verification_uri` and the `user_code` in your reply, copied exactly. Once the claim succeeds, use the access token it returns, because the one you had stops working. - **They will create it themselves.** Send them to , then they run `polar auth login --sandbox`. `init` picks the format from the nearest project file: TypeScript with a `package.json`, JSON with a `pyproject.toml` or with neither. Pass `--format ts` or `--format json` when the project has both or the user wants the other one. For TypeScript it also installs the package the config imports. @@ -65,7 +67,7 @@ Three rules hold in both formats: - **The external ID is the identity.** It is the key in TypeScript and the `external_id` field in JSON, and it is how Polar matches an entry to an existing resource. Changing it removes the old resource and creates a new one, so never rename one. To change what customers see, change the name. - **External IDs** start with a letter or digit and contain only letters, digits, `.`, `_`, `:` and `-`. Prefer snake_case: it stays a valid name in generated code. -- **A section you leave out is left alone. A products section you include is the whole catalog:** an entry missing from a section you include is left out of the next catalog version, and `"products": []` takes every product off sale. `plan` lists these as removed, "not in config". Nothing is deleted on Polar and customers keep what they have, but treat every removal in a plan as something the user must have asked for. +- **A section you leave out is left alone. A products section you include is the whole catalog:** an entry missing from a section you include is left out of the next catalog version, and `"products": []` takes every product off sale. `validate` lists these as removed, "not in config". Nothing is deleted on Polar and customers keep what they have, but treat every removal `validate` reports as something the user must have asked for. ### TypeScript @@ -178,52 +180,57 @@ The file is one object. Each section is a list, and each entry carries its `exte | `unit_amount` on a metered or tiered price | Cents per unit, a string, fractions allowed | `"0.2"` is $0.002 per call, so $2 per 1,000 | | `cap_amount` | Whole cents, a number | `10000` caps the charge at $100.00 | -The plan prints amounts as money (`$29 per month`, `$2 per 1,000`). Run `polar config plan` without `--json` once to see them, and read each one back against what the user said: the JSON output only has the raw numbers. +`validate` prints amounts as money (`$29 per month`, `$2 per 1,000`). Run `polar config validate` without `--json` once to see them, and read each one back against what the user said: the JSON output only has the raw numbers. -- **Meters.** `filter` holds `clauses` joined by `conjunction` (`and` or `or`). A clause has a `property`, an `operator` (`eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `like`, `not_like`) and a `value`. The property `name` is the event name; any other property is read from the event's metadata. `aggregation` is `{ "func": "count" }`, or `sum`, `avg`, `min`, `max` or `unique` with a `"property"`. +- **Meters.** `filter` holds `clauses` joined by `conjunction` (`and` or `or`). A clause has a `property`, an `operator` (`eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `like`, `not_like`) and a `value`. The property `name` is the event name; any other property is read from the event's metadata. `aggregation` is `{ "func": "count" }`, or `sum`, `avg`, `min`, `max` or `unique` with a `"property"`. `unit` is optional: `scalar` (the default), `token`, or `custom` with a `custom_label`. - **Benefits.** `type` is `feature_flag`, a feature the app checks, or `meter_credit`, usage included before a metered price charges, with `properties` naming the `meter`, the `units` and whether unused units `rollover`. - **Products.** `recurring_interval` is `day`, `week`, `month` or `year`; add `recurring_interval_count` for every 3 months. Leave `recurring_interval` out for a one-time purchase. It cannot change once the product exists. Optional: `description`, and a trial with `trial_interval` and `trial_interval_count`. - **Prices.** `amount_type` is `fixed`, `metered_unit`, `metered_tiers`, `seat_based` or `unit_based`. A free plan is a fixed price of `0`. A metered price needs a recurring product. - **Tiers** (for `metered_tiers`, `seat_based` and `unit_based`) go in `"tiers": { "type": "graduated", "tiers": [...] }`, with `volume` as the other type. Each tier has a `unit_amount` and a `bound`, the last unit it covers; the last tier has no `bound`. - **Several currencies.** Add one price object per currency. Every currency must have the same set of price types. -Keys the format does not know are rejected, and so are comments and trailing commas. For anything not shown here, write your best guess and run `polar config plan`: an error names the field and lists the values it accepts. When the organization already has resources, the entries `init` wrote are the most reliable examples. +Keys the format does not know are rejected, and so are comments and trailing commas. For anything not shown here, write your best guess and run `polar config validate`: an error names the field and lists the values it accepts. When the organization already has resources, the entries `init` wrote are the most reliable examples. -## Step 3: Plan, fix, show +## Step 3: Validate, fix, show ```bash -polar config plan --json +polar config validate --json ``` - `entries` lists each resource with an `action` of `created`, `updated`, `unchanged` or `removed`, and for a change the `diff` of each field, `before` and `after`. - `issues` lists problems with a `severity`, the `path` of the entry (`meters.tokens.name`), a `message` and the `location` in the file. -Fix every issue with severity `error` in the file and plan again. Show warnings to the user. "No events with this name have been received yet" is expected until the app sends that event; check the event name for a typo, then move on. +Fix every issue with severity `error` in the file and validate again. Show warnings to the user. "No events with this name have been received yet" is expected until the app sends that event; check the event name for a typo, then move on. -If the plan changes something you did not touch, the file is out of date with Polar. Stop and show the user instead of applying over it. +If `validate` reports a change to something you did not touch, the file is out of date with Polar. Stop and show the user instead of drafting over it. Then tell the user in plain words what would be created, updated and removed, with the old and new value of every price that changes. -## Step 4: Apply, then publish +## Step 4: Draft, then publish Ask before each command. `--confirm` skips the CLI's own question, which a shell without a terminal cannot answer, so the user's yes to you is the confirmation. ```bash -polar config apply --confirm --json +polar config draft --confirm --json polar config publish --confirm --json ``` -- `apply` saves meters, benefits, products and settings to a draft catalog, and nothing a customer sees changes yet. +- `draft` saves meters, benefits, products and settings to the draft catalog, and nothing a customer sees changes yet. - `publish` makes the draft live: new checkouts sell it. Existing customers stay on the version they bought. -Between `apply` and `publish`, four things look wrong and are not: +Normally `draft` just updates the draft. It stops with a conflict when the draft on Polar contains changes that the local config file does not have, for example because a teammate drafted a change from their own copy of the file and has not committed it. Carrying on would throw their changes away. With `--json` the result has `"status": "conflict"` and a `conflicts` list naming each resource and whether the draft added, changed or removed it. Do not pick a way out on your own: show the user that list and ask which of these they want. + +- `polar config draft --force` makes the draft on Polar match the local file and discards the other changes. +- `polar config reset` rewrites the local config file to match what is on Polar: the draft when there is one, the live catalog otherwise. It replaces the whole file, so comments and anything that is not on Polar are lost. Without a terminal it needs `--confirm`, like the other commands that change something. + +Between `draft` and `publish`, four things look wrong and are not: -- `plan` still lists the applied changes and still says to run `apply`. It compares the file with the live catalog, not with the draft. The next step is `publish`. -- `apply` run again reports the same entries as created or updated. +- `validate` still lists the drafted changes and still says to run `draft`. It compares the file with the live catalog, not with the draft. The next step is `publish`. +- `draft` run again reports the same entries as created or updated. - A meter that is new in the draft does not count usage until `publish`. A customer's balance for it does not move while the catalog is only a draft, so publish before you test usage. - Each `publish` makes a new catalog version (`v1`, `v2`, ...). A product that changed gets a new ID on Polar and the old one stays for the customers who bought it, which is why application code uses external IDs (Step 5). -`publish` ships the draft, not the file. If the file changed after the last `apply`, run `apply` again first. To check, run `polar config publish` without `--confirm` and without `--json`: it prints a "Not in the draft" section listing what differs, then stops for confirmation. Publish with `--confirm` only when that section is absent. If the user took a change back after it was applied, say so and show them that section; do not publish over it. +`publish` ships the draft, not the file. If the file changed after the last `draft`, run `draft` again first. To check, run `polar config publish` without `--confirm` and without `--json`: it prints a "Not in the draft" section listing what differs, then stops for confirmation. Without a terminal it exits with an error at that point, which is expected. Publish with `--confirm` only when that section is absent. If the user took a change back after it was drafted, say so and show them that section; do not publish over it. Production is a separate organization with its own catalog. When the user asks for it, have them run `polar auth login --production`, check `polar auth whoami --json`, then repeat Step 3 and Step 4 with the same file. @@ -232,9 +239,9 @@ Production is a separate organization with its own catalog. When the user asks f | The user wants to | Do this | | --- | --- | | Rename what customers see | Change the name. Keep the key. | -| Change a price | Edit it, apply and publish. Existing subscribers keep their price. | -| Stop selling a product | Mark it deprecated, apply and publish. Don't delete the entry: a product with active subscriptions that is missing from the file is an error. | -| Change what a meter counts | Once a meter has billed usage, Polar rejects a change to its filter or aggregation, and `plan` reports it. Add a new meter under a new key and deprecate the old one. | +| Change a price | Edit it, draft and publish. Existing subscribers keep their price. | +| Stop selling a product | Mark it deprecated, draft and publish. Don't delete the entry: a product with active subscriptions that is missing from the file is an error. | +| Change what a meter counts | Once a meter has billed usage, Polar rejects a change to its filter or aggregation, and `validate` reports it. Add a new meter under a new key and deprecate the old one. | | Clean up the file | Run `polar config prune`. It removes deprecated entries nothing uses any more and changes nothing on Polar. | Deprecate with `.deprecated()` in TypeScript and `"deprecated": true` in JSON. A deprecated entry stays for the customers who have it, and nothing new can use it. A live product cannot grant a deprecated benefit: take the benefit out of the product's list first. @@ -260,7 +267,7 @@ Events.api_call # "api_call", from the meters' filters - The language comes from the project (`pyproject.toml`, `requirements.txt`, `setup.py` or `Pipfile` means Python). Pass `--language py` when it cannot tell. Python is the only language so far; in another language, use the external IDs as plain strings. - `--out src/myapp/polar_types.py` puts the file elsewhere. It never replaces a file it did not write. -- Run it again after every change to the config, and commit the file. `polar config generate --check` writes nothing and fails when the file is missing or out of date; add it to CI. +- Run it again after every change to the config, and commit the file. `polar config generate --check` writes nothing and fails when the file is missing or out of date; add it to CI, with the same `--out` if you used one. - Never edit the generated file. The API takes external IDs directly from version 2027-01, so the app never stores Polar's own IDs. In Python that is `from polar.v2027_01 import Polar`, then for example `external_products=[Products.pro]` when creating a checkout, `external_benefit_id=Benefits.priority_support` when listing a customer's benefit grants and `external_meter_id=Meters.api_calls` when reading a customer's meter. In TypeScript, import the client from `@polar-sh/sdk/2027-01` and pass `external_products: ["pro"]` to `polar.checkouts.create`. @@ -269,4 +276,4 @@ Never put a Polar product ID in the app's code or env file. Each publish gives a ## After the catalog is live -To sell the products, hand off to the `polar-integration` skill for the Checkout, Customer Portal and Webhooks endpoints, and to `polar-testing` to try them in sandbox. Follow "Projects with a billing config" in its Checkout recipe, so the app sells by external ID. +To sell the products, hand off to the `polar-integration` skill for the Checkout, Customer Portal and Webhooks endpoints, and to `polar-testing` to try them in sandbox. Follow "Projects with a billing config" in its Checkout recipe, so the app sells by external ID. That skill is written for TypeScript. In another language, build the same three endpoints from the SDK's documentation and the [API reference](https://polar.sh/docs/api-reference), using the external IDs from Step 5. diff --git a/skills/polar-integration/SKILL.md b/skills/polar-integration/SKILL.md index 307438a..e0d9378 100644 --- a/skills/polar-integration/SKILL.md +++ b/skills/polar-integration/SKILL.md @@ -20,7 +20,7 @@ If the project already uses `@polar-sh/sdk` below 1.0 (signs: `new Polar(...)`, Don't install the deprecated `@polar-sh/` adapters (`@polar-sh/express`, `@polar-sh/hono`, `@polar-sh/fastify`, `@polar-sh/elysia`, `@polar-sh/astro`, `@polar-sh/sveltekit`, `@polar-sh/remix`, `@polar-sh/deno`, `@polar-sh/supabase`). `@polar-sh/nextjs`, `@polar-sh/nuxt`, `@polar-sh/tanstack-start` and `@polar-sh/better-auth` are maintained; keep them if the project already uses them. -**First time with Polar?** Before you write code, ask the user whether they already have a Polar organization, want you to create one, or will create it themselves. Suggest starting in sandbox: checkout takes test cards there, so you can make a test purchase and check the whole flow end to end before real money is involved. To create the organization yourself, Polar supports the [auth.md](https://polar.sh/auth.md) spec: an agent can sign up on its own, without a human, set up the organization (products, benefits, meters, checkouts), and hand it over to the user later. Read for sandbox or for production to learn how to sign up and get claimed. A user who creates it themselves starts at or . When you start the claim, put the full `verification_uri` and the `user_code` in your reply to the user, copied exactly. Tool and command output is often collapsed or hidden, so the link only reaches the user if you write it in your message, and they can't claim the organization without it. +**First time with Polar?** Before you write code, and unless they already told you in `setup-polar` or `polar-config`, ask the user whether they already have a Polar organization, want you to create one, or will create it themselves. Suggest starting in sandbox: checkout takes test cards there, so you can make a test purchase and check the whole flow end to end before real money is involved. To create the organization yourself, Polar supports the [auth.md](https://polar.sh/auth.md) spec: an agent can sign up on its own, without a human, set up the organization (products, benefits, meters, checkouts), and hand it over to the user later. Read for sandbox or for production to learn how to sign up and get claimed. A user who creates it themselves starts at or . When you start the claim, put the full `verification_uri` and the `user_code` in your reply to the user, copied exactly. Tool and command output is often collapsed or hidden, so the link only reaches the user if you write it in your message, and they can't claim the organization without it. Required environment variables (use whatever loader your framework provides — `process.env`, `Deno.env`, `import.meta.env`, etc.): diff --git a/skills/setup-polar/SKILL.md b/skills/setup-polar/SKILL.md index 2e846c4..7ae8509 100644 --- a/skills/setup-polar/SKILL.md +++ b/skills/setup-polar/SKILL.md @@ -15,7 +15,7 @@ Ask these three questions before anything else, and wait for the answers. **1. Which organization?** - **I already have one.** Continue with Step 1. The user signs in and picks it in Step 4. -- **Create one for me.** Polar supports the [auth.md](https://polar.sh/auth.md) spec: you sign up on your own, create the organization and its products, and hand it over to the user with a claim. Read for sandbox or for production, and follow it. Skip Steps 1, 2 and 4, and create the product in Step 5 through the API with your access token. Start the claim before Step 6: the app's access token and the webhooks need it. When you start it, put the full `verification_uri` and the `user_code` in your reply to the user, copied exactly. Tool and command output is often collapsed or hidden, so the link only reaches the user if you write it in your message, and they can't claim the organization without it. +- **Create one for me.** Polar supports the [auth.md](https://polar.sh/auth.md) spec: you sign up on your own, create the organization and its products, and hand it over to the user with a claim. Read for sandbox or for production, and follow it. Ask what to call the organization, then create it with `POST /v1/organizations/` (a `name` and a `slug`); if the slug is taken, pick another and say which. Skip Steps 1, 2 and 4. In Step 5, create the product through the API with your access token, or in the config file if that is what the user chooses below. Start the claim before Step 6: the app's access token and the webhooks need it. To start it, ask the user for the email address they will sign in to Polar with. Keep working on what doesn't need the claim while you poll for it, and once it succeeds use the access token it returns, because the one you had stops working. When you start the claim, put the full `verification_uri` and the `user_code` in your reply to the user, copied exactly. Tool and command output is often collapsed or hidden, so the link only reaches the user if you write it in your message, and they can't claim the organization without it. - **I'll create it myself.** Send them to for sandbox or for production, and continue with Step 1 once they have it. **2. Sandbox or production?** @@ -27,7 +27,7 @@ Suggest sandbox. It is a separate copy of Polar where checkout takes test cards, There are two ways to manage products, prices and benefits, and the user chooses. If the project already has a `polar.config.ts` or `polar.config.json`, it uses a config file: don't ask. - **Dashboard.** Products are created and edited in the Polar dashboard, or by you through the API. Product IDs never change. This is how every organization starts, and it is what the steps below follow. -- **Config file.** The catalog lives in a file in the repository. A pricing change is reviewed like any other code change and applied with the Polar CLI. Once it is turned on, products are edited in the file and no longer in the dashboard. +- **Config file.** The catalog lives in a file in the repository. A pricing change is reviewed like any other code change, then drafted and published with the Polar CLI. Once it is turned on, products are edited in the file and no longer in the dashboard. For a config file, use the `polar-config` skill in place of Step 5, and refer to products by their external ID from then on. @@ -74,7 +74,7 @@ Ask the user: - One-time purchase - Both -From here on, work in the environment chosen at the start: use the `polar-sandbox` server's tools for sandbox and the `polar` server's tools for production. If only `polar` is available (as in ChatGPT), create sandbox products in the sandbox dashboard or with the Polar CLI instead. +From here on, work in the environment chosen at the start: use the `polar-sandbox` server's tools for sandbox and the `polar` server's tools for production. With an organization you created yourself, keep calling the API with your access token instead. If only `polar` is available (as in ChatGPT), create sandbox products in the sandbox dashboard or with the Polar CLI instead. ### Step 4: Choose the Organization @@ -120,7 +120,9 @@ polar auth login --sandbox token=$(polar auth token --scope checkouts:write --scope customer_sessions:write) && echo "POLAR_ACCESS_TOKEN=$token" >> .env ``` -`polar auth token` opens the token page in a browser with those scopes preselected, waits for the user to create the token, and prints it, so this saves it to `.env` without showing it. The token belongs to the active organization and its environment: `polar auth whoami --json` shows which one that is, and `polar auth org` changes it. +`polar auth token` opens the token page in a browser with those scopes preselected, waits for the user to create the token, and prints it, so this saves it to `.env` without showing it. Add `--scope events:write` when the app sends usage events, `--scope customer_meters:read` when it reads a customer's balance and `--scope benefits:read` when it checks benefit grants. + +If you created the organization yourself, do this after the claim and run it yourself, with your access token in place of a login: `POLAR_ACCESS_TOKEN= POLAR_ENVIRONMENT=sandbox polar auth token --scope ...`. Give the user the link it prints to approve in their browser. The token belongs to the active organization and its environment: `polar auth whoami --json` shows which one that is, and `polar auth org` changes it. Without the CLI, create the token in the sandbox or production dashboard: Settings → Access Tokens → Create token. @@ -150,4 +152,4 @@ Once basic setup works, suggest: 1. **Link to your auth** - Pass `external_customer_id` from the logged-in user when creating checkouts. 2. **Add benefits** - License keys, file downloads, Discord roles. -3. **Go production** - Production is separate from sandbox: set up the organization at polar.sh, re-create the product (it gets a new ID; with a config file, apply and publish the same file there instead, and the external IDs stay the same), create a production access token and webhook endpoint, and set `POLAR_ENVIRONMENT=production`. Then submit the organization for review in the dashboard; checkouts are blocked until it can accept payments. +3. **Go production** - Production is separate from sandbox: set up the organization at polar.sh, re-create the product (it gets a new ID; with a config file, draft and publish the same file there instead, and the external IDs stay the same), create a production access token and webhook endpoint, and set `POLAR_ENVIRONMENT=production`. Then submit the organization for review in the dashboard; checkouts are blocked until it can accept payments. From 4514a4c6ad7fc88832652e00af8ea56e566e356f Mon Sep 17 00:00:00 2001 From: sebastianekstrom Date: Thu, 26 Nov 2026 12:56:08 +0100 Subject: [PATCH 07/10] Add CI/CD instructions --- skills/polar-config/SKILL.md | 77 +++++++++++++++++++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) diff --git a/skills/polar-config/SKILL.md b/skills/polar-config/SKILL.md index 46e41c8..60e8c7f 100644 --- a/skills/polar-config/SKILL.md +++ b/skills/polar-config/SKILL.md @@ -1,7 +1,7 @@ --- name: polar-config description: | - Manage a Polar catalog as code with a billing config file (polar.config.ts or polar.config.json) and the "polar config" commands of the Polar CLI. Use this skill whenever the user wants to: (1) create or edit a Polar billing config; (2) add or change meters, benefits, products or prices in it; (3) write the config from their app's pricing; (4) check what would change, save it to the draft or publish it with polar config validate, draft or publish; (5) fix an issue those commands report; (6) retire a meter, benefit or product with deprecated and polar config prune; (7) generate the config's names for application code with polar config generate. + Manage a Polar catalog as code with a billing config file (polar.config.ts or polar.config.json) and the "polar config" commands of the Polar CLI. Use this skill whenever the user wants to: (1) create or edit a Polar billing config; (2) add or change meters, benefits, products or prices in it; (3) write the config from their app's pricing; (4) check what would change, save it to the draft or publish it with polar config validate, draft or publish; (5) fix an issue those commands report; (6) retire a meter, benefit or product with deprecated and polar config prune; (7) generate the config's names for application code with polar config generate; (8) set up CI to show config changes on pull requests and draft or publish them when they merge. --- # Polar billing config @@ -274,6 +274,81 @@ The API takes external IDs directly from version 2027-01, so the app never store Never put a Polar product ID in the app's code or env file. Each publish gives a changed product a new ID, and a checkout created with the old one fails with "Product is no longer sold". +## Step 6: Review and release from CI + +Once the config is in the repository, CI can show every pricing change on its pull request and release it when the pull request merges. Set this up when the user asks for it, and ask them two things first: + +- **What should a merge do?** Save the draft only, so a person publishes it afterwards with `polar config publish` or in the dashboard, or draft and publish. Publishing from CI makes a merged pricing change live with no further step, so add it only when the user says so. +- **Which organization does CI release to?** Usually production. For a sandbox organization, set `POLAR_ENVIRONMENT: sandbox` on the steps that run `polar`. + +CI signs in with organization access tokens instead of a login. Ask the user to create two and store them as repository secrets. Piping straight into `gh secret set` keeps the token off the screen: + +```bash +polar auth token --scope organizations:read --scope meters:read --scope benefits:read --scope products:read | gh secret set POLAR_READ_TOKEN +polar auth token --scope organizations:write --scope meters:write --scope benefits:write --scope products:write | gh secret set POLAR_WRITE_TOKEN +``` + +The first can only read and is for pull requests. The second writes and is for the main branch. Add `custom_fields:read` and `custom_fields:write` when the config has custom fields. + +A GitHub Actions workflow for a TypeScript config: + +```yaml +name: Polar billing config + +on: + pull_request: + paths: [polar.config.ts] + push: + branches: [main] + paths: [polar.config.ts] + +jobs: + validate: + if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: { node-version: 22 } + - run: npm ci + - run: npm install -g @polar-sh/cli + - run: polar config validate --pr-comment + env: + POLAR_ACCESS_TOKEN: ${{ secrets.POLAR_READ_TOKEN }} + GITHUB_TOKEN: ${{ github.token }} + + release: + if: github.event_name == 'push' + runs-on: ubuntu-latest + environment: production + permissions: + contents: read + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: { node-version: 22 } + - run: npm ci + - run: npm install -g @polar-sh/cli + - run: polar config draft --confirm + env: + POLAR_ACCESS_TOKEN: ${{ secrets.POLAR_WRITE_TOKEN }} + - run: polar config publish --confirm + env: + POLAR_ACCESS_TOKEN: ${{ secrets.POLAR_WRITE_TOKEN }} +``` + +- Leave the `publish` step out when a merge should only save the draft. +- `validate --pr-comment` posts what would change as one comment on the pull request, updates it on every push and removes it when the config no longer changes anything. It needs `GITHUB_TOKEN` and the `pull-requests: write` permission. It fails the job when the config has errors, so a broken config cannot merge. +- The `validate` job skips pull requests from forks. They get no secrets, so the job would fail without a token. +- When the config is not at the repository root, set `working-directory` on the steps that run `polar` and use the file's full path in `paths`. +- `npm ci` is there because a TypeScript config imports its package. For a JSON config, drop it, point `paths` at `polar.config.json`, and add `polar config generate --check` to the `validate` job when the project generates names (Step 5). +- `environment: production` is a GitHub environment. Suggest a required reviewer on it: a pricing change then needs a person's approval after the merge and before it reaches Polar. +- `draft` stops in CI too when the draft on Polar has changes the file does not have. Do not add `--force` on your own. Ask the user whether the main branch should always win over a draft someone saved from their machine, and add it only if they say yes. +- `--pr-comment` also works in Buildkite for a repository on GitHub. On any other CI system, run the same commands without it and read the job's output. + ## After the catalog is live To sell the products, hand off to the `polar-integration` skill for the Checkout, Customer Portal and Webhooks endpoints, and to `polar-testing` to try them in sandbox. Follow "Projects with a billing config" in its Checkout recipe, so the app sells by external ID. That skill is written for TypeScript. In another language, build the same three endpoints from the SDK's documentation and the [API reference](https://polar.sh/docs/api-reference), using the external IDs from Step 5. From e54c49ebb17328989b03e8d332e86d96958a52a2 Mon Sep 17 00:00:00 2001 From: sebastianekstrom Date: Thu, 26 Nov 2026 17:43:20 +0100 Subject: [PATCH 08/10] Import config helpers from @polar-sh/config --- skills/polar-config/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/polar-config/SKILL.md b/skills/polar-config/SKILL.md index 60e8c7f..9dcc507 100644 --- a/skills/polar-config/SKILL.md +++ b/skills/polar-config/SKILL.md @@ -74,7 +74,7 @@ Three rules hold in both formats: Each section is a function that receives its helpers and returns the entries by key. Amounts are in the currency's major unit: `usd(29)` is $29.00. Every price in a product must list the same currencies. ```ts -import { defineConfig, eq, eur, perThousand, usd } from '@polar-sh/polar' +import { defineConfig, eq, eur, perThousand, usd } from '@polar-sh/config' export default defineConfig({ meters: ({ meter }) => ({ From 287a6ae084646fcaa3f9df3e49b36bed0724ae56 Mon Sep 17 00:00:00 2001 From: sebastianekstrom Date: Fri, 27 Nov 2026 14:08:59 +0100 Subject: [PATCH 09/10] Update config skill for settings, conflicts and publish permissions --- skills/polar-config/SKILL.md | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/skills/polar-config/SKILL.md b/skills/polar-config/SKILL.md index 9dcc507..dc0cf76 100644 --- a/skills/polar-config/SKILL.md +++ b/skills/polar-config/SKILL.md @@ -67,7 +67,7 @@ Three rules hold in both formats: - **The external ID is the identity.** It is the key in TypeScript and the `external_id` field in JSON, and it is how Polar matches an entry to an existing resource. Changing it removes the old resource and creates a new one, so never rename one. To change what customers see, change the name. - **External IDs** start with a letter or digit and contain only letters, digits, `.`, `_`, `:` and `-`. Prefer snake_case: it stays a valid name in generated code. -- **A section you leave out is left alone. A products section you include is the whole catalog:** an entry missing from a section you include is left out of the next catalog version, and `"products": []` takes every product off sale. `validate` lists these as removed, "not in config". Nothing is deleted on Polar and customers keep what they have, but treat every removal `validate` reports as something the user must have asked for. +- **A section you leave out is left alone. A products section you include is the whole catalog:** an entry missing from a section you include is left out of the next catalog version, and `"products": []` takes every product off sale. `validate` lists these as removed, "not in config". Nothing is deleted on Polar and customers keep what they have, but treat every removal `validate` reports as something the user must have asked for. The same holds inside `settings`: see Settings below. ### TypeScript @@ -106,13 +106,20 @@ export default defineConfig({ - **Meters** filter events with `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `like`, `notLike`, `and`, `or`, then aggregate with `.count()`, `.sum(property)`, `.avg(property)`, `.min(property)`, `.max(property)` or `.unique(property)`. `eq('name', 'api_call')` matches the event name. A config with an `events` section, which gives each event a schema, selects events with `.on(events.api_call)` instead; follow whichever the file already uses. - **Benefits** are `flag(name)`, a feature the app checks, or `credits(name).meter(key).units(n)`, usage included before a metered price charges. Add `.rollover()` to carry unused credits over. - **Products** take `.prices(...)`, then `.recurring('monthly')`, `.recurring('yearly')`, `.recurring(3, 'months')` or `.once()`, and optionally `.grants([...])`, `.trial(14, 'days')` and `.description(text)`. -- **Prices** are `free()`, `fixed()`, `seats()`, `units()` and `meter(key)`. Tiered prices use `.graduated(...)` or `.volume(...)` with `tier()`. +- **Prices** are `free()`, `fixed()`, `seats()`, `units()` and `meter(key)`. Tiered prices use `.graduated(...)` or `.volume(...)` with `tier()`. A product takes at most one fixed or free price, one seat-based or unit-based price, and one price per meter; anything else is a type error. The package is fully typed. For anything not shown here, read its type declarations in `node_modules` rather than guessing: a wrong helper is a type error, and a reference to a meter or benefit key that does not exist is one too. ### Settings -`init` also writes a `settings` section with the organization's default currency and tax behavior: `settings: { payments: { currency: 'usd', tax: 'location' } }` in TypeScript, and the same object under `"settings"` in JSON. `tax` is `location`, `inclusive` or `exclusive`. It applies to the whole organization and takes effect on `publish`, so leave it as `init` wrote it unless the user asks for a change. +`settings` holds what applies to the whole organization, in four groups: `payments` (the default `currency`, and `tax`, which is `location`, `inclusive` or `exclusive`), `subscriptions`, `customerPortal` and `customerNotifications`. Keys are camelCase in TypeScript (`subscriptions: { allowMultipleSubscriptions: true }`) and snake_case in JSON (`"subscriptions": { "allow_multiple_subscriptions": true }`). Settings take effect on `publish`. + +Two rules decide what a `settings` section does: + +- **A file with `settings` describes every setting.** One it leaves out goes back to its default, the value a new organization gets, and `validate` shows that reset as a change. A file with no `settings` section at all leaves the organization's settings alone. +- **`init` and `reset` write only the settings that differ from their default**, and an empty `settings` when none do. So a short or empty section is correct. Never delete the section or a line in it to tidy up, and never add one the user did not ask for: both change the organization. + +Leave the section as `init` wrote it unless the user asks for a change. For the settings in each group, read the package's types in TypeScript; in JSON, `validate` names the keys a group accepts. ### JSON @@ -199,6 +206,7 @@ polar config validate --json - `entries` lists each resource with an `action` of `created`, `updated`, `unchanged` or `removed`, and for a change the `diff` of each field, `before` and `after`. - `issues` lists problems with a `severity`, the `path` of the entry (`meters.tokens.name`), a `message` and the `location` in the file. +- `draft` is there when the organization has an unpublished draft. Its `drift` lists the changes in the file that the draft does not have yet. Its `conflicts` lists changes the draft has that the file does not; Step 4 says what to do about those. Fix every issue with severity `error` in the file and validate again. Show warnings to the user. "No events with this name have been received yet" is expected until the app sends that event; check the event name for a typo, then move on. @@ -218,14 +226,16 @@ polar config publish --confirm --json - `draft` saves meters, benefits, products and settings to the draft catalog, and nothing a customer sees changes yet. - `publish` makes the draft live: new checkouts sell it. Existing customers stay on the version they bought. -Normally `draft` just updates the draft. It stops with a conflict when the draft on Polar contains changes that the local config file does not have, for example because a teammate drafted a change from their own copy of the file and has not committed it. Carrying on would throw their changes away. With `--json` the result has `"status": "conflict"` and a `conflicts` list naming each resource and whether the draft added, changed or removed it. Do not pick a way out on your own: show the user that list and ask which of these they want. +Normally `draft` just updates the draft. It stops with a conflict when the draft on Polar contains changes that the local config file does not have, for example because a teammate drafted a change from their own copy of the file and has not committed it. Carrying on would throw their changes away. With `--json` the result has `"status": "conflict"` and a `conflicts` list. Each entry names the resource (`section` and `id`), has an `action` of `created`, `updated` or `removed` for what the draft did to it, and a `diff` with each field's value in the file (`before`) and in the draft (`after`). Do not pick a way out on your own: show the user that list and ask which of these they want. - `polar config draft --force` makes the draft on Polar match the local file and discards the other changes. - `polar config reset` rewrites the local config file to match what is on Polar: the draft when there is one, the live catalog otherwise. It replaces the whole file, so comments and anything that is not on Polar are lost. Without a terminal it needs `--confirm`, like the other commands that change something. +`publish` needs the owner or admin role in the organization. "You don't have permission to publish the catalog" means the signed-in user can save a draft but not publish it: tell the user that an owner or admin has to. + Between `draft` and `publish`, four things look wrong and are not: -- `validate` still lists the drafted changes and still says to run `draft`. It compares the file with the live catalog, not with the draft. The next step is `publish`. +- `validate` still lists the drafted changes, because it compares the file with the live catalog. It checks the draft as well: once the draft has them it says they are saved in a draft and that the next step is `publish`, and with `--json` its `draft.drift` is empty. - `draft` run again reports the same entries as created or updated. - A meter that is new in the draft does not count usage until `publish`. A customer's balance for it does not move while the catalog is only a draft, so publish before you test usage. - Each `publish` makes a new catalog version (`v1`, `v2`, ...). A product that changed gets a new ID on Polar and the old one stays for the customers who bought it, which is why application code uses external IDs (Step 5). @@ -270,7 +280,7 @@ Events.api_call # "api_call", from the meters' filters - Run it again after every change to the config, and commit the file. `polar config generate --check` writes nothing and fails when the file is missing or out of date; add it to CI, with the same `--out` if you used one. - Never edit the generated file. -The API takes external IDs directly from version 2027-01, so the app never stores Polar's own IDs. In Python that is `from polar.v2027_01 import Polar`, then for example `external_products=[Products.pro]` when creating a checkout, `external_benefit_id=Benefits.priority_support` when listing a customer's benefit grants and `external_meter_id=Meters.api_calls` when reading a customer's meter. In TypeScript, import the client from `@polar-sh/sdk/2027-01` and pass `external_products: ["pro"]` to `polar.checkouts.create`. +The API takes external IDs directly from version 2027-01, so the app never stores Polar's own IDs. In Python that is `from polar.v2027_01 import Polar`, then for example `external_products=[Products.pro]` when creating a checkout, `external_benefit_id=Benefits.priority_support` when listing a customer's benefit grants and `external_meter_id=Meters.api_calls` when reading a customer's meter. In TypeScript, import the client from `@polar-sh/sdk/2027-01` and pass `external_products: ["pro"]` to `polar.checkouts.create`. Changing a subscription's plan takes `external_product_id` the same way. Never put a Polar product ID in the app's code or env file. Each publish gives a changed product a new ID, and a checkout created with the old one fails with "Product is no longer sold". From 636308517e7663a13af4181596942ca85a0f54a2 Mon Sep 17 00:00:00 2001 From: sebastianekstrom Date: Fri, 27 Nov 2026 14:20:44 +0100 Subject: [PATCH 10/10] Move CI setup into its own polar-config-ci skill --- README.md | 1 + skills/polar-config-ci/SKILL.md | 82 +++++++++++++++++++++++++++++++++ skills/polar-config/SKILL.md | 75 +----------------------------- 3 files changed, 85 insertions(+), 73 deletions(-) create mode 100644 skills/polar-config-ci/SKILL.md diff --git a/README.md b/README.md index 2a26470..cde8b84 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ Both servers use OAuth. Nothing connects until you sign in to Polar and authoriz | `setup-polar` | Guided setup from scratch: connects the MCP server, creates an organization and a first product, then hands off to `polar-integration`. | | `polar-integration` | Adds Checkout, Customer Portal and Webhooks endpoints with `@polar-sh/sdk` to any TS/JS framework, including Next.js, Express, Hono, Astro, SvelteKit, Remix, Nuxt and Cloudflare Workers. | | `polar-config` | Manages the catalog as code: writes and edits a billing config file in TypeScript or JSON, and validates, drafts and publishes it with the Polar CLI (`polar config validate`, `polar config draft`, `polar config publish`). | +| `polar-config-ci` | Sets up CI for a billing config: comments the changes on each pull request and drafts or publishes them on merge, in GitHub Actions or Buildkite. | | `polar-testing` | Tests an integration against the sandbox: test cards, local webhooks with the Polar CLI (`polar webhook listen`, `polar webhook trigger`), mocks and CI. | | `polar-migration` | Guides a migration to Polar: Polar's assisted migration from Stripe Billing, or recreating the catalog and moving customers from Paddle, Lemon Squeezy and others. | diff --git a/skills/polar-config-ci/SKILL.md b/skills/polar-config-ci/SKILL.md new file mode 100644 index 0000000..7476685 --- /dev/null +++ b/skills/polar-config-ci/SKILL.md @@ -0,0 +1,82 @@ +--- +name: polar-config-ci +description: | + Set up CI for a Polar billing config (polar.config.ts or polar.config.json). Use this skill whenever the user wants to: (1) show the changes a pull request makes to the config as a comment on it, with polar config validate --pr-comment; (2) save the config to the draft or publish it when a pull request merges; (3) create the access tokens and repository secrets CI needs for that; (4) fix a config workflow that fails in GitHub Actions or Buildkite. +--- + +# Polar billing config in CI + +This skill needs a billing config in the repository. If the project has no `polar.config.ts` or `polar.config.json` yet, use the `polar-config` skill first: it also explains what `validate`, `draft` and `publish` do. + +CI can show every pricing change to a billing config on its pull request and release it when the pull request merges. Set this up when the user asks for it, and ask them two things first: + +- **What should a merge do?** Save the draft only, so a person publishes it afterwards with `polar config publish` or in the dashboard, or draft and publish. Publishing from CI makes a merged pricing change live with no further step, so add it only when the user says so. +- **Which organization does CI release to?** Usually production. For a sandbox organization, set `POLAR_ENVIRONMENT: sandbox` on the steps that run `polar`. + +CI signs in with organization access tokens instead of a login. Ask the user to create two and store them as repository secrets. Piping straight into `gh secret set` keeps the token off the screen: + +```bash +polar auth token --scope organizations:read --scope meters:read --scope benefits:read --scope products:read | gh secret set POLAR_READ_TOKEN +polar auth token --scope organizations:write --scope meters:write --scope benefits:write --scope products:write | gh secret set POLAR_WRITE_TOKEN +``` + +The first can only read and is for pull requests. The second writes and is for the main branch. Add `custom_fields:read` and `custom_fields:write` when the config has custom fields. + +A GitHub Actions workflow for a TypeScript config: + +```yaml +name: Polar billing config + +on: + pull_request: + paths: [polar.config.ts] + push: + branches: [main] + paths: [polar.config.ts] + +jobs: + validate: + if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: { node-version: 22 } + - run: npm ci + - run: npm install -g @polar-sh/cli + - run: polar config validate --pr-comment + env: + POLAR_ACCESS_TOKEN: ${{ secrets.POLAR_READ_TOKEN }} + GITHUB_TOKEN: ${{ github.token }} + + release: + if: github.event_name == 'push' + runs-on: ubuntu-latest + environment: production + permissions: + contents: read + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: { node-version: 22 } + - run: npm ci + - run: npm install -g @polar-sh/cli + - run: polar config draft --confirm + env: + POLAR_ACCESS_TOKEN: ${{ secrets.POLAR_WRITE_TOKEN }} + - run: polar config publish --confirm + env: + POLAR_ACCESS_TOKEN: ${{ secrets.POLAR_WRITE_TOKEN }} +``` + +- Leave the `publish` step out when a merge should only save the draft. +- `validate --pr-comment` posts what would change as one comment on the pull request, updates it on every push and removes it when the config no longer changes anything. It needs `GITHUB_TOKEN` and the `pull-requests: write` permission. It fails the job when the config has errors, so a broken config cannot merge. +- The `validate` job skips pull requests from forks. They get no secrets, so the job would fail without a token. +- When the config is not at the repository root, set `working-directory` on the steps that run `polar` and use the file's full path in `paths`. +- `npm ci` is there because a TypeScript config imports its package. For a JSON config, drop it, point `paths` at `polar.config.json`, and add `polar config generate --check` to the `validate` job when the project generates names with `polar config generate`. +- `environment: production` is a GitHub environment. Suggest a required reviewer on it: a pricing change then needs a person's approval after the merge and before it reaches Polar. +- `draft` stops in CI too when the draft on Polar has changes the file does not have. Do not add `--force` on your own. Ask the user whether the main branch should always win over a draft someone saved from their machine, and add it only if they say yes. +- `--pr-comment` also works in Buildkite for a repository on GitHub. On any other CI system, run the same commands without it and read the job's output. diff --git a/skills/polar-config/SKILL.md b/skills/polar-config/SKILL.md index dc0cf76..0089bcc 100644 --- a/skills/polar-config/SKILL.md +++ b/skills/polar-config/SKILL.md @@ -1,7 +1,7 @@ --- name: polar-config description: | - Manage a Polar catalog as code with a billing config file (polar.config.ts or polar.config.json) and the "polar config" commands of the Polar CLI. Use this skill whenever the user wants to: (1) create or edit a Polar billing config; (2) add or change meters, benefits, products or prices in it; (3) write the config from their app's pricing; (4) check what would change, save it to the draft or publish it with polar config validate, draft or publish; (5) fix an issue those commands report; (6) retire a meter, benefit or product with deprecated and polar config prune; (7) generate the config's names for application code with polar config generate; (8) set up CI to show config changes on pull requests and draft or publish them when they merge. + Manage a Polar catalog as code with a billing config file (polar.config.ts or polar.config.json) and the "polar config" commands of the Polar CLI. Use this skill whenever the user wants to: (1) create or edit a Polar billing config; (2) add or change meters, benefits, products or prices in it; (3) write the config from their app's pricing; (4) check what would change, save it to the draft or publish it with polar config validate, draft or publish; (5) fix an issue those commands report; (6) retire a meter, benefit or product with deprecated and polar config prune; (7) generate the config's names for application code with polar config generate. To run these commands from CI, use the polar-config-ci skill. --- # Polar billing config @@ -286,78 +286,7 @@ Never put a Polar product ID in the app's code or env file. Each publish gives a ## Step 6: Review and release from CI -Once the config is in the repository, CI can show every pricing change on its pull request and release it when the pull request merges. Set this up when the user asks for it, and ask them two things first: - -- **What should a merge do?** Save the draft only, so a person publishes it afterwards with `polar config publish` or in the dashboard, or draft and publish. Publishing from CI makes a merged pricing change live with no further step, so add it only when the user says so. -- **Which organization does CI release to?** Usually production. For a sandbox organization, set `POLAR_ENVIRONMENT: sandbox` on the steps that run `polar`. - -CI signs in with organization access tokens instead of a login. Ask the user to create two and store them as repository secrets. Piping straight into `gh secret set` keeps the token off the screen: - -```bash -polar auth token --scope organizations:read --scope meters:read --scope benefits:read --scope products:read | gh secret set POLAR_READ_TOKEN -polar auth token --scope organizations:write --scope meters:write --scope benefits:write --scope products:write | gh secret set POLAR_WRITE_TOKEN -``` - -The first can only read and is for pull requests. The second writes and is for the main branch. Add `custom_fields:read` and `custom_fields:write` when the config has custom fields. - -A GitHub Actions workflow for a TypeScript config: - -```yaml -name: Polar billing config - -on: - pull_request: - paths: [polar.config.ts] - push: - branches: [main] - paths: [polar.config.ts] - -jobs: - validate: - if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository - runs-on: ubuntu-latest - permissions: - contents: read - pull-requests: write - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: { node-version: 22 } - - run: npm ci - - run: npm install -g @polar-sh/cli - - run: polar config validate --pr-comment - env: - POLAR_ACCESS_TOKEN: ${{ secrets.POLAR_READ_TOKEN }} - GITHUB_TOKEN: ${{ github.token }} - - release: - if: github.event_name == 'push' - runs-on: ubuntu-latest - environment: production - permissions: - contents: read - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: { node-version: 22 } - - run: npm ci - - run: npm install -g @polar-sh/cli - - run: polar config draft --confirm - env: - POLAR_ACCESS_TOKEN: ${{ secrets.POLAR_WRITE_TOKEN }} - - run: polar config publish --confirm - env: - POLAR_ACCESS_TOKEN: ${{ secrets.POLAR_WRITE_TOKEN }} -``` - -- Leave the `publish` step out when a merge should only save the draft. -- `validate --pr-comment` posts what would change as one comment on the pull request, updates it on every push and removes it when the config no longer changes anything. It needs `GITHUB_TOKEN` and the `pull-requests: write` permission. It fails the job when the config has errors, so a broken config cannot merge. -- The `validate` job skips pull requests from forks. They get no secrets, so the job would fail without a token. -- When the config is not at the repository root, set `working-directory` on the steps that run `polar` and use the file's full path in `paths`. -- `npm ci` is there because a TypeScript config imports its package. For a JSON config, drop it, point `paths` at `polar.config.json`, and add `polar config generate --check` to the `validate` job when the project generates names (Step 5). -- `environment: production` is a GitHub environment. Suggest a required reviewer on it: a pricing change then needs a person's approval after the merge and before it reaches Polar. -- `draft` stops in CI too when the draft on Polar has changes the file does not have. Do not add `--force` on your own. Ask the user whether the main branch should always win over a draft someone saved from their machine, and add it only if they say yes. -- `--pr-comment` also works in Buildkite for a repository on GitHub. On any other CI system, run the same commands without it and read the job's output. +Once the config is in the repository, CI can show every pricing change on its pull request and save or publish it when the pull request merges. Set this up only when the user asks for it, with the `polar-config-ci` skill. ## After the catalog is live