# Sign-up, plans and billing

Anyone can sign up with Google or an email link or code and start drafting without a card. Google and email create the account without a passkey; the first post adds one.
Sign-up has no Stripe Checkout and creates no Stripe customer. An agent can start the sign-up, collect its token, draft and
schedule; the person adds a card with the first post, or starts billing to continue if the free start expires.
Card entry and posting right now stay with the person, and **payment never schedules or posts**.

## Plans

`GET /api/v1/plans` (no sign-in) lists what's on sale, read from Stripe: `id` (`monthly`, `yearly`, and `founding` while
that offer runs), `amount` in cents, `price` as a decimal string, `currency`, `interval`, `trial_days`, and for
`founding` the `first_amount` and `ends_at`. The top-level `free_start` object gives `days`, `expires`,
`card_trial_enabled`, `card_trial_cutoff_days`, `card_trial_minimum_hours` and `media_limit_bytes` (262144000, or 250 MB). `trial_days` is the legacy configuration:
a positive value enables an eligible card trial, but is **not** the drafting duration or an actual charge-date quote.
The card-trial cutoff is separate from drafting expiry. `signup_open` says whether public sign-up is open yet, and `livemode` is
false while billing runs in Stripe's test mode. Every price Flaghand shows comes from this route. With staged
Managed Payments enabled, worldwide base prices are USD $19/month or $190/year; the founding offer is USD $149 for the first year, then $190/year, while
available. Includes VAT/GST outside the US and Canada; US and Canadian tax is added at checkout where it applies.
Managed Payments Checkout may show a local currency through Adaptive Pricing. Read the route and the final Checkout
quote for current prices and eligibility rather than treating these examples as a separate price source.

## Managed Payments rollout (staged)

The staged default uses one `STRIPE_MANAGED_PAYMENTS` switch for all card and Link Checkout: recurring plans,
one-time prepaid plans and credit packs. With a configured test key it is enabled unless the switch is `"false"`;
with a live key it requires `"true"`. These docs describe the staged behavior, not confirmation that live Managed
Payments has been activated. Check the server's current plans and billing responses before offering a method.

When enabled, a person starting a recurring card plan ticks an initially unticked renewal-consent box on
Flaghand's Billing page or `/approve` **before** Checkout opens. This consent needs no passkey; the later post
approval still does. Managed Payments Checkout has no Stripe renewal checkbox or custom renewal text. An API,
MCP or WebMCP recurring `startCheckout` request with omitted `pay_with` or `pay_with:"card"` returns the Flaghand person
consent link (`consent_url` and `for_person`), not a direct Checkout. Relay it unchanged; no agent or tool may tick
the box. The `agent_card` and `link` subscription modes keep their own Flaghand passkey-consent page instead.
One-time prepaid plans and credit packs do not renew and need no renewal consent. While the switch is off,
ordinary card Checkout retains its existing Stripe consent flow.

Public `listPlans` accepts `billing_country` (ISO 3166-1 alpha-2) and `billing_state` (US postal code) query
parameters for country-aware prepaid availability, for example
`GET /api/v1/plans?billing_country=US&billing_state=NY`. Supply the payer's location when known. A response without
location is discovery, **not a promise that direct prepaid payments are available globally**; it does not save a
workspace's billing location or replace the checks at quote and charge time.

## How agents pay

Read `listPlans` first (`GET /api/v1/plans?billing_country=US&billing_state=NY`): it says which of these are on for this server and payer. An agent pays only with a credential its person delegated, and payment never approves a post.

