Spaces:
Runtime error
Runtime error
Upload folder using huggingface_hub
Browse files- README.md +0 -10
- apps/api/src/circuit-breaker.ts +0 -60
- apps/api/src/expense/adapters/decorators/rate-limit.ts +0 -11
- apps/api/src/expense/adapters/decorators/retry.ts +0 -20
- apps/api/src/expense/adapters/image-store/base64-inline.ts +0 -14
- apps/api/src/expense/adapters/llm/receipt-parser.ts +0 -13
- apps/api/src/expense/adapters/repositories/analytics.repository.ts +0 -99
- apps/api/src/expense/adapters/repositories/budget.repository.ts +0 -55
- apps/api/src/expense/adapters/repositories/category.repository.ts +0 -55
- apps/api/src/expense/adapters/repositories/expense.repository.ts +0 -93
- apps/api/src/expense/adapters/repositories/profile.repository.ts +0 -40
- apps/api/src/expense/adapters/repositories/slip-queue.repository.ts +0 -76
- apps/api/src/expense/analytics/analytics.service.ts +0 -9
- apps/api/src/expense/budgets/budgets.service.ts +0 -8
- apps/api/src/expense/categories/categories.service.ts +0 -8
- apps/api/src/expense/expense.routes.ts +0 -46
- apps/api/src/expense/expenses.service.ts +0 -11
- apps/api/src/expense/ocr.service.test.ts +0 -33
- apps/api/src/expense/ocr.service.ts +0 -24
- apps/api/src/expense/profile/profile.service.ts +0 -6
- apps/api/src/expense/services/expense.domain.ts +0 -45
- apps/api/src/expense/services/slip-queue.service.ts +0 -77
- apps/api/src/prompts/expense.prompt.ts +0 -40
- apps/api/src/providers/base.ts +0 -33
- apps/api/src/providers/cerebras.ts +0 -103
- apps/api/src/providers/ollama.ts +0 -80
- docs/bulk-slip-upload/README.md +0 -251
- docs/superpowers/plans/2026-06-24-route-controller-service.md +0 -1272
- docs/superpowers/plans/2026-06-30-expense-dashboard-backend.md +0 -2021
- docs/superpowers/plans/2026-07-02-llm-router-library.md +0 -1299
- docs/superpowers/specs/2026-06-24-route-controller-service-design.md +0 -154
- docs/superpowers/specs/2026-06-30-expense-dashboard-design.md +0 -384
- docs/superpowers/specs/2026-07-02-expense-dashboard-design.md +0 -217
- docs/superpowers/specs/2026-07-02-llm-router-library-design.md +0 -275
- src/circuit-breaker.ts +0 -60
- src/groq-client.ts +0 -65
- src/index.ts +0 -19
- src/logger.ts +0 -26
- src/middleware/authMiddleware.ts +0 -13
- src/ollama-client.ts +0 -58
- src/pii-scanner.test.ts +0 -53
- src/pii-scanner.ts +0 -36
- src/providers/base.ts +0 -33
- src/providers/cerebras.ts +0 -103
- src/providers/ollama.ts +0 -80
- src/proxy.ts +0 -421
- src/router.ts +0 -249
- src/websearch.ts +0 -35
- tsconfig.json +0 -25
README.md
DELETED
|
@@ -1,10 +0,0 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: Llm Router
|
| 3 |
-
emoji: 🏢
|
| 4 |
-
colorFrom: indigo
|
| 5 |
-
colorTo: yellow
|
| 6 |
-
sdk: docker
|
| 7 |
-
pinned: false
|
| 8 |
-
---
|
| 9 |
-
|
| 10 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/circuit-breaker.ts
DELETED
|
@@ -1,60 +0,0 @@
|
|
| 1 |
-
export type CircuitName = 'ollama' | 'cerebras' | 'claude'
|
| 2 |
-
|
| 3 |
-
interface CircuitState {
|
| 4 |
-
failures: number
|
| 5 |
-
lastFailure: number | null
|
| 6 |
-
isOpen: boolean
|
| 7 |
-
}
|
| 8 |
-
|
| 9 |
-
const FAILURE_THRESHOLD = 3
|
| 10 |
-
const RESET_TIMEOUT_MS = 60000 // 1 minute
|
| 11 |
-
|
| 12 |
-
const circuits: Record<CircuitName, CircuitState> = {
|
| 13 |
-
ollama: { failures: 0, lastFailure: null, isOpen: false },
|
| 14 |
-
cerebras: { failures: 0, lastFailure: null, isOpen: false },
|
| 15 |
-
claude: { failures: 0, lastFailure: null, isOpen: false },
|
| 16 |
-
}
|
| 17 |
-
|
| 18 |
-
export function isCircuitOpen(service: CircuitName): boolean {
|
| 19 |
-
const circuit = circuits[service]
|
| 20 |
-
|
| 21 |
-
if (!circuit.isOpen) return false
|
| 22 |
-
|
| 23 |
-
// Check if enough time passed to try again (half-open state)
|
| 24 |
-
const now = Date.now()
|
| 25 |
-
if (circuit.lastFailure !== null && now - circuit.lastFailure > RESET_TIMEOUT_MS) {
|
| 26 |
-
circuit.isOpen = false
|
| 27 |
-
circuit.failures = 0
|
| 28 |
-
console.log(JSON.stringify({ event: 'circuit_half_open', service }))
|
| 29 |
-
return false
|
| 30 |
-
}
|
| 31 |
-
|
| 32 |
-
return true
|
| 33 |
-
}
|
| 34 |
-
|
| 35 |
-
export function recordSuccess(service: CircuitName): void {
|
| 36 |
-
circuits[service] = { failures: 0, lastFailure: null, isOpen: false }
|
| 37 |
-
}
|
| 38 |
-
|
| 39 |
-
export function recordFailure(service: CircuitName): void {
|
| 40 |
-
const circuit = circuits[service]
|
| 41 |
-
circuit.failures++
|
| 42 |
-
circuit.lastFailure = Date.now()
|
| 43 |
-
|
| 44 |
-
if (circuit.failures >= FAILURE_THRESHOLD) {
|
| 45 |
-
circuit.isOpen = true
|
| 46 |
-
console.log(JSON.stringify({
|
| 47 |
-
event: 'circuit_opened',
|
| 48 |
-
service,
|
| 49 |
-
failures: circuit.failures
|
| 50 |
-
}))
|
| 51 |
-
}
|
| 52 |
-
}
|
| 53 |
-
|
| 54 |
-
export function getCircuitStatus(): Record<CircuitName, { isOpen: boolean; failures: number }> {
|
| 55 |
-
return {
|
| 56 |
-
ollama: { isOpen: circuits.ollama.isOpen, failures: circuits.ollama.failures },
|
| 57 |
-
cerebras: { isOpen: circuits.cerebras.isOpen, failures: circuits.cerebras.failures },
|
| 58 |
-
claude: { isOpen: circuits.claude.isOpen, failures: circuits.claude.failures },
|
| 59 |
-
}
|
| 60 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/adapters/decorators/rate-limit.ts
DELETED
|
@@ -1,11 +0,0 @@
|
|
| 1 |
-
import type { IReceiptParser, ParsedExpense, ParseReceiptInput } from '../../ports/index.js'
|
| 2 |
-
|
| 3 |
-
export class RateLimitReceiptParser implements IReceiptParser {
|
| 4 |
-
constructor(private inner: IReceiptParser, private delayMs: number) {}
|
| 5 |
-
|
| 6 |
-
async parse(input: ParseReceiptInput): Promise<ParsedExpense | null> {
|
| 7 |
-
const result = await this.inner.parse(input)
|
| 8 |
-
if (this.delayMs > 0) await new Promise<void>((r) => setTimeout(r, this.delayMs))
|
| 9 |
-
return result
|
| 10 |
-
}
|
| 11 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/adapters/decorators/retry.ts
DELETED
|
@@ -1,20 +0,0 @@
|
|
| 1 |
-
import type { IReceiptParser, ParsedExpense, ParseReceiptInput } from '../../ports/index.js'
|
| 2 |
-
|
| 3 |
-
export class RetryReceiptParser implements IReceiptParser {
|
| 4 |
-
constructor(private inner: IReceiptParser, private maxRetries: number) {}
|
| 5 |
-
|
| 6 |
-
async parse(input: ParseReceiptInput): Promise<ParsedExpense | null> {
|
| 7 |
-
let lastError: unknown
|
| 8 |
-
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
|
| 9 |
-
try {
|
| 10 |
-
return await this.inner.parse(input)
|
| 11 |
-
} catch (err) {
|
| 12 |
-
lastError = err
|
| 13 |
-
if (attempt < this.maxRetries) {
|
| 14 |
-
await new Promise<void>((r) => setTimeout(r, Math.pow(2, attempt) * 1000))
|
| 15 |
-
}
|
| 16 |
-
}
|
| 17 |
-
}
|
| 18 |
-
throw lastError
|
| 19 |
-
}
|
| 20 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/adapters/image-store/base64-inline.ts
DELETED
|
@@ -1,14 +0,0 @@
|
|
| 1 |
-
import type { IImageStore } from '../../ports/index.js'
|
| 2 |
-
|
| 3 |
-
// Stores images inline as base64 in the DB.
|
| 4 |
-
// The "key" is the base64 string itself.
|
| 5 |
-
// To swap to Cloudflare R2: replace this class in loader.ts.
|
| 6 |
-
export class Base64InlineImageStore implements IImageStore {
|
| 7 |
-
async save(base64: string): Promise<string> {
|
| 8 |
-
return base64
|
| 9 |
-
}
|
| 10 |
-
|
| 11 |
-
async get(key: string): Promise<string> {
|
| 12 |
-
return key
|
| 13 |
-
}
|
| 14 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/adapters/llm/receipt-parser.ts
DELETED
|
@@ -1,13 +0,0 @@
|
|
| 1 |
-
import { route } from '../../../llm-router.js'
|
| 2 |
-
import { parseExpenseJSON } from '../../expense.service.js'
|
| 3 |
-
import type { IReceiptParser, ParsedExpense, ParseReceiptInput } from '../../ports/index.js'
|
| 4 |
-
|
| 5 |
-
export class LLMRouterReceiptParser implements IReceiptParser {
|
| 6 |
-
async parse(input: ParseReceiptInput): Promise<ParsedExpense | null> {
|
| 7 |
-
const msg = input.imageBase64
|
| 8 |
-
? { role: 'user' as const, content: input.text ?? 'Parse this receipt.', imageBase64: input.imageBase64 }
|
| 9 |
-
: { role: 'user' as const, content: input.text ?? '' }
|
| 10 |
-
const result = await route([msg], 'expense-parser')
|
| 11 |
-
return parseExpenseJSON(result.response)
|
| 12 |
-
}
|
| 13 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/adapters/repositories/analytics.repository.ts
DELETED
|
@@ -1,99 +0,0 @@
|
|
| 1 |
-
import { and, gte, lte, eq, sql } from 'drizzle-orm'
|
| 2 |
-
import type { NeonHttpDatabase } from 'drizzle-orm/neon-http'
|
| 3 |
-
import type * as schema from '../../db/schema.js'
|
| 4 |
-
import { expenses, budgets, categories, userProfile } from '../../db/schema.js'
|
| 5 |
-
import type { IAnalyticsRepository } from '../../ports/index.js'
|
| 6 |
-
import type { Summary, Trends } from '@llm-router/shared'
|
| 7 |
-
|
| 8 |
-
type Db = NeonHttpDatabase<typeof schema>
|
| 9 |
-
|
| 10 |
-
export function getCurrentPeriod(
|
| 11 |
-
budgetResetDay: number,
|
| 12 |
-
now: Date = new Date()
|
| 13 |
-
): { start: Date; end: Date; label: string } {
|
| 14 |
-
const year = now.getUTCFullYear()
|
| 15 |
-
const month = now.getUTCMonth()
|
| 16 |
-
const day = now.getUTCDate()
|
| 17 |
-
|
| 18 |
-
let start: Date
|
| 19 |
-
let end: Date
|
| 20 |
-
|
| 21 |
-
if (day >= budgetResetDay) {
|
| 22 |
-
start = new Date(Date.UTC(year, month, budgetResetDay))
|
| 23 |
-
end = new Date(Date.UTC(year, month + 1, budgetResetDay - 1))
|
| 24 |
-
} else {
|
| 25 |
-
start = new Date(Date.UTC(year, month - 1, budgetResetDay))
|
| 26 |
-
end = new Date(Date.UTC(year, month, budgetResetDay - 1))
|
| 27 |
-
}
|
| 28 |
-
|
| 29 |
-
const label = `${start.getUTCFullYear()}-${String(start.getUTCMonth() + 1).padStart(2, '0')}`
|
| 30 |
-
return { start, end, label }
|
| 31 |
-
}
|
| 32 |
-
|
| 33 |
-
export class AnalyticsRepository implements IAnalyticsRepository {
|
| 34 |
-
constructor(private db: Db) {}
|
| 35 |
-
|
| 36 |
-
async getSummary(): Promise<Summary> {
|
| 37 |
-
const profile = await this.db.select().from(userProfile).limit(1)
|
| 38 |
-
const resetDay = profile[0]?.budget_reset_day ?? 1
|
| 39 |
-
const preferredCurrency = profile[0]?.preferred_currency ?? 'USD'
|
| 40 |
-
const { start, end, label } = getCurrentPeriod(resetDay)
|
| 41 |
-
|
| 42 |
-
const startStr = start.toISOString().slice(0, 10)
|
| 43 |
-
const endStr = end.toISOString().slice(0, 10)
|
| 44 |
-
|
| 45 |
-
const allExpenses = await this.db
|
| 46 |
-
.select()
|
| 47 |
-
.from(expenses)
|
| 48 |
-
.where(and(gte(expenses.date, startStr), lte(expenses.date, endStr)))
|
| 49 |
-
|
| 50 |
-
const allBudgets = await this.db.select().from(budgets)
|
| 51 |
-
const allCategories = await this.db.select().from(categories)
|
| 52 |
-
|
| 53 |
-
const currencyWarning = allExpenses.some((e) => e.currency !== preferredCurrency)
|
| 54 |
-
const periodExpenses = allExpenses.filter((e) => e.currency === preferredCurrency)
|
| 55 |
-
const totalSpent = periodExpenses.reduce((sum, e) => sum + Number(e.amount), 0)
|
| 56 |
-
|
| 57 |
-
const spentByCategory = new Map<string, number>()
|
| 58 |
-
for (const e of periodExpenses) {
|
| 59 |
-
spentByCategory.set(e.category_id, (spentByCategory.get(e.category_id) ?? 0) + Number(e.amount))
|
| 60 |
-
}
|
| 61 |
-
|
| 62 |
-
const budgetByCategory = new Map<string, number>()
|
| 63 |
-
for (const b of allBudgets) {
|
| 64 |
-
budgetByCategory.set(b.category_id, Number(b.amount))
|
| 65 |
-
}
|
| 66 |
-
|
| 67 |
-
return {
|
| 68 |
-
period: label,
|
| 69 |
-
total_spent: totalSpent,
|
| 70 |
-
currency_warning: currencyWarning,
|
| 71 |
-
categories: allCategories.map((cat) => {
|
| 72 |
-
const spent = spentByCategory.get(cat.id) ?? 0
|
| 73 |
-
const budget = budgetByCategory.get(cat.id) ?? null
|
| 74 |
-
return { category_id: cat.id, category_name: cat.name, color: cat.color, spent, budget, over_budget: budget !== null && spent > budget }
|
| 75 |
-
}),
|
| 76 |
-
}
|
| 77 |
-
}
|
| 78 |
-
|
| 79 |
-
async getTrends(months: number): Promise<Trends> {
|
| 80 |
-
const profile = await this.db.select().from(userProfile).limit(1)
|
| 81 |
-
const preferredCurrency = profile[0]?.preferred_currency ?? 'USD'
|
| 82 |
-
|
| 83 |
-
const now = new Date()
|
| 84 |
-
const cutoff = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - months, now.getUTCDate()))
|
| 85 |
-
const fromStr = cutoff.toISOString().slice(0, 10)
|
| 86 |
-
|
| 87 |
-
const rows = await this.db
|
| 88 |
-
.select({
|
| 89 |
-
period: sql<string>`to_char(date::date, 'YYYY-MM')`,
|
| 90 |
-
total: sql<number>`cast(sum(amount::numeric) as float)`,
|
| 91 |
-
})
|
| 92 |
-
.from(expenses)
|
| 93 |
-
.where(and(eq(expenses.currency, preferredCurrency), gte(expenses.date, fromStr)))
|
| 94 |
-
.groupBy(sql`to_char(date::date, 'YYYY-MM')`)
|
| 95 |
-
.orderBy(sql`to_char(date::date, 'YYYY-MM')`)
|
| 96 |
-
|
| 97 |
-
return { months: rows.map((r) => ({ period: r.period, total: r.total ?? 0 })) }
|
| 98 |
-
}
|
| 99 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/adapters/repositories/budget.repository.ts
DELETED
|
@@ -1,55 +0,0 @@
|
|
| 1 |
-
import { eq } from 'drizzle-orm'
|
| 2 |
-
import type { NeonHttpDatabase } from 'drizzle-orm/neon-http'
|
| 3 |
-
import type * as schema from '../../db/schema.js'
|
| 4 |
-
import { budgets } from '../../db/schema.js'
|
| 5 |
-
import type { IBudgetRepository } from '../../ports/index.js'
|
| 6 |
-
import type { Budget, CreateBudget, UpdateBudget } from '@llm-router/shared'
|
| 7 |
-
|
| 8 |
-
type Db = NeonHttpDatabase<typeof schema>
|
| 9 |
-
|
| 10 |
-
function rowToBudget(r: typeof budgets.$inferSelect): Budget {
|
| 11 |
-
return {
|
| 12 |
-
id: r.id,
|
| 13 |
-
category_id: r.category_id,
|
| 14 |
-
amount: Number(r.amount),
|
| 15 |
-
period: r.period,
|
| 16 |
-
created_at: r.created_at.toISOString(),
|
| 17 |
-
}
|
| 18 |
-
}
|
| 19 |
-
|
| 20 |
-
export class BudgetRepository implements IBudgetRepository {
|
| 21 |
-
constructor(private db: Db) {}
|
| 22 |
-
|
| 23 |
-
async list(): Promise<Budget[]> {
|
| 24 |
-
const rows = await this.db.select().from(budgets)
|
| 25 |
-
return rows.map(rowToBudget)
|
| 26 |
-
}
|
| 27 |
-
|
| 28 |
-
async create(input: CreateBudget): Promise<Budget> {
|
| 29 |
-
const [row] = await this.db
|
| 30 |
-
.insert(budgets)
|
| 31 |
-
.values({
|
| 32 |
-
category_id: input.category_id,
|
| 33 |
-
amount: String(input.amount),
|
| 34 |
-
period: input.period ?? 'monthly',
|
| 35 |
-
})
|
| 36 |
-
.returning()
|
| 37 |
-
if (!row) throw new Error('Insert failed')
|
| 38 |
-
return rowToBudget(row)
|
| 39 |
-
}
|
| 40 |
-
|
| 41 |
-
async update(id: string, input: UpdateBudget): Promise<Budget> {
|
| 42 |
-
const updates: Partial<typeof budgets.$inferInsert> = {}
|
| 43 |
-
if (input.amount !== undefined) updates.amount = String(input.amount)
|
| 44 |
-
if (input.period !== undefined) updates.period = input.period
|
| 45 |
-
updates.updated_at = new Date()
|
| 46 |
-
|
| 47 |
-
const [row] = await this.db.update(budgets).set(updates).where(eq(budgets.id, id)).returning()
|
| 48 |
-
if (!row) throw new Error(`Budget ${id} not found`)
|
| 49 |
-
return rowToBudget(row)
|
| 50 |
-
}
|
| 51 |
-
|
| 52 |
-
async delete(id: string): Promise<void> {
|
| 53 |
-
await this.db.delete(budgets).where(eq(budgets.id, id))
|
| 54 |
-
}
|
| 55 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/adapters/repositories/category.repository.ts
DELETED
|
@@ -1,55 +0,0 @@
|
|
| 1 |
-
import { eq, sql } from 'drizzle-orm'
|
| 2 |
-
import type { NeonHttpDatabase } from 'drizzle-orm/neon-http'
|
| 3 |
-
import type * as schema from '../../db/schema.js'
|
| 4 |
-
import { categories, expenses } from '../../db/schema.js'
|
| 5 |
-
import type { ICategoryRepository } from '../../ports/index.js'
|
| 6 |
-
import type { Category, CreateCategory, UpdateCategory } from '@llm-router/shared'
|
| 7 |
-
|
| 8 |
-
type Db = NeonHttpDatabase<typeof schema>
|
| 9 |
-
|
| 10 |
-
function rowToCategory(r: typeof categories.$inferSelect): Category {
|
| 11 |
-
return {
|
| 12 |
-
id: r.id,
|
| 13 |
-
name: r.name,
|
| 14 |
-
color: r.color,
|
| 15 |
-
icon: r.icon ?? null,
|
| 16 |
-
created_at: r.created_at.toISOString(),
|
| 17 |
-
}
|
| 18 |
-
}
|
| 19 |
-
|
| 20 |
-
export class CategoryRepository implements ICategoryRepository {
|
| 21 |
-
constructor(private db: Db) {}
|
| 22 |
-
|
| 23 |
-
async list(): Promise<Category[]> {
|
| 24 |
-
const rows = await this.db.select().from(categories).orderBy(categories.name)
|
| 25 |
-
return rows.map(rowToCategory)
|
| 26 |
-
}
|
| 27 |
-
|
| 28 |
-
async create(input: CreateCategory): Promise<Category> {
|
| 29 |
-
const [row] = await this.db.insert(categories).values(input).returning()
|
| 30 |
-
if (!row) throw new Error('Insert failed')
|
| 31 |
-
return rowToCategory(row)
|
| 32 |
-
}
|
| 33 |
-
|
| 34 |
-
async update(id: string, input: UpdateCategory): Promise<Category> {
|
| 35 |
-
const [row] = await this.db.update(categories).set(input).where(eq(categories.id, id)).returning()
|
| 36 |
-
if (!row) throw new Error(`Category ${id} not found`)
|
| 37 |
-
return rowToCategory(row)
|
| 38 |
-
}
|
| 39 |
-
|
| 40 |
-
async delete(id: string): Promise<void> {
|
| 41 |
-
try {
|
| 42 |
-
await this.db.delete(categories).where(eq(categories.id, id))
|
| 43 |
-
} catch (err: unknown) {
|
| 44 |
-
if (typeof err === 'object' && err !== null && 'code' in err && (err as Record<string, unknown>)['code'] === '23503') {
|
| 45 |
-
const countRows = await this.db
|
| 46 |
-
.select({ count: sql<number>`count(*)::int` })
|
| 47 |
-
.from(expenses)
|
| 48 |
-
.where(eq(expenses.category_id, id))
|
| 49 |
-
const n = countRows[0]?.count ?? 0
|
| 50 |
-
throw Object.assign(new Error(`Category has ${n} expenses — reassign them first`), { status: 409 })
|
| 51 |
-
}
|
| 52 |
-
throw err
|
| 53 |
-
}
|
| 54 |
-
}
|
| 55 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/adapters/repositories/expense.repository.ts
DELETED
|
@@ -1,93 +0,0 @@
|
|
| 1 |
-
import { eq, and, gte, lte, ilike, count, or } from 'drizzle-orm'
|
| 2 |
-
import type { NeonHttpDatabase } from 'drizzle-orm/neon-http'
|
| 3 |
-
import type * as schema from '../../db/schema.js'
|
| 4 |
-
import { expenses } from '../../db/schema.js'
|
| 5 |
-
import type { IExpenseRepository, ListExpensesFilter, ListExpensesResult } from '../../ports/index.js'
|
| 6 |
-
import type { Expense, CreateExpense, UpdateExpense } from '@llm-router/shared'
|
| 7 |
-
|
| 8 |
-
type Db = NeonHttpDatabase<typeof schema>
|
| 9 |
-
|
| 10 |
-
function rowToExpense(r: typeof expenses.$inferSelect): Expense {
|
| 11 |
-
return {
|
| 12 |
-
id: r.id,
|
| 13 |
-
amount: Number(r.amount),
|
| 14 |
-
currency: r.currency,
|
| 15 |
-
category_id: r.category_id,
|
| 16 |
-
merchant: r.merchant ?? null,
|
| 17 |
-
date: r.date,
|
| 18 |
-
description: r.description ?? null,
|
| 19 |
-
source: r.source,
|
| 20 |
-
raw_text: r.raw_text ?? null,
|
| 21 |
-
created_at: r.created_at.toISOString(),
|
| 22 |
-
updated_at: r.updated_at.toISOString(),
|
| 23 |
-
}
|
| 24 |
-
}
|
| 25 |
-
|
| 26 |
-
export class ExpenseRepository implements IExpenseRepository {
|
| 27 |
-
constructor(private db: Db) {}
|
| 28 |
-
|
| 29 |
-
async list(filter: ListExpensesFilter): Promise<ListExpensesResult> {
|
| 30 |
-
const page = filter.page ?? 1
|
| 31 |
-
const limit = Math.min(filter.limit ?? 20, 100)
|
| 32 |
-
const offset = (page - 1) * limit
|
| 33 |
-
|
| 34 |
-
const conditions = []
|
| 35 |
-
if (filter.category_id) conditions.push(eq(expenses.category_id, filter.category_id))
|
| 36 |
-
if (filter.from) conditions.push(gte(expenses.date, filter.from))
|
| 37 |
-
if (filter.to) conditions.push(lte(expenses.date, filter.to))
|
| 38 |
-
if (filter.search) {
|
| 39 |
-
conditions.push(
|
| 40 |
-
or(ilike(expenses.merchant, `%${filter.search}%`), ilike(expenses.description, `%${filter.search}%`))
|
| 41 |
-
)
|
| 42 |
-
}
|
| 43 |
-
const where = conditions.length > 0 ? and(...conditions) : undefined
|
| 44 |
-
|
| 45 |
-
const [rows, countRows] = await Promise.all([
|
| 46 |
-
this.db.select().from(expenses).where(where).orderBy(expenses.date).limit(limit).offset(offset),
|
| 47 |
-
this.db.select({ count: count() }).from(expenses).where(where),
|
| 48 |
-
])
|
| 49 |
-
|
| 50 |
-
return { data: rows.map(rowToExpense), total: countRows[0]?.count ?? 0, page, limit }
|
| 51 |
-
}
|
| 52 |
-
|
| 53 |
-
async create(input: CreateExpense): Promise<Expense> {
|
| 54 |
-
const [row] = await this.db
|
| 55 |
-
.insert(expenses)
|
| 56 |
-
.values({
|
| 57 |
-
amount: String(input.amount),
|
| 58 |
-
currency: input.currency ?? 'USD',
|
| 59 |
-
category_id: input.category_id,
|
| 60 |
-
merchant: input.merchant,
|
| 61 |
-
date: input.date,
|
| 62 |
-
description: input.description,
|
| 63 |
-
source: 'manual',
|
| 64 |
-
})
|
| 65 |
-
.returning()
|
| 66 |
-
if (!row) throw new Error('Insert failed')
|
| 67 |
-
return rowToExpense(row)
|
| 68 |
-
}
|
| 69 |
-
|
| 70 |
-
async get(id: string): Promise<Expense | null> {
|
| 71 |
-
const rows = await this.db.select().from(expenses).where(eq(expenses.id, id)).limit(1)
|
| 72 |
-
return rows[0] ? rowToExpense(rows[0]) : null
|
| 73 |
-
}
|
| 74 |
-
|
| 75 |
-
async update(id: string, input: UpdateExpense): Promise<Expense> {
|
| 76 |
-
const updates: Partial<typeof expenses.$inferInsert> = {}
|
| 77 |
-
if (input.amount !== undefined) updates.amount = String(input.amount)
|
| 78 |
-
if (input.currency !== undefined) updates.currency = input.currency
|
| 79 |
-
if (input.category_id !== undefined) updates.category_id = input.category_id
|
| 80 |
-
if (input.merchant !== undefined) updates.merchant = input.merchant
|
| 81 |
-
if (input.date !== undefined) updates.date = input.date
|
| 82 |
-
if (input.description !== undefined) updates.description = input.description
|
| 83 |
-
updates.updated_at = new Date()
|
| 84 |
-
|
| 85 |
-
const [row] = await this.db.update(expenses).set(updates).where(eq(expenses.id, id)).returning()
|
| 86 |
-
if (!row) throw new Error(`Expense ${id} not found`)
|
| 87 |
-
return rowToExpense(row)
|
| 88 |
-
}
|
| 89 |
-
|
| 90 |
-
async delete(id: string): Promise<void> {
|
| 91 |
-
await this.db.delete(expenses).where(eq(expenses.id, id))
|
| 92 |
-
}
|
| 93 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/adapters/repositories/profile.repository.ts
DELETED
|
@@ -1,40 +0,0 @@
|
|
| 1 |
-
import type { NeonHttpDatabase } from 'drizzle-orm/neon-http'
|
| 2 |
-
import type * as schema from '../../db/schema.js'
|
| 3 |
-
import { userProfile } from '../../db/schema.js'
|
| 4 |
-
import type { IUserProfileRepository } from '../../ports/index.js'
|
| 5 |
-
import type { UserProfile, UpdateProfile } from '@llm-router/shared'
|
| 6 |
-
|
| 7 |
-
type Db = NeonHttpDatabase<typeof schema>
|
| 8 |
-
|
| 9 |
-
function rowToProfile(r: typeof userProfile.$inferSelect): UserProfile {
|
| 10 |
-
return {
|
| 11 |
-
id: r.id,
|
| 12 |
-
preferred_currency: r.preferred_currency,
|
| 13 |
-
locale: r.locale,
|
| 14 |
-
budget_reset_day: r.budget_reset_day,
|
| 15 |
-
}
|
| 16 |
-
}
|
| 17 |
-
|
| 18 |
-
export class UserProfileRepository implements IUserProfileRepository {
|
| 19 |
-
constructor(private db: Db) {}
|
| 20 |
-
|
| 21 |
-
async get(): Promise<UserProfile> {
|
| 22 |
-
const rows = await this.db.select().from(userProfile).limit(1)
|
| 23 |
-
const row = rows[0]
|
| 24 |
-
if (!row) throw new Error('Profile not seeded — run seedDefaults() first')
|
| 25 |
-
return rowToProfile(row)
|
| 26 |
-
}
|
| 27 |
-
|
| 28 |
-
async update(input: UpdateProfile): Promise<UserProfile> {
|
| 29 |
-
const updates: Partial<typeof userProfile.$inferInsert> = {}
|
| 30 |
-
if (input.preferred_currency !== undefined) updates.preferred_currency = input.preferred_currency
|
| 31 |
-
if (input.locale !== undefined) updates.locale = input.locale
|
| 32 |
-
if (input.budget_reset_day !== undefined) updates.budget_reset_day = input.budget_reset_day
|
| 33 |
-
updates.updated_at = new Date()
|
| 34 |
-
|
| 35 |
-
const rows = await this.db.update(userProfile).set(updates).returning()
|
| 36 |
-
const row = rows[0]
|
| 37 |
-
if (!row) throw new Error('Profile update failed')
|
| 38 |
-
return rowToProfile(row)
|
| 39 |
-
}
|
| 40 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/adapters/repositories/slip-queue.repository.ts
DELETED
|
@@ -1,76 +0,0 @@
|
|
| 1 |
-
import { eq, asc } from 'drizzle-orm'
|
| 2 |
-
import type { NeonHttpDatabase } from 'drizzle-orm/neon-http'
|
| 3 |
-
import type * as schema from '../../db/schema.js'
|
| 4 |
-
import { slipQueue } from '../../db/schema.js'
|
| 5 |
-
import type { ISlipQueueRepository, SlipQueueItem, SlipStatus, ParsedExpense } from '../../ports/index.js'
|
| 6 |
-
|
| 7 |
-
type Db = NeonHttpDatabase<typeof schema>
|
| 8 |
-
type SlipRow = typeof slipQueue.$inferSelect
|
| 9 |
-
|
| 10 |
-
function rowToItem(r: SlipRow): SlipQueueItem {
|
| 11 |
-
return {
|
| 12 |
-
id: r.id,
|
| 13 |
-
image_base64: r.image_base64,
|
| 14 |
-
status: r.status as SlipStatus,
|
| 15 |
-
retry_count: r.retry_count,
|
| 16 |
-
parsed_result: r.parsed_result as ParsedExpense | null,
|
| 17 |
-
error_message: r.error_message ?? null,
|
| 18 |
-
created_at: r.created_at.toISOString(),
|
| 19 |
-
processed_at: r.processed_at ? r.processed_at.toISOString() : null,
|
| 20 |
-
}
|
| 21 |
-
}
|
| 22 |
-
|
| 23 |
-
export class SlipQueueRepository implements ISlipQueueRepository {
|
| 24 |
-
constructor(private db: Db) {}
|
| 25 |
-
|
| 26 |
-
async createMany(imageBase64List: string[]): Promise<SlipQueueItem[]> {
|
| 27 |
-
const rows = await this.db
|
| 28 |
-
.insert(slipQueue)
|
| 29 |
-
.values(imageBase64List.map(b64 => ({ image_base64: b64 })))
|
| 30 |
-
.returning()
|
| 31 |
-
return rows.map(rowToItem)
|
| 32 |
-
}
|
| 33 |
-
|
| 34 |
-
async listAll(): Promise<SlipQueueItem[]> {
|
| 35 |
-
const rows = await this.db
|
| 36 |
-
.select()
|
| 37 |
-
.from(slipQueue)
|
| 38 |
-
.orderBy(asc(slipQueue.created_at))
|
| 39 |
-
return rows.map(rowToItem)
|
| 40 |
-
}
|
| 41 |
-
|
| 42 |
-
async get(id: string): Promise<SlipQueueItem | null> {
|
| 43 |
-
const rows = await this.db.select().from(slipQueue).where(eq(slipQueue.id, id)).limit(1)
|
| 44 |
-
return rows[0] ? rowToItem(rows[0]) : null
|
| 45 |
-
}
|
| 46 |
-
|
| 47 |
-
async update(
|
| 48 |
-
id: string,
|
| 49 |
-
updates: Partial<Pick<SlipQueueItem, 'status' | 'retry_count' | 'parsed_result' | 'error_message' | 'processed_at'>>,
|
| 50 |
-
): Promise<SlipQueueItem> {
|
| 51 |
-
const values: Partial<typeof slipQueue.$inferInsert> = {}
|
| 52 |
-
if (updates.status !== undefined) values.status = updates.status
|
| 53 |
-
if (updates.retry_count !== undefined) values.retry_count = updates.retry_count
|
| 54 |
-
if (updates.parsed_result !== undefined) values.parsed_result = updates.parsed_result
|
| 55 |
-
if (updates.error_message !== undefined) values.error_message = updates.error_message
|
| 56 |
-
if (updates.processed_at !== undefined) values.processed_at = updates.processed_at ? new Date(updates.processed_at) : null
|
| 57 |
-
|
| 58 |
-
const [row] = await this.db.update(slipQueue).set(values).where(eq(slipQueue.id, id)).returning()
|
| 59 |
-
if (!row) throw new Error(`Slip ${id} not found`)
|
| 60 |
-
return rowToItem(row)
|
| 61 |
-
}
|
| 62 |
-
|
| 63 |
-
async listPending(limit: number): Promise<SlipQueueItem[]> {
|
| 64 |
-
const rows = await this.db
|
| 65 |
-
.select()
|
| 66 |
-
.from(slipQueue)
|
| 67 |
-
.where(eq(slipQueue.status, 'pending'))
|
| 68 |
-
.orderBy(asc(slipQueue.created_at))
|
| 69 |
-
.limit(limit)
|
| 70 |
-
return rows.map(rowToItem)
|
| 71 |
-
}
|
| 72 |
-
|
| 73 |
-
async delete(id: string): Promise<void> {
|
| 74 |
-
await this.db.delete(slipQueue).where(eq(slipQueue.id, id))
|
| 75 |
-
}
|
| 76 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/analytics/analytics.service.ts
DELETED
|
@@ -1,9 +0,0 @@
|
|
| 1 |
-
// Thin re-export layer — logic lives in adapters/repositories/analytics.repository.ts
|
| 2 |
-
// getCurrentPeriod re-exported here because analytics.service.test.ts imports it directly.
|
| 3 |
-
export { getCurrentPeriod } from '../adapters/repositories/analytics.repository.js'
|
| 4 |
-
|
| 5 |
-
import { container } from '../loader.js'
|
| 6 |
-
|
| 7 |
-
const repo = container.analyticsRepo
|
| 8 |
-
export const getSummary = () => repo.getSummary()
|
| 9 |
-
export const getTrends = (months: number) => repo.getTrends(months)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/budgets/budgets.service.ts
DELETED
|
@@ -1,8 +0,0 @@
|
|
| 1 |
-
// Thin re-export layer — logic lives in expense/adapters/neon/budget.repository.ts
|
| 2 |
-
import { container } from '../loader.js'
|
| 3 |
-
|
| 4 |
-
const repo = container.budgetRepo
|
| 5 |
-
export const listBudgets = () => repo.list()
|
| 6 |
-
export const createBudget = (i: Parameters<typeof repo.create>[0]) => repo.create(i)
|
| 7 |
-
export const updateBudget = (id: string, i: Parameters<typeof repo.update>[1]) => repo.update(id, i)
|
| 8 |
-
export const deleteBudget = (id: string) => repo.delete(id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/categories/categories.service.ts
DELETED
|
@@ -1,8 +0,0 @@
|
|
| 1 |
-
// Thin re-export layer — logic lives in expense/adapters/neon/category.repository.ts
|
| 2 |
-
import { container } from '../loader.js'
|
| 3 |
-
|
| 4 |
-
const repo = container.categoryRepo
|
| 5 |
-
export const listCategories = () => repo.list()
|
| 6 |
-
export const createCategory = (i: Parameters<typeof repo.create>[0]) => repo.create(i)
|
| 7 |
-
export const updateCategory = (id: string, i: Parameters<typeof repo.update>[1]) => repo.update(id, i)
|
| 8 |
-
export const deleteCategory = (id: string) => repo.delete(id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/expense.routes.ts
DELETED
|
@@ -1,46 +0,0 @@
|
|
| 1 |
-
import { Router } from 'express'
|
| 2 |
-
import type { Router as ExpressRouter } from 'express'
|
| 3 |
-
|
| 4 |
-
import { validateExpense, validateManualExpense, validateUpdateExpense } from './expense.validator.js'
|
| 5 |
-
import { parseExpense, getExpenses, postManualExpense, getExpense, putExpense, deleteExpenseHandler } from './expense.controller.js'
|
| 6 |
-
|
| 7 |
-
import { validateCreateCategory, validateUpdateCategory } from './categories/categories.validator.js'
|
| 8 |
-
import { getCategories, postCategory, putCategory, deleteCategory } from './categories/categories.controller.js'
|
| 9 |
-
|
| 10 |
-
import { validateCreateBudget, validateUpdateBudget } from './budgets/budgets.validator.js'
|
| 11 |
-
import { getBudgets, postBudget, putBudget, deleteBudget } from './budgets/budgets.controller.js'
|
| 12 |
-
|
| 13 |
-
import { getSummary, getTrends } from './analytics/analytics.controller.js'
|
| 14 |
-
|
| 15 |
-
import { validateUpdateProfile } from './profile/profile.validator.js'
|
| 16 |
-
import { getProfile, putProfile } from './profile/profile.controller.js'
|
| 17 |
-
|
| 18 |
-
const router: ExpressRouter = Router()
|
| 19 |
-
|
| 20 |
-
// ── Fixed paths BEFORE /:id ───────────────────────────────────────────────────
|
| 21 |
-
router.get('/categories', getCategories)
|
| 22 |
-
router.post('/categories', validateCreateCategory, postCategory)
|
| 23 |
-
router.put('/categories/:id', validateUpdateCategory, putCategory)
|
| 24 |
-
router.delete('/categories/:id', deleteCategory)
|
| 25 |
-
|
| 26 |
-
router.get('/budgets', getBudgets)
|
| 27 |
-
router.post('/budgets', validateCreateBudget, postBudget)
|
| 28 |
-
router.put('/budgets/:id', validateUpdateBudget, putBudget)
|
| 29 |
-
router.delete('/budgets/:id', deleteBudget)
|
| 30 |
-
|
| 31 |
-
router.get('/summary', getSummary)
|
| 32 |
-
router.get('/trends', getTrends)
|
| 33 |
-
|
| 34 |
-
router.get('/profile', getProfile)
|
| 35 |
-
router.put('/profile', validateUpdateProfile, putProfile)
|
| 36 |
-
|
| 37 |
-
router.post('/parse', validateExpense, parseExpense)
|
| 38 |
-
router.post('/manual', validateManualExpense, postManualExpense)
|
| 39 |
-
|
| 40 |
-
// ── Parameterized routes LAST ─────────────────────────────────────────────────
|
| 41 |
-
router.get('/', getExpenses)
|
| 42 |
-
router.get('/:id', getExpense)
|
| 43 |
-
router.put('/:id', validateUpdateExpense, putExpense)
|
| 44 |
-
router.delete('/:id', deleteExpenseHandler)
|
| 45 |
-
|
| 46 |
-
export { router as expenseRouter }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/expenses.service.ts
DELETED
|
@@ -1,11 +0,0 @@
|
|
| 1 |
-
// Thin re-export layer — logic lives in expense/services/expense.domain.ts
|
| 2 |
-
export type { ListExpensesFilter, ListExpensesResult } from './ports/index.js'
|
| 3 |
-
|
| 4 |
-
import { container } from './loader.js'
|
| 5 |
-
|
| 6 |
-
const svc = container.expenseService
|
| 7 |
-
export const listExpenses = (f: Parameters<typeof svc.list>[0]) => svc.list(f)
|
| 8 |
-
export const createExpense = (i: Parameters<typeof svc.create>[0]) => svc.create(i)
|
| 9 |
-
export const getExpense = (id: string) => svc.get(id)
|
| 10 |
-
export const updateExpense = (id: string, i: Parameters<typeof svc.update>[1]) => svc.update(id, i)
|
| 11 |
-
export const deleteExpense = (id: string) => svc.delete(id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/ocr.service.test.ts
DELETED
|
@@ -1,33 +0,0 @@
|
|
| 1 |
-
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
| 2 |
-
|
| 3 |
-
vi.mock('tesseract.js', () => ({
|
| 4 |
-
default: {
|
| 5 |
-
recognize: vi.fn().mockResolvedValue({ data: { text: ' ค่าอาหาร 350 บาท ' } }),
|
| 6 |
-
},
|
| 7 |
-
}))
|
| 8 |
-
|
| 9 |
-
describe('extractTextFromImage', () => {
|
| 10 |
-
beforeEach(() => vi.clearAllMocks())
|
| 11 |
-
|
| 12 |
-
it('returns trimmed OCR text', async () => {
|
| 13 |
-
const { extractTextFromImage } = await import('./ocr.service')
|
| 14 |
-
const result = await extractTextFromImage(Buffer.from('fake').toString('base64'))
|
| 15 |
-
expect(result).toBe('ค่าอาหาร 350 บาท')
|
| 16 |
-
})
|
| 17 |
-
|
| 18 |
-
it('strips data-URI prefix before decoding', async () => {
|
| 19 |
-
const Tesseract = await import('tesseract.js')
|
| 20 |
-
const { extractTextFromImage } = await import('./ocr.service')
|
| 21 |
-
const dataUri = 'data:image/png;base64,' + Buffer.from('fake').toString('base64')
|
| 22 |
-
await extractTextFromImage(dataUri)
|
| 23 |
-
const callArg = vi.mocked(Tesseract.default.recognize).mock.calls[0]?.[0]
|
| 24 |
-
expect(Buffer.isBuffer(callArg)).toBe(true)
|
| 25 |
-
})
|
| 26 |
-
|
| 27 |
-
it('throws user-friendly error when Tesseract fails', async () => {
|
| 28 |
-
const Tesseract = await import('tesseract.js')
|
| 29 |
-
vi.mocked(Tesseract.default.recognize).mockRejectedValueOnce(new Error('engine crash'))
|
| 30 |
-
const { extractTextFromImage } = await import('./ocr.service')
|
| 31 |
-
await expect(extractTextFromImage('abc')).rejects.toThrow('Image OCR failed')
|
| 32 |
-
})
|
| 33 |
-
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/ocr.service.ts
DELETED
|
@@ -1,24 +0,0 @@
|
|
| 1 |
-
export async function extractTextFromImage(base64Image: string): Promise<string> {
|
| 2 |
-
try {
|
| 3 |
-
const Tesseract = await import('tesseract.js')
|
| 4 |
-
const cleanBase64 = base64Image.replace(/^data:image\/\w+;base64,/, '')
|
| 5 |
-
const imageBuffer = Buffer.from(cleanBase64, 'base64')
|
| 6 |
-
|
| 7 |
-
const result = await Tesseract.default.recognize(imageBuffer, 'eng', {
|
| 8 |
-
logger: (m: { status: string; progress: number }) => {
|
| 9 |
-
if (m.status === 'recognizing text') {
|
| 10 |
-
console.log(`[ocr] progress: ${Math.round(m.progress * 100)}%`)
|
| 11 |
-
}
|
| 12 |
-
},
|
| 13 |
-
})
|
| 14 |
-
|
| 15 |
-
return result.data.text.trim()
|
| 16 |
-
} catch (err: unknown) {
|
| 17 |
-
const message = err instanceof Error ? err.message : String(err)
|
| 18 |
-
console.error('[ocr] failed:', message)
|
| 19 |
-
throw new Error(
|
| 20 |
-
'Image OCR failed. Please type your expense as text instead. ' +
|
| 21 |
-
'Example: "Grab food 350 baht today"'
|
| 22 |
-
)
|
| 23 |
-
}
|
| 24 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/profile/profile.service.ts
DELETED
|
@@ -1,6 +0,0 @@
|
|
| 1 |
-
// Thin re-export layer — logic lives in expense/adapters/neon/profile.repository.ts
|
| 2 |
-
import { container } from '../loader.js'
|
| 3 |
-
|
| 4 |
-
const repo = container.profileRepo
|
| 5 |
-
export const getProfile = () => repo.get()
|
| 6 |
-
export const updateProfile = (i: Parameters<typeof repo.update>[0]) => repo.update(i)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/services/expense.domain.ts
DELETED
|
@@ -1,45 +0,0 @@
|
|
| 1 |
-
import type {
|
| 2 |
-
IExpenseRepository,
|
| 3 |
-
IUserProfileRepository,
|
| 4 |
-
ListExpensesFilter,
|
| 5 |
-
ListExpensesResult,
|
| 6 |
-
} from '../ports/index.js'
|
| 7 |
-
import type { Expense, CreateExpense, UpdateExpense } from '@llm-router/shared'
|
| 8 |
-
|
| 9 |
-
/**
|
| 10 |
-
* Domain service — owns expense business logic.
|
| 11 |
-
* Depends only on interfaces; knows nothing about Neon, Drizzle, or any SDK.
|
| 12 |
-
*
|
| 13 |
-
* Swapping DB: replace the injected repos in loader.ts. This class never changes.
|
| 14 |
-
*/
|
| 15 |
-
export class ExpenseDomainService {
|
| 16 |
-
constructor(
|
| 17 |
-
private expenseRepo: IExpenseRepository,
|
| 18 |
-
private profileRepo: IUserProfileRepository,
|
| 19 |
-
) {}
|
| 20 |
-
|
| 21 |
-
list(filter: ListExpensesFilter): Promise<ListExpensesResult> {
|
| 22 |
-
return this.expenseRepo.list(filter)
|
| 23 |
-
}
|
| 24 |
-
|
| 25 |
-
async create(input: CreateExpense): Promise<Expense> {
|
| 26 |
-
// Resolve currency from user profile when caller didn't specify one.
|
| 27 |
-
// This is business logic — it lives here, not in the DB adapter.
|
| 28 |
-
const currency = input.currency ?? await this.profileRepo.get()
|
| 29 |
-
.then(p => p.preferred_currency)
|
| 30 |
-
.catch(() => 'USD')
|
| 31 |
-
return this.expenseRepo.create({ ...input, currency })
|
| 32 |
-
}
|
| 33 |
-
|
| 34 |
-
get(id: string): Promise<Expense | null> {
|
| 35 |
-
return this.expenseRepo.get(id)
|
| 36 |
-
}
|
| 37 |
-
|
| 38 |
-
update(id: string, input: UpdateExpense): Promise<Expense> {
|
| 39 |
-
return this.expenseRepo.update(id, input)
|
| 40 |
-
}
|
| 41 |
-
|
| 42 |
-
delete(id: string): Promise<void> {
|
| 43 |
-
return this.expenseRepo.delete(id)
|
| 44 |
-
}
|
| 45 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/expense/services/slip-queue.service.ts
DELETED
|
@@ -1,77 +0,0 @@
|
|
| 1 |
-
import type { ISlipQueueRepository, IReceiptParser, IImageStore, SlipQueueItem } from '../ports/index.js'
|
| 2 |
-
|
| 3 |
-
export class SlipQueueService {
|
| 4 |
-
constructor(
|
| 5 |
-
private slipRepo: ISlipQueueRepository,
|
| 6 |
-
private parser: IReceiptParser,
|
| 7 |
-
private imageStore: IImageStore,
|
| 8 |
-
) {}
|
| 9 |
-
|
| 10 |
-
async enqueue(base64List: string[]): Promise<SlipQueueItem[]> {
|
| 11 |
-
const keys = await Promise.all(base64List.map(b64 => this.imageStore.save(b64)))
|
| 12 |
-
return this.slipRepo.createMany(keys)
|
| 13 |
-
}
|
| 14 |
-
|
| 15 |
-
async listAll(): Promise<SlipQueueItem[]> {
|
| 16 |
-
return this.slipRepo.listAll()
|
| 17 |
-
}
|
| 18 |
-
|
| 19 |
-
async get(id: string): Promise<SlipQueueItem | null> {
|
| 20 |
-
return this.slipRepo.get(id)
|
| 21 |
-
}
|
| 22 |
-
|
| 23 |
-
async processAll(limit = 20): Promise<{ processed: number; succeeded: number; failed: number }> {
|
| 24 |
-
const pending = await this.slipRepo.listPending(limit)
|
| 25 |
-
let succeeded = 0
|
| 26 |
-
let failed = 0
|
| 27 |
-
|
| 28 |
-
for (const slip of pending) {
|
| 29 |
-
await this.slipRepo.update(slip.id, { status: 'processing' })
|
| 30 |
-
try {
|
| 31 |
-
const imageBase64 = await this.imageStore.get(slip.image_base64)
|
| 32 |
-
const parsed = await this.parser.parse({ imageBase64 })
|
| 33 |
-
if (!parsed || !parsed.amount) {
|
| 34 |
-
throw new Error('LLM returned no valid JSON with a numeric amount')
|
| 35 |
-
}
|
| 36 |
-
await this.slipRepo.update(slip.id, {
|
| 37 |
-
status: 'success',
|
| 38 |
-
parsed_result: parsed,
|
| 39 |
-
processed_at: new Date().toISOString(),
|
| 40 |
-
})
|
| 41 |
-
succeeded++
|
| 42 |
-
} catch (err: unknown) {
|
| 43 |
-
const msg = err instanceof Error ? err.message : String(err)
|
| 44 |
-
const newRetryCount = slip.retry_count + 1
|
| 45 |
-
if (newRetryCount < 3) {
|
| 46 |
-
await this.slipRepo.update(slip.id, {
|
| 47 |
-
status: 'pending',
|
| 48 |
-
retry_count: newRetryCount,
|
| 49 |
-
error_message: msg,
|
| 50 |
-
})
|
| 51 |
-
} else {
|
| 52 |
-
await this.slipRepo.update(slip.id, {
|
| 53 |
-
status: 'failed',
|
| 54 |
-
retry_count: newRetryCount,
|
| 55 |
-
error_message: msg,
|
| 56 |
-
processed_at: new Date().toISOString(),
|
| 57 |
-
})
|
| 58 |
-
failed++
|
| 59 |
-
}
|
| 60 |
-
}
|
| 61 |
-
}
|
| 62 |
-
|
| 63 |
-
return { processed: pending.length, succeeded, failed }
|
| 64 |
-
}
|
| 65 |
-
|
| 66 |
-
async resetForRetry(id: string): Promise<SlipQueueItem> {
|
| 67 |
-
return this.slipRepo.update(id, { status: 'pending', retry_count: 0, error_message: null })
|
| 68 |
-
}
|
| 69 |
-
|
| 70 |
-
async setConfirmed(id: string): Promise<SlipQueueItem> {
|
| 71 |
-
return this.slipRepo.update(id, { status: 'confirmed' })
|
| 72 |
-
}
|
| 73 |
-
|
| 74 |
-
async delete(id: string): Promise<void> {
|
| 75 |
-
return this.slipRepo.delete(id)
|
| 76 |
-
}
|
| 77 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/prompts/expense.prompt.ts
DELETED
|
@@ -1,40 +0,0 @@
|
|
| 1 |
-
export const EXPENSE_PARSE_PROMPT = `You are a precise expense parser for a personal finance tracker.
|
| 2 |
-
Extract structured data from bank slip, receipt, or expense note text.
|
| 3 |
-
|
| 4 |
-
Return ONLY valid JSON with no markdown, no explanation, no extra text:
|
| 5 |
-
{
|
| 6 |
-
"amount": <number or null>,
|
| 7 |
-
"currency": "THB",
|
| 8 |
-
"date": "<YYYY-MM-DD or null - use current year 2026 if year not specified>",
|
| 9 |
-
"merchant": "<merchant name or null>",
|
| 10 |
-
"category": "<see rules below>",
|
| 11 |
-
"confidence": <0.0 to 1.0>,
|
| 12 |
-
"raw_description": "<brief summary of original text>"
|
| 13 |
-
}
|
| 14 |
-
|
| 15 |
-
Category selection rules — pick the MOST specific match:
|
| 16 |
-
- food: restaurants, cafes, coffee shops, groceries, food delivery (GrabFood, FoodPanda)
|
| 17 |
-
- transport: Grab ride, taxi, BTS, MRT, fuel, parking, toll
|
| 18 |
-
- shopping: clothes, shoes, electronics, beauty, retail stores
|
| 19 |
-
- bills: phone top-up, internet, Netflix, Spotify, software subscriptions
|
| 20 |
-
- rental_electricity: rent payment, electricity bill, water bill, condo fee
|
| 21 |
-
- gym: fitness center, gym membership, yoga, sports classes
|
| 22 |
-
- health: pharmacy, hospital, clinic, doctor, dental, supplements
|
| 23 |
-
- transfer: money transfer to family, send money, โอนเงิน
|
| 24 |
-
- emergency: unexpected urgent expense, accident, repair
|
| 25 |
-
- pet: pet food, vet clinic, pet grooming, pet supplies
|
| 26 |
-
- maid: cleaning service, แม่บ้าน, housekeeping
|
| 27 |
-
- entertainment: cinema, concert, games, hobbies, travel
|
| 28 |
-
- su_personal: expense explicitly tagged for Su
|
| 29 |
-
- tz_personal: expense explicitly tagged for Tz
|
| 30 |
-
- other: anything that does not fit above categories
|
| 31 |
-
|
| 32 |
-
Critical rules:
|
| 33 |
-
- NEVER guess or fabricate an amount — if unclear set null
|
| 34 |
-
- If date not found use null (caller will use today's date)
|
| 35 |
-
- Set confidence based on how clear the text is (1.0 = crystal clear slip, 0.5 = rough note)
|
| 36 |
-
- For Thai text: handle Thai numerals and common Thai merchant names
|
| 37 |
-
- Extract amount as a plain number from the actual input text only
|
| 38 |
-
- Never use example numbers — only what is in the text
|
| 39 |
-
- Handle formats: "28,000 baht" → 28000, "฿1,200" → 1200, "28000 บาท" → 28000
|
| 40 |
-
- Remove commas and currency symbols`
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/providers/base.ts
DELETED
|
@@ -1,33 +0,0 @@
|
|
| 1 |
-
export type MessageRole = 'user' | 'assistant' | 'system'
|
| 2 |
-
|
| 3 |
-
export interface SimpleMessage {
|
| 4 |
-
role: MessageRole
|
| 5 |
-
content: string
|
| 6 |
-
}
|
| 7 |
-
|
| 8 |
-
export interface CompletionInput {
|
| 9 |
-
messages: SimpleMessage[]
|
| 10 |
-
maxTokens?: number
|
| 11 |
-
temperature?: number
|
| 12 |
-
/**
|
| 13 |
-
* Optional text to pre-fill the assistant's reply.
|
| 14 |
-
* Claude supports this natively; other providers ignore it.
|
| 15 |
-
*/
|
| 16 |
-
prefill?: string
|
| 17 |
-
}
|
| 18 |
-
|
| 19 |
-
export interface CompletionOutput {
|
| 20 |
-
content: string
|
| 21 |
-
/** Actual model identifier returned by the provider */
|
| 22 |
-
model: string
|
| 23 |
-
inputTokens: number
|
| 24 |
-
outputTokens: number
|
| 25 |
-
/** Total cost in USD for this call */
|
| 26 |
-
costUsd: number
|
| 27 |
-
durationMs: number
|
| 28 |
-
}
|
| 29 |
-
|
| 30 |
-
export interface LLMProvider {
|
| 31 |
-
readonly name: string
|
| 32 |
-
complete(input: CompletionInput): Promise<CompletionOutput>
|
| 33 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/providers/cerebras.ts
DELETED
|
@@ -1,103 +0,0 @@
|
|
| 1 |
-
import Cerebras from '@cerebras/cerebras_cloud_sdk'
|
| 2 |
-
import { isCircuitOpen, recordSuccess, recordFailure } from '../circuit-breaker'
|
| 3 |
-
import { logger } from '../logger'
|
| 4 |
-
import type { LLMProvider, CompletionInput, CompletionOutput } from './base'
|
| 5 |
-
|
| 6 |
-
const MAX_RETRIES = 2
|
| 7 |
-
|
| 8 |
-
// Approximate Cerebras pricing per million tokens (as of 2026)
|
| 9 |
-
const PRICING: Record<string, { input: number; output: number }> = {
|
| 10 |
-
'llama-3.3-70b': { input: 0.85, output: 1.20 },
|
| 11 |
-
'llama-3.1-8b': { input: 0.10, output: 0.10 },
|
| 12 |
-
}
|
| 13 |
-
const DEFAULT_PRICING = { input: 0.85, output: 1.20 }
|
| 14 |
-
|
| 15 |
-
// Matches SimpleMessage but typed as the discriminated union the Cerebras SDK requires
|
| 16 |
-
type CerebrasMessage =
|
| 17 |
-
| { role: 'system'; content: string }
|
| 18 |
-
| { role: 'user'; content: string }
|
| 19 |
-
| { role: 'assistant'; content: string }
|
| 20 |
-
|
| 21 |
-
interface CerebrasChoice {
|
| 22 |
-
message: { content: string; role: string }
|
| 23 |
-
finish_reason: string
|
| 24 |
-
}
|
| 25 |
-
|
| 26 |
-
interface CerebrasCompletion {
|
| 27 |
-
model: string
|
| 28 |
-
choices: CerebrasChoice[]
|
| 29 |
-
usage?: { prompt_tokens: number; completion_tokens: number }
|
| 30 |
-
}
|
| 31 |
-
|
| 32 |
-
function calcCostUsd(inputTokens: number, outputTokens: number, model: string): number {
|
| 33 |
-
const rates = PRICING[model] ?? DEFAULT_PRICING
|
| 34 |
-
return (inputTokens * rates.input + outputTokens * rates.output) / 1_000_000
|
| 35 |
-
}
|
| 36 |
-
|
| 37 |
-
export class CerebrasProvider implements LLMProvider {
|
| 38 |
-
readonly name = 'cerebras'
|
| 39 |
-
|
| 40 |
-
private readonly client: Cerebras
|
| 41 |
-
private readonly model: string
|
| 42 |
-
|
| 43 |
-
constructor() {
|
| 44 |
-
this.client = new Cerebras({ apiKey: process.env.CEREBRAS_API_KEY ?? '' })
|
| 45 |
-
this.model = process.env.CLOUD_MODEL ?? 'llama-3.3-70b'
|
| 46 |
-
}
|
| 47 |
-
|
| 48 |
-
async complete(input: CompletionInput): Promise<CompletionOutput> {
|
| 49 |
-
if (!process.env.CEREBRAS_API_KEY) {
|
| 50 |
-
throw new Error('CEREBRAS_API_KEY is not set')
|
| 51 |
-
}
|
| 52 |
-
if (isCircuitOpen('cerebras')) {
|
| 53 |
-
throw new Error('Cerebras circuit open — too many recent failures')
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
let lastError: Error | null = null
|
| 57 |
-
|
| 58 |
-
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
| 59 |
-
try {
|
| 60 |
-
const start = Date.now()
|
| 61 |
-
const raw = await this.client.chat.completions.create({
|
| 62 |
-
model: this.model,
|
| 63 |
-
messages: input.messages as CerebrasMessage[],
|
| 64 |
-
max_tokens: input.maxTokens ?? 4000,
|
| 65 |
-
...(input.temperature !== undefined && { temperature: input.temperature }),
|
| 66 |
-
})
|
| 67 |
-
const durationMs = Date.now() - start
|
| 68 |
-
|
| 69 |
-
recordSuccess('cerebras')
|
| 70 |
-
logger.info('cerebras_success', { attempt }, durationMs)
|
| 71 |
-
|
| 72 |
-
const res = raw as CerebrasCompletion
|
| 73 |
-
const content = res.choices[0]?.message?.content ?? ''
|
| 74 |
-
const inputTokens = res.usage?.prompt_tokens ?? 0
|
| 75 |
-
const outputTokens = res.usage?.completion_tokens ?? 0
|
| 76 |
-
|
| 77 |
-
return {
|
| 78 |
-
content,
|
| 79 |
-
model: res.model,
|
| 80 |
-
inputTokens,
|
| 81 |
-
outputTokens,
|
| 82 |
-
costUsd: calcCostUsd(inputTokens, outputTokens, res.model),
|
| 83 |
-
durationMs,
|
| 84 |
-
}
|
| 85 |
-
} catch (err: unknown) {
|
| 86 |
-
const e = err as { message?: string; status?: number }
|
| 87 |
-
lastError = new Error(e.message ?? 'unknown error')
|
| 88 |
-
recordFailure('cerebras')
|
| 89 |
-
logger.warn('cerebras_attempt_failed', { attempt, status: e.status, error: e.message })
|
| 90 |
-
|
| 91 |
-
if (e.status === 429) {
|
| 92 |
-
await new Promise(r => setTimeout(r, attempt * 2000))
|
| 93 |
-
} else if (attempt < MAX_RETRIES) {
|
| 94 |
-
await new Promise(r => setTimeout(r, attempt * 1000))
|
| 95 |
-
}
|
| 96 |
-
}
|
| 97 |
-
}
|
| 98 |
-
|
| 99 |
-
throw new Error(`Cerebras unavailable: ${lastError?.message}`)
|
| 100 |
-
}
|
| 101 |
-
}
|
| 102 |
-
|
| 103 |
-
export const cerebrasProvider = new CerebrasProvider()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apps/api/src/providers/ollama.ts
DELETED
|
@@ -1,80 +0,0 @@
|
|
| 1 |
-
import { Ollama } from 'ollama'
|
| 2 |
-
import { isCircuitOpen, recordSuccess, recordFailure } from '../circuit-breaker'
|
| 3 |
-
import { logger } from '../logger'
|
| 4 |
-
import type { LLMProvider, CompletionInput, CompletionOutput } from './base'
|
| 5 |
-
|
| 6 |
-
const TIMEOUT_MS = 30_000
|
| 7 |
-
const MAX_RETRIES = 2
|
| 8 |
-
|
| 9 |
-
export class OllamaProvider implements LLMProvider {
|
| 10 |
-
readonly name = 'ollama'
|
| 11 |
-
|
| 12 |
-
private readonly client: Ollama
|
| 13 |
-
private readonly model: string
|
| 14 |
-
|
| 15 |
-
constructor() {
|
| 16 |
-
this.client = new Ollama({ host: process.env.OLLAMA_HOST ?? 'http://localhost:11434' })
|
| 17 |
-
this.model = process.env.OLLAMA_MODEL ?? 'qwen2.5:0.5b'
|
| 18 |
-
}
|
| 19 |
-
|
| 20 |
-
private async attempt(input: CompletionInput): Promise<CompletionOutput> {
|
| 21 |
-
const controller = new AbortController()
|
| 22 |
-
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS)
|
| 23 |
-
const start = Date.now()
|
| 24 |
-
|
| 25 |
-
try {
|
| 26 |
-
const options: Record<string, number> = {}
|
| 27 |
-
if (input.maxTokens !== undefined) options['num_predict'] = input.maxTokens
|
| 28 |
-
if (input.temperature !== undefined) options['temperature'] = input.temperature
|
| 29 |
-
|
| 30 |
-
const response = await this.client.chat({
|
| 31 |
-
model: this.model,
|
| 32 |
-
messages: input.messages,
|
| 33 |
-
...(Object.keys(options).length > 0 && { options }),
|
| 34 |
-
})
|
| 35 |
-
clearTimeout(timer)
|
| 36 |
-
|
| 37 |
-
return {
|
| 38 |
-
content: response.message.content,
|
| 39 |
-
model: this.model,
|
| 40 |
-
inputTokens: response.prompt_eval_count ?? 0,
|
| 41 |
-
outputTokens: response.eval_count ?? 0,
|
| 42 |
-
costUsd: 0, // local model — no API cost
|
| 43 |
-
durationMs: Date.now() - start,
|
| 44 |
-
}
|
| 45 |
-
} catch (err) {
|
| 46 |
-
clearTimeout(timer)
|
| 47 |
-
throw err
|
| 48 |
-
}
|
| 49 |
-
}
|
| 50 |
-
|
| 51 |
-
async complete(input: CompletionInput): Promise<CompletionOutput> {
|
| 52 |
-
if (isCircuitOpen('ollama')) {
|
| 53 |
-
throw new Error('Ollama circuit open — too many recent failures')
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
let lastError: Error | null = null
|
| 57 |
-
|
| 58 |
-
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
| 59 |
-
try {
|
| 60 |
-
const result = await this.attempt(input)
|
| 61 |
-
recordSuccess('ollama')
|
| 62 |
-
logger.info('ollama_success', { attempt, model: this.model }, result.durationMs)
|
| 63 |
-
return result
|
| 64 |
-
} catch (err: unknown) {
|
| 65 |
-
const e = err as Error
|
| 66 |
-
lastError = e
|
| 67 |
-
recordFailure('ollama')
|
| 68 |
-
logger.warn('ollama_attempt_failed', { attempt, error: e.message })
|
| 69 |
-
|
| 70 |
-
if (attempt < MAX_RETRIES) {
|
| 71 |
-
await new Promise(r => setTimeout(r, attempt * 1000))
|
| 72 |
-
}
|
| 73 |
-
}
|
| 74 |
-
}
|
| 75 |
-
|
| 76 |
-
throw new Error(`Ollama unavailable: ${lastError?.message}`)
|
| 77 |
-
}
|
| 78 |
-
}
|
| 79 |
-
|
| 80 |
-
export const ollamaProvider = new OllamaProvider()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
docs/bulk-slip-upload/README.md
DELETED
|
@@ -1,251 +0,0 @@
|
|
| 1 |
-
# Bulk Bank Slip Upload & Queue Processing
|
| 2 |
-
|
| 3 |
-
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
| 4 |
-
|
| 5 |
-
**Goal:** Allow users to upload many bank slip images at once, queue them for sequential LLM parsing (rate-limited for free-tier Ollama on HF Spaces), and review parsed results before confirming them as expenses.
|
| 6 |
-
|
| 7 |
-
**Architecture:** Hexagonal (ports & adapters). The domain core (`SlipQueueService`) depends only on interfaces — never on 3rd-party SDKs directly. A single loader file wires concrete adapters (Neon, LLMRouter, base64 store) to those interfaces at startup; swapping a provider means changing one line in the loader. Cross-cutting concerns (retry, rate-limiting) are decorators that wrap any adapter implementing the same interface. A GitHub Actions cron workflow triggers sequential processing every 5 minutes; the frontend polls for status.
|
| 8 |
-
|
| 9 |
-
**Tech Stack:** PostgreSQL/Neon + Drizzle ORM (queue storage), Express API on HF Spaces (processor), GitHub Actions (cron worker), React + React Router (review UI), `setInterval` polling (status updates).
|
| 10 |
-
|
| 11 |
-
---
|
| 12 |
-
|
| 13 |
-
## Problem Statement
|
| 14 |
-
|
| 15 |
-
The current expense tracker only accepts one bank slip at a time. Users who want to backfill a month's worth of transactions must open the drawer, upload a single image, wait for parsing, confirm it, and repeat — dozens of times. This is impractical for catch-up workflows and makes the tracker unusable for high-transaction days where multiple slips arrive simultaneously.
|
| 16 |
-
|
| 17 |
-
Additionally, the free-tier Ollama model hosted on HF Spaces cannot handle concurrent LLM requests, so naive parallel uploads would fail or produce garbage output.
|
| 18 |
-
|
| 19 |
-
---
|
| 20 |
-
|
| 21 |
-
## Solution
|
| 22 |
-
|
| 23 |
-
Two new surfaces replace the single-slip workflow for bulk cases:
|
| 24 |
-
|
| 25 |
-
1. **Bulk Upload Drawer** — a multi-file drop zone that accepts many images at once, enqueues them all instantly, and redirects to the review page.
|
| 26 |
-
2. **Slip Review Page** — a dedicated page showing every queued slip with its parsed status, parsed fields, and per-item actions (confirm → add to expenses, retry, discard). The page polls the API every 5 seconds while items are in-flight.
|
| 27 |
-
|
| 28 |
-
A GitHub Actions cron workflow runs every 5 minutes, calls a protected API endpoint, and the API processes all pending slips sequentially — one at a time, with a short delay between calls — until the queue is empty or a per-run limit is reached. Failed items are retried automatically up to 3 times before being marked for manual review.
|
| 29 |
-
|
| 30 |
-
---
|
| 31 |
-
|
| 32 |
-
## User Stories
|
| 33 |
-
|
| 34 |
-
1. As a user, I want to select multiple bank slip images at once from my device, so that I do not have to upload them one by one.
|
| 35 |
-
2. As a user, I want to drop a folder or batch of images onto the upload area, so that I can quickly enqueue an entire month of slips.
|
| 36 |
-
3. As a user, I want all selected images to be immediately saved to the server, so that I can close the browser and come back later without losing my uploads.
|
| 37 |
-
4. As a user, I want to be redirected to the review page automatically after uploading, so that I know where to track progress.
|
| 38 |
-
5. As a user, I want to see a status badge on each slip card (Pending, Processing, Parsed, Failed, Confirmed), so that I can tell at a glance what stage each item is in.
|
| 39 |
-
6. As a user, I want the review page to refresh automatically while slips are being processed, so that I do not have to manually reload to see new results.
|
| 40 |
-
7. As a user, I want to see the parsed amount, merchant, date, and category for each successfully parsed slip, so that I can verify the LLM output before committing it.
|
| 41 |
-
8. As a user, I want to confirm a parsed slip so that it is added to my expense list with the extracted data.
|
| 42 |
-
9. As a user, I want to override the category on a parsed slip before confirming, so that I can correct LLM misclassification.
|
| 43 |
-
10. As a user, I want to discard a slip I do not want to track, so that my review queue stays clean.
|
| 44 |
-
11. As a user, I want failed slips to be retried automatically up to 3 times, so that transient Ollama errors do not require my intervention.
|
| 45 |
-
12. As a user, I want to manually trigger a retry on a slip that permanently failed, so that I can attempt re-parsing after fixing the underlying issue (e.g. model unavailable).
|
| 46 |
-
13. As a user, I want to see the reason a slip failed (e.g. "LLM returned no valid JSON", "Timeout"), so that I can decide whether to retry or discard.
|
| 47 |
-
14. As a user, I want confirmed slips to disappear from the review queue (or show as Confirmed and collapsible), so that the page focuses on items still needing attention.
|
| 48 |
-
15. As a user, I want the review page to stop auto-polling once all items are in a terminal state (Parsed awaiting confirmation, Failed, Confirmed), so that the app does not make unnecessary API calls.
|
| 49 |
-
16. As a user, I want to confirm multiple slips at once via a "Confirm all parsed" bulk action, so that I can finish reviewing a large batch quickly.
|
| 50 |
-
17. As a user, I want to see the original slip image thumbnail on each card, so that I can visually verify the correct image was parsed.
|
| 51 |
-
18. As a user, I want to know how many slips are pending, processing, parsed, and failed at a glance via a summary row at the top of the review page, so that I can gauge overall progress.
|
| 52 |
-
19. As a user, I want slips to be processed in the order they were uploaded (FIFO), so that older slips are not indefinitely deferred.
|
| 53 |
-
20. As a user, I want the system to respect a delay between LLM calls, so that my free-tier Ollama server is not overwhelmed and remains stable for other features.
|
| 54 |
-
21. As a user, I want the GitHub Actions worker to process all pending slips in a single run rather than one per trigger, so that a large backlog is cleared within minutes, not hours.
|
| 55 |
-
22. As a user, I want the worker to handle partial failures gracefully — if one slip errors mid-run, the worker continues to the next — so that a bad image does not block the entire queue.
|
| 56 |
-
23. As a user, I want the existing single-slip upload in the Add Expense drawer to continue working unchanged, so that quick one-off captures are not disrupted.
|
| 57 |
-
|
| 58 |
-
---
|
| 59 |
-
|
| 60 |
-
## Implementation Decisions
|
| 61 |
-
|
| 62 |
-
### 0. Architectural Approach — Hexagonal + Decorator + Strategy
|
| 63 |
-
|
| 64 |
-
All 3rd-party dependencies (database, LLM provider, image storage) sit behind **ports** (TypeScript interfaces defined in the domain layer). The domain core never imports an SDK or ORM directly. Concrete **adapters** implement those interfaces and live in a separate `adapters/` directory. A single **loader** file (`adapters/loader.ts`) is the only place that imports SDKs and wires adapters to the service — swapping a provider is a one-line change there.
|
| 65 |
-
|
| 66 |
-
**The three ports:**
|
| 67 |
-
|
| 68 |
-
```
|
| 69 |
-
ISlipQueueRepository — persist and query slip queue rows
|
| 70 |
-
IReceiptParser — parse a base64 image → ParsedExpense | null
|
| 71 |
-
IImageStore — save raw base64 and return a retrieval key (for future R2 swap)
|
| 72 |
-
```
|
| 73 |
-
|
| 74 |
-
**Adapters shipped with this feature:**
|
| 75 |
-
|
| 76 |
-
| Port | Adapter | Swappable with |
|
| 77 |
-
|------|---------|----------------|
|
| 78 |
-
| `ISlipQueueRepository` | `NeonSlipQueueRepository` | Supabase, SQLite, in-memory (tests) |
|
| 79 |
-
| `IReceiptParser` | `LLMRouterReceiptParser` | `GroqReceiptParser`, `OllamaDirectReceiptParser` |
|
| 80 |
-
| `IImageStore` | `Base64InlineImageStore` | `CloudflareR2ImageStore`, `HFDatasetImageStore` |
|
| 81 |
-
|
| 82 |
-
**Decorators (Strategy wrapping Strategy):**
|
| 83 |
-
|
| 84 |
-
Cross-cutting concerns wrap any `IReceiptParser` without touching the adapter or the service:
|
| 85 |
-
|
| 86 |
-
```
|
| 87 |
-
RateLimitDecorator(parser, { delayMs: 2000 }) — waits between calls
|
| 88 |
-
RetryDecorator(parser, { maxRetries: 3 }) — retries on transient errors
|
| 89 |
-
LoggingDecorator(parser) — logs input/output (optional)
|
| 90 |
-
```
|
| 91 |
-
|
| 92 |
-
Decorators are composable — the order in the loader controls behaviour:
|
| 93 |
-
|
| 94 |
-
```
|
| 95 |
-
RetryDecorator(
|
| 96 |
-
RateLimitDecorator(
|
| 97 |
-
LLMRouterReceiptParser(router),
|
| 98 |
-
{ delayMs: 2000 }
|
| 99 |
-
),
|
| 100 |
-
{ maxRetries: 3 }
|
| 101 |
-
)
|
| 102 |
-
```
|
| 103 |
-
|
| 104 |
-
**The loader (`adapters/loader.ts`):**
|
| 105 |
-
|
| 106 |
-
This is the only file that imports Neon, Drizzle, or any LLM SDK. Everything else only sees interfaces.
|
| 107 |
-
|
| 108 |
-
```
|
| 109 |
-
// To swap image storage to Cloudflare R2:
|
| 110 |
-
// change Base64InlineImageStore → CloudflareR2ImageStore here, nowhere else.
|
| 111 |
-
|
| 112 |
-
export const slipQueueService = new SlipQueueService(
|
| 113 |
-
new NeonSlipQueueRepository(db),
|
| 114 |
-
RetryDecorator(RateLimitDecorator(new LLMRouterReceiptParser(router), { delayMs: 2000 }), { maxRetries: 3 }),
|
| 115 |
-
new Base64InlineImageStore(),
|
| 116 |
-
)
|
| 117 |
-
```
|
| 118 |
-
|
| 119 |
-
The existing `LLMProvider` interface in `packages/llm-router` already follows this pattern — `LLMRouterReceiptParser` wraps it so the slip queue domain never knows which model is running.
|
| 120 |
-
|
| 121 |
-
---
|
| 122 |
-
|
| 123 |
-
### 1. `slip_queue` Database Table
|
| 124 |
-
|
| 125 |
-
New table added to the Drizzle schema alongside the existing `expenses` table.
|
| 126 |
-
|
| 127 |
-
Columns:
|
| 128 |
-
- `id` — UUID primary key
|
| 129 |
-
- `image_base64` — text (full base64-encoded image, stored in DB for simplicity; Cloudflare R2 migration is out of scope)
|
| 130 |
-
- `status` — enum: `pending` | `processing` | `success` | `failed` | `confirmed`
|
| 131 |
-
- `retry_count` — integer, default 0, max 3
|
| 132 |
-
- `parsed_result` — JSONB nullable; shape mirrors the existing LLM response: `{ amount, currency, date, merchant, category, confidence }`
|
| 133 |
-
- `error_message` — text nullable; last failure reason
|
| 134 |
-
- `created_at` — timestamp
|
| 135 |
-
- `processed_at` — timestamp nullable; set when processing completes (success or terminal failure)
|
| 136 |
-
|
| 137 |
-
Status transitions:
|
| 138 |
-
```
|
| 139 |
-
pending → processing → success → confirmed
|
| 140 |
-
↘ failed (retry_count < 3) → pending (auto-retry)
|
| 141 |
-
(retry_count = 3) → stays failed (manual retry resets count to 0)
|
| 142 |
-
```
|
| 143 |
-
|
| 144 |
-
No foreign key to `users` for now — the app uses a single-user JWT model. If multi-user is added later, a `user_id` column can be appended without breaking this schema.
|
| 145 |
-
|
| 146 |
-
### 2. SlipQueueService
|
| 147 |
-
|
| 148 |
-
Domain core. Depends only on `ISlipQueueRepository`, `IReceiptParser`, and `IImageStore` — no SDK imports.
|
| 149 |
-
|
| 150 |
-
Responsibilities:
|
| 151 |
-
- Fetch up to `limit` slips in `pending` status via `ISlipQueueRepository`, ordered by `created_at` ASC (FIFO)
|
| 152 |
-
- For each slip: set status → `processing`, call `IReceiptParser.parse(imageBase64)` (rate-limiting and retries are the decorator's concern, not the service's)
|
| 153 |
-
- On success: set status → `success`, write `parsed_result`, set `processed_at`
|
| 154 |
-
- On failure: increment `retry_count`; if `retry_count < 3` set status back to `pending` (decorator retried already, this is the outer failure); else set status → `failed`, write `error_message`
|
| 155 |
-
- Continue until no more pending slips or `limit` is reached; `limit` defaults to 20
|
| 156 |
-
- Each slip is processed to completion (including decorator retries) before moving to the next — no concurrency at the service level
|
| 157 |
-
|
| 158 |
-
### 3. SlipQueue API Routes
|
| 159 |
-
|
| 160 |
-
New route group mounted at `/v1/slip-queue`.
|
| 161 |
-
|
| 162 |
-
- `POST /v1/slip-queue` — accepts `{ images: string[] }` (array of base64 strings, max 50 per request); creates one `slip_queue` row per image with status `pending`; returns array of created IDs. Protected by existing `authMiddleware`.
|
| 163 |
-
- `GET /v1/slip-queue` — returns all slip queue items ordered by `created_at` DESC; includes status, parsed_result, error_message, retry_count, image_base64 (truncated to first 100 chars for the list view to keep payload small — full base64 for thumbnail served separately or included at full size, TBD based on payload size). Protected by `authMiddleware`.
|
| 164 |
-
- `POST /v1/slip-queue/process` — triggers `slipQueueService.processAll(limit)` via the loader-provided instance; protected by `INTERNAL_API_KEY` header rather than user JWT (called by GitHub Actions, not the browser). Returns `{ processed: number, succeeded: number, failed: number }`.
|
| 165 |
-
- `POST /v1/slip-queue/:id/retry` — resets `status` to `pending` and `retry_count` to 0 for a failed item; returns updated item. Protected by `authMiddleware`.
|
| 166 |
-
- `POST /v1/slip-queue/:id/confirm` — validates `parsed_result` exists; calls existing `createExpense()` service to insert into `expenses` table; sets slip status → `confirmed`. Returns the created `Expense`. Protected by `authMiddleware`.
|
| 167 |
-
- `DELETE /v1/slip-queue/:id` — hard-deletes the slip queue row. Protected by `authMiddleware`.
|
| 168 |
-
|
| 169 |
-
### 4. BulkUploadDrawer
|
| 170 |
-
|
| 171 |
-
Replaces the current "Upload" tab inside `AddExpenseDrawer` with a multi-file capable version. The Manual tab is unchanged.
|
| 172 |
-
|
| 173 |
-
Behaviour:
|
| 174 |
-
- File input accepts `image/*`, `multiple` attribute enabled
|
| 175 |
-
- Drag-and-drop zone accepts multiple files simultaneously
|
| 176 |
-
- On file selection: show thumbnail grid with file names and sizes; no parsing happens client-side
|
| 177 |
-
- "Upload & Queue" button: reads all selected files as base64, calls `POST /v1/slip-queue` with the array, then navigates to `/slip-queue`
|
| 178 |
-
- Upload progress shown as a simple count ("Uploading 12 of 20...")
|
| 179 |
-
- No per-image text description field in bulk mode (description can be edited in the review page if needed)
|
| 180 |
-
- Single-image flow (existing behaviour) is preserved when exactly one file is selected and the user clicks "Parse" instead of "Upload & Queue"
|
| 181 |
-
|
| 182 |
-
### 5. SlipReviewPage + `useSlipQueue` Hook
|
| 183 |
-
|
| 184 |
-
New route: `/slip-queue` added to the router alongside existing pages. Linked from the bottom nav and sidebar as "Slip Queue" (or "Review") with a badge showing pending count.
|
| 185 |
-
|
| 186 |
-
**`useSlipQueue` hook:**
|
| 187 |
-
- Calls `GET /v1/slip-queue` on mount
|
| 188 |
-
- While any item has status `pending` or `processing`: polls every 5 seconds via `setInterval`
|
| 189 |
-
- Stops polling when all items are in terminal states (`success`, `failed`, `confirmed`)
|
| 190 |
-
- Exposes: `items`, `loading`, `error`, `refresh`, `confirm(id, overrides?)`, `retry(id)`, `discard(id)`, `confirmAll()`
|
| 191 |
-
|
| 192 |
-
**SlipReviewPage layout:**
|
| 193 |
-
- Summary row at top: count chips for Pending / Processing / Parsed / Failed / Confirmed
|
| 194 |
-
- "Confirm all parsed" bulk action button (only shown when ≥1 item is in `success` state)
|
| 195 |
-
- Card grid (responsive: 1 col mobile, 2 col tablet, 3 col desktop)
|
| 196 |
-
- Each card shows:
|
| 197 |
-
- Image thumbnail (rendered from stored base64)
|
| 198 |
-
- Status badge with colour coding
|
| 199 |
-
- Parsed fields: amount + currency, merchant, date, category (with inline category picker for overrides)
|
| 200 |
-
- Error message if failed
|
| 201 |
-
- Retry count indicator (e.g. "2 / 3 attempts")
|
| 202 |
-
- Actions: Confirm (success state only), Retry (failed state only), Discard (any state)
|
| 203 |
-
- Confirmed items collapsed into a "Confirmed (N)" accordion at the bottom to keep active items prominent
|
| 204 |
-
|
| 205 |
-
### 6. GitHub Actions Cron Worker
|
| 206 |
-
|
| 207 |
-
File: `.github/workflows/slip-queue-worker.yml`
|
| 208 |
-
|
| 209 |
-
- Trigger: `schedule: - cron: '*/5 * * * *'` (every 5 minutes)
|
| 210 |
-
- Single step: HTTP POST to `${{ secrets.API_BASE_URL }}/v1/slip-queue/process` with header `x-internal-key: ${{ secrets.INTERNAL_API_KEY }}` and query param `?limit=20`
|
| 211 |
-
- Uses `curl` — no Node.js setup needed
|
| 212 |
-
- On non-2xx response: step fails, GitHub notifies via its default email notification for failed workflows
|
| 213 |
-
- Secrets required: `API_BASE_URL` (e.g. `https://clarassu-expense-api.hf.space`), `INTERNAL_API_KEY` (random string set in both GH secrets and HF Spaces env vars)
|
| 214 |
-
|
| 215 |
-
---
|
| 216 |
-
|
| 217 |
-
## Testing Decisions
|
| 218 |
-
|
| 219 |
-
No automated tests are in scope for this feature. The existing test suite (if any) should continue to pass. Manual testing checklist:
|
| 220 |
-
|
| 221 |
-
- Upload 5 images → all appear as Pending on review page
|
| 222 |
-
- Wait for GH Actions trigger → items transition to Processing then Parsed/Failed
|
| 223 |
-
- Confirm a parsed item → appears in expense list
|
| 224 |
-
- Retry a failed item → retry_count resets, item goes back to Pending
|
| 225 |
-
- After 3 automatic failures → item stays Failed, manual retry available
|
| 226 |
-
- Confirm all parsed → all success items move to Confirmed accordion
|
| 227 |
-
- Discard an item → removed from queue
|
| 228 |
-
- Single-slip flow in AddExpenseDrawer → unaffected
|
| 229 |
-
|
| 230 |
-
---
|
| 231 |
-
|
| 232 |
-
## Out of Scope
|
| 233 |
-
|
| 234 |
-
- PWA manifest and Web Share Target (installable app, share from phone gallery) — deferred
|
| 235 |
-
- External blob storage (Cloudflare R2, HF Datasets) for images — base64 in Neon DB for now
|
| 236 |
-
- Multi-user slip queues — single-user JWT model assumed
|
| 237 |
-
- Real-time WebSocket / Server-Sent Events — HTTP polling is sufficient given 5-minute worker cadence
|
| 238 |
-
- Concurrent LLM calls — Ollama free tier is sequential only
|
| 239 |
-
- Editing parsed fields beyond category override before confirm — users can edit the expense after confirming via the existing edit flow
|
| 240 |
-
- Automatic category correction via user feedback loop
|
| 241 |
-
- Slip queue expiry / cleanup policy (old confirmed/discarded slips)
|
| 242 |
-
|
| 243 |
-
---
|
| 244 |
-
|
| 245 |
-
## Further Notes
|
| 246 |
-
|
| 247 |
-
- **Image storage size:** Base64 encoding inflates image size by ~33%. A typical bank slip photo is 200–500 KB on disk → 270–670 KB as base64 in the DB. 100 slips ≈ 50 MB in Neon. Neon free tier is 512 MB storage — acceptable for personal use but worth monitoring. If storage becomes a concern, a Cloudflare R2 migration (store URL instead of base64) is a clean follow-up with minimal schema change (swap `image_base64` text column for `image_url` text column).
|
| 248 |
-
- **GH Actions rate limit for private repos:** Free tier = 500 min/month. At 5-min intervals, each run takes ~3–10s. 500 min ÷ (5s ÷ 60) = ~6,000 runs/month — well within limits even for a private repo.
|
| 249 |
-
- **Ollama cold start:** The first LLM call in a batch may take 15–30s if the model is not loaded. The SlipQueueService should use the same retry logic for cold-start timeouts as for other errors, so the slip gets re-queued rather than permanently failing.
|
| 250 |
-
- **`INTERNAL_API_KEY` security:** The process endpoint only mutates internal queue state and is not user-data-destructive, but it should still be protected to prevent abuse on the free-tier server.
|
| 251 |
-
- **Existing `POST /v1/expense/parse` endpoint:** Unchanged. The single-slip flow in `AddExpenseDrawer` continues to call it directly and bypasses the queue entirely.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
docs/superpowers/plans/2026-06-24-route-controller-service.md
DELETED
|
@@ -1,1272 +0,0 @@
|
|
| 1 |
-
# Route / Controller / Service Refactor — Implementation Plan
|
| 2 |
-
|
| 3 |
-
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
| 4 |
-
|
| 5 |
-
**Goal:** Refactor monolithic `proxy.ts` into feature-based routes/controllers/services with reusable Zod validation middleware, and rename `router.ts` → `llm-router.ts`.
|
| 6 |
-
|
| 7 |
-
**Architecture:** Ten sequential tasks. Each feature folder (`chat/`, `expense/`, `health/`) owns its routes, validator, controller, and services. `middleware/validate.ts` is a shared Zod factory used by all validators. `proxy.ts` shrinks to ~35-line bootstrap. Tasks 1–5 build shared infrastructure and expense internals (fully testable in isolation). Tasks 6–9 build controllers and routes. Task 10 wires everything and removes old code from `proxy.ts`.
|
| 8 |
-
|
| 9 |
-
**Tech Stack:** TypeScript 6 (strict, nodenext), Express 5, Zod, Vitest
|
| 10 |
-
|
| 11 |
-
## Global Constraints
|
| 12 |
-
|
| 13 |
-
- TypeScript strict: no `any`, `noImplicitReturns`, `noUnusedParameters`, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`
|
| 14 |
-
- Prefix unused Express params with `_` (e.g. `_req`) to satisfy `noUnusedParameters`
|
| 15 |
-
- Use `.slice(0, 10)` on ISO strings instead of `.split('T')[0]` — avoids `string | undefined` from `noUncheckedIndexedAccess`
|
| 16 |
-
- Use `?? fallback` everywhere array/record access might be `undefined`
|
| 17 |
-
- Zero logic changes to: `llm-router.ts`, `pii-scanner.ts`, `circuit-breaker.ts`, `logger.ts`, `websearch.ts`, `providers/*`, `middleware/authMiddleware.ts`
|
| 18 |
-
- All endpoints maintain existing request/response shapes exactly
|
| 19 |
-
- Tests run with `npm test` (vitest)
|
| 20 |
-
|
| 21 |
-
---
|
| 22 |
-
|
| 23 |
-
### Task 1: Install Zod + Vitest, rename router.ts → llm-router.ts
|
| 24 |
-
|
| 25 |
-
**Files:**
|
| 26 |
-
- Modify: `package.json`
|
| 27 |
-
- Create: `src/llm-router.ts` (copy of `src/router.ts`, no changes)
|
| 28 |
-
- Delete: `src/router.ts`
|
| 29 |
-
- Modify: `src/proxy.ts` line 3 — update import
|
| 30 |
-
- Modify: `src/index.ts` line 1 — update import
|
| 31 |
-
|
| 32 |
-
**Interfaces:**
|
| 33 |
-
- Produces: `src/llm-router.ts` — identical exports to current `src/router.ts`: `route(messages, model?, feature?): Promise<RouterResult>`, `RouterResult`, `EXPENSE_PARSE_PROMPT`
|
| 34 |
-
|
| 35 |
-
- [ ] **Step 1: Install dependencies**
|
| 36 |
-
|
| 37 |
-
```bash
|
| 38 |
-
npm install zod
|
| 39 |
-
npm install -D vitest
|
| 40 |
-
```
|
| 41 |
-
|
| 42 |
-
Expected: both packages added to `package.json`.
|
| 43 |
-
|
| 44 |
-
- [ ] **Step 2: Add test script to package.json**
|
| 45 |
-
|
| 46 |
-
In `package.json`, update the `"scripts"` block:
|
| 47 |
-
|
| 48 |
-
```json
|
| 49 |
-
"scripts": {
|
| 50 |
-
"build": "tsc",
|
| 51 |
-
"dev": "tsx watch src/proxy.ts",
|
| 52 |
-
"start": "node dist/proxy.js",
|
| 53 |
-
"test": "vitest run"
|
| 54 |
-
}
|
| 55 |
-
```
|
| 56 |
-
|
| 57 |
-
- [ ] **Step 3: Copy router.ts content into llm-router.ts**
|
| 58 |
-
|
| 59 |
-
Create `src/llm-router.ts` with the exact contents of `src/router.ts`. No logic changes.
|
| 60 |
-
|
| 61 |
-
- [ ] **Step 4: Delete src/router.ts**
|
| 62 |
-
|
| 63 |
-
```bash
|
| 64 |
-
rm src/router.ts
|
| 65 |
-
```
|
| 66 |
-
|
| 67 |
-
- [ ] **Step 5: Update import in src/proxy.ts**
|
| 68 |
-
|
| 69 |
-
Change line 3:
|
| 70 |
-
```ts
|
| 71 |
-
// before
|
| 72 |
-
import { route } from './router'
|
| 73 |
-
// after
|
| 74 |
-
import { route } from './llm-router'
|
| 75 |
-
```
|
| 76 |
-
|
| 77 |
-
- [ ] **Step 6: Update import in src/index.ts**
|
| 78 |
-
|
| 79 |
-
Change line 1:
|
| 80 |
-
```ts
|
| 81 |
-
// before
|
| 82 |
-
import { route } from "./router"
|
| 83 |
-
// after
|
| 84 |
-
import { route } from "./llm-router"
|
| 85 |
-
```
|
| 86 |
-
|
| 87 |
-
- [ ] **Step 7: Verify build passes**
|
| 88 |
-
|
| 89 |
-
```bash
|
| 90 |
-
npm run build
|
| 91 |
-
```
|
| 92 |
-
|
| 93 |
-
Expected: exits 0, no errors.
|
| 94 |
-
|
| 95 |
-
- [ ] **Step 8: Commit**
|
| 96 |
-
|
| 97 |
-
```bash
|
| 98 |
-
git add -A
|
| 99 |
-
git commit -m "refactor: rename router.ts to llm-router.ts, add zod + vitest"
|
| 100 |
-
```
|
| 101 |
-
|
| 102 |
-
---
|
| 103 |
-
|
| 104 |
-
### Task 2: Create `middleware/validate.ts`
|
| 105 |
-
|
| 106 |
-
**Files:**
|
| 107 |
-
- Create: `src/middleware/validate.ts`
|
| 108 |
-
- Create: `src/middleware/validate.test.ts`
|
| 109 |
-
|
| 110 |
-
**Interfaces:**
|
| 111 |
-
- Consumes: `ZodSchema` from `zod`; `Request, Response, NextFunction, RequestHandler` from `express`
|
| 112 |
-
- Produces: `validate(schema: ZodSchema): RequestHandler` — on invalid body returns `400 { error: string, details: ZodIssue[] }` and does NOT call `next()`; on valid body assigns `req.body = result.data` (coerced/defaulted) then calls `next()`
|
| 113 |
-
|
| 114 |
-
- [ ] **Step 1: Write the failing test**
|
| 115 |
-
|
| 116 |
-
Create `src/middleware/validate.test.ts`:
|
| 117 |
-
|
| 118 |
-
```ts
|
| 119 |
-
import { describe, it, expect, vi } from 'vitest'
|
| 120 |
-
import { z } from 'zod'
|
| 121 |
-
import { validate } from './validate'
|
| 122 |
-
import type { Request, Response, NextFunction } from 'express'
|
| 123 |
-
|
| 124 |
-
const schema = z.object({ name: z.string(), age: z.number() })
|
| 125 |
-
|
| 126 |
-
function makeReq(body: unknown): Request {
|
| 127 |
-
return { body } as unknown as Request
|
| 128 |
-
}
|
| 129 |
-
|
| 130 |
-
function makeRes() {
|
| 131 |
-
const res = { status: vi.fn(), json: vi.fn() }
|
| 132 |
-
res.status.mockReturnValue(res as unknown as Response)
|
| 133 |
-
return res
|
| 134 |
-
}
|
| 135 |
-
|
| 136 |
-
describe('validate', () => {
|
| 137 |
-
it('calls next() and assigns parsed body on valid input', () => {
|
| 138 |
-
const req = makeReq({ name: 'Su', age: 30 })
|
| 139 |
-
const res = makeRes()
|
| 140 |
-
const next = vi.fn() as unknown as NextFunction
|
| 141 |
-
|
| 142 |
-
validate(schema)(req, res as unknown as Response, next)
|
| 143 |
-
|
| 144 |
-
expect(next).toHaveBeenCalledOnce()
|
| 145 |
-
expect(req.body).toEqual({ name: 'Su', age: 30 })
|
| 146 |
-
expect(res.status).not.toHaveBeenCalled()
|
| 147 |
-
})
|
| 148 |
-
|
| 149 |
-
it('returns 400 with error details on invalid input', () => {
|
| 150 |
-
const req = makeReq({ name: 123 })
|
| 151 |
-
const res = makeRes()
|
| 152 |
-
const next = vi.fn() as unknown as NextFunction
|
| 153 |
-
|
| 154 |
-
validate(schema)(req, res as unknown as Response, next)
|
| 155 |
-
|
| 156 |
-
expect(res.status).toHaveBeenCalledWith(400)
|
| 157 |
-
expect(res.json).toHaveBeenCalledWith(
|
| 158 |
-
expect.objectContaining({ error: expect.any(String), details: expect.any(Array) })
|
| 159 |
-
)
|
| 160 |
-
expect(next).not.toHaveBeenCalled()
|
| 161 |
-
})
|
| 162 |
-
|
| 163 |
-
it('coerces Zod defaults into req.body', () => {
|
| 164 |
-
const schemaWithDefault = z.object({ model: z.string().default('smart-router') })
|
| 165 |
-
const req = makeReq({})
|
| 166 |
-
const res = makeRes()
|
| 167 |
-
const next = vi.fn() as unknown as NextFunction
|
| 168 |
-
|
| 169 |
-
validate(schemaWithDefault)(req, res as unknown as Response, next)
|
| 170 |
-
|
| 171 |
-
expect(next).toHaveBeenCalledOnce()
|
| 172 |
-
expect((req.body as { model: string }).model).toBe('smart-router')
|
| 173 |
-
})
|
| 174 |
-
})
|
| 175 |
-
```
|
| 176 |
-
|
| 177 |
-
- [ ] **Step 2: Run test to confirm it fails**
|
| 178 |
-
|
| 179 |
-
```bash
|
| 180 |
-
npm test -- middleware/validate.test.ts
|
| 181 |
-
```
|
| 182 |
-
|
| 183 |
-
Expected: FAIL — "Cannot find module './validate'"
|
| 184 |
-
|
| 185 |
-
- [ ] **Step 3: Implement validate.ts**
|
| 186 |
-
|
| 187 |
-
Create `src/middleware/validate.ts`:
|
| 188 |
-
|
| 189 |
-
```ts
|
| 190 |
-
import type { ZodSchema } from 'zod'
|
| 191 |
-
import type { Request, Response, NextFunction, RequestHandler } from 'express'
|
| 192 |
-
|
| 193 |
-
export const validate = (schema: ZodSchema): RequestHandler =>
|
| 194 |
-
(req: Request, res: Response, next: NextFunction): void => {
|
| 195 |
-
const result = schema.safeParse(req.body)
|
| 196 |
-
if (!result.success) {
|
| 197 |
-
res.status(400).json({
|
| 198 |
-
error: result.error.errors[0]?.message ?? 'Validation failed',
|
| 199 |
-
details: result.error.errors,
|
| 200 |
-
})
|
| 201 |
-
return
|
| 202 |
-
}
|
| 203 |
-
req.body = result.data
|
| 204 |
-
next()
|
| 205 |
-
}
|
| 206 |
-
```
|
| 207 |
-
|
| 208 |
-
- [ ] **Step 4: Run test to confirm it passes**
|
| 209 |
-
|
| 210 |
-
```bash
|
| 211 |
-
npm test -- middleware/validate.test.ts
|
| 212 |
-
```
|
| 213 |
-
|
| 214 |
-
Expected: 3 tests PASS
|
| 215 |
-
|
| 216 |
-
- [ ] **Step 5: Commit**
|
| 217 |
-
|
| 218 |
-
```bash
|
| 219 |
-
git add src/middleware/validate.ts src/middleware/validate.test.ts
|
| 220 |
-
git commit -m "feat: add reusable Zod validate middleware"
|
| 221 |
-
```
|
| 222 |
-
|
| 223 |
-
---
|
| 224 |
-
|
| 225 |
-
### Task 3: Create `expense/ocr.service.ts`
|
| 226 |
-
|
| 227 |
-
**Files:**
|
| 228 |
-
- Create: `src/expense/ocr.service.ts`
|
| 229 |
-
- Create: `src/expense/ocr.service.test.ts`
|
| 230 |
-
|
| 231 |
-
**Interfaces:**
|
| 232 |
-
- Produces: `extractTextFromImage(base64Image: string): Promise<string>` — strips data-URI prefix, runs Tesseract on the buffer, returns trimmed text; throws `Error('Image OCR failed…')` on any Tesseract failure
|
| 233 |
-
|
| 234 |
-
- [ ] **Step 1: Write the failing test**
|
| 235 |
-
|
| 236 |
-
Create `src/expense/ocr.service.test.ts`:
|
| 237 |
-
|
| 238 |
-
```ts
|
| 239 |
-
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
| 240 |
-
|
| 241 |
-
vi.mock('tesseract.js', () => ({
|
| 242 |
-
default: {
|
| 243 |
-
recognize: vi.fn().mockResolvedValue({ data: { text: ' ค่าอาหาร 350 บาท ' } }),
|
| 244 |
-
},
|
| 245 |
-
}))
|
| 246 |
-
|
| 247 |
-
describe('extractTextFromImage', () => {
|
| 248 |
-
beforeEach(() => vi.clearAllMocks())
|
| 249 |
-
|
| 250 |
-
it('returns trimmed OCR text', async () => {
|
| 251 |
-
const { extractTextFromImage } = await import('./ocr.service')
|
| 252 |
-
const result = await extractTextFromImage(Buffer.from('fake').toString('base64'))
|
| 253 |
-
expect(result).toBe('ค่าอาหาร 350 บาท')
|
| 254 |
-
})
|
| 255 |
-
|
| 256 |
-
it('strips data-URI prefix before decoding', async () => {
|
| 257 |
-
const Tesseract = await import('tesseract.js')
|
| 258 |
-
const { extractTextFromImage } = await import('./ocr.service')
|
| 259 |
-
const dataUri = 'data:image/png;base64,' + Buffer.from('fake').toString('base64')
|
| 260 |
-
await extractTextFromImage(dataUri)
|
| 261 |
-
const callArg = vi.mocked(Tesseract.default.recognize).mock.calls[0]?.[0]
|
| 262 |
-
expect(Buffer.isBuffer(callArg)).toBe(true)
|
| 263 |
-
})
|
| 264 |
-
|
| 265 |
-
it('throws user-friendly error when Tesseract fails', async () => {
|
| 266 |
-
const Tesseract = await import('tesseract.js')
|
| 267 |
-
vi.mocked(Tesseract.default.recognize).mockRejectedValueOnce(new Error('engine crash'))
|
| 268 |
-
const { extractTextFromImage } = await import('./ocr.service')
|
| 269 |
-
await expect(extractTextFromImage('abc')).rejects.toThrow('Image OCR failed')
|
| 270 |
-
})
|
| 271 |
-
})
|
| 272 |
-
```
|
| 273 |
-
|
| 274 |
-
- [ ] **Step 2: Run test to confirm it fails**
|
| 275 |
-
|
| 276 |
-
```bash
|
| 277 |
-
npm test -- expense/ocr.service.test.ts
|
| 278 |
-
```
|
| 279 |
-
|
| 280 |
-
Expected: FAIL — "Cannot find module './ocr.service'"
|
| 281 |
-
|
| 282 |
-
- [ ] **Step 3: Implement ocr.service.ts**
|
| 283 |
-
|
| 284 |
-
Create `src/expense/ocr.service.ts`:
|
| 285 |
-
|
| 286 |
-
```ts
|
| 287 |
-
export async function extractTextFromImage(base64Image: string): Promise<string> {
|
| 288 |
-
try {
|
| 289 |
-
const Tesseract = await import('tesseract.js')
|
| 290 |
-
const cleanBase64 = base64Image.replace(/^data:image\/\w+;base64,/, '')
|
| 291 |
-
const imageBuffer = Buffer.from(cleanBase64, 'base64')
|
| 292 |
-
|
| 293 |
-
const result = await Tesseract.default.recognize(imageBuffer, 'tha+eng', {
|
| 294 |
-
logger: (m: { status: string; progress: number }) => {
|
| 295 |
-
if (m.status === 'recognizing text') {
|
| 296 |
-
console.log(`[ocr] progress: ${Math.round(m.progress * 100)}%`)
|
| 297 |
-
}
|
| 298 |
-
},
|
| 299 |
-
})
|
| 300 |
-
|
| 301 |
-
return result.data.text.trim()
|
| 302 |
-
} catch (err: unknown) {
|
| 303 |
-
const message = err instanceof Error ? err.message : String(err)
|
| 304 |
-
console.error('[ocr] failed:', message)
|
| 305 |
-
throw new Error(
|
| 306 |
-
'Image OCR failed. Please type your expense as text instead. ' +
|
| 307 |
-
'Example: "Grab food 350 baht today"'
|
| 308 |
-
)
|
| 309 |
-
}
|
| 310 |
-
}
|
| 311 |
-
```
|
| 312 |
-
|
| 313 |
-
- [ ] **Step 4: Run test to confirm it passes**
|
| 314 |
-
|
| 315 |
-
```bash
|
| 316 |
-
npm test -- expense/ocr.service.test.ts
|
| 317 |
-
```
|
| 318 |
-
|
| 319 |
-
Expected: 3 tests PASS
|
| 320 |
-
|
| 321 |
-
- [ ] **Step 5: Commit**
|
| 322 |
-
|
| 323 |
-
```bash
|
| 324 |
-
git add src/expense/ocr.service.ts src/expense/ocr.service.test.ts
|
| 325 |
-
git commit -m "feat: extract OCR into expense/ocr.service"
|
| 326 |
-
```
|
| 327 |
-
|
| 328 |
-
---
|
| 329 |
-
|
| 330 |
-
### Task 4: Create `expense/expense.service.ts`
|
| 331 |
-
|
| 332 |
-
**Files:**
|
| 333 |
-
- Create: `src/expense/expense.service.ts`
|
| 334 |
-
- Create: `src/expense/expense.service.test.ts`
|
| 335 |
-
|
| 336 |
-
**Interfaces:**
|
| 337 |
-
- Produces:
|
| 338 |
-
- `ParsedExpense` interface: `{ amount: number; currency: string; date: string | null; merchant: string | null; category: string; confidence: number; raw_description: string }`
|
| 339 |
-
- `parseExpenseJSON(raw: string): ParsedExpense | null`
|
| 340 |
-
- `fixDate(expense: ParsedExpense): ParsedExpense`
|
| 341 |
-
- `formatExpenseMessage(expense: ParsedExpense, saved: boolean): string`
|
| 342 |
-
- `triggerN8N(expense: ParsedExpense, source: string, rawText: string): Promise<void>`
|
| 343 |
-
|
| 344 |
-
- [ ] **Step 1: Write the failing test**
|
| 345 |
-
|
| 346 |
-
Create `src/expense/expense.service.test.ts`:
|
| 347 |
-
|
| 348 |
-
```ts
|
| 349 |
-
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
| 350 |
-
import { parseExpenseJSON, fixDate, formatExpenseMessage } from './expense.service'
|
| 351 |
-
|
| 352 |
-
const base = {
|
| 353 |
-
amount: 350,
|
| 354 |
-
currency: 'THB',
|
| 355 |
-
date: '2026-06-24' as string | null,
|
| 356 |
-
merchant: 'Grab' as string | null,
|
| 357 |
-
category: 'food',
|
| 358 |
-
confidence: 0.9,
|
| 359 |
-
raw_description: 'Grab food',
|
| 360 |
-
}
|
| 361 |
-
|
| 362 |
-
describe('parseExpenseJSON', () => {
|
| 363 |
-
it('extracts and parses JSON embedded in model prose', () => {
|
| 364 |
-
const raw = 'Here is your result: {"amount":350,"currency":"THB","date":"2026-06-24","merchant":"Grab","category":"food","confidence":0.9,"raw_description":"Grab food"}'
|
| 365 |
-
const result = parseExpenseJSON(raw)
|
| 366 |
-
expect(result).not.toBeNull()
|
| 367 |
-
expect(result?.amount).toBe(350)
|
| 368 |
-
expect(result?.category).toBe('food')
|
| 369 |
-
})
|
| 370 |
-
|
| 371 |
-
it('returns null when response has no JSON', () => {
|
| 372 |
-
expect(parseExpenseJSON('Could not parse')).toBeNull()
|
| 373 |
-
})
|
| 374 |
-
|
| 375 |
-
it('returns null when JSON is malformed', () => {
|
| 376 |
-
expect(parseExpenseJSON('{ broken : json }')).toBeNull()
|
| 377 |
-
})
|
| 378 |
-
|
| 379 |
-
it('coerces amount to number', () => {
|
| 380 |
-
const raw = '{"amount":"350","currency":"THB","date":null,"merchant":null,"category":"food","confidence":0.9,"raw_description":"food"}'
|
| 381 |
-
const result = parseExpenseJSON(raw)
|
| 382 |
-
expect(typeof result?.amount).toBe('number')
|
| 383 |
-
})
|
| 384 |
-
})
|
| 385 |
-
|
| 386 |
-
describe('fixDate', () => {
|
| 387 |
-
beforeEach(() => {
|
| 388 |
-
vi.useFakeTimers()
|
| 389 |
-
vi.setSystemTime(new Date('2026-06-24'))
|
| 390 |
-
})
|
| 391 |
-
afterEach(() => vi.useRealTimers())
|
| 392 |
-
|
| 393 |
-
it('fills null date with today', () => {
|
| 394 |
-
const result = fixDate({ ...base, date: null })
|
| 395 |
-
expect(result.date).toBe('2026-06-24')
|
| 396 |
-
})
|
| 397 |
-
|
| 398 |
-
it('corrects a stale year to current year', () => {
|
| 399 |
-
const result = fixDate({ ...base, date: '2024-06-24' })
|
| 400 |
-
expect(result.date).toBe('2026-06-24')
|
| 401 |
-
})
|
| 402 |
-
|
| 403 |
-
it('leaves a valid current-year date unchanged', () => {
|
| 404 |
-
const result = fixDate({ ...base, date: '2026-03-15' })
|
| 405 |
-
expect(result.date).toBe('2026-03-15')
|
| 406 |
-
})
|
| 407 |
-
})
|
| 408 |
-
|
| 409 |
-
describe('formatExpenseMessage', () => {
|
| 410 |
-
it('includes amount, category, and merchant', () => {
|
| 411 |
-
const msg = formatExpenseMessage(base, true)
|
| 412 |
-
expect(msg).toContain('350')
|
| 413 |
-
expect(msg).toContain('food')
|
| 414 |
-
expect(msg).toContain('Grab')
|
| 415 |
-
})
|
| 416 |
-
|
| 417 |
-
it('shows saved confirmation when saved=true', () => {
|
| 418 |
-
expect(formatExpenseMessage(base, true)).toContain('✅')
|
| 419 |
-
})
|
| 420 |
-
|
| 421 |
-
it('shows warning when saved=false', () => {
|
| 422 |
-
expect(formatExpenseMessage(base, false)).toContain('⚠️')
|
| 423 |
-
})
|
| 424 |
-
})
|
| 425 |
-
```
|
| 426 |
-
|
| 427 |
-
- [ ] **Step 2: Run test to confirm it fails**
|
| 428 |
-
|
| 429 |
-
```bash
|
| 430 |
-
npm test -- expense/expense.service.test.ts
|
| 431 |
-
```
|
| 432 |
-
|
| 433 |
-
Expected: FAIL — "Cannot find module './expense.service'"
|
| 434 |
-
|
| 435 |
-
- [ ] **Step 3: Implement expense.service.ts**
|
| 436 |
-
|
| 437 |
-
Create `src/expense/expense.service.ts`:
|
| 438 |
-
|
| 439 |
-
```ts
|
| 440 |
-
export interface ParsedExpense {
|
| 441 |
-
amount: number
|
| 442 |
-
currency: string
|
| 443 |
-
date: string | null
|
| 444 |
-
merchant: string | null
|
| 445 |
-
category: string
|
| 446 |
-
confidence: number
|
| 447 |
-
raw_description: string
|
| 448 |
-
}
|
| 449 |
-
|
| 450 |
-
const CATEGORY_EMOJI: Record<string, string> = {
|
| 451 |
-
food: '🍔', transport: '🚗', shopping: '🛍️',
|
| 452 |
-
bills: '📱', rental_electricity: '🏠', gym: '🏋️',
|
| 453 |
-
health: '💊', transfer: '💝', emergency: '🚨',
|
| 454 |
-
pet: '🐾', maid: '🧹', entertainment: '🎬',
|
| 455 |
-
su_personal: '👤', tz_personal: '👤', other: '📦',
|
| 456 |
-
}
|
| 457 |
-
|
| 458 |
-
export function parseExpenseJSON(raw: string): ParsedExpense | null {
|
| 459 |
-
const match = raw.match(/\{[\s\S]*\}/)
|
| 460 |
-
const jsonStr = match?.[0]
|
| 461 |
-
if (!jsonStr) return null
|
| 462 |
-
try {
|
| 463 |
-
const parsed = JSON.parse(jsonStr) as ParsedExpense
|
| 464 |
-
return { ...parsed, amount: Number(parsed.amount) }
|
| 465 |
-
} catch {
|
| 466 |
-
return null
|
| 467 |
-
}
|
| 468 |
-
}
|
| 469 |
-
|
| 470 |
-
export function fixDate(expense: ParsedExpense): ParsedExpense {
|
| 471 |
-
const currentYear = new Date().getFullYear()
|
| 472 |
-
|
| 473 |
-
if (!expense.date) {
|
| 474 |
-
return { ...expense, date: new Date().toISOString().slice(0, 10) }
|
| 475 |
-
}
|
| 476 |
-
|
| 477 |
-
const yearStr = expense.date.split('-')[0] ?? '0'
|
| 478 |
-
const parsedYear = parseInt(yearStr, 10)
|
| 479 |
-
if (parsedYear < currentYear - 1) {
|
| 480 |
-
return { ...expense, date: expense.date.replace(yearStr, String(currentYear)) }
|
| 481 |
-
}
|
| 482 |
-
|
| 483 |
-
return expense
|
| 484 |
-
}
|
| 485 |
-
|
| 486 |
-
export function formatExpenseMessage(expense: ParsedExpense, saved: boolean): string {
|
| 487 |
-
const emoji = CATEGORY_EMOJI[expense.category] ?? '📦'
|
| 488 |
-
return `${emoji} **Expense Recorded!**
|
| 489 |
-
|
| 490 |
-
| Field | Value |
|
| 491 |
-
|-------|-------|
|
| 492 |
-
| Amount | ฿${expense.amount.toLocaleString()} |
|
| 493 |
-
| Category | ${expense.category} |
|
| 494 |
-
| Merchant | ${expense.merchant ?? 'Unknown'} |
|
| 495 |
-
| Date | ${expense.date ?? 'Unknown'} |
|
| 496 |
-
| Confidence | ${Math.round(expense.confidence * 100)}% |
|
| 497 |
-
|
| 498 |
-
${saved ? '✅ Automatically saved to your expense tracker!' : '⚠️ Auto-save not configured.'}`
|
| 499 |
-
}
|
| 500 |
-
|
| 501 |
-
export async function triggerN8N(
|
| 502 |
-
expense: ParsedExpense,
|
| 503 |
-
source: string,
|
| 504 |
-
rawText: string
|
| 505 |
-
): Promise<void> {
|
| 506 |
-
const webhookUrl = process.env['N8N_WEBHOOK_URL']
|
| 507 |
-
if (!webhookUrl) return
|
| 508 |
-
try {
|
| 509 |
-
await fetch(webhookUrl, {
|
| 510 |
-
method: 'POST',
|
| 511 |
-
headers: { 'Content-Type': 'application/json' },
|
| 512 |
-
body: JSON.stringify({ text: rawText, expense, source }),
|
| 513 |
-
signal: AbortSignal.timeout(10000),
|
| 514 |
-
})
|
| 515 |
-
console.log('[n8n] workflow triggered successfully')
|
| 516 |
-
} catch (err: unknown) {
|
| 517 |
-
console.warn('[n8n] trigger failed (non-blocking):', err instanceof Error ? err.message : String(err))
|
| 518 |
-
}
|
| 519 |
-
}
|
| 520 |
-
```
|
| 521 |
-
|
| 522 |
-
- [ ] **Step 4: Run test to confirm it passes**
|
| 523 |
-
|
| 524 |
-
```bash
|
| 525 |
-
npm test -- expense/expense.service.test.ts
|
| 526 |
-
```
|
| 527 |
-
|
| 528 |
-
Expected: 7 tests PASS
|
| 529 |
-
|
| 530 |
-
- [ ] **Step 5: Commit**
|
| 531 |
-
|
| 532 |
-
```bash
|
| 533 |
-
git add src/expense/expense.service.ts src/expense/expense.service.test.ts
|
| 534 |
-
git commit -m "feat: extract expense business logic into expense.service"
|
| 535 |
-
```
|
| 536 |
-
|
| 537 |
-
---
|
| 538 |
-
|
| 539 |
-
### Task 5: Create `expense/expense.validator.ts`
|
| 540 |
-
|
| 541 |
-
**Files:**
|
| 542 |
-
- Create: `src/expense/expense.validator.ts`
|
| 543 |
-
- Create: `src/expense/expense.validator.test.ts`
|
| 544 |
-
|
| 545 |
-
**Interfaces:**
|
| 546 |
-
- Consumes: `validate` from `src/middleware/validate.ts`
|
| 547 |
-
- Produces: `ExpenseInput` type; `validateExpense: RequestHandler`
|
| 548 |
-
|
| 549 |
-
- [ ] **Step 1: Write the failing test**
|
| 550 |
-
|
| 551 |
-
Create `src/expense/expense.validator.test.ts`:
|
| 552 |
-
|
| 553 |
-
```ts
|
| 554 |
-
import { describe, it, expect, vi } from 'vitest'
|
| 555 |
-
import type { Request, Response, NextFunction } from 'express'
|
| 556 |
-
import { validateExpense } from './expense.validator'
|
| 557 |
-
|
| 558 |
-
function makeReq(body: unknown): Request {
|
| 559 |
-
return { body } as unknown as Request
|
| 560 |
-
}
|
| 561 |
-
function makeRes() {
|
| 562 |
-
const res = { status: vi.fn(), json: vi.fn() }
|
| 563 |
-
res.status.mockReturnValue(res as unknown as Response)
|
| 564 |
-
return res
|
| 565 |
-
}
|
| 566 |
-
|
| 567 |
-
describe('validateExpense', () => {
|
| 568 |
-
it('passes through with text field', () => {
|
| 569 |
-
const req = makeReq({ text: 'Grab food 350 baht' })
|
| 570 |
-
const next = vi.fn() as unknown as NextFunction
|
| 571 |
-
validateExpense(req, makeRes() as unknown as Response, next)
|
| 572 |
-
expect(next).toHaveBeenCalledOnce()
|
| 573 |
-
})
|
| 574 |
-
|
| 575 |
-
it('passes through with image field', () => {
|
| 576 |
-
const req = makeReq({ image: 'base64data' })
|
| 577 |
-
const next = vi.fn() as unknown as NextFunction
|
| 578 |
-
validateExpense(req, makeRes() as unknown as Response, next)
|
| 579 |
-
expect(next).toHaveBeenCalledOnce()
|
| 580 |
-
})
|
| 581 |
-
|
| 582 |
-
it('passes through with empty body (controller handles missing text)', () => {
|
| 583 |
-
const req = makeReq({})
|
| 584 |
-
const next = vi.fn() as unknown as NextFunction
|
| 585 |
-
validateExpense(req, makeRes() as unknown as Response, next)
|
| 586 |
-
expect(next).toHaveBeenCalledOnce()
|
| 587 |
-
})
|
| 588 |
-
|
| 589 |
-
it('returns 400 when text is not a string', () => {
|
| 590 |
-
const req = makeReq({ text: 123 })
|
| 591 |
-
const res = makeRes()
|
| 592 |
-
const next = vi.fn() as unknown as NextFunction
|
| 593 |
-
validateExpense(req, res as unknown as Response, next)
|
| 594 |
-
expect(res.status).toHaveBeenCalledWith(400)
|
| 595 |
-
expect(next).not.toHaveBeenCalled()
|
| 596 |
-
})
|
| 597 |
-
})
|
| 598 |
-
```
|
| 599 |
-
|
| 600 |
-
- [ ] **Step 2: Run test to confirm it fails**
|
| 601 |
-
|
| 602 |
-
```bash
|
| 603 |
-
npm test -- expense/expense.validator.test.ts
|
| 604 |
-
```
|
| 605 |
-
|
| 606 |
-
Expected: FAIL — "Cannot find module './expense.validator'"
|
| 607 |
-
|
| 608 |
-
- [ ] **Step 3: Implement expense.validator.ts**
|
| 609 |
-
|
| 610 |
-
Create `src/expense/expense.validator.ts`:
|
| 611 |
-
|
| 612 |
-
```ts
|
| 613 |
-
import { z } from 'zod'
|
| 614 |
-
import { validate } from '../middleware/validate'
|
| 615 |
-
|
| 616 |
-
const expenseSchema = z
|
| 617 |
-
.object({
|
| 618 |
-
text: z.string().optional(),
|
| 619 |
-
message: z.string().optional(),
|
| 620 |
-
content: z.string().optional(),
|
| 621 |
-
image: z.string().optional(),
|
| 622 |
-
imageBase64: z.string().optional(),
|
| 623 |
-
body: z.record(z.unknown()).optional(),
|
| 624 |
-
data: z.record(z.unknown()).optional(),
|
| 625 |
-
})
|
| 626 |
-
.passthrough()
|
| 627 |
-
|
| 628 |
-
export type ExpenseInput = z.infer<typeof expenseSchema>
|
| 629 |
-
|
| 630 |
-
export const validateExpense = validate(expenseSchema)
|
| 631 |
-
```
|
| 632 |
-
|
| 633 |
-
- [ ] **Step 4: Run test to confirm it passes**
|
| 634 |
-
|
| 635 |
-
```bash
|
| 636 |
-
npm test -- expense/expense.validator.test.ts
|
| 637 |
-
```
|
| 638 |
-
|
| 639 |
-
Expected: 4 tests PASS
|
| 640 |
-
|
| 641 |
-
- [ ] **Step 5: Commit**
|
| 642 |
-
|
| 643 |
-
```bash
|
| 644 |
-
git add src/expense/expense.validator.ts src/expense/expense.validator.test.ts
|
| 645 |
-
git commit -m "feat: add Zod validator for expense parse endpoint"
|
| 646 |
-
```
|
| 647 |
-
|
| 648 |
-
---
|
| 649 |
-
|
| 650 |
-
### Task 6: Create `expense/expense.controller.ts` + `expense/expense.routes.ts`
|
| 651 |
-
|
| 652 |
-
**Files:**
|
| 653 |
-
- Create: `src/expense/expense.controller.ts`
|
| 654 |
-
- Create: `src/expense/expense.routes.ts`
|
| 655 |
-
|
| 656 |
-
**Interfaces:**
|
| 657 |
-
- Consumes:
|
| 658 |
-
- `route(messages, model)` from `../llm-router` — signature: `route(messages: SimpleMessage[], model?: string): Promise<RouterResult>`
|
| 659 |
-
- `extractTextFromImage(base64)` from `./ocr.service`
|
| 660 |
-
- `parseExpenseJSON`, `fixDate`, `formatExpenseMessage`, `triggerN8N` from `./expense.service`
|
| 661 |
-
- `validateExpense` from `./expense.validator`
|
| 662 |
-
- `ExpenseInput` type from `./expense.validator`
|
| 663 |
-
- Produces: `expenseRouter` — Express Router to be mounted at `/v1/expense` in `proxy.ts`
|
| 664 |
-
|
| 665 |
-
- [ ] **Step 1: Write expense.controller.ts**
|
| 666 |
-
|
| 667 |
-
Create `src/expense/expense.controller.ts`:
|
| 668 |
-
|
| 669 |
-
```ts
|
| 670 |
-
import type { Request, Response } from 'express'
|
| 671 |
-
import { route } from '../llm-router'
|
| 672 |
-
import { extractTextFromImage } from './ocr.service'
|
| 673 |
-
import { parseExpenseJSON, fixDate, formatExpenseMessage, triggerN8N } from './expense.service'
|
| 674 |
-
import type { ExpenseInput } from './expense.validator'
|
| 675 |
-
|
| 676 |
-
export async function parseExpense(req: Request, res: Response): Promise<void> {
|
| 677 |
-
try {
|
| 678 |
-
const body = req.body as ExpenseInput
|
| 679 |
-
|
| 680 |
-
const bodyNested = body.body as Record<string, unknown> | undefined
|
| 681 |
-
const bodyNested2 = bodyNested?.['body'] as Record<string, unknown> | undefined
|
| 682 |
-
const dataNested = body.data as Record<string, unknown> | undefined
|
| 683 |
-
|
| 684 |
-
const expenseText =
|
| 685 |
-
body.text ??
|
| 686 |
-
(bodyNested?.['text'] as string | undefined) ??
|
| 687 |
-
(bodyNested2?.['text'] as string | undefined) ??
|
| 688 |
-
(dataNested?.['text'] as string | undefined) ??
|
| 689 |
-
body.message ??
|
| 690 |
-
body.content
|
| 691 |
-
|
| 692 |
-
const imageBase64 =
|
| 693 |
-
body.image ??
|
| 694 |
-
(bodyNested?.['image'] as string | undefined) ??
|
| 695 |
-
body.imageBase64
|
| 696 |
-
|
| 697 |
-
console.log('[expense/parse] body keys:', Object.keys(body))
|
| 698 |
-
console.log('[expense/parse] text:', expenseText?.substring(0, 100))
|
| 699 |
-
console.log('[expense/parse] has image:', !!imageBase64)
|
| 700 |
-
|
| 701 |
-
let finalText = expenseText
|
| 702 |
-
|
| 703 |
-
if (!finalText && imageBase64) {
|
| 704 |
-
console.log('[expense/parse] running OCR...')
|
| 705 |
-
finalText = await extractTextFromImage(imageBase64)
|
| 706 |
-
}
|
| 707 |
-
|
| 708 |
-
if (!finalText || typeof finalText !== 'string' || finalText.trim().length === 0) {
|
| 709 |
-
res.status(400).json({
|
| 710 |
-
success: false,
|
| 711 |
-
error: 'Could not find text in request body',
|
| 712 |
-
receivedKeys: Object.keys(body),
|
| 713 |
-
expectedFormats: [
|
| 714 |
-
'{ "text": "350 baht food" }',
|
| 715 |
-
'{ "body": { "text": "350 baht food" } }',
|
| 716 |
-
'{ "image": "base64encodedimage..." }',
|
| 717 |
-
],
|
| 718 |
-
})
|
| 719 |
-
return
|
| 720 |
-
}
|
| 721 |
-
|
| 722 |
-
const result = await route([{ role: 'user', content: finalText }], 'expense-parser')
|
| 723 |
-
const expense = parseExpenseJSON(result.response)
|
| 724 |
-
|
| 725 |
-
if (!expense) {
|
| 726 |
-
res.status(422).json({ success: false, error: 'Model did not return valid JSON', raw: result.response })
|
| 727 |
-
return
|
| 728 |
-
}
|
| 729 |
-
|
| 730 |
-
if (!expense.amount || isNaN(expense.amount)) {
|
| 731 |
-
res.status(422).json({
|
| 732 |
-
success: false,
|
| 733 |
-
error: 'Could not extract a valid amount from text',
|
| 734 |
-
parsed: expense,
|
| 735 |
-
tip: 'Make sure the text includes a clear amount e.g. "350 baht" or "฿350"',
|
| 736 |
-
})
|
| 737 |
-
return
|
| 738 |
-
}
|
| 739 |
-
|
| 740 |
-
const fixed = fixDate(expense)
|
| 741 |
-
if (!fixed.category) fixed.category = 'other'
|
| 742 |
-
|
| 743 |
-
const hasSave = !!process.env['N8N_WEBHOOK_URL'] && !!fixed.amount
|
| 744 |
-
if (hasSave) void triggerN8N(fixed, 'openwebui', finalText)
|
| 745 |
-
|
| 746 |
-
console.log('[expense/parse] success:', {
|
| 747 |
-
amount: fixed.amount, category: fixed.category,
|
| 748 |
-
merchant: fixed.merchant, date: fixed.date, confidence: fixed.confidence,
|
| 749 |
-
})
|
| 750 |
-
|
| 751 |
-
res.json({ success: true, expense: fixed, usedModel: result.usedModel, ocrUsed: !!imageBase64 })
|
| 752 |
-
} catch (err: unknown) {
|
| 753 |
-
const message = err instanceof Error ? err.message : String(err)
|
| 754 |
-
console.error('[expense/parse] error:', message)
|
| 755 |
-
res.status(500).json({ success: false, error: message })
|
| 756 |
-
}
|
| 757 |
-
}
|
| 758 |
-
```
|
| 759 |
-
|
| 760 |
-
- [ ] **Step 2: Write expense.routes.ts**
|
| 761 |
-
|
| 762 |
-
Create `src/expense/expense.routes.ts`:
|
| 763 |
-
|
| 764 |
-
```ts
|
| 765 |
-
import { Router } from 'express'
|
| 766 |
-
import { validateExpense } from './expense.validator'
|
| 767 |
-
import { parseExpense } from './expense.controller'
|
| 768 |
-
|
| 769 |
-
const router = Router()
|
| 770 |
-
|
| 771 |
-
router.post('/parse', validateExpense, parseExpense)
|
| 772 |
-
|
| 773 |
-
export { router as expenseRouter }
|
| 774 |
-
```
|
| 775 |
-
|
| 776 |
-
- [ ] **Step 3: Verify build**
|
| 777 |
-
|
| 778 |
-
```bash
|
| 779 |
-
npm run build
|
| 780 |
-
```
|
| 781 |
-
|
| 782 |
-
Expected: exits 0.
|
| 783 |
-
|
| 784 |
-
- [ ] **Step 4: Commit**
|
| 785 |
-
|
| 786 |
-
```bash
|
| 787 |
-
git add src/expense/expense.controller.ts src/expense/expense.routes.ts
|
| 788 |
-
git commit -m "feat: add expense controller and routes"
|
| 789 |
-
```
|
| 790 |
-
|
| 791 |
-
---
|
| 792 |
-
|
| 793 |
-
### Task 7: Create `chat/chat.validator.ts`
|
| 794 |
-
|
| 795 |
-
**Files:**
|
| 796 |
-
- Create: `src/chat/chat.validator.ts`
|
| 797 |
-
- Create: `src/chat/chat.validator.test.ts`
|
| 798 |
-
|
| 799 |
-
**Interfaces:**
|
| 800 |
-
- Consumes: `validate` from `../middleware/validate`
|
| 801 |
-
- Produces: `ChatInput` type with `{ messages: Array<{role: string, content: string | ContentPart[]}>, model: string, stream: boolean }`; `validateChat: RequestHandler`
|
| 802 |
-
|
| 803 |
-
- [ ] **Step 1: Write the failing test**
|
| 804 |
-
|
| 805 |
-
Create `src/chat/chat.validator.test.ts`:
|
| 806 |
-
|
| 807 |
-
```ts
|
| 808 |
-
import { describe, it, expect, vi } from 'vitest'
|
| 809 |
-
import type { Request, Response, NextFunction } from 'express'
|
| 810 |
-
import { validateChat } from './chat.validator'
|
| 811 |
-
|
| 812 |
-
function makeReq(body: unknown): Request {
|
| 813 |
-
return { body } as unknown as Request
|
| 814 |
-
}
|
| 815 |
-
function makeRes() {
|
| 816 |
-
const res = { status: vi.fn(), json: vi.fn() }
|
| 817 |
-
res.status.mockReturnValue(res as unknown as Response)
|
| 818 |
-
return res
|
| 819 |
-
}
|
| 820 |
-
|
| 821 |
-
describe('validateChat', () => {
|
| 822 |
-
it('passes with a valid messages array', () => {
|
| 823 |
-
const req = makeReq({ messages: [{ role: 'user', content: 'Hello' }] })
|
| 824 |
-
const next = vi.fn() as unknown as NextFunction
|
| 825 |
-
validateChat(req, makeRes() as unknown as Response, next)
|
| 826 |
-
expect(next).toHaveBeenCalledOnce()
|
| 827 |
-
})
|
| 828 |
-
|
| 829 |
-
it('defaults model to "smart-router" when omitted', () => {
|
| 830 |
-
const req = makeReq({ messages: [{ role: 'user', content: 'Hi' }] })
|
| 831 |
-
const next = vi.fn() as unknown as NextFunction
|
| 832 |
-
validateChat(req, makeRes() as unknown as Response, next)
|
| 833 |
-
expect(next).toHaveBeenCalledOnce()
|
| 834 |
-
expect((req.body as { model: string }).model).toBe('smart-router')
|
| 835 |
-
})
|
| 836 |
-
|
| 837 |
-
it('defaults stream to false when omitted', () => {
|
| 838 |
-
const req = makeReq({ messages: [{ role: 'user', content: 'Hi' }] })
|
| 839 |
-
const next = vi.fn() as unknown as NextFunction
|
| 840 |
-
validateChat(req, makeRes() as unknown as Response, next)
|
| 841 |
-
expect((req.body as { stream: boolean }).stream).toBe(false)
|
| 842 |
-
})
|
| 843 |
-
|
| 844 |
-
it('returns 400 for empty messages array', () => {
|
| 845 |
-
const req = makeReq({ messages: [] })
|
| 846 |
-
const res = makeRes()
|
| 847 |
-
validateChat(req, res as unknown as Response, vi.fn() as unknown as NextFunction)
|
| 848 |
-
expect(res.status).toHaveBeenCalledWith(400)
|
| 849 |
-
})
|
| 850 |
-
|
| 851 |
-
it('returns 400 when messages is missing', () => {
|
| 852 |
-
const req = makeReq({})
|
| 853 |
-
const res = makeRes()
|
| 854 |
-
validateChat(req, res as unknown as Response, vi.fn() as unknown as NextFunction)
|
| 855 |
-
expect(res.status).toHaveBeenCalledWith(400)
|
| 856 |
-
})
|
| 857 |
-
|
| 858 |
-
it('accepts image_url content array (OpenWebUI multipart messages)', () => {
|
| 859 |
-
const req = makeReq({
|
| 860 |
-
messages: [{
|
| 861 |
-
role: 'user',
|
| 862 |
-
content: [{ type: 'image_url', image_url: { url: 'data:image/png;base64,abc' } }],
|
| 863 |
-
}],
|
| 864 |
-
})
|
| 865 |
-
const next = vi.fn() as unknown as NextFunction
|
| 866 |
-
validateChat(req, makeRes() as unknown as Response, next)
|
| 867 |
-
expect(next).toHaveBeenCalledOnce()
|
| 868 |
-
})
|
| 869 |
-
})
|
| 870 |
-
```
|
| 871 |
-
|
| 872 |
-
- [ ] **Step 2: Run test to confirm it fails**
|
| 873 |
-
|
| 874 |
-
```bash
|
| 875 |
-
npm test -- chat/chat.validator.test.ts
|
| 876 |
-
```
|
| 877 |
-
|
| 878 |
-
Expected: FAIL — "Cannot find module './chat.validator'"
|
| 879 |
-
|
| 880 |
-
- [ ] **Step 3: Implement chat.validator.ts**
|
| 881 |
-
|
| 882 |
-
Create `src/chat/chat.validator.ts`:
|
| 883 |
-
|
| 884 |
-
```ts
|
| 885 |
-
import { z } from 'zod'
|
| 886 |
-
import { validate } from '../middleware/validate'
|
| 887 |
-
|
| 888 |
-
const ContentPart = z.object({
|
| 889 |
-
type: z.string(),
|
| 890 |
-
text: z.string().optional(),
|
| 891 |
-
image_url: z.object({ url: z.string() }).optional(),
|
| 892 |
-
})
|
| 893 |
-
|
| 894 |
-
const chatSchema = z.object({
|
| 895 |
-
messages: z
|
| 896 |
-
.array(
|
| 897 |
-
z.object({
|
| 898 |
-
role: z.string(),
|
| 899 |
-
content: z.union([z.string(), z.array(ContentPart)]),
|
| 900 |
-
})
|
| 901 |
-
)
|
| 902 |
-
.min(1, 'messages must be a non-empty array'),
|
| 903 |
-
model: z.string().optional().default('smart-router'),
|
| 904 |
-
stream: z.boolean().optional().default(false),
|
| 905 |
-
})
|
| 906 |
-
|
| 907 |
-
export type ChatInput = z.infer<typeof chatSchema>
|
| 908 |
-
|
| 909 |
-
export const validateChat = validate(chatSchema)
|
| 910 |
-
```
|
| 911 |
-
|
| 912 |
-
- [ ] **Step 4: Run test to confirm it passes**
|
| 913 |
-
|
| 914 |
-
```bash
|
| 915 |
-
npm test -- chat/chat.validator.test.ts
|
| 916 |
-
```
|
| 917 |
-
|
| 918 |
-
Expected: 6 tests PASS
|
| 919 |
-
|
| 920 |
-
- [ ] **Step 5: Commit**
|
| 921 |
-
|
| 922 |
-
```bash
|
| 923 |
-
git add src/chat/chat.validator.ts src/chat/chat.validator.test.ts
|
| 924 |
-
git commit -m "feat: add Zod validator for chat completions endpoint"
|
| 925 |
-
```
|
| 926 |
-
|
| 927 |
-
---
|
| 928 |
-
|
| 929 |
-
### Task 8: Create `chat/chat.controller.ts` + `chat/chat.routes.ts`
|
| 930 |
-
|
| 931 |
-
**Files:**
|
| 932 |
-
- Create: `src/chat/chat.controller.ts`
|
| 933 |
-
- Create: `src/chat/chat.routes.ts`
|
| 934 |
-
|
| 935 |
-
**Interfaces:**
|
| 936 |
-
- Consumes:
|
| 937 |
-
- `route(messages: SimpleMessage[], model?: string): Promise<RouterResult>` from `../llm-router`
|
| 938 |
-
- `extractTextFromImage(base64: string): Promise<string>` from `../expense/ocr.service`
|
| 939 |
-
- `parseExpenseJSON(raw: string): ParsedExpense | null` from `../expense/expense.service`
|
| 940 |
-
- `fixDate(expense: ParsedExpense): ParsedExpense` from `../expense/expense.service`
|
| 941 |
-
- `formatExpenseMessage(expense: ParsedExpense, saved: boolean): string` from `../expense/expense.service`
|
| 942 |
-
- `triggerN8N(expense: ParsedExpense, source: string, rawText: string): Promise<void>` from `../expense/expense.service`
|
| 943 |
-
- `validateChat` from `./chat.validator`
|
| 944 |
-
- `ChatInput` type from `./chat.validator`
|
| 945 |
-
- Produces: `chatRouter` — Express Router to be mounted at `/v1` in `proxy.ts`
|
| 946 |
-
|
| 947 |
-
- [ ] **Step 1: Write chat.controller.ts**
|
| 948 |
-
|
| 949 |
-
Create `src/chat/chat.controller.ts`:
|
| 950 |
-
|
| 951 |
-
```ts
|
| 952 |
-
import type { Request, Response } from 'express'
|
| 953 |
-
import { route } from '../llm-router'
|
| 954 |
-
import { extractTextFromImage } from '../expense/ocr.service'
|
| 955 |
-
import {
|
| 956 |
-
parseExpenseJSON,
|
| 957 |
-
fixDate,
|
| 958 |
-
formatExpenseMessage,
|
| 959 |
-
triggerN8N,
|
| 960 |
-
type ParsedExpense,
|
| 961 |
-
} from '../expense/expense.service'
|
| 962 |
-
import type { ChatInput } from './chat.validator'
|
| 963 |
-
import type { SimpleMessage } from '../providers/base'
|
| 964 |
-
|
| 965 |
-
const MODELS = { qwen: 'local/qwen2.5:3b', cloud: 'llama-3.3-70b' } as const
|
| 966 |
-
|
| 967 |
-
export async function chatComplete(req: Request, res: Response): Promise<void> {
|
| 968 |
-
try {
|
| 969 |
-
const { messages, model, stream } = req.body as ChatInput
|
| 970 |
-
|
| 971 |
-
if (model === 'expense-parser') {
|
| 972 |
-
await handleExpenseParser(messages as SimpleMessage[], model, res)
|
| 973 |
-
return
|
| 974 |
-
}
|
| 975 |
-
|
| 976 |
-
const result = await route(messages as SimpleMessage[], model)
|
| 977 |
-
const id = `chatcmpl-${Date.now()}`
|
| 978 |
-
const usedModel = result.usedModel === 'local' ? MODELS.qwen : MODELS.cloud
|
| 979 |
-
console.log(`[routed] → ${result.usedModel.toUpperCase()} (${usedModel}) | PII: ${result.piiDetected}`)
|
| 980 |
-
|
| 981 |
-
if (stream) {
|
| 982 |
-
res.setHeader('Content-Type', 'text/event-stream')
|
| 983 |
-
res.setHeader('Cache-Control', 'no-cache')
|
| 984 |
-
res.setHeader('Connection', 'keep-alive')
|
| 985 |
-
const chunk = {
|
| 986 |
-
id, object: 'chat.completion.chunk', model,
|
| 987 |
-
choices: [{ index: 0, delta: { role: 'assistant', content: result.response }, finish_reason: 'stop' }],
|
| 988 |
-
}
|
| 989 |
-
res.write(`data: ${JSON.stringify(chunk)}\n\n`)
|
| 990 |
-
res.write('data: [DONE]\n\n')
|
| 991 |
-
res.end()
|
| 992 |
-
return
|
| 993 |
-
}
|
| 994 |
-
|
| 995 |
-
res.json({
|
| 996 |
-
id, object: 'chat.completion', model,
|
| 997 |
-
choices: [{ index: 0, message: { role: 'assistant', content: result.response }, finish_reason: 'stop' }],
|
| 998 |
-
})
|
| 999 |
-
} catch (err: unknown) {
|
| 1000 |
-
console.error('[proxy error]', JSON.stringify(err, Object.getOwnPropertyNames(err as object)))
|
| 1001 |
-
res.status(500).json({ error: 'Something went wrong! Please try again.' })
|
| 1002 |
-
}
|
| 1003 |
-
}
|
| 1004 |
-
|
| 1005 |
-
async function handleExpenseParser(
|
| 1006 |
-
messages: SimpleMessage[],
|
| 1007 |
-
model: string,
|
| 1008 |
-
res: Response
|
| 1009 |
-
): Promise<void> {
|
| 1010 |
-
const lastMsg = messages[messages.length - 1]
|
| 1011 |
-
|
| 1012 |
-
type ContentPart = { type: string; image_url?: { url: string }; text?: string }
|
| 1013 |
-
const isContentArray = Array.isArray(lastMsg?.content)
|
| 1014 |
-
const contentParts = isContentArray ? (lastMsg?.content as ContentPart[]) : []
|
| 1015 |
-
const hasImage = contentParts.some((c) => c.type === 'image_url')
|
| 1016 |
-
|
| 1017 |
-
let inputText = ''
|
| 1018 |
-
if (hasImage) {
|
| 1019 |
-
const imageUrl = contentParts.find((c) => c.type === 'image_url')?.image_url?.url ?? ''
|
| 1020 |
-
console.log('[chat] image detected, running OCR...')
|
| 1021 |
-
inputText = await extractTextFromImage(imageUrl)
|
| 1022 |
-
} else {
|
| 1023 |
-
const content = lastMsg?.content
|
| 1024 |
-
inputText =
|
| 1025 |
-
typeof content === 'string'
|
| 1026 |
-
? content
|
| 1027 |
-
: (content as ContentPart[] | undefined)?.[0]?.text ?? ''
|
| 1028 |
-
}
|
| 1029 |
-
|
| 1030 |
-
if (!inputText) {
|
| 1031 |
-
res.json({
|
| 1032 |
-
id: `chatcmpl-${Date.now()}`, object: 'chat.completion', model,
|
| 1033 |
-
choices: [{
|
| 1034 |
-
index: 0,
|
| 1035 |
-
message: { role: 'assistant', content: 'Please describe your expense or upload a receipt image. Example: "Grab food 350 baht today"' },
|
| 1036 |
-
finish_reason: 'stop',
|
| 1037 |
-
}],
|
| 1038 |
-
})
|
| 1039 |
-
return
|
| 1040 |
-
}
|
| 1041 |
-
|
| 1042 |
-
const result = await route([{ role: 'user', content: inputText }], 'expense-parser')
|
| 1043 |
-
const expense: ParsedExpense | null = parseExpenseJSON(result.response)
|
| 1044 |
-
|
| 1045 |
-
if (expense) {
|
| 1046 |
-
const fixed = fixDate(expense)
|
| 1047 |
-
const hasSave = !!process.env['N8N_WEBHOOK_URL'] && !!fixed.amount
|
| 1048 |
-
if (hasSave) void triggerN8N(fixed, 'openwebui', inputText)
|
| 1049 |
-
res.json({
|
| 1050 |
-
id: `chatcmpl-${Date.now()}`, object: 'chat.completion', model,
|
| 1051 |
-
choices: [{ index: 0, message: { role: 'assistant', content: formatExpenseMessage(fixed, hasSave) }, finish_reason: 'stop' }],
|
| 1052 |
-
})
|
| 1053 |
-
return
|
| 1054 |
-
}
|
| 1055 |
-
|
| 1056 |
-
res.json({
|
| 1057 |
-
id: `chatcmpl-${Date.now()}`, object: 'chat.completion', model,
|
| 1058 |
-
choices: [{ index: 0, message: { role: 'assistant', content: result.response }, finish_reason: 'stop' }],
|
| 1059 |
-
})
|
| 1060 |
-
}
|
| 1061 |
-
```
|
| 1062 |
-
|
| 1063 |
-
- [ ] **Step 2: Write chat.routes.ts**
|
| 1064 |
-
|
| 1065 |
-
Create `src/chat/chat.routes.ts`:
|
| 1066 |
-
|
| 1067 |
-
```ts
|
| 1068 |
-
import { Router } from 'express'
|
| 1069 |
-
import { validateChat } from './chat.validator'
|
| 1070 |
-
import { chatComplete } from './chat.controller'
|
| 1071 |
-
|
| 1072 |
-
const router = Router()
|
| 1073 |
-
|
| 1074 |
-
router.post('/chat/completions', validateChat, chatComplete)
|
| 1075 |
-
|
| 1076 |
-
export { router as chatRouter }
|
| 1077 |
-
```
|
| 1078 |
-
|
| 1079 |
-
- [ ] **Step 3: Verify build**
|
| 1080 |
-
|
| 1081 |
-
```bash
|
| 1082 |
-
npm run build
|
| 1083 |
-
```
|
| 1084 |
-
|
| 1085 |
-
Expected: exits 0.
|
| 1086 |
-
|
| 1087 |
-
- [ ] **Step 4: Commit**
|
| 1088 |
-
|
| 1089 |
-
```bash
|
| 1090 |
-
git add src/chat/chat.controller.ts src/chat/chat.routes.ts
|
| 1091 |
-
git commit -m "feat: add chat controller and routes"
|
| 1092 |
-
```
|
| 1093 |
-
|
| 1094 |
-
---
|
| 1095 |
-
|
| 1096 |
-
### Task 9: Create `health/health.routes.ts`
|
| 1097 |
-
|
| 1098 |
-
**Files:**
|
| 1099 |
-
- Create: `src/health/health.routes.ts`
|
| 1100 |
-
|
| 1101 |
-
**Interfaces:**
|
| 1102 |
-
- Consumes: `getCircuitStatus()` from `../circuit-breaker`
|
| 1103 |
-
- Produces: `healthRouter` — Express Router with full paths, mounted at root in `proxy.ts`
|
| 1104 |
-
|
| 1105 |
-
- [ ] **Step 1: Write health.routes.ts**
|
| 1106 |
-
|
| 1107 |
-
Create `src/health/health.routes.ts`:
|
| 1108 |
-
|
| 1109 |
-
```ts
|
| 1110 |
-
import { Router } from 'express'
|
| 1111 |
-
import { getCircuitStatus } from '../circuit-breaker'
|
| 1112 |
-
|
| 1113 |
-
const router = Router()
|
| 1114 |
-
|
| 1115 |
-
router.get('/v1/openapi.json', (_req, res) => {
|
| 1116 |
-
res.json({ openapi: '3.0.0', info: { title: 'LLM Router', version: '1.0.0' }, paths: {} })
|
| 1117 |
-
})
|
| 1118 |
-
|
| 1119 |
-
router.get('/v1/models', (_req, res) => {
|
| 1120 |
-
res.json({
|
| 1121 |
-
object: 'list',
|
| 1122 |
-
data: [
|
| 1123 |
-
{ id: 'smart-router', object: 'model', owned_by: 'local' },
|
| 1124 |
-
{ id: 'professor-ai', object: 'model', owned_by: 'local', description: 'Research + teach mode' },
|
| 1125 |
-
{ id: 'code-assistant', object: 'model', owned_by: 'local', description: 'Coding specialist' },
|
| 1126 |
-
{ id: 'expense-parser', object: 'model', owned_by: 'local', description: 'Parse expenses from text or image' },
|
| 1127 |
-
],
|
| 1128 |
-
})
|
| 1129 |
-
})
|
| 1130 |
-
|
| 1131 |
-
router.get('/health', (_req, res) => {
|
| 1132 |
-
res.json({
|
| 1133 |
-
status: 'ok',
|
| 1134 |
-
timestamp: new Date().toISOString(),
|
| 1135 |
-
circuits: getCircuitStatus(),
|
| 1136 |
-
n8nConfigured: !!process.env['N8N_WEBHOOK_URL'],
|
| 1137 |
-
})
|
| 1138 |
-
})
|
| 1139 |
-
|
| 1140 |
-
export { router as healthRouter }
|
| 1141 |
-
```
|
| 1142 |
-
|
| 1143 |
-
Note: Routes here use full paths (`/v1/openapi.json`, `/v1/models`, `/health`) so `proxy.ts` mounts `healthRouter` at root with `app.use(healthRouter)` — no prefix needed.
|
| 1144 |
-
|
| 1145 |
-
- [ ] **Step 2: Verify build**
|
| 1146 |
-
|
| 1147 |
-
```bash
|
| 1148 |
-
npm run build
|
| 1149 |
-
```
|
| 1150 |
-
|
| 1151 |
-
Expected: exits 0.
|
| 1152 |
-
|
| 1153 |
-
- [ ] **Step 3: Commit**
|
| 1154 |
-
|
| 1155 |
-
```bash
|
| 1156 |
-
git add src/health/health.routes.ts
|
| 1157 |
-
git commit -m "feat: add health/models/openapi routes"
|
| 1158 |
-
```
|
| 1159 |
-
|
| 1160 |
-
---
|
| 1161 |
-
|
| 1162 |
-
### Task 10: Slim down `proxy.ts` and wire all routes
|
| 1163 |
-
|
| 1164 |
-
**Files:**
|
| 1165 |
-
- Modify: `src/proxy.ts` — replace all route handlers with three mount statements; keep body parsers, CORS, auth, keepAlive, and listen
|
| 1166 |
-
|
| 1167 |
-
**Interfaces:**
|
| 1168 |
-
- Consumes: `chatRouter` from `./chat/chat.routes`, `expenseRouter` from `./expense/expense.routes`, `healthRouter` from `./health/health.routes`
|
| 1169 |
-
|
| 1170 |
-
- [ ] **Step 1: Replace proxy.ts contents**
|
| 1171 |
-
|
| 1172 |
-
Replace the entire file `src/proxy.ts` with:
|
| 1173 |
-
|
| 1174 |
-
```ts
|
| 1175 |
-
import 'dotenv/config'
|
| 1176 |
-
import express from 'express'
|
| 1177 |
-
import { authMiddleware } from './middleware/authMiddleware'
|
| 1178 |
-
import { chatRouter } from './chat/chat.routes'
|
| 1179 |
-
import { expenseRouter } from './expense/expense.routes'
|
| 1180 |
-
import { healthRouter } from './health/health.routes'
|
| 1181 |
-
|
| 1182 |
-
const app = express()
|
| 1183 |
-
|
| 1184 |
-
console.log('[startup] OLLAMA_HOST:', process.env['OLLAMA_HOST'] ?? 'MISSING')
|
| 1185 |
-
console.log('[startup] CEREBRAS_API_KEY:', process.env['CEREBRAS_API_KEY'] ? 'SET' : 'MISSING')
|
| 1186 |
-
console.log('[startup] INTERNAL_SECRET:', process.env['INTERNAL_SECRET'] ? 'SET' : 'MISSING')
|
| 1187 |
-
console.log('[startup] N8N_WEBHOOK_URL:', process.env['N8N_WEBHOOK_URL'] ? 'SET' : 'MISSING')
|
| 1188 |
-
|
| 1189 |
-
app.use(express.json({ limit: '50mb' }))
|
| 1190 |
-
app.use(express.urlencoded({ limit: '50mb', extended: true }))
|
| 1191 |
-
app.use(express.raw({ limit: '50mb', type: ['image/*', 'application/octet-stream'] }))
|
| 1192 |
-
app.use(authMiddleware)
|
| 1193 |
-
|
| 1194 |
-
app.use((req, res, next) => {
|
| 1195 |
-
res.setHeader('Access-Control-Allow-Origin', '*')
|
| 1196 |
-
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
|
| 1197 |
-
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, x-internal-key')
|
| 1198 |
-
if (req.method === 'OPTIONS') { res.sendStatus(204); return }
|
| 1199 |
-
next()
|
| 1200 |
-
})
|
| 1201 |
-
|
| 1202 |
-
app.use(healthRouter)
|
| 1203 |
-
app.use('/v1', chatRouter)
|
| 1204 |
-
app.use('/v1/expense', expenseRouter)
|
| 1205 |
-
|
| 1206 |
-
const PORT = parseInt(process.env['PORT'] ?? '7860', 10)
|
| 1207 |
-
const FOUR_MINUTES = 4 * 60 * 1000
|
| 1208 |
-
|
| 1209 |
-
async function keepAlive(): Promise<void> {
|
| 1210 |
-
const services = [
|
| 1211 |
-
`http://localhost:${PORT}/health`,
|
| 1212 |
-
`${process.env['OLLAMA_HOST'] ?? ''}/api/tags`,
|
| 1213 |
-
]
|
| 1214 |
-
for (const url of services) {
|
| 1215 |
-
try {
|
| 1216 |
-
const pingRes = await fetch(url, {
|
| 1217 |
-
headers: { 'x-internal-key': process.env['INTERNAL_SECRET'] ?? '' },
|
| 1218 |
-
signal: AbortSignal.timeout(5000),
|
| 1219 |
-
})
|
| 1220 |
-
console.log('keepalive_ping', { url, status: pingRes.status })
|
| 1221 |
-
} catch (err: unknown) {
|
| 1222 |
-
console.warn('keepalive_failed', { url, error: err instanceof Error ? err.message : String(err) })
|
| 1223 |
-
}
|
| 1224 |
-
}
|
| 1225 |
-
}
|
| 1226 |
-
|
| 1227 |
-
setInterval(() => void keepAlive(), FOUR_MINUTES)
|
| 1228 |
-
void keepAlive()
|
| 1229 |
-
|
| 1230 |
-
app.listen(PORT, '0.0.0.0', () => console.log(`Proxy running on port ${PORT}`))
|
| 1231 |
-
```
|
| 1232 |
-
|
| 1233 |
-
- [ ] **Step 2: Run full test suite**
|
| 1234 |
-
|
| 1235 |
-
```bash
|
| 1236 |
-
npm test
|
| 1237 |
-
```
|
| 1238 |
-
|
| 1239 |
-
Expected: all tests PASS (validate, ocr.service, expense.service, expense.validator, chat.validator)
|
| 1240 |
-
|
| 1241 |
-
- [ ] **Step 3: Verify build**
|
| 1242 |
-
|
| 1243 |
-
```bash
|
| 1244 |
-
npm run build
|
| 1245 |
-
```
|
| 1246 |
-
|
| 1247 |
-
Expected: exits 0.
|
| 1248 |
-
|
| 1249 |
-
- [ ] **Step 4: Smoke test the running server**
|
| 1250 |
-
|
| 1251 |
-
```bash
|
| 1252 |
-
npm run dev &
|
| 1253 |
-
sleep 3
|
| 1254 |
-
curl -s http://localhost:7860/health | grep '"status":"ok"'
|
| 1255 |
-
curl -s http://localhost:7860/v1/models | grep '"smart-router"'
|
| 1256 |
-
curl -s -X POST http://localhost:7860/v1/chat/completions \
|
| 1257 |
-
-H 'Content-Type: application/json' \
|
| 1258 |
-
-d '{}' | grep '"messages must be a non-empty array"'
|
| 1259 |
-
kill %1
|
| 1260 |
-
```
|
| 1261 |
-
|
| 1262 |
-
Expected:
|
| 1263 |
-
- `/health` → contains `"status":"ok"`
|
| 1264 |
-
- `/v1/models` → contains `"smart-router"`
|
| 1265 |
-
- POST with empty body → 400 with `"messages must be a non-empty array"`
|
| 1266 |
-
|
| 1267 |
-
- [ ] **Step 5: Commit**
|
| 1268 |
-
|
| 1269 |
-
```bash
|
| 1270 |
-
git add src/proxy.ts
|
| 1271 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
docs/superpowers/plans/2026-06-30-expense-dashboard-backend.md
DELETED
|
@@ -1,2021 +0,0 @@
|
|
| 1 |
-
# Expense Dashboard — Backend Implementation Plan (1 of 2)
|
| 2 |
-
|
| 3 |
-
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
| 4 |
-
|
| 5 |
-
**Goal:** Migrate the repo to a pnpm monorepo and build all backend API endpoints for the expense dashboard (categories, expenses CRUD, budgets, analytics, profile).
|
| 6 |
-
|
| 7 |
-
**Architecture:** pnpm workspaces with `apps/api` (existing Express backend, moved) and `packages/shared` (Zod schemas). Neon Postgres via Drizzle ORM. All new routes extend `/v1/expense`. Plan 2 adds the Vite + React frontend.
|
| 8 |
-
|
| 9 |
-
**Tech Stack:** pnpm ≥9, Express ^5, Drizzle ORM ^0.44, @neondatabase/serverless, Zod ^4, Vitest ^4, TypeScript ^6 strict.
|
| 10 |
-
|
| 11 |
-
## Global Constraints
|
| 12 |
-
|
| 13 |
-
- TypeScript strict mode: `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`, `noImplicitReturns`, `noUnusedParameters`, no `any`
|
| 14 |
-
- All local imports use `.js` extension (moduleResolution: nodenext): `import { db } from './client.js'`
|
| 15 |
-
- All providers must live in `apps/api/src/expense/db/` or their domain subdirectory
|
| 16 |
-
- Package names: `@llm-router/api`, `@llm-router/shared`, `@llm-router/dashboard`
|
| 17 |
-
- Internal package references use `workspace:*` protocol
|
| 18 |
-
- Express route order: fixed paths (`/categories`, `/budgets`, `/summary`, `/trends`, `/profile`, `/manual`, `/parse`) MUST be registered before `/:id`
|
| 19 |
-
- `budget_reset_day` max value is 28 (all months have ≥28 days)
|
| 20 |
-
- Amount precision: `numeric(10,2)` — stored as string in Drizzle, parse with `Number()` in service
|
| 21 |
-
- All DB-dependent tests use `describe.skipIf(!process.env['DATABASE_URL'])` guard
|
| 22 |
-
|
| 23 |
-
---
|
| 24 |
-
|
| 25 |
-
## File Map
|
| 26 |
-
|
| 27 |
-
```
|
| 28 |
-
pnpm-workspace.yaml ← Task 1 (new)
|
| 29 |
-
package.json ← Task 1 (new root, replaces old)
|
| 30 |
-
|
| 31 |
-
packages/
|
| 32 |
-
shared/
|
| 33 |
-
src/
|
| 34 |
-
expense.types.ts ← Task 2 (new)
|
| 35 |
-
index.ts ← Task 2 (new)
|
| 36 |
-
package.json ← Task 2 (new)
|
| 37 |
-
tsconfig.json ← Task 2 (new)
|
| 38 |
-
|
| 39 |
-
apps/
|
| 40 |
-
api/
|
| 41 |
-
src/ ← Task 1 (moved from root src/)
|
| 42 |
-
expense/
|
| 43 |
-
db/
|
| 44 |
-
client.ts ← Task 3 (new)
|
| 45 |
-
schema.ts ← Task 3 (new)
|
| 46 |
-
migrate.ts ← Task 4 (new)
|
| 47 |
-
seed.ts ← Task 4 (new)
|
| 48 |
-
categories/
|
| 49 |
-
categories.service.ts ← Task 5 (new)
|
| 50 |
-
categories.controller.ts ← Task 5 (new)
|
| 51 |
-
categories.validator.ts ← Task 5 (new)
|
| 52 |
-
budgets/
|
| 53 |
-
budgets.service.ts ← Task 7 (new)
|
| 54 |
-
budgets.controller.ts ← Task 7 (new)
|
| 55 |
-
budgets.validator.ts ← Task 7 (new)
|
| 56 |
-
analytics/
|
| 57 |
-
analytics.service.ts ← Task 8 (new)
|
| 58 |
-
analytics.controller.ts ← Task 8 (new)
|
| 59 |
-
profile/
|
| 60 |
-
profile.service.ts ← Task 9 (new)
|
| 61 |
-
profile.controller.ts ← Task 9 (new)
|
| 62 |
-
profile.validator.ts ← Task 9 (new)
|
| 63 |
-
expense.controller.ts ← Task 6 (add CRUD handlers)
|
| 64 |
-
expense.routes.ts ← Tasks 5-9 (add routes each task)
|
| 65 |
-
expense.validator.ts ← Task 6 (add manual expense schema)
|
| 66 |
-
expense.service.ts ← unchanged
|
| 67 |
-
ocr.service.ts ← unchanged
|
| 68 |
-
package.json ← Task 1 (moved + renamed)
|
| 69 |
-
tsconfig.json ← Task 1 (moved, remove jsx)
|
| 70 |
-
drizzle.config.ts ← Task 3 (new)
|
| 71 |
-
```
|
| 72 |
-
|
| 73 |
-
---
|
| 74 |
-
|
| 75 |
-
### Task 1: Monorepo migration — pnpm workspaces
|
| 76 |
-
|
| 77 |
-
**Files:**
|
| 78 |
-
- Create: `pnpm-workspace.yaml`
|
| 79 |
-
- Create: `package.json` (new root workspace root)
|
| 80 |
-
- Create: `apps/api/package.json` (from existing root `package.json`, name changed)
|
| 81 |
-
- Create: `apps/api/tsconfig.json` (from existing root `tsconfig.json`, jsx removed)
|
| 82 |
-
- Move: `src/` → `apps/api/src/`
|
| 83 |
-
|
| 84 |
-
**Interfaces:**
|
| 85 |
-
- Consumes: nothing
|
| 86 |
-
- Produces: `@llm-router/api` workspace with all 26 existing tests passing
|
| 87 |
-
|
| 88 |
-
- [ ] **Step 1: Install pnpm globally if not already installed**
|
| 89 |
-
|
| 90 |
-
```bash
|
| 91 |
-
npm install -g pnpm@latest
|
| 92 |
-
pnpm --version # expect: 9.x.x or higher
|
| 93 |
-
```
|
| 94 |
-
|
| 95 |
-
- [ ] **Step 2: Create workspace directories**
|
| 96 |
-
|
| 97 |
-
```bash
|
| 98 |
-
mkdir -p apps/api apps/dashboard packages/shared
|
| 99 |
-
```
|
| 100 |
-
|
| 101 |
-
- [ ] **Step 3: Move `src/` and config files into `apps/api/`**
|
| 102 |
-
|
| 103 |
-
```bash
|
| 104 |
-
mv src apps/api/src
|
| 105 |
-
```
|
| 106 |
-
|
| 107 |
-
- [ ] **Step 4: Create `apps/api/package.json`**
|
| 108 |
-
|
| 109 |
-
Write `apps/api/package.json` with this exact content (name changed to `@llm-router/api`, scripts unchanged):
|
| 110 |
-
|
| 111 |
-
```json
|
| 112 |
-
{
|
| 113 |
-
"name": "@llm-router/api",
|
| 114 |
-
"version": "1.0.0",
|
| 115 |
-
"main": "index.js",
|
| 116 |
-
"scripts": {
|
| 117 |
-
"build": "tsc",
|
| 118 |
-
"dev": "tsx watch src/proxy.ts",
|
| 119 |
-
"start": "node dist/proxy.js",
|
| 120 |
-
"test": "vitest run"
|
| 121 |
-
},
|
| 122 |
-
"keywords": [],
|
| 123 |
-
"author": "",
|
| 124 |
-
"license": "ISC",
|
| 125 |
-
"description": "",
|
| 126 |
-
"dependencies": {
|
| 127 |
-
"@cerebras/cerebras_cloud_sdk": "^1.64.1",
|
| 128 |
-
"@types/express": "^5.0.6",
|
| 129 |
-
"dotenv": "^17.4.2",
|
| 130 |
-
"express": "^5.2.1",
|
| 131 |
-
"ollama": "^0.6.3",
|
| 132 |
-
"tesseract.js": "^5.1.0",
|
| 133 |
-
"zod": "^4.4.3"
|
| 134 |
-
},
|
| 135 |
-
"devDependencies": {
|
| 136 |
-
"@types/node": "^25.6.0",
|
| 137 |
-
"tsx": "^4.21.0",
|
| 138 |
-
"typescript": "^6.0.3",
|
| 139 |
-
"vitest": "^4.1.9"
|
| 140 |
-
}
|
| 141 |
-
}
|
| 142 |
-
```
|
| 143 |
-
|
| 144 |
-
- [ ] **Step 5: Create `apps/api/tsconfig.json`**
|
| 145 |
-
|
| 146 |
-
Write `apps/api/tsconfig.json` (same as root tsconfig, `jsx` line removed — API is Node.js only):
|
| 147 |
-
|
| 148 |
-
```json
|
| 149 |
-
{
|
| 150 |
-
"compilerOptions": {
|
| 151 |
-
"rootDir": "./src/",
|
| 152 |
-
"outDir": "./dist",
|
| 153 |
-
"module": "nodenext",
|
| 154 |
-
"target": "esnext",
|
| 155 |
-
"lib": ["esnext"],
|
| 156 |
-
"types": ["node"],
|
| 157 |
-
"sourceMap": true,
|
| 158 |
-
"declaration": true,
|
| 159 |
-
"declarationMap": true,
|
| 160 |
-
"noUncheckedIndexedAccess": true,
|
| 161 |
-
"exactOptionalPropertyTypes": true,
|
| 162 |
-
"noImplicitReturns": true,
|
| 163 |
-
"noImplicitOverride": true,
|
| 164 |
-
"noUnusedParameters": true,
|
| 165 |
-
"strict": true,
|
| 166 |
-
"verbatimModuleSyntax": false,
|
| 167 |
-
"isolatedModules": true,
|
| 168 |
-
"noUncheckedSideEffectImports": true,
|
| 169 |
-
"moduleDetection": "force",
|
| 170 |
-
"skipLibCheck": true
|
| 171 |
-
},
|
| 172 |
-
"exclude": ["**/*.test.ts", "**/*.spec.ts", "dist"]
|
| 173 |
-
}
|
| 174 |
-
```
|
| 175 |
-
|
| 176 |
-
- [ ] **Step 6: Create root `package.json`**
|
| 177 |
-
|
| 178 |
-
Write `package.json` at repo root (workspace root — no code, scripts only):
|
| 179 |
-
|
| 180 |
-
```json
|
| 181 |
-
{
|
| 182 |
-
"name": "llm-router-monorepo",
|
| 183 |
-
"private": true,
|
| 184 |
-
"scripts": {
|
| 185 |
-
"dev": "pnpm -F @llm-router/api dev & pnpm -F @llm-router/dashboard dev",
|
| 186 |
-
"dev:api": "pnpm -F @llm-router/api dev",
|
| 187 |
-
"dev:dashboard": "pnpm -F @llm-router/dashboard dev",
|
| 188 |
-
"build": "pnpm -r build",
|
| 189 |
-
"test": "pnpm -r test"
|
| 190 |
-
}
|
| 191 |
-
}
|
| 192 |
-
```
|
| 193 |
-
|
| 194 |
-
- [ ] **Step 7: Create `pnpm-workspace.yaml`**
|
| 195 |
-
|
| 196 |
-
Write `pnpm-workspace.yaml` at repo root:
|
| 197 |
-
|
| 198 |
-
```yaml
|
| 199 |
-
packages:
|
| 200 |
-
- 'apps/*'
|
| 201 |
-
- 'packages/*'
|
| 202 |
-
```
|
| 203 |
-
|
| 204 |
-
- [ ] **Step 8: Move `.env` if it exists at root**
|
| 205 |
-
|
| 206 |
-
```bash
|
| 207 |
-
[ -f .env ] && mv .env apps/api/.env || echo "no .env at root, skip"
|
| 208 |
-
```
|
| 209 |
-
|
| 210 |
-
- [ ] **Step 9: Delete old root `package.json` and `tsconfig.json`**
|
| 211 |
-
|
| 212 |
-
The root `package.json` was replaced in Step 6. Delete the old `tsconfig.json` from root:
|
| 213 |
-
|
| 214 |
-
```bash
|
| 215 |
-
rm -f tsconfig.json
|
| 216 |
-
```
|
| 217 |
-
|
| 218 |
-
- [ ] **Step 10: Install all dependencies from workspace root**
|
| 219 |
-
|
| 220 |
-
```bash
|
| 221 |
-
pnpm install
|
| 222 |
-
```
|
| 223 |
-
|
| 224 |
-
Expected: lockfile created at root, `node_modules/` at root with hoisted deps.
|
| 225 |
-
|
| 226 |
-
- [ ] **Step 11: Verify all existing tests still pass**
|
| 227 |
-
|
| 228 |
-
```bash
|
| 229 |
-
pnpm -F @llm-router/api test
|
| 230 |
-
```
|
| 231 |
-
|
| 232 |
-
Expected output:
|
| 233 |
-
```
|
| 234 |
-
✓ src/chat/chat.validator.test.ts
|
| 235 |
-
✓ src/expense/expense.service.test.ts
|
| 236 |
-
✓ src/expense/expense.validator.test.ts
|
| 237 |
-
✓ src/expense/ocr.service.test.ts
|
| 238 |
-
✓ src/middleware/validate.test.ts
|
| 239 |
-
✓ src/pii-scanner.test.ts
|
| 240 |
-
Test Files 6 passed (6)
|
| 241 |
-
Tests 26 passed (26)
|
| 242 |
-
```
|
| 243 |
-
|
| 244 |
-
- [ ] **Step 12: Verify build works**
|
| 245 |
-
|
| 246 |
-
```bash
|
| 247 |
-
pnpm -F @llm-router/api build
|
| 248 |
-
```
|
| 249 |
-
|
| 250 |
-
Expected: `apps/api/dist/` created, no TypeScript errors.
|
| 251 |
-
|
| 252 |
-
- [ ] **Step 13: Commit**
|
| 253 |
-
|
| 254 |
-
```bash
|
| 255 |
-
git add pnpm-workspace.yaml package.json apps/api/package.json apps/api/tsconfig.json apps/api/src
|
| 256 |
-
git commit -m "chore: migrate to pnpm monorepo workspaces"
|
| 257 |
-
```
|
| 258 |
-
|
| 259 |
-
---
|
| 260 |
-
|
| 261 |
-
### Task 2: packages/shared — shared Zod schemas + TypeScript types
|
| 262 |
-
|
| 263 |
-
**Files:**
|
| 264 |
-
- Create: `packages/shared/package.json`
|
| 265 |
-
- Create: `packages/shared/tsconfig.json`
|
| 266 |
-
- Create: `packages/shared/src/expense.types.ts`
|
| 267 |
-
- Create: `packages/shared/src/index.ts`
|
| 268 |
-
|
| 269 |
-
**Interfaces:**
|
| 270 |
-
- Consumes: nothing
|
| 271 |
-
- Produces: `@llm-router/shared` package exporting `CategorySchema`, `ExpenseSchema`, `BudgetSchema`, `SummaryItemSchema`, `SummarySchema`, `CreateExpenseSchema`, `CreateCategorySchema`, `CreateBudgetSchema`, `UpdateProfileSchema`, `UserProfileSchema` and their inferred types
|
| 272 |
-
|
| 273 |
-
- [ ] **Step 1: Create `packages/shared/package.json`**
|
| 274 |
-
|
| 275 |
-
```json
|
| 276 |
-
{
|
| 277 |
-
"name": "@llm-router/shared",
|
| 278 |
-
"version": "1.0.0",
|
| 279 |
-
"exports": {
|
| 280 |
-
".": "./src/index.ts"
|
| 281 |
-
},
|
| 282 |
-
"main": "./src/index.ts",
|
| 283 |
-
"types": "./src/index.ts",
|
| 284 |
-
"dependencies": {
|
| 285 |
-
"zod": "^4.4.3"
|
| 286 |
-
}
|
| 287 |
-
}
|
| 288 |
-
```
|
| 289 |
-
|
| 290 |
-
- [ ] **Step 2: Create `packages/shared/tsconfig.json`**
|
| 291 |
-
|
| 292 |
-
```json
|
| 293 |
-
{
|
| 294 |
-
"compilerOptions": {
|
| 295 |
-
"target": "esnext",
|
| 296 |
-
"module": "nodenext",
|
| 297 |
-
"moduleResolution": "nodenext",
|
| 298 |
-
"strict": true,
|
| 299 |
-
"declaration": true,
|
| 300 |
-
"declarationMap": true,
|
| 301 |
-
"skipLibCheck": true
|
| 302 |
-
},
|
| 303 |
-
"include": ["src"]
|
| 304 |
-
}
|
| 305 |
-
```
|
| 306 |
-
|
| 307 |
-
- [ ] **Step 3: Write the failing type test first**
|
| 308 |
-
|
| 309 |
-
Create `packages/shared/src/expense.types.test.ts`:
|
| 310 |
-
|
| 311 |
-
```ts
|
| 312 |
-
import { describe, it, expectTypeOf } from 'vitest'
|
| 313 |
-
import type { Category, Expense, Budget, Summary, CreateExpense } from './expense.types.js'
|
| 314 |
-
|
| 315 |
-
describe('shared types', () => {
|
| 316 |
-
it('Category has expected shape', () => {
|
| 317 |
-
expectTypeOf<Category>().toHaveProperty('id')
|
| 318 |
-
expectTypeOf<Category>().toHaveProperty('name')
|
| 319 |
-
expectTypeOf<Category>().toHaveProperty('color')
|
| 320 |
-
expectTypeOf<Category['icon']>().toEqualTypeOf<string | null>()
|
| 321 |
-
})
|
| 322 |
-
|
| 323 |
-
it('Expense has category_id and numeric amount', () => {
|
| 324 |
-
expectTypeOf<Expense>().toHaveProperty('category_id')
|
| 325 |
-
expectTypeOf<Expense['amount']>().toEqualTypeOf<number>()
|
| 326 |
-
})
|
| 327 |
-
|
| 328 |
-
it('Summary categories is an array', () => {
|
| 329 |
-
expectTypeOf<Summary['categories']>().toBeArray()
|
| 330 |
-
expectTypeOf<Summary['currency_warning']>().toEqualTypeOf<boolean>()
|
| 331 |
-
})
|
| 332 |
-
|
| 333 |
-
it('CreateExpense requires amount, category_id, date', () => {
|
| 334 |
-
expectTypeOf<CreateExpense>().toHaveProperty('amount')
|
| 335 |
-
expectTypeOf<CreateExpense>().toHaveProperty('category_id')
|
| 336 |
-
expectTypeOf<CreateExpense>().toHaveProperty('date')
|
| 337 |
-
})
|
| 338 |
-
})
|
| 339 |
-
```
|
| 340 |
-
|
| 341 |
-
- [ ] **Step 4: Run test to verify it fails**
|
| 342 |
-
|
| 343 |
-
```bash
|
| 344 |
-
pnpm -F @llm-router/shared test 2>&1 | head -20
|
| 345 |
-
```
|
| 346 |
-
|
| 347 |
-
Expected: FAIL — `expense.types.js` does not exist.
|
| 348 |
-
|
| 349 |
-
- [ ] **Step 5: Create `packages/shared/src/expense.types.ts`**
|
| 350 |
-
|
| 351 |
-
```ts
|
| 352 |
-
import { z } from 'zod'
|
| 353 |
-
|
| 354 |
-
// ── Response schemas (API → client) ──────────────────────────────────────────
|
| 355 |
-
|
| 356 |
-
export const CategorySchema = z.object({
|
| 357 |
-
id: z.string().uuid(),
|
| 358 |
-
name: z.string(),
|
| 359 |
-
color: z.string(),
|
| 360 |
-
icon: z.string().nullable(),
|
| 361 |
-
created_at: z.string(),
|
| 362 |
-
})
|
| 363 |
-
|
| 364 |
-
export const ExpenseSchema = z.object({
|
| 365 |
-
id: z.string().uuid(),
|
| 366 |
-
amount: z.number(),
|
| 367 |
-
currency: z.string(),
|
| 368 |
-
category_id: z.string().uuid(),
|
| 369 |
-
merchant: z.string().nullable(),
|
| 370 |
-
date: z.string(),
|
| 371 |
-
description: z.string().nullable(),
|
| 372 |
-
source: z.string(),
|
| 373 |
-
raw_text: z.string().nullable(),
|
| 374 |
-
created_at: z.string(),
|
| 375 |
-
updated_at: z.string(),
|
| 376 |
-
})
|
| 377 |
-
|
| 378 |
-
export const BudgetSchema = z.object({
|
| 379 |
-
id: z.string().uuid(),
|
| 380 |
-
category_id: z.string().uuid(),
|
| 381 |
-
amount: z.number(),
|
| 382 |
-
period: z.string(),
|
| 383 |
-
created_at: z.string(),
|
| 384 |
-
})
|
| 385 |
-
|
| 386 |
-
export const SummaryItemSchema = z.object({
|
| 387 |
-
category_id: z.string().uuid(),
|
| 388 |
-
category_name: z.string(),
|
| 389 |
-
color: z.string(),
|
| 390 |
-
spent: z.number(),
|
| 391 |
-
budget: z.number().nullable(),
|
| 392 |
-
over_budget: z.boolean(),
|
| 393 |
-
})
|
| 394 |
-
|
| 395 |
-
export const SummarySchema = z.object({
|
| 396 |
-
period: z.string(),
|
| 397 |
-
total_spent: z.number(),
|
| 398 |
-
currency_warning: z.boolean(),
|
| 399 |
-
categories: z.array(SummaryItemSchema),
|
| 400 |
-
})
|
| 401 |
-
|
| 402 |
-
export const UserProfileSchema = z.object({
|
| 403 |
-
id: z.string().uuid(),
|
| 404 |
-
preferred_currency: z.string(),
|
| 405 |
-
locale: z.string(),
|
| 406 |
-
budget_reset_day: z.number(),
|
| 407 |
-
})
|
| 408 |
-
|
| 409 |
-
export const TrendMonthSchema = z.object({
|
| 410 |
-
period: z.string(),
|
| 411 |
-
total: z.number(),
|
| 412 |
-
})
|
| 413 |
-
|
| 414 |
-
export const TrendsSchema = z.object({
|
| 415 |
-
months: z.array(TrendMonthSchema),
|
| 416 |
-
})
|
| 417 |
-
|
| 418 |
-
// ── Input schemas (client → API) ─────────────────────────────────────────────
|
| 419 |
-
|
| 420 |
-
export const CreateCategorySchema = z.object({
|
| 421 |
-
name: z.string().min(1).max(50),
|
| 422 |
-
color: z.string().regex(/^#[0-9A-Fa-f]{6}$/, 'color must be a hex color e.g. #FF5500'),
|
| 423 |
-
icon: z.string().emoji().optional(),
|
| 424 |
-
})
|
| 425 |
-
|
| 426 |
-
export const UpdateCategorySchema = CreateCategorySchema.partial()
|
| 427 |
-
|
| 428 |
-
export const CreateExpenseSchema = z.object({
|
| 429 |
-
amount: z.number().positive(),
|
| 430 |
-
currency: z.string().length(3).optional(),
|
| 431 |
-
category_id: z.string().uuid(),
|
| 432 |
-
merchant: z.string().optional(),
|
| 433 |
-
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'date must be YYYY-MM-DD'),
|
| 434 |
-
description: z.string().optional(),
|
| 435 |
-
})
|
| 436 |
-
|
| 437 |
-
export const UpdateExpenseSchema = CreateExpenseSchema.partial()
|
| 438 |
-
|
| 439 |
-
export const CreateBudgetSchema = z.object({
|
| 440 |
-
category_id: z.string().uuid(),
|
| 441 |
-
amount: z.number().positive(),
|
| 442 |
-
period: z.enum(['monthly']).optional().default('monthly'),
|
| 443 |
-
})
|
| 444 |
-
|
| 445 |
-
export const UpdateBudgetSchema = z.object({
|
| 446 |
-
amount: z.number().positive().optional(),
|
| 447 |
-
period: z.enum(['monthly']).optional(),
|
| 448 |
-
})
|
| 449 |
-
|
| 450 |
-
export const UpdateProfileSchema = z.object({
|
| 451 |
-
preferred_currency: z.string().length(3).optional(),
|
| 452 |
-
locale: z.string().optional(),
|
| 453 |
-
budget_reset_day: z.number().int().min(1).max(28).optional(),
|
| 454 |
-
})
|
| 455 |
-
|
| 456 |
-
// ── Inferred TypeScript types ─────────────────────────────────────────────────
|
| 457 |
-
|
| 458 |
-
export type Category = z.infer<typeof CategorySchema>
|
| 459 |
-
export type Expense = z.infer<typeof ExpenseSchema>
|
| 460 |
-
export type Budget = z.infer<typeof BudgetSchema>
|
| 461 |
-
export type SummaryItem = z.infer<typeof SummaryItemSchema>
|
| 462 |
-
export type Summary = z.infer<typeof SummarySchema>
|
| 463 |
-
export type UserProfile = z.infer<typeof UserProfileSchema>
|
| 464 |
-
export type TrendMonth = z.infer<typeof TrendMonthSchema>
|
| 465 |
-
export type Trends = z.infer<typeof TrendsSchema>
|
| 466 |
-
|
| 467 |
-
export type CreateCategory = z.infer<typeof CreateCategorySchema>
|
| 468 |
-
export type UpdateCategory = z.infer<typeof UpdateCategorySchema>
|
| 469 |
-
export type CreateExpense = z.infer<typeof CreateExpenseSchema>
|
| 470 |
-
export type UpdateExpense = z.infer<typeof UpdateExpenseSchema>
|
| 471 |
-
export type CreateBudget = z.infer<typeof CreateBudgetSchema>
|
| 472 |
-
export type UpdateBudget = z.infer<typeof UpdateBudgetSchema>
|
| 473 |
-
export type UpdateProfile = z.infer<typeof UpdateProfileSchema>
|
| 474 |
-
```
|
| 475 |
-
|
| 476 |
-
- [ ] **Step 6: Create `packages/shared/src/index.ts`**
|
| 477 |
-
|
| 478 |
-
```ts
|
| 479 |
-
export * from './expense.types.js'
|
| 480 |
-
```
|
| 481 |
-
|
| 482 |
-
- [ ] **Step 7: Run test to verify it passes**
|
| 483 |
-
|
| 484 |
-
```bash
|
| 485 |
-
pnpm -F @llm-router/shared test
|
| 486 |
-
```
|
| 487 |
-
|
| 488 |
-
Expected:
|
| 489 |
-
```
|
| 490 |
-
✓ src/expense.types.test.ts (4 tests)
|
| 491 |
-
Test Files 1 passed (1)
|
| 492 |
-
Tests 4 passed (4)
|
| 493 |
-
```
|
| 494 |
-
|
| 495 |
-
- [ ] **Step 8: Commit**
|
| 496 |
-
|
| 497 |
-
```bash
|
| 498 |
-
git add packages/shared
|
| 499 |
-
git commit -m "feat: add @llm-router/shared package with expense Zod schemas"
|
| 500 |
-
```
|
| 501 |
-
|
| 502 |
-
---
|
| 503 |
-
|
| 504 |
-
### Task 3: Drizzle ORM setup — DB client, schema, config
|
| 505 |
-
|
| 506 |
-
**Files:**
|
| 507 |
-
- Create: `apps/api/src/expense/db/client.ts`
|
| 508 |
-
- Create: `apps/api/src/expense/db/schema.ts`
|
| 509 |
-
- Create: `apps/api/drizzle.config.ts`
|
| 510 |
-
- Modify: `apps/api/package.json` — add `drizzle-orm`, `@neondatabase/serverless`, `drizzle-kit`
|
| 511 |
-
|
| 512 |
-
**Interfaces:**
|
| 513 |
-
- Consumes: `DATABASE_URL` environment variable
|
| 514 |
-
- Produces: `db` (Drizzle client), `userProfile`, `categories`, `expenses`, `budgets` table references — used by all service files in Tasks 4–9
|
| 515 |
-
|
| 516 |
-
- [ ] **Step 1: Add dependencies**
|
| 517 |
-
|
| 518 |
-
```bash
|
| 519 |
-
pnpm add drizzle-orm @neondatabase/serverless -F @llm-router/api
|
| 520 |
-
pnpm add -D drizzle-kit -F @llm-router/api
|
| 521 |
-
```
|
| 522 |
-
|
| 523 |
-
- [ ] **Step 2: Add DATABASE_URL to `apps/api/.env`**
|
| 524 |
-
|
| 525 |
-
Add this line (do not commit the actual value):
|
| 526 |
-
```
|
| 527 |
-
DATABASE_URL=postgresql://<user>:<password>@<host>.neon.tech/<dbname>?sslmode=require
|
| 528 |
-
```
|
| 529 |
-
|
| 530 |
-
Verify it's in `.gitignore` — the root `.gitignore` already ignores `.env` files.
|
| 531 |
-
|
| 532 |
-
- [ ] **Step 3: Write the failing schema type test first**
|
| 533 |
-
|
| 534 |
-
Create `apps/api/src/expense/db/schema.test.ts`:
|
| 535 |
-
|
| 536 |
-
```ts
|
| 537 |
-
import { describe, it, expect } from 'vitest'
|
| 538 |
-
import { userProfile, categories, expenses, budgets } from './schema.js'
|
| 539 |
-
|
| 540 |
-
describe('drizzle schema', () => {
|
| 541 |
-
it('userProfile table has expected columns', () => {
|
| 542 |
-
expect(userProfile.preferred_currency).toBeDefined()
|
| 543 |
-
expect(userProfile.locale).toBeDefined()
|
| 544 |
-
expect(userProfile.budget_reset_day).toBeDefined()
|
| 545 |
-
})
|
| 546 |
-
|
| 547 |
-
it('categories table has name and color columns', () => {
|
| 548 |
-
expect(categories.name).toBeDefined()
|
| 549 |
-
expect(categories.color).toBeDefined()
|
| 550 |
-
})
|
| 551 |
-
|
| 552 |
-
it('expenses table references categories via category_id', () => {
|
| 553 |
-
expect(expenses.category_id).toBeDefined()
|
| 554 |
-
expect(expenses.amount).toBeDefined()
|
| 555 |
-
expect(expenses.source).toBeDefined()
|
| 556 |
-
})
|
| 557 |
-
|
| 558 |
-
it('budgets table has unique constraint on category_id + period', () => {
|
| 559 |
-
expect(budgets.category_id).toBeDefined()
|
| 560 |
-
expect(budgets.period).toBeDefined()
|
| 561 |
-
})
|
| 562 |
-
})
|
| 563 |
-
```
|
| 564 |
-
|
| 565 |
-
- [ ] **Step 4: Run test to verify it fails**
|
| 566 |
-
|
| 567 |
-
```bash
|
| 568 |
-
pnpm -F @llm-router/api test src/expense/db/schema.test.ts
|
| 569 |
-
```
|
| 570 |
-
|
| 571 |
-
Expected: FAIL — `schema.js` does not exist.
|
| 572 |
-
|
| 573 |
-
- [ ] **Step 5: Create `apps/api/src/expense/db/schema.ts`**
|
| 574 |
-
|
| 575 |
-
```ts
|
| 576 |
-
import { pgTable, uuid, text, numeric, integer, timestamp, date, unique } from 'drizzle-orm/pg-core'
|
| 577 |
-
import { sql } from 'drizzle-orm'
|
| 578 |
-
|
| 579 |
-
export const userProfile = pgTable('user_profile', {
|
| 580 |
-
id: uuid('id').primaryKey().default(sql`gen_random_uuid()`),
|
| 581 |
-
preferred_currency: text('preferred_currency').notNull().default('USD'),
|
| 582 |
-
locale: text('locale').notNull().default('en-US'),
|
| 583 |
-
budget_reset_day: integer('budget_reset_day').notNull().default(1),
|
| 584 |
-
created_at: timestamp('created_at', { withTimezone: true }).notNull().default(sql`now()`),
|
| 585 |
-
updated_at: timestamp('updated_at', { withTimezone: true }).notNull().default(sql`now()`),
|
| 586 |
-
})
|
| 587 |
-
|
| 588 |
-
export const categories = pgTable('categories', {
|
| 589 |
-
id: uuid('id').primaryKey().default(sql`gen_random_uuid()`),
|
| 590 |
-
name: text('name').notNull().unique(),
|
| 591 |
-
color: text('color').notNull().default('#6B7280'),
|
| 592 |
-
icon: text('icon'),
|
| 593 |
-
created_at: timestamp('created_at', { withTimezone: true }).notNull().default(sql`now()`),
|
| 594 |
-
})
|
| 595 |
-
|
| 596 |
-
export const expenses = pgTable('expenses', {
|
| 597 |
-
id: uuid('id').primaryKey().default(sql`gen_random_uuid()`),
|
| 598 |
-
amount: numeric('amount', { precision: 10, scale: 2 }).notNull(),
|
| 599 |
-
currency: text('currency').notNull(),
|
| 600 |
-
category_id: uuid('category_id').notNull().references(() => categories.id),
|
| 601 |
-
merchant: text('merchant'),
|
| 602 |
-
date: date('date').notNull(),
|
| 603 |
-
description: text('description'),
|
| 604 |
-
source: text('source').notNull().default('manual'),
|
| 605 |
-
raw_text: text('raw_text'),
|
| 606 |
-
created_at: timestamp('created_at', { withTimezone: true }).notNull().default(sql`now()`),
|
| 607 |
-
updated_at: timestamp('updated_at', { withTimezone: true }).notNull().default(sql`now()`),
|
| 608 |
-
})
|
| 609 |
-
|
| 610 |
-
export const budgets = pgTable('budgets', {
|
| 611 |
-
id: uuid('id').primaryKey().default(sql`gen_random_uuid()`),
|
| 612 |
-
category_id: uuid('category_id').notNull().references(() => categories.id),
|
| 613 |
-
amount: numeric('amount', { precision: 10, scale: 2 }).notNull(),
|
| 614 |
-
period: text('period').notNull().default('monthly'),
|
| 615 |
-
created_at: timestamp('created_at', { withTimezone: true }).notNull().default(sql`now()`),
|
| 616 |
-
updated_at: timestamp('updated_at', { withTimezone: true }).notNull().default(sql`now()`),
|
| 617 |
-
}, (table) => [
|
| 618 |
-
unique('budgets_category_period_unique').on(table.category_id, table.period),
|
| 619 |
-
])
|
| 620 |
-
```
|
| 621 |
-
|
| 622 |
-
- [ ] **Step 6: Create `apps/api/src/expense/db/client.ts`**
|
| 623 |
-
|
| 624 |
-
```ts
|
| 625 |
-
import 'dotenv/config'
|
| 626 |
-
import { neon } from '@neondatabase/serverless'
|
| 627 |
-
import { drizzle } from 'drizzle-orm/neon-http'
|
| 628 |
-
import * as schema from './schema.js'
|
| 629 |
-
|
| 630 |
-
const url = process.env['DATABASE_URL']
|
| 631 |
-
if (!url) throw new Error('DATABASE_URL is not set')
|
| 632 |
-
|
| 633 |
-
const sql = neon(url)
|
| 634 |
-
export const db = drizzle(sql, { schema })
|
| 635 |
-
```
|
| 636 |
-
|
| 637 |
-
- [ ] **Step 7: Create `apps/api/drizzle.config.ts`**
|
| 638 |
-
|
| 639 |
-
```ts
|
| 640 |
-
import 'dotenv/config'
|
| 641 |
-
import { defineConfig } from 'drizzle-kit'
|
| 642 |
-
|
| 643 |
-
export default defineConfig({
|
| 644 |
-
schema: './src/expense/db/schema.ts',
|
| 645 |
-
out: './drizzle',
|
| 646 |
-
dialect: 'postgresql',
|
| 647 |
-
dbCredentials: {
|
| 648 |
-
url: process.env['DATABASE_URL'] ?? '',
|
| 649 |
-
},
|
| 650 |
-
})
|
| 651 |
-
```
|
| 652 |
-
|
| 653 |
-
- [ ] **Step 8: Add drizzle-kit scripts to `apps/api/package.json`**
|
| 654 |
-
|
| 655 |
-
Add to the `scripts` block:
|
| 656 |
-
```json
|
| 657 |
-
"db:generate": "drizzle-kit generate",
|
| 658 |
-
"db:migrate": "drizzle-kit migrate",
|
| 659 |
-
"db:studio": "drizzle-kit studio"
|
| 660 |
-
```
|
| 661 |
-
|
| 662 |
-
- [ ] **Step 9: Run test to verify it passes**
|
| 663 |
-
|
| 664 |
-
```bash
|
| 665 |
-
pnpm -F @llm-router/api test src/expense/db/schema.test.ts
|
| 666 |
-
```
|
| 667 |
-
|
| 668 |
-
Expected:
|
| 669 |
-
```
|
| 670 |
-
✓ src/expense/db/schema.test.ts (4 tests)
|
| 671 |
-
```
|
| 672 |
-
|
| 673 |
-
- [ ] **Step 10: Generate initial migration**
|
| 674 |
-
|
| 675 |
-
```bash
|
| 676 |
-
pnpm -F @llm-router/api db:generate
|
| 677 |
-
```
|
| 678 |
-
|
| 679 |
-
Expected: `apps/api/drizzle/` directory created with SQL migration file.
|
| 680 |
-
|
| 681 |
-
- [ ] **Step 11: Commit**
|
| 682 |
-
|
| 683 |
-
```bash
|
| 684 |
-
git add apps/api/src/expense/db apps/api/drizzle.config.ts apps/api/drizzle apps/api/package.json
|
| 685 |
-
git commit -m "feat: add Drizzle ORM schema and Neon DB client"
|
| 686 |
-
```
|
| 687 |
-
|
| 688 |
-
---
|
| 689 |
-
|
| 690 |
-
### Task 4: DB migrations + seed on startup
|
| 691 |
-
|
| 692 |
-
**Files:**
|
| 693 |
-
- Create: `apps/api/src/expense/db/migrate.ts`
|
| 694 |
-
- Create: `apps/api/src/expense/db/seed.ts`
|
| 695 |
-
- Create: `apps/api/src/expense/db/seed.test.ts`
|
| 696 |
-
- Modify: `apps/api/src/proxy.ts` — call migrate + seed before `app.listen`
|
| 697 |
-
|
| 698 |
-
**Interfaces:**
|
| 699 |
-
- Consumes: `db` from `./client.js`, `categories` and `userProfile` from `./schema.js`
|
| 700 |
-
- Produces: `runMigrations(): Promise<void>`, `seedDefaults(): Promise<void>` — called in proxy.ts startup
|
| 701 |
-
|
| 702 |
-
- [ ] **Step 1: Write the failing seed test first**
|
| 703 |
-
|
| 704 |
-
Create `apps/api/src/expense/db/seed.test.ts`:
|
| 705 |
-
|
| 706 |
-
```ts
|
| 707 |
-
import { describe, it, expect } from 'vitest'
|
| 708 |
-
import { seedDefaults } from './seed.js'
|
| 709 |
-
import { db } from './client.js'
|
| 710 |
-
import { categories, userProfile } from './schema.js'
|
| 711 |
-
|
| 712 |
-
describe.skipIf(!process.env['DATABASE_URL'])('seedDefaults', () => {
|
| 713 |
-
it('seeds 7 default categories', async () => {
|
| 714 |
-
await seedDefaults()
|
| 715 |
-
const cats = await db.select().from(categories)
|
| 716 |
-
expect(cats.length).toBeGreaterThanOrEqual(7)
|
| 717 |
-
})
|
| 718 |
-
|
| 719 |
-
it('seeds exactly one user_profile row', async () => {
|
| 720 |
-
await seedDefaults()
|
| 721 |
-
const profiles = await db.select().from(userProfile)
|
| 722 |
-
expect(profiles.length).toBe(1)
|
| 723 |
-
expect(profiles[0]?.preferred_currency).toBe('USD')
|
| 724 |
-
})
|
| 725 |
-
|
| 726 |
-
it('is idempotent — second run does not duplicate rows', async () => {
|
| 727 |
-
await seedDefaults()
|
| 728 |
-
await seedDefaults()
|
| 729 |
-
const cats = await db.select().from(categories)
|
| 730 |
-
const names = cats.map((c) => c.name)
|
| 731 |
-
const uniqueNames = new Set(names)
|
| 732 |
-
expect(uniqueNames.size).toBe(names.length)
|
| 733 |
-
})
|
| 734 |
-
})
|
| 735 |
-
```
|
| 736 |
-
|
| 737 |
-
- [ ] **Step 2: Run test to verify it fails (or skips without DATABASE_URL)**
|
| 738 |
-
|
| 739 |
-
```bash
|
| 740 |
-
pnpm -F @llm-router/api test src/expense/db/seed.test.ts
|
| 741 |
-
```
|
| 742 |
-
|
| 743 |
-
Expected: SKIP if no `DATABASE_URL`, or FAIL if `DATABASE_URL` is set (seed.js doesn't exist yet).
|
| 744 |
-
|
| 745 |
-
- [ ] **Step 3: Create `apps/api/src/expense/db/migrate.ts`**
|
| 746 |
-
|
| 747 |
-
```ts
|
| 748 |
-
import { migrate } from 'drizzle-orm/neon-http/migrator'
|
| 749 |
-
import { db } from './client.js'
|
| 750 |
-
|
| 751 |
-
export async function runMigrations(): Promise<void> {
|
| 752 |
-
await migrate(db, { migrationsFolder: new URL('../../../../drizzle', import.meta.url).pathname })
|
| 753 |
-
}
|
| 754 |
-
```
|
| 755 |
-
|
| 756 |
-
- [ ] **Step 4: Create `apps/api/src/expense/db/seed.ts`**
|
| 757 |
-
|
| 758 |
-
```ts
|
| 759 |
-
import { db } from './client.js'
|
| 760 |
-
import { categories, userProfile } from './schema.js'
|
| 761 |
-
|
| 762 |
-
const DEFAULT_CATEGORIES: Array<{ name: string; color: string; icon: string }> = [
|
| 763 |
-
{ name: 'Food', color: '#F59E0B', icon: '🍔' },
|
| 764 |
-
{ name: 'Transport', color: '#3B82F6', icon: '🚗' },
|
| 765 |
-
{ name: 'Health', color: '#10B981', icon: '💊' },
|
| 766 |
-
{ name: 'Shopping', color: '#8B5CF6', icon: '🛍️' },
|
| 767 |
-
{ name: 'Utilities', color: '#6B7280', icon: '💡' },
|
| 768 |
-
{ name: 'Entertainment', color: '#EC4899', icon: '🎬' },
|
| 769 |
-
{ name: 'Other', color: '#9CA3AF', icon: '📦' },
|
| 770 |
-
]
|
| 771 |
-
|
| 772 |
-
export async function seedDefaults(): Promise<void> {
|
| 773 |
-
for (const cat of DEFAULT_CATEGORIES) {
|
| 774 |
-
await db.insert(categories).values(cat).onConflictDoNothing()
|
| 775 |
-
}
|
| 776 |
-
await db
|
| 777 |
-
.insert(userProfile)
|
| 778 |
-
.values({ preferred_currency: 'USD', locale: 'en-US', budget_reset_day: 1 })
|
| 779 |
-
.onConflictDoNothing()
|
| 780 |
-
}
|
| 781 |
-
```
|
| 782 |
-
|
| 783 |
-
- [ ] **Step 5: Modify `apps/api/src/proxy.ts` — add startup call**
|
| 784 |
-
|
| 785 |
-
At the top of `proxy.ts`, add these imports after the existing imports:
|
| 786 |
-
|
| 787 |
-
```ts
|
| 788 |
-
import { runMigrations } from './expense/db/migrate.js'
|
| 789 |
-
import { seedDefaults } from './expense/db/seed.js'
|
| 790 |
-
```
|
| 791 |
-
|
| 792 |
-
Wrap the `app.listen` call in a startup function. Find the existing `app.listen` call and replace it with:
|
| 793 |
-
|
| 794 |
-
```ts
|
| 795 |
-
async function start(): Promise<void> {
|
| 796 |
-
await runMigrations()
|
| 797 |
-
await seedDefaults()
|
| 798 |
-
app.listen(port, () => {
|
| 799 |
-
console.log(`Server running on port ${port}`)
|
| 800 |
-
})
|
| 801 |
-
}
|
| 802 |
-
|
| 803 |
-
start().catch((err: unknown) => {
|
| 804 |
-
console.error('Failed to start server:', err)
|
| 805 |
-
process.exit(1)
|
| 806 |
-
})
|
| 807 |
-
```
|
| 808 |
-
|
| 809 |
-
- [ ] **Step 6: Run test to verify it passes**
|
| 810 |
-
|
| 811 |
-
```bash
|
| 812 |
-
pnpm -F @llm-router/api test src/expense/db/seed.test.ts
|
| 813 |
-
```
|
| 814 |
-
|
| 815 |
-
If `DATABASE_URL` is set: expect 3 tests pass. If not: 3 tests skipped (that's fine).
|
| 816 |
-
|
| 817 |
-
Run the full suite to ensure nothing is broken:
|
| 818 |
-
|
| 819 |
-
```bash
|
| 820 |
-
pnpm -F @llm-router/api test
|
| 821 |
-
```
|
| 822 |
-
|
| 823 |
-
Expected: all 26 existing tests still pass + seed tests (pass or skip).
|
| 824 |
-
|
| 825 |
-
- [ ] **Step 7: Commit**
|
| 826 |
-
|
| 827 |
-
```bash
|
| 828 |
-
git add apps/api/src/expense/db/migrate.ts apps/api/src/expense/db/seed.ts apps/api/src/expense/db/seed.test.ts apps/api/src/proxy.ts
|
| 829 |
-
git commit -m "feat: add DB migrations and seed on startup"
|
| 830 |
-
```
|
| 831 |
-
|
| 832 |
-
---
|
| 833 |
-
|
| 834 |
-
### Task 5: Categories API — CRUD with 409 delete protection
|
| 835 |
-
|
| 836 |
-
**Files:**
|
| 837 |
-
- Create: `apps/api/src/expense/categories/categories.service.ts`
|
| 838 |
-
- Create: `apps/api/src/expense/categories/categories.service.test.ts`
|
| 839 |
-
- Create: `apps/api/src/expense/categories/categories.controller.ts`
|
| 840 |
-
- Create: `apps/api/src/expense/categories/categories.validator.ts`
|
| 841 |
-
- Modify: `apps/api/src/expense/expense.routes.ts`
|
| 842 |
-
|
| 843 |
-
**Interfaces:**
|
| 844 |
-
- Consumes: `db` from `../db/client.js`, `categories`, `expenses` tables from `../db/schema.js`, `CreateCategorySchema`, `UpdateCategorySchema` from `@llm-router/shared`
|
| 845 |
-
- Produces routes: `GET /categories`, `POST /categories`, `PUT /categories/:id`, `DELETE /categories/:id`
|
| 846 |
-
|
| 847 |
-
- [ ] **Step 1: Write the failing service test first**
|
| 848 |
-
|
| 849 |
-
Create `apps/api/src/expense/categories/categories.service.test.ts`:
|
| 850 |
-
|
| 851 |
-
```ts
|
| 852 |
-
import { describe, it, expect } from 'vitest'
|
| 853 |
-
import {
|
| 854 |
-
listCategories,
|
| 855 |
-
createCategory,
|
| 856 |
-
updateCategory,
|
| 857 |
-
deleteCategory,
|
| 858 |
-
} from './categories.service.js'
|
| 859 |
-
|
| 860 |
-
describe.skipIf(!process.env['DATABASE_URL'])('categories service', () => {
|
| 861 |
-
let createdId: string
|
| 862 |
-
|
| 863 |
-
it('listCategories returns an array', async () => {
|
| 864 |
-
const result = await listCategories()
|
| 865 |
-
expect(Array.isArray(result)).toBe(true)
|
| 866 |
-
expect(result.length).toBeGreaterThanOrEqual(7)
|
| 867 |
-
})
|
| 868 |
-
|
| 869 |
-
it('createCategory creates a new category', async () => {
|
| 870 |
-
const cat = await createCategory({
|
| 871 |
-
name: `TestCat_${Date.now()}`,
|
| 872 |
-
color: '#FF5500',
|
| 873 |
-
})
|
| 874 |
-
createdId = cat.id
|
| 875 |
-
expect(cat.name).toMatch(/^TestCat_/)
|
| 876 |
-
expect(cat.color).toBe('#FF5500')
|
| 877 |
-
expect(cat.icon).toBeNull()
|
| 878 |
-
})
|
| 879 |
-
|
| 880 |
-
it('updateCategory updates name', async () => {
|
| 881 |
-
const updated = await updateCategory(createdId, { name: 'UpdatedCat' })
|
| 882 |
-
expect(updated.name).toBe('UpdatedCat')
|
| 883 |
-
})
|
| 884 |
-
|
| 885 |
-
it('deleteCategory removes the category', async () => {
|
| 886 |
-
await deleteCategory(createdId)
|
| 887 |
-
const all = await listCategories()
|
| 888 |
-
expect(all.find((c) => c.id === createdId)).toBeUndefined()
|
| 889 |
-
})
|
| 890 |
-
|
| 891 |
-
it('deleteCategory throws when expenses reference category', async () => {
|
| 892 |
-
const cats = await listCategories()
|
| 893 |
-
const food = cats.find((c) => c.name === 'Food')
|
| 894 |
-
if (!food) return // skip if Food doesn't exist yet
|
| 895 |
-
// Food may have no expenses — this test is best-effort without fixture setup
|
| 896 |
-
// Full protection is tested via the controller returning 409
|
| 897 |
-
expect(typeof food.id).toBe('string')
|
| 898 |
-
})
|
| 899 |
-
})
|
| 900 |
-
```
|
| 901 |
-
|
| 902 |
-
- [ ] **Step 2: Run test to verify it fails**
|
| 903 |
-
|
| 904 |
-
```bash
|
| 905 |
-
pnpm -F @llm-router/api test src/expense/categories/categories.service.test.ts
|
| 906 |
-
```
|
| 907 |
-
|
| 908 |
-
Expected: SKIP (no DATABASE_URL) or FAIL (service doesn't exist).
|
| 909 |
-
|
| 910 |
-
- [ ] **Step 3: Create `apps/api/src/expense/categories/categories.service.ts`**
|
| 911 |
-
|
| 912 |
-
```ts
|
| 913 |
-
import { eq, sql } from 'drizzle-orm'
|
| 914 |
-
import { db } from '../db/client.js'
|
| 915 |
-
import { categories, expenses } from '../db/schema.js'
|
| 916 |
-
import type { CreateCategory, UpdateCategory, Category } from '@llm-router/shared'
|
| 917 |
-
|
| 918 |
-
export async function listCategories(): Promise<Category[]> {
|
| 919 |
-
const rows = await db.select().from(categories).orderBy(categories.name)
|
| 920 |
-
return rows.map((r) => ({
|
| 921 |
-
id: r.id,
|
| 922 |
-
name: r.name,
|
| 923 |
-
color: r.color,
|
| 924 |
-
icon: r.icon ?? null,
|
| 925 |
-
created_at: r.created_at.toISOString(),
|
| 926 |
-
}))
|
| 927 |
-
}
|
| 928 |
-
|
| 929 |
-
export async function createCategory(input: CreateCategory): Promise<Category> {
|
| 930 |
-
const [row] = await db.insert(categories).values(input).returning()
|
| 931 |
-
if (!row) throw new Error('Insert failed')
|
| 932 |
-
return {
|
| 933 |
-
id: row.id,
|
| 934 |
-
name: row.name,
|
| 935 |
-
color: row.color,
|
| 936 |
-
icon: row.icon ?? null,
|
| 937 |
-
created_at: row.created_at.toISOString(),
|
| 938 |
-
}
|
| 939 |
-
}
|
| 940 |
-
|
| 941 |
-
export async function updateCategory(id: string, input: UpdateCategory): Promise<Category> {
|
| 942 |
-
const [row] = await db
|
| 943 |
-
.update(categories)
|
| 944 |
-
.set(input)
|
| 945 |
-
.where(eq(categories.id, id))
|
| 946 |
-
.returning()
|
| 947 |
-
if (!row) throw new Error(`Category ${id} not found`)
|
| 948 |
-
return {
|
| 949 |
-
id: row.id,
|
| 950 |
-
name: row.name,
|
| 951 |
-
color: row.color,
|
| 952 |
-
icon: row.icon ?? null,
|
| 953 |
-
created_at: row.created_at.toISOString(),
|
| 954 |
-
}
|
| 955 |
-
}
|
| 956 |
-
|
| 957 |
-
export async function deleteCategory(id: string): Promise<void> {
|
| 958 |
-
const countResult = await db
|
| 959 |
-
.select({ count: sql<number>`cast(count(*) as int)` })
|
| 960 |
-
.from(expenses)
|
| 961 |
-
.where(eq(expenses.category_id, id))
|
| 962 |
-
const count = countResult[0]?.count ?? 0
|
| 963 |
-
if (count > 0) {
|
| 964 |
-
throw Object.assign(new Error(`Category has ${count} expenses — reassign them first`), {
|
| 965 |
-
status: 409,
|
| 966 |
-
})
|
| 967 |
-
}
|
| 968 |
-
await db.delete(categories).where(eq(categories.id, id))
|
| 969 |
-
}
|
| 970 |
-
```
|
| 971 |
-
|
| 972 |
-
- [ ] **Step 4: Create `apps/api/src/expense/categories/categories.validator.ts`**
|
| 973 |
-
|
| 974 |
-
```ts
|
| 975 |
-
import { CreateCategorySchema, UpdateCategorySchema } from '@llm-router/shared'
|
| 976 |
-
import { validate } from '../../middleware/validate.js'
|
| 977 |
-
|
| 978 |
-
export const validateCreateCategory = validate(CreateCategorySchema)
|
| 979 |
-
export const validateUpdateCategory = validate(UpdateCategorySchema)
|
| 980 |
-
```
|
| 981 |
-
|
| 982 |
-
- [ ] **Step 5: Create `apps/api/src/expense/categories/categories.controller.ts`**
|
| 983 |
-
|
| 984 |
-
```ts
|
| 985 |
-
import type { RequestHandler } from 'express'
|
| 986 |
-
import * as svc from './categories.service.js'
|
| 987 |
-
|
| 988 |
-
export const getCategories: RequestHandler = async (_req, res) => {
|
| 989 |
-
const data = await svc.listCategories()
|
| 990 |
-
res.json(data)
|
| 991 |
-
}
|
| 992 |
-
|
| 993 |
-
export const postCategory: RequestHandler = async (req, res) => {
|
| 994 |
-
const data = await svc.createCategory(req.body)
|
| 995 |
-
res.status(201).json(data)
|
| 996 |
-
}
|
| 997 |
-
|
| 998 |
-
export const putCategory: RequestHandler = async (req, res) => {
|
| 999 |
-
const data = await svc.updateCategory(req.params['id'] ?? '', req.body)
|
| 1000 |
-
res.json(data)
|
| 1001 |
-
}
|
| 1002 |
-
|
| 1003 |
-
export const deleteCategory: RequestHandler = async (req, res) => {
|
| 1004 |
-
try {
|
| 1005 |
-
await svc.deleteCategory(req.params['id'] ?? '')
|
| 1006 |
-
res.status(204).send()
|
| 1007 |
-
} catch (err: unknown) {
|
| 1008 |
-
if (err instanceof Error && (err as NodeJS.ErrnoException & { status?: number }).status === 409) {
|
| 1009 |
-
res.status(409).json({ error: err.message })
|
| 1010 |
-
return
|
| 1011 |
-
}
|
| 1012 |
-
throw err
|
| 1013 |
-
}
|
| 1014 |
-
}
|
| 1015 |
-
```
|
| 1016 |
-
|
| 1017 |
-
- [ ] **Step 6: Add category routes to `apps/api/src/expense/expense.routes.ts`**
|
| 1018 |
-
|
| 1019 |
-
Replace the entire file with:
|
| 1020 |
-
|
| 1021 |
-
```ts
|
| 1022 |
-
import { Router } from 'express'
|
| 1023 |
-
import type { Router as ExpressRouter } from 'express'
|
| 1024 |
-
|
| 1025 |
-
import { validateExpense } from './expense.validator.js'
|
| 1026 |
-
import { parseExpense } from './expense.controller.js'
|
| 1027 |
-
|
| 1028 |
-
import { validateCreateCategory, validateUpdateCategory } from './categories/categories.validator.js'
|
| 1029 |
-
import { getCategories, postCategory, putCategory, deleteCategory } from './categories/categories.controller.js'
|
| 1030 |
-
|
| 1031 |
-
const router: ExpressRouter = Router()
|
| 1032 |
-
|
| 1033 |
-
// ── Categories (fixed paths first) ───────────────────────────────────────────
|
| 1034 |
-
router.get('/categories', getCategories)
|
| 1035 |
-
router.post('/categories', validateCreateCategory, postCategory)
|
| 1036 |
-
router.put('/categories/:id', validateUpdateCategory, putCategory)
|
| 1037 |
-
router.delete('/categories/:id', deleteCategory)
|
| 1038 |
-
|
| 1039 |
-
// ── Existing OCR route ────────────────────────────────────────────────────────
|
| 1040 |
-
router.post('/parse', validateExpense, parseExpense)
|
| 1041 |
-
|
| 1042 |
-
export { router as expenseRouter }
|
| 1043 |
-
```
|
| 1044 |
-
|
| 1045 |
-
- [ ] **Step 7: Run full test suite**
|
| 1046 |
-
|
| 1047 |
-
```bash
|
| 1048 |
-
pnpm -F @llm-router/api test
|
| 1049 |
-
```
|
| 1050 |
-
|
| 1051 |
-
Expected: all 26 original tests pass + categories service tests (pass or skip).
|
| 1052 |
-
|
| 1053 |
-
- [ ] **Step 8: Commit**
|
| 1054 |
-
|
| 1055 |
-
```bash
|
| 1056 |
-
git add apps/api/src/expense/categories apps/api/src/expense/expense.routes.ts
|
| 1057 |
-
git commit -m "feat: add categories CRUD API with 409 delete protection"
|
| 1058 |
-
```
|
| 1059 |
-
|
| 1060 |
-
---
|
| 1061 |
-
|
| 1062 |
-
### Task 6: Expenses CRUD API — list/filter, manual create, get/update/delete
|
| 1063 |
-
|
| 1064 |
-
**Files:**
|
| 1065 |
-
- Create: `apps/api/src/expense/expenses.service.ts`
|
| 1066 |
-
- Create: `apps/api/src/expense/expenses.service.test.ts`
|
| 1067 |
-
- Modify: `apps/api/src/expense/expense.controller.ts` — add CRUD handlers
|
| 1068 |
-
- Modify: `apps/api/src/expense/expense.validator.ts` — add manual expense schema
|
| 1069 |
-
- Modify: `apps/api/src/expense/expense.routes.ts` — add CRUD routes
|
| 1070 |
-
|
| 1071 |
-
**Interfaces:**
|
| 1072 |
-
- Consumes: `db` client, `expenses`, `categories`, `userProfile` tables, `CreateExpenseSchema`, `UpdateExpenseSchema` from `@llm-router/shared`
|
| 1073 |
-
- Produces routes: `GET /`, `POST /manual`, `GET /:id`, `PUT /:id`, `DELETE /:id`
|
| 1074 |
-
|
| 1075 |
-
- [ ] **Step 1: Write the failing service test first**
|
| 1076 |
-
|
| 1077 |
-
Create `apps/api/src/expense/expenses.service.test.ts`:
|
| 1078 |
-
|
| 1079 |
-
```ts
|
| 1080 |
-
import { describe, it, expect } from 'vitest'
|
| 1081 |
-
import { listExpenses, createExpense, getExpense, updateExpense, deleteExpense } from './expenses.service.js'
|
| 1082 |
-
|
| 1083 |
-
describe.skipIf(!process.env['DATABASE_URL'])('expenses service', () => {
|
| 1084 |
-
let expenseId: string
|
| 1085 |
-
let categoryId: string
|
| 1086 |
-
|
| 1087 |
-
it('listExpenses returns paginated result', async () => {
|
| 1088 |
-
const result = await listExpenses({})
|
| 1089 |
-
expect(Array.isArray(result.data)).toBe(true)
|
| 1090 |
-
expect(typeof result.total).toBe('number')
|
| 1091 |
-
})
|
| 1092 |
-
|
| 1093 |
-
it('createExpense inserts a row using preferred currency', async () => {
|
| 1094 |
-
// Get a valid category_id first
|
| 1095 |
-
const { db } = await import('./db/client.js')
|
| 1096 |
-
const { categories } = await import('./db/schema.js')
|
| 1097 |
-
const cats = await db.select().from(categories).limit(1)
|
| 1098 |
-
categoryId = cats[0]?.id ?? ''
|
| 1099 |
-
if (!categoryId) return
|
| 1100 |
-
|
| 1101 |
-
const expense = await createExpense({
|
| 1102 |
-
amount: 99.99,
|
| 1103 |
-
category_id: categoryId,
|
| 1104 |
-
date: '2026-06-30',
|
| 1105 |
-
merchant: 'Test Merchant',
|
| 1106 |
-
})
|
| 1107 |
-
expenseId = expense.id
|
| 1108 |
-
expect(expense.amount).toBe(99.99)
|
| 1109 |
-
expect(expense.source).toBe('manual')
|
| 1110 |
-
})
|
| 1111 |
-
|
| 1112 |
-
it('getExpense returns the created expense', async () => {
|
| 1113 |
-
if (!expenseId) return
|
| 1114 |
-
const expense = await getExpense(expenseId)
|
| 1115 |
-
expect(expense).not.toBeNull()
|
| 1116 |
-
expect(expense?.merchant).toBe('Test Merchant')
|
| 1117 |
-
})
|
| 1118 |
-
|
| 1119 |
-
it('updateExpense modifies merchant', async () => {
|
| 1120 |
-
if (!expenseId) return
|
| 1121 |
-
const updated = await updateExpense(expenseId, { merchant: 'Updated Merchant' })
|
| 1122 |
-
expect(updated.merchant).toBe('Updated Merchant')
|
| 1123 |
-
})
|
| 1124 |
-
|
| 1125 |
-
it('deleteExpense removes the row', async () => {
|
| 1126 |
-
if (!expenseId) return
|
| 1127 |
-
await deleteExpense(expenseId)
|
| 1128 |
-
const gone = await getExpense(expenseId)
|
| 1129 |
-
expect(gone).toBeNull()
|
| 1130 |
-
})
|
| 1131 |
-
})
|
| 1132 |
-
```
|
| 1133 |
-
|
| 1134 |
-
- [ ] **Step 2: Run test to verify it fails**
|
| 1135 |
-
|
| 1136 |
-
```bash
|
| 1137 |
-
pnpm -F @llm-router/api test src/expense/expenses.service.test.ts
|
| 1138 |
-
```
|
| 1139 |
-
|
| 1140 |
-
Expected: SKIP or FAIL.
|
| 1141 |
-
|
| 1142 |
-
- [ ] **Step 3: Create `apps/api/src/expense/expenses.service.ts`**
|
| 1143 |
-
|
| 1144 |
-
```ts
|
| 1145 |
-
import { eq, and, gte, lte, ilike, sql, count } from 'drizzle-orm'
|
| 1146 |
-
import { db } from './db/client.js'
|
| 1147 |
-
import { expenses, userProfile } from './db/schema.js'
|
| 1148 |
-
import type { CreateExpense, UpdateExpense, Expense } from '@llm-router/shared'
|
| 1149 |
-
|
| 1150 |
-
export interface ListExpensesFilter {
|
| 1151 |
-
category_id?: string
|
| 1152 |
-
from?: string
|
| 1153 |
-
to?: string
|
| 1154 |
-
search?: string
|
| 1155 |
-
page?: number
|
| 1156 |
-
limit?: number
|
| 1157 |
-
}
|
| 1158 |
-
|
| 1159 |
-
export interface ListExpensesResult {
|
| 1160 |
-
data: Expense[]
|
| 1161 |
-
total: number
|
| 1162 |
-
page: number
|
| 1163 |
-
limit: number
|
| 1164 |
-
}
|
| 1165 |
-
|
| 1166 |
-
function rowToExpense(r: typeof expenses.$inferSelect): Expense {
|
| 1167 |
-
return {
|
| 1168 |
-
id: r.id,
|
| 1169 |
-
amount: Number(r.amount),
|
| 1170 |
-
currency: r.currency,
|
| 1171 |
-
category_id: r.category_id,
|
| 1172 |
-
merchant: r.merchant ?? null,
|
| 1173 |
-
date: r.date,
|
| 1174 |
-
description: r.description ?? null,
|
| 1175 |
-
source: r.source,
|
| 1176 |
-
raw_text: r.raw_text ?? null,
|
| 1177 |
-
created_at: r.created_at.toISOString(),
|
| 1178 |
-
updated_at: r.updated_at.toISOString(),
|
| 1179 |
-
}
|
| 1180 |
-
}
|
| 1181 |
-
|
| 1182 |
-
export async function listExpenses(filter: ListExpensesFilter): Promise<ListExpensesResult> {
|
| 1183 |
-
const page = filter.page ?? 1
|
| 1184 |
-
const limit = Math.min(filter.limit ?? 20, 100)
|
| 1185 |
-
const offset = (page - 1) * limit
|
| 1186 |
-
|
| 1187 |
-
const conditions = []
|
| 1188 |
-
if (filter.category_id) conditions.push(eq(expenses.category_id, filter.category_id))
|
| 1189 |
-
if (filter.from) conditions.push(gte(expenses.date, filter.from))
|
| 1190 |
-
if (filter.to) conditions.push(lte(expenses.date, filter.to))
|
| 1191 |
-
if (filter.search) {
|
| 1192 |
-
conditions.push(
|
| 1193 |
-
ilike(expenses.merchant, `%${filter.search}%`)
|
| 1194 |
-
)
|
| 1195 |
-
}
|
| 1196 |
-
|
| 1197 |
-
const where = conditions.length > 0 ? and(...conditions) : undefined
|
| 1198 |
-
|
| 1199 |
-
const [rows, countRows] = await Promise.all([
|
| 1200 |
-
db.select().from(expenses).where(where).orderBy(expenses.date).limit(limit).offset(offset),
|
| 1201 |
-
db.select({ count: count() }).from(expenses).where(where),
|
| 1202 |
-
])
|
| 1203 |
-
|
| 1204 |
-
return {
|
| 1205 |
-
data: rows.map(rowToExpense),
|
| 1206 |
-
total: countRows[0]?.count ?? 0,
|
| 1207 |
-
page,
|
| 1208 |
-
limit,
|
| 1209 |
-
}
|
| 1210 |
-
}
|
| 1211 |
-
|
| 1212 |
-
export async function createExpense(input: CreateExpense): Promise<Expense> {
|
| 1213 |
-
const profile = await db.select().from(userProfile).limit(1)
|
| 1214 |
-
const currency = input.currency ?? profile[0]?.preferred_currency ?? 'USD'
|
| 1215 |
-
|
| 1216 |
-
const [row] = await db
|
| 1217 |
-
.insert(expenses)
|
| 1218 |
-
.values({
|
| 1219 |
-
amount: String(input.amount),
|
| 1220 |
-
currency,
|
| 1221 |
-
category_id: input.category_id,
|
| 1222 |
-
merchant: input.merchant,
|
| 1223 |
-
date: input.date,
|
| 1224 |
-
description: input.description,
|
| 1225 |
-
source: 'manual',
|
| 1226 |
-
})
|
| 1227 |
-
.returning()
|
| 1228 |
-
if (!row) throw new Error('Insert failed')
|
| 1229 |
-
return rowToExpense(row)
|
| 1230 |
-
}
|
| 1231 |
-
|
| 1232 |
-
export async function getExpense(id: string): Promise<Expense | null> {
|
| 1233 |
-
const rows = await db.select().from(expenses).where(eq(expenses.id, id)).limit(1)
|
| 1234 |
-
const row = rows[0]
|
| 1235 |
-
return row ? rowToExpense(row) : null
|
| 1236 |
-
}
|
| 1237 |
-
|
| 1238 |
-
export async function updateExpense(id: string, input: UpdateExpense): Promise<Expense> {
|
| 1239 |
-
const updates: Partial<typeof expenses.$inferInsert> = {}
|
| 1240 |
-
if (input.amount !== undefined) updates.amount = String(input.amount)
|
| 1241 |
-
if (input.currency !== undefined) updates.currency = input.currency
|
| 1242 |
-
if (input.category_id !== undefined) updates.category_id = input.category_id
|
| 1243 |
-
if (input.merchant !== undefined) updates.merchant = input.merchant
|
| 1244 |
-
if (input.date !== undefined) updates.date = input.date
|
| 1245 |
-
if (input.description !== undefined) updates.description = input.description
|
| 1246 |
-
updates.updated_at = new Date()
|
| 1247 |
-
|
| 1248 |
-
const [row] = await db.update(expenses).set(updates).where(eq(expenses.id, id)).returning()
|
| 1249 |
-
if (!row) throw new Error(`Expense ${id} not found`)
|
| 1250 |
-
return rowToExpense(row)
|
| 1251 |
-
}
|
| 1252 |
-
|
| 1253 |
-
export async function deleteExpense(id: string): Promise<void> {
|
| 1254 |
-
await db.delete(expenses).where(eq(expenses.id, id))
|
| 1255 |
-
}
|
| 1256 |
-
```
|
| 1257 |
-
|
| 1258 |
-
- [ ] **Step 4: Add `validateManualExpense` to `apps/api/src/expense/expense.validator.ts`**
|
| 1259 |
-
|
| 1260 |
-
Add at the bottom of the existing file:
|
| 1261 |
-
|
| 1262 |
-
```ts
|
| 1263 |
-
import { CreateExpenseSchema, UpdateExpenseSchema } from '@llm-router/shared'
|
| 1264 |
-
|
| 1265 |
-
export const validateManualExpense = validate(CreateExpenseSchema)
|
| 1266 |
-
export const validateUpdateExpense = validate(UpdateExpenseSchema)
|
| 1267 |
-
```
|
| 1268 |
-
|
| 1269 |
-
- [ ] **Step 5: Add CRUD handlers to `apps/api/src/expense/expense.controller.ts`**
|
| 1270 |
-
|
| 1271 |
-
Add at the bottom of the existing file (after existing `parseExpense` handler):
|
| 1272 |
-
|
| 1273 |
-
```ts
|
| 1274 |
-
import * as expensesSvc from './expenses.service.js'
|
| 1275 |
-
|
| 1276 |
-
export const getExpenses: RequestHandler = async (req, res) => {
|
| 1277 |
-
const { category_id, from, to, search, page, limit } = req.query as Record<string, string | undefined>
|
| 1278 |
-
const result = await expensesSvc.listExpenses({
|
| 1279 |
-
category_id,
|
| 1280 |
-
from,
|
| 1281 |
-
to,
|
| 1282 |
-
search,
|
| 1283 |
-
page: page ? Number(page) : undefined,
|
| 1284 |
-
limit: limit ? Number(limit) : undefined,
|
| 1285 |
-
})
|
| 1286 |
-
res.json(result)
|
| 1287 |
-
}
|
| 1288 |
-
|
| 1289 |
-
export const postManualExpense: RequestHandler = async (req, res) => {
|
| 1290 |
-
const data = await expensesSvc.createExpense(req.body)
|
| 1291 |
-
res.status(201).json(data)
|
| 1292 |
-
}
|
| 1293 |
-
|
| 1294 |
-
export const getExpense: RequestHandler = async (req, res) => {
|
| 1295 |
-
const data = await expensesSvc.getExpense(req.params['id'] ?? '')
|
| 1296 |
-
if (!data) {
|
| 1297 |
-
res.status(404).json({ error: 'Expense not found' })
|
| 1298 |
-
return
|
| 1299 |
-
}
|
| 1300 |
-
res.json(data)
|
| 1301 |
-
}
|
| 1302 |
-
|
| 1303 |
-
export const putExpense: RequestHandler = async (req, res) => {
|
| 1304 |
-
const data = await expensesSvc.updateExpense(req.params['id'] ?? '', req.body)
|
| 1305 |
-
res.json(data)
|
| 1306 |
-
}
|
| 1307 |
-
|
| 1308 |
-
export const deleteExpenseHandler: RequestHandler = async (req, res) => {
|
| 1309 |
-
await expensesSvc.deleteExpense(req.params['id'] ?? '')
|
| 1310 |
-
res.status(204).send()
|
| 1311 |
-
}
|
| 1312 |
-
```
|
| 1313 |
-
|
| 1314 |
-
- [ ] **Step 6: Add expense CRUD routes to `apps/api/src/expense/expense.routes.ts`**
|
| 1315 |
-
|
| 1316 |
-
Add the new imports and routes. The updated file:
|
| 1317 |
-
|
| 1318 |
-
```ts
|
| 1319 |
-
import { Router } from 'express'
|
| 1320 |
-
import type { Router as ExpressRouter } from 'express'
|
| 1321 |
-
|
| 1322 |
-
import { validateExpense, validateManualExpense, validateUpdateExpense } from './expense.validator.js'
|
| 1323 |
-
import { parseExpense, getExpenses, postManualExpense, getExpense, putExpense, deleteExpenseHandler } from './expense.controller.js'
|
| 1324 |
-
|
| 1325 |
-
import { validateCreateCategory, validateUpdateCategory } from './categories/categories.validator.js'
|
| 1326 |
-
import { getCategories, postCategory, putCategory, deleteCategory } from './categories/categories.controller.js'
|
| 1327 |
-
|
| 1328 |
-
const router: ExpressRouter = Router()
|
| 1329 |
-
|
| 1330 |
-
// ── Fixed paths BEFORE /:id ───────────────────────────────────────────────────
|
| 1331 |
-
router.get('/categories', getCategories)
|
| 1332 |
-
router.post('/categories', validateCreateCategory, postCategory)
|
| 1333 |
-
router.put('/categories/:id', validateUpdateCategory, putCategory)
|
| 1334 |
-
router.delete('/categories/:id', deleteCategory)
|
| 1335 |
-
|
| 1336 |
-
router.post('/parse', validateExpense, parseExpense)
|
| 1337 |
-
router.post('/manual', validateManualExpense, postManualExpense)
|
| 1338 |
-
|
| 1339 |
-
// ── Parameterized routes LAST ─────────────────────────────────────────────────
|
| 1340 |
-
router.get('/', getExpenses)
|
| 1341 |
-
router.get('/:id', getExpense)
|
| 1342 |
-
router.put('/:id', validateUpdateExpense, putExpense)
|
| 1343 |
-
router.delete('/:id', deleteExpenseHandler)
|
| 1344 |
-
|
| 1345 |
-
export { router as expenseRouter }
|
| 1346 |
-
```
|
| 1347 |
-
|
| 1348 |
-
- [ ] **Step 7: Run full test suite**
|
| 1349 |
-
|
| 1350 |
-
```bash
|
| 1351 |
-
pnpm -F @llm-router/api test
|
| 1352 |
-
```
|
| 1353 |
-
|
| 1354 |
-
Expected: all 26 original tests pass.
|
| 1355 |
-
|
| 1356 |
-
- [ ] **Step 8: Commit**
|
| 1357 |
-
|
| 1358 |
-
```bash
|
| 1359 |
-
git add apps/api/src/expense/expenses.service.ts apps/api/src/expense/expenses.service.test.ts apps/api/src/expense/expense.controller.ts apps/api/src/expense/expense.validator.ts apps/api/src/expense/expense.routes.ts
|
| 1360 |
-
git commit -m "feat: add expenses CRUD API (list, manual create, get, update, delete)"
|
| 1361 |
-
```
|
| 1362 |
-
|
| 1363 |
-
---
|
| 1364 |
-
|
| 1365 |
-
### Task 7: Budgets API — CRUD
|
| 1366 |
-
|
| 1367 |
-
**Files:**
|
| 1368 |
-
- Create: `apps/api/src/expense/budgets/budgets.service.ts`
|
| 1369 |
-
- Create: `apps/api/src/expense/budgets/budgets.service.test.ts`
|
| 1370 |
-
- Create: `apps/api/src/expense/budgets/budgets.controller.ts`
|
| 1371 |
-
- Create: `apps/api/src/expense/budgets/budgets.validator.ts`
|
| 1372 |
-
- Modify: `apps/api/src/expense/expense.routes.ts`
|
| 1373 |
-
|
| 1374 |
-
**Interfaces:**
|
| 1375 |
-
- Consumes: `db` client, `budgets`, `expenses` tables, `CreateBudgetSchema`, `UpdateBudgetSchema` from `@llm-router/shared`
|
| 1376 |
-
- Produces routes: `GET /budgets`, `POST /budgets`, `PUT /budgets/:id`, `DELETE /budgets/:id`
|
| 1377 |
-
|
| 1378 |
-
- [ ] **Step 1: Write the failing service test first**
|
| 1379 |
-
|
| 1380 |
-
Create `apps/api/src/expense/budgets/budgets.service.test.ts`:
|
| 1381 |
-
|
| 1382 |
-
```ts
|
| 1383 |
-
import { describe, it, expect } from 'vitest'
|
| 1384 |
-
import { listBudgets, createBudget, updateBudget, deleteBudget } from './budgets.service.js'
|
| 1385 |
-
|
| 1386 |
-
describe.skipIf(!process.env['DATABASE_URL'])('budgets service', () => {
|
| 1387 |
-
let budgetId: string
|
| 1388 |
-
let categoryId: string
|
| 1389 |
-
|
| 1390 |
-
it('listBudgets returns an array', async () => {
|
| 1391 |
-
const result = await listBudgets()
|
| 1392 |
-
expect(Array.isArray(result)).toBe(true)
|
| 1393 |
-
})
|
| 1394 |
-
|
| 1395 |
-
it('createBudget creates a budget for a category', async () => {
|
| 1396 |
-
const { db } = await import('../db/client.js')
|
| 1397 |
-
const { categories } = await import('../db/schema.js')
|
| 1398 |
-
const cats = await db.select().from(categories).limit(1)
|
| 1399 |
-
categoryId = cats[0]?.id ?? ''
|
| 1400 |
-
if (!categoryId) return
|
| 1401 |
-
|
| 1402 |
-
const budget = await createBudget({ category_id: categoryId, amount: 500 })
|
| 1403 |
-
budgetId = budget.id
|
| 1404 |
-
expect(budget.amount).toBe(500)
|
| 1405 |
-
expect(budget.period).toBe('monthly')
|
| 1406 |
-
})
|
| 1407 |
-
|
| 1408 |
-
it('updateBudget changes amount', async () => {
|
| 1409 |
-
if (!budgetId) return
|
| 1410 |
-
const updated = await updateBudget(budgetId, { amount: 750 })
|
| 1411 |
-
expect(updated.amount).toBe(750)
|
| 1412 |
-
})
|
| 1413 |
-
|
| 1414 |
-
it('deleteBudget removes the row', async () => {
|
| 1415 |
-
if (!budgetId) return
|
| 1416 |
-
await deleteBudget(budgetId)
|
| 1417 |
-
const all = await listBudgets()
|
| 1418 |
-
expect(all.find((b) => b.id === budgetId)).toBeUndefined()
|
| 1419 |
-
})
|
| 1420 |
-
|
| 1421 |
-
it('createBudget throws on duplicate category+period', async () => {
|
| 1422 |
-
if (!categoryId) return
|
| 1423 |
-
await createBudget({ category_id: categoryId, amount: 100 }).catch(() => {})
|
| 1424 |
-
await expect(createBudget({ category_id: categoryId, amount: 200 })).rejects.toThrow()
|
| 1425 |
-
// cleanup
|
| 1426 |
-
const all = await listBudgets()
|
| 1427 |
-
const dup = all.find((b) => b.category_id === categoryId)
|
| 1428 |
-
if (dup) await deleteBudget(dup.id)
|
| 1429 |
-
})
|
| 1430 |
-
})
|
| 1431 |
-
```
|
| 1432 |
-
|
| 1433 |
-
- [ ] **Step 2: Run test to verify it fails**
|
| 1434 |
-
|
| 1435 |
-
```bash
|
| 1436 |
-
pnpm -F @llm-router/api test src/expense/budgets/budgets.service.test.ts
|
| 1437 |
-
```
|
| 1438 |
-
|
| 1439 |
-
Expected: SKIP or FAIL.
|
| 1440 |
-
|
| 1441 |
-
- [ ] **Step 3: Create `apps/api/src/expense/budgets/budgets.service.ts`**
|
| 1442 |
-
|
| 1443 |
-
```ts
|
| 1444 |
-
import { eq } from 'drizzle-orm'
|
| 1445 |
-
import { db } from '../db/client.js'
|
| 1446 |
-
import { budgets } from '../db/schema.js'
|
| 1447 |
-
import type { CreateBudget, UpdateBudget, Budget } from '@llm-router/shared'
|
| 1448 |
-
|
| 1449 |
-
function rowToBudget(r: typeof budgets.$inferSelect): Budget {
|
| 1450 |
-
return {
|
| 1451 |
-
id: r.id,
|
| 1452 |
-
category_id: r.category_id,
|
| 1453 |
-
amount: Number(r.amount),
|
| 1454 |
-
period: r.period,
|
| 1455 |
-
created_at: r.created_at.toISOString(),
|
| 1456 |
-
}
|
| 1457 |
-
}
|
| 1458 |
-
|
| 1459 |
-
export async function listBudgets(): Promise<Budget[]> {
|
| 1460 |
-
const rows = await db.select().from(budgets)
|
| 1461 |
-
return rows.map(rowToBudget)
|
| 1462 |
-
}
|
| 1463 |
-
|
| 1464 |
-
export async function createBudget(input: CreateBudget): Promise<Budget> {
|
| 1465 |
-
const [row] = await db
|
| 1466 |
-
.insert(budgets)
|
| 1467 |
-
.values({
|
| 1468 |
-
category_id: input.category_id,
|
| 1469 |
-
amount: String(input.amount),
|
| 1470 |
-
period: input.period ?? 'monthly',
|
| 1471 |
-
})
|
| 1472 |
-
.returning()
|
| 1473 |
-
if (!row) throw new Error('Insert failed')
|
| 1474 |
-
return rowToBudget(row)
|
| 1475 |
-
}
|
| 1476 |
-
|
| 1477 |
-
export async function updateBudget(id: string, input: UpdateBudget): Promise<Budget> {
|
| 1478 |
-
const updates: Partial<typeof budgets.$inferInsert> = {}
|
| 1479 |
-
if (input.amount !== undefined) updates.amount = String(input.amount)
|
| 1480 |
-
if (input.period !== undefined) updates.period = input.period
|
| 1481 |
-
updates.updated_at = new Date()
|
| 1482 |
-
|
| 1483 |
-
const [row] = await db.update(budgets).set(updates).where(eq(budgets.id, id)).returning()
|
| 1484 |
-
if (!row) throw new Error(`Budget ${id} not found`)
|
| 1485 |
-
return rowToBudget(row)
|
| 1486 |
-
}
|
| 1487 |
-
|
| 1488 |
-
export async function deleteBudget(id: string): Promise<void> {
|
| 1489 |
-
await db.delete(budgets).where(eq(budgets.id, id))
|
| 1490 |
-
}
|
| 1491 |
-
```
|
| 1492 |
-
|
| 1493 |
-
- [ ] **Step 4: Create `apps/api/src/expense/budgets/budgets.validator.ts`**
|
| 1494 |
-
|
| 1495 |
-
```ts
|
| 1496 |
-
import { CreateBudgetSchema, UpdateBudgetSchema } from '@llm-router/shared'
|
| 1497 |
-
import { validate } from '../../middleware/validate.js'
|
| 1498 |
-
|
| 1499 |
-
export const validateCreateBudget = validate(CreateBudgetSchema)
|
| 1500 |
-
export const validateUpdateBudget = validate(UpdateBudgetSchema)
|
| 1501 |
-
```
|
| 1502 |
-
|
| 1503 |
-
- [ ] **Step 5: Create `apps/api/src/expense/budgets/budgets.controller.ts`**
|
| 1504 |
-
|
| 1505 |
-
```ts
|
| 1506 |
-
import type { RequestHandler } from 'express'
|
| 1507 |
-
import * as svc from './budgets.service.js'
|
| 1508 |
-
|
| 1509 |
-
export const getBudgets: RequestHandler = async (_req, res) => {
|
| 1510 |
-
res.json(await svc.listBudgets())
|
| 1511 |
-
}
|
| 1512 |
-
|
| 1513 |
-
export const postBudget: RequestHandler = async (req, res) => {
|
| 1514 |
-
try {
|
| 1515 |
-
res.status(201).json(await svc.createBudget(req.body))
|
| 1516 |
-
} catch (err: unknown) {
|
| 1517 |
-
if (err instanceof Error && err.message.includes('unique')) {
|
| 1518 |
-
res.status(409).json({ error: 'A budget for this category and period already exists' })
|
| 1519 |
-
return
|
| 1520 |
-
}
|
| 1521 |
-
throw err
|
| 1522 |
-
}
|
| 1523 |
-
}
|
| 1524 |
-
|
| 1525 |
-
export const putBudget: RequestHandler = async (req, res) => {
|
| 1526 |
-
res.json(await svc.updateBudget(req.params['id'] ?? '', req.body))
|
| 1527 |
-
}
|
| 1528 |
-
|
| 1529 |
-
export const deleteBudget: RequestHandler = async (req, res) => {
|
| 1530 |
-
await svc.deleteBudget(req.params['id'] ?? '')
|
| 1531 |
-
res.status(204).send()
|
| 1532 |
-
}
|
| 1533 |
-
```
|
| 1534 |
-
|
| 1535 |
-
- [ ] **Step 6: Add budget routes to `apps/api/src/expense/expense.routes.ts`**
|
| 1536 |
-
|
| 1537 |
-
Add budget imports and routes after the categories block, before the expense CRUD block:
|
| 1538 |
-
|
| 1539 |
-
```ts
|
| 1540 |
-
import { validateCreateBudget, validateUpdateBudget } from './budgets/budgets.validator.js'
|
| 1541 |
-
import { getBudgets, postBudget, putBudget, deleteBudget } from './budgets/budgets.controller.js'
|
| 1542 |
-
|
| 1543 |
-
// add after categories routes, before /parse:
|
| 1544 |
-
router.get('/budgets', getBudgets)
|
| 1545 |
-
router.post('/budgets', validateCreateBudget, postBudget)
|
| 1546 |
-
router.put('/budgets/:id', validateUpdateBudget, putBudget)
|
| 1547 |
-
router.delete('/budgets/:id', deleteBudget)
|
| 1548 |
-
```
|
| 1549 |
-
|
| 1550 |
-
- [ ] **Step 7: Run full test suite**
|
| 1551 |
-
|
| 1552 |
-
```bash
|
| 1553 |
-
pnpm -F @llm-router/api test
|
| 1554 |
-
```
|
| 1555 |
-
|
| 1556 |
-
Expected: all tests pass (or skip DB tests).
|
| 1557 |
-
|
| 1558 |
-
- [ ] **Step 8: Commit**
|
| 1559 |
-
|
| 1560 |
-
```bash
|
| 1561 |
-
git add apps/api/src/expense/budgets apps/api/src/expense/expense.routes.ts
|
| 1562 |
-
git commit -m "feat: add budgets CRUD API"
|
| 1563 |
-
```
|
| 1564 |
-
|
| 1565 |
-
---
|
| 1566 |
-
|
| 1567 |
-
### Task 8: Analytics API — summary + trends
|
| 1568 |
-
|
| 1569 |
-
**Files:**
|
| 1570 |
-
- Create: `apps/api/src/expense/analytics/analytics.service.ts`
|
| 1571 |
-
- Create: `apps/api/src/expense/analytics/analytics.service.test.ts`
|
| 1572 |
-
- Create: `apps/api/src/expense/analytics/analytics.controller.ts`
|
| 1573 |
-
- Modify: `apps/api/src/expense/expense.routes.ts`
|
| 1574 |
-
|
| 1575 |
-
**Interfaces:**
|
| 1576 |
-
- Consumes: `db`, `expenses`, `budgets`, `userProfile` tables
|
| 1577 |
-
- Produces routes: `GET /summary`, `GET /trends?months=6`
|
| 1578 |
-
|
| 1579 |
-
- [ ] **Step 1: Write the failing unit test for `getCurrentPeriod` first**
|
| 1580 |
-
|
| 1581 |
-
Create `apps/api/src/expense/analytics/analytics.service.test.ts`:
|
| 1582 |
-
|
| 1583 |
-
```ts
|
| 1584 |
-
import { describe, it, expect } from 'vitest'
|
| 1585 |
-
import { getCurrentPeriod } from './analytics.service.js'
|
| 1586 |
-
|
| 1587 |
-
describe('getCurrentPeriod', () => {
|
| 1588 |
-
it('returns calendar month when reset day is 1', () => {
|
| 1589 |
-
const result = getCurrentPeriod(1, new Date('2026-06-15'))
|
| 1590 |
-
expect(result.label).toBe('2026-06')
|
| 1591 |
-
expect(result.start.toISOString().slice(0, 10)).toBe('2026-06-01')
|
| 1592 |
-
expect(result.end.toISOString().slice(0, 10)).toBe('2026-06-30')
|
| 1593 |
-
})
|
| 1594 |
-
|
| 1595 |
-
it('wraps to previous month when day is before reset day', () => {
|
| 1596 |
-
const result = getCurrentPeriod(10, new Date('2026-06-05'))
|
| 1597 |
-
expect(result.label).toBe('2026-05')
|
| 1598 |
-
expect(result.start.toISOString().slice(0, 10)).toBe('2026-05-10')
|
| 1599 |
-
expect(result.end.toISOString().slice(0, 10)).toBe('2026-06-09')
|
| 1600 |
-
})
|
| 1601 |
-
|
| 1602 |
-
it('uses current month when day equals reset day', () => {
|
| 1603 |
-
const result = getCurrentPeriod(15, new Date('2026-06-15'))
|
| 1604 |
-
expect(result.label).toBe('2026-06')
|
| 1605 |
-
expect(result.start.toISOString().slice(0, 10)).toBe('2026-06-15')
|
| 1606 |
-
})
|
| 1607 |
-
|
| 1608 |
-
it('handles December wrap to January correctly', () => {
|
| 1609 |
-
const result = getCurrentPeriod(20, new Date('2026-12-10'))
|
| 1610 |
-
expect(result.label).toBe('2026-11')
|
| 1611 |
-
expect(result.start.toISOString().slice(0, 10)).toBe('2026-11-20')
|
| 1612 |
-
expect(result.end.toISOString().slice(0, 10)).toBe('2026-12-19')
|
| 1613 |
-
})
|
| 1614 |
-
})
|
| 1615 |
-
```
|
| 1616 |
-
|
| 1617 |
-
- [ ] **Step 2: Run test to verify it fails**
|
| 1618 |
-
|
| 1619 |
-
```bash
|
| 1620 |
-
pnpm -F @llm-router/api test src/expense/analytics/analytics.service.test.ts
|
| 1621 |
-
```
|
| 1622 |
-
|
| 1623 |
-
Expected: FAIL — `analytics.service.js` does not exist.
|
| 1624 |
-
|
| 1625 |
-
- [ ] **Step 3: Create `apps/api/src/expense/analytics/analytics.service.ts`**
|
| 1626 |
-
|
| 1627 |
-
```ts
|
| 1628 |
-
import { and, gte, lte, eq, sql } from 'drizzle-orm'
|
| 1629 |
-
import { db } from '../db/client.js'
|
| 1630 |
-
import { expenses, budgets, categories, userProfile } from '../db/schema.js'
|
| 1631 |
-
import type { Summary, Trends } from '@llm-router/shared'
|
| 1632 |
-
|
| 1633 |
-
export function getCurrentPeriod(
|
| 1634 |
-
budgetResetDay: number,
|
| 1635 |
-
now: Date = new Date()
|
| 1636 |
-
): { start: Date; end: Date; label: string } {
|
| 1637 |
-
const year = now.getFullYear()
|
| 1638 |
-
const month = now.getMonth()
|
| 1639 |
-
const day = now.getDate()
|
| 1640 |
-
|
| 1641 |
-
let start: Date
|
| 1642 |
-
let end: Date
|
| 1643 |
-
|
| 1644 |
-
if (day >= budgetResetDay) {
|
| 1645 |
-
start = new Date(year, month, budgetResetDay)
|
| 1646 |
-
end = new Date(year, month + 1, budgetResetDay - 1)
|
| 1647 |
-
} else {
|
| 1648 |
-
start = new Date(year, month - 1, budgetResetDay)
|
| 1649 |
-
end = new Date(year, month, budgetResetDay - 1)
|
| 1650 |
-
}
|
| 1651 |
-
|
| 1652 |
-
const label = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}`
|
| 1653 |
-
return { start, end, label }
|
| 1654 |
-
}
|
| 1655 |
-
|
| 1656 |
-
export async function getSummary(): Promise<Summary> {
|
| 1657 |
-
const profile = await db.select().from(userProfile).limit(1)
|
| 1658 |
-
const resetDay = profile[0]?.budget_reset_day ?? 1
|
| 1659 |
-
const preferredCurrency = profile[0]?.preferred_currency ?? 'USD'
|
| 1660 |
-
const { start, end, label } = getCurrentPeriod(resetDay)
|
| 1661 |
-
|
| 1662 |
-
const startStr = start.toISOString().slice(0, 10)
|
| 1663 |
-
const endStr = end.toISOString().slice(0, 10)
|
| 1664 |
-
|
| 1665 |
-
const allExpenses = await db
|
| 1666 |
-
.select()
|
| 1667 |
-
.from(expenses)
|
| 1668 |
-
.where(and(gte(expenses.date, startStr), lte(expenses.date, endStr)))
|
| 1669 |
-
|
| 1670 |
-
const allBudgets = await db.select().from(budgets)
|
| 1671 |
-
const allCategories = await db.select().from(categories)
|
| 1672 |
-
|
| 1673 |
-
const currencyWarning = allExpenses.some((e) => e.currency !== preferredCurrency)
|
| 1674 |
-
const periodExpenses = allExpenses.filter((e) => e.currency === preferredCurrency)
|
| 1675 |
-
|
| 1676 |
-
const totalSpent = periodExpenses.reduce((sum, e) => sum + Number(e.amount), 0)
|
| 1677 |
-
|
| 1678 |
-
const spentByCategory = new Map<string, number>()
|
| 1679 |
-
for (const e of periodExpenses) {
|
| 1680 |
-
spentByCategory.set(e.category_id, (spentByCategory.get(e.category_id) ?? 0) + Number(e.amount))
|
| 1681 |
-
}
|
| 1682 |
-
|
| 1683 |
-
const budgetByCategory = new Map<string, number>()
|
| 1684 |
-
for (const b of allBudgets) {
|
| 1685 |
-
budgetByCategory.set(b.category_id, Number(b.amount))
|
| 1686 |
-
}
|
| 1687 |
-
|
| 1688 |
-
const summaryCategories = allCategories.map((cat) => {
|
| 1689 |
-
const spent = spentByCategory.get(cat.id) ?? 0
|
| 1690 |
-
const budget = budgetByCategory.get(cat.id) ?? null
|
| 1691 |
-
return {
|
| 1692 |
-
category_id: cat.id,
|
| 1693 |
-
category_name: cat.name,
|
| 1694 |
-
color: cat.color,
|
| 1695 |
-
spent,
|
| 1696 |
-
budget,
|
| 1697 |
-
over_budget: budget !== null && spent > budget,
|
| 1698 |
-
}
|
| 1699 |
-
})
|
| 1700 |
-
|
| 1701 |
-
return {
|
| 1702 |
-
period: label,
|
| 1703 |
-
total_spent: totalSpent,
|
| 1704 |
-
currency_warning: currencyWarning,
|
| 1705 |
-
categories: summaryCategories,
|
| 1706 |
-
}
|
| 1707 |
-
}
|
| 1708 |
-
|
| 1709 |
-
export async function getTrends(months: number): Promise<Trends> {
|
| 1710 |
-
const profile = await db.select().from(userProfile).limit(1)
|
| 1711 |
-
const preferredCurrency = profile[0]?.preferred_currency ?? 'USD'
|
| 1712 |
-
|
| 1713 |
-
// Compute cutoff date in JS — avoids sql.raw with user input
|
| 1714 |
-
const cutoff = new Date()
|
| 1715 |
-
cutoff.setMonth(cutoff.getMonth() - months)
|
| 1716 |
-
const fromStr = cutoff.toISOString().slice(0, 10)
|
| 1717 |
-
|
| 1718 |
-
const rows = await db
|
| 1719 |
-
.select({
|
| 1720 |
-
period: sql<string>`to_char(date::date, 'YYYY-MM')`,
|
| 1721 |
-
total: sql<number>`cast(sum(amount::numeric) as float)`,
|
| 1722 |
-
})
|
| 1723 |
-
.from(expenses)
|
| 1724 |
-
.where(
|
| 1725 |
-
and(
|
| 1726 |
-
eq(expenses.currency, preferredCurrency),
|
| 1727 |
-
gte(expenses.date, fromStr)
|
| 1728 |
-
)
|
| 1729 |
-
)
|
| 1730 |
-
.groupBy(sql`to_char(date::date, 'YYYY-MM')`)
|
| 1731 |
-
.orderBy(sql`to_char(date::date, 'YYYY-MM')`)
|
| 1732 |
-
|
| 1733 |
-
return {
|
| 1734 |
-
months: rows.map((r) => ({
|
| 1735 |
-
period: r.period,
|
| 1736 |
-
total: r.total ?? 0,
|
| 1737 |
-
})),
|
| 1738 |
-
}
|
| 1739 |
-
}
|
| 1740 |
-
```
|
| 1741 |
-
|
| 1742 |
-
- [ ] **Step 4: Create `apps/api/src/expense/analytics/analytics.controller.ts`**
|
| 1743 |
-
|
| 1744 |
-
```ts
|
| 1745 |
-
import type { RequestHandler } from 'express'
|
| 1746 |
-
import * as svc from './analytics.service.js'
|
| 1747 |
-
|
| 1748 |
-
export const getSummary: RequestHandler = async (_req, res) => {
|
| 1749 |
-
const data = await svc.getSummary()
|
| 1750 |
-
res.json(data)
|
| 1751 |
-
}
|
| 1752 |
-
|
| 1753 |
-
export const getTrends: RequestHandler = async (req, res) => {
|
| 1754 |
-
const months = Number(req.query['months'] ?? 6)
|
| 1755 |
-
const data = await svc.getTrends(months)
|
| 1756 |
-
res.json(data)
|
| 1757 |
-
}
|
| 1758 |
-
```
|
| 1759 |
-
|
| 1760 |
-
- [ ] **Step 5: Add analytics routes to `apps/api/src/expense/expense.routes.ts`**
|
| 1761 |
-
|
| 1762 |
-
Add analytics imports and routes in the fixed-paths section (before `/parse`):
|
| 1763 |
-
|
| 1764 |
-
```ts
|
| 1765 |
-
import { getSummary, getTrends } from './analytics/analytics.controller.js'
|
| 1766 |
-
|
| 1767 |
-
// add after /budgets routes, before /parse:
|
| 1768 |
-
router.get('/summary', getSummary)
|
| 1769 |
-
router.get('/trends', getTrends)
|
| 1770 |
-
```
|
| 1771 |
-
|
| 1772 |
-
- [ ] **Step 6: Run the unit tests to verify they pass**
|
| 1773 |
-
|
| 1774 |
-
```bash
|
| 1775 |
-
pnpm -F @llm-router/api test src/expense/analytics/analytics.service.test.ts
|
| 1776 |
-
```
|
| 1777 |
-
|
| 1778 |
-
Expected:
|
| 1779 |
-
```
|
| 1780 |
-
✓ src/expense/analytics/analytics.service.test.ts (4 tests)
|
| 1781 |
-
```
|
| 1782 |
-
|
| 1783 |
-
- [ ] **Step 7: Run full test suite**
|
| 1784 |
-
|
| 1785 |
-
```bash
|
| 1786 |
-
pnpm -F @llm-router/api test
|
| 1787 |
-
```
|
| 1788 |
-
|
| 1789 |
-
Expected: all tests pass.
|
| 1790 |
-
|
| 1791 |
-
- [ ] **Step 8: Commit**
|
| 1792 |
-
|
| 1793 |
-
```bash
|
| 1794 |
-
git add apps/api/src/expense/analytics apps/api/src/expense/expense.routes.ts
|
| 1795 |
-
git commit -m "feat: add analytics API (summary with over_budget flags + trends)"
|
| 1796 |
-
```
|
| 1797 |
-
|
| 1798 |
-
---
|
| 1799 |
-
|
| 1800 |
-
### Task 9: Profile API — get + update user preferences
|
| 1801 |
-
|
| 1802 |
-
**Files:**
|
| 1803 |
-
- Create: `apps/api/src/expense/profile/profile.service.ts`
|
| 1804 |
-
- Create: `apps/api/src/expense/profile/profile.service.test.ts`
|
| 1805 |
-
- Create: `apps/api/src/expense/profile/profile.controller.ts`
|
| 1806 |
-
- Create: `apps/api/src/expense/profile/profile.validator.ts`
|
| 1807 |
-
- Modify: `apps/api/src/expense/expense.routes.ts`
|
| 1808 |
-
|
| 1809 |
-
**Interfaces:**
|
| 1810 |
-
- Consumes: `db`, `userProfile` table, `UpdateProfileSchema` from `@llm-router/shared`
|
| 1811 |
-
- Produces routes: `GET /profile`, `PUT /profile`
|
| 1812 |
-
|
| 1813 |
-
- [ ] **Step 1: Write the failing service test first**
|
| 1814 |
-
|
| 1815 |
-
Create `apps/api/src/expense/profile/profile.service.test.ts`:
|
| 1816 |
-
|
| 1817 |
-
```ts
|
| 1818 |
-
import { describe, it, expect } from 'vitest'
|
| 1819 |
-
import { getProfile, updateProfile } from './profile.service.js'
|
| 1820 |
-
|
| 1821 |
-
describe.skipIf(!process.env['DATABASE_URL'])('profile service', () => {
|
| 1822 |
-
it('getProfile returns the seeded profile', async () => {
|
| 1823 |
-
const profile = await getProfile()
|
| 1824 |
-
expect(profile.preferred_currency).toBe('USD')
|
| 1825 |
-
expect(profile.locale).toBe('en-US')
|
| 1826 |
-
expect(profile.budget_reset_day).toBe(1)
|
| 1827 |
-
})
|
| 1828 |
-
|
| 1829 |
-
it('updateProfile changes preferred_currency', async () => {
|
| 1830 |
-
await updateProfile({ preferred_currency: 'THB' })
|
| 1831 |
-
const profile = await getProfile()
|
| 1832 |
-
expect(profile.preferred_currency).toBe('THB')
|
| 1833 |
-
// restore
|
| 1834 |
-
await updateProfile({ preferred_currency: 'USD' })
|
| 1835 |
-
})
|
| 1836 |
-
|
| 1837 |
-
it('Zod rejects budget_reset_day > 28 at validation layer', () => {
|
| 1838 |
-
const { UpdateProfileSchema } = require('@llm-router/shared')
|
| 1839 |
-
const result = UpdateProfileSchema.safeParse({ budget_reset_day: 29 })
|
| 1840 |
-
expect(result.success).toBe(false)
|
| 1841 |
-
})
|
| 1842 |
-
})
|
| 1843 |
-
```
|
| 1844 |
-
|
| 1845 |
-
- [ ] **Step 2: Run test to verify it fails**
|
| 1846 |
-
|
| 1847 |
-
```bash
|
| 1848 |
-
pnpm -F @llm-router/api test src/expense/profile/profile.service.test.ts
|
| 1849 |
-
```
|
| 1850 |
-
|
| 1851 |
-
Expected: SKIP or FAIL.
|
| 1852 |
-
|
| 1853 |
-
- [ ] **Step 3: Create `apps/api/src/expense/profile/profile.service.ts`**
|
| 1854 |
-
|
| 1855 |
-
```ts
|
| 1856 |
-
import { db } from '../db/client.js'
|
| 1857 |
-
import { userProfile } from '../db/schema.js'
|
| 1858 |
-
import type { UserProfile, UpdateProfile } from '@llm-router/shared'
|
| 1859 |
-
|
| 1860 |
-
function rowToProfile(r: typeof userProfile.$inferSelect): UserProfile {
|
| 1861 |
-
return {
|
| 1862 |
-
id: r.id,
|
| 1863 |
-
preferred_currency: r.preferred_currency,
|
| 1864 |
-
locale: r.locale,
|
| 1865 |
-
budget_reset_day: r.budget_reset_day,
|
| 1866 |
-
}
|
| 1867 |
-
}
|
| 1868 |
-
|
| 1869 |
-
export async function getProfile(): Promise<UserProfile> {
|
| 1870 |
-
const rows = await db.select().from(userProfile).limit(1)
|
| 1871 |
-
const row = rows[0]
|
| 1872 |
-
if (!row) throw new Error('Profile not seeded — run seedDefaults() first')
|
| 1873 |
-
return rowToProfile(row)
|
| 1874 |
-
}
|
| 1875 |
-
|
| 1876 |
-
export async function updateProfile(input: UpdateProfile): Promise<UserProfile> {
|
| 1877 |
-
await getProfile() // ensure profile row exists before updating
|
| 1878 |
-
const updates: Partial<typeof userProfile.$inferInsert> = {}
|
| 1879 |
-
if (input.preferred_currency !== undefined) updates.preferred_currency = input.preferred_currency
|
| 1880 |
-
if (input.locale !== undefined) updates.locale = input.locale
|
| 1881 |
-
if (input.budget_reset_day !== undefined) updates.budget_reset_day = input.budget_reset_day
|
| 1882 |
-
updates.updated_at = new Date()
|
| 1883 |
-
|
| 1884 |
-
const rows = await db.update(userProfile).set(updates).returning()
|
| 1885 |
-
const row = rows[0]
|
| 1886 |
-
if (!row) throw new Error('Profile update failed')
|
| 1887 |
-
return rowToProfile(row)
|
| 1888 |
-
}
|
| 1889 |
-
```
|
| 1890 |
-
|
| 1891 |
-
- [ ] **Step 4: Create `apps/api/src/expense/profile/profile.validator.ts`**
|
| 1892 |
-
|
| 1893 |
-
```ts
|
| 1894 |
-
import { UpdateProfileSchema } from '@llm-router/shared'
|
| 1895 |
-
import { validate } from '../../middleware/validate.js'
|
| 1896 |
-
|
| 1897 |
-
export const validateUpdateProfile = validate(UpdateProfileSchema)
|
| 1898 |
-
```
|
| 1899 |
-
|
| 1900 |
-
- [ ] **Step 5: Create `apps/api/src/expense/profile/profile.controller.ts`**
|
| 1901 |
-
|
| 1902 |
-
```ts
|
| 1903 |
-
import type { RequestHandler } from 'express'
|
| 1904 |
-
import * as svc from './profile.service.js'
|
| 1905 |
-
|
| 1906 |
-
export const getProfile: RequestHandler = async (_req, res) => {
|
| 1907 |
-
const data = await svc.getProfile()
|
| 1908 |
-
res.json(data)
|
| 1909 |
-
}
|
| 1910 |
-
|
| 1911 |
-
export const putProfile: RequestHandler = async (req, res) => {
|
| 1912 |
-
const data = await svc.updateProfile(req.body)
|
| 1913 |
-
res.json(data)
|
| 1914 |
-
}
|
| 1915 |
-
```
|
| 1916 |
-
|
| 1917 |
-
- [ ] **Step 6: Add profile routes to `apps/api/src/expense/expense.routes.ts`**
|
| 1918 |
-
|
| 1919 |
-
Add profile imports and routes. The final complete `expense.routes.ts`:
|
| 1920 |
-
|
| 1921 |
-
```ts
|
| 1922 |
-
import { Router } from 'express'
|
| 1923 |
-
import type { Router as ExpressRouter } from 'express'
|
| 1924 |
-
|
| 1925 |
-
import { validateExpense, validateManualExpense, validateUpdateExpense } from './expense.validator.js'
|
| 1926 |
-
import { parseExpense, getExpenses, postManualExpense, getExpense, putExpense, deleteExpenseHandler } from './expense.controller.js'
|
| 1927 |
-
|
| 1928 |
-
import { validateCreateCategory, validateUpdateCategory } from './categories/categories.validator.js'
|
| 1929 |
-
import { getCategories, postCategory, putCategory, deleteCategory } from './categories/categories.controller.js'
|
| 1930 |
-
|
| 1931 |
-
import { validateCreateBudget, validateUpdateBudget } from './budgets/budgets.validator.js'
|
| 1932 |
-
import { getBudgets, postBudget, putBudget, deleteBudget } from './budgets/budgets.controller.js'
|
| 1933 |
-
|
| 1934 |
-
import { getSummary, getTrends } from './analytics/analytics.controller.js'
|
| 1935 |
-
|
| 1936 |
-
import { validateUpdateProfile } from './profile/profile.validator.js'
|
| 1937 |
-
import { getProfile, putProfile } from './profile/profile.controller.js'
|
| 1938 |
-
|
| 1939 |
-
const router: ExpressRouter = Router()
|
| 1940 |
-
|
| 1941 |
-
// ── Fixed paths BEFORE /:id ───────────────────────────────────────────────────
|
| 1942 |
-
router.get('/categories', getCategories)
|
| 1943 |
-
router.post('/categories', validateCreateCategory, postCategory)
|
| 1944 |
-
router.put('/categories/:id', validateUpdateCategory, putCategory)
|
| 1945 |
-
router.delete('/categories/:id', deleteCategory)
|
| 1946 |
-
|
| 1947 |
-
router.get('/budgets', getBudgets)
|
| 1948 |
-
router.post('/budgets', validateCreateBudget, postBudget)
|
| 1949 |
-
router.put('/budgets/:id', validateUpdateBudget, putBudget)
|
| 1950 |
-
router.delete('/budgets/:id', deleteBudget)
|
| 1951 |
-
|
| 1952 |
-
router.get('/summary', getSummary)
|
| 1953 |
-
router.get('/trends', getTrends)
|
| 1954 |
-
|
| 1955 |
-
router.get('/profile', getProfile)
|
| 1956 |
-
router.put('/profile', validateUpdateProfile, putProfile)
|
| 1957 |
-
|
| 1958 |
-
router.post('/parse', validateExpense, parseExpense)
|
| 1959 |
-
router.post('/manual', validateManualExpense, postManualExpense)
|
| 1960 |
-
|
| 1961 |
-
// ── Parameterized routes LAST ─────────────────────────────────────────────────
|
| 1962 |
-
router.get('/', getExpenses)
|
| 1963 |
-
router.get('/:id', getExpense)
|
| 1964 |
-
router.put('/:id', validateUpdateExpense, putExpense)
|
| 1965 |
-
router.delete('/:id', deleteExpenseHandler)
|
| 1966 |
-
|
| 1967 |
-
export { router as expenseRouter }
|
| 1968 |
-
```
|
| 1969 |
-
|
| 1970 |
-
- [ ] **Step 7: Run full test suite**
|
| 1971 |
-
|
| 1972 |
-
```bash
|
| 1973 |
-
pnpm -F @llm-router/api test
|
| 1974 |
-
```
|
| 1975 |
-
|
| 1976 |
-
Expected: all tests pass.
|
| 1977 |
-
|
| 1978 |
-
- [ ] **Step 8: Build to verify no TypeScript errors**
|
| 1979 |
-
|
| 1980 |
-
```bash
|
| 1981 |
-
pnpm -F @llm-router/api build
|
| 1982 |
-
```
|
| 1983 |
-
|
| 1984 |
-
Expected: `apps/api/dist/` updated, no errors.
|
| 1985 |
-
|
| 1986 |
-
- [ ] **Step 9: Commit**
|
| 1987 |
-
|
| 1988 |
-
```bash
|
| 1989 |
-
git add apps/api/src/expense/profile apps/api/src/expense/expense.routes.ts
|
| 1990 |
-
git commit -m "feat: add profile API (get + update user preferences)"
|
| 1991 |
-
```
|
| 1992 |
-
|
| 1993 |
-
---
|
| 1994 |
-
|
| 1995 |
-
## End-to-End Smoke Test
|
| 1996 |
-
|
| 1997 |
-
After all 9 tasks complete, verify the full API is wired correctly:
|
| 1998 |
-
|
| 1999 |
-
```bash
|
| 2000 |
-
# Start the API
|
| 2001 |
-
pnpm -F @llm-router/api dev
|
| 2002 |
-
|
| 2003 |
-
# In another terminal:
|
| 2004 |
-
curl http://localhost:3000/health
|
| 2005 |
-
# Expected: { "status": "ok" }
|
| 2006 |
-
|
| 2007 |
-
curl http://localhost:3000/v1/expense/categories
|
| 2008 |
-
# Expected: JSON array with 7 seeded categories
|
| 2009 |
-
|
| 2010 |
-
curl http://localhost:3000/v1/expense/profile
|
| 2011 |
-
# Expected: { preferred_currency: "USD", locale: "en-US", budget_reset_day: 1, ... }
|
| 2012 |
-
|
| 2013 |
-
curl http://localhost:3000/v1/expense/summary
|
| 2014 |
-
# Expected: { period: "2026-06", total_spent: 0, currency_warning: false, categories: [...] }
|
| 2015 |
-
|
| 2016 |
-
curl -X POST http://localhost:3000/v1/expense/manual \
|
| 2017 |
-
-H "Content-Type: application/json" \
|
| 2018 |
-
-H "X-API-Key: <your-api-key>" \
|
| 2019 |
-
-d '{"amount": 42.50, "category_id": "<uuid>", "date": "2026-06-30", "merchant": "Test"}'
|
| 2020 |
-
# Expected: 201 with created expense
|
| 2021 |
-
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
docs/superpowers/plans/2026-07-02-llm-router-library.md
DELETED
|
@@ -1,1299 +0,0 @@
|
|
| 1 |
-
# `@llm-router/llm-router` Library Implementation Plan
|
| 2 |
-
|
| 3 |
-
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
| 4 |
-
|
| 5 |
-
**Goal:** Extract LLM provider + routing logic from `apps/api` into a standalone `packages/llm-router` workspace package that `apps/api` consumes via `workspace:*`.
|
| 6 |
-
|
| 7 |
-
**Architecture:** A domain-agnostic LLM client with 4 providers (Ollama, Cerebras, Groq, Claude), 4 routing strategies (cost/local/quality/fallback), a generified circuit breaker, and a shared retry helper. `apps/api` keeps all domain logic (system prompts, PII routing, expense parser) and imports the library instead of calling providers directly.
|
| 8 |
-
|
| 9 |
-
**Tech Stack:** TypeScript 6, pnpm workspaces, `groq-sdk`, `@anthropic-ai/sdk`, `@cerebras/cerebras_cloud_sdk`, `ollama`
|
| 10 |
-
|
| 11 |
-
## Global Constraints
|
| 12 |
-
|
| 13 |
-
- TypeScript strict mode — `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`, `noImplicitReturns`, `noUnusedParameters`, `noImplicitOverride`; zero `any` types
|
| 14 |
-
- Module system: CommonJS (no `"type": "module"`) to match `apps/api`'s runtime mode; static `import` compiles to `require()`, no `.js` extensions needed on local imports
|
| 15 |
-
- All providers must return `CompletionOutput` (including `provider: string` field — new vs current `base.ts`)
|
| 16 |
-
- `withRetry` onFailure callback signature: `(attempt: number, err: unknown) => number` (returns backoff ms; side-effect: record failure)
|
| 17 |
-
- Circuit breaker keyed by `provider.name` string — no hardcoded union type
|
| 18 |
-
- No tests in this phase — TypeScript type-check (`tsc --noEmit`) is the verification gate for each task
|
| 19 |
-
- Spec: `docs/superpowers/specs/2026-07-02-llm-router-library-design.md`
|
| 20 |
-
|
| 21 |
-
---
|
| 22 |
-
|
| 23 |
-
## File Map
|
| 24 |
-
|
| 25 |
-
### New: `packages/llm-router/`
|
| 26 |
-
| File | Responsibility |
|
| 27 |
-
|---|---|
|
| 28 |
-
| `package.json` | Package identity, deps, build scripts |
|
| 29 |
-
| `tsconfig.json` | Strict TS config matching apps/api settings |
|
| 30 |
-
| `src/types.ts` | All shared interfaces: `SimpleMessage`, `CompletionInput`, `CompletionOutput`, `LLMProvider`, `RouterOptions`, `CompleteOptions`, `RoutingStrategy` |
|
| 31 |
-
| `src/utils/errors.ts` | `LLMError`, `ProviderError`, `CircuitOpenError` |
|
| 32 |
-
| `src/utils/circuit-breaker.ts` | `isCircuitOpen`, `recordSuccess`, `recordFailure`, `getCircuitStatus` — keyed by string |
|
| 33 |
-
| `src/utils/retry.ts` | `withRetry<T>(fn, maxAttempts, onFailure)` |
|
| 34 |
-
| `src/utils/tokens.ts` | `PRICING` map, `calcCostUsd` |
|
| 35 |
-
| `src/providers/ollama.ts` | Migrated from `apps/api/src/providers/ollama.ts` + shared retry |
|
| 36 |
-
| `src/providers/cerebras.ts` | Migrated from `apps/api/src/providers/cerebras.ts` + shared retry |
|
| 37 |
-
| `src/providers/groq.ts` | New: Groq Cloud via `groq-sdk` |
|
| 38 |
-
| `src/providers/claude.ts` | New: Anthropic Claude via `@anthropic-ai/sdk` |
|
| 39 |
-
| `src/providers/index.ts` | Re-exports all four provider singletons |
|
| 40 |
-
| `src/providers/base.ts` | Re-exports `LLMProvider` from `../types` (convenience alias) |
|
| 41 |
-
| `src/routing/strategies.ts` | `orderProviders(providers, strategy)` — strategy-order table |
|
| 42 |
-
| `src/routing/selector.ts` | `selectProvider(providers, strategy)` → `LLMProvider[]` |
|
| 43 |
-
| `src/router.ts` | `LLMRouter` class |
|
| 44 |
-
| `src/index.ts` | Public exports |
|
| 45 |
-
|
| 46 |
-
### Modified: `apps/api/`
|
| 47 |
-
| File | Change |
|
| 48 |
-
|---|---|
|
| 49 |
-
| `apps/api/package.json` | Add `"@llm-router/llm-router": "workspace:*"` dependency |
|
| 50 |
-
| `apps/api/src/llm-router.ts` | Full rewrite (~60 lines): imports `LLMRouter` from library; keeps domain routing |
|
| 51 |
-
| `apps/api/src/chat/chat.controller.ts` | Update `SimpleMessage` import from `../providers/base` → `@llm-router/llm-router` |
|
| 52 |
-
|
| 53 |
-
### New: `apps/api/src/prompts/`
|
| 54 |
-
| File | Responsibility |
|
| 55 |
-
|---|---|
|
| 56 |
-
| `expense.prompt.ts` | `EXPENSE_PARSE_PROMPT` constant |
|
| 57 |
-
| `chat.prompts.ts` | `SYSTEM_PROMPTS` record (smart-router, professor-ai, code-assistant) |
|
| 58 |
-
|
| 59 |
-
### Deleted: `apps/api/src/`
|
| 60 |
-
- `providers/` — entire directory (`base.ts`, `ollama.ts`, `cerebras.ts`)
|
| 61 |
-
- `circuit-breaker.ts`
|
| 62 |
-
|
| 63 |
-
---
|
| 64 |
-
|
| 65 |
-
## Task 1: Package Scaffold
|
| 66 |
-
|
| 67 |
-
**Files:**
|
| 68 |
-
- Create: `packages/llm-router/package.json`
|
| 69 |
-
- Create: `packages/llm-router/tsconfig.json`
|
| 70 |
-
|
| 71 |
-
**Interfaces:**
|
| 72 |
-
- Produces: `@llm-router/llm-router` as a workspace package (importable with `workspace:*`)
|
| 73 |
-
|
| 74 |
-
- [ ] **Step 1: Create package.json**
|
| 75 |
-
|
| 76 |
-
```json
|
| 77 |
-
{
|
| 78 |
-
"name": "@llm-router/llm-router",
|
| 79 |
-
"version": "0.1.0",
|
| 80 |
-
"description": "Domain-agnostic LLM client with provider abstraction, routing, circuit breaking, and cost tracking",
|
| 81 |
-
"main": "./dist/index.js",
|
| 82 |
-
"types": "./dist/index.d.ts",
|
| 83 |
-
"exports": {
|
| 84 |
-
".": {
|
| 85 |
-
"require": "./dist/index.js",
|
| 86 |
-
"types": "./dist/index.d.ts"
|
| 87 |
-
}
|
| 88 |
-
},
|
| 89 |
-
"scripts": {
|
| 90 |
-
"build": "tsc",
|
| 91 |
-
"check": "tsc --noEmit"
|
| 92 |
-
},
|
| 93 |
-
"dependencies": {
|
| 94 |
-
"@cerebras/cerebras_cloud_sdk": "^1.64.1",
|
| 95 |
-
"@anthropic-ai/sdk": "^0.39.0",
|
| 96 |
-
"groq-sdk": "^0.9.0",
|
| 97 |
-
"ollama": "^0.6.3"
|
| 98 |
-
},
|
| 99 |
-
"devDependencies": {
|
| 100 |
-
"@types/node": "^25.6.0",
|
| 101 |
-
"typescript": "^6.0.3"
|
| 102 |
-
}
|
| 103 |
-
}
|
| 104 |
-
```
|
| 105 |
-
|
| 106 |
-
- [ ] **Step 2: Create tsconfig.json**
|
| 107 |
-
|
| 108 |
-
```json
|
| 109 |
-
{
|
| 110 |
-
"compilerOptions": {
|
| 111 |
-
"rootDir": "./src",
|
| 112 |
-
"outDir": "./dist",
|
| 113 |
-
"module": "nodenext",
|
| 114 |
-
"target": "esnext",
|
| 115 |
-
"lib": ["esnext"],
|
| 116 |
-
"types": ["node"],
|
| 117 |
-
"sourceMap": true,
|
| 118 |
-
"declaration": true,
|
| 119 |
-
"declarationMap": true,
|
| 120 |
-
"noUncheckedIndexedAccess": true,
|
| 121 |
-
"exactOptionalPropertyTypes": true,
|
| 122 |
-
"noImplicitReturns": true,
|
| 123 |
-
"noImplicitOverride": true,
|
| 124 |
-
"noUnusedParameters": true,
|
| 125 |
-
"strict": true,
|
| 126 |
-
"verbatimModuleSyntax": false,
|
| 127 |
-
"isolatedModules": true,
|
| 128 |
-
"noUncheckedSideEffectImports": true,
|
| 129 |
-
"moduleDetection": "force",
|
| 130 |
-
"skipLibCheck": true
|
| 131 |
-
},
|
| 132 |
-
"include": ["src"],
|
| 133 |
-
"exclude": ["dist"]
|
| 134 |
-
}
|
| 135 |
-
```
|
| 136 |
-
|
| 137 |
-
- [ ] **Step 3: Install dependencies**
|
| 138 |
-
|
| 139 |
-
```bash
|
| 140 |
-
pnpm install
|
| 141 |
-
```
|
| 142 |
-
|
| 143 |
-
Expected: resolves `@llm-router/llm-router` as a workspace package; downloads `groq-sdk` and `@anthropic-ai/sdk`.
|
| 144 |
-
|
| 145 |
-
- [ ] **Step 4: Commit**
|
| 146 |
-
|
| 147 |
-
```bash
|
| 148 |
-
git add packages/llm-router/package.json packages/llm-router/tsconfig.json pnpm-lock.yaml
|
| 149 |
-
git commit -m "feat(llm-router): scaffold packages/llm-router workspace package"
|
| 150 |
-
```
|
| 151 |
-
|
| 152 |
-
---
|
| 153 |
-
|
| 154 |
-
## Task 2: Core Types and Typed Errors
|
| 155 |
-
|
| 156 |
-
**Files:**
|
| 157 |
-
- Create: `packages/llm-router/src/types.ts`
|
| 158 |
-
- Create: `packages/llm-router/src/utils/errors.ts`
|
| 159 |
-
|
| 160 |
-
**Interfaces:**
|
| 161 |
-
- Produces: `SimpleMessage`, `CompletionInput`, `CompletionOutput`, `LLMProvider`, `RouterOptions`, `CompleteOptions`, `RoutingStrategy` — consumed by every subsequent task
|
| 162 |
-
- Produces: `LLMError`, `ProviderError`, `CircuitOpenError` — consumed by providers and router
|
| 163 |
-
|
| 164 |
-
- [ ] **Step 1: Create src/types.ts**
|
| 165 |
-
|
| 166 |
-
```ts
|
| 167 |
-
export type MessageRole = 'user' | 'assistant' | 'system'
|
| 168 |
-
|
| 169 |
-
export interface SimpleMessage {
|
| 170 |
-
role: MessageRole
|
| 171 |
-
content: string
|
| 172 |
-
}
|
| 173 |
-
|
| 174 |
-
export interface CompletionInput {
|
| 175 |
-
messages: SimpleMessage[]
|
| 176 |
-
maxTokens?: number
|
| 177 |
-
temperature?: number
|
| 178 |
-
prefill?: string
|
| 179 |
-
}
|
| 180 |
-
|
| 181 |
-
export interface CompletionOutput {
|
| 182 |
-
content: string
|
| 183 |
-
model: string
|
| 184 |
-
provider: string
|
| 185 |
-
inputTokens: number
|
| 186 |
-
outputTokens: number
|
| 187 |
-
costUsd: number
|
| 188 |
-
durationMs: number
|
| 189 |
-
}
|
| 190 |
-
|
| 191 |
-
export type RoutingStrategy = 'cost' | 'local' | 'quality' | 'fallback'
|
| 192 |
-
|
| 193 |
-
export interface LLMProvider {
|
| 194 |
-
readonly name: string
|
| 195 |
-
complete(input: CompletionInput): Promise<CompletionOutput>
|
| 196 |
-
}
|
| 197 |
-
|
| 198 |
-
export interface RouterOptions {
|
| 199 |
-
providers: LLMProvider[]
|
| 200 |
-
defaultStrategy?: RoutingStrategy
|
| 201 |
-
}
|
| 202 |
-
|
| 203 |
-
export interface CompleteOptions extends CompletionInput {
|
| 204 |
-
strategy?: RoutingStrategy
|
| 205 |
-
}
|
| 206 |
-
```
|
| 207 |
-
|
| 208 |
-
- [ ] **Step 2: Create src/utils/errors.ts**
|
| 209 |
-
|
| 210 |
-
```ts
|
| 211 |
-
export class LLMError extends Error {
|
| 212 |
-
constructor(
|
| 213 |
-
message: string,
|
| 214 |
-
public readonly provider: string,
|
| 215 |
-
) {
|
| 216 |
-
super(message)
|
| 217 |
-
this.name = 'LLMError'
|
| 218 |
-
}
|
| 219 |
-
}
|
| 220 |
-
|
| 221 |
-
export class CircuitOpenError extends LLMError {
|
| 222 |
-
constructor(provider: string) {
|
| 223 |
-
super(`Circuit open for provider: ${provider}`, provider)
|
| 224 |
-
this.name = 'CircuitOpenError'
|
| 225 |
-
}
|
| 226 |
-
}
|
| 227 |
-
|
| 228 |
-
export class ProviderError extends LLMError {
|
| 229 |
-
constructor(
|
| 230 |
-
message: string,
|
| 231 |
-
provider: string,
|
| 232 |
-
public readonly status?: number,
|
| 233 |
-
) {
|
| 234 |
-
super(message, provider)
|
| 235 |
-
this.name = 'ProviderError'
|
| 236 |
-
}
|
| 237 |
-
}
|
| 238 |
-
```
|
| 239 |
-
|
| 240 |
-
- [ ] **Step 3: Verify TypeScript**
|
| 241 |
-
|
| 242 |
-
```bash
|
| 243 |
-
cd packages/llm-router && pnpm check
|
| 244 |
-
```
|
| 245 |
-
|
| 246 |
-
Expected: clean, no errors (only two files with no cross-dependencies yet).
|
| 247 |
-
|
| 248 |
-
- [ ] **Step 4: Commit**
|
| 249 |
-
|
| 250 |
-
```bash
|
| 251 |
-
git add packages/llm-router/src/types.ts packages/llm-router/src/utils/errors.ts
|
| 252 |
-
git commit -m "feat(llm-router): add core types and typed error classes"
|
| 253 |
-
```
|
| 254 |
-
|
| 255 |
-
---
|
| 256 |
-
|
| 257 |
-
## Task 3: Utility Functions
|
| 258 |
-
|
| 259 |
-
**Files:**
|
| 260 |
-
- Create: `packages/llm-router/src/utils/retry.ts`
|
| 261 |
-
- Create: `packages/llm-router/src/utils/tokens.ts`
|
| 262 |
-
- Create: `packages/llm-router/src/utils/circuit-breaker.ts`
|
| 263 |
-
|
| 264 |
-
**Interfaces:**
|
| 265 |
-
- Produces: `withRetry<T>(fn, maxAttempts, onFailure)` — consumed by all four providers
|
| 266 |
-
- Produces: `PRICING`, `calcCostUsd` — consumed by cloud providers
|
| 267 |
-
- Produces: `isCircuitOpen`, `recordSuccess`, `recordFailure`, `getCircuitStatus` — consumed by providers
|
| 268 |
-
|
| 269 |
-
- [ ] **Step 1: Create src/utils/retry.ts**
|
| 270 |
-
|
| 271 |
-
`onFailure` is called on every failed attempt. It records the failure and returns the backoff duration in ms. Sleep happens only if more attempts remain.
|
| 272 |
-
|
| 273 |
-
```ts
|
| 274 |
-
export async function withRetry<T>(
|
| 275 |
-
fn: () => Promise<T>,
|
| 276 |
-
maxAttempts: number,
|
| 277 |
-
onFailure: (attempt: number, err: unknown) => number,
|
| 278 |
-
): Promise<T> {
|
| 279 |
-
let lastErr: unknown
|
| 280 |
-
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
| 281 |
-
try {
|
| 282 |
-
return await fn()
|
| 283 |
-
} catch (err: unknown) {
|
| 284 |
-
lastErr = err
|
| 285 |
-
const backoffMs = onFailure(attempt, err)
|
| 286 |
-
if (attempt < maxAttempts) {
|
| 287 |
-
await new Promise(r => setTimeout(r, backoffMs))
|
| 288 |
-
}
|
| 289 |
-
}
|
| 290 |
-
}
|
| 291 |
-
throw lastErr
|
| 292 |
-
}
|
| 293 |
-
```
|
| 294 |
-
|
| 295 |
-
- [ ] **Step 2: Create src/utils/tokens.ts**
|
| 296 |
-
|
| 297 |
-
Prices are per million tokens. Add more model IDs as needed.
|
| 298 |
-
|
| 299 |
-
```ts
|
| 300 |
-
export const PRICING: Record<string, { input: number; output: number }> = {
|
| 301 |
-
'llama-3.3-70b': { input: 0.85, output: 1.20 },
|
| 302 |
-
'llama-3.1-8b': { input: 0.10, output: 0.10 },
|
| 303 |
-
'llama-3.3-70b-versatile': { input: 0.59, output: 0.79 },
|
| 304 |
-
'claude-haiku-4-5-20251001': { input: 0.80, output: 4.00 },
|
| 305 |
-
'claude-sonnet-4-6': { input: 3.00, output: 15.00 },
|
| 306 |
-
'claude-opus-4-8': { input: 15.00, output: 75.00 },
|
| 307 |
-
}
|
| 308 |
-
|
| 309 |
-
export function calcCostUsd(
|
| 310 |
-
inputTokens: number,
|
| 311 |
-
outputTokens: number,
|
| 312 |
-
pricing: { input: number; output: number },
|
| 313 |
-
): number {
|
| 314 |
-
return (inputTokens * pricing.input + outputTokens * pricing.output) / 1_000_000
|
| 315 |
-
}
|
| 316 |
-
```
|
| 317 |
-
|
| 318 |
-
- [ ] **Step 3: Create src/utils/circuit-breaker.ts**
|
| 319 |
-
|
| 320 |
-
Keyed by `provider.name` string — no hardcoded union. Threshold: 3 failures → open. Reset: 60 s half-open check.
|
| 321 |
-
|
| 322 |
-
```ts
|
| 323 |
-
interface CircuitState {
|
| 324 |
-
failures: number
|
| 325 |
-
lastFailure: number | null
|
| 326 |
-
isOpen: boolean
|
| 327 |
-
}
|
| 328 |
-
|
| 329 |
-
const FAILURE_THRESHOLD = 3
|
| 330 |
-
const RESET_TIMEOUT_MS = 60_000
|
| 331 |
-
|
| 332 |
-
const circuits = new Map<string, CircuitState>()
|
| 333 |
-
|
| 334 |
-
function getOrCreate(name: string): CircuitState {
|
| 335 |
-
let circuit = circuits.get(name)
|
| 336 |
-
if (circuit === undefined) {
|
| 337 |
-
circuit = { failures: 0, lastFailure: null, isOpen: false }
|
| 338 |
-
circuits.set(name, circuit)
|
| 339 |
-
}
|
| 340 |
-
return circuit
|
| 341 |
-
}
|
| 342 |
-
|
| 343 |
-
export function isCircuitOpen(name: string): boolean {
|
| 344 |
-
const circuit = getOrCreate(name)
|
| 345 |
-
if (!circuit.isOpen) return false
|
| 346 |
-
if (
|
| 347 |
-
circuit.lastFailure !== null &&
|
| 348 |
-
Date.now() - circuit.lastFailure > RESET_TIMEOUT_MS
|
| 349 |
-
) {
|
| 350 |
-
circuit.isOpen = false
|
| 351 |
-
circuit.failures = 0
|
| 352 |
-
return false
|
| 353 |
-
}
|
| 354 |
-
return true
|
| 355 |
-
}
|
| 356 |
-
|
| 357 |
-
export function recordSuccess(name: string): void {
|
| 358 |
-
circuits.set(name, { failures: 0, lastFailure: null, isOpen: false })
|
| 359 |
-
}
|
| 360 |
-
|
| 361 |
-
export function recordFailure(name: string): void {
|
| 362 |
-
const circuit = getOrCreate(name)
|
| 363 |
-
circuit.failures++
|
| 364 |
-
circuit.lastFailure = Date.now()
|
| 365 |
-
if (circuit.failures >= FAILURE_THRESHOLD) {
|
| 366 |
-
circuit.isOpen = true
|
| 367 |
-
}
|
| 368 |
-
}
|
| 369 |
-
|
| 370 |
-
export function getCircuitStatus(): Map<string, { isOpen: boolean; failures: number }> {
|
| 371 |
-
const result = new Map<string, { isOpen: boolean; failures: number }>()
|
| 372 |
-
for (const [name, state] of circuits) {
|
| 373 |
-
result.set(name, { isOpen: state.isOpen, failures: state.failures })
|
| 374 |
-
}
|
| 375 |
-
return result
|
| 376 |
-
}
|
| 377 |
-
```
|
| 378 |
-
|
| 379 |
-
- [ ] **Step 4: Verify TypeScript**
|
| 380 |
-
|
| 381 |
-
```bash
|
| 382 |
-
cd packages/llm-router && pnpm check
|
| 383 |
-
```
|
| 384 |
-
|
| 385 |
-
Expected: clean.
|
| 386 |
-
|
| 387 |
-
- [ ] **Step 5: Commit**
|
| 388 |
-
|
| 389 |
-
```bash
|
| 390 |
-
git add packages/llm-router/src/utils/
|
| 391 |
-
git commit -m "feat(llm-router): add retry, token pricing, and circuit breaker utilities"
|
| 392 |
-
```
|
| 393 |
-
|
| 394 |
-
---
|
| 395 |
-
|
| 396 |
-
## Task 4: Ollama and Cerebras Providers (Migrate)
|
| 397 |
-
|
| 398 |
-
Migrate from `apps/api/src/providers/` and replace inline retry loops with `withRetry`. Note: `CompletionOutput` now requires a `provider` field — add it.
|
| 399 |
-
|
| 400 |
-
**Files:**
|
| 401 |
-
- Create: `packages/llm-router/src/providers/ollama.ts`
|
| 402 |
-
- Create: `packages/llm-router/src/providers/cerebras.ts`
|
| 403 |
-
- Create: `packages/llm-router/src/providers/base.ts`
|
| 404 |
-
|
| 405 |
-
**Interfaces:**
|
| 406 |
-
- Consumes: `CompletionInput`, `CompletionOutput`, `LLMProvider` from `../types`; `withRetry` from `../utils/retry`; `isCircuitOpen`, `recordSuccess`, `recordFailure` from `../utils/circuit-breaker`; `ProviderError`, `CircuitOpenError` from `../utils/errors`
|
| 407 |
-
- Produces: `ollamaProvider`, `cerebrasProvider` singletons
|
| 408 |
-
|
| 409 |
-
- [ ] **Step 1: Create src/providers/base.ts** (convenience re-export)
|
| 410 |
-
|
| 411 |
-
```ts
|
| 412 |
-
export type { LLMProvider } from '../types'
|
| 413 |
-
```
|
| 414 |
-
|
| 415 |
-
- [ ] **Step 2: Create src/providers/ollama.ts**
|
| 416 |
-
|
| 417 |
-
Config env vars: `OLLAMA_HOST` (default `http://localhost:11434`), `OLLAMA_MODEL` (default `qwen2.5:0.5b`). Timeout: 30 s via AbortController.
|
| 418 |
-
|
| 419 |
-
```ts
|
| 420 |
-
import { Ollama } from 'ollama'
|
| 421 |
-
import type { LLMProvider, CompletionInput, CompletionOutput } from '../types'
|
| 422 |
-
import { withRetry } from '../utils/retry'
|
| 423 |
-
import { isCircuitOpen, recordSuccess, recordFailure } from '../utils/circuit-breaker'
|
| 424 |
-
import { CircuitOpenError } from '../utils/errors'
|
| 425 |
-
|
| 426 |
-
const TIMEOUT_MS = 30_000
|
| 427 |
-
const MAX_RETRIES = 2
|
| 428 |
-
|
| 429 |
-
export class OllamaProvider implements LLMProvider {
|
| 430 |
-
readonly name = 'ollama'
|
| 431 |
-
private readonly client: Ollama
|
| 432 |
-
private readonly model: string
|
| 433 |
-
|
| 434 |
-
constructor() {
|
| 435 |
-
this.client = new Ollama({ host: process.env.OLLAMA_HOST ?? 'http://localhost:11434' })
|
| 436 |
-
this.model = process.env.OLLAMA_MODEL ?? 'qwen2.5:0.5b'
|
| 437 |
-
}
|
| 438 |
-
|
| 439 |
-
async complete(input: CompletionInput): Promise<CompletionOutput> {
|
| 440 |
-
if (isCircuitOpen(this.name)) throw new CircuitOpenError(this.name)
|
| 441 |
-
|
| 442 |
-
return withRetry(
|
| 443 |
-
async () => {
|
| 444 |
-
const controller = new AbortController()
|
| 445 |
-
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS)
|
| 446 |
-
const start = Date.now()
|
| 447 |
-
try {
|
| 448 |
-
const options: Record<string, number> = {}
|
| 449 |
-
if (input.maxTokens !== undefined) options['num_predict'] = input.maxTokens
|
| 450 |
-
if (input.temperature !== undefined) options['temperature'] = input.temperature
|
| 451 |
-
|
| 452 |
-
const response = await this.client.chat({
|
| 453 |
-
model: this.model,
|
| 454 |
-
messages: input.messages,
|
| 455 |
-
...(Object.keys(options).length > 0 && { options }),
|
| 456 |
-
})
|
| 457 |
-
clearTimeout(timer)
|
| 458 |
-
recordSuccess(this.name)
|
| 459 |
-
return {
|
| 460 |
-
content: response.message.content,
|
| 461 |
-
model: this.model,
|
| 462 |
-
provider: this.name,
|
| 463 |
-
inputTokens: response.prompt_eval_count ?? 0,
|
| 464 |
-
outputTokens: response.eval_count ?? 0,
|
| 465 |
-
costUsd: 0,
|
| 466 |
-
durationMs: Date.now() - start,
|
| 467 |
-
}
|
| 468 |
-
} catch (err: unknown) {
|
| 469 |
-
clearTimeout(timer)
|
| 470 |
-
throw err
|
| 471 |
-
}
|
| 472 |
-
},
|
| 473 |
-
MAX_RETRIES,
|
| 474 |
-
(attempt, _err) => {
|
| 475 |
-
recordFailure(this.name)
|
| 476 |
-
return attempt * 1000
|
| 477 |
-
},
|
| 478 |
-
)
|
| 479 |
-
}
|
| 480 |
-
}
|
| 481 |
-
|
| 482 |
-
export const ollamaProvider = new OllamaProvider()
|
| 483 |
-
```
|
| 484 |
-
|
| 485 |
-
- [ ] **Step 3: Create src/providers/cerebras.ts**
|
| 486 |
-
|
| 487 |
-
Config env vars: `CEREBRAS_API_KEY`, `CLOUD_MODEL` (default `llama-3.3-70b`). The Cerebras SDK returns a loosely typed response — use the same safe narrowing as the existing code.
|
| 488 |
-
|
| 489 |
-
```ts
|
| 490 |
-
import Cerebras from '@cerebras/cerebras_cloud_sdk'
|
| 491 |
-
import type { LLMProvider, CompletionInput, CompletionOutput } from '../types'
|
| 492 |
-
import { withRetry } from '../utils/retry'
|
| 493 |
-
import { calcCostUsd, PRICING } from '../utils/tokens'
|
| 494 |
-
import { isCircuitOpen, recordSuccess, recordFailure } from '../utils/circuit-breaker'
|
| 495 |
-
import { CircuitOpenError, ProviderError } from '../utils/errors'
|
| 496 |
-
|
| 497 |
-
const MAX_RETRIES = 2
|
| 498 |
-
const DEFAULT_PRICING = PRICING['llama-3.3-70b'] ?? { input: 0.85, output: 1.20 }
|
| 499 |
-
|
| 500 |
-
type CerebrasMessage =
|
| 501 |
-
| { role: 'system'; content: string }
|
| 502 |
-
| { role: 'user'; content: string }
|
| 503 |
-
| { role: 'assistant'; content: string }
|
| 504 |
-
|
| 505 |
-
interface CerebrasCompletion {
|
| 506 |
-
model: string
|
| 507 |
-
choices: Array<{ message: { content: string; role: string }; finish_reason: string }>
|
| 508 |
-
usage?: { prompt_tokens: number; completion_tokens: number }
|
| 509 |
-
}
|
| 510 |
-
|
| 511 |
-
export class CerebrasProvider implements LLMProvider {
|
| 512 |
-
readonly name = 'cerebras'
|
| 513 |
-
private readonly client: Cerebras
|
| 514 |
-
private readonly model: string
|
| 515 |
-
|
| 516 |
-
constructor() {
|
| 517 |
-
this.client = new Cerebras({ apiKey: process.env.CEREBRAS_API_KEY ?? '' })
|
| 518 |
-
this.model = process.env.CLOUD_MODEL ?? 'llama-3.3-70b'
|
| 519 |
-
}
|
| 520 |
-
|
| 521 |
-
async complete(input: CompletionInput): Promise<CompletionOutput> {
|
| 522 |
-
if (!process.env.CEREBRAS_API_KEY) throw new ProviderError('CEREBRAS_API_KEY not set', this.name)
|
| 523 |
-
if (isCircuitOpen(this.name)) throw new CircuitOpenError(this.name)
|
| 524 |
-
|
| 525 |
-
return withRetry(
|
| 526 |
-
async () => {
|
| 527 |
-
const start = Date.now()
|
| 528 |
-
const raw = await this.client.chat.completions.create({
|
| 529 |
-
model: this.model,
|
| 530 |
-
messages: input.messages as CerebrasMessage[],
|
| 531 |
-
max_tokens: input.maxTokens ?? 4000,
|
| 532 |
-
...(input.temperature !== undefined && { temperature: input.temperature }),
|
| 533 |
-
})
|
| 534 |
-
const res = raw as CerebrasCompletion
|
| 535 |
-
recordSuccess(this.name)
|
| 536 |
-
const content = res.choices[0]?.message?.content ?? ''
|
| 537 |
-
const inputTokens = res.usage?.prompt_tokens ?? 0
|
| 538 |
-
const outputTokens = res.usage?.completion_tokens ?? 0
|
| 539 |
-
const pricing = PRICING[res.model] ?? DEFAULT_PRICING
|
| 540 |
-
return {
|
| 541 |
-
content,
|
| 542 |
-
model: res.model,
|
| 543 |
-
provider: this.name,
|
| 544 |
-
inputTokens,
|
| 545 |
-
outputTokens,
|
| 546 |
-
costUsd: calcCostUsd(inputTokens, outputTokens, pricing),
|
| 547 |
-
durationMs: Date.now() - start,
|
| 548 |
-
}
|
| 549 |
-
},
|
| 550 |
-
MAX_RETRIES,
|
| 551 |
-
(attempt, err) => {
|
| 552 |
-
recordFailure(this.name)
|
| 553 |
-
const status = (err as { status?: number }).status
|
| 554 |
-
return status === 429 ? attempt * 2000 : attempt * 1000
|
| 555 |
-
},
|
| 556 |
-
)
|
| 557 |
-
}
|
| 558 |
-
}
|
| 559 |
-
|
| 560 |
-
export const cerebrasProvider = new CerebrasProvider()
|
| 561 |
-
```
|
| 562 |
-
|
| 563 |
-
- [ ] **Step 4: Verify TypeScript**
|
| 564 |
-
|
| 565 |
-
```bash
|
| 566 |
-
cd packages/llm-router && pnpm check
|
| 567 |
-
```
|
| 568 |
-
|
| 569 |
-
Expected: clean.
|
| 570 |
-
|
| 571 |
-
- [ ] **Step 5: Commit**
|
| 572 |
-
|
| 573 |
-
```bash
|
| 574 |
-
git add packages/llm-router/src/providers/
|
| 575 |
-
git commit -m "feat(llm-router): migrate Ollama and Cerebras providers with shared retry"
|
| 576 |
-
```
|
| 577 |
-
|
| 578 |
-
---
|
| 579 |
-
|
| 580 |
-
## Task 5: Groq Provider (New)
|
| 581 |
-
|
| 582 |
-
**Files:**
|
| 583 |
-
- Create: `packages/llm-router/src/providers/groq.ts`
|
| 584 |
-
|
| 585 |
-
**Interfaces:**
|
| 586 |
-
- Consumes: same utils as Task 4
|
| 587 |
-
- Produces: `groqProvider` singleton
|
| 588 |
-
|
| 589 |
-
- [ ] **Step 1: Create src/providers/groq.ts**
|
| 590 |
-
|
| 591 |
-
Config env vars: `GROQ_API_KEY`, `GROQ_MODEL` (default `llama-3.3-70b-versatile`). Rate-limit 429 → 2 s backoff.
|
| 592 |
-
|
| 593 |
-
```ts
|
| 594 |
-
import Groq from 'groq-sdk'
|
| 595 |
-
import type { LLMProvider, CompletionInput, CompletionOutput } from '../types'
|
| 596 |
-
import { withRetry } from '../utils/retry'
|
| 597 |
-
import { calcCostUsd, PRICING } from '../utils/tokens'
|
| 598 |
-
import { isCircuitOpen, recordSuccess, recordFailure } from '../utils/circuit-breaker'
|
| 599 |
-
import { CircuitOpenError, ProviderError } from '../utils/errors'
|
| 600 |
-
|
| 601 |
-
const MAX_RETRIES = 2
|
| 602 |
-
const DEFAULT_PRICING = PRICING['llama-3.3-70b-versatile'] ?? { input: 0.59, output: 0.79 }
|
| 603 |
-
|
| 604 |
-
export class GroqProvider implements LLMProvider {
|
| 605 |
-
readonly name = 'groq'
|
| 606 |
-
private readonly client: Groq
|
| 607 |
-
private readonly model: string
|
| 608 |
-
|
| 609 |
-
constructor() {
|
| 610 |
-
this.client = new Groq({ apiKey: process.env.GROQ_API_KEY ?? '' })
|
| 611 |
-
this.model = process.env.GROQ_MODEL ?? 'llama-3.3-70b-versatile'
|
| 612 |
-
}
|
| 613 |
-
|
| 614 |
-
async complete(input: CompletionInput): Promise<CompletionOutput> {
|
| 615 |
-
if (!process.env.GROQ_API_KEY) throw new ProviderError('GROQ_API_KEY not set', this.name)
|
| 616 |
-
if (isCircuitOpen(this.name)) throw new CircuitOpenError(this.name)
|
| 617 |
-
|
| 618 |
-
return withRetry(
|
| 619 |
-
async () => {
|
| 620 |
-
const start = Date.now()
|
| 621 |
-
const res = await this.client.chat.completions.create({
|
| 622 |
-
model: this.model,
|
| 623 |
-
messages: input.messages,
|
| 624 |
-
max_tokens: input.maxTokens ?? 4000,
|
| 625 |
-
...(input.temperature !== undefined && { temperature: input.temperature }),
|
| 626 |
-
})
|
| 627 |
-
recordSuccess(this.name)
|
| 628 |
-
const content = res.choices[0]?.message?.content ?? ''
|
| 629 |
-
const inputTokens = res.usage?.prompt_tokens ?? 0
|
| 630 |
-
const outputTokens = res.usage?.completion_tokens ?? 0
|
| 631 |
-
const pricing = PRICING[res.model] ?? DEFAULT_PRICING
|
| 632 |
-
return {
|
| 633 |
-
content,
|
| 634 |
-
model: res.model,
|
| 635 |
-
provider: this.name,
|
| 636 |
-
inputTokens,
|
| 637 |
-
outputTokens,
|
| 638 |
-
costUsd: calcCostUsd(inputTokens, outputTokens, pricing),
|
| 639 |
-
durationMs: Date.now() - start,
|
| 640 |
-
}
|
| 641 |
-
},
|
| 642 |
-
MAX_RETRIES,
|
| 643 |
-
(attempt, err) => {
|
| 644 |
-
recordFailure(this.name)
|
| 645 |
-
const status = (err as { status?: number }).status
|
| 646 |
-
return status === 429 ? attempt * 2000 : attempt * 1000
|
| 647 |
-
},
|
| 648 |
-
)
|
| 649 |
-
}
|
| 650 |
-
}
|
| 651 |
-
|
| 652 |
-
export const groqProvider = new GroqProvider()
|
| 653 |
-
```
|
| 654 |
-
|
| 655 |
-
- [ ] **Step 2: Verify TypeScript**
|
| 656 |
-
|
| 657 |
-
```bash
|
| 658 |
-
cd packages/llm-router && pnpm check
|
| 659 |
-
```
|
| 660 |
-
|
| 661 |
-
Expected: clean.
|
| 662 |
-
|
| 663 |
-
- [ ] **Step 3: Commit**
|
| 664 |
-
|
| 665 |
-
```bash
|
| 666 |
-
git add packages/llm-router/src/providers/groq.ts
|
| 667 |
-
git commit -m "feat(llm-router): add Groq provider via groq-sdk"
|
| 668 |
-
```
|
| 669 |
-
|
| 670 |
-
---
|
| 671 |
-
|
| 672 |
-
## Task 6: Claude Provider (New)
|
| 673 |
-
|
| 674 |
-
**Files:**
|
| 675 |
-
- Create: `packages/llm-router/src/providers/claude.ts`
|
| 676 |
-
|
| 677 |
-
**Interfaces:**
|
| 678 |
-
- Consumes: same utils as Task 4; Anthropic SDK
|
| 679 |
-
- Produces: `claudeProvider` singleton
|
| 680 |
-
|
| 681 |
-
**Anthropic API note:** `system` messages are extracted from `input.messages` and passed as the top-level `system` param. Remaining messages (user/assistant) go in `messages`. If `input.prefill` is set, append an assistant turn with that content — Claude will continue from there and return ONLY the continuation (not the prefill text itself). Retry 529/503 → 5 s backoff.
|
| 682 |
-
|
| 683 |
-
- [ ] **Step 1: Create src/providers/claude.ts**
|
| 684 |
-
|
| 685 |
-
Config env vars: `ANTHROPIC_API_KEY`, `CLAUDE_MODEL` (default `claude-sonnet-4-6`).
|
| 686 |
-
|
| 687 |
-
```ts
|
| 688 |
-
import Anthropic from '@anthropic-ai/sdk'
|
| 689 |
-
import type { LLMProvider, CompletionInput, CompletionOutput, SimpleMessage } from '../types'
|
| 690 |
-
import { withRetry } from '../utils/retry'
|
| 691 |
-
import { calcCostUsd, PRICING } from '../utils/tokens'
|
| 692 |
-
import { isCircuitOpen, recordSuccess, recordFailure } from '../utils/circuit-breaker'
|
| 693 |
-
import { CircuitOpenError, ProviderError } from '../utils/errors'
|
| 694 |
-
|
| 695 |
-
const MAX_RETRIES = 2
|
| 696 |
-
const DEFAULT_PRICING = PRICING['claude-sonnet-4-6'] ?? { input: 3.00, output: 15.00 }
|
| 697 |
-
|
| 698 |
-
export class ClaudeProvider implements LLMProvider {
|
| 699 |
-
readonly name = 'claude'
|
| 700 |
-
private readonly client: Anthropic
|
| 701 |
-
private readonly model: string
|
| 702 |
-
|
| 703 |
-
constructor() {
|
| 704 |
-
this.client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY ?? '' })
|
| 705 |
-
this.model = process.env.CLAUDE_MODEL ?? 'claude-sonnet-4-6'
|
| 706 |
-
}
|
| 707 |
-
|
| 708 |
-
async complete(input: CompletionInput): Promise<CompletionOutput> {
|
| 709 |
-
if (!process.env.ANTHROPIC_API_KEY) throw new ProviderError('ANTHROPIC_API_KEY not set', this.name)
|
| 710 |
-
if (isCircuitOpen(this.name)) throw new CircuitOpenError(this.name)
|
| 711 |
-
|
| 712 |
-
return withRetry(
|
| 713 |
-
async () => {
|
| 714 |
-
const start = Date.now()
|
| 715 |
-
|
| 716 |
-
const systemContent = input.messages
|
| 717 |
-
.filter(m => m.role === 'system')
|
| 718 |
-
.map(m => m.content)
|
| 719 |
-
.join('\n')
|
| 720 |
-
|
| 721 |
-
const conversationMessages: Array<{ role: 'user' | 'assistant'; content: string }> =
|
| 722 |
-
input.messages
|
| 723 |
-
.filter((m): m is SimpleMessage & { role: 'user' | 'assistant' } => m.role !== 'system')
|
| 724 |
-
.map(m => ({ role: m.role, content: m.content }))
|
| 725 |
-
|
| 726 |
-
if (input.prefill !== undefined) {
|
| 727 |
-
conversationMessages.push({ role: 'assistant', content: input.prefill })
|
| 728 |
-
}
|
| 729 |
-
|
| 730 |
-
const res = await this.client.messages.create({
|
| 731 |
-
model: this.model,
|
| 732 |
-
max_tokens: input.maxTokens ?? 4000,
|
| 733 |
-
...(systemContent.length > 0 && { system: systemContent }),
|
| 734 |
-
messages: conversationMessages,
|
| 735 |
-
...(input.temperature !== undefined && { temperature: input.temperature }),
|
| 736 |
-
})
|
| 737 |
-
|
| 738 |
-
recordSuccess(this.name)
|
| 739 |
-
const block = res.content[0]
|
| 740 |
-
const content = block?.type === 'text' ? block.text : ''
|
| 741 |
-
const pricing = PRICING[res.model] ?? DEFAULT_PRICING
|
| 742 |
-
return {
|
| 743 |
-
content,
|
| 744 |
-
model: res.model,
|
| 745 |
-
provider: this.name,
|
| 746 |
-
inputTokens: res.usage.input_tokens,
|
| 747 |
-
outputTokens: res.usage.output_tokens,
|
| 748 |
-
costUsd: calcCostUsd(res.usage.input_tokens, res.usage.output_tokens, pricing),
|
| 749 |
-
durationMs: Date.now() - start,
|
| 750 |
-
}
|
| 751 |
-
},
|
| 752 |
-
MAX_RETRIES,
|
| 753 |
-
(attempt, err) => {
|
| 754 |
-
recordFailure(this.name)
|
| 755 |
-
const status = (err as { status?: number }).status
|
| 756 |
-
return status === 529 || status === 503 ? 5000 : attempt * 1000
|
| 757 |
-
},
|
| 758 |
-
)
|
| 759 |
-
}
|
| 760 |
-
}
|
| 761 |
-
|
| 762 |
-
export const claudeProvider = new ClaudeProvider()
|
| 763 |
-
```
|
| 764 |
-
|
| 765 |
-
- [ ] **Step 2: Verify TypeScript**
|
| 766 |
-
|
| 767 |
-
```bash
|
| 768 |
-
cd packages/llm-router && pnpm check
|
| 769 |
-
```
|
| 770 |
-
|
| 771 |
-
Expected: clean.
|
| 772 |
-
|
| 773 |
-
- [ ] **Step 3: Commit**
|
| 774 |
-
|
| 775 |
-
```bash
|
| 776 |
-
git add packages/llm-router/src/providers/claude.ts
|
| 777 |
-
git commit -m "feat(llm-router): add Claude provider via @anthropic-ai/sdk with prefill support"
|
| 778 |
-
```
|
| 779 |
-
|
| 780 |
-
---
|
| 781 |
-
|
| 782 |
-
## Task 7: Providers Index and Routing
|
| 783 |
-
|
| 784 |
-
**Files:**
|
| 785 |
-
- Create: `packages/llm-router/src/providers/index.ts`
|
| 786 |
-
- Create: `packages/llm-router/src/routing/strategies.ts`
|
| 787 |
-
- Create: `packages/llm-router/src/routing/selector.ts`
|
| 788 |
-
|
| 789 |
-
**Interfaces:**
|
| 790 |
-
- Consumes: all four provider singletons; `LLMProvider`, `RoutingStrategy` from `../types`
|
| 791 |
-
- Produces: `selectProvider(providers, strategy)` — consumed by `router.ts`
|
| 792 |
-
|
| 793 |
-
- [ ] **Step 1: Create src/providers/index.ts**
|
| 794 |
-
|
| 795 |
-
```ts
|
| 796 |
-
export { ollamaProvider } from './ollama'
|
| 797 |
-
export { cerebrasProvider } from './cerebras'
|
| 798 |
-
export { groqProvider } from './groq'
|
| 799 |
-
export { claudeProvider } from './claude'
|
| 800 |
-
```
|
| 801 |
-
|
| 802 |
-
- [ ] **Step 2: Create src/routing/strategies.ts**
|
| 803 |
-
|
| 804 |
-
Strategy order defines which providers are tried first. Providers not registered in `RouterOptions.providers` are silently skipped. Providers not listed in the strategy order are appended at the end.
|
| 805 |
-
|
| 806 |
-
```ts
|
| 807 |
-
import type { LLMProvider, RoutingStrategy } from '../types'
|
| 808 |
-
|
| 809 |
-
const STRATEGY_ORDER: Record<RoutingStrategy, readonly string[]> = {
|
| 810 |
-
cost: ['ollama', 'cerebras', 'groq', 'claude'],
|
| 811 |
-
local: ['ollama', 'groq', 'cerebras', 'claude'],
|
| 812 |
-
quality: ['claude', 'groq', 'cerebras', 'ollama'],
|
| 813 |
-
fallback: [],
|
| 814 |
-
}
|
| 815 |
-
|
| 816 |
-
export function orderProviders(providers: LLMProvider[], strategy: RoutingStrategy): LLMProvider[] {
|
| 817 |
-
if (strategy === 'fallback') return [...providers]
|
| 818 |
-
|
| 819 |
-
const order = STRATEGY_ORDER[strategy]
|
| 820 |
-
const byName = new Map(providers.map(p => [p.name, p]))
|
| 821 |
-
|
| 822 |
-
const ordered: LLMProvider[] = []
|
| 823 |
-
for (const name of order) {
|
| 824 |
-
const provider = byName.get(name)
|
| 825 |
-
if (provider !== undefined) ordered.push(provider)
|
| 826 |
-
}
|
| 827 |
-
|
| 828 |
-
const inOrder = new Set(order)
|
| 829 |
-
for (const p of providers) {
|
| 830 |
-
if (!inOrder.has(p.name)) ordered.push(p)
|
| 831 |
-
}
|
| 832 |
-
|
| 833 |
-
return ordered
|
| 834 |
-
}
|
| 835 |
-
```
|
| 836 |
-
|
| 837 |
-
- [ ] **Step 3: Create src/routing/selector.ts**
|
| 838 |
-
|
| 839 |
-
`selectProvider` simply orders providers by strategy. Circuit-open filtering happens inside each provider's `complete()` — it throws `CircuitOpenError`, which the router catches and falls back to the next provider.
|
| 840 |
-
|
| 841 |
-
```ts
|
| 842 |
-
import type { LLMProvider, RoutingStrategy } from '../types'
|
| 843 |
-
import { orderProviders } from './strategies'
|
| 844 |
-
|
| 845 |
-
export function selectProvider(providers: LLMProvider[], strategy: RoutingStrategy): LLMProvider[] {
|
| 846 |
-
return orderProviders(providers, strategy)
|
| 847 |
-
}
|
| 848 |
-
```
|
| 849 |
-
|
| 850 |
-
- [ ] **Step 4: Verify TypeScript**
|
| 851 |
-
|
| 852 |
-
```bash
|
| 853 |
-
cd packages/llm-router && pnpm check
|
| 854 |
-
```
|
| 855 |
-
|
| 856 |
-
Expected: clean.
|
| 857 |
-
|
| 858 |
-
- [ ] **Step 5: Commit**
|
| 859 |
-
|
| 860 |
-
```bash
|
| 861 |
-
git add packages/llm-router/src/providers/index.ts packages/llm-router/src/routing/
|
| 862 |
-
git commit -m "feat(llm-router): add providers index and routing strategy selector"
|
| 863 |
-
```
|
| 864 |
-
|
| 865 |
-
---
|
| 866 |
-
|
| 867 |
-
## Task 8: LLMRouter Class and Public Exports
|
| 868 |
-
|
| 869 |
-
**Files:**
|
| 870 |
-
- Create: `packages/llm-router/src/router.ts`
|
| 871 |
-
- Create: `packages/llm-router/src/index.ts`
|
| 872 |
-
|
| 873 |
-
**Interfaces:**
|
| 874 |
-
- Consumes: `selectProvider` from `./routing/selector`; all types; `LLMError` from `./utils/errors`
|
| 875 |
-
- Produces: `LLMRouter` class — the public API entry point
|
| 876 |
-
|
| 877 |
-
- [ ] **Step 1: Create src/router.ts**
|
| 878 |
-
|
| 879 |
-
Router tries each provider in strategy order. On any error (including `CircuitOpenError`), it catches and tries the next. Throws `LLMError` if all providers fail.
|
| 880 |
-
|
| 881 |
-
```ts
|
| 882 |
-
import type { RouterOptions, CompleteOptions, CompletionOutput, RoutingStrategy } from './types'
|
| 883 |
-
import { selectProvider } from './routing/selector'
|
| 884 |
-
import { LLMError } from './utils/errors'
|
| 885 |
-
|
| 886 |
-
export class LLMRouter {
|
| 887 |
-
private readonly providers: RouterOptions['providers']
|
| 888 |
-
private readonly defaultStrategy: RoutingStrategy
|
| 889 |
-
|
| 890 |
-
constructor(options: RouterOptions) {
|
| 891 |
-
this.providers = options.providers
|
| 892 |
-
this.defaultStrategy = options.defaultStrategy ?? 'fallback'
|
| 893 |
-
}
|
| 894 |
-
|
| 895 |
-
async complete(options: CompleteOptions): Promise<CompletionOutput> {
|
| 896 |
-
const strategy = options.strategy ?? this.defaultStrategy
|
| 897 |
-
const ordered = selectProvider(this.providers, strategy)
|
| 898 |
-
const errors: Error[] = []
|
| 899 |
-
|
| 900 |
-
for (const provider of ordered) {
|
| 901 |
-
try {
|
| 902 |
-
return await provider.complete(options)
|
| 903 |
-
} catch (err: unknown) {
|
| 904 |
-
errors.push(err instanceof Error ? err : new Error(String(err)))
|
| 905 |
-
}
|
| 906 |
-
}
|
| 907 |
-
|
| 908 |
-
throw new LLMError(
|
| 909 |
-
`All providers failed: ${errors.map(e => e.message).join('; ')}`,
|
| 910 |
-
'router',
|
| 911 |
-
)
|
| 912 |
-
}
|
| 913 |
-
}
|
| 914 |
-
```
|
| 915 |
-
|
| 916 |
-
- [ ] **Step 2: Create src/index.ts**
|
| 917 |
-
|
| 918 |
-
```ts
|
| 919 |
-
export { LLMRouter } from './router'
|
| 920 |
-
export { ollamaProvider, cerebrasProvider, groqProvider, claudeProvider } from './providers/index'
|
| 921 |
-
export type {
|
| 922 |
-
SimpleMessage,
|
| 923 |
-
CompletionInput,
|
| 924 |
-
CompletionOutput,
|
| 925 |
-
LLMProvider,
|
| 926 |
-
RouterOptions,
|
| 927 |
-
CompleteOptions,
|
| 928 |
-
RoutingStrategy,
|
| 929 |
-
} from './types'
|
| 930 |
-
export { LLMError, ProviderError, CircuitOpenError } from './utils/errors'
|
| 931 |
-
export { getCircuitStatus } from './utils/circuit-breaker'
|
| 932 |
-
```
|
| 933 |
-
|
| 934 |
-
- [ ] **Step 3: Full TypeScript check**
|
| 935 |
-
|
| 936 |
-
```bash
|
| 937 |
-
cd packages/llm-router && pnpm check
|
| 938 |
-
```
|
| 939 |
-
|
| 940 |
-
Expected: clean — all imports resolved, all types consistent.
|
| 941 |
-
|
| 942 |
-
- [ ] **Step 4: Build**
|
| 943 |
-
|
| 944 |
-
```bash
|
| 945 |
-
cd packages/llm-router && pnpm build
|
| 946 |
-
```
|
| 947 |
-
|
| 948 |
-
Expected: `dist/` populated with `.js`, `.d.ts`, `.js.map`, `.d.ts.map` files. No errors.
|
| 949 |
-
|
| 950 |
-
- [ ] **Step 5: Commit**
|
| 951 |
-
|
| 952 |
-
```bash
|
| 953 |
-
git add packages/llm-router/src/router.ts packages/llm-router/src/index.ts packages/llm-router/dist/
|
| 954 |
-
git commit -m "feat(llm-router): add LLMRouter class and public index — library complete"
|
| 955 |
-
```
|
| 956 |
-
|
| 957 |
-
---
|
| 958 |
-
|
| 959 |
-
## Task 9: Wire apps/api
|
| 960 |
-
|
| 961 |
-
Replace `apps/api`'s own providers, circuit breaker, and 250-line `llm-router.ts` with the new library. Extract prompts into their own files.
|
| 962 |
-
|
| 963 |
-
**Files:**
|
| 964 |
-
- Modify: `apps/api/package.json` — add `@llm-router/llm-router: workspace:*`
|
| 965 |
-
- Create: `apps/api/src/prompts/expense.prompt.ts`
|
| 966 |
-
- Create: `apps/api/src/prompts/chat.prompts.ts`
|
| 967 |
-
- Rewrite: `apps/api/src/llm-router.ts`
|
| 968 |
-
- Modify: `apps/api/src/chat/chat.controller.ts` — update `SimpleMessage` import
|
| 969 |
-
- Delete: `apps/api/src/providers/` (entire directory)
|
| 970 |
-
- Delete: `apps/api/src/circuit-breaker.ts`
|
| 971 |
-
|
| 972 |
-
**Interfaces:**
|
| 973 |
-
- Consumes: `LLMRouter`, `ollamaProvider`, `cerebrasProvider`, `groqProvider`, `SimpleMessage` from `@llm-router/llm-router`
|
| 974 |
-
- Produces: `route(messages, model, feature)` — unchanged signature consumed by `chat.controller.ts` and `expense.controller.ts`
|
| 975 |
-
|
| 976 |
-
- [ ] **Step 1: Add library dependency**
|
| 977 |
-
|
| 978 |
-
In `apps/api/package.json`, add to `dependencies`:
|
| 979 |
-
```json
|
| 980 |
-
"@llm-router/llm-router": "workspace:*"
|
| 981 |
-
```
|
| 982 |
-
|
| 983 |
-
Run:
|
| 984 |
-
```bash
|
| 985 |
-
pnpm install
|
| 986 |
-
```
|
| 987 |
-
|
| 988 |
-
- [ ] **Step 2: Create apps/api/src/prompts/expense.prompt.ts**
|
| 989 |
-
|
| 990 |
-
Move `EXPENSE_PARSE_PROMPT` out of `llm-router.ts` verbatim:
|
| 991 |
-
|
| 992 |
-
```ts
|
| 993 |
-
export const EXPENSE_PARSE_PROMPT = `You are a precise expense parser for a personal finance tracker.
|
| 994 |
-
Extract structured data from bank slip, receipt, or expense note text.
|
| 995 |
-
|
| 996 |
-
Return ONLY valid JSON with no markdown, no explanation, no extra text:
|
| 997 |
-
{
|
| 998 |
-
"amount": <number or null>,
|
| 999 |
-
"currency": "THB",
|
| 1000 |
-
"date": "<YYYY-MM-DD or null - use current year 2026 if year not specified>",
|
| 1001 |
-
"merchant": "<merchant name or null>",
|
| 1002 |
-
"category": "<see rules below>",
|
| 1003 |
-
"confidence": <0.0 to 1.0>,
|
| 1004 |
-
"raw_description": "<brief summary of original text>"
|
| 1005 |
-
}
|
| 1006 |
-
|
| 1007 |
-
Category selection rules — pick the MOST specific match:
|
| 1008 |
-
- food: restaurants, cafes, coffee shops, groceries, food delivery (GrabFood, FoodPanda)
|
| 1009 |
-
- transport: Grab ride, taxi, BTS, MRT, fuel, parking, toll
|
| 1010 |
-
- shopping: clothes, shoes, electronics, beauty, retail stores
|
| 1011 |
-
- bills: phone top-up, internet, Netflix, Spotify, software subscriptions
|
| 1012 |
-
- rental_electricity: rent payment, electricity bill, water bill, condo fee
|
| 1013 |
-
- gym: fitness center, gym membership, yoga, sports classes
|
| 1014 |
-
- health: pharmacy, hospital, clinic, doctor, dental, supplements
|
| 1015 |
-
- transfer: money transfer to family, send money, โอนเงิน
|
| 1016 |
-
- emergency: unexpected urgent expense, accident, repair
|
| 1017 |
-
- pet: pet food, vet clinic, pet grooming, pet supplies
|
| 1018 |
-
- maid: cleaning service, แม่บ้าน, housekeeping
|
| 1019 |
-
- entertainment: cinema, concert, games, hobbies, travel
|
| 1020 |
-
- su_personal: expense explicitly tagged for Su
|
| 1021 |
-
- tz_personal: expense explicitly tagged for Tz
|
| 1022 |
-
- other: anything that does not fit above categories
|
| 1023 |
-
|
| 1024 |
-
Critical rules:
|
| 1025 |
-
- NEVER guess or fabricate an amount — if unclear set null
|
| 1026 |
-
- If date not found use null (caller will use today's date)
|
| 1027 |
-
- Set confidence based on how clear the text is (1.0 = crystal clear slip, 0.5 = rough note)
|
| 1028 |
-
- For Thai text: handle Thai numerals and common Thai merchant names
|
| 1029 |
-
- Extract amount as a plain number from the actual input text only
|
| 1030 |
-
- Never use example numbers — only what is in the text
|
| 1031 |
-
- Handle formats: "28,000 baht" → 28000, "฿1,200" → 1200, "28000 บาท" → 28000
|
| 1032 |
-
- Remove commas and currency symbols`
|
| 1033 |
-
```
|
| 1034 |
-
|
| 1035 |
-
- [ ] **Step 3: Create apps/api/src/prompts/chat.prompts.ts**
|
| 1036 |
-
|
| 1037 |
-
Move the three system prompt strings verbatim from `llm-router.ts`:
|
| 1038 |
-
|
| 1039 |
-
```ts
|
| 1040 |
-
export const SYSTEM_PROMPTS: Record<string, string> = {
|
| 1041 |
-
'smart-router': `You are a smart, helpful assistant with broad expertise.
|
| 1042 |
-
Response rules:
|
| 1043 |
-
- Match length to complexity: short questions get concise answers
|
| 1044 |
-
- Always use concrete examples over abstract explanations
|
| 1045 |
-
- If uncertain say "I am not certain but..." never fabricate facts
|
| 1046 |
-
- For code: always show working examples with inline comments
|
| 1047 |
-
- Use markdown formatting with headers and code blocks when helpful`,
|
| 1048 |
-
|
| 1049 |
-
'professor-ai': `You are Professor AI — a world-class educator and personal mentor.
|
| 1050 |
-
You have deep expertise in technology, programming, trading, finance, crypto, and computer science.
|
| 1051 |
-
|
| 1052 |
-
Teaching philosophy:
|
| 1053 |
-
- Socratic method: guide with questions, not just answers
|
| 1054 |
-
- Start with WHY before HOW
|
| 1055 |
-
- Use real-world analogies for every abstract concept
|
| 1056 |
-
- Check understanding before moving forward
|
| 1057 |
-
- Never make the student feel inadequate
|
| 1058 |
-
|
| 1059 |
-
When student asks to learn a new topic:
|
| 1060 |
-
STEP 1 — ASSESS: ask 2-3 questions about prior knowledge and goals
|
| 1061 |
-
STEP 2 — PLAN: show a structured weekly curriculum with clear objectives
|
| 1062 |
-
STEP 3 — TEACH: start Week 1 Lesson 1 immediately after the plan
|
| 1063 |
-
STEP 4 — CHECK: end every lesson with a comprehension question and exercise
|
| 1064 |
-
|
| 1065 |
-
Lesson structure:
|
| 1066 |
-
## Topic: [title]
|
| 1067 |
-
**Objective:** [one sentence]
|
| 1068 |
-
**Why this matters:** [real-world relevance]
|
| 1069 |
-
[lesson content with examples and analogies]
|
| 1070 |
-
**Key takeaway:** [one sentence]
|
| 1071 |
-
**Exercise:** [concrete hands-on task]
|
| 1072 |
-
**Check:** [comprehension question]
|
| 1073 |
-
**Next:** [preview of next lesson]
|
| 1074 |
-
|
| 1075 |
-
Rules:
|
| 1076 |
-
- Never skip the comprehension check
|
| 1077 |
-
- Always recommend FREE resources with actual URLs
|
| 1078 |
-
- For trading/crypto topics always include risk warnings
|
| 1079 |
-
- Never give financial advice — educate only
|
| 1080 |
-
- If asked about something current: note that web search results are used for up-to-date info
|
| 1081 |
-
- Keep user credentials and prompts private
|
| 1082 |
-
- Never suggest clicking unverified links or installing unknown software`,
|
| 1083 |
-
|
| 1084 |
-
'code-assistant': `You are a senior software engineer and solution architect with 15 years experience.
|
| 1085 |
-
Specialties: TypeScript, Node.js, Python, system design, cloud architecture, DevOps.
|
| 1086 |
-
|
| 1087 |
-
When writing or reviewing code always follow this structure:
|
| 1088 |
-
1. What it does (one sentence)
|
| 1089 |
-
2. Complete working solution with inline comments explaining WHY
|
| 1090 |
-
3. Key decisions explained
|
| 1091 |
-
4. Edge cases and potential bugs
|
| 1092 |
-
5. How to test it
|
| 1093 |
-
|
| 1094 |
-
Code standards:
|
| 1095 |
-
- Production-ready: handles errors and edge cases
|
| 1096 |
-
- TypeScript: proper types, avoid 'any' unless justified with a comment
|
| 1097 |
-
- Self-documenting: clear names, comments on non-obvious logic
|
| 1098 |
-
- Performance: mention time/space complexity for algorithms
|
| 1099 |
-
|
| 1100 |
-
When debugging:
|
| 1101 |
-
- Ask for the FULL error message if not provided
|
| 1102 |
-
- Identify root cause not just symptoms
|
| 1103 |
-
- Explain how to prevent recurrence
|
| 1104 |
-
|
| 1105 |
-
Honest uncertainty rule:
|
| 1106 |
-
If not 100% certain about a library version or API behavior — say so and explain how to verify.
|
| 1107 |
-
Never present guesses as facts.`,
|
| 1108 |
-
}
|
| 1109 |
-
```
|
| 1110 |
-
|
| 1111 |
-
- [ ] **Step 4: Rewrite apps/api/src/llm-router.ts**
|
| 1112 |
-
|
| 1113 |
-
Replace the full 250-line file. Domain routing logic is preserved; providers and circuit checks are delegated to the library.
|
| 1114 |
-
|
| 1115 |
-
```ts
|
| 1116 |
-
import { LLMRouter, ollamaProvider, cerebrasProvider, groqProvider } from '@llm-router/llm-router'
|
| 1117 |
-
import type { SimpleMessage } from '@llm-router/llm-router'
|
| 1118 |
-
import { searchWeb } from './websearch'
|
| 1119 |
-
import { scanForPII } from './pii-scanner'
|
| 1120 |
-
import { EXPENSE_PARSE_PROMPT } from './prompts/expense.prompt'
|
| 1121 |
-
import { SYSTEM_PROMPTS } from './prompts/chat.prompts'
|
| 1122 |
-
|
| 1123 |
-
const ALWAYS_LOCAL = ['cv', 'resume', 'expense-parser']
|
| 1124 |
-
const ALWAYS_CLOUD = ['career_map', 'learning_path']
|
| 1125 |
-
|
| 1126 |
-
const router = new LLMRouter({
|
| 1127 |
-
providers: [ollamaProvider, cerebrasProvider, groqProvider],
|
| 1128 |
-
defaultStrategy: 'fallback',
|
| 1129 |
-
})
|
| 1130 |
-
|
| 1131 |
-
export interface RouterResult {
|
| 1132 |
-
response: string
|
| 1133 |
-
usedModel: 'local' | 'cloud' | 'fallback'
|
| 1134 |
-
piiDetected: boolean
|
| 1135 |
-
piiTypes?: string[]
|
| 1136 |
-
}
|
| 1137 |
-
|
| 1138 |
-
export { EXPENSE_PARSE_PROMPT }
|
| 1139 |
-
|
| 1140 |
-
function scanAllMessages(messages: SimpleMessage[]): { hasPII: boolean; types: string[] } {
|
| 1141 |
-
const allTypes = new Set<string>()
|
| 1142 |
-
for (const m of messages) {
|
| 1143 |
-
for (const t of scanForPII(m.content).types) allTypes.add(t)
|
| 1144 |
-
}
|
| 1145 |
-
return { hasPII: allTypes.size > 0, types: Array.from(allTypes) }
|
| 1146 |
-
}
|
| 1147 |
-
|
| 1148 |
-
export async function route(
|
| 1149 |
-
messages: SimpleMessage[],
|
| 1150 |
-
model: string = 'smart-router',
|
| 1151 |
-
feature?: string,
|
| 1152 |
-
): Promise<RouterResult> {
|
| 1153 |
-
const systemPrompt = SYSTEM_PROMPTS[model] ?? SYSTEM_PROMPTS['smart-router'] ?? ''
|
| 1154 |
-
const messagesWithSystem: SimpleMessage[] = [
|
| 1155 |
-
{ role: 'system', content: systemPrompt },
|
| 1156 |
-
...messages,
|
| 1157 |
-
]
|
| 1158 |
-
|
| 1159 |
-
const { hasPII: piiDetected, types: piiTypes } = scanAllMessages(messages)
|
| 1160 |
-
|
| 1161 |
-
// Expense parser — always cloud for accuracy, temperature 0
|
| 1162 |
-
if (model === 'expense-parser') {
|
| 1163 |
-
try {
|
| 1164 |
-
const result = await router.complete({
|
| 1165 |
-
messages: messagesWithSystem,
|
| 1166 |
-
strategy: 'quality',
|
| 1167 |
-
temperature: 0,
|
| 1168 |
-
})
|
| 1169 |
-
return { response: result.content, usedModel: 'cloud', piiDetected, piiTypes }
|
| 1170 |
-
} catch (err: unknown) {
|
| 1171 |
-
const msg = err instanceof Error ? err.message : String(err)
|
| 1172 |
-
throw new Error(`Expense parsing failed: ${msg}`)
|
| 1173 |
-
}
|
| 1174 |
-
}
|
| 1175 |
-
|
| 1176 |
-
// Professor AI — cloud with web search, Ollama fallback
|
| 1177 |
-
if (model === 'professor-ai') {
|
| 1178 |
-
const lastMessage = messages[messages.length - 1]?.content ?? ''
|
| 1179 |
-
const searchResults = await searchWeb(lastMessage)
|
| 1180 |
-
const contextMessages: SimpleMessage[] = searchResults
|
| 1181 |
-
? [{ role: 'system', content: `Current web research results:\n${searchResults}` }, ...messagesWithSystem]
|
| 1182 |
-
: messagesWithSystem
|
| 1183 |
-
try {
|
| 1184 |
-
const result = await router.complete({ messages: contextMessages, strategy: 'quality' })
|
| 1185 |
-
return { response: result.content, usedModel: 'cloud', piiDetected, piiTypes }
|
| 1186 |
-
} catch {
|
| 1187 |
-
const result = await router.complete({ messages: messagesWithSystem, strategy: 'local' })
|
| 1188 |
-
return { response: result.content, usedModel: 'fallback', piiDetected, piiTypes }
|
| 1189 |
-
}
|
| 1190 |
-
}
|
| 1191 |
-
|
| 1192 |
-
// Code assistant — local first
|
| 1193 |
-
if (model === 'code-assistant') {
|
| 1194 |
-
const result = await router.complete({ messages: messagesWithSystem, strategy: 'local' })
|
| 1195 |
-
return {
|
| 1196 |
-
response: result.content,
|
| 1197 |
-
usedModel: result.provider === 'ollama' ? 'local' : 'fallback',
|
| 1198 |
-
piiDetected,
|
| 1199 |
-
piiTypes,
|
| 1200 |
-
}
|
| 1201 |
-
}
|
| 1202 |
-
|
| 1203 |
-
// Smart router — PII-based routing
|
| 1204 |
-
const wantsLocal =
|
| 1205 |
-
(feature !== undefined && ALWAYS_LOCAL.includes(feature)) ||
|
| 1206 |
-
(feature === undefined && piiDetected && !ALWAYS_CLOUD.includes(''))
|
| 1207 |
-
const strategy = wantsLocal ? 'local' : 'quality'
|
| 1208 |
-
const result = await router.complete({ messages: messagesWithSystem, strategy })
|
| 1209 |
-
return {
|
| 1210 |
-
response: result.content,
|
| 1211 |
-
usedModel: result.provider === 'ollama' ? 'local' : 'cloud',
|
| 1212 |
-
piiDetected,
|
| 1213 |
-
piiTypes,
|
| 1214 |
-
}
|
| 1215 |
-
}
|
| 1216 |
-
```
|
| 1217 |
-
|
| 1218 |
-
- [ ] **Step 5: Update chat.controller.ts import**
|
| 1219 |
-
|
| 1220 |
-
In `apps/api/src/chat/chat.controller.ts`, change line 12:
|
| 1221 |
-
|
| 1222 |
-
Old:
|
| 1223 |
-
```ts
|
| 1224 |
-
import type { SimpleMessage } from '../providers/base'
|
| 1225 |
-
```
|
| 1226 |
-
|
| 1227 |
-
New:
|
| 1228 |
-
```ts
|
| 1229 |
-
import type { SimpleMessage } from '@llm-router/llm-router'
|
| 1230 |
-
```
|
| 1231 |
-
|
| 1232 |
-
- [ ] **Step 6: Delete replaced files**
|
| 1233 |
-
|
| 1234 |
-
```bash
|
| 1235 |
-
rm -rf apps/api/src/providers/
|
| 1236 |
-
rm apps/api/src/circuit-breaker.ts
|
| 1237 |
-
```
|
| 1238 |
-
|
| 1239 |
-
Check that no other file in `apps/api/src/` imports from `./providers/` or `./circuit-breaker`:
|
| 1240 |
-
```bash
|
| 1241 |
-
grep -r "providers/base\|providers/ollama\|providers/cerebras\|circuit-breaker" apps/api/src/
|
| 1242 |
-
```
|
| 1243 |
-
|
| 1244 |
-
Expected: no matches. If any file matches, update its import to use `@llm-router/llm-router`.
|
| 1245 |
-
|
| 1246 |
-
- [ ] **Step 7: TypeScript check for apps/api**
|
| 1247 |
-
|
| 1248 |
-
```bash
|
| 1249 |
-
cd apps/api && pnpm check 2>/dev/null || cd apps/api && npx tsc --noEmit
|
| 1250 |
-
```
|
| 1251 |
-
|
| 1252 |
-
Expected: clean. Fix any type errors before continuing.
|
| 1253 |
-
|
| 1254 |
-
- [ ] **Step 8: Run existing tests**
|
| 1255 |
-
|
| 1256 |
-
```bash
|
| 1257 |
-
cd apps/api && npx vitest run
|
| 1258 |
-
```
|
| 1259 |
-
|
| 1260 |
-
Expected: all existing tests pass (they don't touch providers directly).
|
| 1261 |
-
|
| 1262 |
-
- [ ] **Step 9: Commit**
|
| 1263 |
-
|
| 1264 |
-
```bash
|
| 1265 |
-
git add apps/api/package.json apps/api/src/llm-router.ts apps/api/src/prompts/ apps/api/src/chat/chat.controller.ts pnpm-lock.yaml
|
| 1266 |
-
git rm -r apps/api/src/providers/ apps/api/src/circuit-breaker.ts
|
| 1267 |
-
git commit -m "feat(api): wire @llm-router/llm-router, extract prompts, remove inline providers"
|
| 1268 |
-
```
|
| 1269 |
-
|
| 1270 |
-
---
|
| 1271 |
-
|
| 1272 |
-
## Self-Review Checklist
|
| 1273 |
-
|
| 1274 |
-
**Spec coverage:**
|
| 1275 |
-
- [x] Package scaffold with correct name `@llm-router/llm-router` — Task 1
|
| 1276 |
-
- [x] `types.ts` with all interfaces including `CompleteOptions` — Task 2
|
| 1277 |
-
- [x] Typed errors: `LLMError`, `ProviderError`, `CircuitOpenError` — Task 2
|
| 1278 |
-
- [x] `withRetry` helper — Task 3
|
| 1279 |
-
- [x] `calcCostUsd` + `PRICING` map with all four model families — Task 3
|
| 1280 |
-
- [x] Circuit breaker generified by string key — Task 3
|
| 1281 |
-
- [x] Ollama migrated + shared retry — Task 4
|
| 1282 |
-
- [x] Cerebras migrated + shared retry — Task 4
|
| 1283 |
-
- [x] Groq NEW — Task 5
|
| 1284 |
-
- [x] Claude NEW with prefill — Task 6
|
| 1285 |
-
- [x] All four routing strategies with correct provider order — Task 7
|
| 1286 |
-
- [x] `LLMRouter` class with fallback-to-next-provider logic — Task 8
|
| 1287 |
-
- [x] Public `index.ts` exports — Task 8
|
| 1288 |
-
- [x] `apps/api` wired: old providers deleted, new imports in place — Task 9
|
| 1289 |
-
- [x] Prompts extracted to `prompts/` — Task 9
|
| 1290 |
-
- [x] `chat.controller.ts` import updated — Task 9
|
| 1291 |
-
- [x] `EXPENSE_PARSE_PROMPT` re-exported for backward compat — Task 9
|
| 1292 |
-
|
| 1293 |
-
**Known deviation from spec:** Spec specified `"type": "module"` (ESM). Plan uses CJS (no `"type": "module"`) to match `apps/api`'s runtime mode and avoid CJS/ESM interop issues. ESM dual-build can be added before npm publish.
|
| 1294 |
-
|
| 1295 |
-
**Type consistency check:**
|
| 1296 |
-
- `withRetry(fn, maxAttempts, onFailure)` — `onFailure: (attempt, err) => number` — consistent across Tasks 3–6
|
| 1297 |
-
- `CompletionOutput.provider` field added in Task 2 `types.ts`, consumed correctly in all providers (Tasks 4–6)
|
| 1298 |
-
- `CompleteOptions extends CompletionInput { strategy?: RoutingStrategy }` — router passes `options` (a `CompleteOptions`) directly to `provider.complete(input: CompletionInput)` — valid because `CompleteOptions` is a structural subtype of `CompletionInput`
|
| 1299 |
-
- `SYSTEM_PROMPTS['smart-router']` — with `noUncheckedIndexedAccess`, returns `string | undefined`; the `?? ''` handles the undefined case
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 4 |
-
**Status:** Approved
|
| 5 |
-
|
| 6 |
-
## Goal
|
| 7 |
-
|
| 8 |
-
Refactor the monolithic `proxy.ts` into a feature-based structure:
|
| 9 |
-
routes → validator middleware → controllers → services. Each API endpoint owns
|
| 10 |
-
its own folder. `router.ts` is renamed to `llm-router.ts` to avoid confusion
|
| 11 |
-
with Express routers.
|
| 12 |
-
|
| 13 |
-
## Folder Structure
|
| 14 |
-
|
| 15 |
-
```
|
| 16 |
-
src/
|
| 17 |
-
chat/
|
| 18 |
-
chat.routes.ts — registers POST /v1/chat/completions
|
| 19 |
-
chat.controller.ts — OCR dispatch, streaming, response formatting
|
| 20 |
-
chat.validator.ts — Zod schema + validateChat middleware
|
| 21 |
-
expense/
|
| 22 |
-
expense.routes.ts — registers POST /v1/expense/parse
|
| 23 |
-
expense.controller.ts — text/image extraction, calls expense.service
|
| 24 |
-
expense.validator.ts — Zod schema + validateExpense middleware
|
| 25 |
-
expense.service.ts — parseJSON, fixDate, formatMessage, triggerN8N
|
| 26 |
-
ocr.service.ts — Tesseract OCR (shared by chat + expense)
|
| 27 |
-
health/
|
| 28 |
-
health.routes.ts — GET /health, GET /v1/models, GET /v1/openapi.json
|
| 29 |
-
middleware/
|
| 30 |
-
authMiddleware.ts — unchanged
|
| 31 |
-
validate.ts — reusable validate(ZodSchema) factory
|
| 32 |
-
llm-router.ts — renamed from router.ts; no logic changes
|
| 33 |
-
proxy.ts — bootstrap only: parsers, CORS, route mounting, listen
|
| 34 |
-
```
|
| 35 |
-
|
| 36 |
-
## Request Flow
|
| 37 |
-
|
| 38 |
-
```
|
| 39 |
-
Request
|
| 40 |
-
→ authMiddleware
|
| 41 |
-
→ route
|
| 42 |
-
→ validate(schema) ← returns 400 { error, details } on failure
|
| 43 |
-
→ controller
|
| 44 |
-
→ service / llm-router
|
| 45 |
-
→ response
|
| 46 |
-
```
|
| 47 |
-
|
| 48 |
-
## Components
|
| 49 |
-
|
| 50 |
-
### `middleware/validate.ts`
|
| 51 |
-
|
| 52 |
-
Single factory used by all routes. Parses with `schema.safeParse(req.body)`,
|
| 53 |
-
returns `400` with Zod error details on failure, assigns `req.body = result.data`
|
| 54 |
-
(typed and coerced) on success, then calls `next()`.
|
| 55 |
-
|
| 56 |
-
```ts
|
| 57 |
-
export const validate = (schema: ZodSchema) =>
|
| 58 |
-
(req: Request, res: Response, next: NextFunction) => {
|
| 59 |
-
const result = schema.safeParse(req.body)
|
| 60 |
-
if (!result.success)
|
| 61 |
-
return res.status(400).json({
|
| 62 |
-
error: result.error.errors[0].message,
|
| 63 |
-
details: result.error.errors
|
| 64 |
-
})
|
| 65 |
-
req.body = result.data
|
| 66 |
-
next()
|
| 67 |
-
}
|
| 68 |
-
```
|
| 69 |
-
|
| 70 |
-
### `chat/chat.validator.ts`
|
| 71 |
-
|
| 72 |
-
Defines Zod schema for `POST /v1/chat/completions`:
|
| 73 |
-
- `messages` — non-empty array of `{ role: string, content: string | array }`
|
| 74 |
-
- `model` — optional string, defaults to `'smart-router'`
|
| 75 |
-
- `stream` — optional boolean
|
| 76 |
-
|
| 77 |
-
Exports `validateChat = validate(chatSchema)`.
|
| 78 |
-
|
| 79 |
-
### `chat/chat.routes.ts`
|
| 80 |
-
|
| 81 |
-
```ts
|
| 82 |
-
router.post('/v1/chat/completions', validateChat, chatController.complete)
|
| 83 |
-
```
|
| 84 |
-
|
| 85 |
-
### `chat/chat.controller.ts`
|
| 86 |
-
|
| 87 |
-
Responsibilities:
|
| 88 |
-
- Detect `model === 'expense-parser'` and dispatch OCR if image content present
|
| 89 |
-
- Call `route()` from `llm-router`
|
| 90 |
-
- Handle streaming response (SSE) vs JSON response
|
| 91 |
-
- Format OpenAI-compatible response shape
|
| 92 |
-
|
| 93 |
-
### `expense/expense.validator.ts`
|
| 94 |
-
|
| 95 |
-
Defines Zod schema for `POST /v1/expense/parse`:
|
| 96 |
-
- Accepts any of: `text`, `body.text`, `body.body.text`, `data.text`, `message`,
|
| 97 |
-
`content` (fault-tolerant nesting from n8n/curl)
|
| 98 |
-
- `image` / `imageBase64` — optional string
|
| 99 |
-
|
| 100 |
-
Exports `validateExpense = validate(expenseSchema)`. Validation passes as long
|
| 101 |
-
as the body is parseable; missing text/image is caught in the controller after
|
| 102 |
-
OCR attempt, returning 400 with helpful `expectedFormats`.
|
| 103 |
-
|
| 104 |
-
### `expense/expense.service.ts`
|
| 105 |
-
|
| 106 |
-
Pure functions, no Express types:
|
| 107 |
-
- `parseExpenseJSON(raw: string)` — extracts and parses JSON from model response
|
| 108 |
-
- `fixDate(expense)` — fills missing date with today, corrects wrong year
|
| 109 |
-
- `formatExpenseMessage(expense, saved)` — returns markdown table string
|
| 110 |
-
- `triggerN8N(expense, source, rawText)` — fire-and-forget webhook
|
| 111 |
-
|
| 112 |
-
### `expense/ocr.service.ts`
|
| 113 |
-
|
| 114 |
-
Single function `extractTextFromImage(base64: string): Promise<string>`.
|
| 115 |
-
Shared by `chat.controller` and `expense.controller`.
|
| 116 |
-
|
| 117 |
-
### `health/health.routes.ts`
|
| 118 |
-
|
| 119 |
-
Registers three trivial endpoints with inline handlers (no controller/service
|
| 120 |
-
needed):
|
| 121 |
-
- `GET /health` — circuit status + n8n flag
|
| 122 |
-
- `GET /v1/models` — static model list
|
| 123 |
-
- `GET /v1/openapi.json` — static OpenAPI stub
|
| 124 |
-
|
| 125 |
-
### `llm-router.ts`
|
| 126 |
-
|
| 127 |
-
Renamed from `router.ts`. No logic changes. All imports updated to point to
|
| 128 |
-
the new filename.
|
| 129 |
-
|
| 130 |
-
### `proxy.ts` (after refactor)
|
| 131 |
-
|
| 132 |
-
~30 lines. Only responsibilities:
|
| 133 |
-
1. Load `dotenv`
|
| 134 |
-
2. Create Express app
|
| 135 |
-
3. Register body parsers + CORS
|
| 136 |
-
4. Mount `authMiddleware`
|
| 137 |
-
5. Mount all route modules
|
| 138 |
-
6. Start keepAlive interval
|
| 139 |
-
7. `app.listen`
|
| 140 |
-
|
| 141 |
-
## Validation Library
|
| 142 |
-
|
| 143 |
-
**Zod** — installed as a new dependency (`npm install zod`). Chosen because:
|
| 144 |
-
- TypeScript-native: schema defines both runtime validation and static types
|
| 145 |
-
- `safeParse` never throws
|
| 146 |
-
- Coerces `req.body` to typed shape before it reaches the controller
|
| 147 |
-
|
| 148 |
-
## What Does Not Change
|
| 149 |
-
|
| 150 |
-
- All LLM routing logic in `llm-router.ts` (formerly `router.ts`)
|
| 151 |
-
- `middleware/authMiddleware.ts`
|
| 152 |
-
- All provider files (`providers/ollama.ts`, `providers/cerebras.ts`, etc.)
|
| 153 |
-
- `pii-scanner.ts`, `circuit-breaker.ts`, `logger.ts`, `websearch.ts`
|
| 154 |
-
- Public API surface — all endpoints, request/response shapes unchanged
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
docs/superpowers/specs/2026-06-30-expense-dashboard-design.md
DELETED
|
@@ -1,384 +0,0 @@
|
|
| 1 |
-
# Expense Dashboard Design
|
| 2 |
-
|
| 3 |
-
## Overview
|
| 4 |
-
|
| 5 |
-
Full-stack expense tracker with CRUD dashboard. Personal use. Backend: Express API in this repo. Frontend: Vite + React SPA. Database: Neon serverless Postgres via Drizzle ORM. Repo restructured as a pnpm monorepo.
|
| 6 |
-
|
| 7 |
-
---
|
| 8 |
-
|
| 9 |
-
## Monorepo Structure
|
| 10 |
-
|
| 11 |
-
Migrate from flat repo to pnpm workspaces. The existing Express backend moves to `apps/api/`. A new Vite + React dashboard lives in `apps/dashboard/`. Shared TypeScript types live in `packages/shared/`.
|
| 12 |
-
|
| 13 |
-
```
|
| 14 |
-
llm_router/
|
| 15 |
-
pnpm-workspace.yaml
|
| 16 |
-
package.json ← workspace root (scripts only, no code)
|
| 17 |
-
pnpm-lock.yaml
|
| 18 |
-
|
| 19 |
-
packages/
|
| 20 |
-
shared/ ← @llm-router/shared
|
| 21 |
-
src/
|
| 22 |
-
expense.types.ts ← shared Zod schemas + inferred TS types
|
| 23 |
-
index.ts
|
| 24 |
-
package.json
|
| 25 |
-
tsconfig.json
|
| 26 |
-
|
| 27 |
-
apps/
|
| 28 |
-
api/ ← @llm-router/api (existing backend, moved)
|
| 29 |
-
src/ ← current src/ moved here unchanged
|
| 30 |
-
package.json
|
| 31 |
-
tsconfig.json
|
| 32 |
-
dashboard/ ← @llm-router/dashboard (new)
|
| 33 |
-
src/
|
| 34 |
-
pages/
|
| 35 |
-
components/
|
| 36 |
-
lib/
|
| 37 |
-
hooks/
|
| 38 |
-
index.html
|
| 39 |
-
vite.config.ts
|
| 40 |
-
package.json
|
| 41 |
-
tsconfig.json
|
| 42 |
-
```
|
| 43 |
-
|
| 44 |
-
**`pnpm-workspace.yaml`:**
|
| 45 |
-
```yaml
|
| 46 |
-
packages:
|
| 47 |
-
- 'apps/*'
|
| 48 |
-
- 'packages/*'
|
| 49 |
-
```
|
| 50 |
-
|
| 51 |
-
**Root `package.json`:**
|
| 52 |
-
```json
|
| 53 |
-
{
|
| 54 |
-
"name": "llm-router-monorepo",
|
| 55 |
-
"private": true,
|
| 56 |
-
"scripts": {
|
| 57 |
-
"dev": "pnpm -F @llm-router/api dev & pnpm -F @llm-router/dashboard dev",
|
| 58 |
-
"build": "pnpm -r build",
|
| 59 |
-
"test": "pnpm -r test"
|
| 60 |
-
}
|
| 61 |
-
}
|
| 62 |
-
```
|
| 63 |
-
|
| 64 |
-
**Internal package references use `workspace:*`:**
|
| 65 |
-
```json
|
| 66 |
-
{ "dependencies": { "@llm-router/shared": "workspace:*" } }
|
| 67 |
-
```
|
| 68 |
-
|
| 69 |
-
**Key pnpm commands:**
|
| 70 |
-
```bash
|
| 71 |
-
pnpm install # install everything at root
|
| 72 |
-
pnpm dev # start API + dashboard together
|
| 73 |
-
pnpm -F @llm-router/api dev # just the API
|
| 74 |
-
pnpm -F @llm-router/dashboard dev # just the dashboard
|
| 75 |
-
pnpm -F @llm-router/api test # test one workspace
|
| 76 |
-
pnpm add react -F @llm-router/dashboard # add dep to specific workspace
|
| 77 |
-
pnpm add drizzle-orm -F @llm-router/api # add dep to API
|
| 78 |
-
```
|
| 79 |
-
|
| 80 |
-
---
|
| 81 |
-
|
| 82 |
-
## Tech Stack
|
| 83 |
-
|
| 84 |
-
| Layer | Choice | Version |
|
| 85 |
-
|---|---|---|
|
| 86 |
-
| Runtime | Node.js | ≥22 |
|
| 87 |
-
| Package manager | pnpm workspaces | ≥9 |
|
| 88 |
-
| API framework | Express | ^5 (existing) |
|
| 89 |
-
| ORM | Drizzle ORM | ^0.44 |
|
| 90 |
-
| Database | Neon serverless Postgres | — |
|
| 91 |
-
| Validation | Zod | ^4 (existing) |
|
| 92 |
-
| Frontend framework | React | ^19 |
|
| 93 |
-
| Routing (FE) | React Router | ^7 |
|
| 94 |
-
| Server state | TanStack Query | ^5 |
|
| 95 |
-
| Charts | Recharts | ^2 |
|
| 96 |
-
| UI components | shadcn/ui + Tailwind CSS | latest |
|
| 97 |
-
| Build tool | Vite | ^6 |
|
| 98 |
-
| Testing | Vitest | ^4 (existing) |
|
| 99 |
-
|
| 100 |
-
---
|
| 101 |
-
|
| 102 |
-
## Database Schema
|
| 103 |
-
|
| 104 |
-
All tables in Neon Postgres. Drizzle ORM schema in `apps/api/src/expense/db/schema.ts`.
|
| 105 |
-
|
| 106 |
-
### `user_profile` (single row, seeded on first run)
|
| 107 |
-
|
| 108 |
-
| Column | Type | Constraints |
|
| 109 |
-
|---|---|---|
|
| 110 |
-
| `id` | uuid | PK, default gen_random_uuid() |
|
| 111 |
-
| `preferred_currency` | text | NOT NULL, DEFAULT 'USD' |
|
| 112 |
-
| `locale` | text | NOT NULL, DEFAULT 'en-US' |
|
| 113 |
-
| `budget_reset_day` | int | NOT NULL, DEFAULT 1 |
|
| 114 |
-
| `created_at` | timestamptz | DEFAULT now() |
|
| 115 |
-
| `updated_at` | timestamptz | DEFAULT now() |
|
| 116 |
-
|
| 117 |
-
### `categories`
|
| 118 |
-
|
| 119 |
-
| Column | Type | Constraints |
|
| 120 |
-
|---|---|---|
|
| 121 |
-
| `id` | uuid | PK, default gen_random_uuid() |
|
| 122 |
-
| `name` | text | NOT NULL, UNIQUE |
|
| 123 |
-
| `color` | text | NOT NULL, DEFAULT '#6B7280' (hex) |
|
| 124 |
-
| `icon` | text | nullable (emoji e.g. '🍔') |
|
| 125 |
-
| `created_at` | timestamptz | DEFAULT now() |
|
| 126 |
-
|
| 127 |
-
Seeded defaults: Food, Transport, Health, Shopping, Utilities, Entertainment, Other.
|
| 128 |
-
|
| 129 |
-
### `expenses`
|
| 130 |
-
|
| 131 |
-
| Column | Type | Constraints |
|
| 132 |
-
|---|---|---|
|
| 133 |
-
| `id` | uuid | PK, default gen_random_uuid() |
|
| 134 |
-
| `amount` | numeric(10,2) | NOT NULL |
|
| 135 |
-
| `currency` | text | NOT NULL — API layer defaults to user_profile.preferred_currency at insert time |
|
| 136 |
-
| `category_id` | uuid | NOT NULL, FK → categories(id) |
|
| 137 |
-
| `merchant` | text | nullable |
|
| 138 |
-
| `date` | date | NOT NULL |
|
| 139 |
-
| `description` | text | nullable |
|
| 140 |
-
| `source` | text | NOT NULL, DEFAULT 'manual' — 'manual' \| 'ocr' \| 'n8n' |
|
| 141 |
-
| `raw_text` | text | nullable — original OCR/webhook input, kept for audit |
|
| 142 |
-
| `created_at` | timestamptz | DEFAULT now() |
|
| 143 |
-
| `updated_at` | timestamptz | DEFAULT now() |
|
| 144 |
-
|
| 145 |
-
### `budgets`
|
| 146 |
-
|
| 147 |
-
| Column | Type | Constraints |
|
| 148 |
-
|---|---|---|
|
| 149 |
-
| `id` | uuid | PK, default gen_random_uuid() |
|
| 150 |
-
| `category_id` | uuid | NOT NULL, FK → categories(id) |
|
| 151 |
-
| `amount` | numeric(10,2) | NOT NULL |
|
| 152 |
-
| `period` | text | NOT NULL, DEFAULT 'monthly' |
|
| 153 |
-
| `created_at` | timestamptz | DEFAULT now() |
|
| 154 |
-
| `updated_at` | timestamptz | DEFAULT now() |
|
| 155 |
-
| — | — | UNIQUE(category_id, period) |
|
| 156 |
-
|
| 157 |
-
No alerts table. Over-budget state is computed at query time by comparing current period's expenses against budgets.
|
| 158 |
-
|
| 159 |
-
**Period calculation:** `budget_reset_day` in `user_profile` determines the current period window. If `budget_reset_day = 1`, period = calendar month (1st–last day). If `budget_reset_day = 15`, period = 15th of current month to 14th of next month. The `summary` endpoint computes this window server-side and returns the `period` label as `YYYY-MM` (always the month the period starts in).
|
| 160 |
-
|
| 161 |
-
---
|
| 162 |
-
|
| 163 |
-
## API Endpoints
|
| 164 |
-
|
| 165 |
-
All routes extend `apps/api/src/expense/expense.routes.ts`, mounted at `/v1/expense`.
|
| 166 |
-
|
| 167 |
-
### Categories
|
| 168 |
-
```
|
| 169 |
-
GET /v1/expense/categories list all
|
| 170 |
-
POST /v1/expense/categories create { name, color, icon? }
|
| 171 |
-
PUT /v1/expense/categories/:id update { name?, color?, icon? }
|
| 172 |
-
DELETE /v1/expense/categories/:id delete — 409 if expenses reference it
|
| 173 |
-
```
|
| 174 |
-
|
| 175 |
-
409 response body: `{ error: "Category has 12 expenses — reassign them first" }`
|
| 176 |
-
|
| 177 |
-
### Expenses
|
| 178 |
-
```
|
| 179 |
-
GET /v1/expense list with filters
|
| 180 |
-
?category_id=&from=&to=&search=&page=&limit=
|
| 181 |
-
POST /v1/expense/manual create from dashboard { amount, currency?, category_id, merchant?, date, description? }
|
| 182 |
-
POST /v1/expense/parse existing OCR/n8n route (unchanged)
|
| 183 |
-
GET /v1/expense/:id get one
|
| 184 |
-
PUT /v1/expense/:id update { amount?, currency?, category_id?, merchant?, date?, description? }
|
| 185 |
-
DELETE /v1/expense/:id delete
|
| 186 |
-
```
|
| 187 |
-
|
| 188 |
-
### Budgets
|
| 189 |
-
```
|
| 190 |
-
GET /v1/expense/budgets list all (with current month spent per category)
|
| 191 |
-
POST /v1/expense/budgets create { category_id, amount, period? }
|
| 192 |
-
PUT /v1/expense/budgets/:id update { amount?, period? }
|
| 193 |
-
DELETE /v1/expense/budgets/:id delete
|
| 194 |
-
```
|
| 195 |
-
|
| 196 |
-
### Analytics (read-only, computed)
|
| 197 |
-
```
|
| 198 |
-
GET /v1/expense/summary current period summary (period determined by budget_reset_day)
|
| 199 |
-
GET /v1/expense/trends?months=6 last N months totals (months defaults to 6)
|
| 200 |
-
```
|
| 201 |
-
|
| 202 |
-
**`GET /v1/expense/summary` response:**
|
| 203 |
-
```ts
|
| 204 |
-
{
|
| 205 |
-
period: '2026-06', // YYYY-MM of current budget period
|
| 206 |
-
total_spent: 1240.50,
|
| 207 |
-
currency_warning: boolean, // true if expenses contain mixed currencies
|
| 208 |
-
categories: [
|
| 209 |
-
{
|
| 210 |
-
category_id: string,
|
| 211 |
-
category_name: string,
|
| 212 |
-
color: string,
|
| 213 |
-
spent: number,
|
| 214 |
-
budget: number | null, // null if no budget set
|
| 215 |
-
over_budget: boolean
|
| 216 |
-
}
|
| 217 |
-
]
|
| 218 |
-
}
|
| 219 |
-
```
|
| 220 |
-
|
| 221 |
-
**`GET /v1/expense/trends?months=6` response:**
|
| 222 |
-
```ts
|
| 223 |
-
{
|
| 224 |
-
months: [
|
| 225 |
-
{ period: '2026-01', total: 980.00 },
|
| 226 |
-
{ period: '2026-02', total: 1100.50 },
|
| 227 |
-
// ...
|
| 228 |
-
]
|
| 229 |
-
}
|
| 230 |
-
```
|
| 231 |
-
|
| 232 |
-
### User Profile
|
| 233 |
-
```
|
| 234 |
-
GET /v1/expense/profile get preferences
|
| 235 |
-
PUT /v1/expense/profile update { preferred_currency?, locale?, budget_reset_day? }
|
| 236 |
-
```
|
| 237 |
-
|
| 238 |
-
---
|
| 239 |
-
|
| 240 |
-
## Shared Types (`packages/shared`)
|
| 241 |
-
|
| 242 |
-
`packages/shared/src/expense.types.ts` exports Zod schemas and inferred types used by both API and dashboard:
|
| 243 |
-
|
| 244 |
-
```ts
|
| 245 |
-
export const CategorySchema = z.object({ id: z.string().uuid(), name: z.string(), color: z.string(), icon: z.string().nullable() })
|
| 246 |
-
export const ExpenseSchema = z.object({ id: z.string().uuid(), amount: z.number(), currency: z.string(), category_id: z.string().uuid(), merchant: z.string().nullable(), date: z.string(), description: z.string().nullable(), source: z.string(), created_at: z.string() })
|
| 247 |
-
export const BudgetSchema = z.object({ id: z.string().uuid(), category_id: z.string().uuid(), amount: z.number(), period: z.string() })
|
| 248 |
-
export const SummaryItemSchema = z.object({ category_id: z.string().uuid(), category_name: z.string(), color: z.string(), spent: z.number(), budget: z.number().nullable(), over_budget: z.boolean() })
|
| 249 |
-
export const SummarySchema = z.object({ period: z.string(), total_spent: z.number(), currency_warning: z.boolean(), categories: z.array(SummaryItemSchema) })
|
| 250 |
-
|
| 251 |
-
export type Category = z.infer<typeof CategorySchema>
|
| 252 |
-
export type Expense = z.infer<typeof ExpenseSchema>
|
| 253 |
-
export type Budget = z.infer<typeof BudgetSchema>
|
| 254 |
-
export type Summary = z.infer<typeof SummarySchema>
|
| 255 |
-
```
|
| 256 |
-
|
| 257 |
-
---
|
| 258 |
-
|
| 259 |
-
## Frontend Structure
|
| 260 |
-
|
| 261 |
-
### Pages
|
| 262 |
-
|
| 263 |
-
```
|
| 264 |
-
/ Dashboard
|
| 265 |
-
/expenses Expense CRUD table
|
| 266 |
-
/budgets Budget management
|
| 267 |
-
/settings Profile + category management
|
| 268 |
-
```
|
| 269 |
-
|
| 270 |
-
### Dashboard page layout
|
| 271 |
-
|
| 272 |
-
```
|
| 273 |
-
┌─ AlertBanner (over-budget, dismissible per category+month) ────────┐
|
| 274 |
-
├─ SummaryCards ─────────────────────────────────────────────────────┤
|
| 275 |
-
│ Total spent │ Budget left │ Top category │ # this month │
|
| 276 |
-
├─ TrendChart ───────────────────────────┬─ CategoryChart ───────────┤
|
| 277 |
-
│ Line: last 6 months totals │ Donut: by category │
|
| 278 |
-
├─ CategoryProgressBars ─────────────────┴───────────────────────────┤
|
| 279 |
-
│ Food ████████░░ $420/$300 ⚠️ │
|
| 280 |
-
│ Transport ████░░░░ $80/$150 │
|
| 281 |
-
├─ Recent expenses (last 10) ────────────────────────────────────────┤
|
| 282 |
-
│ Jun 28 Grab Transport $12.50 [edit] │
|
| 283 |
-
└────────────────────────────────────────────────────────────────────┘
|
| 284 |
-
```
|
| 285 |
-
|
| 286 |
-
### Component tree
|
| 287 |
-
|
| 288 |
-
```
|
| 289 |
-
apps/dashboard/src/
|
| 290 |
-
pages/
|
| 291 |
-
Dashboard.tsx
|
| 292 |
-
Expenses.tsx
|
| 293 |
-
Budgets.tsx
|
| 294 |
-
Settings.tsx
|
| 295 |
-
components/
|
| 296 |
-
layout/
|
| 297 |
-
Sidebar.tsx
|
| 298 |
-
Layout.tsx
|
| 299 |
-
expense/
|
| 300 |
-
ExpenseTable.tsx
|
| 301 |
-
ExpenseModal.tsx ← shared for create + edit
|
| 302 |
-
ExpenseFilters.tsx ← date range, category dropdown, search
|
| 303 |
-
budget/
|
| 304 |
-
BudgetList.tsx
|
| 305 |
-
BudgetModal.tsx ← shared for create + edit
|
| 306 |
-
CategoryProgressBar.tsx
|
| 307 |
-
dashboard/
|
| 308 |
-
SummaryCards.tsx
|
| 309 |
-
TrendChart.tsx ← Recharts LineChart
|
| 310 |
-
CategoryChart.tsx ← Recharts PieChart
|
| 311 |
-
AlertBanner.tsx
|
| 312 |
-
ui/ ← shadcn/ui wrappers
|
| 313 |
-
Modal.tsx
|
| 314 |
-
ConfirmDialog.tsx
|
| 315 |
-
lib/
|
| 316 |
-
api.ts ← typed fetch wrapper, base URL from VITE_API_URL env var
|
| 317 |
-
queryClient.ts ← TanStack Query client setup
|
| 318 |
-
hooks/
|
| 319 |
-
useExpenses.ts
|
| 320 |
-
useBudgets.ts
|
| 321 |
-
useSummary.ts
|
| 322 |
-
useCategories.ts
|
| 323 |
-
useProfile.ts
|
| 324 |
-
```
|
| 325 |
-
|
| 326 |
-
### `lib/api.ts` shape
|
| 327 |
-
|
| 328 |
-
Typed wrapper around `fetch`, reads `VITE_API_URL` from env:
|
| 329 |
-
|
| 330 |
-
```ts
|
| 331 |
-
export const api = {
|
| 332 |
-
get: <T>(path: string) => fetch(`${BASE}/v1/expense${path}`).then(r => r.json() as Promise<T>),
|
| 333 |
-
post: <T>(path: string, body: unknown) => fetch(..., { method: 'POST', body: JSON.stringify(body) }).then(...),
|
| 334 |
-
put: <T>(path: string, body: unknown) => ...,
|
| 335 |
-
del: (path: string) => ...,
|
| 336 |
-
}
|
| 337 |
-
```
|
| 338 |
-
|
| 339 |
-
---
|
| 340 |
-
|
| 341 |
-
## Alert Logic
|
| 342 |
-
|
| 343 |
-
- `AlertBanner` reads `over_budget: true` from `/v1/expense/summary`
|
| 344 |
-
- One dismissible banner per over-budget category
|
| 345 |
-
- Message: `"⚠️ Food: $420 spent of $300 budget this month"`
|
| 346 |
-
- Dismissed state: `localStorage` key `dismissed_alerts_{YYYY-MM}` (array of category IDs)
|
| 347 |
-
- Auto-resets next month (key includes period)
|
| 348 |
-
|
| 349 |
-
---
|
| 350 |
-
|
| 351 |
-
## Currency Handling
|
| 352 |
-
|
| 353 |
-
- `user_profile.preferred_currency` is the default for new expenses
|
| 354 |
-
- Each expense stores its own `currency` (for multi-currency / travel)
|
| 355 |
-
- Dashboard totals only sum expenses matching `preferred_currency`
|
| 356 |
-
- If mixed currencies exist in the period: `currency_warning: true` in summary → frontend shows info banner: `"Some expenses are in a different currency and are excluded from totals"`
|
| 357 |
-
- No exchange rate conversion in this phase
|
| 358 |
-
|
| 359 |
-
---
|
| 360 |
-
|
| 361 |
-
## Environment Variables
|
| 362 |
-
|
| 363 |
-
**`apps/api/.env`:**
|
| 364 |
-
```
|
| 365 |
-
DATABASE_URL=postgresql://...neon.tech/expense?sslmode=require
|
| 366 |
-
PORT=3000
|
| 367 |
-
API_KEY=...
|
| 368 |
-
```
|
| 369 |
-
|
| 370 |
-
**`apps/dashboard/.env`:**
|
| 371 |
-
```
|
| 372 |
-
VITE_API_URL=http://localhost:3000
|
| 373 |
-
```
|
| 374 |
-
|
| 375 |
-
---
|
| 376 |
-
|
| 377 |
-
## Out of Scope (Phase 2)
|
| 378 |
-
|
| 379 |
-
- Exchange rate conversion for multi-currency totals
|
| 380 |
-
- Email/push alerts (in-app only for now)
|
| 381 |
-
- Recurring expense detection
|
| 382 |
-
- Receipt image storage (OCR result saved as `raw_text`, image not stored)
|
| 383 |
-
- Export to CSV/PDF
|
| 384 |
-
-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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
docs/superpowers/specs/2026-07-02-expense-dashboard-design.md
DELETED
|
@@ -1,217 +0,0 @@
|
|
| 1 |
-
# Expense Dashboard Design
|
| 2 |
-
|
| 3 |
-
## Overview
|
| 4 |
-
|
| 5 |
-
A single-user React web app for managing personal expenses. Lives at `apps/expense-dashboard` in the monorepo. Talks to the existing `apps/api` on port 7860.
|
| 6 |
-
|
| 7 |
-
---
|
| 8 |
-
|
| 9 |
-
## Tech Stack
|
| 10 |
-
|
| 11 |
-
| Concern | Choice |
|
| 12 |
-
|---|---|
|
| 13 |
-
| Build tool | Vite |
|
| 14 |
-
| Framework | React 18 + TypeScript |
|
| 15 |
-
| Styling | Tailwind CSS |
|
| 16 |
-
| Components | shadcn/ui |
|
| 17 |
-
| Charts | Recharts |
|
| 18 |
-
| Auth token | JWT stored in localStorage |
|
| 19 |
-
| HTTP | fetch (typed wrappers in `src/api/`) |
|
| 20 |
-
|
| 21 |
-
---
|
| 22 |
-
|
| 23 |
-
## Authentication
|
| 24 |
-
|
| 25 |
-
Single-user. Login with email + password.
|
| 26 |
-
|
| 27 |
-
**Backend addition:** `POST /auth/login` endpoint in `apps/api`
|
| 28 |
-
- Accepts `{ email, password }`
|
| 29 |
-
- Verifies password against `ADMIN_PASSWORD` env var (bcrypt hash)
|
| 30 |
-
- Returns `{ token: <JWT> }` signed with `JWT_SECRET` env var, 7-day expiry
|
| 31 |
-
- JWT payload: `{ sub: 'admin' }`
|
| 32 |
-
|
| 33 |
-
**Frontend:**
|
| 34 |
-
- Unauthenticated users redirected to `/login`
|
| 35 |
-
- JWT stored in `localStorage` as `expense_token`
|
| 36 |
-
- All API requests send `Authorization: Bearer <token>`
|
| 37 |
-
- On 401 response → clear token, redirect to `/login`
|
| 38 |
-
|
| 39 |
-
---
|
| 40 |
-
|
| 41 |
-
## File Structure
|
| 42 |
-
|
| 43 |
-
```
|
| 44 |
-
apps/expense-dashboard/
|
| 45 |
-
src/
|
| 46 |
-
api/
|
| 47 |
-
client.ts ← base fetch wrapper (attaches Bearer token, handles 401)
|
| 48 |
-
auth.ts ← login()
|
| 49 |
-
expenses.ts ← parse(), create(), list(), update(), delete()
|
| 50 |
-
categories.ts ← list(), create(), update(), delete()
|
| 51 |
-
budgets.ts ← list(), create(), update(), delete()
|
| 52 |
-
analytics.ts ← summary(), trends()
|
| 53 |
-
components/
|
| 54 |
-
layout/
|
| 55 |
-
Sidebar.tsx
|
| 56 |
-
AppShell.tsx
|
| 57 |
-
expenses/
|
| 58 |
-
ExpenseList.tsx
|
| 59 |
-
ExpenseRow.tsx
|
| 60 |
-
AddExpenseDrawer.tsx ← two tabs: Upload Receipt / Manual Entry
|
| 61 |
-
ReceiptPreview.tsx ← parsed result + category picker
|
| 62 |
-
CategoryPicker.tsx
|
| 63 |
-
analytics/
|
| 64 |
-
SpendDonut.tsx
|
| 65 |
-
DailyBarChart.tsx
|
| 66 |
-
BudgetCard.tsx
|
| 67 |
-
ui/ ← shadcn generated components
|
| 68 |
-
pages/
|
| 69 |
-
LoginPage.tsx
|
| 70 |
-
DashboardPage.tsx
|
| 71 |
-
ExpensesPage.tsx
|
| 72 |
-
CategoriesPage.tsx
|
| 73 |
-
BudgetsPage.tsx
|
| 74 |
-
hooks/
|
| 75 |
-
useAuth.ts
|
| 76 |
-
useExpenses.ts
|
| 77 |
-
useCategories.ts
|
| 78 |
-
useBudgets.ts
|
| 79 |
-
useAnalytics.ts
|
| 80 |
-
lib/
|
| 81 |
-
auth.ts ← getToken(), clearToken(), isAuthenticated()
|
| 82 |
-
dates.ts ← formatMonth(), monthRange()
|
| 83 |
-
router.tsx ← React Router v6, protected route wrapper
|
| 84 |
-
main.tsx
|
| 85 |
-
index.html
|
| 86 |
-
vite.config.ts
|
| 87 |
-
tailwind.config.ts
|
| 88 |
-
tsconfig.json
|
| 89 |
-
package.json
|
| 90 |
-
```
|
| 91 |
-
|
| 92 |
-
---
|
| 93 |
-
|
| 94 |
-
## Pages
|
| 95 |
-
|
| 96 |
-
### Login (`/login`)
|
| 97 |
-
- Email + password form
|
| 98 |
-
- Calls `POST /auth/login`, stores JWT, redirects to `/`
|
| 99 |
-
- No sidebar — full-screen centered card
|
| 100 |
-
|
| 101 |
-
### Dashboard (`/`)
|
| 102 |
-
- Month picker (default: current month)
|
| 103 |
-
- **Total spend vs budget** — large number + overall progress bar
|
| 104 |
-
- **Spend by category** — donut chart (Recharts PieChart)
|
| 105 |
-
- **Daily spend** — bar chart (Recharts BarChart), x-axis = days of month
|
| 106 |
-
- **Budget cards** — one card per category with a budget set: spent / limit, color-coded (green < 80%, amber 80–100%, red > 100%)
|
| 107 |
-
|
| 108 |
-
### Expenses (`/expenses`)
|
| 109 |
-
- Month picker at top
|
| 110 |
-
- Expense list — grouped by date, sorted newest first
|
| 111 |
-
- Each row: date, merchant, category badge (color), amount
|
| 112 |
-
- Click row → inline edit (amount, merchant, date, category, description)
|
| 113 |
-
- Delete button on row
|
| 114 |
-
- Floating **+ Add** button → opens `AddExpenseDrawer`
|
| 115 |
-
|
| 116 |
-
**AddExpenseDrawer — two tabs:**
|
| 117 |
-
|
| 118 |
-
*Upload Receipt*
|
| 119 |
-
1. Image dropzone (accepts JPEG/PNG/base64) + optional description textarea
|
| 120 |
-
2. "Parse" button → calls `POST /v1/expense/parse`
|
| 121 |
-
3. `ReceiptPreview` shows: amount, merchant, date, detected category
|
| 122 |
-
4. Category picker: auto-selects if name matches existing category; required picker if no match
|
| 123 |
-
5. "Save" → calls `POST /v1/expense/manual` with confirmed data
|
| 124 |
-
|
| 125 |
-
*Manual Entry*
|
| 126 |
-
- Amount, currency, merchant, date, description fields
|
| 127 |
-
- Category picker (required)
|
| 128 |
-
- "Save" → calls `POST /v1/expense/manual`
|
| 129 |
-
|
| 130 |
-
### Categories (`/categories`)
|
| 131 |
-
- List of categories with color swatch and icon
|
| 132 |
-
- Add category: name, color (hex picker), emoji icon (optional)
|
| 133 |
-
- Edit inline
|
| 134 |
-
- Delete (disabled if category has expenses)
|
| 135 |
-
|
| 136 |
-
### Budgets (`/budgets`)
|
| 137 |
-
- List of monthly budgets, one per category
|
| 138 |
-
- Add budget: pick category, set amount
|
| 139 |
-
- Edit amount inline
|
| 140 |
-
- Delete
|
| 141 |
-
|
| 142 |
-
---
|
| 143 |
-
|
| 144 |
-
## Key Flows
|
| 145 |
-
|
| 146 |
-
### Receipt Upload + Category Tagging
|
| 147 |
-
|
| 148 |
-
```
|
| 149 |
-
User drops image (+ optional description)
|
| 150 |
-
→ POST /v1/expense/parse → { expense: { amount, merchant, date, category, confidence }, ocrUsed }
|
| 151 |
-
→ ReceiptPreview rendered
|
| 152 |
-
→ FE matches expense.category string against categories list (case-insensitive)
|
| 153 |
-
match found → category pre-selected, user can override
|
| 154 |
-
no match → CategoryPicker shown, required before save
|
| 155 |
-
→ User confirms
|
| 156 |
-
→ POST /v1/expense/manual → { id, ... }
|
| 157 |
-
→ Expense list refreshed
|
| 158 |
-
```
|
| 159 |
-
|
| 160 |
-
### Month Navigation
|
| 161 |
-
|
| 162 |
-
All pages with a month picker share a `selectedMonth` state (YYYY-MM string). The month picker is a `<select>` showing the last 12 months. Changing it refetches the relevant data.
|
| 163 |
-
|
| 164 |
-
---
|
| 165 |
-
|
| 166 |
-
## API Mapping
|
| 167 |
-
|
| 168 |
-
| FE call | API endpoint |
|
| 169 |
-
|---|---|
|
| 170 |
-
| `auth.login()` | `POST /auth/login` (new) |
|
| 171 |
-
| `expenses.parse()` | `POST /v1/expense/parse` |
|
| 172 |
-
| `expenses.create()` | `POST /v1/expense/manual` |
|
| 173 |
-
| `expenses.list()` | `GET /v1/expense?from=&to=` |
|
| 174 |
-
| `expenses.update()` | `PUT /v1/expense/:id` |
|
| 175 |
-
| `expenses.delete()` | `DELETE /v1/expense/:id` |
|
| 176 |
-
| `categories.list()` | `GET /v1/expense/categories` |
|
| 177 |
-
| `categories.create()` | `POST /v1/expense/categories` |
|
| 178 |
-
| `categories.update()` | `PUT /v1/expense/categories/:id` |
|
| 179 |
-
| `categories.delete()` | `DELETE /v1/expense/categories/:id` |
|
| 180 |
-
| `budgets.list()` | `GET /v1/expense/budgets` |
|
| 181 |
-
| `budgets.create()` | `POST /v1/expense/budgets` |
|
| 182 |
-
| `budgets.update()` | `PUT /v1/expense/budgets/:id` |
|
| 183 |
-
| `budgets.delete()` | `DELETE /v1/expense/budgets/:id` |
|
| 184 |
-
| `analytics.summary()` | `GET /v1/expense/summary?period=YYYY-MM` |
|
| 185 |
-
| `analytics.trends()` | `GET /v1/expense/trends` |
|
| 186 |
-
|
| 187 |
-
---
|
| 188 |
-
|
| 189 |
-
## Backend Addition: Auth Endpoint
|
| 190 |
-
|
| 191 |
-
New file: `apps/api/src/auth/auth.routes.ts`
|
| 192 |
-
|
| 193 |
-
```
|
| 194 |
-
POST /auth/login
|
| 195 |
-
Body: { email: string, password: string }
|
| 196 |
-
→ bcrypt.compare(password, process.env.ADMIN_PASSWORD_HASH)
|
| 197 |
-
→ sign JWT { sub: 'admin' } with process.env.JWT_SECRET, expiresIn: '7d'
|
| 198 |
-
→ return { token }
|
| 199 |
-
|
| 200 |
-
New env vars:
|
| 201 |
-
ADMIN_EMAIL ← email to accept
|
| 202 |
-
ADMIN_PASSWORD_HASH ← bcrypt hash of password (generated once via script)
|
| 203 |
-
JWT_SECRET ← random secret for signing
|
| 204 |
-
```
|
| 205 |
-
|
| 206 |
-
`authMiddleware` updated to also accept valid JWTs (verify with `JWT_SECRET`) in addition to the existing `INTERNAL_SECRET` key check.
|
| 207 |
-
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
docs/superpowers/specs/2026-07-02-llm-router-library-design.md
DELETED
|
@@ -1,275 +0,0 @@
|
|
| 1 |
-
# `@llm-router/llm-router` Library Design
|
| 2 |
-
|
| 3 |
-
## Overview
|
| 4 |
-
|
| 5 |
-
Extract the LLM provider and routing logic from `apps/api` into a standalone, domain-agnostic package at `packages/llm-router`. Published internally as `@llm-router/llm-router` (workspace) and eventually to npm as `@yagonnan/llm-router`.
|
| 6 |
-
|
| 7 |
-
The library knows nothing about expenses, chat, PII, or system prompts. It is a pure LLM client with provider abstraction, circuit breaking, retry, token counting, and cost tracking.
|
| 8 |
-
|
| 9 |
-
`apps/api` retains all domain logic (system prompts, PII routing, expense parser, professor-ai) and imports the library instead of calling providers directly.
|
| 10 |
-
|
| 11 |
-
---
|
| 12 |
-
|
| 13 |
-
## Package Identity
|
| 14 |
-
|
| 15 |
-
| Field | Value |
|
| 16 |
-
|---|---|
|
| 17 |
-
| Package name | `@llm-router/llm-router` |
|
| 18 |
-
| Location | `packages/llm-router/` |
|
| 19 |
-
| Version | `0.1.0` |
|
| 20 |
-
| Future npm name | `@yagonnan/llm-router` |
|
| 21 |
-
| Module system | ESM (`"type": "module"`) |
|
| 22 |
-
| TypeScript | strict, `moduleResolution: nodenext` |
|
| 23 |
-
|
| 24 |
-
---
|
| 25 |
-
|
| 26 |
-
## File Structure
|
| 27 |
-
|
| 28 |
-
```
|
| 29 |
-
packages/llm-router/
|
| 30 |
-
src/
|
| 31 |
-
index.ts ← public exports
|
| 32 |
-
types.ts ← all shared interfaces and types
|
| 33 |
-
router.ts ← LLMRouter class
|
| 34 |
-
providers/
|
| 35 |
-
base.ts ← LLMProvider interface
|
| 36 |
-
ollama.ts ← Ollama (migrated + retry extracted)
|
| 37 |
-
cerebras.ts ← Cerebras (migrated + retry extracted)
|
| 38 |
-
groq.ts ← NEW: Groq Cloud
|
| 39 |
-
claude.ts ← NEW: Anthropic Claude
|
| 40 |
-
index.ts ← re-exports all four providers
|
| 41 |
-
utils/
|
| 42 |
-
retry.ts ← exponential backoff helper
|
| 43 |
-
tokens.ts ← per-million cost calculation, token count helpers
|
| 44 |
-
errors.ts ← LLMError, ProviderError, CircuitOpenError
|
| 45 |
-
circuit-breaker.ts ← generified circuit breaker (keyed by provider name)
|
| 46 |
-
routing/
|
| 47 |
-
strategies.ts ← RoutingStrategy type + provider ordering per strategy
|
| 48 |
-
selector.ts ← selectProvider(providers, strategy) → LLMProvider
|
| 49 |
-
package.json
|
| 50 |
-
tsconfig.json
|
| 51 |
-
```
|
| 52 |
-
|
| 53 |
-
---
|
| 54 |
-
|
| 55 |
-
## Core Types (`types.ts`)
|
| 56 |
-
|
| 57 |
-
```ts
|
| 58 |
-
export type MessageRole = 'user' | 'assistant' | 'system'
|
| 59 |
-
|
| 60 |
-
export interface SimpleMessage {
|
| 61 |
-
role: MessageRole
|
| 62 |
-
content: string
|
| 63 |
-
}
|
| 64 |
-
|
| 65 |
-
export interface CompletionInput {
|
| 66 |
-
messages: SimpleMessage[]
|
| 67 |
-
maxTokens?: number
|
| 68 |
-
temperature?: number
|
| 69 |
-
prefill?: string // Claude pre-fill; other providers ignore
|
| 70 |
-
}
|
| 71 |
-
|
| 72 |
-
export interface CompletionOutput {
|
| 73 |
-
content: string
|
| 74 |
-
model: string // actual model identifier from provider
|
| 75 |
-
provider: string // provider name (e.g. 'groq', 'ollama')
|
| 76 |
-
inputTokens: number
|
| 77 |
-
outputTokens: number
|
| 78 |
-
costUsd: number // 0 for local models
|
| 79 |
-
durationMs: number
|
| 80 |
-
}
|
| 81 |
-
|
| 82 |
-
export type RoutingStrategy = 'cost' | 'local' | 'quality' | 'fallback'
|
| 83 |
-
|
| 84 |
-
export interface RouterOptions {
|
| 85 |
-
providers: LLMProvider[]
|
| 86 |
-
defaultStrategy?: RoutingStrategy // defaults to 'fallback'
|
| 87 |
-
}
|
| 88 |
-
|
| 89 |
-
export interface CompleteOptions extends CompletionInput {
|
| 90 |
-
strategy?: RoutingStrategy // overrides defaultStrategy for this call
|
| 91 |
-
}
|
| 92 |
-
```
|
| 93 |
-
|
| 94 |
-
---
|
| 95 |
-
|
| 96 |
-
## Provider Interface
|
| 97 |
-
|
| 98 |
-
`LLMProvider` lives in `types.ts` (alongside `CompletionInput`/`CompletionOutput`) to avoid circular imports. `providers/base.ts` re-exports it as a convenience:
|
| 99 |
-
|
| 100 |
-
```ts
|
| 101 |
-
// types.ts
|
| 102 |
-
export interface LLMProvider {
|
| 103 |
-
readonly name: string
|
| 104 |
-
complete(input: CompletionInput): Promise<CompletionOutput>
|
| 105 |
-
}
|
| 106 |
-
```
|
| 107 |
-
|
| 108 |
-
---
|
| 109 |
-
|
| 110 |
-
## Providers
|
| 111 |
-
|
| 112 |
-
### Ollama (`providers/ollama.ts`)
|
| 113 |
-
- Config: `OLLAMA_HOST` (default `http://localhost:11434`), `OLLAMA_MODEL` (default `qwen2.5:0.5b`)
|
| 114 |
-
- Cost: `0` (local)
|
| 115 |
-
- Retry: 2 attempts via shared `retry.ts`
|
| 116 |
-
- Timeout: 30 000 ms
|
| 117 |
-
- Circuit: keyed as `'ollama'`
|
| 118 |
-
|
| 119 |
-
### Cerebras (`providers/cerebras.ts`)
|
| 120 |
-
- Config: `CEREBRAS_API_KEY`, `CLOUD_MODEL` (default `llama-3.3-70b`)
|
| 121 |
-
- Pricing: per-million tokens map (existing rates preserved)
|
| 122 |
-
- Retry: 2 attempts, 429 → 2 s backoff, other → 1 s backoff
|
| 123 |
-
- Circuit: keyed as `'cerebras'`
|
| 124 |
-
|
| 125 |
-
### Groq (`providers/groq.ts`) — NEW
|
| 126 |
-
- Config: `GROQ_API_KEY`, `GROQ_MODEL` (default `llama-3.3-70b-versatile`)
|
| 127 |
-
- SDK: `groq-sdk`
|
| 128 |
-
- Pricing: per-million tokens (Groq public rates)
|
| 129 |
-
- Retry: 2 attempts, 429 → 2 s backoff
|
| 130 |
-
- Circuit: keyed as `'groq'`
|
| 131 |
-
|
| 132 |
-
### Claude (`providers/claude.ts`) — NEW
|
| 133 |
-
- Config: `ANTHROPIC_API_KEY`, `CLAUDE_MODEL` (default `claude-sonnet-4-6`)
|
| 134 |
-
- SDK: `@anthropic-ai/sdk`
|
| 135 |
-
- Pricing: `claude-sonnet-4-6` → input $3/M, output $15/M
|
| 136 |
-
- Pre-fill: supported via `prefill` option (appended as assistant turn)
|
| 137 |
-
- Retry: 2 attempts, 529/overloaded → 5 s backoff
|
| 138 |
-
- Circuit: keyed as `'claude'`
|
| 139 |
-
|
| 140 |
-
---
|
| 141 |
-
|
| 142 |
-
## Routing Strategies (`routing/strategies.ts`)
|
| 143 |
-
|
| 144 |
-
`selectProvider` tries providers in strategy order, skipping any whose circuit is open. If all circuits are open, throws `CircuitOpenError`.
|
| 145 |
-
|
| 146 |
-
| Strategy | Provider order |
|
| 147 |
-
|---|---|
|
| 148 |
-
| `'cost'` | Ollama → Cerebras → Groq → Claude |
|
| 149 |
-
| `'local'` | Ollama → Groq → Cerebras → Claude |
|
| 150 |
-
| `'quality'` | Claude → Groq → Cerebras → Ollama |
|
| 151 |
-
| `'fallback'` | Config registration order |
|
| 152 |
-
|
| 153 |
-
Only providers registered in `RouterOptions.providers` are considered. If a strategy names a provider not registered, it is skipped silently.
|
| 154 |
-
|
| 155 |
-
---
|
| 156 |
-
|
| 157 |
-
## Circuit Breaker (`utils/circuit-breaker.ts`)
|
| 158 |
-
|
| 159 |
-
- Keyed by `provider.name` (string) — no hardcoded union type
|
| 160 |
-
- Threshold: 3 failures → open
|
| 161 |
-
- Reset: 60 s half-open (auto-reset on next `isCircuitOpen` check after timeout)
|
| 162 |
-
- API: `isCircuitOpen(name)`, `recordSuccess(name)`, `recordFailure(name)`, `getCircuitStatus()`
|
| 163 |
-
|
| 164 |
-
---
|
| 165 |
-
|
| 166 |
-
## Retry Helper (`utils/retry.ts`)
|
| 167 |
-
|
| 168 |
-
```ts
|
| 169 |
-
export async function withRetry<T>(
|
| 170 |
-
fn: () => Promise<T>,
|
| 171 |
-
maxAttempts: number,
|
| 172 |
-
backoffMs: (attempt: number) => number
|
| 173 |
-
): Promise<T>
|
| 174 |
-
```
|
| 175 |
-
|
| 176 |
-
Used by all providers. Replaces the inline retry loops currently duplicated in Ollama and Cerebras.
|
| 177 |
-
|
| 178 |
-
---
|
| 179 |
-
|
| 180 |
-
## Token + Cost Utilities (`utils/tokens.ts`)
|
| 181 |
-
|
| 182 |
-
```ts
|
| 183 |
-
export function calcCostUsd(
|
| 184 |
-
inputTokens: number,
|
| 185 |
-
outputTokens: number,
|
| 186 |
-
pricing: { input: number; output: number } // per million
|
| 187 |
-
): number
|
| 188 |
-
|
| 189 |
-
export const PRICING: Record<string, { input: number; output: number }> = {
|
| 190 |
-
'llama-3.3-70b': { input: 0.85, output: 1.20 },
|
| 191 |
-
'llama-3.1-8b': { input: 0.10, output: 0.10 },
|
| 192 |
-
'llama-3.3-70b-versatile': { input: 0.59, output: 0.79 }, // Groq
|
| 193 |
-
'claude-sonnet-4-6': { input: 3.00, output: 15.00 },
|
| 194 |
-
}
|
| 195 |
-
```
|
| 196 |
-
|
| 197 |
-
---
|
| 198 |
-
|
| 199 |
-
## Typed Errors (`utils/errors.ts`)
|
| 200 |
-
|
| 201 |
-
```ts
|
| 202 |
-
export class LLMError extends Error {
|
| 203 |
-
constructor(message: string, public readonly provider: string) { super(message) }
|
| 204 |
-
}
|
| 205 |
-
|
| 206 |
-
export class CircuitOpenError extends LLMError {}
|
| 207 |
-
|
| 208 |
-
export class ProviderError extends LLMError {
|
| 209 |
-
constructor(message: string, provider: string, public readonly status?: number) {
|
| 210 |
-
super(message, provider)
|
| 211 |
-
}
|
| 212 |
-
}
|
| 213 |
-
```
|
| 214 |
-
|
| 215 |
-
All `catch (err: any)` blocks become `catch (err: unknown)` with narrowing via `instanceof`.
|
| 216 |
-
|
| 217 |
-
---
|
| 218 |
-
|
| 219 |
-
## LLMRouter Class (`router.ts`)
|
| 220 |
-
|
| 221 |
-
```ts
|
| 222 |
-
export class LLMRouter {
|
| 223 |
-
constructor(options: RouterOptions)
|
| 224 |
-
|
| 225 |
-
async complete(options: CompleteOptions): Promise<CompletionOutput>
|
| 226 |
-
}
|
| 227 |
-
```
|
| 228 |
-
|
| 229 |
-
- Selects provider via `selectProvider(this.providers, strategy)`
|
| 230 |
-
- Calls `provider.complete(input)`
|
| 231 |
-
- If provider throws, tries next provider in strategy order
|
| 232 |
-
- Throws `LLMError` if all providers fail
|
| 233 |
-
|
| 234 |
-
---
|
| 235 |
-
|
| 236 |
-
## Public Exports (`index.ts`)
|
| 237 |
-
|
| 238 |
-
```ts
|
| 239 |
-
export { LLMRouter } from './router.js'
|
| 240 |
-
export { ollamaProvider, cerebrasProvider, groqProvider, claudeProvider } from './providers/index.js'
|
| 241 |
-
export type { SimpleMessage, CompletionInput, CompletionOutput, RoutingStrategy, RouterOptions, CompleteOptions } from './types.js'
|
| 242 |
-
export { LLMError, ProviderError, CircuitOpenError } from './utils/errors.js'
|
| 243 |
-
```
|
| 244 |
-
|
| 245 |
-
---
|
| 246 |
-
|
| 247 |
-
## `apps/api` Changes
|
| 248 |
-
|
| 249 |
-
### Deleted
|
| 250 |
-
- `apps/api/src/providers/` — entire directory
|
| 251 |
-
- `apps/api/src/circuit-breaker.ts`
|
| 252 |
-
|
| 253 |
-
### Modified
|
| 254 |
-
- `apps/api/src/llm-router.ts` — slimmed to ~40 lines; imports `LLMRouter` from `@llm-router/llm-router`; keeps domain routing logic, system prompts, PII routing
|
| 255 |
-
- `apps/api/src/index.ts` — deleted (dead test script)
|
| 256 |
-
- `apps/api/package.json` — adds `"@llm-router/llm-router": "workspace:*"`
|
| 257 |
-
|
| 258 |
-
### New
|
| 259 |
-
- `apps/api/src/prompts/expense.prompt.ts` — `EXPENSE_PARSE_PROMPT` constant
|
| 260 |
-
- `apps/api/src/prompts/chat.prompts.ts` — `smart-router`, `professor-ai`, `code-assistant` system prompts
|
| 261 |
-
|
| 262 |
-
---
|
| 263 |
-
|
| 264 |
-
## Testing
|
| 265 |
-
|
| 266 |
-
No tests in this phase. Integration tests (with real API keys) will be added in a follow-up.
|
| 267 |
-
|
| 268 |
-
---
|
| 269 |
-
|
| 270 |
-
## Out of Scope
|
| 271 |
-
|
| 272 |
-
- npm publish to `@yagonnan/llm-router` (done after API stabilises)
|
| 273 |
-
- Streaming responses
|
| 274 |
-
- Expense-tracker and ai-apps repo splits
|
| 275 |
-
- Frontend dashboard (Plan 2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/circuit-breaker.ts
DELETED
|
@@ -1,60 +0,0 @@
|
|
| 1 |
-
export type CircuitName = 'ollama' | 'cerebras' | 'claude'
|
| 2 |
-
|
| 3 |
-
interface CircuitState {
|
| 4 |
-
failures: number
|
| 5 |
-
lastFailure: number | null
|
| 6 |
-
isOpen: boolean
|
| 7 |
-
}
|
| 8 |
-
|
| 9 |
-
const FAILURE_THRESHOLD = 3
|
| 10 |
-
const RESET_TIMEOUT_MS = 60000 // 1 minute
|
| 11 |
-
|
| 12 |
-
const circuits: Record<CircuitName, CircuitState> = {
|
| 13 |
-
ollama: { failures: 0, lastFailure: null, isOpen: false },
|
| 14 |
-
cerebras: { failures: 0, lastFailure: null, isOpen: false },
|
| 15 |
-
claude: { failures: 0, lastFailure: null, isOpen: false },
|
| 16 |
-
}
|
| 17 |
-
|
| 18 |
-
export function isCircuitOpen(service: CircuitName): boolean {
|
| 19 |
-
const circuit = circuits[service]
|
| 20 |
-
|
| 21 |
-
if (!circuit.isOpen) return false
|
| 22 |
-
|
| 23 |
-
// Check if enough time passed to try again (half-open state)
|
| 24 |
-
const now = Date.now()
|
| 25 |
-
if (circuit.lastFailure !== null && now - circuit.lastFailure > RESET_TIMEOUT_MS) {
|
| 26 |
-
circuit.isOpen = false
|
| 27 |
-
circuit.failures = 0
|
| 28 |
-
console.log(JSON.stringify({ event: 'circuit_half_open', service }))
|
| 29 |
-
return false
|
| 30 |
-
}
|
| 31 |
-
|
| 32 |
-
return true
|
| 33 |
-
}
|
| 34 |
-
|
| 35 |
-
export function recordSuccess(service: CircuitName): void {
|
| 36 |
-
circuits[service] = { failures: 0, lastFailure: null, isOpen: false }
|
| 37 |
-
}
|
| 38 |
-
|
| 39 |
-
export function recordFailure(service: CircuitName): void {
|
| 40 |
-
const circuit = circuits[service]
|
| 41 |
-
circuit.failures++
|
| 42 |
-
circuit.lastFailure = Date.now()
|
| 43 |
-
|
| 44 |
-
if (circuit.failures >= FAILURE_THRESHOLD) {
|
| 45 |
-
circuit.isOpen = true
|
| 46 |
-
console.log(JSON.stringify({
|
| 47 |
-
event: 'circuit_opened',
|
| 48 |
-
service,
|
| 49 |
-
failures: circuit.failures
|
| 50 |
-
}))
|
| 51 |
-
}
|
| 52 |
-
}
|
| 53 |
-
|
| 54 |
-
export function getCircuitStatus(): Record<CircuitName, { isOpen: boolean; failures: number }> {
|
| 55 |
-
return {
|
| 56 |
-
ollama: { isOpen: circuits.ollama.isOpen, failures: circuits.ollama.failures },
|
| 57 |
-
cerebras: { isOpen: circuits.cerebras.isOpen, failures: circuits.cerebras.failures },
|
| 58 |
-
claude: { isOpen: circuits.claude.isOpen, failures: circuits.claude.failures },
|
| 59 |
-
}
|
| 60 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/groq-client.ts
DELETED
|
@@ -1,65 +0,0 @@
|
|
| 1 |
-
import Cerebras from '@cerebras/cerebras_cloud_sdk'
|
| 2 |
-
import { recordSuccess, recordFailure, isCircuitOpen } from './circuit-breaker'
|
| 3 |
-
import { logger } from './logger'
|
| 4 |
-
|
| 5 |
-
const cerebras = new Cerebras({ apiKey: process.env.CEREBRAS_API_KEY })
|
| 6 |
-
const MAX_RETRIES = 2
|
| 7 |
-
|
| 8 |
-
export type SimpleMessage = { role: 'user' | 'assistant' | 'system'; content: string, image_url?: { url: string } }
|
| 9 |
-
interface CerebrasChoice {
|
| 10 |
-
message: {
|
| 11 |
-
content: string
|
| 12 |
-
role: string
|
| 13 |
-
}
|
| 14 |
-
finish_reason: string
|
| 15 |
-
}
|
| 16 |
-
|
| 17 |
-
interface CerebrasResponse {
|
| 18 |
-
choices: CerebrasChoice[]
|
| 19 |
-
}
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
export async function queryCloud(messages: SimpleMessage[]): Promise<string> {
|
| 23 |
-
if (isCircuitOpen('cerebras')) {
|
| 24 |
-
throw new Error('Cerebras circuit open — too many recent failures')
|
| 25 |
-
}
|
| 26 |
-
|
| 27 |
-
let lastError: Error | null = null
|
| 28 |
-
|
| 29 |
-
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
| 30 |
-
try {
|
| 31 |
-
const start = Date.now()
|
| 32 |
-
const response = await cerebras.chat.completions.create({
|
| 33 |
-
model: process.env.CLOUD_MODEL || 'llama-3.3-70b',
|
| 34 |
-
messages,
|
| 35 |
-
max_tokens: 4000
|
| 36 |
-
})
|
| 37 |
-
const ms = Date.now() - start
|
| 38 |
-
|
| 39 |
-
recordSuccess('cerebras')
|
| 40 |
-
|
| 41 |
-
logger.info('cerebras_success', { attempt }, ms)
|
| 42 |
-
|
| 43 |
-
const result = response as CerebrasResponse
|
| 44 |
-
return result.choices[0]?.message?.content || ''
|
| 45 |
-
} catch (err: any) {
|
| 46 |
-
lastError = err
|
| 47 |
-
recordFailure('cerebras')
|
| 48 |
-
logger.warn('cerebras_attempt_failed', {
|
| 49 |
-
attempt,
|
| 50 |
-
status: err.status,
|
| 51 |
-
error: err.message
|
| 52 |
-
})
|
| 53 |
-
|
| 54 |
-
// Don't retry on rate limit — wait longer
|
| 55 |
-
if (err.status === 429) {
|
| 56 |
-
logger.warn('cerebras_rate_limited', { waitMs: attempt * 2000 })
|
| 57 |
-
await new Promise(r => setTimeout(r, attempt * 2000))
|
| 58 |
-
} else if (attempt < MAX_RETRIES) {
|
| 59 |
-
await new Promise(r => setTimeout(r, attempt * 1000))
|
| 60 |
-
}
|
| 61 |
-
}
|
| 62 |
-
}
|
| 63 |
-
|
| 64 |
-
throw new Error(`Cloud model unavailable: ${lastError?.message}`)
|
| 65 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/index.ts
DELETED
|
@@ -1,19 +0,0 @@
|
|
| 1 |
-
import { route } from "./router"
|
| 2 |
-
|
| 3 |
-
async function main() {
|
| 4 |
-
const result1 = await route([{ role: 'user', content: "This is my email yagon.nan@gmail.com" }], 'smart-router')
|
| 5 |
-
const result2 = await route([{ role: 'user', content: "What is lite llm" }], 'smart-router')
|
| 6 |
-
|
| 7 |
-
console.log('Model used:', result1.usedModel)
|
| 8 |
-
console.log('PII detected:', result1.piiDetected)
|
| 9 |
-
console.log('PII types:', result1.piiTypes)
|
| 10 |
-
console.log('Response:', result1.response)
|
| 11 |
-
|
| 12 |
-
console.log('Model used:', result2.usedModel)
|
| 13 |
-
console.log('PII detected:', result2.piiDetected)
|
| 14 |
-
console.log('PII types:', result2.piiTypes)
|
| 15 |
-
console.log('Response:', result2.response)
|
| 16 |
-
|
| 17 |
-
}
|
| 18 |
-
|
| 19 |
-
// main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/logger.ts
DELETED
|
@@ -1,26 +0,0 @@
|
|
| 1 |
-
type LogLevel = 'info' | 'warn' | 'error'
|
| 2 |
-
|
| 3 |
-
interface LogEntry {
|
| 4 |
-
timestamp: string
|
| 5 |
-
level: LogLevel
|
| 6 |
-
event: string
|
| 7 |
-
data?: Record<string, unknown>
|
| 8 |
-
durationMs?: number
|
| 9 |
-
}
|
| 10 |
-
|
| 11 |
-
function log(level: LogLevel, event: string, data?: Record<string, unknown>, durationMs?: number) {
|
| 12 |
-
const entry: LogEntry = {
|
| 13 |
-
timestamp: new Date().toISOString(),
|
| 14 |
-
level,
|
| 15 |
-
event,
|
| 16 |
-
...(data && { data }),
|
| 17 |
-
...(durationMs !== undefined && { durationMs })
|
| 18 |
-
}
|
| 19 |
-
console.log(JSON.stringify(entry))
|
| 20 |
-
}
|
| 21 |
-
|
| 22 |
-
export const logger = {
|
| 23 |
-
info: (event: string, data?: Record<string, unknown>, ms?: number) => log('info', event, data, ms),
|
| 24 |
-
warn: (event: string, data?: Record<string, unknown>, ms?: number) => log('warn', event, data, ms),
|
| 25 |
-
error: (event: string, data?: Record<string, unknown>, ms?: number) => log('error', event, data, ms)
|
| 26 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/middleware/authMiddleware.ts
DELETED
|
@@ -1,13 +0,0 @@
|
|
| 1 |
-
import { Request, Response, NextFunction, RequestHandler } from 'express'
|
| 2 |
-
|
| 3 |
-
export const authMiddleware = (req: Request, res: Response, next: NextFunction) => {
|
| 4 |
-
if (req.path === 'health') return next()
|
| 5 |
-
|
| 6 |
-
const key = req.headers['x-internal-key'] as string
|
| 7 |
-
const bearerKey = (req.headers['authorization'] as string)?.replace('Bearer', '').trim()
|
| 8 |
-
const expected = process.env.INTERNAL_SECRET
|
| 9 |
-
if (expected && key !== expected && bearerKey !== expected) {
|
| 10 |
-
return res.status(401).json({ error: 'Unauthorized' })
|
| 11 |
-
}
|
| 12 |
-
next()
|
| 13 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/ollama-client.ts
DELETED
|
@@ -1,58 +0,0 @@
|
|
| 1 |
-
import { Ollama } from 'ollama'
|
| 2 |
-
import { recordSuccess, recordFailure, isCircuitOpen } from './circuit-breaker'
|
| 3 |
-
import { logger } from './logger'
|
| 4 |
-
|
| 5 |
-
const ollama = new Ollama({ host: process.env.OLLAMA_HOST || 'http://localhost:11434' })
|
| 6 |
-
const TIMEOUT_MS = 30000
|
| 7 |
-
const MAX_RETRIES = 2
|
| 8 |
-
|
| 9 |
-
export type SimpleMessage = { role: 'user' | 'assistant' | 'system'; content: string }
|
| 10 |
-
|
| 11 |
-
async function attemptOllama(messages: SimpleMessage[]): Promise<string> {
|
| 12 |
-
const controller = new AbortController()
|
| 13 |
-
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS)
|
| 14 |
-
|
| 15 |
-
try {
|
| 16 |
-
const response = await ollama.chat({
|
| 17 |
-
model: process.env.OLLAMA_MODEL || 'qwen2.5:0.5b',
|
| 18 |
-
messages,
|
| 19 |
-
})
|
| 20 |
-
clearTimeout(timer)
|
| 21 |
-
return response.message.content
|
| 22 |
-
} catch (err) {
|
| 23 |
-
clearTimeout(timer)
|
| 24 |
-
throw err
|
| 25 |
-
}
|
| 26 |
-
}
|
| 27 |
-
|
| 28 |
-
export async function queryLocal(messages: SimpleMessage[]): Promise<string> {
|
| 29 |
-
if (isCircuitOpen('ollama')) {
|
| 30 |
-
throw new Error('Ollama circuit open — too many recent failures')
|
| 31 |
-
}
|
| 32 |
-
|
| 33 |
-
let lastError: Error | null = null
|
| 34 |
-
|
| 35 |
-
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
| 36 |
-
try {
|
| 37 |
-
const start = Date.now()
|
| 38 |
-
const result = await attemptOllama(messages)
|
| 39 |
-
const ms = Date.now() - start
|
| 40 |
-
|
| 41 |
-
recordSuccess('ollama')
|
| 42 |
-
logger.info('ollama_success', { attempt, model: process.env.OLLAMA_MODEL }, ms)
|
| 43 |
-
return result
|
| 44 |
-
|
| 45 |
-
} catch (err: any) {
|
| 46 |
-
lastError = err
|
| 47 |
-
recordFailure('ollama')
|
| 48 |
-
logger.warn('ollama_attempt_failed', { attempt, error: err.message })
|
| 49 |
-
|
| 50 |
-
if (attempt < MAX_RETRIES) {
|
| 51 |
-
// Wait before retry — exponential backoff
|
| 52 |
-
await new Promise(r => setTimeout(r, attempt * 1000))
|
| 53 |
-
}
|
| 54 |
-
}
|
| 55 |
-
}
|
| 56 |
-
|
| 57 |
-
throw new Error(`Local model unavailable: ${lastError?.message}`)
|
| 58 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/pii-scanner.test.ts
DELETED
|
@@ -1,53 +0,0 @@
|
|
| 1 |
-
import { scanForPII } from './pii-scanner'
|
| 2 |
-
|
| 3 |
-
const run = (label: string, pass: boolean) =>
|
| 4 |
-
console.log(`${pass ? '✅' : '❌'} ${label}`)
|
| 5 |
-
|
| 6 |
-
// --- EMAIL ---
|
| 7 |
-
const emailResult = scanForPII('Contact me at john.doe@gmail.com please')
|
| 8 |
-
run('EMAIL: hasPII is true', emailResult.hasPII === true)
|
| 9 |
-
run('EMAIL: types contains EMAIL', emailResult.types.includes('EMAIL'))
|
| 10 |
-
run('EMAIL: address is redacted', emailResult.redacted.includes('[EMAIL]'))
|
| 11 |
-
run('EMAIL: original not in redacted', !emailResult.redacted.includes('john.doe@gmail.com'))
|
| 12 |
-
|
| 13 |
-
// --- PHONE ---
|
| 14 |
-
const phoneResult = scanForPII('Call me at 415-555-1234 anytime')
|
| 15 |
-
run('PHONE: hasPII is true', phoneResult.hasPII === true)
|
| 16 |
-
run('PHONE: types contains PHONE', phoneResult.types.includes('PHONE'))
|
| 17 |
-
run('PHONE: number is redacted', phoneResult.redacted.includes('[PHONE]'))
|
| 18 |
-
|
| 19 |
-
// --- SSN ---
|
| 20 |
-
const ssnResult = scanForPII('My SSN is 123-45-6789')
|
| 21 |
-
run('SSN: hasPII is true', ssnResult.hasPII === true)
|
| 22 |
-
run('SSN: types contains SSN', ssnResult.types.includes('SSN'))
|
| 23 |
-
run('SSN: number is redacted', ssnResult.redacted.includes('[SSN]'))
|
| 24 |
-
|
| 25 |
-
// --- CREDIT CARD ---
|
| 26 |
-
const ccResult = scanForPII('Card number 4111 1111 1111 1111 expires soon')
|
| 27 |
-
run('CREDIT_CARD: hasPII is true', ccResult.hasPII === true)
|
| 28 |
-
run('CREDIT_CARD: type detected', ccResult.types.includes('CREDIT_CARD'))
|
| 29 |
-
run('CREDIT_CARD: number redacted', ccResult.redacted.includes('[CREDIT_CARD]'))
|
| 30 |
-
|
| 31 |
-
// --- IP ADDRESS ---
|
| 32 |
-
const ipResult = scanForPII('Server IP is 192.168.1.100')
|
| 33 |
-
run('IP_ADDRESS: hasPII is true', ipResult.hasPII === true)
|
| 34 |
-
run('IP_ADDRESS: type detected', ipResult.types.includes('IP_ADDRESS'))
|
| 35 |
-
run('IP_ADDRESS: address redacted', ipResult.redacted.includes('[IP_ADDRESS]'))
|
| 36 |
-
|
| 37 |
-
// --- MULTIPLE PII TYPES ---
|
| 38 |
-
const multiResult = scanForPII('Email: jane@example.com, SSN: 987-65-4321')
|
| 39 |
-
run('MULTI: hasPII is true', multiResult.hasPII === true)
|
| 40 |
-
run('MULTI: detects EMAIL', multiResult.types.includes('EMAIL'))
|
| 41 |
-
run('MULTI: detects SSN', multiResult.types.includes('SSN'))
|
| 42 |
-
run('MULTI: both redacted', multiResult.redacted.includes('[EMAIL]') && multiResult.redacted.includes('[SSN]'))
|
| 43 |
-
|
| 44 |
-
// --- CLEAN TEXT (no PII) ---
|
| 45 |
-
const cleanResult = scanForPII('The weather today is sunny and warm')
|
| 46 |
-
run('CLEAN: hasPII is false', cleanResult.hasPII === false)
|
| 47 |
-
run('CLEAN: types array is empty', cleanResult.types.length === 0)
|
| 48 |
-
run('CLEAN: redacted equals original', cleanResult.redacted === 'The weather today is sunny and warm')
|
| 49 |
-
|
| 50 |
-
// --- EMPTY STRING ---
|
| 51 |
-
const emptyResult = scanForPII('')
|
| 52 |
-
run('EMPTY: hasPII is false', emptyResult.hasPII === false)
|
| 53 |
-
run('EMPTY: types is empty array', emptyResult.types.length === 0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/pii-scanner.ts
DELETED
|
@@ -1,36 +0,0 @@
|
|
| 1 |
-
export interface PIIScanResult {
|
| 2 |
-
hasPII: boolean
|
| 3 |
-
types: string[]
|
| 4 |
-
redacted: string
|
| 5 |
-
}
|
| 6 |
-
const arrPIIScans = [
|
| 7 |
-
{ type: 'EMAIL', pattern: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g },
|
| 8 |
-
{ type: 'CREDIT_CARD', pattern: /\b(?:\d{4}[-\s]?){3}\d{4}\b/g },
|
| 9 |
-
{ type: 'PHONE', pattern: /(\+?1[-.\s]?)?(\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}/g },
|
| 10 |
-
{ type: 'SSN', pattern: /\b\d{3}-\d{2}-\d{4}\b/g },
|
| 11 |
-
{ type: 'IP_ADDRESS', pattern: /\b(?:\d{1,3}\.){3}\d{1,3}\b/g },
|
| 12 |
-
{ type: 'PASSPORT', pattern: /\b[A-Z]{1,2}\d{6,9}\b/g },
|
| 13 |
-
{ type: 'DATE_OF_BIRTH', pattern: /\b(0?[1-9]|1[0-2])[\/\-](0?[1-9]|[12]\d|3[01])[\/\-](\d{2}|\d{4})\b/g },
|
| 14 |
-
{ type: 'IBAN', pattern: /\b[A-Z]{2}\d{2}[A-Z0-9]{4}\d{7}([A-Z0-9]?){0,16}\b/g },
|
| 15 |
-
{ type: 'MAC_ADDRESS', pattern: /\b([0-9A-Fa-f]{2}[:\-]){5}[0-9A-Fa-f]{2}\b/g },
|
| 16 |
-
]
|
| 17 |
-
|
| 18 |
-
export function scanForPII(text: string): PIIScanResult {
|
| 19 |
-
const PIIScanLists = new Set<string>()
|
| 20 |
-
let redacted = text
|
| 21 |
-
|
| 22 |
-
for (const arrPIIScan of arrPIIScans) {
|
| 23 |
-
arrPIIScan.pattern.lastIndex = 0
|
| 24 |
-
if (redacted.match(arrPIIScan.pattern)) {
|
| 25 |
-
PIIScanLists.add(arrPIIScan.type)
|
| 26 |
-
redacted = redacted.replace(arrPIIScan.pattern, `[${arrPIIScan.type}]`)
|
| 27 |
-
}
|
| 28 |
-
}
|
| 29 |
-
|
| 30 |
-
return {
|
| 31 |
-
hasPII: PIIScanLists.size > 0,
|
| 32 |
-
types: Array.from(PIIScanLists),
|
| 33 |
-
redacted
|
| 34 |
-
}
|
| 35 |
-
}
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/providers/base.ts
DELETED
|
@@ -1,33 +0,0 @@
|
|
| 1 |
-
export type MessageRole = 'user' | 'assistant' | 'system'
|
| 2 |
-
|
| 3 |
-
export interface SimpleMessage {
|
| 4 |
-
role: MessageRole
|
| 5 |
-
content: string
|
| 6 |
-
}
|
| 7 |
-
|
| 8 |
-
export interface CompletionInput {
|
| 9 |
-
messages: SimpleMessage[]
|
| 10 |
-
maxTokens?: number
|
| 11 |
-
temperature?: number
|
| 12 |
-
/**
|
| 13 |
-
* Optional text to pre-fill the assistant's reply.
|
| 14 |
-
* Claude supports this natively; other providers ignore it.
|
| 15 |
-
*/
|
| 16 |
-
prefill?: string
|
| 17 |
-
}
|
| 18 |
-
|
| 19 |
-
export interface CompletionOutput {
|
| 20 |
-
content: string
|
| 21 |
-
/** Actual model identifier returned by the provider */
|
| 22 |
-
model: string
|
| 23 |
-
inputTokens: number
|
| 24 |
-
outputTokens: number
|
| 25 |
-
/** Total cost in USD for this call */
|
| 26 |
-
costUsd: number
|
| 27 |
-
durationMs: number
|
| 28 |
-
}
|
| 29 |
-
|
| 30 |
-
export interface LLMProvider {
|
| 31 |
-
readonly name: string
|
| 32 |
-
complete(input: CompletionInput): Promise<CompletionOutput>
|
| 33 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/providers/cerebras.ts
DELETED
|
@@ -1,103 +0,0 @@
|
|
| 1 |
-
import Cerebras from '@cerebras/cerebras_cloud_sdk'
|
| 2 |
-
import { isCircuitOpen, recordSuccess, recordFailure } from '../circuit-breaker'
|
| 3 |
-
import { logger } from '../logger'
|
| 4 |
-
import type { LLMProvider, CompletionInput, CompletionOutput } from './base'
|
| 5 |
-
|
| 6 |
-
const MAX_RETRIES = 2
|
| 7 |
-
|
| 8 |
-
// Approximate Cerebras pricing per million tokens (as of 2026)
|
| 9 |
-
const PRICING: Record<string, { input: number; output: number }> = {
|
| 10 |
-
'llama-3.3-70b': { input: 0.85, output: 1.20 },
|
| 11 |
-
'llama-3.1-8b': { input: 0.10, output: 0.10 },
|
| 12 |
-
}
|
| 13 |
-
const DEFAULT_PRICING = { input: 0.85, output: 1.20 }
|
| 14 |
-
|
| 15 |
-
// Matches SimpleMessage but typed as the discriminated union the Cerebras SDK requires
|
| 16 |
-
type CerebrasMessage =
|
| 17 |
-
| { role: 'system'; content: string }
|
| 18 |
-
| { role: 'user'; content: string }
|
| 19 |
-
| { role: 'assistant'; content: string }
|
| 20 |
-
|
| 21 |
-
interface CerebrasChoice {
|
| 22 |
-
message: { content: string; role: string }
|
| 23 |
-
finish_reason: string
|
| 24 |
-
}
|
| 25 |
-
|
| 26 |
-
interface CerebrasCompletion {
|
| 27 |
-
model: string
|
| 28 |
-
choices: CerebrasChoice[]
|
| 29 |
-
usage?: { prompt_tokens: number; completion_tokens: number }
|
| 30 |
-
}
|
| 31 |
-
|
| 32 |
-
function calcCostUsd(inputTokens: number, outputTokens: number, model: string): number {
|
| 33 |
-
const rates = PRICING[model] ?? DEFAULT_PRICING
|
| 34 |
-
return (inputTokens * rates.input + outputTokens * rates.output) / 1_000_000
|
| 35 |
-
}
|
| 36 |
-
|
| 37 |
-
export class CerebrasProvider implements LLMProvider {
|
| 38 |
-
readonly name = 'cerebras'
|
| 39 |
-
|
| 40 |
-
private readonly client: Cerebras
|
| 41 |
-
private readonly model: string
|
| 42 |
-
|
| 43 |
-
constructor() {
|
| 44 |
-
this.client = new Cerebras({ apiKey: process.env.CEREBRAS_API_KEY ?? '' })
|
| 45 |
-
this.model = process.env.CLOUD_MODEL ?? 'llama-3.3-70b'
|
| 46 |
-
}
|
| 47 |
-
|
| 48 |
-
async complete(input: CompletionInput): Promise<CompletionOutput> {
|
| 49 |
-
if (!process.env.CEREBRAS_API_KEY) {
|
| 50 |
-
throw new Error('CEREBRAS_API_KEY is not set')
|
| 51 |
-
}
|
| 52 |
-
if (isCircuitOpen('cerebras')) {
|
| 53 |
-
throw new Error('Cerebras circuit open — too many recent failures')
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
let lastError: Error | null = null
|
| 57 |
-
|
| 58 |
-
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
| 59 |
-
try {
|
| 60 |
-
const start = Date.now()
|
| 61 |
-
const raw = await this.client.chat.completions.create({
|
| 62 |
-
model: this.model,
|
| 63 |
-
messages: input.messages as CerebrasMessage[],
|
| 64 |
-
max_tokens: input.maxTokens ?? 4000,
|
| 65 |
-
...(input.temperature !== undefined && { temperature: input.temperature }),
|
| 66 |
-
})
|
| 67 |
-
const durationMs = Date.now() - start
|
| 68 |
-
|
| 69 |
-
recordSuccess('cerebras')
|
| 70 |
-
logger.info('cerebras_success', { attempt }, durationMs)
|
| 71 |
-
|
| 72 |
-
const res = raw as CerebrasCompletion
|
| 73 |
-
const content = res.choices[0]?.message?.content ?? ''
|
| 74 |
-
const inputTokens = res.usage?.prompt_tokens ?? 0
|
| 75 |
-
const outputTokens = res.usage?.completion_tokens ?? 0
|
| 76 |
-
|
| 77 |
-
return {
|
| 78 |
-
content,
|
| 79 |
-
model: res.model,
|
| 80 |
-
inputTokens,
|
| 81 |
-
outputTokens,
|
| 82 |
-
costUsd: calcCostUsd(inputTokens, outputTokens, res.model),
|
| 83 |
-
durationMs,
|
| 84 |
-
}
|
| 85 |
-
} catch (err: unknown) {
|
| 86 |
-
const e = err as { message?: string; status?: number }
|
| 87 |
-
lastError = new Error(e.message ?? 'unknown error')
|
| 88 |
-
recordFailure('cerebras')
|
| 89 |
-
logger.warn('cerebras_attempt_failed', { attempt, status: e.status, error: e.message })
|
| 90 |
-
|
| 91 |
-
if (e.status === 429) {
|
| 92 |
-
await new Promise(r => setTimeout(r, attempt * 2000))
|
| 93 |
-
} else if (attempt < MAX_RETRIES) {
|
| 94 |
-
await new Promise(r => setTimeout(r, attempt * 1000))
|
| 95 |
-
}
|
| 96 |
-
}
|
| 97 |
-
}
|
| 98 |
-
|
| 99 |
-
throw new Error(`Cerebras unavailable: ${lastError?.message}`)
|
| 100 |
-
}
|
| 101 |
-
}
|
| 102 |
-
|
| 103 |
-
export const cerebrasProvider = new CerebrasProvider()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/providers/ollama.ts
DELETED
|
@@ -1,80 +0,0 @@
|
|
| 1 |
-
import { Ollama } from 'ollama'
|
| 2 |
-
import { isCircuitOpen, recordSuccess, recordFailure } from '../circuit-breaker'
|
| 3 |
-
import { logger } from '../logger'
|
| 4 |
-
import type { LLMProvider, CompletionInput, CompletionOutput } from './base'
|
| 5 |
-
|
| 6 |
-
const TIMEOUT_MS = 30_000
|
| 7 |
-
const MAX_RETRIES = 2
|
| 8 |
-
|
| 9 |
-
export class OllamaProvider implements LLMProvider {
|
| 10 |
-
readonly name = 'ollama'
|
| 11 |
-
|
| 12 |
-
private readonly client: Ollama
|
| 13 |
-
private readonly model: string
|
| 14 |
-
|
| 15 |
-
constructor() {
|
| 16 |
-
this.client = new Ollama({ host: process.env.OLLAMA_HOST ?? 'http://localhost:11434' })
|
| 17 |
-
this.model = process.env.OLLAMA_MODEL ?? 'qwen2.5:0.5b'
|
| 18 |
-
}
|
| 19 |
-
|
| 20 |
-
private async attempt(input: CompletionInput): Promise<CompletionOutput> {
|
| 21 |
-
const controller = new AbortController()
|
| 22 |
-
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS)
|
| 23 |
-
const start = Date.now()
|
| 24 |
-
|
| 25 |
-
try {
|
| 26 |
-
const options: Record<string, number> = {}
|
| 27 |
-
if (input.maxTokens !== undefined) options['num_predict'] = input.maxTokens
|
| 28 |
-
if (input.temperature !== undefined) options['temperature'] = input.temperature
|
| 29 |
-
|
| 30 |
-
const response = await this.client.chat({
|
| 31 |
-
model: this.model,
|
| 32 |
-
messages: input.messages,
|
| 33 |
-
...(Object.keys(options).length > 0 && { options }),
|
| 34 |
-
})
|
| 35 |
-
clearTimeout(timer)
|
| 36 |
-
|
| 37 |
-
return {
|
| 38 |
-
content: response.message.content,
|
| 39 |
-
model: this.model,
|
| 40 |
-
inputTokens: response.prompt_eval_count ?? 0,
|
| 41 |
-
outputTokens: response.eval_count ?? 0,
|
| 42 |
-
costUsd: 0, // local model — no API cost
|
| 43 |
-
durationMs: Date.now() - start,
|
| 44 |
-
}
|
| 45 |
-
} catch (err) {
|
| 46 |
-
clearTimeout(timer)
|
| 47 |
-
throw err
|
| 48 |
-
}
|
| 49 |
-
}
|
| 50 |
-
|
| 51 |
-
async complete(input: CompletionInput): Promise<CompletionOutput> {
|
| 52 |
-
if (isCircuitOpen('ollama')) {
|
| 53 |
-
throw new Error('Ollama circuit open — too many recent failures')
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
let lastError: Error | null = null
|
| 57 |
-
|
| 58 |
-
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
| 59 |
-
try {
|
| 60 |
-
const result = await this.attempt(input)
|
| 61 |
-
recordSuccess('ollama')
|
| 62 |
-
logger.info('ollama_success', { attempt, model: this.model }, result.durationMs)
|
| 63 |
-
return result
|
| 64 |
-
} catch (err: unknown) {
|
| 65 |
-
const e = err as Error
|
| 66 |
-
lastError = e
|
| 67 |
-
recordFailure('ollama')
|
| 68 |
-
logger.warn('ollama_attempt_failed', { attempt, error: e.message })
|
| 69 |
-
|
| 70 |
-
if (attempt < MAX_RETRIES) {
|
| 71 |
-
await new Promise(r => setTimeout(r, attempt * 1000))
|
| 72 |
-
}
|
| 73 |
-
}
|
| 74 |
-
}
|
| 75 |
-
|
| 76 |
-
throw new Error(`Ollama unavailable: ${lastError?.message}`)
|
| 77 |
-
}
|
| 78 |
-
}
|
| 79 |
-
|
| 80 |
-
export const ollamaProvider = new OllamaProvider()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/proxy.ts
DELETED
|
@@ -1,421 +0,0 @@
|
|
| 1 |
-
import 'dotenv/config'
|
| 2 |
-
import express from 'express'
|
| 3 |
-
import { route } from './router'
|
| 4 |
-
import { authMiddleware } from './middleware/authMiddleware'
|
| 5 |
-
|
| 6 |
-
const app = express()
|
| 7 |
-
|
| 8 |
-
console.log('[startup] OLLAMA_HOST:', process.env.OLLAMA_HOST || 'MISSING')
|
| 9 |
-
console.log('[startup] CEREBRAS_API_KEY:', process.env.CEREBRAS_API_KEY ? 'SET' : 'MISSING')
|
| 10 |
-
console.log('[startup] INTERNAL_SECRET:', process.env.INTERNAL_SECRET ? 'SET' : 'MISSING')
|
| 11 |
-
console.log('[startup] N8N_WEBHOOK_URL:', process.env.N8N_WEBHOOK_URL ? 'SET' : 'MISSING')
|
| 12 |
-
|
| 13 |
-
const models = {
|
| 14 |
-
qwen: 'local/qwen2.5:3b',
|
| 15 |
-
cloud: 'llama-3.3-70b'
|
| 16 |
-
}
|
| 17 |
-
|
| 18 |
-
// ─── BODY PARSERS ─────────────────────────────────────────
|
| 19 |
-
app.use(express.json({ limit: '50mb' }))
|
| 20 |
-
app.use(express.urlencoded({ limit: '50mb', extended: true }))
|
| 21 |
-
app.use(express.raw({ limit: '50mb', type: ['image/*', 'application/octet-stream'] }))
|
| 22 |
-
app.use(authMiddleware)
|
| 23 |
-
|
| 24 |
-
// ─── CORS ─────────────────────────────────────────────────
|
| 25 |
-
app.use((req, res, next) => {
|
| 26 |
-
res.setHeader('Access-Control-Allow-Origin', '*')
|
| 27 |
-
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
|
| 28 |
-
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, x-internal-key')
|
| 29 |
-
if (req.method === 'OPTIONS') { res.sendStatus(204); return }
|
| 30 |
-
next()
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
// ─── HELPERS ──────────────────────────────────────────────
|
| 34 |
-
async function extractTextFromImage(base64Image: string): Promise<string> {
|
| 35 |
-
try {
|
| 36 |
-
const Tesseract = await import('tesseract.js')
|
| 37 |
-
const cleanBase64 = base64Image.replace(/^data:image\/\w+;base64,/, '')
|
| 38 |
-
const imageBuffer = Buffer.from(cleanBase64, 'base64')
|
| 39 |
-
|
| 40 |
-
console.log('[ocr] starting Tesseract OCR...')
|
| 41 |
-
const result = await Tesseract.default.recognize(imageBuffer, 'tha+eng', {
|
| 42 |
-
logger: (m: any) => {
|
| 43 |
-
if (m.status === 'recognizing text') {
|
| 44 |
-
console.log(`[ocr] progress: ${Math.round(m.progress * 100)}%`)
|
| 45 |
-
}
|
| 46 |
-
}
|
| 47 |
-
})
|
| 48 |
-
|
| 49 |
-
const text = result.data.text.trim()
|
| 50 |
-
console.log('[ocr] extracted text:', text.substring(0, 200))
|
| 51 |
-
return text
|
| 52 |
-
|
| 53 |
-
} catch (err: any) {
|
| 54 |
-
console.error('[ocr] failed:', err.message)
|
| 55 |
-
throw new Error(
|
| 56 |
-
'Image OCR failed. Please type your expense as text instead. ' +
|
| 57 |
-
'Example: "Grab food 350 baht today"'
|
| 58 |
-
)
|
| 59 |
-
}
|
| 60 |
-
}
|
| 61 |
-
|
| 62 |
-
async function triggerN8N(expense: any, source: string, rawText: string): Promise<void> {
|
| 63 |
-
const webhookUrl = process.env.N8N_WEBHOOK_URL
|
| 64 |
-
if (!webhookUrl) return
|
| 65 |
-
|
| 66 |
-
try {
|
| 67 |
-
await fetch(webhookUrl, {
|
| 68 |
-
method: 'POST',
|
| 69 |
-
headers: { 'Content-Type': 'application/json' },
|
| 70 |
-
body: JSON.stringify({
|
| 71 |
-
text: rawText,
|
| 72 |
-
expense,
|
| 73 |
-
source
|
| 74 |
-
}),
|
| 75 |
-
signal: AbortSignal.timeout(10000)
|
| 76 |
-
})
|
| 77 |
-
console.log('[n8n] workflow triggered successfully')
|
| 78 |
-
} catch (err: any) {
|
| 79 |
-
console.warn('[n8n] trigger failed (non-blocking):', err.message)
|
| 80 |
-
}
|
| 81 |
-
}
|
| 82 |
-
|
| 83 |
-
function formatExpenseMessage(expense: any, saved: boolean): string {
|
| 84 |
-
const categoryEmoji: Record<string, string> = {
|
| 85 |
-
food: '🍔', transport: '🚗', shopping: '🛍️',
|
| 86 |
-
bills: '📱', rental_electricity: '🏠', gym: '🏋️',
|
| 87 |
-
health: '💊', transfer: '💝', emergency: '🚨',
|
| 88 |
-
pet: '🐾', maid: '🧹', entertainment: '🎬',
|
| 89 |
-
su_personal: '👤', tz_personal: '👤', other: '📦'
|
| 90 |
-
}
|
| 91 |
-
const emoji = categoryEmoji[expense.category] || '📦'
|
| 92 |
-
|
| 93 |
-
return `${emoji} **Expense Recorded!**
|
| 94 |
-
|
| 95 |
-
| Field | Value |
|
| 96 |
-
|-------|-------|
|
| 97 |
-
| Amount | ฿${expense.amount.toLocaleString()} |
|
| 98 |
-
| Category | ${expense.category} |
|
| 99 |
-
| Merchant | ${expense.merchant || 'Unknown'} |
|
| 100 |
-
| Date | ${expense.date} |
|
| 101 |
-
| Confidence | ${Math.round((expense.confidence || 0) * 100)}% |
|
| 102 |
-
|
| 103 |
-
${saved ? '✅ Automatically saved to your expense tracker!' : '⚠️ Auto-save not configured.'}`
|
| 104 |
-
}
|
| 105 |
-
|
| 106 |
-
// ─── ROUTES ───────────────────────────────────────────────
|
| 107 |
-
app.get('/v1/openapi.json', (_req, res) => {
|
| 108 |
-
return res.json({ openapi: '3.0.0', info: { title: 'LLM Router', version: '1.0.0' }, paths: {} })
|
| 109 |
-
})
|
| 110 |
-
|
| 111 |
-
app.get('/v1/models', (_req, res) => {
|
| 112 |
-
return res.json({
|
| 113 |
-
object: 'list',
|
| 114 |
-
data: [
|
| 115 |
-
{ id: 'smart-router', object: 'model', owned_by: 'local' },
|
| 116 |
-
{ id: 'professor-ai', object: 'model', owned_by: 'local', description: 'Research + teach mode' },
|
| 117 |
-
{ id: 'code-assistant', object: 'model', owned_by: 'local', description: 'Coding specialist' },
|
| 118 |
-
{ id: 'expense-parser', object: 'model', owned_by: 'local', description: 'Parse expenses from text or image' }
|
| 119 |
-
]
|
| 120 |
-
})
|
| 121 |
-
})
|
| 122 |
-
|
| 123 |
-
app.get('/health', (_req, res) => {
|
| 124 |
-
const { getCircuitStatus } = require('./circuit-breaker')
|
| 125 |
-
res.json({
|
| 126 |
-
status: 'ok',
|
| 127 |
-
timestamp: new Date().toISOString(),
|
| 128 |
-
circuits: getCircuitStatus(),
|
| 129 |
-
n8nConfigured: !!process.env.N8N_WEBHOOK_URL
|
| 130 |
-
})
|
| 131 |
-
})
|
| 132 |
-
|
| 133 |
-
// ─── CHAT COMPLETIONS ─────────────────────────────────────
|
| 134 |
-
app.post('/v1/chat/completions', async (req, res) => {
|
| 135 |
-
try {
|
| 136 |
-
const { messages, stream, model } = req.body
|
| 137 |
-
|
| 138 |
-
if (!Array.isArray(messages) || messages.length === 0) {
|
| 139 |
-
return res.status(400).json({ error: 'messages must be a non-empty array' })
|
| 140 |
-
}
|
| 141 |
-
|
| 142 |
-
// ── Expense parser model — special handling ──────────
|
| 143 |
-
if (model === 'expense-parser') {
|
| 144 |
-
const lastMsg = messages[messages.length - 1]
|
| 145 |
-
let inputText = ''
|
| 146 |
-
|
| 147 |
-
// Handle image content
|
| 148 |
-
const hasImage = Array.isArray(lastMsg?.content) &&
|
| 149 |
-
lastMsg.content.some((c: any) => c.type === 'image_url')
|
| 150 |
-
|
| 151 |
-
if (hasImage) {
|
| 152 |
-
const imageContent = lastMsg.content.find((c: any) => c.type === 'image_url')
|
| 153 |
-
const imageUrl = imageContent?.image_url?.url || ''
|
| 154 |
-
console.log('[chat] image detected, running OCR...')
|
| 155 |
-
inputText = await extractTextFromImage(imageUrl)
|
| 156 |
-
} else {
|
| 157 |
-
// Plain text message
|
| 158 |
-
inputText = typeof lastMsg?.content === 'string'
|
| 159 |
-
? lastMsg.content
|
| 160 |
-
: lastMsg?.content?.[0]?.text || ''
|
| 161 |
-
}
|
| 162 |
-
|
| 163 |
-
if (!inputText) {
|
| 164 |
-
return res.json({
|
| 165 |
-
id: `chatcmpl-${Date.now()}`,
|
| 166 |
-
object: 'chat.completion',
|
| 167 |
-
model,
|
| 168 |
-
choices: [{
|
| 169 |
-
index: 0,
|
| 170 |
-
message: {
|
| 171 |
-
role: 'assistant',
|
| 172 |
-
content: 'Please describe your expense or upload a receipt image. Example: "Grab food 350 baht today"'
|
| 173 |
-
},
|
| 174 |
-
finish_reason: 'stop'
|
| 175 |
-
}]
|
| 176 |
-
})
|
| 177 |
-
}
|
| 178 |
-
|
| 179 |
-
// Parse the expense
|
| 180 |
-
const result = await route(
|
| 181 |
-
[{ role: 'user' as const, content: inputText }],
|
| 182 |
-
'expense-parser'
|
| 183 |
-
)
|
| 184 |
-
|
| 185 |
-
// Try to extract JSON from response
|
| 186 |
-
const jsonMatch = result.response.match(/\{[\s\S]*\}/)
|
| 187 |
-
if (jsonMatch) {
|
| 188 |
-
try {
|
| 189 |
-
const expense = JSON.parse(jsonMatch[0])
|
| 190 |
-
expense.amount = Number(expense.amount)
|
| 191 |
-
|
| 192 |
-
// Fix year if wrong
|
| 193 |
-
if (expense.date) {
|
| 194 |
-
const currentYear = new Date().getFullYear()
|
| 195 |
-
const parsedYear = parseInt(expense.date.split('-')[0])
|
| 196 |
-
if (parsedYear < currentYear - 1) {
|
| 197 |
-
expense.date = expense.date.replace(parsedYear.toString(), currentYear.toString())
|
| 198 |
-
}
|
| 199 |
-
}
|
| 200 |
-
|
| 201 |
-
if (!expense.date) {
|
| 202 |
-
expense.date = new Date().toISOString().split('T')[0]
|
| 203 |
-
}
|
| 204 |
-
|
| 205 |
-
// Auto-save via n8n (fire and forget)
|
| 206 |
-
const hasSave = !!process.env.N8N_WEBHOOK_URL && !!expense.amount
|
| 207 |
-
if (hasSave) {
|
| 208 |
-
triggerN8N(expense, 'openwebui', inputText)
|
| 209 |
-
}
|
| 210 |
-
|
| 211 |
-
// Return friendly formatted message
|
| 212 |
-
const friendlyMessage = formatExpenseMessage(expense, hasSave)
|
| 213 |
-
|
| 214 |
-
return res.json({
|
| 215 |
-
id: `chatcmpl-${Date.now()}`,
|
| 216 |
-
object: 'chat.completion',
|
| 217 |
-
model,
|
| 218 |
-
choices: [{
|
| 219 |
-
index: 0,
|
| 220 |
-
message: { role: 'assistant', content: friendlyMessage },
|
| 221 |
-
finish_reason: 'stop'
|
| 222 |
-
}]
|
| 223 |
-
})
|
| 224 |
-
} catch {
|
| 225 |
-
// JSON parse failed — return raw response
|
| 226 |
-
}
|
| 227 |
-
}
|
| 228 |
-
|
| 229 |
-
// Fallback — return raw response if JSON parsing failed
|
| 230 |
-
return res.json({
|
| 231 |
-
id: `chatcmpl-${Date.now()}`,
|
| 232 |
-
object: 'chat.completion',
|
| 233 |
-
model,
|
| 234 |
-
choices: [{
|
| 235 |
-
index: 0,
|
| 236 |
-
message: { role: 'assistant', content: result.response },
|
| 237 |
-
finish_reason: 'stop'
|
| 238 |
-
}]
|
| 239 |
-
})
|
| 240 |
-
}
|
| 241 |
-
|
| 242 |
-
// ── Standard routing for other models ───────────────
|
| 243 |
-
const response = await route(messages, model || 'smart-router')
|
| 244 |
-
const id = `chatcmpl-${Date.now()}`
|
| 245 |
-
const usedModel = response.usedModel === 'local' ? models.qwen : models.cloud
|
| 246 |
-
console.log(`[routed] → ${response.usedModel.toUpperCase()} (${usedModel}) | PII: ${response.piiDetected}`)
|
| 247 |
-
|
| 248 |
-
if (stream) {
|
| 249 |
-
res.setHeader('Content-Type', 'text/event-stream')
|
| 250 |
-
res.setHeader('Cache-Control', 'no-cache')
|
| 251 |
-
res.setHeader('Connection', 'keep-alive')
|
| 252 |
-
const chunk = {
|
| 253 |
-
id, object: 'chat.completion.chunk', model,
|
| 254 |
-
choices: [{ index: 0, delta: { role: 'assistant', content: response.response }, finish_reason: 'stop' }]
|
| 255 |
-
}
|
| 256 |
-
res.write(`data: ${JSON.stringify(chunk)}\n\n`)
|
| 257 |
-
res.write('data: [DONE]\n\n')
|
| 258 |
-
return res.end()
|
| 259 |
-
}
|
| 260 |
-
|
| 261 |
-
return res.json({
|
| 262 |
-
id,
|
| 263 |
-
object: 'chat.completion',
|
| 264 |
-
model,
|
| 265 |
-
choices: [{ index: 0, message: { role: 'assistant', content: response.response }, finish_reason: 'stop' }]
|
| 266 |
-
})
|
| 267 |
-
|
| 268 |
-
} catch (err) {
|
| 269 |
-
console.error('[proxy error]', JSON.stringify(err, Object.getOwnPropertyNames(err)))
|
| 270 |
-
return res.status(500).json({ error: 'Something went wrong! Please try again.' })
|
| 271 |
-
}
|
| 272 |
-
})
|
| 273 |
-
|
| 274 |
-
// ─── EXPENSE PARSE (direct API endpoint) ──────────────────
|
| 275 |
-
app.post('/v1/expense/parse', async (req, res) => {
|
| 276 |
-
try {
|
| 277 |
-
const reqBody = req.body || {}
|
| 278 |
-
|
| 279 |
-
// Fault tolerant — handles all nesting shapes from n8n/curl
|
| 280 |
-
const expenseText =
|
| 281 |
-
reqBody.text ||
|
| 282 |
-
reqBody?.body?.text ||
|
| 283 |
-
reqBody?.body?.body?.text ||
|
| 284 |
-
reqBody?.data?.text ||
|
| 285 |
-
reqBody?.message ||
|
| 286 |
-
reqBody?.content ||
|
| 287 |
-
(typeof reqBody === 'string' ? reqBody : null)
|
| 288 |
-
|
| 289 |
-
const imageBase64 =
|
| 290 |
-
reqBody.image ||
|
| 291 |
-
reqBody?.body?.image ||
|
| 292 |
-
reqBody?.imageBase64
|
| 293 |
-
|
| 294 |
-
console.log('[expense/parse] body keys:', Object.keys(reqBody))
|
| 295 |
-
console.log('[expense/parse] text:', expenseText?.substring(0, 100))
|
| 296 |
-
console.log('[expense/parse] has image:', !!imageBase64)
|
| 297 |
-
|
| 298 |
-
let finalText = expenseText
|
| 299 |
-
|
| 300 |
-
// OCR if image provided and no text
|
| 301 |
-
if (!finalText && imageBase64) {
|
| 302 |
-
console.log('[expense/parse] running OCR...')
|
| 303 |
-
finalText = await extractTextFromImage(imageBase64)
|
| 304 |
-
}
|
| 305 |
-
|
| 306 |
-
if (!finalText || typeof finalText !== 'string' || finalText.trim().length === 0) {
|
| 307 |
-
return res.status(400).json({
|
| 308 |
-
success: false,
|
| 309 |
-
error: 'Could not find text in request body',
|
| 310 |
-
receivedKeys: Object.keys(reqBody),
|
| 311 |
-
expectedFormats: [
|
| 312 |
-
'{ "text": "350 baht food" }',
|
| 313 |
-
'{ "body": { "text": "350 baht food" } }',
|
| 314 |
-
'{ "image": "base64encodedimage..." }'
|
| 315 |
-
]
|
| 316 |
-
})
|
| 317 |
-
}
|
| 318 |
-
|
| 319 |
-
const result = await route(
|
| 320 |
-
[{ role: 'user' as const, content: finalText }],
|
| 321 |
-
'expense-parser'
|
| 322 |
-
)
|
| 323 |
-
|
| 324 |
-
const rawResponse = result.response
|
| 325 |
-
const jsonMatch = rawResponse.match(/\{[\s\S]*\}/)
|
| 326 |
-
|
| 327 |
-
if (!jsonMatch) {
|
| 328 |
-
return res.status(422).json({
|
| 329 |
-
success: false,
|
| 330 |
-
error: 'Model did not return valid JSON',
|
| 331 |
-
raw: rawResponse
|
| 332 |
-
})
|
| 333 |
-
}
|
| 334 |
-
|
| 335 |
-
let expense
|
| 336 |
-
try {
|
| 337 |
-
expense = JSON.parse(jsonMatch[0])
|
| 338 |
-
} catch {
|
| 339 |
-
return res.status(422).json({
|
| 340 |
-
success: false,
|
| 341 |
-
error: 'Could not parse model response as JSON',
|
| 342 |
-
raw: rawResponse
|
| 343 |
-
})
|
| 344 |
-
}
|
| 345 |
-
|
| 346 |
-
if (!expense.amount || isNaN(Number(expense.amount))) {
|
| 347 |
-
return res.status(422).json({
|
| 348 |
-
success: false,
|
| 349 |
-
error: 'Could not extract a valid amount from text',
|
| 350 |
-
parsed: expense,
|
| 351 |
-
tip: 'Make sure the text includes a clear amount e.g. "350 baht" or "฿350"'
|
| 352 |
-
})
|
| 353 |
-
}
|
| 354 |
-
|
| 355 |
-
expense.amount = Number(expense.amount)
|
| 356 |
-
|
| 357 |
-
// Fix date
|
| 358 |
-
if (!expense.date) {
|
| 359 |
-
expense.date = new Date().toISOString().split('T')[0]
|
| 360 |
-
}
|
| 361 |
-
const currentYear = new Date().getFullYear()
|
| 362 |
-
if (expense.date) {
|
| 363 |
-
const parsedYear = parseInt(expense.date.split('-')[0])
|
| 364 |
-
if (parsedYear < currentYear - 1) {
|
| 365 |
-
expense.date = expense.date.replace(parsedYear.toString(), currentYear.toString())
|
| 366 |
-
console.log('[expense/parse] corrected year to:', expense.date)
|
| 367 |
-
}
|
| 368 |
-
}
|
| 369 |
-
|
| 370 |
-
if (!expense.category) expense.category = 'other'
|
| 371 |
-
|
| 372 |
-
console.log('[expense/parse] success:', {
|
| 373 |
-
amount: expense.amount,
|
| 374 |
-
category: expense.category,
|
| 375 |
-
merchant: expense.merchant,
|
| 376 |
-
date: expense.date,
|
| 377 |
-
confidence: expense.confidence
|
| 378 |
-
})
|
| 379 |
-
|
| 380 |
-
return res.json({
|
| 381 |
-
success: true,
|
| 382 |
-
expense,
|
| 383 |
-
usedModel: result.usedModel,
|
| 384 |
-
ocrUsed: !!imageBase64
|
| 385 |
-
})
|
| 386 |
-
|
| 387 |
-
} catch (err: any) {
|
| 388 |
-
console.error('[expense/parse] error:', err.message)
|
| 389 |
-
return res.status(500).json({
|
| 390 |
-
success: false,
|
| 391 |
-
error: err.message
|
| 392 |
-
})
|
| 393 |
-
}
|
| 394 |
-
})
|
| 395 |
-
|
| 396 |
-
// ─── KEEP ALIVE ───────────────────────────────────────────
|
| 397 |
-
const PORT = parseInt(process.env.PORT || '7860')
|
| 398 |
-
const FOUR_MINUTES = 4 * 60 * 1000
|
| 399 |
-
|
| 400 |
-
async function keepAlive() {
|
| 401 |
-
const services = [
|
| 402 |
-
`http://localhost:${PORT}/health`,
|
| 403 |
-
`${process.env.OLLAMA_HOST}/api/tags`
|
| 404 |
-
]
|
| 405 |
-
for (const url of services) {
|
| 406 |
-
try {
|
| 407 |
-
const pingRes = await fetch(url, {
|
| 408 |
-
headers: { 'x-internal-key': process.env.INTERNAL_SECRET || '' },
|
| 409 |
-
signal: AbortSignal.timeout(5000)
|
| 410 |
-
})
|
| 411 |
-
console.log('keepalive_ping', { url, status: pingRes.status })
|
| 412 |
-
} catch (err: any) {
|
| 413 |
-
console.warn('keepalive_failed', { url, error: err.message })
|
| 414 |
-
}
|
| 415 |
-
}
|
| 416 |
-
}
|
| 417 |
-
|
| 418 |
-
setInterval(keepAlive, FOUR_MINUTES)
|
| 419 |
-
keepAlive()
|
| 420 |
-
|
| 421 |
-
app.listen(PORT, '0.0.0.0', () => console.log(`Proxy running on port ${PORT}`))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/router.ts
DELETED
|
@@ -1,249 +0,0 @@
|
|
| 1 |
-
import { ollamaProvider } from './providers/ollama'
|
| 2 |
-
import { cerebrasProvider } from './providers/cerebras'
|
| 3 |
-
import { isCircuitOpen } from './circuit-breaker'
|
| 4 |
-
import { logger } from './logger'
|
| 5 |
-
import { searchWeb } from './websearch'
|
| 6 |
-
import { scanForPII } from './pii-scanner'
|
| 7 |
-
import type { SimpleMessage } from './providers/base'
|
| 8 |
-
|
| 9 |
-
const ALWAYS_LOCAL = ['cv', 'resume']
|
| 10 |
-
const ALWAYS_CLOUD = ['career_map', 'learning_path', 'expense-parser']
|
| 11 |
-
|
| 12 |
-
function scanAllMessages(messages: SimpleMessage[]): { hasPII: boolean; types: string[] } {
|
| 13 |
-
const allTypes = new Set<string>()
|
| 14 |
-
for (const m of messages) {
|
| 15 |
-
for (const t of scanForPII(m.content).types) allTypes.add(t)
|
| 16 |
-
}
|
| 17 |
-
return { hasPII: allTypes.size > 0, types: Array.from(allTypes) }
|
| 18 |
-
}
|
| 19 |
-
|
| 20 |
-
export interface RouterResult {
|
| 21 |
-
response: string
|
| 22 |
-
usedModel: 'local' | 'cloud' | 'fallback'
|
| 23 |
-
piiDetected: boolean
|
| 24 |
-
piiTypes?: string[]
|
| 25 |
-
}
|
| 26 |
-
|
| 27 |
-
export const EXPENSE_PARSE_PROMPT = `You are a precise expense parser for a personal finance tracker.
|
| 28 |
-
Extract structured data from bank slip, receipt, or expense note text.
|
| 29 |
-
|
| 30 |
-
Return ONLY valid JSON with no markdown, no explanation, no extra text:
|
| 31 |
-
{
|
| 32 |
-
"amount": <number or null>,
|
| 33 |
-
"currency": "THB",
|
| 34 |
-
"date": "<YYYY-MM-DD or null - use current year 2026 if year not specified>",
|
| 35 |
-
"merchant": "<merchant name or null>",
|
| 36 |
-
"category": "<see rules below>",
|
| 37 |
-
"confidence": <0.0 to 1.0>,
|
| 38 |
-
"raw_description": "<brief summary of original text>"
|
| 39 |
-
}
|
| 40 |
-
|
| 41 |
-
Category selection rules — pick the MOST specific match:
|
| 42 |
-
- food: restaurants, cafes, coffee shops, groceries, food delivery (GrabFood, FoodPanda)
|
| 43 |
-
- transport: Grab ride, taxi, BTS, MRT, fuel, parking, toll
|
| 44 |
-
- shopping: clothes, shoes, electronics, beauty, retail stores
|
| 45 |
-
- bills: phone top-up, internet, Netflix, Spotify, software subscriptions
|
| 46 |
-
- rental_electricity: rent payment, electricity bill, water bill, condo fee
|
| 47 |
-
- gym: fitness center, gym membership, yoga, sports classes
|
| 48 |
-
- health: pharmacy, hospital, clinic, doctor, dental, supplements
|
| 49 |
-
- transfer: money transfer to family, send money, โอนเงิน
|
| 50 |
-
- emergency: unexpected urgent expense, accident, repair
|
| 51 |
-
- pet: pet food, vet clinic, pet grooming, pet supplies
|
| 52 |
-
- maid: cleaning service, แม่บ้าน, housekeeping
|
| 53 |
-
- entertainment: cinema, concert, games, hobbies, travel
|
| 54 |
-
- su_personal: expense explicitly tagged for Su
|
| 55 |
-
- tz_personal: expense explicitly tagged for Tz
|
| 56 |
-
- other: anything that does not fit above categories
|
| 57 |
-
|
| 58 |
-
Critical rules:
|
| 59 |
-
- NEVER guess or fabricate an amount — if unclear set null
|
| 60 |
-
- If date not found use null (caller will use today's date)
|
| 61 |
-
- Set confidence based on how clear the text is (1.0 = crystal clear slip, 0.5 = rough note)
|
| 62 |
-
- For Thai text: handle Thai numerals and common Thai merchant names
|
| 63 |
-
- Extract amount as a plain number from the actual input text only
|
| 64 |
-
- Never use example numbers — only what is in the text
|
| 65 |
-
- Handle formats: "28,000 baht" → 28000, "฿1,200" → 1200, "28000 บาท" → 28000
|
| 66 |
-
- Remove commas and currency symbols"`
|
| 67 |
-
|
| 68 |
-
export async function route(
|
| 69 |
-
messages: SimpleMessage[],
|
| 70 |
-
model: string = 'smart-router',
|
| 71 |
-
feature?: string
|
| 72 |
-
): Promise<RouterResult> {
|
| 73 |
-
const start = Date.now()
|
| 74 |
-
|
| 75 |
-
const systemPrompts: Record<string, string> = {
|
| 76 |
-
'smart-router': `You are a smart, helpful assistant with broad expertise.
|
| 77 |
-
Response rules:
|
| 78 |
-
- Match length to complexity: short questions get concise answers
|
| 79 |
-
- Always use concrete examples over abstract explanations
|
| 80 |
-
- If uncertain say "I am not certain but..." never fabricate facts
|
| 81 |
-
- For code: always show working examples with inline comments
|
| 82 |
-
- Use markdown formatting with headers and code blocks when helpful`,
|
| 83 |
-
|
| 84 |
-
'expense-parser': EXPENSE_PARSE_PROMPT,
|
| 85 |
-
|
| 86 |
-
'professor-ai': `You are Professor AI — a world-class educator and personal mentor.
|
| 87 |
-
You have deep expertise in technology, programming, trading, finance, crypto, and computer science.
|
| 88 |
-
|
| 89 |
-
Teaching philosophy:
|
| 90 |
-
- Socratic method: guide with questions, not just answers
|
| 91 |
-
- Start with WHY before HOW
|
| 92 |
-
- Use real-world analogies for every abstract concept
|
| 93 |
-
- Check understanding before moving forward
|
| 94 |
-
- Never make the student feel inadequate
|
| 95 |
-
|
| 96 |
-
When student asks to learn a new topic:
|
| 97 |
-
STEP 1 — ASSESS: ask 2-3 questions about prior knowledge and goals
|
| 98 |
-
STEP 2 — PLAN: show a structured weekly curriculum with clear objectives
|
| 99 |
-
STEP 3 — TEACH: start Week 1 Lesson 1 immediately after the plan
|
| 100 |
-
STEP 4 — CHECK: end every lesson with a comprehension question and exercise
|
| 101 |
-
|
| 102 |
-
Lesson structure:
|
| 103 |
-
## Topic: [title]
|
| 104 |
-
**Objective:** [one sentence]
|
| 105 |
-
**Why this matters:** [real-world relevance]
|
| 106 |
-
[lesson content with examples and analogies]
|
| 107 |
-
**Key takeaway:** [one sentence]
|
| 108 |
-
**Exercise:** [concrete hands-on task]
|
| 109 |
-
**Check:** [comprehension question]
|
| 110 |
-
**Next:** [preview of next lesson]
|
| 111 |
-
|
| 112 |
-
Rules:
|
| 113 |
-
- Never skip the comprehension check
|
| 114 |
-
- Always recommend FREE resources with actual URLs
|
| 115 |
-
- For trading/crypto topics always include risk warnings
|
| 116 |
-
- Never give financial advice — educate only
|
| 117 |
-
- If asked about something current: note that web search results are used for up-to-date info
|
| 118 |
-
- Keep user credentials and prompts private
|
| 119 |
-
- Never suggest clicking unverified links or installing unknown software`,
|
| 120 |
-
|
| 121 |
-
'code-assistant': `You are a senior software engineer and solution architect with 15 years experience.
|
| 122 |
-
Specialties: TypeScript, Node.js, Python, system design, cloud architecture, DevOps.
|
| 123 |
-
|
| 124 |
-
When writing or reviewing code always follow this structure:
|
| 125 |
-
1. What it does (one sentence)
|
| 126 |
-
2. Complete working solution with inline comments explaining WHY
|
| 127 |
-
3. Key decisions explained
|
| 128 |
-
4. Edge cases and potential bugs
|
| 129 |
-
5. How to test it
|
| 130 |
-
|
| 131 |
-
Code standards:
|
| 132 |
-
- Production-ready: handles errors and edge cases
|
| 133 |
-
- TypeScript: proper types, avoid 'any' unless justified with a comment
|
| 134 |
-
- Self-documenting: clear names, comments on non-obvious logic
|
| 135 |
-
- Performance: mention time/space complexity for algorithms
|
| 136 |
-
|
| 137 |
-
When debugging:
|
| 138 |
-
- Ask for the FULL error message if not provided
|
| 139 |
-
- Identify root cause not just symptoms
|
| 140 |
-
- Explain how to prevent recurrence
|
| 141 |
-
|
| 142 |
-
Honest uncertainty rule:
|
| 143 |
-
If not 100% certain about a library version or API behavior — say so and explain how to verify.
|
| 144 |
-
Never present guesses as facts.`
|
| 145 |
-
}
|
| 146 |
-
|
| 147 |
-
const systemPrompt = systemPrompts[model] || systemPrompts['smart-router']
|
| 148 |
-
const messagesWithSystem: SimpleMessage[] = systemPrompt
|
| 149 |
-
? [{ role: 'system' as const, content: systemPrompt }, ...messages]
|
| 150 |
-
: [...messages]
|
| 151 |
-
|
| 152 |
-
const piiScan = scanAllMessages(messages)
|
| 153 |
-
const piiDetected = piiScan.hasPII
|
| 154 |
-
const piiTypes = piiScan.types
|
| 155 |
-
|
| 156 |
-
// ── EXPENSE PARSER — always cloud, needs accuracy ────────
|
| 157 |
-
if (model === 'expense-parser') {
|
| 158 |
-
try {
|
| 159 |
-
const response = (await cerebrasProvider.complete({ messages: messagesWithSystem })).content
|
| 160 |
-
logger.info('routed', { to: 'cloud', model, piiDetected })
|
| 161 |
-
return { response, usedModel: 'cloud', piiDetected, piiTypes }
|
| 162 |
-
} catch (err: any) {
|
| 163 |
-
logger.error('expense_parser_failed', { error: err.message })
|
| 164 |
-
throw new Error(`Expense parsing failed: ${err.message}`)
|
| 165 |
-
}
|
| 166 |
-
}
|
| 167 |
-
|
| 168 |
-
// ── PROFESSOR AI — cloud with web search ─────────────────
|
| 169 |
-
if (model === 'professor-ai') {
|
| 170 |
-
try {
|
| 171 |
-
const lastMessage = messages[messages.length - 1]?.content ?? ''
|
| 172 |
-
const searchResults = await searchWeb(lastMessage)
|
| 173 |
-
|
| 174 |
-
const contextMessages: SimpleMessage[] = searchResults
|
| 175 |
-
? [
|
| 176 |
-
{
|
| 177 |
-
role: 'system' as const,
|
| 178 |
-
content: `Current web research results:\n${searchResults}\n\nUse this to provide up-to-date information and resources.`
|
| 179 |
-
},
|
| 180 |
-
...messagesWithSystem
|
| 181 |
-
]
|
| 182 |
-
: messagesWithSystem
|
| 183 |
-
|
| 184 |
-
const response = (await cerebrasProvider.complete({ messages: contextMessages })).content
|
| 185 |
-
logger.info('routed', { to: 'cloud', model, piiDetected })
|
| 186 |
-
return { response, usedModel: 'cloud', piiDetected, piiTypes }
|
| 187 |
-
} catch (err: any) {
|
| 188 |
-
logger.warn('professor_cloud_failed', { error: err.message })
|
| 189 |
-
const response = (await ollamaProvider.complete({ messages: messagesWithSystem })).content
|
| 190 |
-
return { response, usedModel: 'fallback', piiDetected, piiTypes }
|
| 191 |
-
}
|
| 192 |
-
}
|
| 193 |
-
|
| 194 |
-
// ── CODE ASSISTANT — local first, cloud fallback ──────────
|
| 195 |
-
if (model === 'code-assistant') {
|
| 196 |
-
try {
|
| 197 |
-
const response = (await ollamaProvider.complete({ messages: messagesWithSystem })).content
|
| 198 |
-
logger.info('routed', { to: 'local', model, piiDetected })
|
| 199 |
-
return { response, usedModel: 'local', piiDetected, piiTypes }
|
| 200 |
-
} catch {
|
| 201 |
-
const response = (await cerebrasProvider.complete({ messages: messagesWithSystem })).content
|
| 202 |
-
logger.info('routed', { to: 'cloud_fallback', model, piiDetected })
|
| 203 |
-
return { response, usedModel: 'fallback', piiDetected, piiTypes }
|
| 204 |
-
}
|
| 205 |
-
}
|
| 206 |
-
|
| 207 |
-
// ── SMART ROUTER — PII-based routing ─────────────────────
|
| 208 |
-
const wantsLocal =
|
| 209 |
-
(feature && ALWAYS_LOCAL.includes(feature)) ||
|
| 210 |
-
(!feature && piiDetected && !ALWAYS_CLOUD.includes(feature || ''))
|
| 211 |
-
|
| 212 |
-
logger.info('routing_decision', {
|
| 213 |
-
model,
|
| 214 |
-
piiDetected,
|
| 215 |
-
feature,
|
| 216 |
-
wantsLocal,
|
| 217 |
-
ollamaCircuitOpen: isCircuitOpen('ollama'),
|
| 218 |
-
cerebrasCircuitOpen: isCircuitOpen('cerebras')
|
| 219 |
-
})
|
| 220 |
-
|
| 221 |
-
if (wantsLocal && !isCircuitOpen('ollama')) {
|
| 222 |
-
try {
|
| 223 |
-
const response = (await ollamaProvider.complete({ messages: messagesWithSystem })).content
|
| 224 |
-
logger.info('routed', { to: 'local', piiDetected }, Date.now() - start)
|
| 225 |
-
return { response, usedModel: 'local', piiDetected, piiTypes }
|
| 226 |
-
} catch (err: any) {
|
| 227 |
-
logger.warn('local_failed_trying_cloud', { error: err.message })
|
| 228 |
-
if (feature && ALWAYS_LOCAL.includes(feature)) {
|
| 229 |
-
throw new Error('Private service unavailable. Your data was not sent to cloud. Please try again.')
|
| 230 |
-
}
|
| 231 |
-
}
|
| 232 |
-
} else if (wantsLocal) {
|
| 233 |
-
logger.warn('ollama_circuit_open_falling_back')
|
| 234 |
-
}
|
| 235 |
-
|
| 236 |
-
if (!isCircuitOpen('cerebras')) {
|
| 237 |
-
try {
|
| 238 |
-
const response = (await cerebrasProvider.complete({ messages: messagesWithSystem })).content
|
| 239 |
-
const usedModel = wantsLocal ? 'fallback' : 'cloud'
|
| 240 |
-
logger.info('routed', { to: usedModel, piiDetected }, Date.now() - start)
|
| 241 |
-
return { response, usedModel, piiDetected, piiTypes }
|
| 242 |
-
} catch (err: any) {
|
| 243 |
-
logger.error('cloud_failed', { error: err.message })
|
| 244 |
-
}
|
| 245 |
-
}
|
| 246 |
-
|
| 247 |
-
logger.error('all_models_failed', {}, Date.now() - start)
|
| 248 |
-
throw new Error('All AI services are currently unavailable. Please try again in a moment.')
|
| 249 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/websearch.ts
DELETED
|
@@ -1,35 +0,0 @@
|
|
| 1 |
-
export async function searchWeb(query: string): Promise<string> {
|
| 2 |
-
const apiKey = process.env.TAVILY_API_KEY
|
| 3 |
-
if (!apiKey) return ''
|
| 4 |
-
|
| 5 |
-
try {
|
| 6 |
-
const response = await fetch('https://api.tavily.com/search', {
|
| 7 |
-
method: 'POST',
|
| 8 |
-
headers: { 'Content-Type': 'application/json' },
|
| 9 |
-
body: JSON.stringify({
|
| 10 |
-
api_key: apiKey,
|
| 11 |
-
query,
|
| 12 |
-
max_results: 3,
|
| 13 |
-
include_answer: true,
|
| 14 |
-
search_depth: 'advanced'
|
| 15 |
-
}),
|
| 16 |
-
signal: AbortSignal.timeout(10000)
|
| 17 |
-
})
|
| 18 |
-
|
| 19 |
-
const data = await response.json() as {
|
| 20 |
-
answer?: string
|
| 21 |
-
results: Array<{ url: string; content?: string }>
|
| 22 |
-
}
|
| 23 |
-
|
| 24 |
-
if (data.answer) return `Research summary: ${data.answer}\n\nSources:\n` +
|
| 25 |
-
data.results.map(r => `- ${r.url}: ${r.content?.substring(0, 200) ?? ''}`).join('\n')
|
| 26 |
-
|
| 27 |
-
return data.results
|
| 28 |
-
.map(r => `Source: ${r.url}\n${r.content?.substring(0, 300) ?? ''}`)
|
| 29 |
-
.join('\n\n')
|
| 30 |
-
|
| 31 |
-
} catch (err) {
|
| 32 |
-
console.warn('web_search_failed', { error: (err as Error).message })
|
| 33 |
-
return ''
|
| 34 |
-
}
|
| 35 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tsconfig.json
DELETED
|
@@ -1,25 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"compilerOptions": {
|
| 3 |
-
"rootDir": "./src/",
|
| 4 |
-
"outDir": "./dist",
|
| 5 |
-
"module": "nodenext",
|
| 6 |
-
"target": "esnext",
|
| 7 |
-
"lib": ["esnext"],
|
| 8 |
-
"types": ["node"],
|
| 9 |
-
"sourceMap": true,
|
| 10 |
-
"declaration": true,
|
| 11 |
-
"declarationMap": true,
|
| 12 |
-
"noUncheckedIndexedAccess": true,
|
| 13 |
-
"exactOptionalPropertyTypes": true,
|
| 14 |
-
"noImplicitReturns": true,
|
| 15 |
-
"noImplicitOverride": true,
|
| 16 |
-
"noUnusedParameters": true,
|
| 17 |
-
"strict": true,
|
| 18 |
-
"jsx": "react-jsx",
|
| 19 |
-
"verbatimModuleSyntax": false,
|
| 20 |
-
"isolatedModules": true,
|
| 21 |
-
"noUncheckedSideEffectImports": true,
|
| 22 |
-
"moduleDetection": "force",
|
| 23 |
-
"skipLibCheck": true,
|
| 24 |
-
}
|
| 25 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|