feat(assistant): support the managed TREK gateway

This commit is contained in:
Maurice
2026-12-01 00:27:08 +01:00
parent fa23f94ee8
commit 00e98b8711
19 changed files with 207 additions and 39 deletions
+1 -1
View File
@@ -165,7 +165,7 @@ below.)
**Runtime-toggled** (read live on every access via `readEnv()` /
`RuntimeEnvService`; tests mutate these mid-lifetime):
TREK_MANAGED, PLACES_API_BASE, PLACES_API_KEY, AMAP_API_BASE, AMAP_API_KEY, AMAP_API_SECRET, MAPBOX_ACCESS_TOKEN, CARTO_API_KEY, DEMO_MODE, NODE_ENV, APP_VERSION, APP_URL, TREK_API_DOCS_ENABLED,
TREK_MANAGED, TREK_MANAGED_ASSISTANT_URL, TREK_MANAGED_ASSISTANT_TOKEN, TREK_MANAGED_ASSISTANT_MODEL, PLACES_API_BASE, PLACES_API_KEY, AMAP_API_BASE, AMAP_API_KEY, AMAP_API_SECRET, MAPBOX_ACCESS_TOKEN, CARTO_API_KEY, DEMO_MODE, NODE_ENV, APP_VERSION, APP_URL, TREK_API_DOCS_ENABLED,
TREK_PLUGINS_ENABLED / _DEV_LINK / _IGNORE_TREK_RANGE / _DIR / _DATA_DIR / TREK_PLUGIN_PERMISSIONS,
OIDC_*, SMTP_*, FORCE_HTTPS, COOKIE_SECURE,
ALLOWED_ORIGINS, UNSPLASH_ACCESS_KEY, WEBAUTHN_*, TZ, ADMIN_EMAIL,
+6 -5
View File
@@ -122,17 +122,18 @@ function flagText(raw: string | undefined): 'true' | 'false' | undefined {
* Whether this instance is centrally administered: somebody other than its
* admin user owns the configuration, the credentials and the upgrade schedule.
*
* Only a boolean, on purpose. It answers "who configures this install", and the
* surfaces that care read it themselves rather than being listed here, so adding
* one never touches this file.
*
* `=== true` so an unset, empty or unparseable value means off. A managed
* install sets it deliberately; nothing should be able to switch it on by
* accident, and a typo must not silently take settings away from an admin.
*/
export function deriveManaged(raw: RawEnv) {
const enabled = parseBool(raw.TREK_MANAGED) === true;
const baseUrl = raw.TREK_MANAGED_ASSISTANT_URL?.trim();
const token = raw.TREK_MANAGED_ASSISTANT_TOKEN?.trim();
const model = raw.TREK_MANAGED_ASSISTANT_MODEL?.trim();
return {
enabled: parseBool(raw.TREK_MANAGED) === true,
enabled,
assistant: enabled && baseUrl && token && model ? { baseUrl, token, model } : null,
};
}
+3
View File
@@ -213,6 +213,9 @@ export const envSchema = z.object({
ADMIN_EMAIL: anyString,
ADMIN_PASSWORD: anyString,
TREK_MANAGED: boolStr,
TREK_MANAGED_ASSISTANT_URL: url,
TREK_MANAGED_ASSISTANT_TOKEN: anyString,
TREK_MANAGED_ASSISTANT_MODEL: anyString,
PLACES_API_BASE: url,
GOOGLE_LIST_DATA_BASE: url,
TREK_PLACES_URL: url,
+26
View File
@@ -28,6 +28,7 @@ export const SECRET_ENV_KEYS: ReadonlySet<string> = new Set([
'ADMIN_PASSWORD',
'PLACES_API_KEY',
'TREK_SERVICES_KEY',
'TREK_MANAGED_ASSISTANT_TOKEN',
'AMAP_API_KEY',
'AMAP_API_SECRET',
'MAPBOX_ACCESS_TOKEN',
@@ -153,5 +154,30 @@ function managedPreconditions(raw: RawEnv): string[] {
);
}
const {
TREK_MANAGED_ASSISTANT_URL: baseUrl,
TREK_MANAGED_ASSISTANT_MODEL: model,
TREK_MANAGED_ASSISTANT_TOKEN: token,
} = raw;
if (baseUrl || model || token) {
if (!baseUrl || !model?.trim() || !token?.trim()) {
problems.push(' - The managed assistant URL, model and token must be configured together.');
} else {
const endpoint = URL.canParse(baseUrl) ? new URL(baseUrl) : null;
if (
!endpoint ||
endpoint.protocol !== 'https:' ||
endpoint.username ||
endpoint.password ||
endpoint.search ||
endpoint.hash
) {
problems.push(
' - TREK_MANAGED_ASSISTANT_URL must be an HTTPS URL without credentials, a query or a fragment.',
);
}
}
}
return problems;
}
@@ -16,6 +16,7 @@ import { Injectable } from '@nestjs/common';
* is the adapter's.
*/
const cloudFetch: AiFetch = (url, init) => safeFetch(url, { ...init, signal: init.signal }, { maxBytes: null });
const hostedFetch: AiFetch = (url, init) => cloudFetch(url, { ...init, redirect: 'error' });
/**
* An admin's own server, which may sit on loopback or in the LAN: the guard
@@ -46,6 +47,15 @@ export class AiChatClientService {
create(connection: ResolvedAiConnection): AiChatClient {
const { credential, kind, model } = connection;
if (credential.type === 'chatgpt') return this.chatgptPlan(connection.id, model, credential.accessToken);
if (connection.managed) {
return new OpenAiChatClient(
'openrouter',
model,
ownServerChatBase(connection.baseUrl),
credential.apiKey,
hostedFetch,
);
}
if (kind === 'openai' && openAiWantsResponses(model)) {
const apiKey = credential.apiKey ?? '';
return new OpenAiResponsesClient(model, () => Promise.resolve(apiKey), cloudFetch, 'openai');
@@ -46,6 +46,7 @@ export class AiConnectionsController {
) {}
@Get('status')
@ManagedForbidden('managed status describes the operator gateway', { allowHostedAssistant: true })
@ResponseContract(aiStatusResponseSchema)
status(@CurrentUser() user: User) {
return this.connections.status(user.id);
@@ -78,6 +79,9 @@ export class AiConnectionsController {
}
@Post('privacy-ack')
@ManagedForbidden('the hosted assistant requires each user to acknowledge the provider', {
allowHostedAssistant: true,
})
@HttpCode(200)
@ResponseContract(successResponseSchema)
async ackPrivacy(@CurrentUser() user: User, @Body() body: AiPrivacyAckDto) {
@@ -48,6 +48,27 @@ import {
/** A key test asks the provider for its models: a few a minute per user, so the server is no oracle for keys. */
const MODEL_CALLS_PER_MINUTE = 5;
function hostedConnection(): ResolvedAiConnection | null {
const config = readEnv().managed.assistant;
if (!config) return null;
return {
id: 0,
managed: true,
scope: 'instance',
kind: 'openrouter',
model: config.model,
baseUrl: config.baseUrl,
host: aiHostOf('openrouter', null),
paidBy: 'instance',
status: 'ok',
credential: { type: 'api_key', apiKey: config.token },
};
}
function privacyTarget(connection: Pick<ResolvedAiConnection, 'kind' | 'host' | 'managed'>): string {
return `${connection.kind}@${connection.host}${connection.managed ? ':managed' : ''}`;
}
function kindOf(row: AiConnectionRow): AiConnectionKind {
return row.kind as AiConnectionKind;
}
@@ -94,13 +115,35 @@ export class AiConnectionsService implements SharedAiConnectionPort {
/** `kind:model` of the models a provider refused an image for, while this process runs. */
private readonly textOnly = new Set<string>();
/** Whether the assistant exists here at all: the addon is on and the install is not centrally administered. */
/** The addon must be on. Managed installs additionally require the operator gateway. */
async enabled(): Promise<boolean> {
return !readEnv().managed.enabled && (await this.addons.isAddonEnabled(ADDON_IDS.AI_ASSISTANT));
const managed = readEnv().managed;
return (!managed.enabled || !!managed.assistant) && (await this.addons.isAddonEnabled(ADDON_IDS.AI_ASSISTANT));
}
async status(userId: number): Promise<AiStatusResponse> {
const settings = await this.aiSettings.read();
const hosted = hostedConnection();
if (hosted) {
const available = await this.enabled();
const target = privacyTarget(hosted);
const instance = { kind: hosted.kind, model: hosted.model, host: hosted.host };
return {
available,
policy: 'instance',
canConnectOwn: false,
effective: available ? { ...instance, source: 'instance', paidBy: 'instance' } : null,
own: null,
instance: available ? instance : null,
quota: null,
privacyAcked:
available && (await this.settings.getDecryptedUserSetting(userId, AI_PRIVACY_ACK_SETTING)) === target,
studioImages: available && this.readsImages(hosted),
studioImagesAcked: available && (await this.studioImagesAckedFor(userId, target)),
retention: settings.retention,
openrouterOAuth: false,
};
}
const own = await this.connections.findForUser(userId);
const instance = await this.connections.findInstance();
const picked = (await this.enabled()) ? pickConnection(settings.policy, own, instance) : null;
@@ -148,6 +191,14 @@ export class AiConnectionsService implements SharedAiConnectionPort {
*/
async resolveForUser(userId: number): Promise<ResolvedAiConnection> {
if (!(await this.enabled())) throw aiRefusal('not_connected', 'The AI assistant is not available');
const hosted = hostedConnection();
if (hosted) {
const target = privacyTarget(hosted);
if ((await this.settings.getDecryptedUserSetting(userId, AI_PRIVACY_ACK_SETTING)) !== target) {
throw aiRefusal('forbidden', 'Acknowledge the AI Assistant privacy notice first');
}
return hosted;
}
const { policy } = await this.aiSettings.read();
const picked = pickConnection(
policy,
@@ -177,6 +228,7 @@ export class AiConnectionsService implements SharedAiConnectionPort {
* clears an earlier mark.
*/
async noteOutcome(connection: ResolvedAiConnection, code: AssistantErrorCode | null): Promise<void> {
if (connection.managed) return;
if (code === 'invalid_key' && connection.status !== 'error') {
await this.connections.setStatus(connection.id, 'error');
} else if (code === 'needs_reauth' && connection.kind === 'chatgpt') {
@@ -241,12 +293,19 @@ export class AiConnectionsService implements SharedAiConnectionPort {
*/
async ackPrivacy(userId: number, req: AiPrivacyAckRequest): Promise<void> {
const key = req.scope === 'studio_images' ? AI_STUDIO_IMAGES_ACK_SETTING : AI_PRIVACY_ACK_SETTING;
await this.settings.upsertSetting(userId, key, `${req.kind}@${req.host}`);
const hosted = hostedConnection();
if (hosted && (req.kind !== hosted.kind || req.host !== hosted.host)) {
throw aiRefusal('forbidden', 'This is not the configured AI Assistant provider');
}
await this.settings.upsertSetting(userId, key, privacyTarget(hosted ?? req));
}
/** Whether the user let this connection receive images of their Studio pages; without it a turn stays text. */
async studioImagesAcked(userId: number, connection: Pick<ResolvedAiConnection, 'kind' | 'host'>): Promise<boolean> {
return this.studioImagesAckedFor(userId, `${connection.kind}@${connection.host}`);
async studioImagesAcked(
userId: number,
connection: Pick<ResolvedAiConnection, 'kind' | 'host' | 'managed'>,
): Promise<boolean> {
return this.studioImagesAckedFor(userId, privacyTarget(connection));
}
private async studioImagesAckedFor(userId: number, target: string): Promise<boolean> {
@@ -259,8 +318,9 @@ export class AiConnectionsService implements SharedAiConnectionPort {
* runs. Status asks this too, so the Studio offers images only where a turn
* would send them.
*/
readsImages({ kind, model }: Pick<ResolvedAiConnection, 'kind' | 'model'>): boolean {
return modelReadsImages(kind, model) && !this.textOnly.has(`${kind}:${model}`);
readsImages({ kind, model, managed }: Pick<ResolvedAiConnection, 'kind' | 'model' | 'managed'>): boolean {
const supported = modelReadsImages(kind, model) || (managed === true && model === 'qwen/qwen3.7-flash');
return supported && !this.textOnly.has(`${kind}:${model}`);
}
/** A provider refused an image for this model: it reads pages in words until the process restarts. */
@@ -10,6 +10,8 @@ export type AiCredential = { type: 'api_key'; apiKey: string | null } | { type:
*/
export interface ResolvedAiConnection {
id: number;
/** Operator gateway configuration has no database connection row or tenant daily quota. */
managed?: true;
scope: AiConnectionScope;
kind: AiConnectionKind;
model: string;
@@ -5,7 +5,7 @@ import { aiRefusal } from '../ai-connections/ai-connections.constants';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { isManagedBlocked, MANAGED_FORBIDDEN_ERROR, ManagedForbidden } from '../common/managed';
import { isManagedAssistantBlocked, MANAGED_FORBIDDEN_ERROR, ManagedForbidden } from '../common/managed';
import { TripAccessService } from '../trip-membership/trip-access.service';
import { MAX_ATTACHMENT_BYTES } from './assistant-tools.constants';
import { channelOf } from './assistant.controller';
@@ -90,7 +90,7 @@ export class AssistantAttachmentsController {
if (!(await this.addons.isAddonEnabled(ADDON_IDS.AI_ASSISTANT))) {
throw new HttpException({ error: 'AI assistant addon is not enabled' }, 404);
}
if (isManagedBlocked(this.env)) throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403);
if (isManagedAssistantBlocked(this.env)) throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403);
if (!(await this.trips.findAccessible(tripId, user.id))) {
throw new HttpException({ error: 'Trip not found' }, 404);
}
@@ -5,7 +5,7 @@ import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { readImageHeader } from '../common/image-header';
import { isManagedBlocked, MANAGED_FORBIDDEN_ERROR, ManagedForbidden } from '../common/managed';
import { isManagedAssistantBlocked, MANAGED_FORBIDDEN_ERROR, ManagedForbidden } from '../common/managed';
import { ResponseContract } from '../common/response-contract';
import { toRowId } from '../common/row-id';
import { JourneyAiPhotosService } from '../journey/journey-ai-photos.service';
@@ -90,7 +90,7 @@ export class AssistantRendersController {
if (!(await this.addons.isAddonEnabled(ADDON_IDS.AI_ASSISTANT))) {
throw new HttpException({ error: 'AI assistant addon is not enabled' }, 404);
}
if (isManagedBlocked(this.env)) throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403);
if (isManagedAssistantBlocked(this.env)) throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403);
if (!(await this.addons.isAddonEnabled(ADDON_IDS.JOURNEY))) {
throw new HttpException({ error: 'Journey addon is not enabled' }, 404);
}
@@ -66,7 +66,7 @@ export function channelOf(res: Response): TurnChannel {
@Controller('api/trips/:tripId/assistant')
@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)
@RequireAddon(ADDON_IDS.AI_ASSISTANT, 'AI assistant')
@ManagedForbidden('the operator decides which model a managed install talks to, and pays for it')
@ManagedForbidden('managed assistant requests use the operator gateway', { allowHostedAssistant: true })
export class AssistantController {
constructor(
private readonly assistant: AssistantService,
@@ -249,7 +249,7 @@ export class AssistantService {
if (begun.created) w.thread(begun.threadId, begun.title);
await this.usage.record(userId, connection.paidBy, { turns: 1 });
const quota =
connection.paidBy === 'instance'
connection.paidBy === 'instance' && dailyTurns !== null
? { used: await this.usage.instanceTurnsToday(userId), limit: dailyTurns }
: null;
const spec: TurnSpec = {
@@ -372,7 +372,7 @@ export class AssistantService {
const w = new UiStreamWriter(stream);
w.start(messageIdOf(await this.answerStart(threadId, decided[0].call.message_id)));
const quota =
connection.paidBy === 'instance'
connection.paidBy === 'instance' && dailyTurns !== null
? { used: await this.usage.instanceTurnsToday(userId), limit: dailyTurns }
: null;
const spec: TurnSpec = {
@@ -530,7 +530,8 @@ export class AssistantService {
* day reached the admin's limit; answers that limit. A decision counts no
* turn of its own, but runs the model again, so it is held to the limit too.
*/
private async withinDailyLimit(userId: number, connection: ResolvedAiConnection): Promise<number> {
private async withinDailyLimit(userId: number, connection: ResolvedAiConnection): Promise<number | null> {
if (connection.managed) return null;
const { dailyTurns } = await this.connections.readSettings();
if (connection.paidBy === 'instance' && (await this.usage.instanceTurnsToday(userId)) >= dailyTurns) {
throw aiRefusal('daily_limit', 'The daily limit of the assistant is reached');
@@ -36,7 +36,7 @@ import type { Response } from 'express';
@Controller('api/assistant')
@UseGuards(AddonGuard, JwtAuthGuard)
@RequireAddon(ADDON_IDS.AI_ASSISTANT, 'AI assistant')
@ManagedForbidden('the operator decides which model a managed install talks to, and pays for it')
@ManagedForbidden('managed assistant requests use the operator gateway', { allowHostedAssistant: true })
export class HomeAssistantController {
constructor(private readonly assistant: AssistantService) {}
@@ -49,7 +49,7 @@ function journeyScope(journeyId: string, surface?: AssistantJourneySurface): Ass
@Controller('api/journeys/:journeyId/assistant')
@UseGuards(AddonGuard, JwtAuthGuard, JourneyAssistantGuard)
@RequireAddon(ADDON_IDS.AI_ASSISTANT, 'AI assistant')
@ManagedForbidden('the operator decides which model a managed install talks to, and pays for it')
@ManagedForbidden('managed assistant requests use the operator gateway', { allowHostedAssistant: true })
export class JourneyAssistantController {
constructor(private readonly assistant: AssistantService) {}
+5 -5
View File
@@ -1,5 +1,5 @@
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { MANAGED_FORBIDDEN, MANAGED_FORBIDDEN_ERROR } from './managed';
import { isManagedAssistantBlocked, MANAGED_FORBIDDEN, MANAGED_FORBIDDEN_ERROR } from './managed';
import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
@@ -31,10 +31,9 @@ export class ManagedGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
if (!this.env.isManaged()) return true;
const marked = this.reflector.getAllAndOverride<{ enforcedInHandler?: boolean } | undefined>(MANAGED_FORBIDDEN, [
context.getHandler(),
context.getClass(),
]);
const marked = this.reflector.getAllAndOverride<
{ enforcedInHandler?: boolean; allowHostedAssistant?: boolean } | undefined
>(MANAGED_FORBIDDEN, [context.getHandler(), context.getClass()]);
if (!marked) return true;
// A multipart handler checks for itself, after the interceptor has drained
@@ -42,6 +41,7 @@ export class ManagedGuard implements CanActivate {
// see an ECONNRESET rather than the 403 (PROFILE-015). The marker still sits
// on the route so the boot gate can inventory it.
if (marked.enforcedInHandler) return true;
if (marked.allowHostedAssistant && !isManagedAssistantBlocked(this.env)) return true;
throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403);
}
+10 -2
View File
@@ -38,8 +38,12 @@ export const MANAGED_FORBIDDEN_ERROR = {
* still carry the marker, because the boot gate inventories markers and a route
* missing from that inventory is exactly what nobody notices.
*/
export const ManagedForbidden = (reason: string, opts?: { enforcedInHandler?: true }) =>
SetMetadata(MANAGED_FORBIDDEN, { reason, enforcedInHandler: opts?.enforcedInHandler === true });
export const ManagedForbidden = (reason: string, opts?: { enforcedInHandler?: true; allowHostedAssistant?: true }) =>
SetMetadata(MANAGED_FORBIDDEN, {
reason,
enforcedInHandler: opts?.enforcedInHandler === true,
...(opts?.allowHostedAssistant ? { allowHostedAssistant: true } : {}),
});
/**
* The handler-side flavour of the guard below.
@@ -53,6 +57,10 @@ export function isManagedBlocked(env: RuntimeEnvService): boolean {
return env.isManaged();
}
export function isManagedAssistantBlocked(env: RuntimeEnvService): boolean {
return env.isManaged() && !env.env().managed.assistant;
}
/**
* The settings a centrally administered install does not hand to its admin,
* because the value belongs to whoever operates it.