feat(server): let a trip owner switch trip addons for one trip

A trip can now turn a trip addon (lists, costs, documents, collab, road
trip, tours) on or off for itself, whatever the instance switch says. No
row in the new trip_addon_overrides table means the trip follows the
instance; a row is the owner's choice. Going back to the instance setting
deletes the row, and no addon data is touched either way.

- GET/PUT /api/trips/:tripId/addons[/:addonId] (every member reads, the
  owner writes) and the MCP tools get_trip_addons and set_trip_addon, on
  the shared tripAddons contract; tripAddons:changed tells the members.
- Every trip-scoped addon surface asks the trip: REST through
  TripAddonGuard, MCP through a per-call gate on the named or pinned trip,
  plugin RPC and events, the share link, the offline bundle, reminders,
  doc sync, the assistant (tools, keep_attached_file), booking costs, the
  trip summary prompt, and the cross-trip tour reads (library, Atlas
  stats, collection save).
- Routes without a trip open while the addon is on in any of the user's
  trips. Switching an addon on that the instance has off ends the members'
  MCP sessions so they reconnect with its tools.
- A copied trip takes its owner's choices along.

Behaviour changes: an anonymous call to an addon route that is off now
gets 401 instead of 404, and with an instance switch off the packing,
todo and files plugin RPC methods, the files MCP tools, todo reminder
mails, core plugin events, plugin view contributions, the share link's
lists, costs and chat sections and the offline bundle's lists follow it.
This commit is contained in:
Maurice
2026-11-21 13:23:02 +01:00
parent 2f7b8357ce
commit 3f38621024
203 changed files with 3710 additions and 498 deletions
@@ -37,8 +37,8 @@ export interface AttachedFileReader {
* (assistant-attach-answer.ts); no answer ends on the error then.
*/
readonly acknowledges: boolean;
/** Refuses a file nobody here can read, before a turn begins. */
ensureReadable(userId: number, file: Express.Multer.File): Promise<void>;
/** Refuses a file nobody here can read for this trip, before a turn begins. */
ensureReadable(userId: number, tripId: number, file: Express.Multer.File): Promise<void>;
/** What the file holds, at most a step's worth. Persists nothing. */
propose(userId: number, tripId: number, file: Express.Multer.File): Promise<FileRead>;
}
@@ -74,6 +74,8 @@ export interface AttachedTurn {
attached: readonly AssistantAttachmentSummary[];
/** The model and its host, as the consent card names them. */
sentTo: string;
/** Whether a file may go into the trip's Files: false while the trip has Documents off. */
keeps: boolean;
/** Reads a file the user let the model read already. */
read(attachmentId: string): Promise<AgentToolRun>;
}
@@ -87,7 +89,8 @@ function attachmentOf(turn: AttachedTurn, args: ToolArgs): AssistantAttachmentSu
/**
* The turn's tools with the attached files' own: keep_attached_file where
* the thread holds an attachment, read_attached_file where one holds text.
* the thread holds an attachment and the trip has Documents on,
* read_attached_file where one holds text.
* A file not yet shared is a write (held as the consent card), a shared one
* a read; a keep is always held. A held call keeps the file's name (and
* where its text goes) for the card, never the text.
@@ -96,14 +99,18 @@ export function attachedPort(port: AgentToolPort, turn: AttachedTurn | null): Ag
if (!turn || turn.attached.length === 0) return port;
const reads = turn.attached.some((row) => row.text_status === 'ok');
return {
specs: () => [...port.specs(), ...(reads ? [READ_ATTACHED_FILE_SPEC] : []), KEEP_ATTACHED_FILE_SPEC],
specs: () => [
...port.specs(),
...(reads ? [READ_ATTACHED_FILE_SPEC] : []),
...(turn.keeps ? [KEEP_ATTACHED_FILE_SPEC] : []),
],
kindOf: (name, args) => {
if (name === KEEP_ATTACHED_FILE_TOOL) return 'write';
if (name === KEEP_ATTACHED_FILE_TOOL && turn.keeps) return 'write';
if (name !== READ_ATTACHED_FILE_TOOL || !reads) return port.kindOf(name, args);
return attachmentOf(turn, args ?? {})?.shared_at ? 'read' : 'write';
},
pinArgs: (name, args) => {
if (name === KEEP_ATTACHED_FILE_TOOL) return keepArgs(turn, args);
if (name === KEEP_ATTACHED_FILE_TOOL && turn.keeps) return keepArgs(turn, args);
if (name !== READ_ATTACHED_FILE_TOOL || !reads) return port.pinArgs(name, args);
const row = attachmentOf(turn, args);
if (!row) return { error: NO_SUCH_ATTACHMENT };
@@ -183,9 +183,11 @@ export class AssistantAttachmentsService {
const compact = connection.kind === 'custom';
const { attached, texts } = await this.forTurn(threadId, userId, compact);
const sentTo = `${connection.model} (${connection.host})`;
// A thread's files all belong to its trip, so the first one names it.
const keeps = attached.length > 0 && (await this.keeper.keepsOn(attached[0].trip_id));
// Read while the turn streams, outside any request's context.
const read = (id: string) => withRequestContext(this.orm, () => this.readShared(userId, threadId, id, compact));
return { texts, turn: { attached, sentTo, read } };
return { texts, turn: { attached, sentTo, keeps, read } };
}
/** Whether a held change is one on an attachment, which `applyChange` runs. */
@@ -76,7 +76,7 @@ export class AssistantBookingImportService implements AttachedFileReader {
* Refuses a file nobody here can read: no extractor and no AI parsing, or a
* photo while the AI model reads no images (the extractor never reads one).
*/
async ensureReadable(userId: number, file: Express.Multer.File): Promise<void> {
async ensureReadable(userId: number, _tripId: number, file: Express.Multer.File): Promise<void> {
const ai = await this.bookingImport.aiAvailable(userId);
if (!ai && !this.bookingImport.isAvailable()) {
throw aiRefusal('import_unavailable', 'Reading booking files is not available on this server');
@@ -1,5 +1,8 @@
import { ADDON_IDS } from '../../addons';
import { AssistantAttachments } from '../../db/entities/AssistantAttachments.entity';
import type { AssistantAttachmentsRepository } from '../../db/repositories/AssistantAttachments.repository';
import { addonOffMessage } from '../addons/addons.constants';
import { AddonsService } from '../addons/addons.service';
import { logError } from '../audit/audit-log.logger';
import { DemoService } from '../common/demo.service';
import { UnitOfWork } from '../database/unit-of-work';
@@ -70,6 +73,7 @@ export class AssistantKeepFileService {
private readonly demo: DemoService,
private readonly trips: TripAccessService,
private readonly uow: UnitOfWork,
private readonly addons: AddonsService,
) {}
/**
@@ -122,10 +126,22 @@ export class AssistantKeepFileService {
return { ok: true, value: { file: keptOf({ ...created, ...links }) } };
}
/** Why the user may not keep this file here, or null: the demo, the trip, the Files rights. */
/**
* Whether files may go into the trip's Files at all: the trip's Documents
* addon, which follows the instance unless the trip's owner chose for it.
*/
keepsOn(tripId: number): Promise<boolean> {
return this.addons.isEnabledForTrip(tripId, ADDON_IDS.DOCUMENTS);
}
/**
* Why the user may not keep this file here, or null: the demo, the trip, the
* trip's Documents addon (answered as the Files routes answer it), the Files rights.
*/
private async refusalOf(at: KeepAt, args: AssistantKeepFileArgs): Promise<string | null> {
if (await this.demo.isDemoUserId(at.userId)) return NOT_ALLOWED;
if (!(await this.trips.findAccessible(at.tripId, at.userId))) return NOT_ALLOWED;
if (!(await this.keepsOn(at.tripId))) return addonOffMessage(ADDON_IDS.DOCUMENTS);
if (!(await this.guards.hasTripPermission('file_upload', at.tripId, at.userId))) return NOT_ALLOWED;
const linking = args.reservation_id ?? args.budget_item_id ?? args.place_id;
if (linking && !(await this.guards.hasTripPermission('file_edit', at.tripId, at.userId))) {
@@ -50,7 +50,7 @@ export class AssistantShareService {
// The asking tab, which the route hands on; deliberately not skipped (see the class comment).
_askingSocketId: string | undefined,
) {
const collabOn = await this.addons.isAddonEnabled(ADDON_IDS.COLLAB);
const collabOn = await this.addons.isEnabledForTrip(tripId, ADDON_IDS.COLLAB);
if (!collabOn || !(await this.addons.getCollabFeatures()).chat) throw aiRefusal('forbidden', 'Collab chat is off');
if (!(await this.threads.findOwned(threadId, user.id, tripId))) {
throw aiRefusal('not_found', 'Conversation not found');
@@ -592,10 +592,13 @@ export class AssistantToolsService implements OnApplicationBootstrap {
traceEntry('mcp', `${info.kind} ${info.name} user=${userId} client=assistant`, () =>
withRequestContext(this.orm, call),
);
// A trip chat is about its one trip: the addon gates ask that trip, so an
// addon the owner switched off for it is never offered (see addon-gate.ts).
const tripId = pin.arg === PINNED_ARG ? pin.id : undefined;
await withRequestContext(this.orm, () =>
this.registry.attach(
server,
{ userId, scopes: [...ASSISTANT_SCOPES], isStaticToken: false },
{ userId, scopes: [...ASSISTANT_SCOPES], isStaticToken: false, ...(tripId === undefined ? {} : { tripId }) },
{ include: (kind, name) => kind === 'tool' && offer.include(name), around },
),
);
@@ -47,9 +47,9 @@ export class AssistantTourFileService implements AttachedFileReader {
private readonly addons: AddonsService,
) {}
/** Refuses a route file where tours are off: nothing could take it in. */
async ensureReadable(_userId: number, _file: Express.Multer.File): Promise<void> {
if (!(await this.addons.isAddonEnabled(ADDON_IDS.TOURS))) {
/** Refuses a route file where Tours is off for the trip: nothing could take it in. */
async ensureReadable(_userId: number, tripId: number, _file: Express.Multer.File): Promise<void> {
if (!(await this.addons.isEnabledForTrip(tripId, ADDON_IDS.TOURS))) {
throw aiRefusal('import_unavailable', 'Tours are not enabled on this server');
}
}
@@ -289,7 +289,7 @@ export class AssistantService {
): Promise<void> {
await this.admit(userId);
const reader: AttachedFileReader = isAssistantTourFile(file.originalname) ? this.tourFiles : this.bookings;
await reader.ensureReadable(userId, file);
await reader.ensureReadable(userId, tripId, file);
const connection = await this.connections.resolveForUser(userId);
await this.withinDailyLimit(userId, connection);
await this.claimed(userId, channel.signal, async (signal) => {