mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-21 11:36:05 +00:00
feat(tours): assistant takes found places into saved tours and route files from the chat
P6: insert_tour_stop and remove_tour_stop take a place into a saved hike or city walk as one stop and out again, each the other's undo, with change cards in the chat. The planner's insertion rule (poiInsertion) moved to shared so the planner and the server place a stop the same way. "+ Tour" on a found place holds it as a stop of the saved tour open in the planner. P7: GPX, KML and KMZ files attached in the chat are read into their tracks and each is held as a change that takes it in as a hike through import_tour_gpx, undoable per track; the GPX text stays on the held call.
This commit is contained in:
@@ -64,6 +64,7 @@ const REFUSAL_STATUS: Record<AiRefusalCode, number> = {
|
||||
empty_answer: 502,
|
||||
offline: 503,
|
||||
no_bookings_found: 422,
|
||||
no_tracks_found: 422,
|
||||
import_unavailable: 503,
|
||||
decide_first: 409,
|
||||
too_many_requests: 429,
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { AssistantErrorCode } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* A file the user attaches in the trip chat is read by the server itself,
|
||||
* not by the model: a booking file into bookings, a route file into tracks
|
||||
* (P7). Each kind of file has its reader; AssistantService.attach runs it the
|
||||
* same way for every kind: the read step as a call of its own, then one held
|
||||
* change per thing the file holds, decided like any other change.
|
||||
*/
|
||||
|
||||
/** One change a file proposes: the server's write it is held as, and its arguments. */
|
||||
export interface FileProposal {
|
||||
toolName: string;
|
||||
/** What the change runs with, kept on the held call only. */
|
||||
args: Record<string, unknown>;
|
||||
/**
|
||||
* What the message shows of the call where that is less than it runs with
|
||||
* (a GPX text stays on the held call, out of the thread and the history).
|
||||
*/
|
||||
shownArgs?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** What reading a file found: the read step's answer, and the changes it proposes. */
|
||||
export interface FileRead {
|
||||
found: Record<string, unknown>;
|
||||
proposals: FileProposal[];
|
||||
}
|
||||
|
||||
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. */
|
||||
readonly emptyCode: AssistantErrorCode;
|
||||
/** 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. */
|
||||
propose(userId: number, tripId: number, file: Express.Multer.File): Promise<FileRead>;
|
||||
}
|
||||
@@ -23,13 +23,13 @@ import {
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { LLM_PHOTO_EXTENSIONS } from '@trek/shared';
|
||||
import { ASSISTANT_TOUR_FILE_EXTENSIONS, LLM_PHOTO_EXTENSIONS } from '@trek/shared';
|
||||
|
||||
import type { Response } from 'express';
|
||||
import { memoryStorage } from 'multer';
|
||||
import { extname } from 'node:path';
|
||||
|
||||
/** What the assistant reads bookings from: the booking import's formats, plus calendar files. */
|
||||
/** What the assistant reads: the booking import's formats, calendar files, and route files taken in as tours (P7). */
|
||||
const ACCEPTED_EXTENSIONS: ReadonlySet<string> = new Set([
|
||||
'.eml',
|
||||
'.pdf',
|
||||
@@ -39,10 +39,11 @@ const ACCEPTED_EXTENSIONS: ReadonlySet<string> = new Set([
|
||||
'.htm',
|
||||
'.txt',
|
||||
...LLM_PHOTO_EXTENSIONS,
|
||||
...ASSISTANT_TOUR_FILE_EXTENSIONS,
|
||||
]);
|
||||
|
||||
const PHOTO_LABEL = LLM_PHOTO_EXTENSIONS.map((ext) => ext.slice(1).toUpperCase()).join(', ');
|
||||
const ACCEPTED_LABEL = `EML, PDF, PKPass, ICS, HTML, TXT, ${PHOTO_LABEL}`;
|
||||
const ACCEPTED_LABEL = `EML, PDF, PKPass, ICS, HTML, TXT, ${PHOTO_LABEL}, GPX, KML, KMZ`;
|
||||
|
||||
const UPLOAD = {
|
||||
storage: memoryStorage(),
|
||||
|
||||
@@ -3,7 +3,8 @@ import { BookingImportService } from '../booking-import/booking-import.service';
|
||||
import { DemoService } from '../common/demo.service';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { TripAccessService } from '../trip-membership/trip-access.service';
|
||||
import { MAX_WRITES_PER_STEP } from './assistant-tools.constants';
|
||||
import type { AttachedFileReader, FileRead } from './assistant-attached-file';
|
||||
import { IMPORT_BOOKING_TOOL, MAX_WRITES_PER_STEP, READ_BOOKING_FILE_TOOL } from './assistant-tools.constants';
|
||||
import type { ToolRun } from './assistant-tools.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { bookingImportPreviewItemSchema, LLM_PHOTO_EXTENSIONS, type BookingImportPreviewItem } from '@trek/shared';
|
||||
@@ -24,7 +25,10 @@ const BROKEN = 'This booking can no longer be read.';
|
||||
* and the `reservation_edit` right, taken when it is applied.
|
||||
*/
|
||||
@Injectable()
|
||||
export class AssistantBookingImportService {
|
||||
export class AssistantBookingImportService implements AttachedFileReader {
|
||||
readonly readTool = READ_BOOKING_FILE_TOOL;
|
||||
readonly emptyCode = 'no_bookings_found' as const;
|
||||
|
||||
constructor(
|
||||
private readonly bookingImport: BookingImportService,
|
||||
private readonly trips: TripAccessService,
|
||||
@@ -58,6 +62,15 @@ export class AssistantBookingImportService {
|
||||
return preview.items.slice(0, MAX_WRITES_PER_STEP);
|
||||
}
|
||||
|
||||
/** The bookings of the file as the changes the chat holds, one import_booking each. */
|
||||
async propose(userId: number, _tripId: number, file: Express.Multer.File): Promise<FileRead> {
|
||||
const items = await this.read(userId, file);
|
||||
return {
|
||||
found: { bookings: items.map((item) => item.title) },
|
||||
proposals: items.map((item) => ({ toolName: IMPORT_BOOKING_TOOL, args: item as Record<string, unknown> })),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the booking the user applied, from the arguments the server stored
|
||||
* when it proposed it. The answer is shaped like a tool's: the created
|
||||
|
||||
@@ -33,13 +33,17 @@ import { AssistantStreamRegistry } from './assistant-stream.registry';
|
||||
import { ADD_FOUND_PLACE_TOOL, TURNS_PER_MINUTE } from './assistant-tools.constants';
|
||||
import { AssistantToolsService } from './assistant-tools.service';
|
||||
import { AssistantCardContext } from './cards/card-context';
|
||||
import { recordOf } from './cards/card-values';
|
||||
import { defaultAfterKeyOf } from './cards/tour/tour-stop.cards';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
categoryIdForKind,
|
||||
TOUR_STOP_TYPES,
|
||||
type AssistantAddFoundPlaceRequest,
|
||||
type AssistantAddFoundPlaceResponse,
|
||||
type AssistantFoundPlace,
|
||||
type AssistantInsertFoundPlaceRequest,
|
||||
type AssistantMessage,
|
||||
type AssistantMessagePart,
|
||||
} from '@trek/shared';
|
||||
@@ -47,7 +51,22 @@ import {
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
/** What a suggestion reads of the trip: its days and places, and the categories a new place is filed in. */
|
||||
const TRIP_READS: ReadonlySet<string> = new Set(['get_trip_summary', 'list_places', 'list_categories']);
|
||||
const TRIP_READS: ReadonlySet<string> = new Set([
|
||||
'get_trip_summary',
|
||||
'list_places',
|
||||
'list_categories',
|
||||
'get_tour_plan',
|
||||
]);
|
||||
|
||||
/** The tour types a found place is taken into as a stop ("+ Tour"), as insert_tour_stop takes them. */
|
||||
const STOP_TOURS: ReadonlySet<unknown> = new Set(TOUR_STOP_TYPES);
|
||||
|
||||
/** What a suggestion reads of the trip: its card, its categories and, for "+ Tour", the tour. */
|
||||
interface TripRead {
|
||||
card: TripCard;
|
||||
categories: CardCategory[];
|
||||
tour: unknown;
|
||||
}
|
||||
|
||||
/** Message rows searched for the place a suggestion names; the history a turn sends the provider. */
|
||||
const SEARCHED_ROWS = 40;
|
||||
@@ -104,6 +123,38 @@ function suggestionArgs(
|
||||
};
|
||||
}
|
||||
|
||||
/** What either suggestion names: the place by its ref, and the user's language and zone for its card. */
|
||||
type SuggestionRequest = Pick<AssistantAddFoundPlaceRequest, 'ref' | 'locale' | 'timeZone'>;
|
||||
|
||||
/** The arguments a suggestion holds, from the place and what was read of the trip; throws to refuse. */
|
||||
type ArgsOf = (place: AssistantFoundPlace, trip: TripRead) => Record<string, unknown>;
|
||||
|
||||
/**
|
||||
* The arguments a found place is taken into a saved tour with ("+ Tour"):
|
||||
* insert_tour_stop's, against the revision read now, after the last point
|
||||
* before the place along the way, with the tour's name for the history. A
|
||||
* tour of another trip, one not read, or one of a type that takes no stop
|
||||
* here is refused.
|
||||
*/
|
||||
export function stopArgs(place: AssistantFoundPlace, tourId: number, read: unknown): Record<string, unknown> {
|
||||
const plan = recordOf(read);
|
||||
const tour = recordOf(plan.tour);
|
||||
if (tour.place_id !== tourId || typeof tour.revision !== 'number') {
|
||||
throw aiRefusal('generic', 'Tour not found in this trip');
|
||||
}
|
||||
if (!STOP_TOURS.has(tour.tour_type)) throw aiRefusal('generic', 'Only a hike or a city walk takes a stop here');
|
||||
const spot = { lat: place.lat, lng: place.lng };
|
||||
const afterKey = defaultAfterKeyOf(plan, spot);
|
||||
return {
|
||||
via: 'insert_tour_stop',
|
||||
placeId: tourId,
|
||||
expected_revision: tour.revision,
|
||||
stop: { ...spot, name: place.name },
|
||||
...(afterKey ? { after_key: afterKey } : {}),
|
||||
tourName: typeof tour.name === 'string' ? tour.name : '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* "+ Day 3" on a place a search found: the place is proposed for the day as a
|
||||
* change card, held and decided like one the model proposed, but without a
|
||||
@@ -137,6 +188,39 @@ export class AssistantFoundPlacesService {
|
||||
tripId: number,
|
||||
threadId: number,
|
||||
req: AssistantAddFoundPlaceRequest,
|
||||
): Promise<AssistantAddFoundPlaceResponse> {
|
||||
return this.hold(userId, tripId, threadId, req, null, (place, trip) => {
|
||||
if (!trip.card.days.some((day) => day.id === req.dayId)) throw aiRefusal('generic', 'Day not found in this trip');
|
||||
return suggestionArgs(place, req.dayId, trip.card, trip.categories);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* "+ Tour" on a place a search found, while a saved hike or city walk is
|
||||
* open in the planner: the place is proposed as a stop of that tour, after
|
||||
* the last point before it along the way, against the revision the tour has
|
||||
* now. Held and decided like "+ Day 3"; applying it runs insert_tour_stop
|
||||
* with the user's own rights, which checks the tour again.
|
||||
*/
|
||||
async insertIntoTour(
|
||||
userId: number,
|
||||
tripId: number,
|
||||
threadId: number,
|
||||
req: AssistantInsertFoundPlaceRequest,
|
||||
): Promise<AssistantAddFoundPlaceResponse> {
|
||||
return this.hold(userId, tripId, threadId, req, req.tourId, (place, trip) =>
|
||||
stopArgs(place, req.tourId, trip.tour),
|
||||
);
|
||||
}
|
||||
|
||||
/** Holds the change `argsOf` builds for a found place, under the rules both suggestions share. */
|
||||
private async hold(
|
||||
userId: number,
|
||||
tripId: number,
|
||||
threadId: number,
|
||||
req: SuggestionRequest,
|
||||
tourId: number | null,
|
||||
argsOf: ArgsOf,
|
||||
): Promise<AssistantAddFoundPlaceResponse> {
|
||||
if (!(await this.threads.findOwned(threadId, userId, tripId))) {
|
||||
throw aiRefusal('not_found', 'Conversation not found');
|
||||
@@ -149,7 +233,7 @@ export class AssistantFoundPlacesService {
|
||||
throw aiRefusal('busy', 'The assistant is already answering in another window');
|
||||
}
|
||||
try {
|
||||
await this.propose(userId, tripId, threadId, req);
|
||||
await this.propose(userId, tripId, threadId, req, tourId, argsOf);
|
||||
} finally {
|
||||
await this.streams.release(userId, controller);
|
||||
}
|
||||
@@ -160,20 +244,21 @@ export class AssistantFoundPlacesService {
|
||||
userId: number,
|
||||
tripId: number,
|
||||
threadId: number,
|
||||
req: AssistantAddFoundPlaceRequest,
|
||||
req: SuggestionRequest,
|
||||
tourId: number | null,
|
||||
argsOf: ArgsOf,
|
||||
): Promise<void> {
|
||||
if ((await this.toolCalls.listOpen(threadId)).length > 0) {
|
||||
throw aiRefusal('decide_first', 'Decide on the changes that are waiting first');
|
||||
}
|
||||
const place = foundPlace(await this.messages.listLatest(threadId, SEARCHED_ROWS), req.ref);
|
||||
if (!place) throw aiRefusal('generic', 'This place is not among the search results of the conversation');
|
||||
const { card, categories } = await this.tripOf(userId, tripId);
|
||||
if (!card.days.some((day) => day.id === req.dayId)) throw aiRefusal('generic', 'Day not found in this trip');
|
||||
const trip = await this.tripOf(userId, tripId, tourId);
|
||||
const args = argsOf(place, trip);
|
||||
|
||||
const id = randomUUID();
|
||||
const args = suggestionArgs(place, req.dayId, card, categories);
|
||||
const names = new Map(categories.map((category): [number, string] => [category.id, category.name]));
|
||||
const ctx = this.cardContext.contextOf(card, names, req.locale, todayIn(req.timeZone, new Date()));
|
||||
const names = new Map(trip.categories.map((category): [number, string] => [category.id, category.name]));
|
||||
const ctx = this.cardContext.contextOf(trip.card, names, req.locale, todayIn(req.timeZone, new Date()));
|
||||
const [{ preview }] = await this.cardContext.describeProposed(userId, tripId, ctx, [
|
||||
{ id, toolName: ADD_FOUND_PLACE_TOOL, args },
|
||||
]);
|
||||
@@ -208,16 +293,21 @@ export class AssistantFoundPlacesService {
|
||||
});
|
||||
}
|
||||
|
||||
/** The trip card and the categories, read through the trip tools with the user's rights. */
|
||||
private async tripOf(userId: number, tripId: number): Promise<{ card: TripCard; categories: CardCategory[] }> {
|
||||
/**
|
||||
* The trip card and the categories, read through the trip tools with the
|
||||
* user's rights, and with `tourId` the saved tour a stop goes into.
|
||||
*/
|
||||
private async tripOf(userId: number, tripId: number, tourId: number | null): Promise<TripRead> {
|
||||
const session = await this.tools.open(userId, tripId, TRIP_READS);
|
||||
try {
|
||||
const summary = await session.read('get_trip_summary');
|
||||
const places = await session.read('list_places');
|
||||
const listed = await session.read('list_categories');
|
||||
const tour = tourId === null ? null : await session.read('get_tour_plan', { placeId: tourId });
|
||||
return {
|
||||
card: buildTripCard(tripId, userId, summary.ok ? summary.value : null, places.ok ? places.value : null, null),
|
||||
categories: categoriesFrom(listed.ok ? listed.value : null),
|
||||
tour: tour?.ok ? tour.value : null,
|
||||
};
|
||||
} finally {
|
||||
await session.close();
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { AssistantMessagePart } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The server's own tour steps as the model is told of them (P6, P7): a found
|
||||
* place the user took into a tour with "+ Tour", a route file read, a track
|
||||
* of it taken in. Like the booking file's notes in assistant-history.ts, in
|
||||
* plain words, since none of them is a call the model made.
|
||||
*/
|
||||
|
||||
type ToolCallPart = Extract<AssistantMessagePart, { type: 'tool-call' }>;
|
||||
|
||||
function quoted(value: unknown): string {
|
||||
return `"${typeof value === 'string' && value !== '' ? value : '?'}"`;
|
||||
}
|
||||
|
||||
/** What became of a decided change, in the words of what it was. */
|
||||
function decided(part: ToolCallPart, what: string, done: string, waiting: string): string {
|
||||
if (part.approval?.approved === true) return part.isError ? `${what} could not be ${done}.` : `${what} was ${done}.`;
|
||||
if (part.approval?.approved === false) return `The user discarded ${what}.`;
|
||||
if (part.approval?.resolution) return `${what} was not ${done}; the user moved on without deciding.`;
|
||||
return waiting;
|
||||
}
|
||||
|
||||
/** A found place the user took into a saved tour as a stop. */
|
||||
export function tourStopOutcome(part: ToolCallPart): string {
|
||||
const stop = part.args.stop && typeof part.args.stop === 'object' ? (part.args.stop as Record<string, unknown>) : {};
|
||||
const what = `${quoted(stop.name)} as a stop of the tour ${quoted(part.args.tourName)}`;
|
||||
const waiting = `The user picked ${what} from the search results; it waits for them to add or discard it.`;
|
||||
return decided(part, what, 'added', waiting);
|
||||
}
|
||||
|
||||
/** A route file read into its tracks. */
|
||||
export function tourFileReadNote(part: ToolCallPart): string {
|
||||
const file = quoted(part.args.name);
|
||||
if (part.isError) return `TREK could not read the attached route file ${file}.`;
|
||||
const result = (part.result ?? {}) as { tracks?: unknown };
|
||||
const tracks = Array.isArray(result.tracks) ? result.tracks : [];
|
||||
if (tracks.length === 0) return `TREK read the attached route file ${file} and found no track or route in it.`;
|
||||
return `TREK read the attached route file ${file} and found ${tracks.length} track(s): ${JSON.stringify(tracks)}.`;
|
||||
}
|
||||
|
||||
/** One track of a route file taken in as a hike. */
|
||||
export function tourFileOutcome(part: ToolCallPart): string {
|
||||
const what = `The track ${quoted(part.args.track_name)} of ${quoted(part.args.file_name)}`;
|
||||
const waiting = `${what} waits for the user to take it in as a hike or discard it.`;
|
||||
return decided(part, what, 'taken in as a hike', waiting);
|
||||
}
|
||||
@@ -4,13 +4,16 @@ import type { AssistantToolCallRow } from '../../db/repositories/AssistantToolCa
|
||||
import { parseDbTimestamp, utcSuffix } from '../../db/types';
|
||||
import { decodeJson } from '../../utils/json-column';
|
||||
import type { AiChatMessage, AiToolCall } from '../ai-connections/ai-chat-client.interface';
|
||||
import { tourFileOutcome, tourFileReadNote, tourStopOutcome } from './assistant-history-tours';
|
||||
import { fitToSize } from './assistant-output';
|
||||
import {
|
||||
ADD_FOUND_PLACE_TOOL,
|
||||
APPROVAL_TTL_MS,
|
||||
ASSISTANT_SERVER_TOOLS,
|
||||
IMPORT_BOOKING_TOOL,
|
||||
IMPORT_TOUR_FILE_TOOL,
|
||||
READ_BOOKING_FILE_TOOL,
|
||||
READ_TOUR_FILE_TOOL,
|
||||
TAKE_PROPOSAL_TOOL,
|
||||
} from './assistant-tools.constants';
|
||||
import {
|
||||
@@ -115,6 +118,14 @@ function takenProposalOutcome(part: ToolCallPart): string {
|
||||
return `The user took the proposed ${what} ${name} to add it; it waits for them to add or discard it.`;
|
||||
}
|
||||
|
||||
/** The note of a server step about tours (P6, P7), null for any other. */
|
||||
function tourStepNote(part: ToolCallPart): string | null {
|
||||
if (part.toolName === ADD_FOUND_PLACE_TOOL && part.args.via === 'insert_tour_stop') return tourStopOutcome(part);
|
||||
if (part.toolName === READ_TOUR_FILE_TOOL) return tourFileReadNote(part);
|
||||
if (part.toolName === IMPORT_TOUR_FILE_TOOL) return tourFileOutcome(part);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The server's own steps of a message (reading an attached file, the bookings
|
||||
* it found) as one note in plain words. They are no tools the provider knows,
|
||||
@@ -124,7 +135,10 @@ function takenProposalOutcome(part: ToolCallPart): string {
|
||||
export function serverStepsNote(calls: readonly ToolCallPart[]): string {
|
||||
const lines: string[] = [];
|
||||
for (const part of calls) {
|
||||
if (part.toolName === READ_BOOKING_FILE_TOOL) {
|
||||
const tourNote = tourStepNote(part);
|
||||
if (tourNote !== null) {
|
||||
lines.push(tourNote);
|
||||
} else if (part.toolName === READ_BOOKING_FILE_TOOL) {
|
||||
const result = (part.result ?? {}) as { bookings?: unknown };
|
||||
const titles = Array.isArray(result.bookings) ? result.bookings.map(quoted) : [];
|
||||
const file = quoted(part.args.name);
|
||||
|
||||
@@ -245,6 +245,7 @@ const CORE_TOOL_GROUPS: ToolGroups = {
|
||||
'TourActivitiesMcp',
|
||||
'TourActivityStatsMcp',
|
||||
'TourWalkImportMcp',
|
||||
'TourStopsMcp',
|
||||
'CollectionToursMcp',
|
||||
'PaddleRoutingMcp',
|
||||
'SkiRoutingMcp',
|
||||
|
||||
@@ -112,6 +112,18 @@ export const READ_BOOKING_FILE_TOOL = 'read_booking_file';
|
||||
/** A booking read from an attached file, held as a change card like any write. */
|
||||
export const IMPORT_BOOKING_TOOL = 'import_booking';
|
||||
|
||||
/**
|
||||
* P7: the step that reads a route file the user attached (GPX, KML, KMZ),
|
||||
* run by the server itself like the booking read, and each track or route it
|
||||
* found held as a change that takes it in as a tour through the model's
|
||||
* import_tour_gpx, named in its `via` argument.
|
||||
*/
|
||||
export const READ_TOUR_FILE_TOOL = 'read_tour_file';
|
||||
export const IMPORT_TOUR_FILE_TOOL = 'import_tour_file';
|
||||
|
||||
/** What a held track of a route file runs as. */
|
||||
const TOUR_FILE_VIA = 'import_tour_gpx';
|
||||
|
||||
/**
|
||||
* A place from the search results of an answer, suggested for a day by the
|
||||
* user ("+ Day 3"). Held as a change card like any write, without a model turn.
|
||||
@@ -143,7 +155,12 @@ export const REMEMBER_TOOL = 'remember_for_trip';
|
||||
export const PREVIEW_BOOK_PAGE_TOOL = 'preview_book_page';
|
||||
|
||||
/** The model's tools a found place is added through: a new place for the day, or one the trip has already. */
|
||||
const FOUND_PLACE_VIA: ReadonlySet<string> = new Set(['create_and_assign_place', 'assign_place_to_day']);
|
||||
const FOUND_PLACE_VIA: ReadonlySet<string> = new Set([
|
||||
'create_and_assign_place',
|
||||
'assign_place_to_day',
|
||||
// "+ Tour": the place taken into the saved tour open in the planner as a stop (P6).
|
||||
'insert_tour_stop',
|
||||
]);
|
||||
|
||||
/** The model's tools a taken proposal is created through: a hike, a bike tour or a run, a city walk, a paddle or ski tour, a wanderer trail imported. */
|
||||
const PROPOSAL_VIA: ReadonlySet<string> = new Set([
|
||||
@@ -166,6 +183,7 @@ const PROPOSAL_VIA: ReadonlySet<string> = new Set([
|
||||
*/
|
||||
export const ASSISTANT_SERVER_WRITE_TOOLS: Readonly<Record<string, AssistantWriteTool>> = {
|
||||
[IMPORT_BOOKING_TOOL]: { verbKey: 'importBooking', entity: 'reservation' },
|
||||
[IMPORT_TOUR_FILE_TOOL]: { verbKey: 'importTour', entity: 'tour' },
|
||||
// The card names the verb of the `via` tool; these are its fallbacks.
|
||||
[ADD_FOUND_PLACE_TOOL]: { verbKey: 'addPlaceToDay', entity: 'place', quiet: true },
|
||||
[TAKE_PROPOSAL_TOOL]: { verbKey: 'addTour', entity: 'tour', quiet: true },
|
||||
@@ -182,12 +200,22 @@ export function writeToolOf(toolName: string, args: Record<string, unknown>): st
|
||||
const via = typeof args.via === 'string' ? args.via : '';
|
||||
if (toolName === ADD_FOUND_PLACE_TOOL) return FOUND_PLACE_VIA.has(via) ? via : toolName;
|
||||
if (toolName === TAKE_PROPOSAL_TOOL) return PROPOSAL_VIA.has(via) ? via : toolName;
|
||||
if (toolName === IMPORT_TOUR_FILE_TOOL) return via === TOUR_FILE_VIA ? via : toolName;
|
||||
return toolName;
|
||||
}
|
||||
|
||||
/** The arguments a found place or a taken proposal runs its `via` tool with: what that tool takes, nothing else. */
|
||||
export function foundPlaceArgs(args: Record<string, unknown>): Record<string, unknown> {
|
||||
if (args.via === 'assign_place_to_day') return { dayId: args.dayId, placeId: args.placeId };
|
||||
if (args.via === TOUR_FILE_VIA) {
|
||||
// The track's own name stays with the card; the import takes the file's text, its name and the type.
|
||||
const { gpx, file_name, tour_type } = args;
|
||||
return { gpx, ...(file_name !== undefined ? { file_name } : {}), tour_type };
|
||||
}
|
||||
if (args.via === 'insert_tour_stop') {
|
||||
const { placeId, expected_revision, stop, after_key } = args;
|
||||
return { placeId, expected_revision, stop, ...(after_key !== undefined ? { after_key } : {}) };
|
||||
}
|
||||
const { via: _via, ...rest } = args;
|
||||
return rest;
|
||||
}
|
||||
@@ -195,6 +223,7 @@ export function foundPlaceArgs(args: Record<string, unknown>): Record<string, un
|
||||
/** Calls the server makes on its own: replayed to the model as a note, never as a call of an unknown tool. */
|
||||
export const ASSISTANT_SERVER_TOOLS: ReadonlySet<string> = new Set([
|
||||
READ_BOOKING_FILE_TOOL,
|
||||
READ_TOUR_FILE_TOOL,
|
||||
...Object.keys(ASSISTANT_SERVER_WRITE_TOOLS),
|
||||
]);
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { aiRefusal } from '../ai-connections/ai-connections.constants';
|
||||
import { TourFileReadService, type TourFileTrack } from '../tours/tour-file-read.service';
|
||||
import type { AttachedFileReader, FileProposal, FileRead } from './assistant-attached-file';
|
||||
import { IMPORT_TOUR_FILE_TOOL, MAX_WRITES_PER_STEP, READ_TOUR_FILE_TOOL } from './assistant-tools.constants';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
/** The longest file name an import keeps, as import_tour_gpx takes it. */
|
||||
const FILE_NAME_CHARS = 200;
|
||||
|
||||
/** Kilometres to a hundred metres: enough for the model to tell the tracks apart. */
|
||||
function roundedKm(km: number): number {
|
||||
return Math.round(km * 10) / 10;
|
||||
}
|
||||
|
||||
/** A track as the read step tells the model of it: what it is, and why it is not proposed where it is not. */
|
||||
function trackFact(track: TourFileTrack) {
|
||||
return {
|
||||
name: track.name,
|
||||
distance_km: roundedKm(track.distance_km),
|
||||
points: track.point_count,
|
||||
has_heights: track.has_heights,
|
||||
...(track.duplicate ? { skipped: 'already_in_trip' } : {}),
|
||||
...(track.gpx === null ? { skipped: 'too_large' } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* P7: a GPX, KML or KMZ file the user attached in the trip chat, read into
|
||||
* its tracks and routes (TourFileReadService, the Tours import's reader) and
|
||||
* proposed as one held change per track, which takes it in as a hike through
|
||||
* import_tour_gpx with the user's rights when they apply it (the type can be
|
||||
* changed in the planner, or by asking the assistant afterwards). A track the
|
||||
* trip has already, or one longer than one import takes, is named in the read
|
||||
* step and not proposed. Only the held call keeps the track's GPX text; the
|
||||
* thread shows its name and the file's.
|
||||
*/
|
||||
@Injectable()
|
||||
export class AssistantTourFileService implements AttachedFileReader {
|
||||
readonly readTool = READ_TOUR_FILE_TOOL;
|
||||
readonly emptyCode = 'no_tracks_found' as const;
|
||||
|
||||
constructor(
|
||||
private readonly files: TourFileReadService,
|
||||
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))) {
|
||||
throw aiRefusal('import_unavailable', 'Tours are not enabled on this server');
|
||||
}
|
||||
}
|
||||
|
||||
async propose(_userId: number, tripId: number, file: Express.Multer.File): Promise<FileRead> {
|
||||
const read = await this.files.read(tripId, file.buffer, file.originalname);
|
||||
const fileName = file.originalname.trim().slice(0, FILE_NAME_CHARS) || 'import.gpx';
|
||||
const taken = read.tracks.filter((track) => !track.duplicate && track.gpx !== null).slice(0, MAX_WRITES_PER_STEP);
|
||||
const proposals = taken.map((track): FileProposal => {
|
||||
const shown = { via: 'import_tour_gpx', file_name: fileName, tour_type: 'hike', track_name: track.name };
|
||||
return { toolName: IMPORT_TOUR_FILE_TOOL, args: { ...shown, gpx: track.gpx }, shownArgs: shown };
|
||||
});
|
||||
return {
|
||||
found: {
|
||||
tracks: read.tracks.map(trackFact),
|
||||
// A GPX file that could not be cut into its tracks comes in as one import of all of them.
|
||||
...(read.whole ? { whole_file: true } : {}),
|
||||
...(read.left_out ? { left_out: read.left_out } : {}),
|
||||
...(read.tracks.length > taken.length ? { proposed: taken.length } : {}),
|
||||
},
|
||||
proposals,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
AssistantAddFoundPlaceDto,
|
||||
AssistantChatDto,
|
||||
AssistantDecisionsDto,
|
||||
AssistantInsertFoundPlaceDto,
|
||||
AssistantShareDto,
|
||||
AssistantStopDto,
|
||||
AssistantTakeProposalDto,
|
||||
@@ -133,6 +134,23 @@ export class AssistantController {
|
||||
return this.foundPlaces.add(user.id, Number(tripId), idParam(threadId), body);
|
||||
}
|
||||
|
||||
/**
|
||||
* "+ Tour" on a place a search found, while a saved tour is open: a change card that takes it in as a
|
||||
* stop, no model turn. It changes a tour, so it asks for the right the tour routes ask for.
|
||||
*/
|
||||
@Post('threads/:threadId/found-places/tour')
|
||||
@HttpCode(200)
|
||||
@RequirePermission('place_edit')
|
||||
@ResponseContract(assistantAddFoundPlaceResponseSchema)
|
||||
insertFoundPlace(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@Param('threadId') threadId: string,
|
||||
@Body() body: AssistantInsertFoundPlaceDto,
|
||||
) {
|
||||
return this.foundPlaces.insertIntoTour(user.id, Number(tripId), idParam(threadId), body);
|
||||
}
|
||||
|
||||
/**
|
||||
* "Plan this" on a hike or a city walk an answer proposed: a change card that creates it, no model turn.
|
||||
* It holds a new tour, so it asks for the right the tour routes ask for.
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
assistantAttachmentRequestSchema,
|
||||
assistantChatRequestSchema,
|
||||
assistantDecisionsRequestSchema,
|
||||
assistantInsertFoundPlaceRequestSchema,
|
||||
assistantRenderUploadRequestSchema,
|
||||
assistantShareRequestSchema,
|
||||
assistantStopRequestSchema,
|
||||
@@ -21,6 +22,7 @@ export class AssistantAddFoundPlaceDto extends createZodDto(assistantAddFoundPla
|
||||
export class AssistantAttachmentDto extends createZodDto(assistantAttachmentRequestSchema) {}
|
||||
export class AssistantChatDto extends createZodDto(assistantChatRequestSchema) {}
|
||||
export class AssistantDecisionsDto extends createZodDto(assistantDecisionsRequestSchema) {}
|
||||
export class AssistantInsertFoundPlaceDto extends createZodDto(assistantInsertFoundPlaceRequestSchema) {}
|
||||
export class AssistantRenderUploadDto extends createZodDto(assistantRenderUploadRequestSchema) {}
|
||||
export class AssistantShareDto extends createZodDto(assistantShareRequestSchema) {}
|
||||
export class AssistantStopDto extends createZodDto(assistantStopRequestSchema) {}
|
||||
|
||||
@@ -15,6 +15,7 @@ import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { PhotoSignalsModule } from '../photos/photo-signals.module';
|
||||
import { SchedulingModule } from '../scheduling/scheduling.module';
|
||||
import { SettingsModule } from '../settings/settings.module';
|
||||
import { TourFilesModule } from '../tours/tour-files.module';
|
||||
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
|
||||
import { AssistantAttachmentsController } from './assistant-attachments.controller';
|
||||
import { AssistantBookContext } from './assistant-book-context';
|
||||
@@ -29,6 +30,7 @@ import { AssistantScopes } from './assistant-scope';
|
||||
import { AssistantShareService } from './assistant-share.service';
|
||||
import { AssistantStreamRegistry, InMemoryAssistantStreamRegistry } from './assistant-stream.registry';
|
||||
import { AssistantToolsService } from './assistant-tools.service';
|
||||
import { AssistantTourFileService } from './assistant-tour-file.service';
|
||||
import { AssistantVision } from './assistant-vision';
|
||||
import { AssistantController } from './assistant.controller';
|
||||
import { AssistantService } from './assistant.service';
|
||||
@@ -74,6 +76,8 @@ import { Module } from '@nestjs/common';
|
||||
SchedulingModule,
|
||||
SettingsModule,
|
||||
TripMembershipModule,
|
||||
// P7: a route file attached in the chat, read into its tracks.
|
||||
TourFilesModule,
|
||||
MikroOrmModule.forFeature([AssistantThreads, AssistantMessages, AssistantToolCalls]),
|
||||
],
|
||||
controllers: [
|
||||
@@ -89,6 +93,7 @@ import { Module } from '@nestjs/common';
|
||||
AssistantService,
|
||||
AssistantToolsService,
|
||||
AssistantBookingImportService,
|
||||
AssistantTourFileService,
|
||||
AssistantFoundPlacesService,
|
||||
AssistantProposalsService,
|
||||
AssistantShareService,
|
||||
|
||||
@@ -33,6 +33,7 @@ import { withRequestContext } from '../database/request-context';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { runAgentLoop, type AgentStore, type HeldCall, type StepRecord } from './assistant-agent';
|
||||
import type { AttachedFileReader } from './assistant-attached-file';
|
||||
import { AssistantBookingImportService } from './assistant-booking-import.service';
|
||||
import { mentionItems } from './assistant-cards.helpers';
|
||||
import { todayIn } from './assistant-context';
|
||||
@@ -48,13 +49,13 @@ import {
|
||||
ASSISTANT_SERVER_WRITE_TOOLS,
|
||||
foundPlaceArgs,
|
||||
IMPORT_BOOKING_TOOL,
|
||||
READ_BOOKING_FILE_TOOL,
|
||||
REMEMBER_TOOL,
|
||||
TURNS_PER_MINUTE,
|
||||
UNDO_WINDOW_MS,
|
||||
writeToolOf,
|
||||
} from './assistant-tools.constants';
|
||||
import { AssistantToolsService, type AssistantToolSession, type ToolRun } from './assistant-tools.service';
|
||||
import { AssistantTourFileService } from './assistant-tour-file.service';
|
||||
import { readTripCard } from './assistant-trip-scope';
|
||||
import { unchangedSinceApplied, undoSnapshotOf, undoTargetsOf } from './assistant-undo.helpers';
|
||||
import { AssistantVision } from './assistant-vision';
|
||||
@@ -78,8 +79,8 @@ import type {
|
||||
AssistantThreadListResponse,
|
||||
AssistantThreadResponse,
|
||||
AssistantThreadSummary,
|
||||
BookingImportPreviewItem,
|
||||
} from '@trek/shared';
|
||||
import { isAssistantTourFile } from '@trek/shared';
|
||||
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
@@ -171,6 +172,7 @@ export class AssistantService {
|
||||
private readonly usage: AiUsageService,
|
||||
private readonly tools: AssistantToolsService,
|
||||
private readonly bookings: AssistantBookingImportService,
|
||||
private readonly tourFiles: AssistantTourFileService,
|
||||
private readonly settings: SettingsService,
|
||||
private readonly rateLimit: RateLimitService,
|
||||
private readonly streams: AssistantStreamRegistry,
|
||||
@@ -251,9 +253,9 @@ export class AssistantService {
|
||||
|
||||
/**
|
||||
* A file the user attached, in a thread of theirs on this trip or (no
|
||||
* threadId) a new one, answered as a stream: the file is read into bookings
|
||||
* and each is proposed as a change card, applied or discarded like any
|
||||
* other. No model is asked here; the decision on the cards starts the next
|
||||
* threadId) a new one, answered as a stream: the file is read into bookings,
|
||||
* or a route file (GPX, KML, KMZ) into its tracks, and each is proposed as a
|
||||
* change card, applied or discarded like any other. No model is asked here; the decision on the cards starts the next
|
||||
* answer. Refused like a chat turn, and also when nothing here reads files.
|
||||
*
|
||||
* @txIndependent the opening rows are one transaction and the proposals
|
||||
@@ -267,7 +269,8 @@ export class AssistantService {
|
||||
channel: TurnChannel,
|
||||
): Promise<void> {
|
||||
await this.admit(userId);
|
||||
await this.bookings.ensureReadable(userId, file);
|
||||
const reader: AttachedFileReader = isAssistantTourFile(file.originalname) ? this.tourFiles : this.bookings;
|
||||
await reader.ensureReadable(userId, file);
|
||||
const connection = await this.connections.resolveForUser(userId);
|
||||
await this.withinDailyLimit(userId, connection);
|
||||
await this.claimed(userId, channel.signal, async (signal) => {
|
||||
@@ -283,7 +286,7 @@ export class AssistantService {
|
||||
try {
|
||||
const { locale, timeZone } = req;
|
||||
const turn = { userId, tripId, threadId: begun.threadId, rowId: begun.rowId, locale, timeZone, name };
|
||||
await this.proposeBookings(turn, file, w, signal);
|
||||
await this.proposeFromFile(turn, file, reader, w, signal);
|
||||
} catch (err) {
|
||||
const reason = err instanceof Error ? err.message : String(err);
|
||||
logError(`[assistant] attachment in thread ${begun.threadId} failed: ${reason}`);
|
||||
@@ -539,16 +542,18 @@ export class AssistantService {
|
||||
|
||||
/**
|
||||
* Reads the attached file and proposes what it found, in the answer's first
|
||||
* row: the read step, then one held `import_booking` change per booking,
|
||||
* each with its card. A file without bookings ends the answer with
|
||||
* `no_bookings_found`; one that cannot be read, with `generic`.
|
||||
* row: the read step, then one held change per booking (`import_booking`)
|
||||
* or track (`import_tour_file`), each with its card. A file without any
|
||||
* ends the answer with the reader's code; one that cannot be read, with
|
||||
* `generic`.
|
||||
*
|
||||
* @txIndependent the row is written once the file was read, in a
|
||||
* transaction of its own.
|
||||
*/
|
||||
private async proposeBookings(
|
||||
private async proposeFromFile(
|
||||
turn: { userId: number; tripId: number; threadId: number; rowId: number; name: string } & AssistantClientCtx,
|
||||
file: Express.Multer.File,
|
||||
reader: AttachedFileReader,
|
||||
w: UiStreamWriter,
|
||||
signal: AbortSignal,
|
||||
): Promise<void> {
|
||||
@@ -557,17 +562,17 @@ export class AssistantService {
|
||||
const readPart = (result: unknown, isError = false): AssistantMessagePart => ({
|
||||
type: 'tool-call',
|
||||
toolCallId: readId,
|
||||
toolName: READ_BOOKING_FILE_TOOL,
|
||||
toolName: reader.readTool,
|
||||
args: readArgs,
|
||||
result,
|
||||
...(isError ? { isError: true } : {}),
|
||||
});
|
||||
const fieldsOf = (parts: AssistantMessagePart[]) => ({ parts: encodeParts(parts), providerState: null });
|
||||
w.startStep();
|
||||
w.toolInput(readId, READ_BOOKING_FILE_TOOL, readArgs);
|
||||
let items: BookingImportPreviewItem[];
|
||||
w.toolInput(readId, reader.readTool, readArgs);
|
||||
let read: Awaited<ReturnType<AttachedFileReader['propose']>>;
|
||||
try {
|
||||
items = await this.inContext(() => this.bookings.read(turn.userId, file));
|
||||
read = await this.inContext(() => reader.propose(turn.userId, turn.tripId, file));
|
||||
} catch (err) {
|
||||
logError(`[assistant] reading ${turn.name} failed: ${err instanceof Error ? err.message : String(err)}`);
|
||||
await this.saveRow(turn.threadId, turn.rowId, fieldsOf([readPart(FILE_UNREADABLE, true)]), 'error');
|
||||
@@ -576,27 +581,25 @@ export class AssistantService {
|
||||
w.finish('error');
|
||||
return;
|
||||
}
|
||||
const found = { bookings: items.map((item) => item.title) };
|
||||
const { found, proposals } = read;
|
||||
if (signal.aborted) {
|
||||
await this.saveRow(turn.threadId, turn.rowId, fieldsOf([readPart(found)]), 'aborted');
|
||||
w.abort();
|
||||
return;
|
||||
}
|
||||
w.toolOutput(readId, found);
|
||||
if (items.length === 0) {
|
||||
if (proposals.length === 0) {
|
||||
await this.saveRow(turn.threadId, turn.rowId, fieldsOf([readPart(found)]), 'error');
|
||||
w.finishStep();
|
||||
w.error('no_bookings_found');
|
||||
w.error(reader.emptyCode);
|
||||
w.finish('error');
|
||||
return;
|
||||
}
|
||||
const card = await readTripCard(this.tools, turn.userId, turn.tripId);
|
||||
const ctx = this.cardContext.contextOf(card, new Map(), turn.locale, todayIn(turn.timeZone, new Date()));
|
||||
const proposed = items.map((item) => ({
|
||||
id: randomUUID(),
|
||||
toolName: IMPORT_BOOKING_TOOL,
|
||||
args: item as Record<string, unknown>,
|
||||
}));
|
||||
const proposed = 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[] = [
|
||||
@@ -605,14 +608,14 @@ export class AssistantService {
|
||||
type: 'tool-call',
|
||||
toolCallId: change.id,
|
||||
toolName: change.toolName,
|
||||
args: change.args,
|
||||
args: shown.get(change.id) ?? change.args,
|
||||
approval: { id: change.id },
|
||||
})),
|
||||
...held.map((change): AssistantMessagePart => ({ type: 'data-trek-change', data: change.preview })),
|
||||
];
|
||||
await this.holdChanges(turn.threadId, turn.rowId, fieldsOf(parts), held);
|
||||
for (const change of held) {
|
||||
w.toolInput(change.id, change.toolName, change.args);
|
||||
w.toolInput(change.id, change.toolName, shown.get(change.id) ?? change.args);
|
||||
w.approvalRequest(change.id);
|
||||
w.change(change.preview);
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
type SportLoaded,
|
||||
} from './tour-sport-change.cards';
|
||||
import { cityWalkCard, paddleCard, skiCard } from './tour-sport.cards';
|
||||
import { TOUR_STOP_CARDS } from './tour-stop.cards';
|
||||
import { DELETE_CREATED_TOUR, DELETE_IMPORTED_TOUR } from './tour-undo';
|
||||
import { describeVisit, loadVisit, SET_VISIT_UNDO } from './tour-visit.cards';
|
||||
import { IMPORT_WANDERER_TRAIL, legWayCard, roundHikeCard, wandererPreviewCard } from './tour-ways.cards';
|
||||
@@ -140,6 +141,7 @@ export const TOUR_CARDS: DomainCards = {
|
||||
describe: TOUR_DESCRIBERS.import_tour_gpx,
|
||||
undo: DELETE_IMPORTED_TOUR,
|
||||
},
|
||||
...TOUR_STOP_CARDS,
|
||||
take_over_tour: {
|
||||
write: { verbKey: 'addTour', entity: 'tour' },
|
||||
describe: TOUR_DESCRIBERS.take_over_tour,
|
||||
|
||||
@@ -124,6 +124,8 @@ export const TOUR_DESCRIBERS = {
|
||||
take_over_tour: (_ctx, args) => ({ subject: text(args.name), rows: new Rows(), dayId: null, placeIds: [] }),
|
||||
import_tour_gpx: (_ctx, args) => {
|
||||
const rows = new Rows().add('type', text(args.tour_type));
|
||||
return { subject: text(args.file_name) || gpxName(args.gpx) || 'GPX', rows, dayId: null, placeIds: [] };
|
||||
// A track of a file attached in the chat names itself (track_name); the model's import names the file.
|
||||
const subject = text(args.track_name) || text(args.file_name) || gpxName(args.gpx) || 'GPX';
|
||||
return { subject, rows, dayId: null, placeIds: [] };
|
||||
},
|
||||
} satisfies Readonly<Record<string, (ctx: PreviewContext, args: ToolArgs) => Described>>;
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import type { CardReader, Described, PreviewContext, ToolArgs, ToolCards, UndoCall, UndoSnapshot } from '../card-types';
|
||||
import { argId, readKey, recordOf, type Row } from '../card-values';
|
||||
import { Rows, text } from '../preview-format';
|
||||
import { rowsIn } from './tour-card-values';
|
||||
import { alongRouteM, defaultAfterId, type InsertionPoint } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* P6: a place taken into a saved hike or city walk as one stop
|
||||
* (insert_tour_stop), and a stop taken out again (remove_tour_stop). Each is
|
||||
* the other's way back: an insert is undone by taking out the stop it added,
|
||||
* a removal by putting the stop back after the point it followed, both while
|
||||
* the tour is still at the revision the change left it at. The card names the
|
||||
* tour, the stop and where it goes, between which two points, read from the
|
||||
* tour as saved now.
|
||||
*/
|
||||
|
||||
/** The saved tour a held change is about, read once for its card. */
|
||||
async function loadStopTour(args: ToolArgs, read: CardReader): Promise<unknown> {
|
||||
const placeId = argId(args, 'placeId');
|
||||
return placeId === null ? null : read('get_tour_plan', { placeId });
|
||||
}
|
||||
|
||||
/** The points of the tour as read, as the planner's insertion rule takes them. */
|
||||
function pointsOf(plan: Row): Array<InsertionPoint & { name: string }> {
|
||||
return rowsIn(plan.waypoints).flatMap((point, index) => {
|
||||
if (typeof point.lat !== 'number' || typeof point.lng !== 'number') return [];
|
||||
return [
|
||||
{
|
||||
id: typeof point.key === 'string' ? point.key : `#${index}`,
|
||||
lat: point.lat,
|
||||
lng: point.lng,
|
||||
role: typeof point.role === 'string' ? point.role : 'via',
|
||||
fixedLeg: point.fixed_leg ? (point.fixed_leg as InsertionPoint['fixedLeg']) : null,
|
||||
...(point.shaping === true ? { shaping: true } : {}),
|
||||
name: text(point.name) || String(index + 1),
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
/** The saved line in brief, for where along it a stop lies. */
|
||||
function previewOf(plan: Row): Array<[number, number]> | null {
|
||||
const preview = recordOf(plan.line).preview;
|
||||
if (!Array.isArray(preview)) return null;
|
||||
const line = preview.flatMap((point): Array<[number, number]> => {
|
||||
const [lat, lng] = Array.isArray(point) ? point : [];
|
||||
return typeof lat === 'number' && typeof lng === 'number' ? [[lat, lng]] : [];
|
||||
});
|
||||
return line.length > 1 ? line : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The key of the point a stop at `spot` goes after where none is named: the
|
||||
* last point before it along the saved line, as insert_tour_stop picks it.
|
||||
*/
|
||||
export function defaultAfterKeyOf(plan: Row, spot: { lat: number; lng: number }): string | null {
|
||||
const points = pointsOf(plan);
|
||||
const line = previewOf(plan);
|
||||
const id = defaultAfterId(points, line, alongRouteM(points, line, spot));
|
||||
return id !== null && !id.startsWith('#') ? id : null;
|
||||
}
|
||||
|
||||
/** "Parking → Hut": the two points a stop goes between, or the one it follows as the new end. */
|
||||
function betweenOf(plan: Row, args: ToolArgs): string {
|
||||
const points = pointsOf(plan);
|
||||
const stop = recordOf(args.stop);
|
||||
let afterId = typeof args.after_key === 'string' ? args.after_key : null;
|
||||
if (afterId === null && typeof stop.lat === 'number' && typeof stop.lng === 'number') {
|
||||
afterId = defaultAfterKeyOf(plan, { lat: stop.lat, lng: stop.lng });
|
||||
}
|
||||
const index = points.findIndex((point) => point.id === afterId);
|
||||
const after = points[index];
|
||||
if (!after) return '';
|
||||
const next = points.slice(index + 1).find((point) => point.shaping !== true);
|
||||
return next ? `${after.name} → ${next.name}` : `${after.name} →`;
|
||||
}
|
||||
|
||||
function tourName(ctx: PreviewContext, args: ToolArgs, plan: Row): string {
|
||||
const placeId = argId(args, 'placeId');
|
||||
return text(recordOf(plan.tour).name) || (placeId === null ? '' : (ctx.card.places.get(placeId)?.name ?? ''));
|
||||
}
|
||||
|
||||
function described(ctx: PreviewContext, args: ToolArgs, plan: Row, rows: Rows, verbKey: Described['verbKey']) {
|
||||
const placeId = argId(args, 'placeId');
|
||||
return {
|
||||
subject: tourName(ctx, args, plan),
|
||||
rows,
|
||||
dayId: null,
|
||||
placeIds: placeId !== null && ctx.card.places.has(placeId) ? [placeId] : [],
|
||||
verbKey,
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether the tour is still at the revision the change left it at, read before the way back. */
|
||||
function atRevision(result: unknown, snapshot: UndoSnapshot, call?: UndoCall): boolean {
|
||||
if (!call) return false;
|
||||
const plan = recordOf(snapshot.reads.get(readKey('get_tour_plan', { placeId: call.args.placeId })));
|
||||
const revision = recordOf(recordOf(result).tour).revision;
|
||||
return typeof revision === 'number' && recordOf(plan.tour).revision === revision;
|
||||
}
|
||||
|
||||
const readsPlan = (args: ToolArgs) => [{ tool: 'get_tour_plan', args: { placeId: args.placeId } }];
|
||||
|
||||
const insertStop: ToolCards<unknown> = {
|
||||
write: { verbKey: 'addTourStop', entity: 'tour' },
|
||||
load: loadStopTour,
|
||||
describe: (ctx, args, loaded) => {
|
||||
const plan = recordOf(loaded);
|
||||
const rows = new Rows().add('name', text(recordOf(args.stop).name)).add('position', betweenOf(plan, args));
|
||||
return described(ctx, args, plan, rows, 'addTourStop');
|
||||
},
|
||||
undo: {
|
||||
tool: 'remove_tour_stop',
|
||||
args: (_args, result) => {
|
||||
const answer = recordOf(result);
|
||||
const tour = recordOf(answer.tour);
|
||||
const key = recordOf(answer.stop).key;
|
||||
if (typeof key !== 'string' || typeof tour.revision !== 'number' || typeof tour.place_id !== 'number') {
|
||||
return null;
|
||||
}
|
||||
return { placeId: tour.place_id, key, expected_revision: tour.revision };
|
||||
},
|
||||
reads: readsPlan,
|
||||
unchanged: atRevision,
|
||||
},
|
||||
};
|
||||
|
||||
const removeStop: ToolCards<unknown> = {
|
||||
write: { verbKey: 'removeTourStop', entity: 'tour' },
|
||||
load: loadStopTour,
|
||||
describe: (ctx, args, loaded) => {
|
||||
const plan = recordOf(loaded);
|
||||
const stop = rowsIn(plan.waypoints).find((point) => point.key === args.key);
|
||||
return described(ctx, args, plan, new Rows().add('name', text(stop?.name)), 'removeTourStop');
|
||||
},
|
||||
undo: {
|
||||
tool: 'insert_tour_stop',
|
||||
args: (_args, result) => {
|
||||
const answer = recordOf(result);
|
||||
const tour = recordOf(answer.tour);
|
||||
const removed = recordOf(answer.removed);
|
||||
if (typeof tour.revision !== 'number' || typeof tour.place_id !== 'number') return null;
|
||||
if (typeof removed.lat !== 'number' || typeof removed.lng !== 'number') return null;
|
||||
const stop: Row = { lat: removed.lat, lng: removed.lng };
|
||||
if (typeof removed.name === 'string') stop.name = removed.name;
|
||||
if (typeof removed.poi_category === 'string') stop.poi_category = removed.poi_category;
|
||||
const after = typeof removed.after_key === 'string' ? { after_key: removed.after_key } : {};
|
||||
return { placeId: tour.place_id, expected_revision: tour.revision, stop, ...after };
|
||||
},
|
||||
reads: readsPlan,
|
||||
unchanged: atRevision,
|
||||
},
|
||||
};
|
||||
|
||||
export const TOUR_STOP_CARDS: Readonly<Record<string, ToolCards>> = {
|
||||
insert_tour_stop: insertStop,
|
||||
remove_tour_stop: removeStop,
|
||||
};
|
||||
@@ -91,6 +91,7 @@ export const MANAGED_ROUTE_ALLOW_LIST: string[] = [
|
||||
'AssistantController.chat',
|
||||
'AssistantController.decide',
|
||||
'AssistantController.deleteThread',
|
||||
'AssistantController.insertFoundPlace',
|
||||
'AssistantController.share',
|
||||
'AssistantController.stop',
|
||||
'AssistantController.takeProposal',
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { PlaceImportService } from '../place-import/place-import.service';
|
||||
import type { PreparedGpxPlace } from '../place-import/place-import.types';
|
||||
import { PlacesService } from '../places/places.service';
|
||||
import { readTourFile } from './tour-file-import.helpers';
|
||||
import { gpxOfLine, splitGpxTracks } from './tour-file-split.helpers';
|
||||
import { computeTourMetrics, parseRouteGeometry } from './tours.helpers';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { TOUR_GPX_TEXT_MAX, type TourFileLeftOut } from '@trek/shared';
|
||||
|
||||
/** One track or route of an attached file, ready for import_tour_gpx. */
|
||||
export interface TourFileTrack {
|
||||
name: string;
|
||||
/** Its own GPX text; null where it is longer than one import takes. */
|
||||
gpx: string | null;
|
||||
point_count: number;
|
||||
distance_km: number;
|
||||
has_heights: boolean;
|
||||
/** A track already in the trip under the same name and start, which the import would skip. */
|
||||
duplicate: boolean;
|
||||
}
|
||||
|
||||
/** What an attached route file holds, track by track. */
|
||||
interface TourFileTracks {
|
||||
tracks: TourFileTrack[];
|
||||
/**
|
||||
* True where a GPX file could not be cut into its tracks: its one entry is
|
||||
* then the whole file, which comes in as one import of all its tracks.
|
||||
*/
|
||||
whole: boolean;
|
||||
/** What a KML or KMZ file holds besides its lines (pins, areas), never taken in. */
|
||||
left_out?: TourFileLeftOut;
|
||||
}
|
||||
|
||||
const GPX_OPTIONS = { importWaypoints: false, importRoutes: true, importTracks: true } as const;
|
||||
|
||||
function isGpxName(fileName: string): boolean {
|
||||
const ext = fileName.toLowerCase().split('.').pop();
|
||||
return ext !== 'kml' && ext !== 'kmz';
|
||||
}
|
||||
|
||||
/**
|
||||
* P7: a route file the user attached in the assistant's chat, read the way
|
||||
* the Tours import reads it (readTourFile: GPX by its tracks and routes, KML
|
||||
* and KMZ by their lines) and cut into one GPX text per track, so each one is
|
||||
* proposed and taken in as a tour of its own and taken back on its own.
|
||||
* Reads only: nothing is stored here, the import is import_tour_gpx's.
|
||||
*/
|
||||
@Injectable()
|
||||
export class TourFileReadService {
|
||||
constructor(
|
||||
private readonly placeImport: PlaceImportService,
|
||||
private readonly places: PlacesService,
|
||||
) {}
|
||||
|
||||
async read(tripId: number, buffer: Buffer, fileName: string): Promise<TourFileTracks> {
|
||||
const { rows, leftOut } = await readTourFile(this.placeImport, buffer, fileName);
|
||||
if (rows.length === 0) return { tracks: [], whole: false };
|
||||
const duplicates = await this.places.gpxDuplicates(String(tripId), rows);
|
||||
const texts = isGpxName(fileName) ? this.cutGpx(buffer.toString('utf8'), rows.length, fileName) : null;
|
||||
const extra = leftOut ? { left_out: leftOut } : {};
|
||||
if (isGpxName(fileName) && !texts) {
|
||||
return { tracks: [this.wholeFile(buffer.toString('utf8'), rows, fileName)], whole: true, ...extra };
|
||||
}
|
||||
const tracks = rows.map((row, index) => {
|
||||
const own = texts?.[index] ?? gpxOfLine(row.name, row.description, parseRouteGeometry(row.routeGeometry));
|
||||
return this.trackOf(row, own, duplicates[index] ?? false);
|
||||
});
|
||||
return { tracks, whole: false, ...extra };
|
||||
}
|
||||
|
||||
/** A GPX text cut into its tracks; null where a piece does not read back as exactly the one it should. */
|
||||
private cutGpx(text: string, count: number, fileName: string): string[] | null {
|
||||
const pieces = splitGpxTracks(text);
|
||||
if (pieces.length !== count) return null;
|
||||
const readable = pieces.every((piece) => {
|
||||
const rows = this.placeImport.readGpx(Buffer.from(piece, 'utf8'), { ...GPX_OPTIONS, defaultName: fileName });
|
||||
return rows.length === 1;
|
||||
});
|
||||
return readable ? pieces : null;
|
||||
}
|
||||
|
||||
private trackOf(row: PreparedGpxPlace, gpx: string, duplicate: boolean): TourFileTrack {
|
||||
const line = parseRouteGeometry(row.routeGeometry);
|
||||
const metrics = computeTourMetrics(line);
|
||||
return {
|
||||
name: row.name,
|
||||
gpx: gpx.length <= TOUR_GPX_TEXT_MAX ? gpx : null,
|
||||
point_count: line.length,
|
||||
distance_km: metrics.distanceKm,
|
||||
has_heights: metrics.hasElevation,
|
||||
duplicate,
|
||||
};
|
||||
}
|
||||
|
||||
/** The whole GPX file as one entry, named by the file and measured over all its tracks. */
|
||||
private wholeFile(text: string, rows: readonly PreparedGpxPlace[], fileName: string): TourFileTrack {
|
||||
const lines = rows.map((row) => parseRouteGeometry(row.routeGeometry));
|
||||
const metrics = lines.map((line) => computeTourMetrics(line));
|
||||
return {
|
||||
name: fileName,
|
||||
gpx: text.length <= TOUR_GPX_TEXT_MAX ? text : null,
|
||||
point_count: lines.reduce((sum, line) => sum + line.length, 0),
|
||||
distance_km: metrics.reduce((sum, metric) => sum + metric.distanceKm, 0),
|
||||
has_heights: metrics.every((metric) => metric.hasElevation),
|
||||
duplicate: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { escapeHtml, type GeometryPoint } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* P7: a route file the user attached in the chat, cut into one GPX text per
|
||||
* track or route, so each comes in as a tour of its own and can be taken back
|
||||
* on its own. A GPX file is cut out of its own text, so every point keeps
|
||||
* what it carried (times, heights, extensions); a KML or KMZ line, which
|
||||
* holds no times, is written as GPX from its points.
|
||||
*/
|
||||
|
||||
/** Where every `<trk>` and `<rte>` element of a GPX text starts and ends, in order. */
|
||||
function trackBlocks(gpx: string): Array<{ from: number; to: number }> {
|
||||
const blocks: Array<{ from: number; to: number }> = [];
|
||||
let at = 0;
|
||||
for (;;) {
|
||||
const trk = openingAt(gpx, 'trk', at);
|
||||
const rte = openingAt(gpx, 'rte', at);
|
||||
const next = [trk, rte].filter((found) => found >= 0).sort((a, b) => a - b)[0];
|
||||
if (next === undefined) return blocks;
|
||||
const tag = next === trk ? 'trk' : 'rte';
|
||||
const close = gpx.indexOf(`</${tag}>`, next);
|
||||
if (close < 0) return blocks;
|
||||
const to = close + tag.length + 3;
|
||||
blocks.push({ from: next, to });
|
||||
at = to;
|
||||
}
|
||||
}
|
||||
|
||||
/** The first `<tag>` or `<tag ...>` from `at`, not a longer tag such as `<trkseg>`. */
|
||||
function openingAt(text: string, tag: string, at: number): number {
|
||||
let from = at;
|
||||
for (;;) {
|
||||
const found = text.indexOf(`<${tag}`, from);
|
||||
if (found < 0) return -1;
|
||||
const after = text.charAt(found + tag.length + 1);
|
||||
if (after === '>' || after === ' ' || after === '\n' || after === '\r' || after === '\t') return found;
|
||||
from = found + 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One GPX text per track and route of a GPX file: the file's head (its
|
||||
* declaration, the `<gpx>` element and its metadata) around each element.
|
||||
* Empty where the file holds none the cut can find (a namespace prefix, say).
|
||||
*/
|
||||
export function splitGpxTracks(gpx: string): string[] {
|
||||
const blocks = trackBlocks(gpx);
|
||||
const first = blocks[0];
|
||||
if (!first) return [];
|
||||
const head = gpx.slice(0, first.from);
|
||||
// The head ends before the first waypoint as well: an import never takes loose points.
|
||||
const wpt = openingAt(head, 'wpt', 0);
|
||||
const kept = wpt >= 0 ? head.slice(0, wpt) : head;
|
||||
return blocks.map(({ from, to }) => `${kept}${gpx.slice(from, to)}\n</gpx>\n`);
|
||||
}
|
||||
|
||||
/** A line read from a KML or KMZ file as a GPX text of one track. */
|
||||
export function gpxOfLine(name: string, description: string | null, line: readonly GeometryPoint[]): string {
|
||||
const points = line
|
||||
.map(([lat, lng, ele]) => {
|
||||
const height = typeof ele === 'number' && Number.isFinite(ele) ? `<ele>${ele}</ele>` : '';
|
||||
return `<trkpt lat="${lat}" lon="${lng}">${height}</trkpt>`;
|
||||
})
|
||||
.join('');
|
||||
const desc = description ? `<desc>${escapeHtml(description)}</desc>` : '';
|
||||
return (
|
||||
'<?xml version="1.0" encoding="UTF-8"?>\n' +
|
||||
'<gpx version="1.1" creator="TREK" xmlns="http://www.topografix.com/GPX/1/1">\n' +
|
||||
`<trk><name>${escapeHtml(name)}</name>${desc}<trkseg>${points}</trkseg></trk>\n</gpx>\n`
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { PlaceImportModule } from '../place-import/place-import.module';
|
||||
import { PlacesModule } from '../places/places.module';
|
||||
import { TourFileReadService } from './tour-file-read.service';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* P7: a route file read into tours without storing anything, for the
|
||||
* assistant's chat (a GPX, KML or KMZ file the user attaches). It reads the
|
||||
* file as the Tours import does, through PlaceImportModule's readers, and
|
||||
* marks the tracks the trip has already through PlacesModule; the import
|
||||
* itself stays import_tour_gpx's. A module of its own so the assistant takes
|
||||
* this one reader without the whole Tours module.
|
||||
*/
|
||||
@Module({
|
||||
imports: [PlaceImportModule, PlacesModule],
|
||||
providers: [TourFileReadService],
|
||||
exports: [TourFileReadService],
|
||||
})
|
||||
export class TourFilesModule {}
|
||||
@@ -0,0 +1,138 @@
|
||||
import {
|
||||
alongRouteM,
|
||||
defaultAfterId,
|
||||
haversineMetres,
|
||||
insertionBlock,
|
||||
isClosedLoop,
|
||||
withPointAfter,
|
||||
type GeometryPoint,
|
||||
type HikeStop,
|
||||
type InsertionPoint,
|
||||
type TourStop,
|
||||
type TourWaypoint,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* P6: the pure half of a stop taken into a saved tour or out of it (see
|
||||
* TourStopsService). The points of the tour are read as the planner reads
|
||||
* them for a found place (poi-insertion.ts in @trek/shared), so the stop goes
|
||||
* where the planner would put it and a leg drawn by hand is never cut.
|
||||
*/
|
||||
|
||||
/** How near a saved point must lie to the stop to be the one the save made of it, in metres. */
|
||||
const SAME_SPOT_M = 30;
|
||||
|
||||
/** A saved point as the insertion rule reads it, keeping the point itself. */
|
||||
export interface StopPoint extends InsertionPoint {
|
||||
saved: TourWaypoint;
|
||||
}
|
||||
|
||||
/** The id a point goes by: its key, or its place in the order where it has none yet. */
|
||||
function idOf(point: TourWaypoint, index: number): string {
|
||||
return point.key ?? `#${index}`;
|
||||
}
|
||||
|
||||
export function stopPointsOf(waypoints: readonly TourWaypoint[]): StopPoint[] {
|
||||
return waypoints.map((saved, index) => ({
|
||||
id: idOf(saved, index),
|
||||
lat: saved.lat,
|
||||
lng: saved.lng,
|
||||
role: saved.role,
|
||||
fixedLeg: saved.fixed_leg ?? null,
|
||||
...(saved.shaping ? { shaping: true } : {}),
|
||||
saved,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Why the stop cannot go after the point named, in words an assistant can pass on. */
|
||||
const BLOCKED: Readonly<Record<'fixed' | 'free' | 'none', string>> = {
|
||||
fixed: 'The leg after that point is a fixed line (a via ferrata, a ferry or a portage): a stop there would cut it.',
|
||||
free: 'The leg after that point is drawn by hand: a stop there would redraw it. Put the stop in the planner.',
|
||||
none: 'Nothing comes after that point: it is the way back of a loop. Name the point before it.',
|
||||
};
|
||||
|
||||
/**
|
||||
* The point the stop goes after: the one named by its key, or the last point
|
||||
* before the stop along the saved line. A string says why it cannot go in.
|
||||
*/
|
||||
export function afterPointOf(
|
||||
points: readonly StopPoint[],
|
||||
line: readonly GeometryPoint[],
|
||||
stop: Pick<TourStop, 'lat' | 'lng'>,
|
||||
afterKey: string | undefined,
|
||||
): StopPoint | string {
|
||||
if (afterKey !== undefined) {
|
||||
const named = points.find((point) => point.id === afterKey);
|
||||
if (!named) return `This tour has no point with the key ${afterKey}: read it again with get_tour_plan.`;
|
||||
if (named.shaping) return 'That point only shapes the line and is no stop: name a stop of the tour.';
|
||||
const block = insertionBlock(points, named.id);
|
||||
return block ? BLOCKED[block] : named;
|
||||
}
|
||||
const route = line.length > 1 ? line : null;
|
||||
const id = defaultAfterId(points, route, alongRouteM(points, route, stop));
|
||||
const chosen = points.find((point) => point.id === id);
|
||||
return chosen ?? 'No leg of this tour can take a stop: every one is drawn by hand or a fixed line.';
|
||||
}
|
||||
|
||||
/** A saved point as a hike's update takes it: its spot, and its name, kind and stage end where it has them. */
|
||||
function hikeStopOf(point: TourWaypoint): HikeStop {
|
||||
return {
|
||||
lat: point.lat,
|
||||
lng: point.lng,
|
||||
...(point.name ? { name: point.name } : {}),
|
||||
...(point.poi_category ? { poi_category: point.poi_category } : {}),
|
||||
...(point.stage_end ? { stage_end: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** The stop as a new saved point would carry it; the server gives it its key on the save. */
|
||||
function waypointOfStop(stop: TourStop): TourWaypoint {
|
||||
return {
|
||||
lat: stop.lat,
|
||||
lng: stop.lng,
|
||||
role: 'via',
|
||||
sequence: 0,
|
||||
...(stop.name ? { name: stop.name } : {}),
|
||||
...(stop.poi_category ? { poi_category: stop.poi_category } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** A hike's points with the stop after `afterId`, as update_tour takes them; null where it cannot go there. */
|
||||
export function hikePointsWithStop(points: readonly StopPoint[], afterId: string, stop: TourStop): HikeStop[] | null {
|
||||
const added: StopPoint = { id: '#new', lat: stop.lat, lng: stop.lng, role: 'via', saved: waypointOfStop(stop) };
|
||||
const next = withPointAfter(points, afterId, added);
|
||||
return next ? next.map((point) => hikeStopOf(point.saved)) : null;
|
||||
}
|
||||
|
||||
/** Why a stop cannot be taken out of these points, or null when it can. */
|
||||
export function removalRefusal(points: readonly StopPoint[], key: string): string | null {
|
||||
const index = points.findIndex((point) => point.id === key);
|
||||
if (index < 0) return `This tour has no point with the key ${key}: read it again with get_tour_plan.`;
|
||||
if (points.length <= 2) return 'A tour keeps at least its start and its end: this point cannot be taken out.';
|
||||
if (index === 0) return 'The start of a tour is not taken out here: change the start in the planner.';
|
||||
if (isClosedLoop(points) && index === points.length - 1)
|
||||
return 'The way back of a loop is not taken out here: use the planner.';
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A hike's points without the one keyed `key`. */
|
||||
export function hikePointsWithout(points: readonly StopPoint[], key: string): HikeStop[] {
|
||||
return points.filter((point) => point.id !== key).map((point) => hikeStopOf(point.saved));
|
||||
}
|
||||
|
||||
/** The key the save gave the stop: the saved point nearest its spot, within a few metres of it. */
|
||||
export function keyNear(waypoints: readonly TourWaypoint[], spot: { lat: number; lng: number }): string | null {
|
||||
let best: { key: string; metres: number } | null = null;
|
||||
for (const point of waypoints) {
|
||||
if (!point.key) continue;
|
||||
const metres = haversineMetres(point.lat, point.lng, spot.lat, spot.lng);
|
||||
if (metres <= SAME_SPOT_M && (!best || metres < best.metres)) best = { key: point.key, metres };
|
||||
}
|
||||
return best?.key ?? null;
|
||||
}
|
||||
|
||||
/** The key of the point before the one keyed `key`, where it has one. */
|
||||
export function keyBefore(points: readonly StopPoint[], key: string): string | null {
|
||||
const index = points.findIndex((point) => point.id === key);
|
||||
return index > 0 ? (points[index - 1]?.saved.key ?? null) : null;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_WRITE, errorResult, ok, type McpContext } from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { TripAccessService } from '../trip-membership/trip-access.service';
|
||||
import { TourStopsService } from './tour-stops.service';
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import {
|
||||
idSchema,
|
||||
tourStopInsertRequestSchema,
|
||||
tourStopRemoveRequestSchema,
|
||||
type TourStopInsertRequest,
|
||||
type TourStopRemoveRequest,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** A refusal for a tour this trip does not have, the same text every tool of the tours answers. */
|
||||
function tourNotFound(err: unknown) {
|
||||
if (err instanceof NotFoundException) return errorResult('Tour not found.');
|
||||
throw err;
|
||||
}
|
||||
|
||||
/**
|
||||
* P6: a place taken into a saved hike or city walk as one stop, and taken out
|
||||
* again. Both write with 'place_edit' on the trip, as the planner's save over
|
||||
* REST asks (ToursController's update) and as update_tour and
|
||||
* save_tour_change ask, whose paths they save through; the trip hears of the
|
||||
* change as from those (tours:changed and place:updated).
|
||||
*/
|
||||
@McpController()
|
||||
export class TourStopsMcp {
|
||||
constructor(
|
||||
private readonly stops: TourStopsService,
|
||||
private readonly access: TripAccessService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
// Read by the addon gate of every tool here.
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
name: 'insert_tour_stop',
|
||||
description:
|
||||
'Take a place into a saved hike or city walk as one stop, against the revision it was read at (expected_revision is tour.revision from get_tour_plan or list_tours): a hut, a café, a viewpoint the traveller found along it, from search_tour_pois or any search. stop is where it is, its name and on a hike its poi_category, on a city walk its opening_hours. With after_key (the key of a point from get_tour_plan) the stop comes after that point; left out, after the last point before it along the route, as the planner puts a found place. A leg drawn by hand or a fixed line (a via ferrata, a ferry, a portage) is never cut, and nothing goes after the way back of a loop: such a place is refused with the reason, name another point. A hike plans its way anew through the points, as update_tour does (where it cannot be planned nothing is saved and the error says why), and keeps its stages and the links of its points; a city walk saves the stop as a new station as save_tour_change does, the visits of its other stations kept. Any other type, and a recorded track without points of its own, is refused: change those in the planner. A tour changed since that revision is refused as a conflict: read it again. The answer: tour (place_id, name, tour_type, the new revision, distance_km and minutes as now stored, route_pending), stop (its key, where it is, after_key and after_name, the point it follows) and before (distance_km and minutes as stored before). Take it out again with remove_tour_stop. Needs place editing permission on the trip. Take a place in only after the traveller said yes.',
|
||||
inputSchema: { tripId: idSchema, ...tourStopInsertRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
access: { group: 'trips', mode: 'write' },
|
||||
})
|
||||
async insertTourStop({ tripId, ...request }: { tripId: number } & TourStopInsertRequest, ctx: McpContext) {
|
||||
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
try {
|
||||
return ok(await this.stops.insert(ctx.userId, tripId, request));
|
||||
} catch (err: unknown) {
|
||||
return tourNotFound(err);
|
||||
}
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'remove_tour_stop',
|
||||
description:
|
||||
'Take one stop out of a saved hike or city walk by its key (from get_tour_plan or insert_tour_stop), against the revision it was read at (expected_revision). A hike plans its way anew through the points left, as update_tour does; a city walk removes the station as save_tour_change does, and refuses a station protected, or visited or skipped on a day. The start of a tour, the way back of a loop and a tour of two points keep their points: those are refused. Any other type is refused: change it in the planner. A tour changed since that revision is refused as a conflict: read it again. The answer: tour (place_id, name, tour_type, the new revision, distance_km and minutes as now stored, route_pending) and removed (the stop with its key, where it was, its name and after_key, the point it followed). Needs place editing permission on the trip. Take a stop out only after the traveller said yes.',
|
||||
inputSchema: { tripId: idSchema, ...tourStopRemoveRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
access: { group: 'trips', mode: 'write' },
|
||||
})
|
||||
async removeTourStop({ tripId, ...request }: { tripId: number } & TourStopRemoveRequest, ctx: McpContext) {
|
||||
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
try {
|
||||
return ok(await this.stops.remove(ctx.userId, tripId, request));
|
||||
} catch (err: unknown) {
|
||||
return tourNotFound(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import { badRequest } from '../common/domain-error';
|
||||
import { HikePlanService } from './hike-plan.service';
|
||||
import { proposalIdOf } from './tour-change-proposal';
|
||||
import { TourChangeSaveService } from './tour-change-save.service';
|
||||
import { tourRevisionConflict } from './tour-revision';
|
||||
import {
|
||||
afterPointOf,
|
||||
hikePointsWithStop,
|
||||
hikePointsWithout,
|
||||
keyBefore,
|
||||
keyNear,
|
||||
removalRefusal,
|
||||
stopPointsOf,
|
||||
type StopPoint,
|
||||
} from './tour-stops.helpers';
|
||||
import { ToursService } from './tours.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
TOUR_STOP_TYPES,
|
||||
type HikeStop,
|
||||
type TourChange,
|
||||
type TourDetailResponse,
|
||||
type TourStopInsertRequest,
|
||||
type TourStopInsertResult,
|
||||
type TourStopRemoveRequest,
|
||||
type TourStopRemoveResult,
|
||||
} from '@trek/shared';
|
||||
|
||||
type StopTourType = (typeof TOUR_STOP_TYPES)[number];
|
||||
|
||||
/** The tour as an answer names it, from the tour as saved now. */
|
||||
function tourOf(detail: TourDetailResponse, tourType: StopTourType): TourStopInsertResult['tour'] {
|
||||
const { tour } = detail;
|
||||
return {
|
||||
place_id: tour.place_id,
|
||||
name: tour.name,
|
||||
tour_type: tourType,
|
||||
revision: tour.revision ?? 1,
|
||||
distance_km: tour.distance ?? null,
|
||||
minutes: tour.duration ?? null,
|
||||
route_pending: tour.route_pending === true,
|
||||
};
|
||||
}
|
||||
|
||||
/** The type of a tour a stop is taken in or out of here; any other is refused with where to change it. */
|
||||
function stopTypeOf(detail: TourDetailResponse): StopTourType {
|
||||
const type = detail.tour.tour_type;
|
||||
if (type === 'hike' || type === 'walk') {
|
||||
if (detail.tour.has_waypoints !== true) {
|
||||
throw badRequest(
|
||||
'This tour is a recorded track without points of its own: a stop would plan it over. Plan it in the planner first.',
|
||||
);
|
||||
}
|
||||
return type;
|
||||
}
|
||||
throw badRequest('Only a hike or a city walk takes a stop here: change any other tour in the planner.');
|
||||
}
|
||||
|
||||
/**
|
||||
* P6: a place taken into a saved hike or city walk as one stop, and the same
|
||||
* stop taken out again, which is how the assistant's insert is undone. Where
|
||||
* the stop goes is the planner's own rule for a found place (poi-insertion.ts
|
||||
* in @trek/shared): after the point named or after the last one before it
|
||||
* along the route, never into a leg drawn by hand or a fixed line.
|
||||
*
|
||||
* Nothing here writes on its own: a hike is saved through update_tour's path
|
||||
* (HikePlanService.update: its way planned anew through the points, its
|
||||
* stages and the links of its points kept), a city walk through
|
||||
* save_tour_change's (TourChangeSaveService.save: one recorded step, the
|
||||
* visits of the other stations kept). Both refuse a tour changed since the
|
||||
* revision it was read at, and both tell the trip about the change.
|
||||
*/
|
||||
@Injectable()
|
||||
export class TourStopsService {
|
||||
constructor(
|
||||
private readonly tours: ToursService,
|
||||
private readonly hikes: HikePlanService,
|
||||
private readonly walkChanges: TourChangeSaveService,
|
||||
) {}
|
||||
|
||||
/** The tour as saved, of a type that takes a stop here, at the revision the request read it at. */
|
||||
private async current(tripId: number, placeId: number, expected: number) {
|
||||
const detail = await this.tours.getTour(String(tripId), String(placeId));
|
||||
const type = stopTypeOf(detail);
|
||||
const revision = detail.tour.revision ?? null;
|
||||
if (revision !== expected) throw tourRevisionConflict(revision);
|
||||
return { detail, type, points: stopPointsOf(detail.waypoints) };
|
||||
}
|
||||
|
||||
async insert(userId: number, tripId: number, request: TourStopInsertRequest): Promise<TourStopInsertResult> {
|
||||
const { placeId, stop } = request;
|
||||
const { detail, type, points } = await this.current(tripId, placeId, request.expected_revision);
|
||||
const line = await this.tours.savedLine(tripId, placeId);
|
||||
const after = afterPointOf(points, line, stop, request.after_key);
|
||||
if (typeof after === 'string') throw badRequest(after);
|
||||
const saved =
|
||||
type === 'hike'
|
||||
? await this.saveHike(
|
||||
userId,
|
||||
tripId,
|
||||
placeId,
|
||||
request.expected_revision,
|
||||
hikePointsWithStop(points, after.id, stop),
|
||||
)
|
||||
: await this.saveWalk(userId, tripId, placeId, request.expected_revision, {
|
||||
op: 'add',
|
||||
after_key: this.walkKeyOf(after),
|
||||
station: {
|
||||
lat: stop.lat,
|
||||
lng: stop.lng,
|
||||
...(stop.name ? { name: stop.name } : {}),
|
||||
...(stop.opening_hours ? { opening_hours: stop.opening_hours } : {}),
|
||||
},
|
||||
});
|
||||
return {
|
||||
tour: tourOf(saved, type),
|
||||
stop: {
|
||||
key: keyNear(saved.waypoints, stop),
|
||||
lat: stop.lat,
|
||||
lng: stop.lng,
|
||||
name: stop.name ?? null,
|
||||
poi_category: stop.poi_category ?? null,
|
||||
after_key: after.saved.key ?? null,
|
||||
after_name: after.saved.name ?? null,
|
||||
},
|
||||
before: { distance_km: detail.tour.distance ?? null, minutes: detail.tour.duration ?? null },
|
||||
};
|
||||
}
|
||||
|
||||
async remove(userId: number, tripId: number, request: TourStopRemoveRequest): Promise<TourStopRemoveResult> {
|
||||
const { placeId, key } = request;
|
||||
const { type, points } = await this.current(tripId, placeId, request.expected_revision);
|
||||
const refusal = removalRefusal(points, key);
|
||||
const gone = points.find((point) => point.id === key);
|
||||
if (refusal || !gone) throw badRequest(refusal ?? 'This stop is not on the tour.');
|
||||
const saved =
|
||||
type === 'hike'
|
||||
? await this.saveHike(userId, tripId, placeId, request.expected_revision, hikePointsWithout(points, key))
|
||||
: await this.saveWalk(userId, tripId, placeId, request.expected_revision, { op: 'remove', key });
|
||||
return {
|
||||
tour: tourOf(saved, type),
|
||||
removed: {
|
||||
key,
|
||||
lat: gone.lat,
|
||||
lng: gone.lng,
|
||||
name: gone.saved.name ?? null,
|
||||
poi_category: gone.saved.poi_category ?? null,
|
||||
after_key: keyBefore(points, key),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A city walk names the station a stop comes after by its key; a station without one is not named yet. */
|
||||
private walkKeyOf(point: StopPoint): string {
|
||||
if (!point.saved.key)
|
||||
throw badRequest('The stations of this walk have no keys yet: open and save it in the planner.');
|
||||
return point.saved.key;
|
||||
}
|
||||
|
||||
/** A hike saved through new points, its way planned anew as update_tour plans it. */
|
||||
private async saveHike(
|
||||
userId: number,
|
||||
tripId: number,
|
||||
placeId: number,
|
||||
expectedRevision: number,
|
||||
waypoints: HikeStop[] | null,
|
||||
): Promise<TourDetailResponse> {
|
||||
if (!waypoints) throw badRequest('The stop cannot go in there: name another point of the tour.');
|
||||
return this.hikes.update(userId, tripId, { placeId, expected_revision: expectedRevision, waypoints });
|
||||
}
|
||||
|
||||
/** A city walk saved through one change, as save_tour_change saves a confirmed proposal, then read as it is now. */
|
||||
private async saveWalk(
|
||||
userId: number,
|
||||
tripId: number,
|
||||
placeId: number,
|
||||
expectedRevision: number,
|
||||
change: TourChange,
|
||||
): Promise<TourDetailResponse> {
|
||||
const changes = [change];
|
||||
const proposalId = proposalIdOf({ tripId, placeId, revision: expectedRevision, changes });
|
||||
await this.walkChanges.save(tripId, placeId, userId, {
|
||||
changes,
|
||||
expected_revision: expectedRevision,
|
||||
proposal_id: proposalId,
|
||||
confirmed: true,
|
||||
});
|
||||
return this.tours.getTour(String(tripId), String(placeId));
|
||||
}
|
||||
}
|
||||
@@ -78,6 +78,8 @@ import { TourSkiController } from './tour-ski.controller';
|
||||
import { TourSkiService } from './tour-ski.service';
|
||||
import { TourSportWritesMcp } from './tour-sport-writes.mcp';
|
||||
import { TourTrailDetailsService } from './tour-trail-details.service';
|
||||
import { TourStopsMcp } from './tour-stops.mcp';
|
||||
import { TourStopsService } from './tour-stops.service';
|
||||
import { TourTrailGradeController } from './tour-trail-grade.controller';
|
||||
import { TourTrailGradeService } from './tour-trail-grade.service';
|
||||
import { TourVisitsController } from './tour-visits.controller';
|
||||
@@ -238,6 +240,7 @@ import { Module } from '@nestjs/common';
|
||||
TourChangePreviewService,
|
||||
TourChangeSaveService,
|
||||
TourChangeUndoService,
|
||||
TourStopsService,
|
||||
TourDraftsService,
|
||||
TourActivitiesService,
|
||||
TourActivityStatsService,
|
||||
@@ -261,6 +264,8 @@ import { Module } from '@nestjs/common';
|
||||
TourSportWritesMcp,
|
||||
HikeWaysMcp,
|
||||
ToursWandererMcp,
|
||||
// P6: a found place taken into a saved hike or city walk, and out again.
|
||||
TourStopsMcp,
|
||||
],
|
||||
})
|
||||
export class ToursModule {}
|
||||
|
||||
Reference in New Issue
Block a user