ソフトウェアのデフォルトは No subscriptions(
access_model = off、default_token_quota = 0 は無制限を意味します)です。新規インストールと既存のセルフホストはここから始まります。管理者が Stripe の設定を選択するまで、請求 UI は表示されません。What you get
- Three access postures: no subscriptions, included + paid, or paid only
- Stripe-hosted Checkout — users upgrade without your code ever touching card data
- Customer Portal — users update payment methods, download invoices, cancel — all on Stripe’s UI
- Webhook-driven lifecycle — subscriptions provision and renew automatically; canceled paid users return to the included tier (or become unentitled in paid-only) at period end
- Quota enforcement — token usage recorded in an append-only ledger and summed per period; mid-stream cutoff with a structured upgrade prompt
- Admin pages for plan CRUD and subscription monitoring
前提条件
- Stripe アカウント(ライブモード有効化済み)。シンガポール法人の場合は KYC(事業 UEN、取締役 ID、銀行口座)の完了が必須です。承認には通常 1~3 日かかります。
- Stripe ライブ API キー(制限付きタイプ推奨。標準の
sk_live_***より取り消しやすく、権限がスコープされています)。 - Webhook エンドポイント(
<your-domain>/api/webhooks/stripeで公開アクセス可能)。 - 銀行口座(支払い用)。USD 以外がデフォルトの Stripe アカウントの場合、マルチ通貨決済(例:USD 口座への USD 支払い)を推奨します。これにより、トランザクションあたり 1.5~2% の為替損失を回避できます。
セットアップ
1. Stripe ダッシュボード
Pro製品を作成する
- Catalog → Products → + Add product
- Name:
Pro、description:5M tokens / month, priority support - Pricing: Recurring、monthly、$20.00 USD(ご自身の価格戦略に合わせて調整してください)
- Save → 結果の
price_***IDをコピーします(アクティベーション後、ローカルのbilling_plansテーブルをこの値で更新します)
制限付きAPIキーを作成する
- Developers → API keys → + Create restricted key
- Name:
fim-one production - Permissions (minimum):
- Customers: Write
- Subscriptions: Write
- Checkout Sessions: Write
- Customer portal: Write
- Prices: Read
- Products: Read
- Save → copy
rk_live_***
Webhookエンドポイントを登録する
- Developers → Webhooks → + Add endpoint
- URL:
https://<your-domain>/api/webhooks/stripe - 受け取るイベント:
checkout.session.completedcustomer.subscription.createdcustomer.subscription.updatedcustomer.subscription.deletedinvoice.payment_succeededinvoice.payment_failed
- 保存後、「Reveal signing secret」をクリック →
whsec_***をコピー
複数通貨決済の設定(推奨)
Stripeアカウントのデフォルト通貨が、請求する価格通貨と異なる場合(一般的な例:SGDアカウントでUSD請求):- Settings → Bank accounts and currencies → Add a settlement currency
- 価格通貨を選択(例:USD)
- 対応する銀行口座を接続(例:Aspire USD仮想口座)
- 保存 — StripeはUSD請求をUSD支払いに直接ルーティングし、為替変換は行いません
2. Backend .env
本番環境の.envで以下の3つのキーを設定します:
.envを編集した後、バックエンドを再起動してキーが読み込まれるようにします:
3. 管理員で有効化
- 管理者としてログイン
- Admin → System Settings → Access and billing
- 1つのポスチャーを選択(インスタンスは常に正確に1つの状態):
- No subscriptions(ソフトウェアデフォルト)— Stripe未使用。トークンアクセスはデフォルト月間クォータ(
0= 無制限)。 - Included + paid — Stripe必須。新規ユーザーはインクルード層にランディング。アップグレード可能。キャンセルされた有料ユーザーは期間終了時にインクルード層に戻る。
- Paid only — Stripe必須。インクルード層なし。ユーザーはモデルを呼び出す前にサブスクライブする必要がある。Included + paidから切り替える場合、既存のインクルード層ユーザーはクォータを保持。
- No subscriptions(ソフトウェアデフォルト)— Stripe未使用。トークンアクセスはデフォルト月間クォータ(
- バックエンドは、Stripeポスチャーを選択する際に
STRIPE_SECRET_KEYとSTRIPE_WEBHOOK_SECRETの両方が存在することを検証します — どちらかが欠落している場合は400を返す - Stripeポスチャーの初回有効化時、バックエンドはべき等セットアップを実行:
- Included + paid: インクルードプラン(
slug=free)+ 空のPrice IDを持つProテンプレートをシード。default_plan_idを設定。プランのないユーザーをバックフィル - Paid only: Proテンプレートのみをシード。バックフィルなし
- そのプランがシードされるときに
default_token_quotaをインクルードプランにコピー(0は0のまま、無制限)
- Included + paid: インクルードプラン(
- No subscriptionsに戻すことは純粋なフラグ反転で、データ副作用なし。Included + paidがアクティブな間、インクルードデフォルトプランは削除できない。
4. Pro プランをライブ価格で更新する
アクティベーション後、シードされた Pro プランをライブ Stripe 価格にポイントするように更新します:- Admin → Billing → Plans → Pro → Edit
- ステップ 1 から取得した
price_1***をStripe Price IDに貼り付けます - 保存します
5. スモークテスト
- 通常ユーザーとして
/settings?tab=billingを開く - Switch to Pro をクリック
- Stripe Checkout が開く。少額の実カードで完了する(その後払い戻す)
- Webhook が発火する — Stripe Dashboard → Webhooks → 最近のイベントで 2xx レスポンスが表示されることを確認
subscriptionsテーブルにサブスクリプション行が表示される。users.plan_idがproに切り替わる- UI に Pro プランと「Manage subscription」ボタンが表示される
請求の無効化
Admin → System Settings → Billing で Enable Stripe Billing スイッチを OFF に切り替えます。 無効化すると:- すべての
/api/billing/*エンドポイントが 503 を返す - webhook エンドポイントが 503 を返す(Stripe は再試行し、Dashboard に失敗として表示されます — これは問題ありません。請求が永続的に無効な場合は、Stripe Dashboard で webhook を無効にすることもできます)
Plan & Billingユーザー向けタブが消える- Admin → Billing ナビゲーショングループが非表示になる
- クォータチェーンがプランティアをスキップし、
default_token_quotaに直接フォールバックする
subscriptions、billing_plans、users.plan_id 行は変更されません。再度有効化すると、マイグレーションなしで同じ状態から再開されます。
計算リファレンス — クォータ & トークン計算
これは、ユーザーが消費できる内容、カウンターがリセットされるタイミング、および解決チェーンがどのように構成されるかを決定するすべての数値ルールの信頼できるリファレンスです。価格設定の変更、クォータの調整、使用状況ダッシュボードの構築、またはv2/v3作業の計画を行う前に、これをお読みください。まだ出荷されていない将来のルールは、予約されたスロットに記載されているため、貢献者は新しいロジックがどこに組み込まれるかを知ることができます。Glossary
What counts as a token
Token consumption is metered in the model client, from the provider’susage object on every call, and written to the usage ledger (usage_ledger): an append-only table with one row per turn, run or request and model. A user’s “used” is the sum of their ledger rows since their window began. The quota check, the Usage card in Settings, Admin → Users and the user export all read that sum. The token figures of the platform statistics (Admin → Overview, Analytics, the metrics API) and of each user’s dashboard are read from the same ledger, by the time the usage was recorded; the evaluation center’s tokens consumed is the one figure still summed from the evaluation runs.
- Counted: prompt tokens + completion tokens of every model call made on the user’s account (the provider’s own
total_tokenswhen it reports one) - Counted: every model call of a chat turn, not only the answer: the agent’s tool rounds, routing in Auto mode, domain classification, step titles, context compaction, follow-up suggestions, the conversation title, and the calls of an agent the turn delegated to with
call_agent - Counted: a turn that was stopped or abandoned and a turn that failed, for what they consumed up to that point. When the provider sends no usage for a call (a stream cut short, or a provider that reports none), the call is estimated and its row is marked
estimated. The estimate counts the messages sent, the tool calls in their history, the tool definitions sent with the call, a fixed 1,100 tokens per image, and the text, reasoning and tool-call arguments that had come back, and is rounded up. Against OpenAI’so200k_basetokenizer it comes within about 10% on a tool-heavy agent call, and between 0.8 and 1.5 times the real count on English, Chinese, Japanese, Korean, Russian, Greek, Arabic, Hebrew, Thai and Hindi text, code, JSON, emoji, base64, hex, random identifiers and whitespace - Counted: a chat request sent without a
conversation_id - Counted: workflow runs, against whoever ran them; a run started by a trigger key or a schedule counts against the workflow’s author. Single-step tests count too
- Counted: the model-backed helper endpoints (AI-assisted agent and connector create and refine, connector action generation, database chat and schema annotation, knowledge-base chat), evaluation runs (the agent and the grader), and the vision model reading images and scanned pages while a document is added to a knowledge base
- Over quota or without a plan: adding a document to a knowledge base is not refused, but the document is read without the vision model (text only: no reading of images or scanned pages), the server logs it, and the document shows a warning with the reason; retrying the document once the quota allows reads it with the vision model
- Not counted: embedding, reranking and image generation requests
- Counted: a model call that had been sent but had returned nothing yet when its turn was stopped or abandoned (a call still waiting for its response, a stream before its first chunk, or a tool-call round whose arguments the model was still writing). The provider bills what it was sent, so the prompt is recorded, estimated, plus any tool-call arguments already received; the row is marked
estimated. The client cannot tell whether the request had reached the provider: a turn stopped while the call is still connecting is counted the same way, though the provider received nothing. During a provider outage, a user who presses Stop is therefore charged the prompt, and one who waits for the error is not - Not counted: requests that fail before reaching the provider (auth error, rate-limit pre-check, a call still waiting for the local rate limiter), and a call the provider refused or that broke on an error before its first chunk
- Cached input: counted at full price (no provider cache discount is applied). The ledger records cache-read and cache-creation tokens per row for later use.
source_type (conversation, workflow_run, eval_run or endpoint) with the id, entry (chat, dag, auto, background, a run mode such as trigger or schedule, ai_assist.*, kb_chat, db_chat, kb_ingest, eval), the model, and the organization of the agent, workflow, connector or knowledge base it ran through. conversations.total_tokens and workflow_runs.total_tokens are still kept as “what this conversation / this run reported” and can be lower than the ledger, which also holds interrupted turns, delegated agents and the streamed answer.
Rows are written when a turn, run or request ends, however it ends; a long one is also written as it goes, at most every 30 seconds. If the server process is killed, what its in-flight turns consumed in the last 30 seconds at most is not recorded. A write that fails is retried once and then logged at ERROR with the user and the numbers (Usage not recorded), and the turn is not failed for it.
Upgrading to the release that adds the ledger. The migration carries every conversation’s and run’s total_tokens into the ledger, so each user’s “used” is the same before and after. It then compares the result per user with the source tables once. If an instance of the previous release is still serving and changed a total while the migration ran, each user that differs is carried over again and compared in a single transaction (one snapshot on PostgreSQL), so a writer that keeps running does not stop the migration from finishing. The migration fails only if a user’s carry-over does not match the sources it read, which points to a fault, not to a running writer; it resumes where it was when run again. What an old instance writes after that has no ledger row: for a user who was carried over again, what was committed after their carry-over began; for everyone else, what was committed after the comparison, and everything written once the migration has finished. Once the last old instance has stopped, run the top-up command described in the next paragraph.
After rolling back and upgrading again. A release older than the ledger keeps adding to conversations.total_tokens and workflow_runs.total_tokens without writing ledger rows. If you roll back to one and later upgrade again, run python -m fim_one.core.usage.topup (with the application’s DATABASE_URL) to see what the ledger is missing, and again with --apply to record it: one adjustment row per conversation or run whose ledger rows add up to less than its total. It only adds rows, and a second run finds nothing left. The added usage counts in the window in which the command is run. Run it with the application stopped: against a live one it can count a turn twice whose conversation total was saved a moment before its ledger rows. It compares sums per conversation or run, so where the ledger already holds usage the total never reported (an interrupted turn, a delegated agent), that much of a gap is not recovered: a conversation reporting 180 whose rows add up to 170, 20 of them a delegated agent’s, is missing 30 and gets 10.
Three-state override semantics
users.token_quota はユーザーごとの管理者オーバーライドです。1つのカラムに3つの意味を持ちます:
オーバーライドは常にプランとデフォルトより優先されます。管理者が Stripe に触れることなく、個別ユーザーをプラン階層の上下に固定できるよう存在します。
クォータ解決チェーン — v1(現在)
認証されたリクエストの場合、上限は上から下へ計算されます——最初にマッチしたものが優先されます:default_token_quotaが0であっても権限がなく(チャットは402を返します)。
Period reset
- “Used” is not a counter that is reset: it is the sum of the user’s ledger rows from the start of their current window. A new window starts with nothing in it.
- For paid users the window is the subscription period: it starts on the monthly anniversary of the subscription and ends at
Subscription.current_period_end(mirrored onusers.quota_reset_at), which theinvoice.payment_succeededwebhook advances on each renewal. - For users without a Stripe subscription the window is the calendar month (UTC).
- Plan changes mid-period do not start a new window, only renewals do. This prevents quota-cycling exploits (“subscribe → use Pro quota → cancel → subscribe again”).
Mid-stream enforcement
- Pre-flight check at chat-call entry: cheapest path, blocks requests the user can’t afford to start.
- While an answer streams, the turn compares what the user had used when it started, plus what the turn itself has consumed so far (the calls that have finished, and an estimate of the answer being written), with the cap, about every 200 characters. No database query is made for this. Crossing the cap closes the stream with a structured terminator frame, not a network error. Usage from the same user’s other tabs during the turn is seen by the next turn’s pre-flight check.
- The frontend interprets the terminator and surfaces
<QuotaExceededDialog>with a deep link to/settings?tab=billing. - An evaluation run and a workflow batch are admitted once, and checked again the same way before each case or item starts: what the user had used when the run or batch started plus what it has consumed since (for an evaluation, its own meter; for a batch, the totals of the items that have finished). Once the cap is reached no further case or item starts; those under way finish. The evaluation run ends
failedwithtoken_quota_exceededand the number of cases not run in its error; each batch item not started isfailedwithtoken_quota_exceeded. A single workflow run is checked only when it starts (and when it continues after waiting for a decision). - A request made when the quota is already used up is refused before any stream starts: HTTP
429witherror_codetoken_quota_exceeded. Under Paid only, a user with no plan gets HTTP402witherror_codesubscription_required. - The same pre-flight check guards the other endpoints that call a model: AI-assisted agent and connector create and refine, connector action generation, database chat and schema annotation, knowledge-base chat, starting an eval run, and every way of starting a workflow. What they consume counts against the quota like a chat turn does.
請求機能無効時のフォールバック
system_settings.billing_enabled = FALSE の場合:
- チェーンのステップ 2 がスキップされます — チェーンは
override → default → unlimitedに縮小されます。 /api/billing/*と/api/webhooks/stripeは503を返します。Plan & Billingユーザータブと Admin → Billing ナビゲーショングループは非表示になります。- すべての請求データ(サブスクリプション、プラン、
users.plan_id)は保持されます — 再度有効にすると、マイグレーションなしで同じ状態から再開されます。
予約済み: クォータチェーン v2 — Team シート
まだリリースされていません。v2 作業の既知のランディングスポットとしてここに記載されています。
Subscription.quantityはシート数を保持します(Stripe ネイティブ)。- ユーザーの有効なプランは、個人プランにフォールバックする前に Team メンバーシップを通じて解決されます:
- クォータはシートごとです(各 Team メンバーは完全な
monthly_token_quotaを取得します)。プール化されたバケットではありません。プール化されたバケットは先着順の枯渇を引き起こし、顧客にとって悪いものです。 - オーバーライドセマンティクスは変わりません — Team 管理者は
users.token_quota = Nを使用して個別メンバーをハードキャップできます。これはチームプランチェーンの上に位置します。
予約済み: クォータチェーン v3 — ネイティブ Org アロケーション (Stripe なし)
まだリリースされていません。Stripe を通じてユーザーごとに支払うことなく、内部的にクォータを割り当てるオンプレミス / エンタープライズデプロイメント向けに予約されています。
- 新しいテーブル
org_quota_allocations(user_id, monthly_token_quota, org_id)は親予算をメンバー全体に配分します。 - アロケーションは共有プール ではなく、ユーザーごと — すべてのメンバーが明確な個別 SLA を持ちます。
- 更新されたチェーン:
max()、sum()ではありません。有料 Pro ユーザーは、Org 管理者が低いアロケーションを設定した場合でも、支払った額より少なくなることはありません。Stripe で支払われたクォータは神聖です。
予約済み:従量課金クレジット残高(v3 別次元)
未出荷。上記のチェーンとは別の軸——クレジットは1回限りのトップアップであり、サブスクリプション階層ではありません。
- 新しいテーブル
user_credits(user_id, balance_cents, currency)— Stripe Checkoutmode='payment'経由で資金提供。 - 消費順序:サブスクリプション割当量優先、その後クレジット残高(サブスクリプションが枯渇した後のみクレジット減少が開始)。
- クレジット残高は払い戻し不可(プリペイドの業界標準)。
- UI は両方のバーを公開:
Subscription quota: 4.2M / 5M used+Credits: $7.40 remaining。
デフォルト値
出荷時のデフォルト — すべてインストール後に調整可能(記載がある場合を除く)。料金モデル
V1はフラットサブスクリプションです。Free + Pro、月次請求、USD のみ。 V1 の対象外 (意図的に、ロードマップに延期):- Team プラン (Stripe seats /
subscription.quantity) - 年間請求
- 複数通貨の表示
- クーポン / プロモコード
- 税務処理 (Stripe Tax 統合 — 別途コンプライアンスレビューが必要)
- 使用量ベースのメータリング / 超過料金
- 従量課金クレジット残高 (ワンタイムトップアップ)
トラブルシューティング
トグルが有効化されない — 400 エラー
トグルが有効化されない — 400 エラー
有効化エンドポイントには
STRIPE_SECRET_KEY と STRIPE_WEBHOOK_SECRET の両方が設定されている必要があります。.env に存在することを確認し、編集後にバックエンドが再起動されていることを確認してください。Webhook が 503 を返す
Webhook が 503 を返す
課金が無効化されているか(トグルが OFF)、またはリクエスト署名の検証に失敗しています(
STRIPE_WEBHOOK_SECRET が一致していない)。Stripe ダッシュボード → Webhooks → 最近のイベントで実際のエラー本文を確認してください。ユーザーがサブスクライブしたが、まだ Free プランが表示される
ユーザーがサブスクライブしたが、まだ Free プランが表示される
checkout.session.completed webhook がバックエンドに到達しませんでした。Stripe ダッシュボードのエンドポイント URL が <your-domain>/api/webhooks/stripe と完全に一致していることを確認してください(末尾のパスを含む)。Webhook の最近の配信でエラーを確認してください。Pro ユーザーがテストモードの価格 ID を見ている
Pro ユーザーがテストモードの価格 ID を見ている
シード マイグレーションはテストモードの価格 ID を書き込みます。本番課金を有効化した後、Admin → Billing → Plans → Pro → Edit で Pro プランを更新して、本番環境の
price_1*** を使用するか、直接 SQL UPDATE で更新してください。領収書が Stripe のデフォルト ブランディングで表示される
領収書が Stripe のデフォルト ブランディングで表示される
Stripe ダッシュボード → Settings → Branding でビジネス ブランディングを設定してください。ロゴ、ビジネス名(例:「FIM Labs Pte. Ltd.」)、住所を追加してください。Stripe はこれらを自動生成されたすべての領収書と請求書に適用します。
支払い時の為替損失
支払い時の為替損失
Stripe アカウントのデフォルト通貨が請求通貨と異なる場合、Stripe は支払いのたびに変換します(1.5~2% のスプレッド)。Settings → Bank accounts and currencies で一致する決済通貨を追加し、同じ通貨の銀行口座を接続すると、Stripe は変換なしで同じ通貨の支払いをルーティングします。