pave_ai 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. checksums.yaml +7 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.md +195 -0
  4. data/app/assets/stylesheets/pave_ai/application.css +15 -0
  5. data/app/controllers/pave_ai/application_controller.rb +4 -0
  6. data/app/helpers/pave_ai/application_helper.rb +4 -0
  7. data/app/jobs/pave_ai/application_job.rb +4 -0
  8. data/app/mailers/pave_ai/application_mailer.rb +6 -0
  9. data/app/models/pave_ai/application_record.rb +5 -0
  10. data/app/models/pave_ai/chat.rb +49 -0
  11. data/app/models/pave_ai/chat_message.rb +28 -0
  12. data/app/models/pave_ai/intent.rb +34 -0
  13. data/app/models/pave_ai/persona.rb +34 -0
  14. data/app/models/pave_ai/persona_document.rb +35 -0
  15. data/app/models/pave_ai/quota.rb +77 -0
  16. data/app/models/pave_ai/spend_log.rb +47 -0
  17. data/app/services/pave_ai/client/provider.rb +50 -0
  18. data/app/services/pave_ai/client/providers/anthropic.rb +15 -0
  19. data/app/services/pave_ai/client/providers/gemini.rb +15 -0
  20. data/app/services/pave_ai/client/providers/ollama.rb +16 -0
  21. data/app/services/pave_ai/client/providers/openai.rb +14 -0
  22. data/app/services/pave_ai/client/providers/openai_compatible.rb +18 -0
  23. data/app/services/pave_ai/client/providers/xai.rb +14 -0
  24. data/app/services/pave_ai/client/providers/zai.rb +13 -0
  25. data/app/services/pave_ai/client/providers/zen.rb +12 -0
  26. data/app/services/pave_ai/client.rb +683 -0
  27. data/app/services/pave_ai/credential.rb +66 -0
  28. data/app/services/pave_ai/governance.rb +70 -0
  29. data/app/services/pave_ai/rates.rb +101 -0
  30. data/app/services/pave_ai/spend.rb +539 -0
  31. data/app/views/layouts/pave_ai/application.html.erb +17 -0
  32. data/config/ai_governance/ETHICS.md +20 -0
  33. data/config/routes.rb +2 -0
  34. data/db/migrate/20260404000001_create_pave_ai_tables.rb +102 -0
  35. data/db/migrate/20260820000002_add_billable_to_pave_ai_spend_logs.rb +5 -0
  36. data/db/migrate/20260827000001_add_model_to_pave_ai_spend_logs.rb +8 -0
  37. data/db/migrate/20260828000001_add_intent_credit_cost_and_log_credits.rb +10 -0
  38. data/db/migrate/20261123000001_remove_quota_limit_defaults.rb +9 -0
  39. data/lib/generators/pave_ai/install/install_generator.rb +61 -0
  40. data/lib/pave_ai/engine.rb +23 -0
  41. data/lib/pave_ai/middleware/request_cleanup.rb +17 -0
  42. data/lib/pave_ai/version.rb +3 -0
  43. data/lib/pave_ai.rb +247 -0
  44. data/lib/tasks/pave_ai_tasks.rake +4 -0
  45. metadata +127 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5c2107b1e8939b947c3f98c4412990cffeff77d57b72a10557d24842c5d55a7a
