Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 83 additions & 76 deletions docs/TASKS.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions src/domain/comboResolver.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// @ts-check
/**
* Combo Resolver — FASE-09 Domain Extraction (T-46)
*
Expand Down
157 changes: 157 additions & 0 deletions src/domain/costRules.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
/**
* Cost Rules — Domain Layer (T-19)
*
* Business rules for cost management: budget thresholds,
* quota checking, and cost summaries per API key.
*
* @module domain/costRules
*/

// @ts-check

/**
* @typedef {Object} BudgetConfig
* @property {number} dailyLimitUsd - Max daily spend in USD
* @property {number} [monthlyLimitUsd] - Max monthly spend in USD
* @property {number} [warningThreshold=0.8] - Alert when usage reaches this fraction
*/

/**
* @typedef {Object} CostEntry
* @property {number} cost - Cost in USD
* @property {number} timestamp - Unix timestamp
*/

/** @type {Map<string, BudgetConfig>} API key ID → budget config */
const budgets = new Map();

/** @type {Map<string, CostEntry[]>} API key ID → cost entries */
const costHistory = new Map();
Comment on lines +28 to +29

Copilot AI Feb 14, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The costHistory Map accumulates cost entries indefinitely without any cleanup mechanism. In a long-running application, this could lead to unbounded memory growth. Consider implementing periodic cleanup of old entries (e.g., entries older than 30 days) or a maximum size limit with eviction of oldest entries. The getDailyTotal and getCostSummary functions only need recent data, so older entries could be safely removed.

Copilot uses AI. Check for mistakes.

/**
* Set budget for an API key.
*
* @param {string} apiKeyId
* @param {BudgetConfig} config
*/
export function setBudget(apiKeyId, config) {
budgets.set(apiKeyId, {
dailyLimitUsd: config.dailyLimitUsd,
monthlyLimitUsd: config.monthlyLimitUsd || 0,
warningThreshold: config.warningThreshold ?? 0.8,
});
}

/**
* Get budget config for an API key.
*
* @param {string} apiKeyId
* @returns {BudgetConfig | null}
*/
export function getBudget(apiKeyId) {
return budgets.get(apiKeyId) || null;
}

/**
* Record a cost for an API key.
*
* @param {string} apiKeyId
* @param {number} cost - Cost in USD
*/
export function recordCost(apiKeyId, cost) {
if (!costHistory.has(apiKeyId)) {
costHistory.set(apiKeyId, []);
}
costHistory.get(apiKeyId).push({ cost, timestamp: Date.now() });
}
Comment on lines +61 to +66

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

The costHistory Map stores an array of cost entries for each API key. The recordCost function appends new entries to these arrays without any mechanism to prune or rotate old data. In a long-running proxy process, this will lead to indefinite memory growth, eventually causing the process to crash due to an Out-of-Memory (OOM) error. Additionally, functions like getDailyTotal and getCostSummary iterate over the entire history for an API key, leading to increasing performance degradation as the history grows.

export function recordCost(apiKeyId, cost) {
  if (!costHistory.has(apiKeyId)) {
    costHistory.set(apiKeyId, []);
  }
  const entries = costHistory.get(apiKeyId);
  entries.push({ cost, timestamp: Date.now() });

  // Prune entries older than 31 days to prevent memory exhaustion
  const thirtyOneDaysAgo = Date.now() - 31 * 24 * 60 * 60 * 1000;
  while (entries.length > 0 && entries[0].timestamp < thirtyOneDaysAgo) {
    entries.shift();
  }
}


/**
* Check if an API key has remaining budget.
*
* @param {string} apiKeyId
* @param {number} [additionalCost=0] - Projected cost to check
* @returns {{ allowed: boolean, reason?: string, dailyUsed: number, dailyLimit: number, warningReached: boolean }}
*/
export function checkBudget(apiKeyId, additionalCost = 0) {
const budget = budgets.get(apiKeyId);
if (!budget) {
return { allowed: true, dailyUsed: 0, dailyLimit: 0, warningReached: false };
}

const dailyUsed = getDailyTotal(apiKeyId);
const projectedTotal = dailyUsed + additionalCost;
const warningReached = projectedTotal >= budget.dailyLimitUsd * budget.warningThreshold;

if (projectedTotal > budget.dailyLimitUsd) {
return {
allowed: false,
reason: `Daily budget exceeded: $${projectedTotal.toFixed(4)} / $${budget.dailyLimitUsd.toFixed(2)}`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

A mensagem de motivo para um orçamento excedido formata o projectedTotal com 4 casas decimais (toFixed(4)) mas o dailyLimitUsd com 2 casas decimais (toFixed(2)). Para valores financeiros, é importante ser consistente. Recomendo usar o mesmo número de casas decimais para ambos os valores para evitar confusão.

      reason: `Daily budget exceeded: $${projectedTotal.toFixed(4)} / $${budget.dailyLimitUsd.toFixed(4)}`,

dailyUsed,
dailyLimit: budget.dailyLimitUsd,
warningReached: true,
};
}

return {
allowed: true,
dailyUsed,
dailyLimit: budget.dailyLimitUsd,
warningReached,
};
}

/**
* Get daily total cost for an API key.
*
* @param {string} apiKeyId
* @returns {number} Total cost today in USD
*/
export function getDailyTotal(apiKeyId) {
const entries = costHistory.get(apiKeyId) || [];
const todayStart = new Date();
todayStart.setHours(0, 0, 0, 0);
const startMs = todayStart.getTime();
Comment on lines +111 to +113

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

O cálculo para o início do dia (todayStart) usa new Date() e setHours(0, 0, 0, 0), que dependem do fuso horário local do servidor. Isso pode levar a um comportamento inconsistente se a aplicação for implantada em vários servidores em fusos horários diferentes. É uma boa prática usar UTC para tais cálculos para garantir a consistência.

  const today = new Date();
  const todayStart = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate()));
  const startMs = todayStart.getTime();


