feat(tours): a city walk prepared from a briefing over MCP, and the station fields an assistant reads spelled out (CW-10, CW-11)

An assistant connected over MCP can now prepare a city walk from what the
traveller tells it. propose_city_walk takes a start (and an end), a time
frame on a day of the trip, the themes of CW-05, the stations the
traveller wishes for, the places of the trip it may use and fixed
appointments with their times, and saves nothing. Places for the themes
come from the search along a tour, at most eight, each with the theme,
category and source that brought it; nothing is made up. The stations are
ordered on estimates over the straight distance, and a place of a theme or
of the trip goes in only where it is open on arrival, keeps the frame and
the appointments, and leaves every station already on the walk open when
the walk gets there. The walk in that order is then planned on foot by the
router the road trip uses (the traveller's own routing server where they
set one), and its legs give the walking distance and time from one station
to the next. Where the router cannot be reached, or a station lies more
than 300 m off every way (the planner's limit, now shared with the
server), the times are estimates over the straight distance with an
allowance for streets at 4.5 km/h, and the answer says so and why. The
answer gives the arrival and leave times, the stay where the traveller
gave it and unknown otherwise, which makes every later arrival the
earliest one, and the opening hours checked against the arrival on that
day with the helpers the planner uses. Walking and stays are counted
apart, the total is complete only when every stay is known, and the
minutes the frame leaves for the unknown stays are named. Free time before
an appointment or at the end, wishes and appointments that cannot be kept
as asked, and places left out with their reason are listed; a tour of the
trip offered as a station is named as a tour. A wish or an appointment is
never dropped; an appointment is a must and protected. A place's default
duration is not read as a stay: every place carries one, so it says
nothing.

Once the traveller confirms, create_city_walk saves the walk through the
same creation the planner's save uses: one write, a key for every station,
the links to the trip's places checked, the trip told, with place editing
permission on the trip. Its way on foot is planned by the same router and
saved with the walk, together with its distance and walking time. Where
the router gives no way, the walk is saved with its stations only and the
answer says why: no line, no distance and no walking time. The tours list
says so (route_pending), the tour detail says in one line that the way is
planned in the planner, and opening the walk in the planner plans its way
at once and offers to save it, with a note once it is planned that it was
just planned. Such a walk can be saved as a new tour and taken over into
another trip, starting at its first stop, and is never offered as a place
to stay. A tour without a line needs two points of its own.

get_tour_plan now spells out every field of a city walk's stations: key,
name, stay (null when not known), importance (null for normal), protection
(false when not set) and opening hours (null when none are known);
list_tours names the station count and whether a walk waits for its way,
get_city_walk_progress gives each station's key and opening hours, and
take_over_tour says a walk keeps its stations with their protection. No
tool changes a walk's stations; deleting a walk's place takes its stations
along, protected ones included, and both delete tools now ask the
assistant to name those and ask the traveller first. REST answers the
stations as before.

