Skip to content

refactor: provider namespace unification and architecture overhaul#90

Merged
INONONO66 merged 13 commits into
mainfrom
refactor/provider-namespace
May 28, 2026
Merged

refactor: provider namespace unification and architecture overhaul#90
INONONO66 merged 13 commits into
mainfrom
refactor/provider-namespace

Conversation

@INONONO66
Copy link
Copy Markdown
Owner

@INONONO66 INONONO66 commented May 28, 2026

Summary

Major architecture refactor that unifies the provider namespace, separates bypass from tool identification, and switches cost calculation to use actual upstream response data.

50 files changed, +694 / -1,100 lines (net reduction of 406 lines)

Changes by Phase

Phase 1: Provider namespace foundation

  • New CanonicalProvider resolver — single source of truth for model→provider mapping
  • Replaces hardcoded MODEL_PROVIDER_OVERRIDES, provider === 'claude' ? 'anthropic' : 'openai', and provider === 'openai' billing special-case
  • New admin endpoints: GET /admin/providers, GET /admin/pricing, GET /admin/config

Phase 2: ProviderTransform split

  • Separate bypass logic from AgentPlugin into provider-level ProviderTransform registry
  • AgentPlugin now handles tool identification only (id + matches)
  • Bypass applied based on resolved provider id, not tool identity

Phase 3-4: actual_provider + cost switch

  • New actual_provider column on request_logs (migration 011)
  • Cost calculation now uses actual_model + actual_provider from upstream response
  • Pricing matches the model that actually served the request

Phase 5: Correlator reduction

  • Correlator reduced to account attribution only (cliproxy_account, cliproxy_auth_index)
  • actual_model and reasoning_tokens now captured at finalize time
  • New GET /admin/logs/:id/cost-audit endpoint

Phase 6: Quota improvements

  • Quota refresh loop starts even with 0 auth files (fixes late OAuth pickup)
  • Stale quota snapshots cleaned on account removal
  • Codex additional_rate_limits parsing for model-tier quotas
  • model dimension added to quota_snapshots (migration 012)

Phase 7: API key enforcement

  • allowedAccounts mismatch monitoring on correlation
  • allowedProviders soft validation against registry on key create/update
  • New GET /admin/quotas/probes endpoint

Cleanup

  • Removed dead agent-plugins/ directory and identification/ module
  • Removed subscription_code remnants and unused exports
  • Externalized pricing overrides to PRICING_OVERRIDES_JSON / PRICING_ALIASES_JSON
  • Consolidated 13 incremental migrations into single 001_init.sql
  • Dropped unused account_subscriptions table
  • Synced README with removed plans feature and new endpoints

New Admin API Endpoints

Method Path Description
GET /admin/providers Registered provider list + source info
GET /admin/pricing Pricing cache freshness
GET /admin/config Non-secret config snapshot
GET /admin/logs/:id/cost-audit Cost calculation audit trail
GET /admin/quotas/probes Registered quota probe types

DB Migrations

  • Fresh installs: Single 001_init.sql creates full schema
  • Existing DBs: Need manual ALTER for actual_provider + quota_snapshots.model columns

Verification

  • bun run typecheck
  • bun test tests/unit/ — 166 pass, 0 fail ✅
  • bun run build

Summary by cubic

Unifies provider mapping with a single CanonicalProvider, moves bypass to provider-level transforms, and switches cost calculation to the actual upstream provider/model. Adds new admin endpoints and streamlines quotas, pricing overrides, and schema.

  • New Features

    • Admin endpoints: GET /admin/providers, GET /admin/pricing, GET /admin/config, GET /admin/logs/:id/cost-audit, GET /admin/quotas/probes.
    • Quotas: model-tier snapshots (new model field), codex probe parses model limits, refresh loop starts without auth files and cleans stale accounts.
    • API keys: validate allowedProviders against the registry and warn on allowedAccounts mismatches.
  • Migration

    • Fresh installs: use the single 001_init.sql.
    • Existing DBs: add request_logs.actual_provider and quota_snapshots.model, then drop legacy migrations and the account_subscriptions table.

