All documentation

AI API Reference

The AI Platform's HTTP surface. Almost everything is a Next.js Server Action (not a REST endpoint) invoked directly from a Server Component form — the same convention as every other feature in this codebase (see docs/ARCHITECTURE.md). Only the two routes below are real HTTP endpoints, because streaming and external-cron triggering both need one.

POST /api/ai/chat

The Chat Assistant's streaming endpoint.

  • Auth: cookie session only (no Bearer-token/API-key path) — a

browser-only chat UI, not a programmatic API surface.

  • Gate: checkFeatureAccess(supabase, userId, 'ai_coach'), then

checkAIRateLimit('chat', userId) (30/hour).

  • Body: { conversationId?: string; message: string }. Omitting

conversationId starts a new conversation. message is sanitized via sanitizeUserInput() before use.

  • Response: text/event-stream (SSE), sseResponseHeaders() +

X-Conversation-Id header. Each event is one AIStreamChunk: {type:'content', delta} / {type:'tool_call', toolCall} / {type:'usage', usage} / {type:'done', finishReason} — see services/streaming-service.ts for the exact wire format.

  • Behind it: ChatService.streamReply() — RAG retrieval, tool

execution (capped at 2 rounds), conversation persistence.

GET /api/ai/automations/run

External-cron trigger for AutomationEngine — mirrors GET /api/admin/alerts/check exactly (same pattern, same honesty about this app having no persistent process to run a background scheduler itself — see docs/ARCHITECTURE.md).

  • Auth: shared-secret header (AI_AUTOMATION_RUN_SECRET), no user

session — call this from an external scheduler (cron, GitHub Actions, a hosting platform's own cron trigger).

  • What it does: evaluates every active ai_automations row across

every user against current risk/journal/prop-firm state and executes matching actions (warn, pause, reduce risk, generate report, send brief, alert).

  • Response: { evaluated: number, triggered: number } summary.

Server Actions by feature

Every action follows the ActionState = { error?: string; success?: boolean } + useActionState convention. All require an authenticated session (supabase.auth.getUser()); AI-calling actions additionally check checkAIRateLimit().

FeatureFileActions
Prop Firmapp/dashboard/prop-firms/actions.tsaskPropFirmQuestion
Journalapp/dashboard/journal/actions.tsanalyzeTradeAction, generateReportAction
Coachapp/dashboard/ai-assistant/actions.tsgenerateCoachingAction, createGoalAction
Risk Managerapp/dashboard/risk-manager/ai-monitor/actions.tsrunRiskCheckAction, createRuleAction, toggleRuleAction, deleteRuleAction
Marketapp/dashboard/market/actions.tsregenerateBriefAction
Automationsapp/dashboard/automations/actions.tscreateAutomationAction, toggleAutomationAction, deleteAutomationAction
Admin — Promptsapp/admin/ai/prompts/actions.tssetPromptOverrideAction (requires manage_ai)

Read-only data layers (no HTTP surface — Server Component reads)

  • src/lib/ai/dashboard/dashboard-service.ts — buildAIDashboardSnapshot(supabase, userId), powers /dashboard/ai.
  • src/lib/admin/ai-queries.ts — getProviderStatuses, getAIUsageSummary, getAICostTrend, listConversations, getRecentAIErrors, listPromptTemplates, powers /admin/ai/*.

Internal (not exposed over HTTP) — programmatic entry points

For anything integrating against this codebase directly (e.g. a script, not a browser):

import { createAIProviderManager } from '@/lib/ai/compose';
import { AIRecommendationEngine } from '@/lib/ai/services/recommendation-engine';

const manager = createAIProviderManager();
const engine = new AIRecommendationEngine(manager);
const insight = await engine.generateInsight(supabase, {
  userId, feature: 'journal', promptKey: 'journal_trade_analysis',
  promptVariables: { tradeDetails, riskContext },
  insightType: 'journal_entry', title: '...',
});

createChatService(supabase) (compose.ts) is the equivalent composition root for the Chat Assistant's full RAG + tools + streaming stack.