return entries
.filter((e) => e.timestamp >= startMs)
.reduce((sum, e) => sum + e.cost, 0);
}
Comment on lines +109 to +118

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

A função getDailyTotal itera sobre todos os registros em costHistory para calcular o total diário. Da mesma forma, getCostSummary (linhas 126-149) também itera sobre todos os registros. Como costHistory é um array em memória que cresce continuamente sem um mecanismo de limpeza, isso levará à degradação do desempenho e ao aumento do uso de memória ao longo do tempo, à medida que o número de registros de custo aumenta. Isso pode eventualmente causar um vazamento de memória e impactar a estabilidade da aplicação. Considere implementar uma estrutura de dados mais eficiente ou uma estratégia de limpeza para registros antigos.


/**
* Get cost summary for an API key.
*
* @param {string} apiKeyId
* @returns {{ dailyTotal: number, monthlyTotal: number, totalEntries: number, budget: BudgetConfig | null }}
*/
export function getCostSummary(apiKeyId) {
const entries = costHistory.get(apiKeyId) || [];
const now = new Date();

const todayStart = new Date(now);
todayStart.setHours(0, 0, 0, 0);

const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
Comment on lines +130 to +133

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

O cálculo para o início do dia (todayStart) e do mês (monthStart) usa new Date(), que depende do fuso horário local do servidor. Isso pode levar a um comportamento inconsistente se a aplicação for implantada em vários servidores em fusos horários diferentes. É uma boa prática usar UTC para tais cálculos para garantir a consistência.

  const todayStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));

  const monthStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));


const dailyTotal = entries
.filter((e) => e.timestamp >= todayStart.getTime())
.reduce((sum, e) => sum + e.cost, 0);

const monthlyTotal = entries
.filter((e) => e.timestamp >= monthStart.getTime())
.reduce((sum, e) => sum + e.cost, 0);

return {
dailyTotal,
monthlyTotal,
totalEntries: entries.length,
budget: budgets.get(apiKeyId) || null,
};
}

/**
* Clear all cost data (for testing).
*/
export function resetCostData() {
budgets.clear();
costHistory.clear();
}
108 changes: 108 additions & 0 deletions src/domain/fallbackPolicy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/**
* Fallback Policy — Domain Layer (T-19)
*
* Declarative fallback chain for model routing.
* When a primary provider is unavailable, the policy engine
* resolves to alternative providers in priority order.
*
* @module domain/fallbackPolicy
*/

// @ts-check

/**
* @typedef {Object} FallbackEntry
* @property {string} provider - Provider ID
* @property {number} [priority=0] - Lower = higher priority
* @property {boolean} [enabled=true] - Whether this fallback is active
*/

/** @type {Map<string, FallbackEntry[]>} model → fallback chain */
const fallbackChains = new Map();

/**
* Register a fallback chain for a model.
*
* @param {string} model - Model identifier (e.g. "gpt-4o")
* @param {FallbackEntry[]} chain - Ordered list of fallback providers
*/
export function registerFallback(model, chain) {
const sorted = [...chain]
.map((e) => ({
provider: e.provider,
priority: e.priority ?? 0,
enabled: e.enabled ?? true,
}))
.sort((a, b) => a.priority - b.priority);

fallbackChains.set(model, sorted);
}

/**
* Resolve the fallback chain for a model.
* Returns only enabled providers, sorted by priority.
*
* @param {string} model
* @param {string[]} [excludeProviders=[]] - Providers to skip (e.g. already tried)
* @returns {FallbackEntry[]} Ordered list of fallback providers
*/
export function resolveFallbackChain(model, excludeProviders = []) {
const chain = fallbackChains.get(model);
if (!chain) return [];

const excludeSet = new Set(excludeProviders);
return chain.filter((e) => e.enabled && !excludeSet.has(e.provider));
}

/**
* Get the next provider in the fallback chain.
*
* @param {string} model
* @param {string[]} [excludeProviders=[]]
* @returns {string | null} Next provider ID or null if chain exhausted
*/
export function getNextFallback(model, excludeProviders = []) {
const chain = resolveFallbackChain(model, excludeProviders);
return chain.length > 0 ? chain[0].provider : null;
}

/**
* Check if a model has any fallback providers configured.
*
* @param {string} model
* @returns {boolean}
*/
export function hasFallback(model) {
const chain = fallbackChains.get(model);
return !!chain && chain.some((e) => e.enabled);
}

/**
* Remove a fallback chain for a model.
*
* @param {string} model
* @returns {boolean} true if removed
*/
export function removeFallback(model) {
return fallbackChains.delete(model);
}

/**
* Get all registered fallback chains (for dashboard).
*
* @returns {Record<string, FallbackEntry[]>}
*/
export function getAllFallbackChains() {
const result = {};
for (const [model, chain] of fallbackChains.entries()) {
result[model] = chain;
}
return result;
}

/**
* Reset all fallback chains (for testing).
*/
export function resetAllFallbacks() {
fallbackChains.clear();
}
1 change: 1 addition & 0 deletions src/domain/lockoutPolicy.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// @ts-check
/**
* Lockout Policy — FASE-09 Domain Extraction (T-46)
*
Expand Down
Loading