Written for commit 15b9df2. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

Release Notes

  • New Features

    • Added admin endpoints for provider metadata, pricing configuration, quota monitoring, request cost auditing, and API key management.
    • Introduced configurable pricing overrides and model aliases via environment variables.
    • Enhanced API key scoping with allowed provider and account restrictions.
    • Added per-model quota tracking and cost attribution improvements.
  • Documentation

    • Updated architecture and contribution guidance for clarity.

Review Change Stack

INONONO66 added 13 commits May 28, 2026 19:36
Replace hardcoded MODEL_PROVIDER_OVERRIDES in pass-through.ts,
provider === 'claude' ? 'anthropic' : 'openai' remap in service.ts,
and provider === 'openai' billing special-case in pricing.ts with
a unified CanonicalProvider resolver that derives provider from
model prefix using longest-prefix matching.

The resolver merges default rules with ProviderRegistry model lists
so custom providers from PROVIDERS_JSON auto-participate without
code changes. Billing semantics (anthropic vs openai cache-read
handling) are now determined by provider type from the registry.

Add three new admin API endpoints:
- GET /admin/providers: registered provider list with source info
- GET /admin/pricing: pricing cache freshness and path
- GET /admin/config: non-secret configuration snapshot
Move anthropic bypass logic from AgentPlugin transform methods to the
new ProviderTransform registry. AgentPlugin now handles tool
identification only (id + matches). pass-through.ts applies provider
transforms based on the resolved provider id instead of the matched
agent plugin.
Add actual_provider column to request_logs via migration 011. During finalize, derive actual_provider from the response's actual_model using CanonicalProvider.fromModel(). Cost calculation is unchanged in this commit — actual_provider is shadow-recorded for validation before switching cost basis.
Cost computation now uses the response's actual_model and actual_provider (derived from CanonicalProvider) instead of the request-time proxy provider and model. This ensures pricing matches the model that actually served the request.

daily_usage aggregation and cost_audit now reflect actual provider/model combinations.
…t endpoint

Remove actual_model and reasoning_tokens from correlator writes since
these are now captured at finalize time. Correlator now only attributes
cliproxy_account, cliproxy_auth_index, and cliproxy_source.

Add GET /admin/logs/:id/cost-audit endpoint to expose the cost
calculation audit trail for a specific request log.
…pshots

Always start the quota refresh loop when CLIPROXY_AUTH_DIR is
configured and readable, even if no .json auth files exist yet.
This ensures OAuth logins added later are picked up on the next tick.

Clean up stale quota snapshots for accounts whose auth files have
been removed, preventing ghost accounts in the latest quota view.
…ier quotas

Add nullable model column to quota_snapshots via migration 012.
Parse additional_rate_limits from OpenAI wham/usage response in the
codex probe, storing model-tier-specific rate limits (e.g. o3, gpt-4.1)
as separate quota snapshots with the model dimension populated.

Account-level snapshots keep model as NULL; model-tier snapshots
use the limit_name as the model identifier.
…alidation

Add post-hoc account mismatch detection: when the correlator attributes a request to an account not in the API key's allowedAccounts, emit a warning event for monitoring.

Validate allowedProviders against the provider registry on API key create/update, returning warnings for unknown provider IDs.

Add GET /admin/quotas/probes endpoint exposing registered quota probe types.
AgentPlugins registry is unused after ProviderTransform split.
Tool identification is handled by RequestInspector. Move anthropic
bypass helpers into provider/transforms/anthropic.ts and delete
the entire agent-plugins directory.
Remove subscription_code plumbing from types, repos, and service
since no code path sets it. Remove unused function exports from
ProviderTransforms, ProviderRegistry, CanonicalProvider, and
UsageRepo. Remove unused barrel index files.
Move hardcoded pricing model overrides and aliases to config-driven
PRICING_OVERRIDES_JSON and PRICING_ALIASES_JSON environment variables
with backward-compatible defaults.