4
+ data.tar.gz: c69716e71a128d63d35f74326e26d8ab25b9513db5839659c97dc67547162fea
5
+ SHA512:
6
+ metadata.gz: 558c6aa153b9db0e4752c18ca2f1d242de042b4f9e13e18b4295a8731ca44c128b356f5c942978755ee83450cac5abc3b3c3dc3f925c0c4663ffb6f6b0afc931
7
+ data.tar.gz: d85ed30ad860fa134daac259f17c1d9c31eb6ad09f923a9794fd653c292939dc3da3553654953c40ec058b0e06dcb8e12b2b5f0841e4d9999eee1f3e18bc1503
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright Nauman Tariq
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,195 @@
1
+ # PaveAi
2
+
3
+ A mountable Rails engine for **AI inference you resell**. It gives a host app one client for
4
+ several providers and — the part that matters — a meter underneath it: quotas, spend logs, model
5
+ rates as data, and a credit deduction the host prices itself.
6
+
7
+ **Buy the pipes, own the till.** Transport, streaming and provider quirks are
8
+ [RubyLLM](https://rubyllm.com)'s job, because the provider layer is the part that drifts. The
9
+ ledger is ours, because it is the part the business depends on and no library models it the way a
10
+ specific price list does.
11
+
12
+ ## Installation
13
+
14
+ The current engine requires RubyLLM 2.1 (`~> 2.1`). Hosts upgrading from an older
15
+ engine ref should update the engine and RubyLLM together and remove any host-side
16
+ RubyLLM 1.x compatibility pin. PaveAI uses RubyLLM's transport API with its own
17
+ ordinary Active Record models; it does not use RubyLLM's persisted-chat macros,
18
+ so this transport upgrade introduces no RubyLLM data migration.
19
+
20
+ Add the engine to your Gemfile.
21
+
22
+ ```ruby
23
+ gem "pave_ai"
24
+ ```
25
+
26
+ Migrations **auto-append** to the host — do not run `pave_ai:install:migrations` (that mints
27
+ duplicates). Just migrate:
28
+
29
+ ```bash
30
+ bin/rails db:migrate
31
+ ```
32
+
33
+ That creates `pave_ai_quotas`, `pave_ai_spend_logs`, and the chat/persona/intent tables.
34
+
35
+ ## Configure
36
+
37
+ Pass provider keys from your host application. This example reads them from environment variables.
38
+
39
+ ```ruby
40
+ # config/initializers/pave_ai.rb
41
+ PaveAi.configure do |config|
42
+ config.default_provider = "xai" # xai · zen · zai · ollama · openai
43
+ # anthropic and gemini need an explicit model on every Client.new: no default is pinned yet.
44
+ config.xai_api_key = ENV["XAI_API_KEY"]
45
+ config.zen_api_key = ENV["ZEN_API_KEY"]
46
+ config.user_class = "User"
47
+
48
+ # Cheap/flat-rate providers the global budget gate never blocks, and where to
49
+ # downgrade when the paid budget runs out (instead of failing the request).
50
+ config.budget_exempt_providers = %w[ollama zen]
51
+ config.budget_fallback = { provider: "zen", model: "kimi-k2.5" }
52
+
53
+ # Rates as DATA — pinned explicit IDs, never floating aliases.
54
+ config.model_rates = {
55
+ "grok-4-1-fast-non-reasoning" => { input: 0.20, output: 0.50, verified_on: Date.new(2026, 8, 22) }
56
+ }
57
+
58
+ # Your plans and prices. The engine ships none: metering raises
59
+ # ConfigurationError, naming the missing setting, until they are set.
60
+ config.quota_tiers = {
61
+ user: { generations: 100, exports: 10, credits: 50 },
62
+ free: { generations: 10, exports: 1, credits: 5 },
63
+ admin: { generations: 1_000, exports: 100, credits: 1_000 }
64
+ }
65
+ config.quota_tier_proc = ->(user) { user.plan.to_sym } # optional; default reads admin/free flags
66
+ config.monthly_budget_cents = 5_000 # platform spend cap on paid providers
67
+ config.credits_for_cost_proc = ->(cost_cents) { (cost_cents / 10.0).ceil } # intents without a credit_cost
68
+ config.denial_messages = { # optional; neutral defaults otherwise
69
+ credits_exhausted: "You're out of AI credits for this month.",
70
+ budget_reached: "AI is busy right now. Please try again shortly."
71
+ }
72
+ end
73
+ ```
74
+
75
+ The numbers above are placeholders, not recommendations.
76
+
77
+ Only the providers whose keys you set are usable; the others raise `ConfigurationError` when
78
+ selected, not at boot.
79
+
80
+ ## The two things you call
81
+
82
+ **Generate text** — metered automatically, including the credit deduction:
83
+
84
+ ```ruby
85
+ reply = PaveAi::Client.new.generate("Summarise this page", user: current_user)
86
+ ```
87
+
88
+ **Meter something else** — wrap any billable operation:
89
+
90
+ ```ruby
91
+ PaveAi::Spend.request(
92
+ intent: "summarise_document", spend_type: :text, provider: "xai",
93
+ user: current_user, billable: current_team, estimated_tokens: 800
94
+ ) do |budget|
95
+ result = do_the_work
96
+ budget.record!(actual_tokens: result.tokens)
97
+ end
98
+ ```
99
+
100
+ `user` is who clicked; `billable` is who pays (a workspace, an org, a team) — they are not the same
101
+ question, and per-team volume pricing needs the second one.
102
+
103
+ **Funds are reserved before your block runs and settled after it.** If the operation is not
104
+ affordable the block never runs at all: `PaveAi::Spend::BudgetExceeded` is raised and a denied
105
+ `SpendLog` row is still written, so refusals are as auditable as charges. If it is affordable,
106
+ the estimated credits are held under a row lock — a concurrent request cannot spend them — and
107
+ reconciled against the real cost when you call `record!`. Passing `input_tokens:`/`output_tokens:`
108
+ (and `cached_tokens:`) reprices from the model's real rates and refunds the difference.
109
+
110
+ However the block ends, the operation ends in exactly one recorded state:
111
+
112
+ - **returns** — settled; a forgotten `record!` settles at the estimate rather than giving it away
113
+ (so does leaving the block with `break`);
114
+ - **raises before `record!`** — the hold is released and a failed row written;
115
+ - **raises after `record!`** — the charge is refunded and a reversal row written beside it, so
116
+ the pair nets to what the customer actually paid. Rows are never rewritten.
117
+
118
+ Usage reported as all zeros settles at the estimate (flagged `usage_missing`), never at zero.
119
+ Every movement of funds runs in its own savepoint, so this holds inside your own transaction.
120
+ `credits_charged` is what was actually deducted; `credits_priced` and `credits_by_source` say
121
+ when that differs from the price or came from more than one place. A hold remembers its quota
122
+ month and its price, so a refund after midnight on the 1st, or an intent edited mid-flight,
123
+ cannot change a purchase already made.
124
+
125
+ `client.chat_with_usage` is for calls you meter yourself; called outside any meter it meters
126
+ itself, so no call goes unmetered.
127
+
128
+ **Let a person use their own key** — recorded, never charged:
129
+
130
+ ```ruby
131
+ credential = PaveAi::Credential.new(api_key: their_key) # the host stores, authorizes and revokes it
132
+ client = PaveAi::Client.new(provider: "anthropic", model: "<pinned id>", credential: credential)
133
+
134
+ client.meter(intent: "summarise_document", user: current_user, billable: current_team, estimated_tokens: 800) do |budget|
135
+ response = client.chat_with_usage(messages, max_tokens: 800, intent: "summarise_document", user: current_user)
136
+ budget.record!(input_tokens: response[:input_tokens], output_tokens: response[:output_tokens])
137
+ end
138
+ ```
139
+
140
+ Only the caller's key is sent, the call is never rerouted onto a provider you pay for, no credits
141
+ are held or charged, and the `SpendLog` row is still written (`funding_source: "caller_key"`).
142
+ `client.meter` takes provider, model and funding from the client, so the till cannot disagree
143
+ with the key the call used. Providers: `openai`, `xai`, `anthropic`, `gemini`, `zai`, `zen`, and
144
+ `openai_compatible` for any OpenAI-compatible endpoint (pass `api_base:` on the credential; it
145
+ must be a plain `https` URL, and **your app** must refuse private and internal addresses before
146
+ building it). Pass `nil` or a `PaveAi::Credential`, never `false` or a string: anything else raises.
147
+
148
+ ## What an operation costs
149
+
150
+ Two separate questions, and conflating them is how a meter starts lying:
151
+
152
+ - **Cost** — what *we* paid, in cents. From `PaveAi::Rates` for the model actually invoked.
153
+ - **Price** — what the *customer* pays, in credits. From the **intent**: `PaveAi::Intent#credit_cost`
154
+ (a price is a property of the feature, never of the provider). When the intent carries no
155
+ price, `config.credits_for_cost_proc` decides. Both are the host's: the engine has no price list.
156
+ Each log row records which applied (`price_source`); set `config.require_priced_intents = true`
157
+ to refuse any intent without its own price, so a typo'd intent name fails instead of
158
+ quietly falling back.
159
+
160
+ ## What the host must provide
161
+
162
+ `user_class` is duck-typed — implement only what you need:
163
+
164
+ | Method | Effect when present |
165
+ |---|---|
166
+ | `ai_veto?` | true ⇒ this user is never charged or blocked (staff/admin) |
167
+ | `pave_ai_admin?` / `pave_ai_free?` | selects the `:admin` / `:free` tier of `config.quota_tiers` (unless you set `quota_tier_proc`) |
168
+ | `tool_credits_balance` | purchased-credit wallet consulted after the monthly quota |
169
+ | `sufficient_tool_credits?(n)` / `spend_tool_credits!(n, source:, description:)` | lets overflow spend hit that wallet |
170
+ | `refund_tool_credits!(n, source:)` | lets an over-estimate reserved from the wallet be returned. Without it the engine records `refund_owed_credits` in the log's metadata rather than quietly keeping the difference. |
171
+
172
+ ## Reading the meter
173
+
174
+ ```ruby
175
+ PaveAi::Quota.current_for(user).credit_summary # "12/30"
176
+ PaveAi::SpendLog.for_billable(team).total_cents # what this team cost us
177
+ PaveAi::Rates.for(model: "grok-4-1-fast-non-reasoning") # => Rate(input:, output:, verified_on:, source:)
178
+ PaveAi::Rates.stale # pinned rates past rates_max_age_days
179
+ ```
180
+
181
+ `Rates.stale` is not decoration. A stale rate table mis-charges every customer quietly, in
182
+ whichever direction the vendor moved — surface it somewhere a human sees.
183
+
184
+ ## Development
185
+
186
+ ```bash
187
+ bin/rails test # 198 runs, 0 failures
188
+ ```
189
+
190
+ Tests run against a dummy app in `test/dummy`. If bundler cannot write to the system gem dir,
191
+ use `BUNDLE_PATH=vendor/bundle`.
192
+
193
+ ## License
194
+
195
+ MIT.
@@ -0,0 +1,15 @@
1
+ /*
2
+ * This is a manifest file that'll be compiled into application.css, which will include all the files
3
+ * listed below.
4
+ *
5
+ * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
6
+ * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
7
+ *
8
+ * You're free to add application-wide styles to this file and they'll appear at the bottom of the
9
+ * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
10
+ * files in this directory. Styles in this file should be added after the last require_* statement.
11
+ * It is generally better to create a new file per style scope.
12
+ *
13
+ *= require_tree .
14
+ *= require_self
15
+ */
@@ -0,0 +1,4 @@
1
+ module PaveAi
2
+ class ApplicationController < ActionController::Base
3
+ end
4
+ end
@@ -0,0 +1,4 @@
1
+ module PaveAi
2
+ module ApplicationHelper
3
+ end
4
+ end
@@ -0,0 +1,4 @@
1
+ module PaveAi
2
+ class ApplicationJob < ActiveJob::Base
3
+ end
4
+ end
@@ -0,0 +1,6 @@
1
+ module PaveAi
2
+ class ApplicationMailer < ActionMailer::Base
3
+ default from: "from@example.com"
4
+ layout "mailer"
5
+ end
6
+ end
@@ -0,0 +1,5 @@
1
+ module PaveAi
2
+ class ApplicationRecord < ActiveRecord::Base
3
+ self.abstract_class = true
4
+ end
5
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaveAi
4
+ class Chat < ApplicationRecord
5
+ STATUSES = %w[active archived].freeze
6
+
7
+ belongs_to :user, polymorphic: true
8
+ belongs_to :intent, class_name: "PaveAi::Intent"
9
+ has_many :messages, class_name: "PaveAi::ChatMessage", foreign_key: :pave_ai_chat_id, dependent: :destroy
10
+
11
+ validates :status, inclusion: { in: STATUSES }
12
+
13
+ scope :active, -> { where(status: "active") }
14
+ scope :archived, -> { where(status: "archived") }
15
+ scope :recent, -> { order(updated_at: :desc) }
16
+ scope :for_intent, ->(intent) { where(intent: intent) }
17
+
18
+ def chat_history(limit: 20)
19
+ messages.conversation.last(limit).map { |msg| { role: msg.role, content: msg.content } }
20
+ end
21
+
22
+ def auto_title!
23
+ first_message = messages.where(role: "user").order(:created_at).first
24
+ return unless first_message
25
+ update!(title: first_message.content.truncate(60))
26
+ end
27
+
28
+ def provider_override
29
+ metadata&.dig("provider").presence
30
+ end
31
+
32
+ def model_override
33
+ metadata&.dig("model").presence
34
+ end
35
+
36
+ def pipeline
37
+ value = metadata&.dig("pipeline").to_s
38
+ value.present? ? value : "general"
39
+ end
40
+
41
+ def prompt_template
42
+ metadata&.dig("prompt_template").to_s.strip.presence
43
+ end
44
+
45
+ def tags
46
+ Array(metadata&.dig("tags")).map { |tag| tag.to_s.strip.downcase }.reject(&:blank?).uniq
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaveAi
4
+ class ChatMessage < ApplicationRecord
5
+ ROLES = %w[user assistant system].freeze
6
+
7
+ belongs_to :chat, class_name: "PaveAi::Chat", foreign_key: :pave_ai_chat_id, touch: true
8
+
9
+ validates :role, presence: true, inclusion: { in: ROLES }
10
+ validates :content, presence: true
11
+
12
+ scope :chronological, -> { order(created_at: :asc) }
13
+ scope :conversation, -> { where(role: %w[user assistant]).chronological }
14
+
15
+ after_create_commit :auto_title_chat, if: :first_user_message?
16
+
17
+ private
18
+
19
+ def first_user_message?
20
+ role == "user" && chat.messages.where(role: "user").count == 1
21
+ end
22
+
23
+ def auto_title_chat
24
+ return if chat.title.present? && chat.title != "New chat"
25
+ chat.update!(title: content.truncate(60))
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaveAi
4
+ class Intent < ApplicationRecord
5
+ CONTENT_TYPES = %w[general custom].freeze
6
+
7
+ belongs_to :user, polymorphic: true, optional: true
8
+ belongs_to :persona, class_name: "PaveAi::Persona", optional: true
9
+ has_many :chats, class_name: "PaveAi::Chat", foreign_key: :intent_id
10
+
11
+ validates :name, presence: true, uniqueness: true
12
+ validates :display_name, presence: true
13
+ validates :credit_cost, numericality: { greater_than_or_equal_to: 0, only_integer: true }
14
+
15
+ # The price of this feature in credits, or nil when the intent is not a
16
+ # registered one (callers then fall back to the host's cost-based policy).
17
+ # A cheap read: intents are few and change rarely.
18
+ def self.credit_cost_for(name)
19
+ return nil if name.blank?
20
+
21
+ find_by(name: name.to_s)&.credit_cost
22
+ end
23
+
24
+ scope :active, -> { where(active: true) }
25
+ scope :presets, -> { where(preset: true) }
26
+ scope :user_accessible, -> { where(user_accessible: true, active: true) }
27
+ scope :ordered, -> { order(position: :asc, display_name: :asc) }
28
+
29
+ def topic_keywords_list
30
+ return [] if topic_keywords.blank?
31
+ topic_keywords.split(",").map(&:strip).reject(&:blank?)
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaveAi
4
+ class Persona < ApplicationRecord
5
+ belongs_to :user, polymorphic: true, optional: true
6
+
7
+ validates :content, presence: true
8
+ validates :user_id, uniqueness: { scope: :user_type }, allow_nil: true
9
+
10
+ def self.for_user(user)
11
+ return default_persona if user.nil?
12
+ find_by(user: user) || default_persona
13
+ end
14
+
15
+ def voice = extract_section("Voice")
16
+ def playbook = extract_section("Playbook")
17
+ def focus = extract_section("Focus")
18
+
19
+ private
20
+
21
+ def self.default_persona
22
+ path = PaveAi::Engine.root.join("config", "ai_persona", "PERSONA.md")
23
+ content = File.exist?(path) ? File.read(path) : ""
24
+ new(content: content)
25
+ end
26
+
27
+ def extract_section(heading)
28
+ return nil if content.blank?
29
+ pattern = /^##\s+#{Regexp.escape(heading)}\s*\n(.*?)(?=\n^##\s|\z)/mi
30
+ match = content.match(pattern)
31
+ match ? match[1].strip : nil
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaveAi
4
+ class PersonaDocument < ApplicationRecord
5
+ CATEGORIES = %w[soul doctrine policy persona execution constraint source governance].freeze
6
+
7
+ validates :name, presence: true
8
+ validates :slug, presence: true, uniqueness: true
9
+ validates :content, presence: true
10
+ validates :category, presence: true, inclusion: { in: CATEGORIES }
11
+
12
+ scope :active, -> { where(active: true) }
13
+ scope :ordered, -> { order(position: :asc, name: :asc) }
14
+ scope :by_category, ->(cat) { where(category: cat) }
15
+
16
+ after_save :clear_for_prompt_cache
17
+ after_destroy :clear_for_prompt_cache
18
+
19
+ def self.for_prompt
20
+ cache = Thread.current[:pave_ai_persona_document_for_prompt]
21
+ return cache if cache
22
+ Thread.current[:pave_ai_persona_document_for_prompt] = active.ordered.group_by(&:category)
23
+ end
24
+
25
+ def self.clear_request_cache!
26
+ Thread.current[:pave_ai_persona_document_for_prompt] = nil
27
+ end
28
+
29
+ private
30
+
31
+ def clear_for_prompt_cache
32
+ self.class.clear_request_cache!
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaveAi
4
+ class Quota < ApplicationRecord
5
+ # "quota".pluralize is "quota" under ActiveSupport's Latin -a rule, which
6
+ # would resolve the table as pave_ai_quota. The table is pave_ai_quotas.
7
+ self.table_name = "pave_ai_quotas"
8
+
9
+ belongs_to :user, polymorphic: true
10
+
11
+ validates :period, presence: true
12
+ validates :period, uniqueness: { scope: [ :user_id, :user_type ] }
13
+
14
+ def self.current_for(user)
15
+ period = current_period
16
+ find_or_create_by!(user: user, period: period) do |quota|
17
+ limits = PaveAi.config.quota_limits_for(user)
18
+ quota.generations_limit = limits[:generations]
19
+ quota.exports_limit = limits[:exports]
20
+ quota.credits_limit = limits[:credits]
21
+ end
22
+ rescue ActiveRecord::RecordNotUnique
23
+ # Two first requests of the month raced to create the row; the loser
24
+ # takes the winner's.
25
+ find_by!(user: user, period: period)
26
+ end
27
+
28
+ # Check if user is within generation quota.
29
+ # For generations: checks quota first, then falls back to wallet credits.
30
+ def self.within_quota?(user, type: :generation)
31
+ quota = current_for(user)
32
+ case type
33
+ when :generation
34
+ return true if quota.generations_used < quota.generations_limit
35
+ # Quota exhausted — check wallet overflow
36
+ user.respond_to?(:tool_credits_balance) && user.tool_credits_balance > 0
37
+ when :export
38
+ quota.exports_used < quota.exports_limit
39
+ else
40
+ true
41
+ end
42
+ end
43
+
44
+ # Check if user is within credit quota (quota + wallet).
45
+ def self.within_credit_quota?(user)
46
+ quota = current_for(user)
47
+ return true if quota.credits_used < quota.credits_limit
48
+ # Quota exhausted — check wallet overflow
49
+ user.respond_to?(:tool_credits_balance) && user.tool_credits_balance > 0
50
+ end
51
+
52
+ def self.increment!(user, type: :generation)
53
+ quota = current_for(user)
54
+ case type
55
+ when :generation then quota.increment!(:generations_used)
56
+ when :export then quota.increment!(:exports_used)
57
+ end
58
+ end
59
+
60
+ def self.deduct_credit!(user, amount: 1)
61
+ quota = current_for(user)
62
+ quota.increment!(:credits_used, amount)
63
+ end
64
+
65
+ def generation_summary = "#{generations_used}/#{generations_limit}"
66
+ def export_summary = "#{exports_used}/#{exports_limit}"
67
+ def credit_summary = "#{credits_used}/#{credits_limit}"
68
+ def credits_remaining = [ credits_limit - credits_used, 0 ].max
69
+
70
+ def generation_percentage
71
+ return 0 if generations_limit.zero?
72
+ [ (generations_used * 100.0 / generations_limit).round, 100 ].min
73
+ end
74
+
75
+ def self.current_period = Time.current.strftime("%Y-%m")
76
+ end
77
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaveAi
4
+ class SpendLog < ApplicationRecord
5
+ belongs_to :user, polymorphic: true, optional: true
6
+ # The party whose usage this is billed against — a Space, an Org, a
7
+ # team. Distinct from user (the person who triggered the operation).
8
+ belongs_to :billable, polymorphic: true, optional: true
9
+
10
+ validates :intent, presence: true
11
+ validates :spend_type, presence: true
12
+ validates :provider, presence: true
13
+
14
+ scope :for_period, ->(start_at, end_at) { where(created_at: start_at..end_at) }
15
+ scope :for_user, ->(user) { where(user_id: user.id, user_type: user.class.name) }
16
+ scope :for_intent, ->(intent) { where(intent: intent) }
17
+ scope :for_provider, ->(provider) { where(provider: provider) }
18
+ scope :for_billable, ->(billable) { where(billable: billable) }
19
+ scope :for_model, ->(model) { where(model: model) }
20
+
21
+ # Append-only: a spend log is the evidence behind a charge, so nothing
22
+ # may rewrite or delete a persisted row. (Bulk delete_all in test
23
+ # teardown bypasses this deliberately — it is not a record operation.)
24
+ def readonly? = persisted?
25
+
26
+ before_destroy do
27
+ raise ActiveRecord::ReadOnlyRecord, "PaveAi::SpendLog is append-only"
28
+ end
29
+
30
+ # delete and the counter helpers write straight to the table, skipping
31
+ # readonly? and callbacks.
32
+ def delete
33
+ persisted? ? raise(ActiveRecord::ReadOnlyRecord, "PaveAi::SpendLog is append-only") : super
34
+ end
35
+
36
+ def increment!(*) = raise(ActiveRecord::ReadOnlyRecord, "PaveAi::SpendLog is append-only")
37
+ def decrement!(*) = raise(ActiveRecord::ReadOnlyRecord, "PaveAi::SpendLog is append-only")
38
+ scope :approved, -> { where(approved: true) }
39
+ scope :denied, -> { where(approved: false) }
40
+ scope :successful, -> { where(success: true) }
41
+
42
+ def self.total_cents = sum(:actual_cost_cents)
43
+ def self.total_credits = sum(:credits_charged)
44
+ def approved? = approved
45
+ def success? = success
46
+ end
47
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaveAi
4
+ class Client::Provider
5
+ attr_reader :model
6
+
7
+ def initialize(model:)
8
+ @model = model
9
+ end
10
+
11
+ def self.for(provider_name)
12
+ klass = registry[provider_name.to_s]
13
+ raise PaveAi::Client::ConfigurationError, "Unknown AI provider: #{provider_name}" unless klass
14
+ klass.new(model: nil)
15
+ end
16
+
17
+ def provider_name = raise(NotImplementedError)
18
+ def chat_url = raise(NotImplementedError)
19
+ def image_url = nil
20
+ def api_key = raise(NotImplementedError)
21
+ def openai_compatible? = true
22
+ def image_available? = image_url.present?
23
+ def configured? = raise(NotImplementedError)
24
+ def default_model = raise(NotImplementedError)
25
+ def default_image_model = nil
26
+ def credit_cost = 1
27
+
28
+ # RubyLLM speaks this vendor's own protocol rather than Chat Completions.
29
+ def native_protocol? = false
30
+ # Usable only with a caller's Credential (it has no platform identity).
31
+ def requires_caller_credential? = false
32
+ # A caller's Credential may carry its own base URL for this provider.
33
+ def accepts_api_base? = false
34
+ # A caller's Credential may be used with this provider at all.
35
+ def accepts_caller_credential? = true
36
+
37
+ def self.registry
38
+ @registry ||= {
39
+ "anthropic" => PaveAi::Client::Providers::Anthropic,
40
+ "gemini" => PaveAi::Client::Providers::Gemini,
41
+ "ollama" => PaveAi::Client::Providers::Ollama,
42
+ "openai" => PaveAi::Client::Providers::Openai,
43
+ "openai_compatible" => PaveAi::Client::Providers::OpenaiCompatible,
44
+ "xai" => PaveAi::Client::Providers::Xai,
45
+ "zai" => PaveAi::Client::Providers::Zai,
46
+ "zen" => PaveAi::Client::Providers::Zen
47
+ }.freeze
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaveAi
4
+ # Routed natively by RubyLLM (the Messages API), not as an OpenAI-compatible
5
+ # vendor. No default model: a pin is trusted only after one live smoke, so the host names the model.
6
+ class Client::Providers::Anthropic < Client::Provider
7
+ def provider_name = "anthropic"
8
+ def chat_url = "https://api.anthropic.com/v1/messages"
9
+ def api_key = PaveAi.config.anthropic_api_key
10
+ def openai_compatible? = false
11
+ def native_protocol? = true
12
+ def configured? = PaveAi.config.anthropic_configured?
13
+ def default_model = nil
14
+ end
15
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaveAi
4
+ # Routed natively by RubyLLM (generateContent), not as an OpenAI-compatible
5
+ # vendor. No default model: a pin is trusted only after one live smoke, so the host names the model.
6
+ class Client::Providers::Gemini < Client::Provider
7
+ def provider_name = "gemini"
8
+ def chat_url = "https://generativelanguage.googleapis.com/v1beta"
9
+ def api_key = PaveAi.config.gemini_api_key
10
+ def openai_compatible? = false
11
+ def native_protocol? = true
12
+ def configured? = PaveAi.config.gemini_configured?
13
+ def default_model = nil
14
+ end
15
+ end