feat(assistant): every attached booking file gets an answer with what to do next

A booking file without a booking ended the answer on the error "No booking
found in this file." with no action, and the user was left to type. Now the
server answers every booking file itself, without a model: one line that
names the file and what TREK found in it, or that it found nothing, why, and
asks what to do with the file. Under it come up to three chips, picked from
what the user may do on the trip and what the file allows: keep it in Files,
make a booking from its text, attach it to a booking or an expense, ask what
is in it, or keep it with the booking just found. A chip sends its words as
an ordinary chat message.

The line and the chips are written in the language of the request from new
assistant.attach.* keys in all 27 locales, through a small helper the sports
proposals now share. The empty answer finishes as stop; no_bookings_found
stays in the contract for the threads older builds wrote. Route files keep
their answer as it was.
This commit is contained in:
Maurice
2026-10-24 21:23:41 +02:00
parent 41fb5759e2
commit 2f3a0219cd
40 changed files with 870 additions and 43 deletions
@@ -0,0 +1,88 @@
import type { BookingReadReason } from './assistant-booking-import.service';
import type { TripCard } from './assistant-context';
import type { AssistantWords } from './assistant-words';
import { MAX_FOLLOW_UPS } from '@trek/shared';
/**
* The words the server answers an attached booking file with, before any
* model is asked: one line that names the file and what TREK found in it
* (and why it found nothing), then up to three chips with what makes sense
* to do with the file next. A chip sends its words as an ordinary chat
* message, so it goes through the model like anything the user types.
*/
/** What the chips are chosen from: what the file held, and what the user may do with it on this trip. */
export interface AttachFacts {
/** The bookings the file proposes. */
found: number;
/** TREK read text out of the file, so the model could read it too. */
readable: boolean;
/** The file's type is allowed in Files and the user may upload there. */
canKeep: boolean;
/** The user may also change what a file is attached to. */
canLink: boolean;
/** The trip has a booking or an expense the file could be attached to. */
hasTargets: boolean;
/** The user may add bookings to the trip. */
canBook: boolean;
}
/** Each chip's words, as literal keys so the i18n check sees them. */
const CHIPS = {
keep: 'assistant.attach.chip.keep',
book: 'assistant.attach.chip.book',
attach: 'assistant.attach.chip.attach',
read: 'assistant.attach.chip.read',
keepWithBooking: 'assistant.attach.chip.keepWithBooking',
} as const;
/** Why a file held no booking, in the user's words. */
const WHY: Readonly<Record<BookingReadReason, string>> = {
ai_not_configured: 'assistant.attach.why.aiNotConfigured',
ai_failed: 'assistant.attach.why.aiFailed',
no_text: 'assistant.attach.why.noText',
nothing_found: 'assistant.attach.why.nothingFound',
};
/**
* The chips under the answer, in order, at most MAX_FOLLOW_UPS. A file with
* bookings asks to keep it with the booking once it is added; one without
* offers to keep it, to make a booking from its text, to attach it to what
* the trip holds, and to say what is in it.
*/
export function attachChipKeys(facts: AttachFacts): string[] {
const wanted =
facts.found > 0
? [facts.canKeep && facts.canLink && CHIPS.keepWithBooking, facts.readable && CHIPS.read]
: [
facts.canKeep && CHIPS.keep,
facts.readable && facts.canBook && CHIPS.book,
facts.canKeep && facts.canLink && facts.hasTargets && CHIPS.attach,
facts.readable && CHIPS.read,
];
return wanted.filter((key): key is (typeof CHIPS)[keyof typeof CHIPS] => !!key).slice(0, MAX_FOLLOW_UPS);
}
/** The answer's line: what TREK found in the file, or that it found nothing, why, and the question what to do. */
export function attachLine(
words: AssistantWords,
name: string,
found: number,
reason: BookingReadReason | null,
): string {
if (found > 0) return words.count('assistant.attach.found', found, { name });
return [
words.text('assistant.attach.none', { name }),
...(reason ? [words.text(WHY[reason])] : []),
words.text('assistant.attach.ask'),
].join(' ');
}
/** Whether the trip has a booking or an expense a file could be kept with. */
export function hasLinkTargets(card: TripCard): boolean {
if (card.reservations.size > 0) return true;
const summary = card.sources.summary;
const budget =
summary && typeof summary === 'object' ? (summary as { budget?: { items?: unknown } }).budget : undefined;
return Array.isArray(budget?.items) && budget.items.length > 0;
}
@@ -29,8 +29,14 @@ export interface FileRead {
export interface AttachedFileReader {
/** The name the read step goes by in the thread. */
readonly readTool: string;
/** The error a file that holds nothing to propose ends the answer with. */
/** The error a file that holds nothing to propose ends the answer with, unless the reader `acknowledges` it. */
readonly emptyCode: AssistantErrorCode;
/**
* The answer names the file and what was found in it in a line of its own,
* a file without anything says why, and chips offer what to do with it
* (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>;
/** What the file holds, at most a step's worth. Persists nothing. */
@@ -63,7 +63,9 @@ export function emptyReason(preview: BookingImportPreviewResponse, aiAvailable:
@Injectable()
export class AssistantBookingImportService implements AttachedFileReader {
readonly readTool = READ_BOOKING_FILE_TOOL;
/** Kept for the answers older builds wrote; this one acknowledges every file instead. */
readonly emptyCode = 'no_bookings_found' as const;
readonly acknowledges = true;
constructor(
private readonly bookingImport: BookingImportService,
@@ -1,10 +1,17 @@
import type { AssistantAttachmentTextStatus } from '../../db/repositories/AssistantAttachments.repository';
import { logError } from '../audit/audit-log.logger';
import { withRequestContext } from '../database/request-context';
import { AllowedFileTypesService } from '../files/allowed-file-types.service';
import { isUploadTypeAllowed } from '../files/files.constants';
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
import type { HeldCall } from './assistant-agent';
import { attachChipKeys, attachLine, hasLinkTargets, type AttachFacts } from './assistant-attach-answer';
import type { AttachedFileReader, FileRead } from './assistant-attached-file';
import { todayIn } from './assistant-context';
import { BOOKING_READ_REASONS, type BookingReadReason } from './assistant-booking-import.service';
import { todayIn, type TripCard } from './assistant-context';
import { AssistantToolsService } from './assistant-tools.service';
import { readTripCard } from './assistant-trip-scope';
import { AssistantWords } from './assistant-words';
import { AssistantCardContext } from './cards/card-context';
import type { UiStreamWriter } from './ui-stream.writer';
import { MikroORM } from '@mikro-orm/core';
@@ -16,13 +23,16 @@ import { randomUUID } from 'node:crypto';
/** What the read step of an attached file answers when the file could not be read. */
const FILE_UNREADABLE = 'The file could not be read.';
/** The turn a file was attached in: who, on which trip, the thread and the answer's first row. */
/** The turn a file was attached in: who, on which trip, the thread, the answer's first row and the file kept. */
export interface FileTurn extends AssistantClientCtx {
userId: number;
tripId: number;
threadId: number;
rowId: number;
name: string;
mime: string;
/** How TREK's reading of the file's text went, when it was kept (AssistantAttachmentsService). */
textStatus: AssistantAttachmentTextStatus;
}
/** How the answer's row is written: AssistantService's, which owns the rows and their transactions. */
@@ -39,24 +49,41 @@ export interface FileAnswerOut {
rows: FileAnswerRows;
}
/** A file that proposes nothing holds no change. */
const NOTHING_HELD: {
held: HeldCall[];
parts: AssistantMessagePart[];
shown: ReadonlyMap<string, Record<string, unknown>>;
} = { held: [], parts: [], shown: new Map() };
/** The reason a read step names, when it is one this build knows. */
function reasonOf(found: Record<string, unknown>): BookingReadReason | null {
const reason = found.reason;
return (BOOKING_READ_REASONS as readonly unknown[]).includes(reason) ? (reason as BookingReadReason) : null;
}
/**
* The answer to a file the user attached in the trip chat, written by the
* server itself, in the answer's first row: the read step, then one held
* change per booking (`import_booking`) or track (`import_tour_file`), each
* with its card. No model is asked.
* with its card. A booking file is always answered with a line that names
* what was found (or why nothing was) and chips with what to do with the
* file next (assistant-attach-answer.ts). No model is asked.
*/
@Injectable()
export class AssistantFileAnswers {
constructor(
private readonly tools: AssistantToolsService,
private readonly cardContext: AssistantCardContext,
private readonly guards: McpToolGuardsService,
private readonly allowedTypes: AllowedFileTypesService,
private readonly orm: MikroORM,
) {}
/**
* Reads the attached file and proposes what it found. A file without any
* ends the answer with the reader's code; one that cannot be read, with
* `generic`.
* Reads the attached file and proposes what it found. A file that cannot
* be read ends the answer with `generic`; a route file without any track,
* with its reader's code.
*
* @txIndependent the row is written once the file was read, in a
* transaction of its own.
@@ -93,7 +120,7 @@ export class AssistantFileAnswers {
return;
}
w.toolOutput(readId, found);
if (proposals.length === 0) {
if (proposals.length === 0 && !reader.acknowledges) {
await rows.save([readPart(found)], 'error');
w.finishStep();
w.error(reader.emptyCode);
@@ -101,14 +128,37 @@ export class AssistantFileAnswers {
return;
}
const card = await readTripCard(this.tools, turn.userId, turn.tripId);
const said = reader.acknowledges ? await this.acknowledgement(turn, card, proposals.length, reasonOf(found)) : null;
if (said) w.text(said.line);
const held = proposals.length > 0 ? await this.held(turn, card, read) : NOTHING_HELD;
const tail: AssistantMessagePart[] = said?.chips ? [{ type: 'data-trek-follow-ups', data: said.chips }] : [];
const parts: AssistantMessagePart[] = [
readPart(found),
...(said ? [{ type: 'text' as const, text: said.line }] : []),
...held.parts,
...tail,
];
if (held.held.length > 0) await rows.hold(parts, held.held);
else await rows.save(parts, 'complete');
for (const change of held.held) {
w.toolInput(change.id, change.toolName, held.shown.get(change.id) ?? change.args);
w.approvalRequest(change.id);
w.change(change.preview);
}
if (said?.chips) w.followUps(said.chips);
w.finishStep();
w.finish(held.held.length > 0 ? 'tool-calls' : 'stop');
}
/** The changes the file proposes, held with their cards, and the parts that show them. */
private async held(turn: FileTurn, card: TripCard, read: FileRead) {
const ctx = this.cardContext.contextOf(card, new Map(), turn.locale, todayIn(turn.timeZone, new Date()));
const proposed = proposals.map((proposal) => ({ ...proposal, id: randomUUID() }));
const proposed = read.proposals.map((proposal) => ({ ...proposal, id: randomUUID() }));
// The thread shows a call as the reader shows it; the held call keeps everything it runs with.
const shown = new Map<string, Record<string, unknown>>(proposed.map((c) => [c.id, c.shownArgs ?? c.args]));
const described = await this.cardContext.describeProposed(turn.userId, turn.tripId, ctx, proposed);
const held: HeldCall[] = described.map((change) => ({ ...change, providerCallId: `import_${change.id}` }));
const parts: AssistantMessagePart[] = [
readPart(found),
...held.map((change): AssistantMessagePart => ({
type: 'tool-call',
toolCallId: change.id,
@@ -118,13 +168,36 @@ export class AssistantFileAnswers {
})),
...held.map((change): AssistantMessagePart => ({ type: 'data-trek-change', data: change.preview })),
];
await rows.hold(parts, held);
for (const change of held) {
w.toolInput(change.id, change.toolName, shown.get(change.id) ?? change.args);
w.approvalRequest(change.id);
w.change(change.preview);
}
w.finishStep();
w.finish('tool-calls');
return { held, parts, shown };
}
/** The answer's line and its chips, in the user's language; no chips when nothing fits. */
private async acknowledgement(turn: FileTurn, card: TripCard, found: number, reason: BookingReadReason | null) {
const words = await AssistantWords.of(turn.locale);
const facts = await withRequestContext(this.orm, () => this.factsOf(turn, card, found));
const questions = attachChipKeys(facts).map((key) => words.text(key));
return {
line: attachLine(words, turn.name, found, reason),
chips: questions.length > 0 ? { questions } : null,
};
}
/** What the chips are chosen from: the file, and the user's rights on the trip. */
private async factsOf(turn: FileTurn, card: TripCard, found: number): Promise<AttachFacts> {
const { userId, tripId } = turn;
const [upload, edit, book, allowed] = await Promise.all([
this.guards.hasTripPermission('file_upload', tripId, userId),
this.guards.hasTripPermission('file_edit', tripId, userId),
this.guards.hasTripPermission('reservation_edit', tripId, userId),
this.allowedTypes.get(),
]);
return {
found,
readable: turn.textStatus === 'ok',
canKeep: upload && isUploadTypeAllowed(turn.name, turn.mime, allowed),
canLink: edit,
hasTargets: hasLinkTargets(card),
canBook: book,
};
}
}
@@ -1,6 +1,6 @@
import { localeTable, supportedLocale } from './assistant-words';
import { recordOf, type Row } from './cards/card-values';
import { haversineMetres } from '@trek/shared';
import { SUPPORTED_LANGUAGE_CODES } from '@trek/shared/i18n';
/**
* "Plan this" on a paddle or ski plan an answer showed (plan_paddle_route,
@@ -104,29 +104,11 @@ const TYPE_WORD_KEYS: Readonly<Record<SportPlanTool, string>> = {
plan_ski_route: 'tourTypes.ski',
};
/** The words of one locale's table, or none when it cannot be read. */
async function wordsOf(language: string): Promise<Record<string, unknown>> {
try {
// A supported code only, so the path is one of the package's own locale entries.
const loaded: unknown = await import(`@trek/shared/i18n/${language}`);
const words = (loaded as { default?: unknown } | null)?.default;
return words !== null && typeof words === 'object' ? (words as Record<string, unknown>) : {};
} catch {
return {};
}
}
/** A plan's tour type in the user's language ("Paddeltour"), English where the language has no table. */
export async function tourTypeWord(locale: string, toolName: SportPlanTool): Promise<string> {
const language = locale.split('-')[0] ?? 'en';
const code = SUPPORTED_LANGUAGE_CODES.includes(locale)
? locale
: SUPPORTED_LANGUAGE_CODES.includes(language)
? language
: 'en';
const key = TYPE_WORD_KEYS[toolName];
const own = (await wordsOf(code))[key];
const own = (await localeTable(supportedLocale(locale)))[key];
if (typeof own === 'string') return own;
const english = (await wordsOf('en'))[key];
const english = (await localeTable('en'))[key];
return typeof english === 'string' ? english : 'Tour';
}
@@ -40,6 +40,7 @@ function trackFact(track: TourFileTrack) {
export class AssistantTourFileService implements AttachedFileReader {
readonly readTool = READ_TOUR_FILE_TOOL;
readonly emptyCode = 'no_tracks_found' as const;
readonly acknowledges = false;
constructor(
private readonly files: TourFileReadService,
@@ -0,0 +1,64 @@
import { resolvePluralKey } from '@trek/shared';
import { getIntlLanguage, SUPPORTED_LANGUAGE_CODES } from '@trek/shared/i18n';
/**
* The few words the assistant writes itself, without a model (the line that
* answers an attached file, the chips under it, a tour type's name), in the
* user's language from the shared locale tables, English where a table has
* no such key.
*/
type Table = Readonly<Record<string, unknown>>;
/** The supported code a request's locale reads as: itself, its language, or English. */
export function supportedLocale(locale: string): string {
if (SUPPORTED_LANGUAGE_CODES.includes(locale)) return locale;
const language = locale.split('-')[0] ?? 'en';
return SUPPORTED_LANGUAGE_CODES.includes(language) ? language : 'en';
}
/** The words of one locale's table, or none when it cannot be read. */
export async function localeTable(code: string): Promise<Table> {
try {
// A supported code only, so the path is one of the package's own locale entries.
const loaded: unknown = await import(`@trek/shared/i18n/${code}`);
const words = (loaded as { default?: unknown } | null)?.default;
return words !== null && typeof words === 'object' ? (words as Table) : {};
} catch {
return {};
}
}
function filled(text: string, params: Readonly<Record<string, string | number>>): string {
return text.replace(/\{(\w+)\}/g, (whole, name: string) => (name in params ? String(params[name]) : whole));
}
/** One locale's words, with English behind them. */
export class AssistantWords {
private constructor(
private readonly code: string,
private readonly own: Table,
private readonly english: Table,
) {}
static async of(locale: string): Promise<AssistantWords> {
const code = supportedLocale(locale);
const [own, english] = await Promise.all([localeTable(code), code === 'en' ? null : localeTable('en')]);
return new AssistantWords(code, own, english ?? own);
}
/** The string under `key` with its params filled in; the key itself where no table has it. */
text(key: string, params: Readonly<Record<string, string | number>> = {}): string {
const value = this.own[key] ?? this.english[key];
return filled(typeof value === 'string' ? value : key, params);
}
/** The form of a count-bearing string the language picks for `count`, with `count` among its params. */
count(key: string, count: number, params: Readonly<Record<string, string | number>> = {}): string {
const all = { ...params, count };
const own = resolvePluralKey(this.own, key, count, getIntlLanguage(this.code));
if (own) return filled(String(this.own[own]), all);
const english = resolvePluralKey(this.english, key, count, 'en');
return english ? filled(String(this.english[english]), all) : key;
}
}
@@ -9,6 +9,7 @@ import { AuditModule } from '../audit/audit.module';
import { BookingImportModule } from '../booking-import/booking-import.module';
import { CollabModule } from '../collab/collab.module';
import { RateLimitModule } from '../common/rate-limit.module';
import { AllowedFileTypesModule } from '../files/allowed-file-types.module';
import { JourneyBookModule } from '../journey/journey-book.module';
import { JourneyDomainModule } from '../journey/journey-domain.module';
import { LlmParseModule } from '../llm-parse/llm-parse.module';
@@ -92,6 +93,8 @@ import { Module } from '@nestjs/common';
// AI import reads it.
StorageModule,
LlmParseModule,
// The chips under the answer offer to keep a file only where Files takes its type.
AllowedFileTypesModule,
MikroOrmModule.forFeature([AssistantThreads, AssistantMessages, AssistantToolCalls, AssistantAttachments]),
],
controllers: [
+12 -1
View File
@@ -312,7 +312,18 @@ export class AssistantService {
const stopKeepalive = armKeepalive(stream);
try {
const { locale, timeZone } = req;
const turn = { userId, tripId, threadId: begun.threadId, rowId: begun.rowId, locale, timeZone, name };
const { threadId, rowId } = begun;
const turn = {
userId,
tripId,
threadId,
rowId,
locale,
timeZone,
name,
mime: kept.mime,
textStatus: kept.textStatus,
};
await this.fileAnswers.answer(turn, file, reader, { w, signal, rows: this.answerRows(turn) });
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);