Remove stale subscription plans documentation from README, update
admin endpoint table with new endpoints, and sync project description.
Add migration 013 to DROP the account_subscriptions table and its
index. The table was created in migration 006 for subscription plan
bindings but was never used after plans were removed. Fix stale
'subscription' wording in CLI init prompt.
Replace 13 incremental migrations with a single 001_init.sql that
creates the final schema directly. Remove ensureColumn compatibility
shims and stale-row UPDATE from db.ts since fresh installs are the
only supported path. Drop account_subscriptions table (unused).

Update storage-lifecycle-cost tests to match the consolidated schema.
@INONONO66 INONONO66 merged commit 3b8fef1 into main May 28, 2026
1 of 2 checks passed
@INONONO66 INONONO66 deleted the refactor/provider-namespace branch May 28, 2026 12:30
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 28, 2026

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 337ad3be-ee7a-4ace-83eb-a4b463f6a7cd

📥 Commits

Reviewing files that changed from the base of the PR and between a158c69 and 15b9df2.

📒 Files selected for processing (50)
  • CONTRIBUTING.md
  • README.md
  • package.json
  • src/admin/api-keys.ts
  • src/admin/index.ts
  • src/agent-plugins/generic.ts
  • src/agent-plugins/hermes.ts
  • src/agent-plugins/index.ts
  • src/agent-plugins/openclaw.ts
  • src/agent-plugins/opencode.ts
  • src/agent-plugins/types.ts
  • src/cli.ts
  • src/cliproxy/correlator.ts
  • src/cliproxy/quota/index.ts
  • src/cliproxy/quota/probes/codex.ts
  • src/cliproxy/quota/types.ts
  • src/config/validate.ts
  • src/identification/index.ts
  • src/provider/canonical.ts
  • src/provider/index.ts
  • src/provider/registry.ts
  • src/provider/transform.ts
  • src/provider/transforms/anthropic.ts
  • src/provider/transforms/index.ts
  • src/server/pass-through.ts
  • src/storage/api-keys.ts
  • src/storage/db.ts
  • src/storage/index.ts
  • src/storage/migrations/001_init.sql
  • src/storage/migrations/002_agent_attribution.sql
  • src/storage/migrations/003_enhanced_logging.sql
  • src/storage/migrations/004_cliproxy_attribution.sql
  • src/storage/migrations/005_lifecycle_cost_subscription.sql
  • src/storage/migrations/006_account_subscriptions.sql
  • src/storage/migrations/007_drop_msg_id_unique.sql
  • src/storage/migrations/008_api_keys.sql
  • src/storage/migrations/009_api_key_allowed_accounts.sql
  • src/storage/migrations/010_unique_msg_id.sql
  • src/storage/pricing.ts
  • src/storage/repo.ts
  • src/storage/service.ts
  • src/usage/index.ts
  • tests/unit/agent-plugins/generic.test.ts
  • tests/unit/agent-plugins/hermes.test.ts
  • tests/unit/agent-plugins/openclaw.test.ts
  • tests/unit/agent-plugins/opencode.test.ts
  • tests/unit/agent-plugins/registry.test.ts
  • tests/unit/config.test.ts
  • tests/unit/registry-schema.test.ts
  • tests/unit/storage-lifecycle-cost.test.ts

📝 Walkthrough

Walkthrough

This PR restructures provider request handling by removing the agent-plugin system and replacing it with canonical provider resolution and per-provider transforms. Database schema consolidation merges incremental migrations into a single initialization. Cost and usage tracking now separate actual and cost providers, with configurable pricing overrides/aliases and stronger API key scope validation.

Changes

Provider Transforms & Cost Attribution Consolidation