| The person gave you | Do this | Details |
| --- | --- | --- |
| A Link virtual card | `startCheckout` with `pay_with: "agent_card"`, then the person ticks once and you enter the card | [Paying as an agent](https://app.flaghand.com/docs/billing#paying-as-an-agent) |
| A Shared Payment Token | `payPlan`, answer the `mpp` challenge | [Prepaid payments](https://app.flaghand.com/docs/billing#prepaid-payments-for-agents) |
| A wallet with USDC on Base, funded or capped by them | `payPlan`, answer the `x402` challenge | [x402 USDC on Base](https://app.flaghand.com/docs/billing#x402-usdc-on-base) |
| A wallet that pays from a browser | `startCheckout` with `payment_method: "crypto"` | [Stablecoins in Checkout](https://app.flaghand.com/docs/billing#stablecoins-in-checkout) |
| A Link Pay Token | `startCheckout` with `pay_with: "link"`, then the person ticks once | [Link Pay Token](https://app.flaghand.com/docs/billing#link-pay-token-experimental) |
| Nothing, or a payer outside the direct rails' countries | Send the person the Checkout link | [One-time Managed Payments](https://app.flaghand.com/docs/billing#one-time-managed-payments-checkout) |

## Prepaid payments for agents

Read `listPlans` (`GET /api/v1/plans`, with `billing_country` / `billing_state` when known) first: `prepaid_payments.enabled` and `schemes`, together with country-aware availability, say what this server actually accepts in its Stripe mode. **In live mode, MPP with a Shared Payment Token and x402 are both on.** When a scheme isn't listed, use the existing person-led Checkout, not a wallet transfer to an unadvertised destination. Each plan's `prepaid` quote gives its one-time amount, currency and period; founding uses `first_amount` for the first paid year while eligible. These purchases **do not renew**.

With a workspace token's `billing` scope, call `payPlan` (MCP), `flaghand billing pay --plan monthly`, or `POST https://app.flaghand.com/api/v1/billing/pay` with `{"plan":"monthly","billing":{"country":"US","state":"NY"}}`. The `billing` object is optional when a complete location is already remembered for this workspace's billing account; [the shared payer-country policy](https://app.flaghand.com/docs/billing#shared-payer-country-policy) applies to every direct prepaid rail. For a new purchase, keep a unique `Idempotency-Key` and save the answer. An owner session also supplies `workspace`. The desk exposes the same operation through WebMCP; none of these interfaces approves a post.

1. Once the location policy passes, HTTP **402 payment_required** returns `error.challenges`, a list of payment schemes, plus `payment_id`, exact `amount` in cents, `currency`, `interval`, `auto_renews:false`, `description` and `terms_url`. MPP supplies `WWW-Authenticate`; x402 supplies `PAYMENT-REQUIRED`. MCP/CLI preserve each serialized challenge in the error. Confirm the resource, price, period and [Terms](https://flaghand.com/terms) against the person's delegation before answering one scheme, once. MPP names the seller's Stripe `networkId`; x402 names the Stripe deposit `payTo`. Do not substitute another seller, payee or amount.
2. Link answers the `mpp` / `stripe` challenge with a **Shared Payment Token (SPT) that the person approved**. An agent may use only a credential its person delegated, never a guessed card, an undelegated wallet or a saved card taken from another purpose. If delegation is missing, let Link ask the person to approve the spend request; the Flaghand workspace token is not payment authority. Use only an unexpired, unrevoked SPT for this one authorization.
3. Keep `Authorization: Bearer …` for workspace access and send the serialized `Payment …` answer in `Payment-Credential`, as the challenge advertises. MCP and CLI can instead send `payment_credential` in JSON. Standard MPP clients using `Authorization: Payment …` put the workspace token in `X-Flaghand-Token` on this endpoint only. Build the answer with a standard MPP client rather than by hand: with [`mppx`](https://www.npmjs.com/package/mppx), `Credential.serialize({ challenge, payload: { spt, externalId: challenge.request.externalId } })` with `const challenge = Challenge.deserialize(wwwAuthenticate)`. The payload must carry the challenge's `externalId` (this purchase's `payment_id`); without it the answer gets **400** "The Shared Payment Token credential does not match this purchase." A hand-built answer that drops, reorders or re-encodes a challenge field gets **400** "The payment challenge was changed; nothing was charged." Rebuild it from the same challenge; nothing was spent. Never send both workspace-token forms or put tokens/credentials in URLs, command arguments, screenshots or logs.
4. HTTP **200** includes `Payment-Receipt`, a paid Stripe invoice URL, `period_start` and `paid_through` (an exclusive instant), and `auto_renews:false`. Keep the receipt, not the payment credential. A lost reply or pending/error response means **recover this same `payment_id`** with the same plan; do not start another purchase to find out whether the first succeeded. A confirmed purchase always replays its receipt and never charges again. Only a definitive failure permits a fresh challenge and a newly approved credential.

For credential-bearing CLI calls, pass a private JSON file or stdin instead of a `--payment-credential` argument:

```sh
flaghand billing pay -d @/private/path/payment-request.json --json
# Or pipe the JSON from your secret-storage consumer:
flaghand billing pay -d - --json
```

The JSON contains `plan`, optional `billing`, and either `payment_id` for recovery or `payment_credential` for the challenge's answer. Keep that JSON private; the ordinary configured workspace token remains separate. With remote MCP, `getOperation` for `payPlan` loads its schema, then `callWriteOperation` with `operation_id:"payPlan"` and `arguments:{plan:"monthly",billing:{country:"US",state:"NY"}}` starts the quote (omit `billing` only when already saved). Answer with the same operation and `payment_credential`; a payment error is not post approval.

One purchase buys one calendar month or year. Remaining first-week free days stay free and posting works immediately; an SPT card that already received Flaghand free days starts its paid period immediately instead. Another purchase before expiry adds after the current paid-through instant. While the monthly X allowance applies (until posting spends credits), a top-up does not restart it, and yearly/founding plans reset it monthly. When prepaid expires without other paid access, posting stops and the existing read-only/export/deletion behavior applies; no scheduled post catches up automatically. Paid, unexpired prepaid time also satisfies the public preview and calendar-sharing requirement without a card.

A renewing subscription, or an unresolved past-due/unpaid obligation, returns **409 recurring_subscription_active**, no challenge and no prepaid charge. Follow `manage_billing` or the existing invoice recovery; payPlan never cancels the subscription. If the person already stopped renewal, prepaid begins after that subscription's remaining period. Conversely, adding a recurring plan during prepaid time defers its first charge to prepaid end; this is already-paid time, not a new free trial.

If paid-through is more than Stripe's 730-day maximum deferral away, recurring `startCheckout` returns **200**, `checkout_url:null`, `recurring_available_from` and `paid_through`, with `for_person` saying no recurring plan is needed yet and when one can start. No Checkout, subscription or charge is created. Relay that message; do not navigate a null URL or start another payment to work around it. Return on or after `recurring_available_from`. Prepaid purchases, access and the one end notice are unchanged; this is not a limit on buying prepaid time.

A full refund or lost card dispute removes that purchase's unused paid time; later stacked periods move earlier by that unused part. A partial refund, open dispute, fraud warning or won dispute does not remove access. Recovering a reversed purchase returns `status:"reversed"` and `reversed_at`, never a new charge or a fresh grant. The original invoice dates remain financial history; effective `period_start`/`paid_through` can move when an earlier purchase is reversed. There is no agent refund action. If a delegated card needs cardholder authentication, its uncharged intent is canceled and the response directs the person to the existing Checkout step.

The owners receive our payment acknowledgment. One service notice goes seven days before the current prepaid end, skipped if extended or a card was added. There are no automatic renewals or extra payment nudges. Refund rights follow the [Terms](https://flaghand.com/terms#refunds); agents have no refund endpoint. Paying never approves, schedules or posts. Agents can manage future schedules; immediate posting still needs the owner’s passkey approval.

### x402 USDC on Base

When `listPlans.prepaid_payments.schemes` advertises `x402` / `exact`, the same `payPlan` quote offers
`PAYMENT-REQUIRED`, a base64-encoded x402 v2 `PaymentRequired` value. The identical value is preserved in
`error.challenges` for HTTP JSON, MCP and CLI. The MPP steps above still apply to MPP; answer only one scheme for a
purchase. Decode and verify the purchase `resource.url`, its description (plan, exact price, period, no renewal and
Terms), `accepts` and `error.terms_url` against the person's delegation. Follow the [Terms](https://flaghand.com/terms); this is
one prepaid period, never a recurring authorization or post approval.

- The only x402 scheme is `exact`, paying **USDC on Base**: live `eip155:8453`, test Base Sepolia `eip155:84532`.
  The requirement's `asset` identifies USDC on that network and `amount` is its exact atomic-unit amount, not cents.
  Pay only the quoted **Stripe deposit `payTo`**, never an arbitrary wallet, another asset/network or a Permit2 flow.
- Use only a wallet the person explicitly **delegated and funded or capped for this spend**. Workspace `billing`
  scope permits access, not spending; do not take a wallet from another purpose or ask for a private key in chat.
- **Delegated bearer credential:** the standard client's EIP-3009 authorization signs the payer, payee, exact
  amount, network/asset domain, client-generated nonce and validity window. It does **not** sign the HTTP workspace,
  `payment_id` or resource URL. Standard `@x402/fetch` and `@x402/evm` **2.29.0** exact clients are supported without
  a custom signer or server-selected `authorizationNonce`.
- **First-use purchase binding is server-side, not cryptographic workspace binding.** Before facilitator dispatch,
  the server binds an immutable quote to the authenticated workspace and durably, atomically claims
  `(mode, network, asset, payer, nonce)` for that purchase on first use. After that claim, the authorization can only
  recover or replay the original purchase, never fund another workspace or purchase. A stolen preclaim signature is
  transferable to a same-price eligible purchase in another eligible workspace the holder can access. This bearer
  model assumes the delegated credential remains confidential; disclosure compromises it, and TLS does not protect
  it after disclosure.
- Keep `Authorization: Bearer …` for workspace access. Send the signed base64 x402 v2 payload in HTTP
  `PAYMENT-SIGNATURE`, or the identical value in JSON `payment_signature` for HTTP, MCP or CLI. Include the original
  `payment_id` and plan. Use only authenticated TLS transport; keep raw signatures and credentials out of URLs,
  command arguments, logs, errors, screenshots and retained evidence. Use the private file/stdin pattern above.
- US billing country **and state**, plus a known US **trusted edge-IP country**, are required at quote and before
  submission. `DE`, missing or unknown edge evidence makes x402 unavailable; a client-supplied country header is not
  evidence. Follow the machine-readable `next_action` for `startCheckout` with `mode:"payment",managed_payments:true`.
  It appears on `managed_payments_required`, or in `error.x402_unavailable.next_action` if an eligible MPP challenge
  remains. Do not switch to an unadvertised payment destination. The California cutoff below still applies.
- x402 also leaves `listPlans` and the 402 by itself while its settlement service is out of credits or not answering,
  with `x402_unavailable.reason` `facilitator_unavailable`, and returns by itself. Use another listed scheme or the
  `next_action`. A signature for an older quote is refused with nothing charged; sign a new quote when x402 returns.
- A facilitator submitting or settling the transfer is **not payment truth**. Paid time requires Stripe-verified
  USD settlement: a matching succeeded Stripe PaymentIntent **and its verified paid Charge** for this purchase's
  exact mode, customer, USD amount and currency, linked to the quoted network/asset and Base transaction. A transfer,
  facilitator receipt, timeout or processing result alone does not grant access. Recover the **same `payment_id` and
  plan** after every lost/pending response; retry the original signature only for this purchase, never double buy.
  A verified 200 includes `x402:{transaction,network,payer}`, the base64 v2 `PAYMENT-RESPONSE` header, the Stripe
  receipt and `paid_through`. A confirmed retry replays that purchase, never another charge or paid period.

Standard client wiring with `@x402/fetch@2.29.0` and `@x402/evm@2.29.0`:

```js
import { wrapFetchWithPayment, x402Client } from "@x402/fetch";
import { ExactEvmScheme } from "@x402/evm/exact/client";

export function prepaidFetch(delegatedSigner, livemode) {
  const network = livemode ? "eip155:8453" : "eip155:84532";
  const client = x402Client.fromConfig({
    schemes: [{ network, client: new ExactEvmScheme(delegatedSigner) }],
    spendControls: { maxAmountPerPayment: false },
  });
  return wrapFetchWithPayment(globalThis.fetch, client);
}
```

The SDK's default `maxAmountPerPayment` is **$1**, so `new x402Client()` rejects the **$19** monthly quote before
signing. This sample disables that SDK default with `maxAmountPerPayment:false`; it does **not** expand the person's
spending delegation. Use only the wallet the person explicitly delegated and funded or capped for this spend, and
validate the exact quote against that delegation. Alternatively, configure `maxAmountPerPayment` to the person's
actual delegated quote amount, not a new arbitrary cap.

This is SDK transport wiring, not wallet delegation, quote validation or a recovery loop. Supply an already
person-delegated wallet signer and the advertised mode. First verify the quote and Terms and save its `payment_id`,
plan and `Idempotency-Key`; use the returned fetch only for that same authenticated `payPlan` POST over TLS. The
wrapper answers its 402 with `PAYMENT-SIGNATURE` while preserving workspace auth and the request body; the standard
EVM scheme chooses the nonce. After a lost or pending answer, recover the original purchase rather than run a fresh
automatic-payment attempt or sign a new authorization. Never print raw SDK errors or credential-bearing requests.

x402 runs outside Managed Payments, so no Managed Payments tax coverage applies. No automatic renewal, scheduling,
posting or approval is added.

### Shared payer-country policy

`payPlan` accepts optional `billing:{country:"US",state:"NY"}` in its JSON body. `country` is an ISO 3166-1
alpha-2 country code; for `US`, `state` is a two-letter US postal code. The supplied location is remembered per
workspace billing account, so later purchases may omit it. `getBilling` returns the saved `billing_location`.
To correct it without starting a purchase, call `updateBillingLocation` (`billing` scope):
`PATCH /api/v1/workspaces/{workspace}/billing/location` with `{"billing":{"country":"US","state":"NY"}}`.
This persists the changed location; it does not start payment. MCP uses `getOperation` then `callWriteOperation`
with `operation_id:"updateBillingLocation"` and `arguments:{workspace:"ws_…",billing:{country:"US",state:"NY"}}`;
the generated CLI equivalent is `flaghand billing update-location --workspace ws_… -d '@/private/path/billing-location.json'`.
The file contains the same `billing` object as the HTTP body.

If neither the request nor the remembered location supplies the country, `payPlan` returns
**409 billing_location_required**, with `missing_fields:["billing.country"]`. A US payer without a state gets the same
code with `missing_fields:["billing.state"]`. **Nothing is charged.** Obtain the person's actual billing location,
save or supply the missing fields, and request a quote; do not guess a country or infer it from workspace time zone.

All direct prepaid rails share the same policy, whether MPP card, crypto or Stripe pay is advertised:

- The payer must be in the **United States (`US`)**.
- California (`country:"US",state:"CA"`) is ineligible **at or after `2027-01-01T08:00:00Z`**, which is
  **January 1, 2027 at 00:00 in `America/Los_Angeles`**. Before that instant it is not excluded by this state rule.
- A known evidence country different from the declared billing country also requires Managed Payments Checkout:
  the **SPT card country for MPP card**, the **trusted Cloudflare edge IP country for crypto**, or the **Stripe
  sender business country for Stripe pay**. For MPP card and Stripe sender evidence, unknown values and the sentinel
  countries `XX` and `T1` do not create a mismatch or stand in for the required billing location. **Crypto Checkout
  creation and x402 admission require a known US trusted edge-IP country**, not an unknown record. Do not substitute a client-supplied
  country header for trusted edge evidence or switch rails to evade a mismatch.

An ineligible location or a known country mismatch returns **409 managed_payments_required**, without a direct
prepaid charge. It includes an executable handoff (selected error fields shown):

```json
{
  "error": {
    "code": "managed_payments_required",
    "next_action": {
      "operation": "startCheckout",
      "arguments": {
        "workspace": "ws_…",
        "plan": "monthly",
        "mode": "payment",
        "managed_payments": true
      }
    }
  }
}
```

Use the returned workspace and plan, not the placeholders above. For HTTP, call
`POST /api/v1/workspaces/{workspace}/billing/checkout` with the returned `plan`, `mode:"payment"` and
`managed_payments:true`. For MCP, load `getOperation` for `next_action.operation`, then use `callWriteOperation`
with that `operation_id` and the returned `arguments`. For the generated CLI, write the returned `arguments` to a
private JSON file and call `flaghand billing start-checkout -d '@/private/path/managed-checkout.json' --json`.
Relay its `checkout_url` and `for_person` verbatim for the person to finish. **Keep `mode:"payment"` and
`managed_payments:true`: this is one-time Managed Payments Checkout, not a request for recurring billing.**
The handoff itself does not charge, and payment still never approves a post.

An account's newest verified Stripe Checkout country also participates in every direct payment rail, including
MPP and crypto. A contradictory country routes the next request to Managed Payments; a verified California state
observes the same PT cutoff. A newer provider record supersedes an older one, but changing the declared billing
location does not erase verified evidence. Billing reports this routing, and billing-scoped exports retain the
country-conflict record and provider timings. Money already paid is always honored; a later mismatch never causes
an automatic refund, void or denial of the paid period.

The policy is checked when quoting and again immediately before a charge or retry, using the current saved
location, applicable evidence and cutoff time. A quote is not permission to bypass a later failed check. If the
saved location changed after the quote, the stale quote is refused **without charging**: obtain a new quote for
the current location rather than answering the old challenge. This explicit uncharged rejection is different from
an unclear payment result; a lost or pending response still requires recovery of the original `payment_id`, not
another purchase. The policy does not enable live payments, change refund behavior or add a prepaid purchase cap.

## One-time Managed Payments Checkout

For one prepaid month or year by card or Link, use `startCheckout` with
`{"plan":"monthly","mode":"payment","managed_payments":true}`. This is also the executable
`next_action` for an ineligible direct payment country. Read `listPlans.managed_payments_checkout.enabled`
first. Under the staged shared switch, card/Link prepaid Checkout uses Managed Payments by default when enabled;
`mode:"payment"` still selects a one-time purchase. Omitting `mode` selects a recurring plan, not prepaid. Test
keys default to Managed Payments unless explicitly disabled; live requires explicit enablement.

This Checkout is available for any billing country supported by Stripe Managed Payments. It buys time using the
same prepaid ledger and never automatically renews, so there is **no renewal-consent box or passkey renewal step**.
The person can finish the returned `checkout_url`, or an agent can pay only with a Link-issued credential the person
approved. For a delegated card add `pay_with:"agent_card"`; for Link's token UI add `pay_with:"link"` when enabled.
Never use a card supplied in chat. Use the chosen plan's `prepaid.amount` and currency for a **one-time** spend request
(omit `--recurring-interval`); Stripe displays the final tax, currency and total before payment. Do not exceed the
person's approved amount: obtain a new approval if the final total exceeds it. Founding buys its first year at
`first_amount`; this purchase has no automatic renewal. A later purchase quotes the then-current plan price.
Includes VAT/GST outside the US and Canada; US and Canadian tax is added at checkout where it applies.

CLI: `flaghand billing start-checkout --plan monthly --mode payment --managed-payments true --pay-with agent_card --json`.
MCP: `getOperation` for `startCheckout`, then `callWriteOperation` with the same arguments and workspace.
WebMCP accepts the same options. Save `payment_id` and `checkout_session_id`; an ambiguous response means recover
that same purchase, not buy a second one. `confirmCheckout` verifies Stripe's actual paid Session, subtotal/tax/total
and currency, PaymentIntent and paid Charge before access. The plan quote is USD; Adaptive Pricing may show local
currency in Checkout. A browser redirect alone proves nothing.
Stripe handles its tax and receipt/invoice; Flaghand retains the provider's paid receipt and sends the prepaid
acknowledgment and one end notice. Payment never approves a post and no agent refund action exists.

## Stablecoins in Checkout

Read `listPlans.crypto_checkout.enabled` before offering this method, supplying `billing_country` and US `billing_state` for discovery. Its `country_policy` explains missing location or ineligibility and `managed_payments_operation` names `startCheckout`. Crypto availability also checks trusted edge IP country; MPP card discovery uses billing location because its separate card evidence arrives with the SPT. Neither a client-supplied IP header nor missing location promises global crypto availability. **Stablecoin Checkout is on in live mode for US payers (not California from Jan 1, 2027).** Stablecoin subscriptions require Stripe preview access, so this method instead buys the same prepaid month or year described above. It never renews, needs no renewal-consent box and keeps the workspace's remaining first-week free days.

It uses the shared US-payer policy above: supply or remember `billing` country and US state. **Creating crypto
Checkout also requires a known US request-IP country from our trusted edge**; unknown or conflicting evidence routes
to the returned one-time Managed Payments action instead. We ask for the location once, not again on Stripe's page.
If Stripe supplies an address anyway, its country/state is retained separately as a third record. A later contradiction
is flagged for the books and affects the next direct-rail request; it never reverses a paid purchase. Neither record
comes from a client-supplied `CF-IPCountry` header. Correcting the saved billing location retires an open stale
stablecoin Checkout before a new one can be offered. If Stripe cannot confirm expiry, recover that same purchase
before trying another; failed expiry is not proof that no payment happened.

California crypto Checkout expires no later than January 1, 2027 at 00:00 PT (`2027-01-01T08:00:00Z`). With fewer than Stripe's
30-minute creation minimum remaining, request the returned one-time Managed Payments action instead. A payment already
in flight can settle after expiry, the cutoff or a location correction: **verified money received still buys its full
paid period**. These exceptions are recorded for the books, never automatically voided or refunded.

With `billing` scope, call `startCheckout` with `{"plan":"monthly","payment_method":"crypto"}` (yearly/founding also work while eligible). HTTP `POST /api/v1/workspaces/{workspace}/billing/checkout` and CLI `flaghand billing start-checkout --plan monthly --payment-method crypto` are equivalent. Save `payment_id` and `checkout_session_id`; relay `for_person` and the short Flaghand `checkout_url` unchanged. The person chooses a coin and connects their wallet on **crypto.stripe.com**. An agent may finish only with a wallet its person delegated and funded; a Flaghand token is not wallet authority. Never put wallet keys in Flaghand, chat, command arguments or logs.

The response quotes `amount` in USD cents, `currency`, `interval` and `auto_renews:false`. Opening or returning from Checkout is not proof of payment: `confirmCheckout` reads Stripe's actual paid Session, PaymentIntent and Charge. A pending or lost reply means recover this same Checkout, not buy again. Compatible retries share one open purchase; a different plan waits until that Checkout finishes or expires. The existing card default remains a recurring plan. A recurring subscription or unpaid obligation blocks prepaid purchases; a pending stablecoin Checkout blocks a competing new card Checkout.

Stripe converts the stablecoin to USD for our Stripe balance; Flaghand holds no coins. We retain the verified paying wallet address, network, coin and transaction ID with the billing record. **A stablecoin payment can't be cancelled, reversed or disputed.** A refund, if due under the Terms, returns as the same stablecoin to the wallet that paid; agents have no refund action. Owners receive the prepaid acknowledgment and the same one end notice. Payment never approves, schedules or posts.

## Monthly X allowance

Until posting to X spends credits, every plan includes **300 X posts per workspace per billing month, including up
to 30 link posts**. Once `getCredits.spends` or `listPlans.credits.spends` lists `x_posting`, this count ends; the
[posting credits](https://app.flaghand.com/docs/credits.md#posting-on-credits) and their set-asides apply instead. Posts scheduled before posting
spent credits go out free.

While the allowance applies, a billing month runs from one monthly renewal day to the next, in UTC; yearly and
founding plans reset on that same day each month,
not once a year. A day missing from a shorter month uses that month's last day, then returns to the original day
(for example January 31 → February 28 → March 31). The first reset is one month after the first-charge date;
posts accepted during the free days count toward that same first month, not a second free allowance.

Only accepted X writes use the allowance: each thread part, plug reply and delayed repost counts as one. Creating a
post containing one or more URLs also uses one link post (not one per URL). A later delete does not give either back.
This allowance applies only to X. Failed X writes do not count. In-flight or unclear outcomes
reserve capacity until acceptance is known. When X answers a post or thread part with a server error (5xx), it keeps
its one reservation and is retried as before: twice more, 2 minutes apart, or by approving the same text again. X
normally refuses an exact repeat of a recent post, and a resend never counts twice. Any other unclear outcome (no
answer, a dropped connection, no post id) is never sent again automatically, and neither is a plug or repost.

While the allowance applies, `getBilling`, `getMe`'s workspace entries and `flaghand billing get` return `x_posts`,
and the desk's Billing view shows the same counts. Once posting spends credits, `x_posts` is `null` and Billing
shows credits instead. An allowance example:

```json
{ "used": 12, "limit": 300, "link_posts": { "used": 3, "limit": 30 },
  "reserved": 0, "link_reserved": 0,
  "period_started_at": "2026-11-13T18:02:11.000Z", "resets_at": "2026-12-13T18:02:11.000Z" }
```

`used` is accepted writes only; `reserved` and `link_reserved` protect capacity while a write is in flight, its
outcome is uncertain, or it waits to be resent after a 5xx. Checks, approval and scheduling say when a plan would
exceed its target period, including already-scheduled work and every part of a multi-draft plan. They do not charge
for scheduling. At posting time the same check runs again and each send reserves capacity atomically across all of
the workspace's connections.

While the allowance applies, a due post that cannot fit is **held** with `error_code: "x_allowance_reached"`, the reset date and the next step.
It uses the same `job.held` event and owner alerts as other holds, including a plug or repost held separately from its
live parent. It never posts late by itself after a reset. Cancel the held job, choose a new time at or after the
returned reset date and request the owner's approval again; if only the link allowance ran out, removing the link
and requesting approval again is another option. A held plug or delayed repost can't be given a new time, so its
`next_step` says what can be done: cancel it, then draft the plug's text as a new X reply to the live post
(`reply_to_url`) for approval after the reset (or now, without its link, if only links ran out), or repost the post
on X yourself after the reset. There is no extra-usage purchase to offer.

## Signing up

1. `POST /api/v1/signup` with `{ "email": "person@example.com", "workspace_name": "My workspace", "found_via": "llms-txt" }`.
   `plan` is optional (`monthly`, `yearly`, `founding`); `plan: null` means no preference, not a free subscription.
   Checkout defaults to monthly unless a plan is chosen there. Optional `workspace_name` names new workspaces only;
   an existing owner's workspace stays unchanged, as the Allow page and ready claim explain. Also optional: `agent_name`,
   IANA `time_zone`, `invite`, `referrer`, `landing_path` and campaign tags. Use `found_via` for where you found the product;
   legacy `utm_source` aliases it only when `found_via` is absent. The answer:
   `{ "signup_url": "https://app.flaghand.com/start#signup=…", "for_person": "…", "user_code": "K7QM-2XRT", "claim_code": "clm_…", "expires_at": "…" }`.
   New, pending and existing emails all get the same answer, with a fresh link, code and claim code on every call;
   earlier links remain valid. `user_code` is the code an existing owner types before Allow, and `for_person` ends with
   it; it isn't a secret like the claim code, but show it only to your own person.
   The claim code is a secret like the token: write this reply to a new private file outside the repository before
   printing anything (`umask 077`); show only `for_person`, `signup_url` and expiry. Never print the claim code or put
   it in command arguments, shell history or shared logs.
2. Relay `for_person` unchanged alongside `signup_url`; do not invent prices or substitute payment instructions.
   An unused link lasts 24 hours. New owners create their account and workspace with Google or an email link or code.
   Google and email do not require a passkey at sign-up; the first approval creates it. Sign-up has no Checkout or
   card step and creates no Stripe customer. Existing owners sign in with a configured method for that email,
   choose a workspace they own, type the code from `for_person` and click **Allow**, with their passkey or, if they
   have none, a code emailed to them. The page shows the agent's name and its four OAuth scopes; signing in alone grants no access, and a missing or wrong code answers
   `user_code_mismatch`. Every owner of the workspace is emailed at once, with a link to review or revoke the agent.
   No new account, subscription or free-start window is created.
3. Collect with `claimSignup`: `POST /api/v1/signup/claim` with `{ "claim_code": "…" }`. It answers `202 {"status":
   "pending"}` with `Retry-After: 5` until registration or consent, then
   `200 {"status": "ready", "token": "tok_…", "workspace_id": "ws_…", "scopes": [...]}`.
   Write that answer to a private file before printing anything, then keep the token in secret storage. New-account tokens have every agent scope,
   `billing` included. Existing-account grants have only `read`, `drafts`, `media` and `request-approval`, like OAuth.
   Both can manage future scheduled posts with drafts scope; neither can approve or post immediately. Use the returned scopes. A ready claim also returns `identity_assertion`
   and `assertion_expires`, saved atomically with the token. Keep the assertion in secret storage too if you use
   [auth.md's JWT-bearer grant](https://app.flaghand.com/auth.md#step-5-another-token-from-the-assertion); revoking any token from the
   claim ends that assertion's ability to mint more. A reissue (rotation with the current token, or an owner's approval)
   replaces both the token secret and assertion without extending their seven-day claim deadline; earlier credentials
   stop working.

After relaying `for_person` with its link, ask the person to tell you when they're back.
Where installed, `flaghand signup --email person@example.com` saves a private start reply and prints its resume command
before waiting. `flaghand signup wait @/private/path/signup.json` reads the saved start reply (or a plain code file);
`flaghand signup wait - < /private/path/claim-code` reads stdin, keeping the code out of argv and shell history. It
waits quietly using `Retry-After`, keeps the token as `login` does and answers once without printing either secret
(`--json` returns `stored: true`). Otherwise stop the turn and call `claimSignup`
once when the person returns. If still pending, keep the original link and honor the retry hint between turns;
never loop pending tool calls into agent context or start another sign-up just because the first is pending.
Pending `next_step` and `message` explain the person's original-link handoff and passkey alternatives, without
disclosing email existence. The claim is ready after registration or explicit Allow, not payment. There is no Checkout
to wait for at sign-up. Read `getMe` and `getSetup` and follow their `next` guidance to connect and draft during an
eligible workspace's free start; recovering access never restarts that window.

## Picking up an interrupted sign-up

- An unused sign-up link expires after 24 hours. The page tells the person to return to their agent for a fresh
  `startSignup` link; the old `claimSignup` answers `challenge_expired`. Use the same email, not another account.
- Once registration is complete, reopening the original link resumes the existing account, even after the link's original
  expiry. On a second device, sign in with a configured method. There is no signup card step
  to complete and no reason to create another account.
- The original code remains collectible for seven days after registration or consent, independently of Checkout.
  Write the claim answer to a private file before printing anything, then keep its token in secret storage. `getMe`
  identifies the workspace and `getBilling` shows its access. Do not wait for `can_post: true` before drafting in `starting`.
- If the agent lost the token but still has the claim code, it claims again with that code within 7 days of the
  registration or Allow. The code alone doesn't issue the token again: HTTP 202 with `next_step: "owner_approves_reissue"`
  includes an `approve_url`, where a workspace
  owner signs in and taps Reissue, and the agent then collects a new secret with the returned `reissue_code`. The
  earlier secret stops working then. An agent that still has the token rotates it by sending it as its bearer on the
  same claim. Once a token from that sign-up has been revoked, the code makes no more.
- If the agent lost its claim code, or the code has stopped working, a fresh `startSignup` with the same email lets the
  owner sign in, type the new link's code and **Allow** that agent. The workspace, subscription and original free-start/trial dates are kept.
  The existing-account grant has only the four OAuth scopes: it can read billing but cannot start Checkout or connect
  platform accounts itself. The owner handles those steps in the product; adding a card is not a condition of Allow
  during `starting`.
- Two pending links remain independent, including when the second is opened in the same tab. The first registration
  creates the account; the second link uses that account's sign-in and explicit Allow. Each agent claims
  its own code. Neither link creates another account, subscription, trial or free-start window.
- If a later add-card Checkout is interrupted, closing it loses neither the account nor the agent's claim. The same
  plan reuses a compatible open Stripe session; an expired session gets a fresh link. A plan change first confirms
  that the earlier session has expired. A failed confirmation never opens a second payable session. A finished
  Checkout is confirmed before another can start, even if its webhook has not arrived: do not pay again.
  The first-approval card step returns to `/approve` for normal passkey approval; payment never approves a post.
  An unexpired compatible Checkout begun before the card-trial cutoff keeps its saved first-charge date after that cutoff.
  If expiry or changed terms require a replacement with a different charge time, the response asks the owner to reload
  Billing or the approval link and review the new timing before another Checkout starts. A rejected creation request
  can be corrected without waiting for its old request to expire; an unclear provider result still keeps its original
  idempotent request until safely resolved.

The person finishes by returning to their agent. Read setup once when they return, or use the quiet CLI signup wait
for the claim. Never start more sign-ups merely because the current claim is pending.

The web page does the same: `https://app.flaghand.com/start` offers the configured sign-in methods and an optional plan preference.
Google/email sign-up does not require a passkey or card; the first approval handles those steps. The email is for sign-in, billing and account recovery. A post in the link's hash (`https://app.flaghand.com/start#platform=x&text=…`, or
`platform=linkedin`; an X thread as `platform=x&post=…&post=…`, its posts in order) stays in that browser tab, unsent,
until the first run's "Or write it yourself" opens it as a draft (a thread as one `x_thread`).

Lost every passkey? `POST /api/v1/auth/recover` with `{ "email": "…" }` (or "Lost your passkey?" on `https://app.flaghand.com/sign-in`)
emails that account a one-time link to add a new one, at most once per five minutes. It answers `200 {"ok":true}`
whether the email was sent, suppressed or has no account. Repeats don't extend the window; receipts are never limited
by it. See the [recovery email limit](https://app.flaghand.com/docs/sign-in-and-tokens#recovery-email-limit).

## The free start and first approval

An eligible, non-comped workspace that has never had a Stripe subscription in the current test/live mode is `starting`.
Its clock is measured from `workspace.created_at`, not from a token claim or card addition. Read `free_start` in
`GET /api/v1/plans` for the current duration and whether drafting expires. Billing reports `state: "starting"`,
`free_until` (null when it does not expire) and `can_post: false`. During this window agents can
draft, upload media, connect accounts, check and request approval, and owners can create tokens and authorize OAuth
apps without a card. The usual scope, passkey and platform-consent boundaries do not change.

Until a card is added, a `starting` workspace holds up to **250 MB of media** (250 × 1024 × 1024 bytes):
the files you upload and the copies Flaghand stores from them. This includes retained slide renders, PDF exports,
platform conversions and the desk's image cache; shared storage keys count once. Backups and the separate analytics
JSON history are not additional media. Adding a card through an accepted card trial, or starting a paid plan,
lifts the storage limit; a refused card trial that leaves the workspace `starting` does not. No other billing state
has this storage limit. Necessary copies of media already stored are never refused, so they can take usage above
250 MB; new uploads and explicit renders are then refused until billing starts or enough unused media is deleted.

`getBilling` (`GET /api/v1/workspaces/{workspace}/billing`, CLI `flaghand billing get --workspace ws_… --json`,
MCP `getBilling`) includes `media_storage: { "used_bytes": 1048576, "limit_bytes": 262144000, "deletes_at": null }`.
`limit_bytes` is null in every other state. An addition that would pass the limit returns HTTP 402
[`media_storage_full`](https://app.flaghand.com/docs/errors.md), with the used and limit bytes and one `next_step`; relay its line unchanged.

Approval, scheduling and posting require `active`, even for approve-only plans. Best-times refresh and automatic
insights reads also require `active`; connecting and explicit connection verification are unchanged. Ordinary
suggestions and stored results remain readable without starting new automatic platform reads.

When the plan is ready, give the owner its `approval_url`. On `/approve`, a starting workspace shows the chosen plan,
price and estimated first-charge timing. When the staged Managed Payments switch is enabled, the person ticks the
initially unticked renewal box here before opening Stripe Checkout, without a passkey for that billing consent.
When disabled, ordinary Checkout keeps its existing Stripe consent flow. Checkout shows the exact trial charge date
and time before card entry. It returns to the same approval
page for the normal passkey approval of the exact snapshot. Adding a card neither approves nor schedules nor posts.
Do not replace that one-link handoff with a separate payment chore before drafting.

In the desk, a draft's post button says what billing needs and goes there: "Add a card to post" (starting, or the free
start ended) and "Restart to post" (the plan ended) open that draft's `/approve` card step, which returns for the
passkey; "Update card to post" (payment failed) opens the Stripe Customer Portal. A post button that is off for another
reason names it under the button, for example "Add text or media to your post first." Agents reach the same places
with the draft's `approval_url`, `startCheckout` (its `return_to` that approval link) or `openBillingPortal`, and read
the reason from `getBilling`'s `can_post` and `message`, or `checkDraft`'s answer.

If the free start expires without a card, the workspace is `lapsed`: reading, export and starting billing still work,
but new drafts and other drafting changes stop. `getMe` and `getSetup`'s `next` guidance points to billing. A refused change
returns HTTP 402 `workspace_inactive` with a `next_step` linking to the add-card step. There is no new add-card
reminder email; the agent explains the returned next step.

## Paying as an agent

An agent may finish Stripe Checkout using **only a Link-issued payment credential its person approved** for this
purchase. Never ask for, accept or type a card number from chat. A Flaghand billing token lets you start Checkout;
it is not authority to spend from someone's wallet. Payment never approves, schedules or posts anything.

1. Read `GET /api/v1/plans` (`listPlans`) and the workspace's billing state. Use the chosen plan's `amount` (minor units),
   `currency` and `interval` for the recurring authorization. `first_amount` is the founding first-year discount, not
   its renewal: founding needs an authorization covering **USD $190 each year**, although its first year is $149.
   Includes VAT/GST outside the US and Canada; US and Canadian tax is added at checkout where it applies.
   Include any tax Stripe actually quotes; do not invent a price or increase an approved amount without approval.
2. Use `startCheckout` (`billing` scope) with `{"plan":"monthly","pay_with":"agent_card"}` for a recurring virtual
   card, or `pay_with: "link"` for Link's token/wallet UI. Read `link_checkout_enabled` first: true in test and live
   mode. CLI:
   `flaghand billing start-checkout --plan monthly --pay-with agent_card --json`. MCP: load `getOperation` for
   `startCheckout`, then `callWriteOperation` with those arguments. WebMCP accepts the same options.
   **HTTP 202 means no Checkout exists yet.** Relay `consent_url` and `for_person` unchanged to the person. They review
   the exact A3 renewal text, tick its initially unticked box themselves and confirm with their own user-verifying
   passkey on Flaghand. If needed, they add their own passkey first. The agent cannot do this with a billing token,
   a signed-in cookie or wallet approval. When they return, retry the same `startCheckout` request.
   Only then follow its **unchanged** `checkout_url` through `/pay#…`; never rebuild or strip Stripe's redirect fragment.
   The agent-paid Checkout has **no renewal-consent box** and uses the saved plan, amount and first-charge time. Changed
   terms, a restart or an expired session need a new person consent, never a silently earlier/later charge.
   `recovery` continues an existing obligation: follow its current instructions, not a second subscription/spend request.
3. Authorize your agent with Link's `payment_methods.agentic` scope using
   [Link's agent authorization](https://docs.stripe.com/agentic-commerce/agents/link-agent-wallet/oauth).
   Create a recurring virtual-card spend request for the actual plan and merchant, using the final approved amount,
   not a base amount that omits applicable tax. Includes VAT/GST outside the US and Canada; US and Canadian tax is added at checkout where it applies.

```sh
link-cli spend-request create --amount "$APPROVED_AMOUNT_MINOR" --currency "$APPROVED_CURRENCY" --recurring-interval month --merchant-name "Flaghand" --merchant-url "https://flaghand.com" --context "Setting up the person's requested Flaghand monthly subscription with a recurring virtual card at the approved total until they cancel in Flaghand Billing." --idempotency-key "UNIQUE_PURCHASE_INTENT"
```

   For yearly or founding, read plans again and use `--recurring-interval year` and that plan's renewal `amount`.
   Reuse an idempotency key only for the same purchase intent. Relay Link's approval URL to the person and wait for
   its approved result; a pending, denied, expired or `requires_action` request is not permission to pay.
4. Retrieve the approved card with `link-cli spend-request retrieve REQUEST_ID --include card --format json`, piping
   its output **directly into your secure browser-input helper**, never to chat, model context, terminal output or
   shared logs. Check both the spend request's expiry and the card's `valid_until`: a recurring card still expires.
   It must remain valid through the deferred first charge and the period you are authorizing; plan how to update it
   before a future renewal outlives the credential. A one-time virtual card is not a recurring-subscription credential.
   If it expires before the deferred charge, request a recurring credential with adequate validity or hand the person
   an ordinary `pay_with: "card"` Checkout for their own durable card. Never silently remove free days or move the charge
   earlier to make a short-lived card work; any changed first-charge terms require new person consent.
5. Enter the approved credential only on Stripe's agent-paid Checkout page, after the Flaghand passkey consent above.
   **Never tick any renewal box for the person**, including by switching to ordinary card mode. Wallet approval alone
   is not renewal consent, and payment is never passkey approval of a post.
   After Checkout finishes, call `confirmCheckout` with its `checkout_session_id`, or read `getBilling` to verify the
   subscription. A browser redirect or a successful wallet authorization alone does not prove Flaghand is active.

The steps above are for a recurring subscription. For a **single paid period**, use [one-time Managed Payments Checkout](https://app.flaghand.com/docs/billing#one-time-managed-payments-checkout): no recurring authorization or renewal consent is needed. Only a person-approved credential may pay, and its amount must cover Stripe's final tax/total.

### Link Pay Token (experimental)

Read `link_checkout_enabled` from plans first. When true, `startCheckout` with
`{"plan":"monthly","pay_with":"link"}` offers Link **for that session only**. CLI adds `--pay-with link`; MCP and
WebMCP accept `pay_with: "link"`. Both agent subscription modes require the passkey-consent flow above. When the
staged Managed Payments switch is enabled, omission or `"card"` instead returns the person's Flaghand Billing or
`/approve` renewal-consent link, never a direct Checkout. That person's own unticked box needs no billing passkey;
an agent must not tick it. With the switch off, ordinary card Checkout retains its Stripe renewal box.
Only `"link"` enables Link's save box and phone field in non-Managed Checkout. **Managed Payments is different:**
Stripe owns its payment methods and requires Link's display to stay `auto`, including for `pay_with:"agent_card"`;
use the approved virtual card on that form and decline optional saving if not authorized. Managed Payments adds
no Stripe renewal checkbox or custom renewal text.
Changing modes retires the previous payable Checkout first. Test Stripe keys
enable agent modes; both are off live until security review and the approved legal pages are published.

On Stripe's page, discover the current WebMCP tools rather than hard-coding tool names or schemas, and rediscover
when the payment form changes. Stripe's consequential payment tool still needs the person's confirmation.
Search the top page and every Stripe frame for `.AiAgentPaymentSteering`. In the frame containing it, confirm
`input[name="link_pay_token"]` exists and read `[data-stripe-merchant-account]` inside the same steering block.
If either is missing, **fall back to an approved recurring virtual card**, not a guessed account or injected control.

When supported, create a Link spend request with `--credential-type link_pay_token --merchant-account-id` set to that
observed account, the plan's amount/currency, **`--recurring-interval month` or `year`** matching plans, and a description
of its renewal terms; omit `--merchant-name` and `--merchant-url` for this credential type. Confirm the approved response
actually carries that recurring authorization. If the provider refuses it or returns only one-time authority, use an
approved recurring virtual card instead; explanatory context alone never authorizes future charges. After the person
approves, retrieve `--include link_pay_token` straight into the browser helper. Use the input's native
`HTMLInputElement.prototype.value` setter, then dispatch a bubbling
`input` event, as [Link's payment guide](https://docs.stripe.com/agentic-commerce/agents/link-agent-wallet/use-link-wallet-pay-online#pay-with-a-link-pay-token)
instructs. Wait for Stripe to replace the form with the saved method before submitting. The person's signed Flaghand
renewal consent is already on file; verify the completed subscription just as for a card. Tokens expire after at most
30 minutes.

**Test limitation, checked October 27, 2026:** Link CLI 0.30.0 documents that `link_pay_token` requests reject `--test`.
It is not a test-mode payment path we can promise works. Never drop `--test` to get around this or inject a live
credential into test Checkout. For a test-mode virtual card request, add `--test` to the recurring example above;
Link says this never charges the underlying payment method. Retrieve the actual approved test credential rather than
copying a sample card from its README: the sample ending 1984 was rejected as an invalid card number in our Stripe
test Checkout on October 27, 2026. This still requires Link authorization; a public test card used by itself is a
card-form test, not evidence of person-approved wallet delegation.

**What we have verified:** on October 27, 2026, Stripe test cards completed the agent-paid monthly/yearly subscription
path after a synthetic owner's passkey renewal consent, including Managed Payments. Stripe's sandbox Link save-and-pay
flow also completed and returned a card with `wallet.type=link`. These are test-mode integration checks, **not proof of
Link agent-wallet issuance, an approved real spend request, or a Link Pay Token payment**. Those end-to-end Link-wallet
steps remain unverified; the first real approved wallet payment will be observed in production, not forced with a
company self-purchase. Live agent Checkout stays off until the separate security/legal release.

If a CAPTCHA or bot control stops payment, report the blocker without inventing a successful payment or changing
account security. [Stripe WebMCP](https://docs.stripe.com/agentic-commerce/agents/webmcp) is experimental.

## Starting and managing the plan

Signed-in owners, and tokens with the `billing` scope:

| Route | Does |
|---|---|
| `PATCH /workspaces/{workspace}/billing/location` `{ "billing": { "country": "US", "state": "NY" } }` | `updateBillingLocation`: saves the payer location for this workspace's billing account without starting payment; `getBilling.billing_location` reads it back. |
| `POST /workspaces/{workspace}/billing/checkout` `{ "plan": "monthly" }` | When staged Managed Payments is enabled, API/MCP/WebMCP `card` requests return the Flaghand person renewal-consent link (`consent_url`, `for_person`), not a direct Checkout; the person ticks the box on Billing or `/approve` without a billing passkey. Otherwise returns a short Flaghand `checkout_url` for payment or existing-subscription recovery, relayed verbatim without unwrapping it. `incomplete`, `unpaid` and `paused` recover the existing obligation, never a second plan; Managed Payments owns its recovery and Flaghand does not directly pay its invoices. Compatible open Checkouts are reused. If its short link is unavailable, `409 conflict` includes `error.checkout_session_id` and `error.next_step`: continue the already-open Checkout or retry the same arguments, including `plan` and `return_to`; never start a second subscription. The `free_start` policy describes eligibility, cutoff and minimum; disabled trials, new Checkouts after cutoff and restarts charge when completed. |
| `POST /workspaces/{workspace}/billing/sync` `{ "checkout_session_id": "cs_…" }` | Reads a finished Checkout from Stripe now, so nothing waits on a webhook. The Checkout return calls it; passkey-only sign-up has no Checkout to confirm. |
| `POST /workspaces/{workspace}/billing/portal` | A short Flaghand link (`portal_url`) to Stripe Customer Portal: the card, invoices, monthly or yearly, cancel. |
| `POST /workspaces/{workspace}/billing/cancel` | Cancels at the end of the period: a card-backed trial ends with nothing charged; before a plan starts, confirms nothing is due without starting one. |
| `POST /workspaces/{workspace}/billing/resume` | Keeps the plan: undoes a cancel before the period ends. |

### If the person asks to cancel in the free week

Call `cancelPlan` (`POST …/billing/cancel`, `billing` scope); don't send them to Checkout first or ask again.
Without a subscription there is nothing to stop or pay: the original `free_until` is unchanged, and at that time the
workspace becomes read-only. With a card-backed trial, cancellation stops the first charge and the plan ends at
`ends_at` (the trial end). Drafts remain readable and exportable after either ends, and starting a plan in Billing
brings the workspace back; cancellation does not delete the account or its drafts.

The answer's `for_person` is one sentence to relay unchanged, with the actual date, time, workspace time zone and
Billing link. For example: “Your trial is canceled with nothing to pay; drafting and posting end on November 3, 2026
at 10:00 AM PST, then the workspace is read-only, your drafts stay readable and exportable, and you can return by
starting a plan in Billing at https://app.flaghand.com/billing?workspace=ws_….” No cancellation email is sent: the API/MCP answer
is the confirmation. Any earlier subscription-terms email remains a record of the original agreement, not a new charge.

Checkout always collects a payment method. For an eligible first subscription with a card trial enabled and Checkout
created before `card_trial_cutoff_days` from workspace creation, the first charge is due one hour after that cutoff or
`card_trial_minimum_hours` after Checkout creation, whichever is later. The minimum is measured from creating Checkout,
not when the card is entered. Read the actual date and time shown before confirming. With trials disabled, or for a new
Checkout at or after the cutoff, there is no trial and the charge is due when Checkout completes. A compatible existing
Checkout may retain its saved first-charge date after the cutoff. There is still only one trial per workspace, and a card
cannot be used to claim another trial. The founding first-year coupon is unchanged. No Stripe customer is created until
the person starts the add-card step.

The billing portal normally lets the person switch between monthly and yearly plans. Switching during the free trial keeps
its original end date: it does not start charging early. After the trial, plan changes prorate charges and credits.
During unexpired prepaid access, the Portal keeps payment methods, invoices and billing details but cannot change a plan or undo cancellation. Cancel renewal using **Cancel plan** in Billing, `cancelPlan` (MCP), or the matching HTTP/CLI operation instead. Earlier Portal links keep Stripe's own lifetime; changes made directly in the Stripe Dashboard remain an operator boundary.

`GET /workspaces/{workspace}/billing` (scope `read`) says where it stands. Card details and invoice links also need
scope `billing`; without it, `card` and `invoices` are omitted, including from JSON and ZIP exports. Owners and the
full-scope sign-up token keep these details. `plan` is the current-mode subscription's plan; without a subscription
status, it is the sign-up's chosen plan in `starting` or `lapsed`, or null if none was chosen. This choice is not a
subscription or a reserved offer: check `GET /api/v1/plans` for what's still available. The card step preselects the
chosen plan when offered. Without a subscription, prepaid access reports its purchased plan, amount and currency; otherwise `amount` and `currency` stay null.

The response also includes `billing_location`, the remembered payer country and US state for this workspace's
billing account. Correct it through `updateBillingLocation`; changing it requires a new quote for an uncharged
prepaid purchase, not reuse of a quote for the previous location.

The following are selected fields for a workspace still in its card-free start, with both scopes:

```json
{ "state": "starting", "free_until": "2026-11-13T18:02:11.000Z", "can_post": false,
  "stripe_status": null, "plan": "yearly", "amount": null, "currency": null, "card": null }
```

After adding a card, an eligible workspace can be active during its remaining trial. This example's `amount` is
in USD cents. Includes VAT/GST outside the US and Canada; US and Canadian tax is added at checkout where it applies.

```json
{ "state": "active", "stripe_status": "trialing", "plan": "monthly", "amount": 1900, "currency": "usd",
  "trial_ends_at": "2026-11-13T18:02:11.000Z", "renews_at": null, "ends_at": null, "cancel_requested_at": null,
  "posts_after_end": 0, "can_post": true, "comped": false, "livemode": true, "trial_available": false,
  "card": { "brand": "visa", "last4": "4242" }, "message": null, "invoices": [] }
```

`invoices` lists what was charged (`paid`) or is still owed (`open`), newest first, each with `created_at`, `amount`,
`currency`, `status` and `url` (Stripe's page for it). It's empty during a trial, and missing if Stripe couldn't be
reached; the billing portal lists them too. For polling, add `?include_invoices=false` to omit that field and read only
saved billing state, without fetching invoice history from Stripe. The default includes invoices only with `billing`
scope; asking for `include_invoices=true` never adds that scope.

`starting` and its `free_until` follow workspace age before any subscription exists; afterwards, the state follows
Stripe. Each Stripe change reaches the server as a webhook, and the Checkout return reads the finished session
at once. Once an hour the server also lists Stripe's recent events and applies any that never arrived, so a
change made in Stripe shows here within the hour even if its webhook was lost.

## Waiting for Checkout

This wait is for an add-card handoff, **not sign-up**: `starting` intentionally has `can_post: false`, and drafting
does not require waiting for it to turn true. Give the owner the `approval_url` when a plan is ready; it includes the
card step and returns for passkey approval. For an explicit billing start or a lapsed workspace, relay `consent_url`
and `for_person` when consent is required, otherwise `checkout_url`. With staged Managed Payments enabled, the
person first ticks the renewal box on Billing or `/approve`, without a billing passkey, then enters Checkout.
For an approval handoff, say: "Finish the card step in Stripe Checkout, then return to approve the plan with your
passkey. Adding the card doesn't approve or post anything. I can't enter the card or finish payment for you."
`getBilling` returns immediately; when `can_post` is false and a Checkout is recorded as open, it carries
`Retry-After: 60`. Completion or expiry reaches the saved state through the webhook, the Checkout return's
`confirmCheckout`, or reconciliation. This hint is advice, not a rate limit, a server-side hold or proof of payment.

- **CLI installed:** run `flaghand billing wait` once (`--workspace ws_…` selects a workspace). It reads quietly until
  `can_post: true`, then prints the current billing response once (`--json` for JSON). An already active or comped
  workspace answers at once. It honors `Retry-After` (seconds or an HTTP date), falling back to 60 seconds without a
  valid hint. It has no time limit; Ctrl-C stops it, and API errors exit nonzero. It never creates or confirms
  Checkout, charges a card, approves, schedules or posts. If the person abandons Checkout, stop the wait rather than
  promising activation.
- **HTTP or remote-only client:** stop this turn. When the person returns, call `getBilling` once more. If still
  inactive, explain its `message` and leave the card step with them; use the retry hint between turns, not a stream
  of tool calls in the conversation. With `billing` scope and the `checkout_session_id` from `startCheckout`,
  `confirmCheckout` can read the finished session now if the webhook hasn't arrived; it doesn't complete payment.

Only `can_post: true` says the workspace can post. Scheduled posts then go out at their time; posting right now still needs the owner's passkey.

## Operations

Each operation's own page has its fields, an example request and answer, and its errors. The operation id is also the
MCP tool's name; MCP says how to call it (`callReadOperation` or `callWriteOperation`, by id).

| Operation | HTTP | CLI | MCP | Scopes | Does |
| --- | --- | --- | --- | --- | --- |
| [`listPlans`](https://app.flaghand.com/docs/api/listPlans.md) | `GET /plans` | `flaghand sign-up list-plans` | `callReadOperation` | none | The plans on sale, their prices and free-start policy |
| [`startSignup`](https://app.flaghand.com/docs/api/startSignup.md) | `POST /signup` | `flaghand sign-up start-signup` | `callWriteOperation` | none | Start agent access: a new owner creates an account with a configured sign-in method and no card; an existing owner signs in and allows the agent; never reveals whether the email has an account |
| [`claimSignup`](https://app.flaghand.com/docs/api/claimSignup.md) | `POST /signup/claim` | `flaghand sign-up claim-signup` | `callWriteOperation` | none | Collect the agent token; 202 until the person creates their account or allows the agent |
| [`getBilling`](https://app.flaghand.com/docs/api/getBilling.md) | `GET /workspaces/{workspace}/billing` | `flaghand billing get` | `callReadOperation` | `read` | The workspace's plan and whether it can post |
| [`updateBillingLocation`](https://app.flaghand.com/docs/api/updateBillingLocation.md) | `PATCH /workspaces/{workspace}/billing/location` | `flaghand billing update-location` | `callWriteOperation` | `billing` | Change the remembered billing country and US state; never starts a payment |
| [`payPlan`](https://app.flaghand.com/docs/api/payPlan.md) | `POST /billing/pay` | `flaghand billing pay` | `callWriteOperation` | `billing` | Buy one prepaid month or year with delegated MPP or x402; never renews or approves a post |
| [`startCheckout`](https://app.flaghand.com/docs/api/startCheckout.md) | `POST /workspaces/{workspace}/billing/checkout` | `flaghand billing start-checkout` | `callWriteOperation` | `billing` | Open recurring plan or one-time prepaid Checkout; payment never approves or posts |
| [`confirmCheckout`](https://app.flaghand.com/docs/api/confirmCheckout.md) | `POST /workspaces/{workspace}/billing/sync` | `flaghand billing confirm-checkout` | `callWriteOperation` | `billing` | Read a finished Checkout from Stripe now, without waiting for its webhook |
| [`openBillingPortal`](https://app.flaghand.com/docs/api/openBillingPortal.md) | `POST /workspaces/{workspace}/billing/portal` | `flaghand billing open-portal` | `callWriteOperation` | `billing` | A Stripe Customer Portal link: card, invoices, billing details and eligible plan changes |
| [`cancelPlan`](https://app.flaghand.com/docs/api/cancelPlan.md) | `POST /workspaces/{workspace}/billing/cancel` | `flaghand billing cancel-plan` | `callWriteOperation` | `billing` | Cancel renewal, or confirm nothing is due before a plan starts |
| [`resumePlan`](https://app.flaghand.com/docs/api/resumePlan.md) | `POST /workspaces/{workspace}/billing/resume` | `flaghand billing resume-plan` | `callWriteOperation` | `billing` | Keep the plan: undo a cancel before the period ends |
| [`exportWorkspace`](https://app.flaghand.com/docs/api/exportWorkspace.md) | `GET /workspaces/{workspace}/export` | `flaghand workspaces export` | `callReadOperation` | `read` | Everything in the workspace, in any plan state: a zip of Markdown drafts, media and one JSON file, or (format=json) just the JSON |

## Billing reminders

There are no emails nudging a starting workspace to add a card (apart from the one card-step email when it's on).

Every reminder says when the charge falls (in the workspace's time zone), how much Stripe previews for it, the
previous payment and any increase, the plan's price after it and the next payment date, the least the person pays if
they don't cancel, and how to cancel before the charge. They go to every subscriber:

- **Free days ending:** one email up to 3 days before the first charge after a card trial (at once if less time is
  left). A prepaid period's deferred charge and a trial set to cancel get none.
- **Yearly plans** (including the founding offer): one email 30 days before each renewal and another 7 days before.
  Inside the last 7 days only the second is sent. A founding first year renews at the ordinary yearly price, not its
  first-year discount.
- **Monthly plans:** one email 7 days before every sixth payment, counted from the first paid period (after the
  trial, not the day an invoice happened to be paid). The yearly anniversary reminder still exists and is skipped
  when that year's six-month reminder already went out.

Plans set to cancel at the period's end get no reminder. The ordinary maintenance cron sends these through the same
sender as the subscription acknowledgment. It checks Stripe's current subscription before sending and records each
subscription, kind and charge in D1. An unclear send is retried with the same email and provider key; a rejected
request gets fresh billing terms before its retry. A sent record suppresses later cron runs, even after the
provider's idempotency window. Ended, comped and other-mode subscriptions get no reminders. A restart gets its own
anniversaries; old reminders aren't backfilled in a stack after downtime.

## End-of-plan email

When a person cancels a plan (Cancel plan in Billing, the API, the Customer Portal or Link), the owner gets one
email, normally within minutes and always within 24 hours, saying when the plan ends and that nothing more is
charged; a cancel during free days says the card won't be charged. It names Keep plan for changing their mind.
Cancel, Keep plan and cancel again sends one email for the cancellation that stands, and none when the plan then
ends as it said. A failed payment ending a plan, an account deletion, comped workspaces and cancellations more than
two days old get none.

## What the plan allows

| state | Stripe status | Posts | Everything else |
|---|---|---|---|
| `starting` | Eligible, never subscribed in the current mode, not comped, and within the free start if it expires | no | drafts, media, connections, token creation, OAuth Allow, checks, approval requests and reads. No approval, scheduling, posting, best-times refresh or automatic insights reads. `free_until` gives an expiry when one exists; `can_post` is false. |
| `active` | `trialing`, `active`, or comped | yes | yes |
| `paused` | `past_due`: a charge failed and Stripe is retrying | no | drafts, media, checks, approval requests, reading, export. Approving and best-times refresh answer `workspace_inactive`; automatic insights reads stop. |
| `lapsed` | No subscription after the free start, or `canceled`, `unpaid`, `incomplete`, `incomplete_expired` | no | reading, export, billing, revoking tokens, disconnecting accounts, canceling jobs. Every other change, including drafting, answers `workspace_inactive`. |

`workspace_inactive` is HTTP 402. Its message explains the blocker, and `next_step` gives the owner the add-card or
billing link. Send that link, not an instruction to bypass approval or another sign-up. Each route's `x-plan` in the
OpenAPI spec says what it needs: `active`, `not_lapsed` or `any`; `not_lapsed` includes `starting` and `paused`, not
permission to post.

Jobs are never deleted. A job whose time comes while the workspace isn't active ends `failed` with `error_code`
`workspace_inactive`, and nothing is posted. A job still in the future posts on time if the workspace is active by then.
A missed job never posts on its own later: the owner approves it again.

Comped workspaces (the operator marks them: `node tools/operator.mjs comp --workspace ws_…`) are always active and never
billed.

## Unpaid media after the trial

The unpaid-media cleanup job is currently **dry-run**: it deletes nothing and `media_storage.deletes_at` is null.
When enabled after the revised Terms are published, it applies only to a covered workspace that never paid, is not
comped, is currently `lapsed` and has been read-only for at least 30 days. Any paid invoice, confirmed paid period,
prepaid plan or credit purchase excludes it, even after a refund. An unresolved prepaid payment is excluded too.

The deadline is 30 × 24 hours after the later of the free week's end and the actual end of any never-paid card trial
or plan. A canceled/refused card trial counts from when it stopped being writable; a payment-retry `paused` period does
not run down that clock. Ending comped access also starts a full 30-day read-only period. Starting/restarting a plan
before the deadline keeps the media. Eligible live-mode billing
returns the deadline as `media_storage.deletes_at`, also shown in the existing read-only message in the workspace's
time zone. Uncovered older Terms, missing acceptance evidence and dry-run all return null; no add-card email is sent.

Only media goes: uploads, platform copies, slide/PDF renders and image caches. The workspace, account, drafts' text,
posts and history remain readable/exportable. Non-media analytics JSON is retained. A draft keeps its missing media id
and cannot be approved after restarting until the attachment is replaced or removed. Exports identify each deleted
file with `deleted_at` and `file: null`. Paying after deletion restores plan access, **not deleted media**. Backup
retention is unchanged (deleted objects leave the daily copy within 30 days). The existing read-only `/ops/jobs`
operator feed exposes count-only run receipts; mode and acceptance policy are operator-managed.

## When a renewal payment fails

Posting pauses: nothing posts while the plan is past due. The workspace owner gets at most two notices for that
invoice: after failed attempt 1, and after failed attempt 8 if Stripe has scheduled the last retry. The final notice
gives that retry's date (UTC). Both link to Billing to update the card and to Stripe's invoice to pay it. Smart Retries
chooses the retry dates within its month-long window; these are not fixed calendar days. Every other attempt is silent.
If the card needs 3D Secure confirmation, Stripe sends its hosted confirmation email instead, not another notice from
Flaghand. Updating a card sends no extra email.

A card used to pay a failed renewal becomes the subscription's card for future renewals. A new default card saved in
the billing portal also replaces the subscription's old card and retries its open past-due invoice, unless collection
is paused or the plan is already set to end. A delayed portal update never replaces a newer card saved by a later
invoice payment. If the last retry fails, the plan ends and its open invoices are voided: an old payment link cannot charge
for an ended plan. A paid renewal also voids older, still-open renewal invoices of the same subscription.

## Export

`GET /workspaces/{workspace}/export` (scope `read`, any state) returns a zip: one Markdown file per draft in `drafts/`
(front matter with the platform, account, status, time and posted link, then the text; a thread's posts as numbered
sections), the media files in `media/`, the workspace's voice note as `voice.md` (when it has one), and one JSON file
with everything (the voice note, drafts, approvals with their snapshots, jobs and their recorded metrics, media,
connections without their logins, posting slots, feeds, client preview link records (never their secret URLs), the last
sent-back draft versions, the people, the plan, the sign-up and Checkout consent records, X usage counts, best times' X
history and the audit log). Saved automatic link-tag settings (`workspace.link_tracking`) and connection preview
profiles are included too. `?format=json` returns just the JSON; both formats carry the same records.

A **signed-in owner** also gets safe configuration and inventories: `api_tokens` (labels, permissions,
expiry/revocation, usage times and saved app/client attribution), `webhook_endpoints` and `webhook_deliveries` (including
removed endpoints and recorded attempts), `calendar` (status, creation time and creator), and **their own**
`push_subscriptions` (device IDs, labels and creation times) and `passkeys` (IDs, names, device type, backup state,
transports and usage times). Another member's device and passkey details are not part of your export. API-token
values, prefixes and hashes, webhook signing secrets, secret chat destinations, private calendar URLs and hashes,
push addresses/subscriptions and keys, and passkey public keys and counters are never included in these sections.
Derived image caches are not copied into the archive.

Tokens and editors keep the read export, without those owner-only sections—even a token with every scope does not
receive them. Card details, invoice links and credit purchases' Stripe Checkout and payment IDs still require
`billing` scope, and so do the Stripe IDs on plan events in the audit log and on `checkouts` (`target.id` and `id` are `null` without it). A read token may see some token labels in the audit activity; that is not a token inventory.

## Deleting the account

Export first if you want a copy. In Settings, a workspace owner chooses **Delete account** and confirms with a fresh
passkey assertion. If their account has **no passkey**, they instead confirm with an email link or code sent to their
primary address. An ordinary signed-in session or provider sign-in is not deletion confirmation. Tokens cannot delete.

For the passkey API flow, call `POST /workspaces/{workspace}/delete/options`, then
`POST /workspaces/{workspace}/delete` with that challenge's `{challenge_id, response}`. The no-passkey flow uses
`POST /auth/email/request` with `{purpose: "delete", workspace_id}` and the originating owner session; completing the
email proof returns a single-use `proof_token` valid for five minutes. Send `{proof_token}` to the same workspace
`/delete` route to finish. Email verification alone does not delete anything. See
[deletion confirmation](https://app.flaghand.com/docs/sign-in-and-tokens#deleting-an-account) for the session and proof requirements.

Deletion cancels the plan at once (no proration refund). It disconnects the X and LinkedIn logins and deletes the
workspace's drafts, media, approvals, jobs, connections, tokens, audit log, sign-ups and waitlist entry (once its email
is proven; before that, the entry is only unlinked), and its people (with their unfinished sign-ups) unless they belong
to another workspace. The [Privacy Policy](https://flaghand.com/privacy#retention) describes retained billing, consent, card-check
and deletion records and backup retention.
