Skip to content

feat: add model registry, preferences, routing, and cost ledger - #10

Merged
imtahirabatool merged 3 commits into
mainfrom
feature/model-registry
Nov 12, 2026
Merged

imtahirabatool merged 3 commits into
mainfrom
feature/model-registry

Conversation

@MemonaAmirAbdulHaq

@MemonaAmirAbdulHaq MemonaAmirAbdulHaq commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

This PR introduces the Model Registry and Cost Ledger functionality to the CodeHands backend. It establishes the foundation for managing AI model configurations, selecting models dynamically based on user preferences, handling model fallbacks, tracking usage costs, and synchronizing model preferences across devices.

1. Model Registry

  • Introduced a YAML-based model registry using models.yaml as the central configuration file for available AI models.
  • Added model definitions containing:
    • Model ID and provider information.
    • Input and output token pricing per million tokens.
    • Optional cache read and cache write pricing.
    • Context window size.
    • Supported model capabilities.
    • Pricing source URL and last-updated date.
  • Implemented registry validation to ensure model configurations are valid before they can be used.
  • Added validation for duplicate model IDs, missing pricing information, negative prices, invalid URLs, invalid dates, and unsupported context sizes.
  • Implemented conversion of YAML snake_case pricing fields into camelCase internal TypeScript properties.

2. Model Preferences

  • Introduced model preference management to allow users to configure which AI model should be used for different execution phases.
  • Implemented primary model and backup model selection for each phase.
  • Added validation to ensure:
    • All required phases are configured.
    • Selected model IDs exist in the registry.
    • Backup models are valid and unique.
    • The primary model is not repeated in the backup list.
    • Preference configurations follow the expected structure.
  • Added whitespace normalization for model IDs.

3. Model Router and Fallback Mechanism

  • Implemented a model router that selects the appropriate model based on the user's configured preferences.
  • Added support for primary model selection and ordered backup model fallback.
  • Implemented failure-aware routing so previously failed models are not selected again during the same routing process.
  • Added handling for scenarios where all configured models have failed or no backup models are available.
  • Ensured model selection is independent across execution phases.
  • Preserved backup priority regardless of the order in which failed models are reported.

4. Cost Ledger and Cost Calculation

  • Introduced a cost ledger for tracking AI model usage and associated costs.
  • Implemented token-based cost calculations using the pricing information available in the model registry.
  • Added support for:
    • Input token costs.
    • Output token costs.
    • Cache read costs.
    • Cache write costs.
  • Implemented validation for unknown models and negative token counts.
  • Added session-level and phase-level cost aggregation helpers that compute totals from an array of CostLedgerRecord objects; wiring to the live SQLite session is handled separately in watcher.ts
  • Added conversion of ledger records into SyncChange records while ensuring compatibility with the existing sync data guard.

4b . Daemon Budget Enforcement (watcher.ts): Connected claimTasks() to pickModel("implement", failedModels, preferences) so sessions.model is populated via the router. Implemented recordSessionCost() as an atomic SQLite transaction that increments sessions.cost_usd, appends a cost.recorded event, and calls checkAndEnforceSpendCap(). When cost_usd ≥ budgetUsd (default $0.50), the session transitions from running → stopped with reason "budget $X.XX reached at ". Implemented recoverSessions() to transition only running sessions to failed on daemon restart, preserving stopped, queued, and other terminal states.

5. Sync API Integration

  • Extended the existing sync functionality to support model preferences.
  • Added model-specific preference validation during synchronization.
  • Ensured synchronized model preferences reference valid model IDs and supported execution phases.
  • Added model-preference-specific validation on top of the existing checkData guard, without modifying validation behavior for other record types.
  • Added version-based synchronization handling to prevent stale preference updates from overwriting newer data.

6. Two-Laptop Synchronization Testing

  • Added an integration test demonstrating synchronization of model preferences and cost ledger records between two simulated laptops.
  • Verified that settings saved on Laptop A can be pulled and reconstructed on Laptop B.
  • Tested synchronization isolation and batching behavior.
  • Verified that model preferences and ledger records can pass through the existing synchronization flow.

7. Package Manager Migration

  • Migrated the root backend package manager from npm to pnpm.
  • Added pnpm-lock.yaml and configured the project to use [email protected].
  • Added the YAML dependency required for model registry configuration.
  • Updated the root test script to execute the relevant model registry, preferences, router, cost ledger, and synchronization test suites.
  • Added a demo:sync script for running the synchronization demo.

Testing and Verification

All relevant tests passed successfully.

Test results:

  • Total tests: 61
  • Passed: 61
  • Failed: 0
  • Skipped: 0

Test coverage includes:

  • Model registry loading and validation.
  • Model preference validation.
  • Primary and backup model selection.
  • Model routing and fallback behavior.
  • Token-based cost calculations.
  • Session and phase cost aggregation.
  • Sync guard compatibility.
  • Model preference synchronization.
  • Two-laptop synchronization, isolation, and batching.

TypeScript verification:

corepack [email protected] exec tsc --noEmit

Result: Passed with no TypeScript errors.

Test command:

corepack [email protected] test

Result: All 61 tests passed.


Outcome

This implementation establishes the backend foundation for model configuration, preference-driven model selection, automatic fallback handling, AI usage cost tracking, and cross-device synchronization of model preferences.

It provides a validated and extensible structure for integrating model selection and cost tracking into the CodeHands execution workflow.

@imtahirabatool
imtahirabatool merged commit 0a98295 into main Nov 12, 2026
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.

2 participants