Layer / File(s) Summary
Type system updates
src/usage/index.ts, src/cliproxy/quota/types.ts
Usage.RequestLog adds actual_provider, cost_provider, cost_model and removes subscription_code; ProbeWindow adds optional model field.
Remove agent-plugins system
src/agent-plugins/*
Removes entire agent-plugins directory including registry, plugin implementations (opencode, openclaw, hermes, generic), and type exports.
Provider transforms system
src/provider/transform.ts, src/provider/transforms/*
Introduces ProviderTransform interface and ProviderTransforms namespace with registration and hook application; wires Anthropic transforms into the registry.
Canonical provider resolution
src/provider/canonical.ts, src/provider/index.ts
Adds CanonicalProvider namespace for longest-prefix model→provider mapping, auth-type normalization, registry-based resolution, and billing-semantics determination.
Configuration pricing infrastructure
src/config/validate.ts
Adds PricingOverride type and extends ValidatedConfig with pricingOverrides/pricingAliases parsed from JSON env variables; includes validation helpers and defaults.
Consolidate database schema
src/storage/migrations/001_init.sql, src/storage/db.ts, src/storage/migrations/002-010_*.sql
Merges incremental migrations into 001_init.sql with full schema for request_logs, daily_account_usage, quota_snapshots, cost_audit, api_keys; removes inline schema initialization and empties older migrations.
Quota and API key storage
src/cliproxy/quota/index.ts, src/storage/api-keys.ts, src/storage/repo.ts
Adds registeredProbeTypes() export, findByIdAllowedAccounts() repository function, and deleteByProviderAccount() quota helper; extends quota snapshots with model column.
Update request repository
src/storage/repo.ts
Modifies insert() to include finalized_at/error_message; narrows applyCorrelation() to cliproxy fields; removes subscription_code from lifecycle/finalize; adds actual_provider support; replaces cost-audit retrieval with ordered array.
Update pricing for canonical providers
src/storage/pricing.ts
Uses CanonicalProvider.billingSemantics() for OpenAI detection; applies Config.pricingOverrides dynamically; replaces fixed alias rules with configurable prefix-based aliasing from Config.pricingAliases.
Refactor usage service
src/storage/service.ts
Updates cost finalization to prefer cost_provider/cost_model overrides; refines correlation to validate against API key allowed accounts; uses CanonicalProvider.fromAuthType() for local quota; deletes stale quota snapshots; continues refresh when no auth files exist.
Refactor pass-through request handling
src/server/pass-through.ts
Removes AgentPlugins.resolve() and replaces with CanonicalProvider.resolve() for provider determination; refactors buildBody()/buildHeaders() to use ProviderTransforms by providerId; updates handlers and finalization logging for cost/actual provider computation.
Expand admin API
src/admin/api-keys.ts, src/admin/index.ts
Adds provider warning validation to API-key endpoints; introduces new routes for probe types, providers, pricing status, proxy config, and cost-audit retrieval.
Cliproxy updates
src/cliproxy/correlator.ts, src/cliproxy/quota/probes/codex.ts
Updates correlator to send cliproxy account/auth metadata; extends Codex probe to support per-model rate limits with model field in quota windows.
Documentation and CLI
CONTRIBUTING.md, README.md, package.json, src/cli.ts
Reflects removal of identification/plans subsystems; describes provider-based architecture; adds pricing config docs; updates CLI terminology and admin endpoints; simplifies package description.
Test updates
tests/unit/config.test.ts, tests/unit/registry-schema.test.ts, tests/unit/storage-lifecycle-cost.test.ts
Adds pricing config parsing test; updates registry test to use resolve(); updates lifecycle/cost test for 001_init.sql migration and removes subscription_code references.

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly Related PRs

  • INONONO66/agent-cli-proxy#83: Both PRs refactor the src/agent-plugins system—main PR removes the entire registry and plugin infrastructure, while this one removes a specific inert plugin variant and adjusts registrations.
  • INONONO66/agent-cli-proxy#80: Both PRs modify src/admin/api-keys.ts endpoints—main PR adds provider warning validation to response payloads, while this one hardens auth by removing CSRF enforcement from the same handlers.

🐰 Plugin pipelines traded for provider pipes,
Migrations unified, schemas now ripe,
Cost tracking sharpened with canonical sight,
CLI-Proxy hops forward—the architecture takes flight!

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/provider-namespace

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


Comment @coderabbitai help to get the list of available commands and usage tips.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant