|
| 1 | +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * `/ai` domain — extracted dispatcher body (ADR-0076 D11 step ③, PR-7). |
| 5 | + * Dispatches to the AI service's registered route handlers (the |
| 6 | + * `__aiRoutes` table the AI plugin caches on the request kernel), enforcing |
| 7 | + * each route's declared `auth` contract and threading the resolved actor |
| 8 | + * into handlers. NOTE: receives the FULL cleanPath (no prefix strip) — the |
| 9 | + * legacy branch passed `cleanPath` whole and the matcher re-prefixes |
| 10 | + * `/api/v1` internally; preserved verbatim. |
| 11 | + */ |
| 12 | + |
| 13 | +import { |
| 14 | + shouldDenyAnonymous, ANONYMOUS_DENY_STATUS, ANONYMOUS_DENY_CODE, ANONYMOUS_DENY_MESSAGE, |
| 15 | +} from '@objectstack/core'; |
| 16 | +import type { HttpProtocolContext, HttpDispatcherResult } from '../http-dispatcher.js'; |
| 17 | +import type { DomainHandlerDeps, DomainRoute } from '../domain-handler-registry.js'; |
| 18 | + |
| 19 | +export function createAiDomain(deps: DomainHandlerDeps): DomainRoute { |
| 20 | + return { |
| 21 | + prefix: '/ai', |
| 22 | + handler: (req, context) => |
| 23 | + handleAIRequest(deps, req.path, req.method, req.body, req.query, context), |
| 24 | + }; |
| 25 | +} |
| 26 | + |
| 27 | +/** |
| 28 | + * Handle AI service routes (/ai/chat, /ai/models, /ai/conversations, etc.) |
| 29 | + * Resolves the AI service and its built-in route handlers, then dispatches. |
| 30 | + */ |
| 31 | +export async function handleAIRequest(deps: DomainHandlerDeps, subPath: string, method: string, body: any, query: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> { |
| 32 | + let aiService: any; |
| 33 | + try { |
| 34 | + aiService = await deps.resolveService('ai'); |
| 35 | + } catch { |
| 36 | + // AI service not registered |
| 37 | + } |
| 38 | + |
| 39 | + if (!aiService) { |
| 40 | + // The console polls `GET /ai/agents` on every navigation to decide |
| 41 | + // whether to show AI affordances. Reporting that as a 404 turns the |
| 42 | + // normal "no AI service configured" state (the open-source default — |
| 43 | + // service-ai is a Cloud/Enterprise package) into console error-log |
| 44 | + // spam on every page. An empty list conveys the same information |
| 45 | + // without looking like a fault. Every other /ai/* route still 404s. |
| 46 | + if (method === 'GET' && subPath === '/ai/agents') { |
| 47 | + return { handled: true, response: { status: 200, body: { agents: [] } } }; |
| 48 | + } |
| 49 | + return { |
| 50 | + handled: true, |
| 51 | + response: { |
| 52 | + status: 404, |
| 53 | + body: { success: false, error: { message: 'AI service is not configured', code: 404 } }, |
| 54 | + }, |
| 55 | + }; |
| 56 | + } |
| 57 | + |
| 58 | + // The AI service exposes route definitions via buildAIRoutes. |
| 59 | + // We match the request path against known AI route patterns. |
| 60 | + const fullPath = `/api/v1${subPath}`; |
| 61 | + |
| 62 | + // Build a simple param-extracting matcher for route patterns like /api/v1/ai/conversations/:id |
| 63 | + const matchRoute = (pattern: string, path: string): Record<string, string> | null => { |
| 64 | + const patternParts = pattern.split('/'); |
| 65 | + const pathParts = path.split('/'); |
| 66 | + if (patternParts.length !== pathParts.length) return null; |
| 67 | + const params: Record<string, string> = {}; |
| 68 | + for (let i = 0; i < patternParts.length; i++) { |
| 69 | + if (patternParts[i].startsWith(':')) { |
| 70 | + params[patternParts[i].substring(1)] = pathParts[i]; |
| 71 | + } else if (patternParts[i] !== pathParts[i]) { |
| 72 | + return null; |
| 73 | + } |
| 74 | + } |
| 75 | + return params; |
| 76 | + }; |
| 77 | + |
| 78 | + // Try to get route definitions from the AI service's cached routes |
| 79 | + const routes = deps.getRegisteredAiRoutes() as Array<{ |
| 80 | + method: string; path: string; handler: (req: any) => Promise<any>; auth?: boolean; |
| 81 | + }> | undefined; |
| 82 | + |
| 83 | + if (!routes) { |
| 84 | + return { |
| 85 | + handled: true, |
| 86 | + response: { |
| 87 | + status: 503, |
| 88 | + body: { success: false, error: { message: 'AI service routes not yet initialized', code: 503 } }, |
| 89 | + }, |
| 90 | + }; |
| 91 | + } |
| 92 | + |
| 93 | + for (const route of routes) { |
| 94 | + if (route.method !== method) continue; |
| 95 | + const params = matchRoute(route.path, fullPath); |
| 96 | + if (params === null) continue; |
| 97 | + |
| 98 | + // Enforce the route's declared `auth` contract. Nothing upstream |
| 99 | + // does: `enforceAuthGate` only covers ADR-0069 password/MFA gates |
| 100 | + // and `enforceProjectMembership` bails when the request is |
| 101 | + // anonymous or unscoped — so without this an anonymous caller |
| 102 | + // reached `auth: true` handlers (e.g. GET /ai/status) and got the |
| 103 | + // adapter/model config back. Gate when the deployment requires |
| 104 | + // auth; an authenticated user (or an internal system context) |
| 105 | + // passes, matching the REST `enforceAuth` seam. Off → unchanged. |
| 106 | + if (route.auth !== false) { |
| 107 | + const gec: any = context.executionContext; |
| 108 | + // `requireAuth && route.auth !== false` is the AI-route contract; |
| 109 | + // the shared function owns the anonymous decision itself. |
| 110 | + if (shouldDenyAnonymous({ requireAuth: deps.isAuthRequired(), userId: gec?.userId, isSystem: gec?.isSystem })) { |
| 111 | + return { |
| 112 | + handled: true, |
| 113 | + response: deps.error(ANONYMOUS_DENY_MESSAGE, ANONYMOUS_DENY_STATUS, { code: ANONYMOUS_DENY_CODE }), |
| 114 | + }; |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + // Resolve `req.user` from the already-resolved ExecutionContext so |
| 119 | + // AI route handlers can attribute the call to the authenticated |
| 120 | + // actor (drives auto-titled conversations, permission-aware |
| 121 | + // tools, HITL conversation linkage, …). Falls back to undefined |
| 122 | + // for anonymous requests (only reachable when the deployment does |
| 123 | + // NOT require auth — the gate above rejects them otherwise). |
| 124 | + const ec: any = context.executionContext; |
| 125 | + // `ai_seat` is synthesized into ec.permissions by resolveExecutionContext |
| 126 | + // (the single, scope-correct source — security/resolve-execution-context.ts), |
| 127 | + // so it flows through here with no extra per-request lookup. |
| 128 | + const user = ec?.userId |
| 129 | + ? { |
| 130 | + userId: ec.userId, |
| 131 | + id: ec.userId, |
| 132 | + displayName: ec.userDisplayName ?? ec.userName ?? ec.userId, |
| 133 | + email: ec.userEmail, |
| 134 | + roles: Array.isArray(ec.positions) ? ec.positions : [], |
| 135 | + permissions: Array.isArray(ec.permissions) ? ec.permissions : [], |
| 136 | + organizationId: ec.tenantId, |
| 137 | + } |
| 138 | + : undefined; |
| 139 | + |
| 140 | + const result = await route.handler({ |
| 141 | + body, |
| 142 | + params, |
| 143 | + query, |
| 144 | + headers: context.request?.headers, |
| 145 | + user, |
| 146 | + }); |
| 147 | + |
| 148 | + if (result.stream && result.events) { |
| 149 | + // Return a streaming result for the adapter to handle |
| 150 | + return { |
| 151 | + handled: true, |
| 152 | + result: { |
| 153 | + type: 'stream', |
| 154 | + contentType: result.vercelDataStream |
| 155 | + ? 'text/plain; charset=utf-8' |
| 156 | + : 'text/event-stream', |
| 157 | + events: result.events, |
| 158 | + vercelDataStream: result.vercelDataStream, |
| 159 | + headers: { |
| 160 | + 'Content-Type': result.vercelDataStream |
| 161 | + ? 'text/plain; charset=utf-8' |
| 162 | + : 'text/event-stream', |
| 163 | + 'Cache-Control': 'no-cache', |
| 164 | + 'Connection': 'keep-alive', |
| 165 | + }, |
| 166 | + }, |
| 167 | + }; |
| 168 | + } |
| 169 | + |
| 170 | + return { |
| 171 | + handled: true, |
| 172 | + response: { |
| 173 | + status: result.status, |
| 174 | + body: result.body, |
| 175 | + }, |
| 176 | + }; |
| 177 | + } |
| 178 | + |
| 179 | + return { |
| 180 | + handled: true, |
| 181 | + response: deps.routeNotFound(subPath), |
| 182 | + }; |
| 183 | +} |
0 commit comments