A tour create refused for a type that is switched off, a description that
is too long or planned times out of range is a domain refusal now, so an
assistant gets the same text REST sends; REST still answers it as an error
at 400.
This commit is contained in:
Maurice
2026-10-20 06:22:30 +00:00
parent f79b2020d6
commit 554d6f1b9f
69 changed files with 2994 additions and 102 deletions
+16 -1
View File
@@ -40,6 +40,8 @@ export interface TourListRow {
has_recorded_track: number;
planned: number;
has_waypoints: number;
/** CW-11: 1 while the owning place has no line, a city walk saved with its stations only. */
route_missing: number;
/** P2C-03: the tour's technical revision. */
revision: number;
/** MF-08: a hike's routing preferences, still JSON text. */
@@ -249,6 +251,7 @@ export class ToursRepository extends TrekRepository<Tours> {
't.revision as revision',
't.hiking_preferences as hiking_preferences',
eb('t.recorded_route_geometry', 'is not', null).as('has_recorded_track'),
eb('p.route_geometry', 'is', null).as('route_missing'),
eb
.exists(eb.selectFrom('day_assignments as da').select('da.id').whereRef('da.place_id', '=', 'p.id'))
.as('planned'),
@@ -510,6 +513,16 @@ export class ToursRepository extends TrekRepository<Tours> {
.execute();
}
/** CW-11: a day of this trip with its date, for a city walk proposed on it; `undefined` for a day of another trip. */
async dayOfTrip(trip_id: number, day_id: number): Promise<{ id: number; date: string | null } | undefined> {
return await this.db()
.selectFrom('days')
.select(['id', 'date'])
.where('id', '=', day_id)
.where('trip_id', '=', trip_id)
.executeTakeFirst();
}
/** TO3 — `SELECT 1 FROM tours WHERE place_id = ?`: whether the place is a tour. */
async existsForPlace(place_id: number): Promise<boolean> {
const row = await this.db()
@@ -780,10 +793,11 @@ function toLibraryRow<R extends Omit<TourLibraryRow, 'has_waypoints'> & { has_wa
}
function toListRow<
R extends Omit<TourListRow, 'planned' | 'has_waypoints' | 'has_recorded_track'> & {
R extends Omit<TourListRow, 'planned' | 'has_waypoints' | 'has_recorded_track' | 'route_missing'> & {
planned: unknown;
has_waypoints: unknown;
has_recorded_track: unknown;
route_missing: unknown;
},
>(r: R): TourListRow {
return {
@@ -791,5 +805,6 @@ function toListRow<
planned: Number(r.planned),
has_waypoints: Number(r.has_waypoints),
has_recorded_track: Number(r.has_recorded_track),
route_missing: Number(r.route_missing),
};
}
@@ -1,9 +1,9 @@
/** What a drawn tour writes onto its owning place. */
/** What a drawn tour writes onto its owning place; a city walk saved with its stations only has no line yet (CW-11). */
export interface TourPlaceWrite {
name: string;
lat: number;
lng: number;
route_geometry: string;
route_geometry: string | null;
description?: string | null;
website?: string | null;
}
+2 -2
View File
@@ -276,7 +276,7 @@ export class PlacesMcp {
@Tool({
name: 'delete_place',
description: 'Permanently delete a place from a trip. Removes its day assignments, its linked expenses and any nights booked at it, including each night\'s reservation and that reservation\'s expense. If the place is a Tour, its route and editable waypoints are also permanently deleted. Warn the user before calling: this cannot be undone.',
description: 'Permanently delete a place from a trip. Removes its day assignments, its linked expenses and any nights booked at it, including each night\'s reservation and that reservation\'s expense. If the place is a Tour, its route and editable waypoints are also permanently deleted. A city walk takes all its stations with it, protected ones included: name those to the traveller and ask first. Warn the user before calling: this cannot be undone.',
inputSchema: {
tripId: idSchema,
placeId: idSchema,
@@ -447,7 +447,7 @@ export class PlacesMcp {
@Tool({
name: 'bulk_delete_places',
description: 'Permanently delete multiple places from a trip at once. Removes all day assignments for each place as well, plus each place\'s linked expenses and any nights booked at it, with their reservations and expenses. Any Tours in the selection also lose their routes and editable waypoints. Warn the user before calling: this cannot be undone.',
description: 'Permanently delete multiple places from a trip at once. Removes all day assignments for each place as well, plus each place\'s linked expenses and any nights booked at it, with their reservations and expenses. Any Tours in the selection also lose their routes and editable waypoints. A city walk in the selection takes all its stations with it, protected ones included: name those to the traveller and ask first. Warn the user before calling: this cannot be undone.',
inputSchema: {
tripId: idSchema,
placeIds: z.array(idSchema).min(1).max(200),
+2 -1
View File
@@ -129,6 +129,7 @@ import { Module } from '@nestjs/common';
RoadtripPlanService,
RoadtripPlanningMcp,
],
exports: [RoadtripService],
// The router also plans a city walk on foot that an assistant prepares (CW-11).
exports: [RoadtripService, RoadtripRouterService],
})
export class RoadtripModule {}
@@ -0,0 +1,593 @@
import { badRequest } from '../common/domain-error';
import {
clockOf,
haversineMetres,
minutesOf,
stationFit,
stationHoursOn,
TOUR_MAX_SNAP_M,
TOUR_POI_MAX_CATEGORIES,
TOUR_STATION_HOURS_MAX,
TOUR_STATION_NAME_MAX,
WALK_THEMES,
type CityWalkStation,
type HoursSource,
type HoursWindow,
type StationFit,
type TourPoi,
type TourPoiCategory,
type WalkTheme,
} from '@trek/shared';
/**
* CW-11: a city walk proposed from a briefing, worked out without guessing.
* The stations are ordered on estimates over the straight distance with an
* allowance for streets; the walk in that order is then planned on foot by the
* router, and its legs time the walk. Where the router gives no way, the
* estimates stand and say so. A stay is known only where the traveller gave
* it, and every other stay stays unknown, which makes the arrivals after it
* lower bounds. Opening hours are read with the helpers the planner and the
* tour detail use, and a lower bound is never called a conflict unless it
* already is one.
*/
/** The walking pace of the estimate, 4.5 km/h, in metres a minute. */
const WALK_PACE_M_PER_MIN = 75;
/** The allowance for streets over the straight distance. */
const STREET_FACTOR = 1.3;
/** Closer than this, a place found is a station the traveller already named. */
const SAME_PLACE_M = 60;
type BriefingSource = 'start' | 'end' | 'wished' | 'appointment' | 'trip_place' | 'theme';
/** Why a place of a theme is in: its theme and category, the source that has it, how far from the line searched. */
interface ThemeFind {
theme: WalkTheme;
category: TourPoiCategory;
kind: string;
found_in: string;
poi_id: string;
distance_to_search_m: number;
}
/** A station the walk may get, as the proposal weighs it. */
export interface WalkCandidate {
source: BriefingSource;
name: string | null;
lat: number;
lng: number;
/** Minutes; null when nobody said. */
stay: number | null;
/** A trip place's own hours, seven days as JSON. */
placeHours: string | null;
/** Hours as OpenStreetMap writes them. */
osmHours: string | null;
/** The trip place it stands for. */
placeId: number | null;
/** An appointment's time, minutes after midnight. */
time: number | null;
find: ThemeFind | null;
}
/** The frame of a walk in minutes after midnight, and the date its hours are read for. */
export interface WalkFrame {
start: number;
end: number;
date: string | null;
}
export type LeftOutReason =
'closed_all_day' | 'closed_at_arrival' | 'closes_during_stay' | 'no_time' | 'no_position' | 'not_in_trip' | 'is_tour';
export interface LeftOut {
name: string | null;
source: BriefingSource;
place_id: number | null;
poi_id: string | null;
reason: LeftOutReason;
}
type StationConflict = 'closed_all_day' | 'closed_at_arrival' | 'closes_during_stay' | 'late' | 'after_frame';
type HoursConflict = Extract<StationConflict, LeftOutReason>;
type Clock = { from: string; to: string };
/** What a station's hours say about the visit, as an assistant reads it. */
export type HoursCheck =
| { kind: 'no_date' }
| { kind: 'unknown' }
| { kind: 'unread'; text: string }
| { kind: 'next_day' }
| { kind: 'uncertain'; source: HoursSource }
| { kind: 'open'; source: HoursSource; window: Clock }
| { kind: 'closed_all_day'; source: HoursSource }
| { kind: 'closed'; source: HoursSource; windows: Clock[] }
| { kind: 'closes'; source: HoursSource; window: Clock };
interface Leg {
metres: number;
minutes: number;
}
/** The way on foot between the stations as the router planned it, or why the estimates stand in for it. */
export type FootWay =
| { kind: 'routed'; line: Array<[number, number]>; legs: Leg[]; seconds: number }
| {
kind: 'unrouted';
why: 'nothing_to_route' | 'router_unavailable' | 'station_off_the_way';
/** The station no way reaches, counted from 1. */
position: number | null;
};
/** What the router answers for the stations: its line, a part for each leg, and how far it moved each station onto a way. */
export interface FootRouteAnswer {
leg: { line: Array<[number, number]> };
parts: ReadonlyArray<{ distance: number; duration: number }>;
snapped?: ReadonlyArray<{ meters: number }>;
}
interface Visit {
node: WalkCandidate;
leg: Leg | null;
arrival: number;
/** The arrival is only a lower bound: a stay before it is not known. */
earliest: boolean;
leave: number | null;
lateBy: number;
roomBefore: number;
fit: StationFit | 'no_date' | null;
}
interface Timeline {
visits: Visit[];
endsAt: number;
endsEarliest: boolean;
}
/** The frame a briefing gives; refused when it ends before it starts or an appointment lies outside it. */
export function frameOf(
briefing: { start_time: string; end_time: string; appointments?: ReadonlyArray<{ time: string }> },
date: string | null,
): WalkFrame {
const start = minutesOf(briefing.start_time) ?? Number.NaN;
const end = minutesOf(briefing.end_time) ?? Number.NaN;
if (!(end > start)) throw badRequest('end_time must be after start_time, both HH:MM on one day');
const outside = (briefing.appointments ?? []).some((appointment) => {
const time = minutesOf(appointment.time) ?? Number.NaN;
return !(time >= start && time <= end);
});
if (outside) throw badRequest('An appointment has to lie between start_time and end_time');
return { start, end, date };
}
/** The categories the themes ask for, each with the first theme that brought it, as many as one search takes. */
export function briefingCategories(themes: readonly WalkTheme[]): {
searched: Array<{ category: TourPoiCategory; theme: WalkTheme }>;
notSearched: TourPoiCategory[];
} {
const all = themes.flatMap((theme) => WALK_THEMES[theme].map((category) => ({ category, theme })));
const unique = all.filter((entry, index) => all.findIndex((other) => other.category === entry.category) === index);
return {
searched: unique.slice(0, TOUR_POI_MAX_CATEGORIES),
notSearched: unique.slice(TOUR_POI_MAX_CATEGORIES).map((entry) => entry.category),
};
}
function metresBetween(a: { lat: number; lng: number }, b: { lat: number; lng: number }): number {
return haversineMetres(a.lat, a.lng, b.lat, b.lng);
}
/** The straight distance and the walking time it estimates. */
export function legOf(from: { lat: number; lng: number }, to: { lat: number; lng: number }): Leg {
const metres = metresBetween(from, to);
return { metres: Math.round(metres), minutes: Math.ceil((metres * STREET_FACTOR) / WALK_PACE_M_PER_MIN) };
}
/**
* The router's way as the walk takes it: each leg's distance and walking time,
* and the line. A station the router had to move further onto a way than the
* planner allows is one no way on foot reaches, and the way is not taken.
*/
export function footWayOf(answer: FootRouteAnswer): FootWay {
const off = (answer.snapped ?? []).findIndex((point) => point.meters > TOUR_MAX_SNAP_M);
if (off >= 0) return { kind: 'unrouted', why: 'station_off_the_way', position: off + 1 };
return {
kind: 'routed',
line: answer.leg.line,
legs: answer.parts.map((part) => ({ metres: Math.round(part.distance), minutes: Math.ceil(part.duration / 60) })),
seconds: answer.parts.reduce((sum, part) => sum + part.duration, 0),
};
}
/**
* The places of the themes as candidates, the nearest to the line searched
* first, taking turns between the categories so each theme is heard. A place
* without a name, or one where the traveller already named a station, is not
* offered.
*/
export function themeCandidates(
pois: readonly TourPoi[],
searched: ReadonlyArray<{ category: TourPoiCategory; theme: WalkTheme }>,
taken: ReadonlyArray<{ lat: number; lng: number }>,
): WalkCandidate[] {
const offered = pois.filter(
(poi) => poi.name.trim() !== '' && !taken.some((spot) => metresBetween(spot, poi) <= SAME_PLACE_M),
);
const queues = searched.map(({ category, theme }) =>
offered
.filter((poi) => poi.category === category)
.sort((a, b) => a.distance_m - b.distance_m)
.map((poi) => themeCandidate(poi, theme)),
);
const rounds = Math.max(0, ...queues.map((queue) => queue.length));
return Array.from({ length: rounds }, (_, round) => queues.flatMap((queue) => queue.slice(round, round + 1))).flat();
}
function themeCandidate(poi: TourPoi, theme: WalkTheme): WalkCandidate {
return {
source: 'theme',
name: poi.name,
lat: poi.lat,
lng: poi.lng,
stay: null,
placeHours: null,
osmHours: poi.opening_hours,
placeId: null,
time: null,
find: {
theme,
category: poi.category,
kind: poi.kind,
found_in: poi.source,
poi_id: poi.id,
distance_to_search_m: poi.distance_m,
},
};
}
function fitOf(node: WalkCandidate, at: { arrival: number; atLeast: boolean }, date: string | null): Visit['fit'] {
if (node.source === 'start' || node.source === 'end') return null;
if (date === null) return 'no_date';
return stationFit(stationHoursOn({ place: node.placeHours, osm: node.osmHours }, date), at, node.stay);
}
/**
* The arrivals along the walk: the start at its time, the walking time of each
* leg (the router's where it planned the way, else the estimate), the stays as
* far as known. An appointment's own time sets the clock again once the walk
* is there in time; a stay not known makes every later arrival a lower bound
* until then.
*/
function timelineOf(route: readonly WalkCandidate[], frame: WalkFrame, legs?: readonly Leg[]): Timeline {
let clock = frame.start;
let unknownBefore = false;
const visits = route.map((node, index): Visit => {
const leg = index > 0 ? (legs?.[index - 1] ?? legOf(route[index - 1], node)) : null;
clock += leg?.minutes ?? 0;
const lateBy = node.time === null ? 0 : Math.max(0, clock - node.time);
const roomBefore = node.time === null ? 0 : Math.max(0, node.time - clock);
if (node.time !== null && lateBy === 0) {
clock = node.time;
unknownBefore = false;
}
const at = { arrival: clock, atLeast: unknownBefore };
const fit = fitOf(node, at, frame.date);
if (node.stay === null) unknownBefore = true;
else clock += node.stay;
return {
node,
leg,
arrival: at.arrival,
earliest: at.atLeast,
leave: node.stay === null ? null : clock,
lateBy,
roomBefore,
fit,
};
});
return { visits, endsAt: clock, endsEarliest: unknownBefore };
}
const HOURS_CONFLICTS: Partial<Record<StationFit['kind'], HoursConflict>> = {
closedAllDay: 'closed_all_day',
closed: 'closed_at_arrival',
closes: 'closes_during_stay',
};
function hoursConflictOf(visit: Visit): HoursConflict | undefined {
return visit.fit && visit.fit !== 'no_date' ? HOURS_CONFLICTS[visit.fit.kind] : undefined;
}
/** How far the walk misses its times: appointments reached late, and the end past the frame. */
function overrunOf(timeline: Timeline, frame: WalkFrame): number {
return timeline.visits.reduce((sum, visit) => sum + visit.lateBy, Math.max(0, timeline.endsAt - frame.end));
}
/** The places a station may take: after the start, and before the end when the walk has one. */
function slotsOf(route: readonly WalkCandidate[], hasEnd: boolean): number[] {
return Array.from({ length: route.length - (hasEnd ? 1 : 0) }, (_, index) => index + 1);
}
/** The straight metres a station adds where it goes in. */
function detourOf(route: readonly WalkCandidate[], at: number, station: WalkCandidate): number {
const before = route[at - 1];
const after = route[at];
const to = metresBetween(before, station);
return after ? to + metresBetween(station, after) - metresBetween(before, after) : to;
}
/**
* Where a station goes: the cheapest place it fits, open on arrival, without
* making an appointment late or the walk end later past its frame, and
* without bringing a station already on the walk there after it closed; the
* cheapest place and what stands in its way otherwise.
*/
function placed(
route: readonly WalkCandidate[],
station: WalkCandidate,
frame: WalkFrame,
hasEnd: boolean,
): { route: WalkCandidate[]; trouble: Exclude<LeftOutReason, 'no_position' | 'not_in_trip' | 'is_tour'> | null } {
const before = timelineOf(route, frame);
const base = overrunOf(before, frame);
const closedBefore = new Set(
before.visits.filter((visit) => hoursConflictOf(visit) !== undefined).map((visit) => visit.node),
);
const options = slotsOf(route, hasEnd)
.map((at) => {
const next = [...route.slice(0, at), station, ...route.slice(at)];
const timeline = timelineOf(next, frame);
const visit = timeline.visits[at];
const late = visit.arrival > frame.end || overrunOf(timeline, frame) > base;
const closesOther = timeline.visits.some(
(other, index) => index !== at && hoursConflictOf(other) !== undefined && !closedBefore.has(other.node),
);
return {
route: next,
trouble: hoursConflictOf(visit) ?? (late || closesOther ? ('no_time' as const) : null),
detour: detourOf(route, at, station),
};
})
.sort((a, b) => a.detour - b.detour);
return options.find((option) => option.trouble === null) ?? options[0];
}
function leftOutOf(station: WalkCandidate, reason: LeftOutReason): LeftOut {
return {
name: station.name,
source: station.source,
place_id: station.placeId,
poi_id: station.find?.poi_id ?? null,
reason,
};
}
export interface WalkPlanInput {
frame: WalkFrame;
start: WalkCandidate;
end: WalkCandidate | null;
appointments: WalkCandidate[];
wished: WalkCandidate[];
tripPlaces: WalkCandidate[];
/** In the order they are offered. */
themes: WalkCandidate[];
themeLimit: number;
}
/**
* The stations in their order: the start, the appointments in time order and
* the end stay where they are; every wished station goes in, where it fits
* best, whatever stands in its way; a trip place and a place of a theme go in
* only where they fit, and a theme takes at most `themeLimit` places, looking
* at twice as many. What did not fit is left out with the reason.
*/
export function planWalk(input: WalkPlanInput): { route: WalkCandidate[]; leftOut: LeftOut[] } {
const hasEnd = input.end !== null;
const appointments = [...input.appointments].sort((a, b) => Number(a.time) - Number(b.time));
let route = [input.start, ...appointments, ...(input.end ? [input.end] : [])];
const leftOut: LeftOut[] = [];
for (const station of input.wished) route = placed(route, station, input.frame, hasEnd).route;
const offer = (station: WalkCandidate) => {
const option = placed(route, station, input.frame, hasEnd);
if (option.trouble === null) route = option.route;
else leftOut.push(leftOutOf(station, option.trouble));
return option.trouble === null;
};
input.tripPlaces.forEach(offer);
let taken = 0;
for (const station of input.themes.slice(0, input.themeLimit * 2)) {
if (taken < input.themeLimit && offer(station)) taken += 1;
}
return { route, leftOut };
}
function clockSpan([from, to]: HoursWindow): Clock {
return { from: clockOf(from), to: clockOf(to) };
}
/** A station's hours check as an assistant reads it. */
export function hoursCheckOf(fit: StationFit | 'no_date'): HoursCheck {
if (fit === 'no_date') return { kind: 'no_date' };
switch (fit.kind) {
case 'unknown':
return { kind: 'unknown' };
case 'unread':
return { kind: 'unread', text: fit.text };
case 'nextDay':
return { kind: 'next_day' };
case 'uncertain':
return { kind: 'uncertain', source: fit.source };
case 'open':
return { kind: 'open', source: fit.source, window: clockSpan(fit.window) };
case 'closedAllDay':
return { kind: 'closed_all_day', source: fit.source };
case 'closed':
return { kind: 'closed', source: fit.source, windows: fit.windows.map(clockSpan) };
case 'closes':
return { kind: 'closes', source: fit.source, window: clockSpan(fit.window) };
}
}
function conflictsOf(visit: Visit, frame: WalkFrame): StationConflict[] {
const hours = hoursConflictOf(visit);
return [
...(hours ? [hours] : []),
...(visit.lateBy > 0 ? (['late'] as const) : []),
...(visit.arrival > frame.end ? (['after_frame'] as const) : []),
];
}
const IMPORTANCE: Record<BriefingSource, 'must' | 'optional' | null> = {
start: null,
end: null,
wished: 'must',
appointment: 'must',
trip_place: null,
theme: 'optional',
};
/** A station as create_city_walk takes it: what the proposal knows, nothing more. */
function stationForCreate(node: WalkCandidate): CityWalkStation {
const hours = node.osmHours?.trim() ?? '';
return {
lat: node.lat,
lng: node.lng,
name: node.name?.slice(0, TOUR_STATION_NAME_MAX) ?? null,
stay_minutes: node.stay,
importance: IMPORTANCE[node.source],
protected: node.source === 'appointment',
// Hours too long to keep are left out rather than cut into something else.
opening_hours: hours && hours.length <= TOUR_STATION_HOURS_MAX ? hours : null,
linked_place_id: node.placeId,
};
}
/** Where a known stay comes from: the traveller, or the frame, which leaves the start and ends at the end; null when not known. */
function staySourceOf(node: WalkCandidate): 'given' | 'frame' | null {
if (node.stay === null) return null;
return node.source === 'start' || node.source === 'end' ? 'frame' : 'given';
}
function stationOf(visit: Visit, index: number, frame: WalkFrame) {
const { node } = visit;
return {
position: index + 1,
name: node.name,
lat: node.lat,
lng: node.lng,
source: node.source,
found: node.find,
place_id: node.placeId,
walk_from_previous: visit.leg && { metres: visit.leg.metres, minutes: visit.leg.minutes },
arrival: clockOf(visit.arrival),
arrival_is_earliest: visit.earliest,
appointment_time: node.time === null ? null : clockOf(node.time),
stay_minutes: node.stay,
stay_source: staySourceOf(node),
leave: visit.leave === null ? null : clockOf(visit.leave),
importance: IMPORTANCE[node.source],
protected: node.source === 'appointment',
opening_hours: node.osmHours,
hours: visit.fit && hoursCheckOf(visit.fit),
conflicts: conflictsOf(visit, frame),
};
}
interface Gap {
before_position: number | null;
from: string;
to: string;
minutes: number;
unknown_stays: number;
kind: 'before_appointment' | 'at_end';
}
/** Free time before an appointment the walk reaches early, and at the end of the frame, with the unknown stays it may take. */
function gapsOf(timeline: Timeline, frame: WalkFrame): Gap[] {
const gaps: Gap[] = [];
let unknown = 0;
timeline.visits.forEach((visit, index) => {
if (visit.node.time !== null) {
if (visit.roomBefore > 0) {
const from = clockOf(visit.arrival - visit.roomBefore);
gaps.push({
before_position: index + 1,
from,
to: clockOf(visit.arrival),
minutes: visit.roomBefore,
unknown_stays: unknown,
kind: 'before_appointment',
});
}
unknown = 0;
}
if (visit.node.stay === null) unknown += 1;
});
const room = frame.end - timeline.endsAt;
if (room > 0) {
gaps.push({
before_position: null,
from: clockOf(timeline.endsAt),
to: clockOf(frame.end),
minutes: room,
unknown_stays: unknown,
kind: 'at_end',
});
}
return gaps;
}
function totalsOf(timeline: Timeline, gaps: readonly Gap[], frame: WalkFrame) {
const { visits } = timeline;
const walk = visits.reduce((sum, visit) => sum + (visit.leg?.minutes ?? 0), 0);
const stays = visits.reduce((sum, visit) => sum + (visit.node.stay ?? 0), 0);
const unknown = visits.filter((visit) => visit.node.stay === null).length;
return {
walk_minutes: walk,
walk_m: visits.reduce((sum, visit) => sum + (visit.leg?.metres ?? 0), 0),
stay_minutes_known: stays,
stays_unknown: unknown,
total_minutes: walk + stays,
total_complete: unknown === 0,
ends_at: clockOf(timeline.endsAt),
ends_at_is_earliest: timeline.endsEarliest,
over_frame_by_minutes: Math.max(0, timeline.endsAt - frame.end),
minutes_left_for_unknown_stays:
unknown === 0 ? null : gaps.filter((gap) => gap.unknown_stays > 0).reduce((sum, gap) => sum + gap.minutes, 0),
};
}
/** How the walking times were found: the router's way on foot, or the estimate over the straight distance and why. */
function estimateOf(way: FootWay) {
if (way.kind === 'routed') return { kind: 'routed' as const, profile: 'walking' as const };
return {
kind: 'straight_line' as const,
street_factor: STREET_FACTOR,
pace_kmh: (WALK_PACE_M_PER_MIN * 60) / 1000,
why: way.why,
position: way.position,
};
}
/** The walk as the proposal says it: its stations with their times, the gaps, the totals and what create_city_walk takes. */
export function describeWalk(route: readonly WalkCandidate[], frame: WalkFrame, way: FootWay) {
const timeline = timelineOf(route, frame, way.kind === 'routed' ? way.legs : undefined);
const stations = timeline.visits.map((visit, index) => stationOf(visit, index, frame));
const gaps = gapsOf(timeline, frame);
const stationsForCreate = route.map(stationForCreate);
return {
date: frame.date,
frame: { start_time: clockOf(frame.start), end_time: clockOf(frame.end) },
stations,
wishes_not_met: stations
.filter(
(station) => (station.source === 'wished' || station.source === 'appointment') && station.conflicts.length > 0,
)
.map(({ position, name, source, conflicts }) => ({ position, name, source, conflicts })),
gaps,
totals: totalsOf(timeline, gaps, frame),
estimate: estimateOf(way),
stations_for_create: stationsForCreate,
can_create: stationsForCreate.length >= 2,
};
}
@@ -0,0 +1,241 @@
import { Places } from '../../db/entities/Places.entity';
import { TourWaypoints } from '../../db/entities/TourWaypoints.entity';
import { Tours } from '../../db/entities/Tours.entity';
import type { PlaceRow, PlacesRepository } from '../../db/repositories/Places.repository';
import type { TourWaypointsRepository } from '../../db/repositories/TourWaypoints.repository';
import type { ToursRepository } from '../../db/repositories/Tours.repository';
import { logWarn } from '../audit/audit-log.logger';
import { notFound } from '../common/domain-error';
import { RoadtripRouterService } from '../roadtrip/roadtrip-router.service';
import {
briefingCategories,
describeWalk,
footWayOf,
frameOf,
planWalk,
themeCandidates,
type FootWay,
type LeftOut,
type LeftOutReason,
type WalkCandidate,
} from './city-walk-briefing.helpers';
import { TourPoiSearchService } from './tour-poi-search.service';
import { ToursService } from './tours.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import {
CITY_WALK_BRIEFING_LIMITS,
minutesOf,
type CityWalkBriefingRequest,
type CityWalkCreateRequest,
type TourPoiSearchResponse,
} from '@trek/shared';
/** How far from the start, the wishes and the appointments the themes are searched when the briefing does not say. */
const DEFAULT_CORRIDOR_M = 1000;
/**
* The day the router is asked for. A way on foot does not depend on the day:
* the router only keys its cache by one and hands it to a routing plugin,
* which a walk on foot never asks.
*/
const ANY_DAY = 0;
/** The places of the trip a briefing names, and which of them a station may stand for (no tour). */
interface NamedPlaces {
rows: Map<number, PlaceRow>;
linkable: Set<number>;
}
type Spot = { name?: string; lat: number; lng: number };
/** The traveller's own point, a start, an end, a wish or an appointment, as a candidate. */
function given(
source: WalkCandidate['source'],
spot: Spot,
more: Partial<Pick<WalkCandidate, 'stay' | 'osmHours' | 'time' | 'placeId' | 'placeHours'>>,
): WalkCandidate {
return {
source,
name: spot.name ?? null,
lat: spot.lat,
lng: spot.lng,
stay: more.stay ?? null,
placeHours: more.placeHours ?? null,
osmHours: more.osmHours ?? null,
placeId: more.placeId ?? null,
time: more.time ?? null,
find: null,
};
}
/** A place of the trip the traveller allowed, as a candidate, or why it cannot be one. */
function tripPlaceOf(
choice: { place_id: number; stay_minutes?: number | null },
known: NamedPlaces,
): WalkCandidate | LeftOut {
const place = known.rows.get(choice.place_id);
const refused = (reason: LeftOutReason): LeftOut => ({
name: place?.name ?? null,
source: 'trip_place',
place_id: choice.place_id,
poi_id: null,
reason,
});
if (!place) return refused('not_in_trip');
if (!known.linkable.has(place.id)) return refused('is_tour');
if (place.lat == null || place.lng == null) return refused('no_position');
return given(
'trip_place',
{ name: place.name, lat: place.lat, lng: place.lng },
{ stay: choice.stay_minutes, placeHours: place.opening_hours, placeId: place.id },
);
}
/**
* CW-11: a city walk proposed from a briefing, for an assistant to show the
* traveller before anything is saved. It reads the trip's day and places,
* searches the places of the themes with the search along a tour uses and
* plans the way on foot with the router the road trip uses (the traveller's
* own routing server where they set one); it writes nothing. The walk is
* created only through create_city_walk, once the traveller confirmed it,
* with its way planned by the same router.
*/
@Injectable()
export class CityWalkBriefingService {
constructor(
private readonly poiSearch: TourPoiSearchService,
private readonly router: RoadtripRouterService,
private readonly tours: ToursService,
@InjectRepository(Tours) private readonly toursRepo: ToursRepository,
@InjectRepository(TourWaypoints) private readonly waypointsRepo: TourWaypointsRepository,
@InjectRepository(Places) private readonly placesRepo: PlacesRepository,
) {}
async propose(tripId: number, userId: number, briefing: CityWalkBriefingRequest) {
const frame = frameOf(briefing, await this.dateOf(tripId, briefing.day_id));
const known = await this.tripPlacesOf(tripId, briefing);
const choices = (briefing.trip_places ?? []).map((choice) => tripPlaceOf(choice, known));
const leftOut = choices.filter((choice): choice is LeftOut => 'reason' in choice);
const tripPlaces = choices.filter((choice): choice is WalkCandidate => !('reason' in choice));
const wished = (briefing.wished ?? []).map((wish) =>
given('wished', wish, { stay: wish.stay_minutes, osmHours: wish.opening_hours }),
);
const appointments = (briefing.appointments ?? []).map((appointment) => {
const id = appointment.place_id;
const place = id !== undefined && known.linkable.has(id) ? known.rows.get(id) : undefined;
return given('appointment', appointment, {
stay: appointment.stay_minutes,
time: minutesOf(appointment.time),
placeId: place?.id,
placeHours: place?.opening_hours,
});
});
const start = given('start', briefing.start, { stay: 0 });
const end = briefing.end ? given('end', briefing.end, { stay: 0 }) : null;
const named = [start, ...wished, ...tripPlaces, ...appointments, ...(end ? [end] : [])];
const theme = await this.themePlaces(briefing, named);
const plan = planWalk({
frame,
start,
end,
appointments,
wished,
tripPlaces,
themes: theme.candidates,
themeLimit: theme.limit,
});
return {
...describeWalk(plan.route, frame, await this.footWay(userId, tripId, plan.route)),
left_out: [...leftOut, ...plan.leftOut],
searched: theme.searched,
};
}
/**
* The walk the traveller confirmed, created through the creation the
* planner's save uses, with its way on foot planned by the router the
* proposal used. Where the router gives no way, the walk is saved with its
* stations only and says why; no straight line is stored as a route.
*/
async create(tripId: number, userId: number, body: CityWalkCreateRequest) {
const way = await this.footWay(userId, tripId, body.stations);
const created = await this.tours.createCityWalk(String(tripId), body, way.kind === 'routed' ? way : null);
return {
...created,
foot_way: way.kind === 'routed' ? { planned: true } : { planned: false, why: way.why, position: way.position },
};
}
/** The way on foot through the stations in their order, or why there is none. */
private async footWay(
userId: number,
tripId: number,
stations: ReadonlyArray<{ lat: number; lng: number }>,
): Promise<FootWay> {
if (stations.length < 2) return { kind: 'unrouted', why: 'nothing_to_route', position: null };
const points = stations.map(({ lat, lng }) => ({ lat, lng }));
try {
return footWayOf(await this.router.route(userId, tripId, ANY_DAY, points, 'walking', []));
} catch (err: unknown) {
logWarn(`[CityWalk] no way on foot for trip ${tripId}: ${err instanceof Error ? err.message : String(err)}`);
return { kind: 'unrouted', why: 'router_unavailable', position: null };
}
}
/** The date of the day the walk is for, null without one; a day of another trip is not found. */
private async dateOf(tripId: number, dayId: number | undefined): Promise<string | null> {
if (dayId === undefined) return null;
const day = await this.toursRepo.dayOfTrip(tripId, dayId);
if (!day) throw notFound('Day not found');
return day.date;
}
/** The places of this trip the briefing names, none of another trip, and those a station may stand for: no tour. */
private async tripPlacesOf(tripId: number, briefing: CityWalkBriefingRequest): Promise<NamedPlaces> {
const ids = [
...new Set([
...(briefing.trip_places ?? []).map((choice) => choice.place_id),
...(briefing.appointments ?? []).flatMap((appointment) => appointment.place_id ?? []),
]),
];
const [linkable, rows] = await Promise.all([
this.waypointsRepo.linkablePlaceIds(tripId, ids),
Promise.all(ids.map((id) => this.placesRepo.findInTrip(id, tripId))),
]);
const found = rows.filter((row): row is PlaceRow => row !== undefined);
return { rows: new Map(found.map((row) => [row.id, row])), linkable };
}
/** The places of the themes along the traveller's own points, or none when the briefing asks for none. */
private async themePlaces(briefing: CityWalkBriefingRequest, named: readonly WalkCandidate[]) {
const limit = briefing.theme_places_max ?? CITY_WALK_BRIEFING_LIMITS.themePlaces;
if (limit === 0) return { limit, candidates: [], searched: null };
const categories = briefingCategories(briefing.themes ?? ['mixed']);
const corridor = briefing.corridor_m ?? DEFAULT_CORRIDOR_M;
const line = named.map((spot): [number, number] => [spot.lat, spot.lng]);
const found: TourPoiSearchResponse = await this.poiSearch.search({
tour_type: 'walk',
categories: categories.searched.map((entry) => entry.category),
corridor_m: corridor,
// One point alone is searched around: a line from it to itself.
line: line.length > 1 ? line : [...line, ...line],
lang: briefing.lang,
});
const candidates = themeCandidates(found.pois, categories.searched, named);
return {
limit,
candidates,
searched: {
categories: categories.searched.map((entry) => entry.category),
categories_not_searched: categories.notSearched,
corridor_m: corridor,
found: found.pois.length,
unavailable: found.unavailable,
partial: found.partial,
capped: found.capped,
truncated: found.truncated,
},
};
}
}
+79
View File
@@ -0,0 +1,79 @@
import { ADDON_IDS } from '../../addons';
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
import {
McpController,
Tool,
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
TOOL_ANNOTATIONS_READONLY,
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 { CityWalkBriefingService } from './city-walk-briefing.service';
import {
cityWalkBriefingRequestSchema,
cityWalkCreateRequestSchema,
idSchema,
type CityWalkBriefingRequest,
type CityWalkCreateRequest,
} from '@trek/shared';
const create = cityWalkCreateRequestSchema.shape;
/**
* CW-11: a city walk prepared from a traveller's briefing. The proposal reads
* only, so turning it down changes nothing; the walk is created once the
* traveller confirmed it, through the creation the planner's save uses (one
* write, a key for every station, the links to the trip's places checked, the
* trip told), with 'place_edit' on the trip, as REST asks. Both plan the way on
* foot with the router the road trip uses. A refusal of the service is a
* DomainError, which the registry answers as an error result with the text
* REST sends.
*/
@McpController()
export class CityWalkMcp {
constructor(
private readonly briefing: CityWalkBriefingService,
private readonly access: TripAccessService,
private readonly guards: McpToolGuardsService,
// Read by the addon gate of every tool here.
readonly addons: AddonsService,
) {}
@Tool({
name: 'propose_city_walk',
description:
"Propose a city walk for a trip from the traveller's briefing, without saving anything: where it starts (and ends), the time frame (start_time to end_time, on day_id for its date), their interests (themes: culture for museums and sights, parks for parks and viewpoints, food for cafes, places to eat and markets, mixed for a bit of each; mixed when left out), the stations they asked for (wished), the places of the trip it may use (trip_places) and their fixed appointments with their times. Places for the themes come from the same search as search_tour_pois, around the start, the wishes and the appointments, up to theme_places_max (8 when left out); nothing is made up. Answers the stations in order, each with its source and why it is in (found names the theme, the category and where it was found), the walking distance and time from the one before (walk_from_previous: metres, minutes), the arrival and leave times, the stay where the traveller gave it (stay_source given; null when not known: then every later arrival is only the earliest, arrival_is_earliest; the start and the end are passed, stay_source frame), and its opening hours checked against the arrival on that day where they can be read (hours; an earliest arrival only ever shows a conflict that is certain). The order is chosen on estimates; the walk in that order is then planned on foot by TREK's router (the traveller's own routing server where they set one), whose legs give the distances and times (estimate kind routed). Where the router gives no way, they are estimates over the straight distance with an allowance for streets (estimate kind straight_line with street_factor and pace_kmh, and why: router_unavailable, or station_off_the_way with the position of the station no way on foot reaches); tell the traveller so. totals keeps walking and stays apart, total_complete only when every stay is known, and minutes_left_for_unknown_stays is what the frame leaves for the stays not known. gaps lists free time before an appointment and at the end, wishes_not_met the wishes and appointments that cannot be kept as asked (closed that day, closed or closing at the arrival, late, after the frame), left_out what was not taken and why, searched what was searched. Wished stations and appointments are always in; an appointment is a must and protected. Show the proposal to the traveller; once they confirm, pass stations_for_create to create_city_walk.",
inputSchema: { tripId: idSchema, ...cityWalkBriefingRequestSchema.shape },
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'read' },
})
async proposeCityWalk({ tripId, ...briefing }: { tripId: number } & CityWalkBriefingRequest, ctx: McpContext) {
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
return ok(await this.briefing.propose(tripId, ctx.userId, briefing));
}
@Tool({
name: 'create_city_walk',
description:
'Create a city walk in a trip from stations the traveller confirmed (for instance stations_for_create of propose_city_walk), the way the planner saves a new walk: a new tour of type walk with its stations in their order, each with its name, stay_minutes (0 for a point passed through, null when not known), importance (optional, must, or null for normal), protected (a station any later proposal has to keep where it is), opening_hours as OpenStreetMap writes them and the place of the trip it stands for (linked_place_id; a place that is not of this trip leaves the station unlinked, a tour is refused). The way between the stations is planned on foot by the router the proposal uses, and the walk is saved with it, its distance and its walking time (foot_way planned true). Where the router gives no way (foot_way planned false, with why and position as in the estimate of the proposal), the walk is saved with its stations only (route_pending true, distance and walking time null), and TREK plans the way on foot when someone opens it in the planner and saves it; no straight line is stored as a route. Put it on a day with assign_place_to_day and give it a start time with update_assignment_time. Needs place editing permission on the trip. Create it only after the traveller said yes.',
inputSchema: {
tripId: idSchema.describe('The trip to create the walk in'),
name: create.name,
description: create.description,
stations: create.stations,
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'write' },
})
async createCityWalk({ tripId, ...body }: { tripId: number } & CityWalkCreateRequest, ctx: McpContext) {
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
return ok(await this.briefing.create(tripId, ctx.userId, body));
}
}
+1 -1
View File
@@ -57,7 +57,7 @@ export class TourLibraryMcp {
@Tool({
name: 'take_over_tour',
description:
'Copy a saved tour of another trip (as list_tour_library gives it) into a trip, as an independent tour of that trip: its line, measures, settings and control points, without its days, its links to places of the other trip or the decisions taken there about obstacles. The copy remembers which trip and tour it was taken from. Nothing changes in the source trip.',
'Copy a saved tour of another trip (as list_tour_library gives it) into a trip, as an independent tour of that trip: its line, measures, settings and control points, without its days, its links to places of the other trip or the decisions taken there about obstacles. The copy remembers which trip and tour it was taken from. A city walk keeps its stations with their keys, names, stays, importance, protection and opening hours; what was checked off on the days of the other trip stays there, and a walk still waiting for its way (route_pending) is copied as it is. Nothing changes in the source trip.',
inputSchema: {
tripId: idSchema.describe('The trip to copy the tour into'),
source_trip_id: takeOver.source_trip_id,
@@ -66,6 +66,7 @@ export class TourVisitsService {
const statusOf = new Map(walk.visits.map((visit) => [visit.station_key, visit.status]));
const stations: WalkProgressStation[] = walk.stations.map((station, index) => ({
position: index + 1,
key: station.key ?? null,
name: station.name ?? null,
lat: station.lat,
lng: station.lng,
@@ -73,6 +74,7 @@ export class TourVisitsService {
importance: station.importance ?? 'normal',
protected: station.protected === true,
stay_minutes: station.stay_minutes ?? null,
opening_hours: station.opening_hours ?? null,
linked_place_id: station.linked_place_id ?? null,
}));
const open = stations.filter((station) => station.status === 'planned');
@@ -113,6 +115,8 @@ export class TourVisitsService {
/** CW-09: one station of a walk on a day, as an assistant reads it. */
interface WalkProgressStation {
position: number;
/** The station's own key, the same across saves; null only for a point saved before keys existed. */
key: string | null;
name: string | null;
lat: number;
lng: number;
@@ -121,6 +125,8 @@ interface WalkProgressStation {
protected: boolean;
/** Null where the stay is not known; 0 is a station passed through. */
stay_minutes: number | null;
/** As OpenStreetMap writes them; a hint to check, null when none is known. */
opening_hours: string | null;
linked_place_id: number | null;
}
+38 -6
View File
@@ -10,12 +10,43 @@ import { TourPoiSearchService } from './tour-poi-search.service';
import { TourVisitsService } from './tour-visits.service';
import { ToursService } from './tours.service';
import { NotFoundException } from '@nestjs/common';
import { idSchema, tourPoiSearchRequestSchema, type TourListItem, type TourPoiSearchRequest } from '@trek/shared';
import {
idSchema,
tourPoiSearchRequestSchema,
walkStationsOf,
type TourListItem,
type TourPoiSearchRequest,
type TourWaypoint,
} from '@trek/shared';
type TourDay = Pick<TourDayRow, 'day_id' | 'day_number' | 'date' | 'title'>;
const poiFields = tourPoiSearchRequestSchema.shape;
/**
* CW-10: a station of a city walk with every field it has spelled out, so an
* assistant reads a stay nobody entered as null and never as missing: null
* for an unknown stay, a normal importance and no known hours, false for an
* unprotected station. REST answers the stored fields as they are.
*/
function spelledOut<T extends TourWaypoint>(station: T) {
return {
...station,
key: station.key ?? null,
name: station.name ?? null,
stay_minutes: station.stay_minutes ?? null,
importance: station.importance ?? null,
protected: station.protected === true,
opening_hours: station.opening_hours ?? null,
};
}
/** The points of a tour as get_tour_plan answers them: a city walk's stations spelled out, every other point as stored. */
function planPoints<T extends TourWaypoint>(tourType: string, points: T[]) {
const stations = new Set<T>(tourType === 'walk' ? walkStationsOf(points) : []);
return points.map((point) => (stations.has(point) ? spelledOut(point) : point));
}
/** A tour as a client reads it: its list facts and the days of the trip it is on. */
function withDays(tour: TourListItem, days: ReadonlyMap<number, TourDay[]>) {
return { ...tour, days: days.get(tour.place_id) ?? [] };
@@ -54,7 +85,7 @@ export class ToursMcp {
@Tool({
name: 'list_tours',
description:
'List the saved tours of a trip (hikes, bike tours and paddle tours planned or imported in the Tours addon): name, type (hike, bike, or kayak for a paddle tour), where it came from (origin: trek, gpx or wanderer), distance in km, ascent and descent in metres, the stored routing limit of a hike (max_hiking_difficulty, SAC T1 to T6) and its route choices (hiking_preferences: avoid_climbs for gentler ways, avoid_steps, avoid_ferries; weightings, never a grade of the path), the profile a bike tour is routed for (bike_profile: touring for paved cycle paths and quiet roads, road for asphalt, gravel for gravel and farm tracks, mtb for rough tracks; a routing preference, never a statement that a way is rideable or safe), the boat, water and chosen speed of a paddle tour (boat_type, water_context, paddle_speed_kmh in km/h, null while the suggested speed of the boat applies), the check bench of a paddle tour (paddle_check: how far the OpenStreetMap obstacle data covers its line and how many obstacles are open, to check again or decided by the travellers; a planning status, never a safety or legal clearance), the revision (raised by every saved change of the tour), and the days of the trip each tour is on.',
'List the saved tours of a trip (hikes, city walks, bike tours and paddle tours planned or imported in the Tours addon): name, type (hike, walk for a city walk, bike, or kayak for a paddle tour), where it came from (origin: trek, gpx or wanderer), distance in km, ascent and descent in metres, the stored routing limit of a hike (max_hiking_difficulty, SAC T1 to T6) and its route choices (hiking_preferences: avoid_climbs for gentler ways, avoid_steps, avoid_ferries; weightings, never a grade of the path), the profile a bike tour is routed for (bike_profile: touring for paved cycle paths and quiet roads, road for asphalt, gravel for gravel and farm tracks, mtb for rough tracks; a routing preference, never a statement that a way is rideable or safe), the boat, water and chosen speed of a paddle tour (boat_type, water_context, paddle_speed_kmh in km/h, null while the suggested speed of the boat applies), the check bench of a paddle tour (paddle_check: how far the OpenStreetMap obstacle data covers its line and how many obstacles are open, to check again or decided by the travellers; a planning status, never a safety or legal clearance), for a city walk the number of its stations (station_count: its points without the shaping points and the way back of a loop), their stays as far as entered (station_stay_minutes) and how many have none (station_stays_unknown), whether a tour still waits for its way to be planned (route_pending: saved with its points only, so its distance and walking time stay null until someone opens it in the planner and saves it), the revision (raised by every saved change of the tour), and the days of the trip each tour is on.',
inputSchema: { tripId: idSchema },
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.TOURS),
@@ -69,7 +100,7 @@ export class ToursMcp {
@Tool({
name: 'get_tour_plan',
description:
'Read one saved tour of a trip: its facts, its ordered control points (start, via and end; an import without its own shows the two ends of its track), where it came from (provenance) and the days it is on. A control point with linked_place_id stands for that place of the trip (linked_place_name names it); it keeps its own coordinates. A control point whose fixed_leg is set leads to the next one along a line the router did not plan: kind ferrata follows a via ferrata, kind free is drawn by hand and was checked by nothing. A paddle tour also carries its obstacle checklist (obstacle_check): the obstacles of the OpenStreetMap data along its line, the decisions the travellers made about them and their own portages and locks; a planning aid, never a safety or legal clearance. The full track geometry is not included.',
'Read one saved tour of a trip: its facts, its ordered control points (start, via and end; an import without its own shows the two ends of its track), where it came from (provenance) and the days it is on. A control point with linked_place_id stands for that place of the trip (linked_place_name names it); it keeps its own coordinates. A control point whose fixed_leg is set leads to the next one along a line the router did not plan: kind ferrata follows a via ferrata, kind free is drawn by hand and was checked by nothing. A paddle tour also carries its obstacle checklist (obstacle_check): the obstacles of the OpenStreetMap data along its line, the decisions the travellers made about them and their own portages and locks; a planning aid, never a safety or legal clearance. A city walk (tour_type walk) has stations for control points, shaping points and the way back of a loop aside, each with every field spelled out: key (its own id, the same across saves; the visits of a day are kept by it), name, stay_minutes (the stay in minutes; 0 for a point only passed through, null when not known), importance (optional or must; null for a normal station), protected (true for a station any change you propose has to keep where it is: neither removed, replaced nor moved; the travellers can still edit it themselves in the app) and opening_hours (as OpenStreetMap writes them; a hint to check, never a promise; null when none is known). How far a walk got on a day is get_city_walk_progress. The full track geometry is not included.',
inputSchema: { tripId: idSchema, placeId: idSchema.describe('The place id of the tour, as list_tours gives it') },
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.TOURS),
@@ -84,9 +115,10 @@ export class ToursMcp {
]);
// A point standing for a place of the trip (PR1-10) says which, by name.
const names = await this.tours.linkedPlaceNames(tripId, detail.waypoints);
const waypoints = detail.waypoints.map((point) =>
const named = detail.waypoints.map((point) =>
point.linked_place_id ? { ...point, linked_place_name: names.get(point.linked_place_id) ?? null } : point,
);
const waypoints = planPoints(detail.tour.tour_type, named);
return ok({ ...detail, waypoints, tour: withDays(detail.tour, days) });
} catch (err: unknown) {
if (err instanceof NotFoundException) return errorResult('Tour not found.');
@@ -97,7 +129,7 @@ export class ToursMcp {
@Tool({
name: 'get_city_walk_progress',
description:
'Read how far a city walk (tour_type walk) got on one day it is on: every station in order with its status that day (planned, visited or skipped, as the travellers checked them off in the day plan), its importance (normal, optional, must), whether it is protected (a station a proposed change must leave where it is, neither removed, replaced nor moved), its stay in minutes (null when not known, 0 for a point passed through) and its linked place. "open" sums what is still planned: the stations, their known stays and how many stays are unknown; walking_minutes is the walking time of the whole walk. Visits belong to that day only: the same walk on another day, or a copy, has none. Anything the traveller tells you besides (for instance "continue from 2 pm") is theirs to say, not stored here. Reading changes nothing.',
'Read how far a city walk (tour_type walk) got on one day it is on: every station in order with its key (its own id, as get_tour_plan gives it), its status that day (planned, visited or skipped, as the travellers checked them off in the day plan), its importance (normal, optional, must; get_tour_plan says null for normal), whether it is protected (a station a proposed change must leave where it is, neither removed, replaced nor moved), its stay in minutes (null when not known, 0 for a point passed through), its opening hours as OpenStreetMap writes them (null when none is known) and its linked place. "open" sums what is still planned: the stations, their known stays and how many stays are unknown; walking_minutes is the walking time of the whole walk. Visits belong to that day only: the same walk on another day, or a copy, has none. Anything the traveller tells you besides (for instance "continue from 2 pm") is theirs to say, not stored here. Reading changes nothing.',
inputSchema: {
tripId: idSchema,
placeId: idSchema.describe('The place id of the city walk, as list_tours gives it'),
@@ -158,7 +190,7 @@ export class ToursMcp {
@Tool({
name: 'search_tour_pois',
description:
'Search places along the saved line of a tour: what a hike, a bike tour, a paddle tour or a city walk stops for (viewpoint, peak, shelter, drinking_water, food, toilets, picnic, campsite, sights, slipway, boat_rental, bike_repair for repair stations and bike shops, and for a city walk museum for museums and galleries, park for parks and gardens, cafe, restaurant and market), within corridor_m metres of the line. Answers each place with its source (TREK places index or OpenStreetMap), kind, address, website and phone where known, opening hours as the source has them (a hint to check, never a promise), distance_m (straight across to the line, not a detour) and along_m (from the start along the line); up to 60, the nearest to the line when more match, listed from the start. A place OpenStreetMap has no name for (a tap, a bench) comes with an empty name. unavailable lists the categories no source could be searched for right now: their places are missing, not absent, so ask again later rather than reporting none. partial says some stretches could not be searched, capped that only the first part of a long line was, truncated that more places matched. Nothing is added to the tour or the trip.',
'Search places along the saved line of a tour: what a hike, a bike tour, a paddle tour or a city walk stops for (viewpoint, peak, shelter, drinking_water, food, toilets, picnic, campsite, sights, slipway, boat_rental, bike_repair for repair stations and bike shops, and for a city walk museum for museums and galleries, park for parks and gardens, cafe, restaurant and market), within corridor_m metres of the line. Answers each place with its source (TREK places index or OpenStreetMap), kind, address, website and phone where known, opening hours as the source has them (a hint to check, never a promise), distance_m (straight across to the line, not a detour) and along_m (from the start along the line); up to 60, the nearest to the line when more match, listed from the start. A place OpenStreetMap has no name for (a tap, a bench) comes with an empty name. unavailable lists the categories no source could be searched for right now: their places are missing, not absent, so ask again later rather than reporting none. partial says some stretches could not be searched, capped that only the first part of a long line was, truncated that more places matched. A tour saved with its points only (route_pending) has no line to search along yet. Nothing is added to the tour or the trip.',
inputSchema: {
tripId: idSchema,
placeId: idSchema.describe('The place id of the tour, as list_tours gives it'),
+11 -1
View File
@@ -13,8 +13,11 @@ import { PaddleObstaclesModule } from '../paddle-obstacles/paddle-obstacles.modu
import { PermissionsModule } from '../permissions/permissions.module';
import { PlaceImportModule } from '../place-import/place-import.module';
import { PlacesModule } from '../places/places.module';
import { RoadtripModule } from '../roadtrip/roadtrip.module';
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
import { WandererModule } from '../wanderer/wanderer.module';
import { CityWalkBriefingService } from './city-walk-briefing.service';
import { CityWalkMcp } from './city-walk.mcp';
import { TourGpxExportService } from './tour-gpx-export.service';
import { TourLibraryController, TourTakeOverController } from './tour-library.controller';
import { TourLibraryMcp } from './tour-library.mcp';
@@ -48,7 +51,10 @@ import { Module } from '@nestjs/common';
* through PlacesRepository, registered here because forFeature only reaches
* this module's own providers. A Google Maps walking route is read into the
* stops of a city walk through PlaceImportModule as well (CW-07), its short
* link followed by the narrow resolver there (CW-06).
* link followed by the narrow resolver there (CW-06). A city walk an assistant
* prepares from a briefing reads the day and places of the trip through the
* tours' own repositories, is planned on foot by RoadtripModule's router and
* is created through ToursService (CW-11).
*/
@Module({
imports: [
@@ -67,6 +73,8 @@ import { Module } from '@nestjs/common';
WandererModule,
// The obstacle data a paddle tour's checklist reads (PAD-06, PAD-09).
PaddleObstaclesModule,
// A city walk prepared over MCP is planned on foot by the router the road trip uses (CW-11).
RoadtripModule,
MikroOrmModule.forFeature([
Tours,
TourTypes,
@@ -101,9 +109,11 @@ import { Module } from '@nestjs/common';
TourTrailGradeService,
TourVisitsService,
TourWalkImportService,
CityWalkBriefingService,
ToursMcp,
TourLibraryMcp,
TourWalkImportMcp,
CityWalkMcp,
],
})
export class ToursModule {}
+93 -29
View File
@@ -20,7 +20,7 @@ import type {
TourUpdate,
} from '../../db/repositories/Tours.repository';
import { decodeJson, encodeJson } from '../../utils/json-column';
import { DomainError } from '../common/domain-error';
import { badRequest, DomainError } from '../common/domain-error';
import { toRowId } from '../common/row-id';
import { UnitOfWork } from '../database/unit-of-work';
import { PlaceImportService } from '../place-import/place-import.service';
@@ -36,13 +36,14 @@ import {
type GeometryPoint,
} from './tours.helpers';
import { InjectRepository } from '@mikro-orm/nestjs';
import { BadRequestException, Injectable, Logger, NotFoundException } from '@nestjs/common';
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import {
hikingPreferencesOf,
MAX_PLANNED_TOUR_DURATION_MINUTES,
plannedTourDurationMinutesSchema,
tourWebsiteSchema,
type BikeProfile,
type CityWalkCreateRequest,
type PaddleBoatType,
type PaddleLakeStyle,
type PaddleWaterContext,
@@ -80,8 +81,24 @@ export interface ImportGpxAsTourResult {
/** A GPX file imported without a type is a hike. */
const HIKE_IMPORT: TourGpxImportFields = { tour_type: 'hike' };
/**
* What a create writes: the request as the contract reads it, or for a city
* walk an assistant created from its stations (CW-11) the way the server's
* router planned on foot, which has no heights, or no line when it planned
* none, which the planner then plans when the walk is opened.
*/
export type TourCreateCommand = Omit<TourCreateRequest, 'route_geometry'> & {
route_geometry: GeometryPoint[] | null;
};
/** The way on foot the server's router planned for a city walk (CW-11): its line, and how long it walks in seconds. */
interface CityWalkFootRoute {
line: Array<[number, number]>;
seconds: number;
}
/** MF-08: a save's hiking preferences as stored: a hike's switched-on ones as JSON, else NULL. */
function hikingFields(input: TourCreateRequest): string | null {
function hikingFields(input: TourCreateCommand): string | null {
const preferences = input.tour_type === 'hike' ? hikingPreferencesOf(input.hiking_preferences) : null;
return preferences ? encodeJson(TOUR_HIKING_PREFERENCES, preferences) : null;
}
@@ -151,20 +168,24 @@ export class ToursService {
revision: r.revision,
hiking_preferences: decodeJson(TOUR_HIKING_PREFERENCES, r.hiking_preferences, 'tour'),
...walkStationFacts(r.tour_type, points),
route_pending: Boolean(r.route_missing) && Boolean(r.has_waypoints),
};
}
/** The route a create or an update writes: metrics derived from the geometry, duration stored in minutes. */
private routeFields(input: TourCreateRequest): TourUpdate {
const metrics = computeTourMetrics(input.route_geometry as GeometryPoint[]);
/**
* The route a create or an update writes: metrics derived from the geometry, duration stored in minutes.
* Without a line (CW-11) distance, heights and walking time stay unknown until the planner plans the way.
*/
private routeFields(input: TourCreateCommand): TourUpdate {
const metrics = input.route_geometry ? computeTourMetrics(input.route_geometry) : null;
// A paddle tour drawn here has its heights read off the banks at the points set, not
// off the water: its ascent and descent stay unknown rather than wrong.
const heightsKnown = input.tour_type !== 'kayak';
return {
tour_type: input.tour_type,
distance: metrics.distanceKm,
elevation_gain: heightsKnown ? metrics.elevationGainM : null,
elevation_loss: heightsKnown ? metrics.elevationLossM : null,
distance: metrics?.distanceKm ?? null,
elevation_gain: heightsKnown ? (metrics?.elevationGainM ?? null) : null,
elevation_loss: heightsKnown ? (metrics?.elevationLossM ?? null) : null,
duration: input.duration_seconds == null ? null : Math.round(input.duration_seconds / 60),
...(input.planned_duration_minutes !== undefined
? { planned_duration_minutes: input.planned_duration_minutes }
@@ -188,25 +209,26 @@ export class ToursService {
/**
* `tour_types` knows every key the contract accepts, most of them disabled.
* Checked before the write, so a disabled type is a 400 and not a tour the
* planner cannot show.
* planner cannot show. The refusals here are DomainErrors, so REST answers
* `{ error }` and an MCP tool the same text as its error result.
*/
private async assertTourTypeEnabled(key: string): Promise<void> {
if (!(await this.tourTypesRepo.isEnabled(key))) throw new BadRequestException('Tour type is not available');
if (!(await this.tourTypesRepo.isEnabled(key))) throw badRequest('Tour type is not available');
}
private validateInformationalMetadata(input: TourCreateRequest): void {
private validateInformationalMetadata(input: TourCreateCommand): void {
if (input.description != null && input.description.length > 2000) {
throw new BadRequestException('description must be 2000 characters or less');
throw badRequest('description must be 2000 characters or less');
}
if (input.website != null && !tourWebsiteSchema.safeParse(input.website).success) {
throw new BadRequestException('website must be a valid HTTPS URL without credentials');
throw badRequest('website must be a valid HTTPS URL without credentials');
}
}
private validatePlannedTimes(input: TourCreateRequest): void {
private validatePlannedTimes(input: TourCreateCommand): void {
for (const value of [input.planned_duration_minutes, input.break_additional_minutes]) {
if (value !== undefined && !plannedTourDurationMinutesSchema.safeParse(value).success) {
throw new BadRequestException('planned Tour times must be whole minutes from 0 to 1440');
throw badRequest('planned Tour times must be whole minutes from 0 to 1440');
}
}
if (
@@ -215,9 +237,7 @@ export class ToursService {
Math.round(input.duration_seconds / 60) + (input.break_additional_minutes ?? 0) >
MAX_PLANNED_TOUR_DURATION_MINUTES
) {
throw new BadRequestException(
'walking time plus breaks must be 1440 minutes or less unless a total is overridden',
);
throw badRequest('walking time plus breaks must be 1440 minutes or less unless a total is overridden');
}
}
@@ -323,14 +343,20 @@ export class ToursService {
};
}
/** Create the owning Place, Tours facet, and ordered control points as one write. */
async createTour(tripId: string, input: TourCreateRequest, socketId?: string): Promise<TourCreateResponse> {
/**
* Create the owning Place, Tours facet, and ordered control points as one write. A create
* without a line (CW-11) puts the place at its first point.
*/
async createTour(tripId: string, input: TourCreateCommand, socketId?: string): Promise<TourCreateResponse> {
// The controller's TripAccessGuard already resolved this trip id.
const tid = toRowId(tripId)!;
await this.assertTourTypeEnabled(input.tour_type);
this.validateInformationalMetadata(input);
this.validatePlannedTimes(input);
const start = input.route_geometry[0];
const start = input.route_geometry ? input.route_geometry[0] : firstPointOf(input.waypoints);
if (!start || (input.route_geometry === null && input.waypoints.length < 2)) {
throw badRequest('A tour needs at least two points');
}
const fields = this.routeFields(input);
const derivedFrom = input.derived_from_place_id ?? null;
@@ -348,7 +374,7 @@ export class ToursService {
name: input.name,
lat: start[0],
lng: start[1],
route_geometry: JSON.stringify(input.route_geometry),
route_geometry: input.route_geometry ? JSON.stringify(input.route_geometry) : null,
description: input.description ?? null,
website: input.website ?? null,
});
@@ -389,6 +415,36 @@ export class ToursService {
};
}
/**
* CW-11: a city walk the traveller confirmed through an assistant, made the
* way the planner's save makes one, in the same write with the same checks:
* its stations in order, each with a key of its own, its links to the trip's
* places checked. Its distance and walking time come from the way the
* server's router planned on foot. Without one it is saved with its stations
* only: no line, no distance and no walking time, until the planner plans the
* way when it is opened.
*/
async createCityWalk(
tripId: string,
input: CityWalkCreateRequest,
way: CityWalkFootRoute | null,
): Promise<TourCreateResponse> {
const last = input.stations.length - 1;
return await this.createTour(tripId, {
name: input.name,
description: input.description,
tour_type: 'walk',
route_geometry: way?.line ?? null,
duration_seconds: way?.seconds ?? null,
max_hiking_difficulty: null,
waypoints: input.stations.map((station, sequence) => ({
...station,
role: sequence === 0 ? 'start' : sequence === last ? 'end' : 'via',
sequence,
})),
});
}
/**
* Takes an import that was planned over in place back to the track it was
* recorded with: its line, the measures read from that line and the grade
@@ -513,21 +569,23 @@ export class ToursService {
target: { tid: number; name: string },
how: { derivedFrom: number | null; sameTrip: boolean; takenOverFrom?: { tripTitle: string; tourName: string } },
): Promise<number> {
const [row, provenance, place] = await Promise.all([
const [row, provenance, place, waypoints] = await Promise.all([
this.toursRepo.findInTrip(source.tid, source.pid),
this.toursRepo.findProvenance(source.tid, source.pid),
this.placesRepo.findInTrip(source.pid, source.tid),
this.waypointsRepo.listForPlace(source.pid),
]);
const start = parseRouteGeometry(place?.route_geometry)[0];
// A tour without a line has nothing to copy.
if (!row || !provenance || !place?.route_geometry || !start) throw new NotFoundException('Tour not found');
// A city walk saved with its stations only (CW-11) is copied from its first one, its way still to plan;
// a line that holds no point has nothing to copy.
const start = place?.route_geometry == null ? firstPointOf(waypoints) : parseRouteGeometry(place.route_geometry)[0];
if (!row || !provenance || !place || !start) throw new NotFoundException('Tour not found');
if (!how.sameTrip) await this.assertTourTypeEnabled(row.tour_type);
const id = await this.placesRepo.insertTourPlace({
trip_id: target.tid,
name: target.name,
lat: start[0],
lng: start[1],
route_geometry: place.route_geometry,
route_geometry: place.route_geometry ?? null,
description: place.description ?? null,
website: place.website ?? null,
});
@@ -559,7 +617,6 @@ export class ToursService {
taken_over_from_trip_title: how.takenOverFrom?.tripTitle ?? provenance.taken_over_from_trip_title,
taken_over_from_tour_name: how.takenOverFrom?.tourName ?? provenance.taken_over_from_tour_name,
});
const waypoints = await this.waypointsRepo.listForPlace(source.pid);
// A stop standing for a place of the source trip stands for nothing in another trip.
await this.waypointsRepo.insertForPlace(
id,
@@ -783,6 +840,7 @@ export class ToursService {
has_recorded_track: 0,
planned: 0,
has_waypoints: 0,
route_missing: 0,
revision: 1,
hiking_preferences: null,
}),
@@ -844,6 +902,12 @@ export class ToursService {
}
}
/** Where a tour without a line starts (CW-11): at its first point. */
function firstPointOf(points: readonly { lat: number; lng: number }[]): [number, number] | undefined {
const point = points[0];
return point ? [point.lat, point.lng] : undefined;
}
/** The file name a GPX import keeps: the name as uploaded, without a path, cut to what the column shows. */
function gpxFileName(name: string | undefined): string | null {
const base = name?.split('/').pop()?.trim();