mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-20 19:16:08 +00:00
feat(tours): round hikes, other ways of a leg and wanderer trails through the assistant
The assistant can now search a round hike of about a wished length from one point and the router's other ways for one leg of a hike, with the planner's own search, and propose each one as a hike card to compare and take. It can also search the user's wanderer trails, preview one as a card, import it and check a wanderer tour against its source. The round search, its loop geometry, the test whether two lines are one way, the other ways among a router's offers and the pins that hold a chosen way move to @trek/shared; the planner and the road trip use them from there.
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
import { recordOf, type Row } from './cards/card-values';
|
||||
import type { TourRouteCard } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* "Plan this" on the planner's other searches the assistant ran: a round
|
||||
* hike and another way for one leg of a hike, created as a hike through the
|
||||
* points the proposal answered (create_with), and a wanderer trail, imported
|
||||
* with the fingerprint its preview answered. What is created comes from the
|
||||
* stored proposal, never from the request.
|
||||
*/
|
||||
|
||||
/** The proposing reads of this kind, and the tool each one is created through. */
|
||||
export const WAY_CREATES: Readonly<Record<string, string>> = {
|
||||
propose_round_hike: 'create_hike',
|
||||
propose_hike_leg_way: 'create_hike',
|
||||
preview_wanderer_trail: 'import_wanderer_trail',
|
||||
};
|
||||
|
||||
/** The fields of a round or a leg's way a hike is created with as the call asked them. */
|
||||
const ASKED_FIELDS = ['name', 'max_hiking_difficulty', 'hiking_preferences', 'day_id', 'start_time'] as const;
|
||||
|
||||
/** A point of create_with as create_hike takes it: where it is, its name, its kind and a stage ending there. */
|
||||
function pointOf(row: Row): Row | null {
|
||||
if (typeof row.lat !== 'number' || typeof row.lng !== 'number') return null;
|
||||
return {
|
||||
lat: row.lat,
|
||||
lng: row.lng,
|
||||
...(typeof row.name === 'string' ? { name: row.name } : {}),
|
||||
...(typeof row.poi_category === 'string' ? { poi_category: row.poi_category } : {}),
|
||||
...(row.stage_end === true ? { stage_end: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether `toolName` is one of these searches. */
|
||||
export function isWayProposal(toolName: string): boolean {
|
||||
return Object.prototype.hasOwnProperty.call(WAY_CREATES, toolName);
|
||||
}
|
||||
|
||||
/**
|
||||
* The change a taken way holds, or null when nothing can be created from it:
|
||||
* a way that was not planned, the way of a saved hike's leg (that hike is
|
||||
* changed with update_tour), a trail already in the trip as it is.
|
||||
*/
|
||||
export function wayTakeArgsOf(toolName: string, args: Row, result: Row, card: TourRouteCard): Row | null {
|
||||
const via = WAY_CREATES[toolName];
|
||||
if (via === 'import_wanderer_trail') {
|
||||
if (result.state === 'unchanged' || typeof args.trailId !== 'string' || typeof result.contentHash !== 'string') {
|
||||
return null;
|
||||
}
|
||||
return { via, trailId: args.trailId, contentHash: result.contentHash };
|
||||
}
|
||||
if (via !== 'create_hike' || !card.routed || card.placeId !== null) return null;
|
||||
const create = recordOf(result.create_with);
|
||||
const rows = Array.isArray(create.waypoints) ? create.waypoints.map(recordOf) : [];
|
||||
const waypoints = rows.map(pointOf);
|
||||
if (waypoints.length < 2 || waypoints.some((point) => point === null)) return null;
|
||||
const taken: Row = { via, waypoints, round_trip: create.round_trip === true };
|
||||
for (const key of ASKED_FIELDS) if (args[key] !== undefined) taken[key] = args[key];
|
||||
return taken;
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import { RateLimitService } from '../common/rate-limit.service';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { buildTripCard, categoriesFrom, todayIn, type TripCard } from './assistant-context';
|
||||
import { partsOf, toThreadMessages } from './assistant-history';
|
||||
import { isWayProposal, WAY_CREATES, wayTakeArgsOf } from './assistant-proposal-ways';
|
||||
import { AssistantStreamRegistry } from './assistant-stream.registry';
|
||||
import { TAKE_PROPOSAL_TOOL, TURNS_PER_MINUTE } from './assistant-tools.constants';
|
||||
import { AssistantToolsService, type ToolRun } from './assistant-tools.service';
|
||||
@@ -69,9 +70,10 @@ interface StoredProposal {
|
||||
}
|
||||
|
||||
/** The proposing reads a card can be taken from, and the tool each one is created through. */
|
||||
const CREATES: Readonly<Record<string, 'create_hike' | 'create_city_walk'>> = {
|
||||
const CREATES: Readonly<Record<string, string>> = {
|
||||
propose_hike: 'create_hike',
|
||||
propose_city_walk: 'create_city_walk',
|
||||
...WAY_CREATES,
|
||||
};
|
||||
const PROPOSING: ReadonlySet<string> = new Set(Object.keys(CREATES));
|
||||
|
||||
@@ -151,6 +153,9 @@ const HIKE_FIELDS = [
|
||||
* nothing can be created from.
|
||||
*/
|
||||
export function takeArgsOf(proposal: StoredProposal): Row | null {
|
||||
if (isWayProposal(proposal.toolName)) {
|
||||
return wayTakeArgsOf(proposal.toolName, proposal.args, proposal.result, proposal.card);
|
||||
}
|
||||
const via = CREATES[proposal.toolName];
|
||||
if (via === 'create_hike') {
|
||||
if (!proposal.card.routed) return null;
|
||||
|
||||
@@ -244,6 +244,8 @@ const CORE_TOOL_GROUPS: ToolGroups = {
|
||||
'CollectionToursMcp',
|
||||
'PaddleRoutingMcp',
|
||||
'SkiRoutingMcp',
|
||||
'HikeWaysMcp',
|
||||
'ToursWandererMcp',
|
||||
],
|
||||
},
|
||||
roadtrip: {
|
||||
|
||||
@@ -145,8 +145,8 @@ 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']);
|
||||
|
||||
/** The model's tools a taken proposal is created through: a hike, a city walk. */
|
||||
const PROPOSAL_VIA: ReadonlySet<string> = new Set(['create_hike', 'create_city_walk']);
|
||||
/** The model's tools a taken proposal is created through: a hike, a city walk, a wanderer trail imported. */
|
||||
const PROPOSAL_VIA: ReadonlySet<string> = new Set(['create_hike', 'create_city_walk', 'import_wanderer_trail']);
|
||||
|
||||
/**
|
||||
* Changes the server applies itself: a booking from an attached file, a search
|
||||
|
||||
@@ -16,6 +16,7 @@ import { proposalCard, savedTourCard } from './tour-route.cards';
|
||||
import { cityWalkCard, paddleCard, skiCard } from './tour-sport.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';
|
||||
import { TOUR_WRITE_CARDS } from './tour-writes.cards';
|
||||
|
||||
/**
|
||||
@@ -61,6 +62,10 @@ export const TOUR_CARDS: DomainCards = {
|
||||
tools: {
|
||||
propose_hike: { argPolicy: WITH_GEOMETRY, answer: proposalCard },
|
||||
propose_city_walk: { argPolicy: WITH_GEOMETRY, answer: cityWalkCard },
|
||||
propose_round_hike: { argPolicy: WITH_GEOMETRY, answer: roundHikeCard },
|
||||
propose_hike_leg_way: { argPolicy: WITH_GEOMETRY, answer: legWayCard },
|
||||
preview_wanderer_trail: { argPolicy: WITH_GEOMETRY, answer: wandererPreviewCard },
|
||||
import_wanderer_trail: IMPORT_WANDERER_TRAIL,
|
||||
plan_paddle_route: { argPolicy: WITH_GEOMETRY, answer: paddleCard },
|
||||
plan_ski_route: { argPolicy: WITH_GEOMETRY, answer: skiCard },
|
||||
get_tour_plan: { project: withoutPreview, answer: savedTourCard },
|
||||
@@ -95,6 +100,6 @@ export const TOUR_CARDS: DomainCards = {
|
||||
},
|
||||
prompt: [
|
||||
'Hikes: call propose_hike with a name, and day_id and start_time when known; to compare ways, call it up to three times in one step, each with a variant_label and along false, the way you recommend first (the card shows the first one chosen). Call create_hike only once the user chose a way. A hike over several days is one hike: stage_end on each stop a day ends at (no day_id), then each stage on its day with assign_place_to_day and tourStageKey.',
|
||||
'The app draws a proposed, planned or saved tour (route, profile, stops, times, weather, warnings) and lists of tours as cards: do not repeat their figures or list them again, say in one sentence what matters. Once a tour is planned, offer what goes with it: places along it (search_tour_pois), what to pack (get_tour_packing, link_tour_packing), the GPX file (export_tour_gpx).',
|
||||
'The app draws a proposed, planned or saved tour (route, profile, stops, times, weather, warnings) and lists of tours as cards: do not repeat their figures or list them again, say in one sentence what matters. Once a tour is planned, offer what goes with it: places along it (search_tour_pois), what to pack (get_tour_packing, link_tour_packing), the GPX file (export_tour_gpx). A round of about so many km from one point: propose_round_hike with round a, b and c in one step; other ways for one leg of a hike: propose_hike_leg_way with way a, b and c; then create_hike with the chosen create_with (update_tour for a saved hike). Wanderer trails of the user: search_wanderer_trails, preview_wanderer_trail, and import_wanderer_trail only after a yes.',
|
||||
],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import type { AnswerInput, CardReader, Described, PreviewContext, ToolArgs, ToolCards } from '../card-types';
|
||||
import { clipped, finite, recordOf, type Row } from '../card-values';
|
||||
import { Rows, text } from '../preview-format';
|
||||
import { climbOf, fitted, lineOf, metresOf, minutesOf, near, routeCard, stopOf, whole } from './tour-card-values';
|
||||
import { appliedTourCard } from './tour-change.cards';
|
||||
import { hikeCard } from './tour-route.cards';
|
||||
import { DELETE_CREATED_TOUR } from './tour-undo';
|
||||
import { TOUR_ROUTE_LIMITS, wandererDifficultyToSac, type TourRouteCard } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The cards of the planner's other searches through the assistant: a round
|
||||
* hike of a wished length and another way for one leg of a hike, drawn as
|
||||
* propose_hike's proposals are (they answer one), the leg's way beside the
|
||||
* hike as it runs now; and a wanderer trail, previewed as a way to take in
|
||||
* and imported with its own change card.
|
||||
*/
|
||||
|
||||
/** How close a trail's end must lie to its start to be a loop with one stop. */
|
||||
const LOOP_END_M = 60;
|
||||
|
||||
/** Whether the tool found the way it was asked for; one not found answers `found: false` and draws nothing. */
|
||||
function found(value: unknown): boolean {
|
||||
return recordOf(value).found === true;
|
||||
}
|
||||
|
||||
/** propose_round_hike: the round as a hike proposal's card. */
|
||||
export function roundHikeCard({ value, args, card }: AnswerInput): TourRouteCard | null {
|
||||
if (!found(value)) return null;
|
||||
const proposal = hikeCard(value, args, card, 'proposal');
|
||||
return proposal ? fitted(proposal) : null;
|
||||
}
|
||||
|
||||
/** The hike as it runs now, under a way for one of its legs: its line flat, its length, climb and time. */
|
||||
function currentOf(value: Row): TourRouteCard['previous'] {
|
||||
const current = recordOf(value.current);
|
||||
const line = lineOf(value.current_geometry, TOUR_ROUTE_LIMITS.previous);
|
||||
const distanceM = metresOf(current.distance_m);
|
||||
if (line.length < 2 || distanceM === null) return null;
|
||||
return {
|
||||
line: line.map(([lat, lng]): [number, number] => [lat, lng]),
|
||||
distanceM,
|
||||
ascentM: climbOf(current.ascent_m),
|
||||
minutes: minutesOf(current.duration_minutes),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* propose_hike_leg_way: the whole hike with the leg taken that way, the way
|
||||
* it runs now drawn faint beneath it; a saved hike's way names its tour, so
|
||||
* it is changed with update_tour rather than planned anew.
|
||||
*/
|
||||
export function legWayCard({ value, args, card }: AnswerInput): TourRouteCard | null {
|
||||
if (!found(value)) return null;
|
||||
const proposal = hikeCard(value, args, card, 'proposal');
|
||||
if (!proposal) return null;
|
||||
const answer = recordOf(value);
|
||||
const placeId = whole(recordOf(answer.leg_way).tour_id, 1, Number.MAX_SAFE_INTEGER);
|
||||
return fitted({ ...proposal, placeId, previous: currentOf(answer) });
|
||||
}
|
||||
|
||||
/**
|
||||
* A wanderer trail as a way to take in: its full line, the length and climb
|
||||
* measured from its GPX, and wanderer's difficulty on the SAC scale. One the
|
||||
* trip already holds as it is reads as that saved tour.
|
||||
*/
|
||||
export function wandererTrailCard(value: unknown, source: 'proposal' | 'pending'): TourRouteCard | null {
|
||||
const preview = recordOf(value);
|
||||
const trail = recordOf(preview.trail);
|
||||
const line = lineOf(preview.line_geometry);
|
||||
const [first, last] = [line[0], line.at(-1)];
|
||||
if (!first || !last || line.length < 2) return null;
|
||||
const snapshot = recordOf(preview.snapshot);
|
||||
const kept = preview.state === 'unchanged' ? whole(snapshot.placeId, 1, Number.MAX_SAFE_INTEGER) : null;
|
||||
const distanceKm = finite(preview.distanceKm);
|
||||
const start = { lat: first[0], lng: first[1] };
|
||||
const end = { lat: last[0], lng: last[1] };
|
||||
const loop = near(start, end, LOOP_END_M);
|
||||
const difficulty = trail.difficulty;
|
||||
const sac =
|
||||
difficulty === 'easy' || difficulty === 'moderate' || difficulty === 'difficult'
|
||||
? wandererDifficultyToSac(difficulty)
|
||||
: null;
|
||||
return fitted(
|
||||
routeCard({
|
||||
source: kept !== null && source === 'proposal' ? 'saved' : source,
|
||||
activity: 'hike',
|
||||
placeId: source === 'proposal' ? kept : null,
|
||||
name: clipped(trail.name, 120),
|
||||
distanceM: distanceKm === null ? null : metresOf(distanceKm * 1000),
|
||||
ascentM: climbOf(preview.elevationGainM),
|
||||
descentM: climbOf(preview.elevationLossM),
|
||||
limit: sac,
|
||||
routed: true,
|
||||
line,
|
||||
stops: [
|
||||
stopOf({ role: 'start', ...start, atM: 0, name: clipped(trail.location, 80) }),
|
||||
...(loop ? [] : [stopOf({ role: 'end', ...end, atM: metresOf((distanceKm ?? 0) * 1000) ?? 0 })]),
|
||||
],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** preview_wanderer_trail: the trail as a card. */
|
||||
export function wandererPreviewCard({ value }: AnswerInput): TourRouteCard | null {
|
||||
return wandererTrailCard(value, 'proposal');
|
||||
}
|
||||
|
||||
/** What a held wanderer import looked up: the trail's preview. */
|
||||
interface TrailLoaded {
|
||||
preview: unknown;
|
||||
}
|
||||
|
||||
/** import_wanderer_trail: the trail previewed again, for its name and its line. */
|
||||
async function loadImport(args: ToolArgs, read: CardReader): Promise<TrailLoaded | null> {
|
||||
if (typeof args.trailId !== 'string') return null;
|
||||
const preview = await read('preview_wanderer_trail', { trailId: args.trailId, include_geometry: true });
|
||||
return preview ? { preview } : null;
|
||||
}
|
||||
|
||||
/** The SAC grade a wanderer difficulty stands for, T1 to T3. */
|
||||
function gradeOf(difficulty: unknown): string {
|
||||
const sac =
|
||||
difficulty === 'easy' || difficulty === 'moderate' || difficulty === 'difficult'
|
||||
? wandererDifficultyToSac(difficulty)
|
||||
: null;
|
||||
return sac === null ? '' : `T${sac}`;
|
||||
}
|
||||
|
||||
/** import_wanderer_trail: the trail by its name, where it lies, its grade and its page on wanderer. */
|
||||
function describeImport(_ctx: PreviewContext, args: ToolArgs, loaded: TrailLoaded | null): Described {
|
||||
const trail = recordOf(recordOf(loaded?.preview).trail);
|
||||
const rows = new Rows()
|
||||
.add('location', text(trail.location))
|
||||
.add('difficulty', gradeOf(trail.difficulty))
|
||||
.add('link', text(trail.externalUrl));
|
||||
return { subject: text(trail.name) || text(args.trailId), rows, dayId: null, placeIds: [] };
|
||||
}
|
||||
|
||||
export const IMPORT_WANDERER_TRAIL: ToolCards<TrailLoaded> = {
|
||||
write: { verbKey: 'importTour', entity: 'tour' },
|
||||
load: loadImport,
|
||||
describe: describeImport,
|
||||
change: (_ctx, _args, loaded) => (loaded ? wandererTrailCard(loaded.preview, 'pending') : null),
|
||||
applied: appliedTourCard,
|
||||
undo: DELETE_CREATED_TOUR,
|
||||
};
|
||||
@@ -83,6 +83,8 @@ const valhallaSchema = z.object({
|
||||
}),
|
||||
});
|
||||
type Point = { lat: number; lng: number };
|
||||
/** A Valhalla answer that asked for alternates: its own way, then each other way it offers. */
|
||||
const alternatesSchema = valhallaSchema.extend({ alternates: z.array(valhallaSchema).max(5).optional() });
|
||||
export interface RoadtripRoute {
|
||||
leg: RoutedLeg;
|
||||
parts: { distance: number; duration: number }[];
|
||||
@@ -588,4 +590,33 @@ export class RoadtripRouterService {
|
||||
if (!valhalla) throw new RouteRefusal('no_valhalla', 'No Valhalla is set to describe a line with');
|
||||
return tracedWaysOf(await this.request(`${valhalla}/trace_attributes`, traceBody(line), TRACE_TIMEOUT_MS));
|
||||
}
|
||||
|
||||
/**
|
||||
* RTE-02: the ways on foot between two points under a hike's own costing,
|
||||
* the router's own first and then each other way it offers, at most
|
||||
* `count` besides, as the planner asks them (`valhallaAlternates`). Asked of
|
||||
* Valhalla alone through the paced queue: only Valhalla knows a hiking limit
|
||||
* and offers alternates on foot. A `RouteRefusal` where there is no Valhalla
|
||||
* or no way within the limit.
|
||||
*/
|
||||
async alternatesOnFoot(
|
||||
userId: number,
|
||||
from: Point,
|
||||
to: Point,
|
||||
costingOptions: NonNullable<RouteOptions['costingOptions']>,
|
||||
count: number,
|
||||
): Promise<Array<[number, number][]>> {
|
||||
const valhalla = await this.valhallaFor(userId);
|
||||
if (!valhalla) throw new RouteRefusal('no_valhalla', 'No Valhalla is set to plan a hike with');
|
||||
const payload = await this.request(`${valhalla}/route`, {
|
||||
locations: [from, to].map((p) => ({ lat: p.lat, lon: p.lng, radius: 50 })),
|
||||
costing: 'pedestrian',
|
||||
costing_options: { pedestrian: { ...costingOptions } },
|
||||
directions_options: { units: 'kilometers' },
|
||||
...(count > 0 ? { alternates: count } : {}),
|
||||
});
|
||||
const parsed = alternatesSchema.parse(payload);
|
||||
const trips = [parsed.trip, ...(parsed.alternates ?? []).map((alternate) => alternate.trip)];
|
||||
return trips.map((trip) => trip.legs.flatMap((leg) => decode(leg.shape)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { hikePointsOf } from './hike-plan.helpers';
|
||||
import {
|
||||
HIKE_MAX_WAYPOINTS,
|
||||
HIKE_WAY_KEYS,
|
||||
hikingPreferencesOf,
|
||||
TOURS_MAX_HIKING_DIFFICULTY,
|
||||
type HikeLegWayRequest,
|
||||
type HikePlanPoint,
|
||||
type HikeRoundProposeRequest,
|
||||
type HikeStop,
|
||||
type HikeWayKey,
|
||||
type HikeWayMiss,
|
||||
type HikeWayMissing,
|
||||
type HikeWayPoints,
|
||||
type HikingPreferences,
|
||||
type RoadLine,
|
||||
type WayPin,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The pure halves of the round hikes and the ways of a leg the assistant
|
||||
* proposes (HikeWaysService): which way a call asks for, the points a found
|
||||
* way is proposed and created through, and the keys a search is kept under.
|
||||
*/
|
||||
|
||||
type Spot = { lat: number; lng: number };
|
||||
|
||||
/** Points nearer than this many decimal places of a degree (about a metre) are one point for a search kept. */
|
||||
const KEY_DECIMALS = 5;
|
||||
|
||||
const keySpot = ({ lat, lng }: Spot) => [Number(lat.toFixed(KEY_DECIMALS)), Number(lng.toFixed(KEY_DECIMALS))];
|
||||
|
||||
/** The position of a way's letter among the ways found: a is the first. */
|
||||
export function wayIndexOf(key: HikeWayKey | undefined): number {
|
||||
return Math.max(0, HIKE_WAY_KEYS.indexOf(key ?? 'a'));
|
||||
}
|
||||
|
||||
/** The letter of the way at `index`. */
|
||||
export function wayKeyAt(index: number): HikeWayKey {
|
||||
return HIKE_WAY_KEYS[index] ?? 'a';
|
||||
}
|
||||
|
||||
/** The answer for a way asked for that was not found: why none, or that fewer were. */
|
||||
export function wayMissing(key: HikeWayKey | undefined, found: number, why: HikeWayMiss | null): HikeWayMissing {
|
||||
return { found: false, way: key ?? 'a', ways_found: found, why: why ?? 'none_found' };
|
||||
}
|
||||
|
||||
/** The hike's limit and preferences as a search is asked under, the defaults filled in. */
|
||||
export function rulesOf(request: { max_hiking_difficulty?: number; hiking_preferences?: HikingPreferences | null }): {
|
||||
limit: number;
|
||||
preferences: HikingPreferences | null;
|
||||
} {
|
||||
return {
|
||||
limit: request.max_hiking_difficulty ?? TOURS_MAX_HIKING_DIFFICULTY,
|
||||
preferences: hikingPreferencesOf(request.hiking_preferences),
|
||||
};
|
||||
}
|
||||
|
||||
/** What one round search depends on: who asked in which trip, the start to about a metre, the length and the rules. */
|
||||
export function roundSearchKey(userId: number, tripId: number, request: HikeRoundProposeRequest): string {
|
||||
const { limit, preferences } = rulesOf(request);
|
||||
return JSON.stringify([
|
||||
'round',
|
||||
userId,
|
||||
tripId,
|
||||
keySpot(request.start),
|
||||
Math.round(request.distance_km * 1000),
|
||||
limit,
|
||||
preferences,
|
||||
]);
|
||||
}
|
||||
|
||||
/** What the ways of one leg depend on: who asked in which trip, the hike's points, the leg and the rules. */
|
||||
export function legWaysKey(userId: number, tripId: number, request: HikeLegWayRequest): string {
|
||||
const { limit, preferences } = rulesOf(request);
|
||||
const points = hikePointsOf(request.waypoints, request.round_trip).map(keySpot);
|
||||
return JSON.stringify(['leg', userId, tripId, points, request.leg, limit, preferences]);
|
||||
}
|
||||
|
||||
/** The points a round is proposed and created through: its start, then the spots its loop is steered through. */
|
||||
export function roundPointsOf(start: HikePlanPoint, via: readonly Spot[]): HikeWayPoints {
|
||||
return { waypoints: [start, ...via.map(({ lat, lng }) => ({ lat, lng }))], round_trip: true };
|
||||
}
|
||||
|
||||
/** The two ends of leg `leg` (counted from 1) of a hike through these points, its way back included. */
|
||||
export function legEndsOf(
|
||||
waypoints: readonly HikeStop[],
|
||||
roundTrip: boolean | undefined,
|
||||
leg: number,
|
||||
): { from: Spot; to: Spot } | null {
|
||||
const points = hikePointsOf(waypoints, roundTrip);
|
||||
const from = points[leg - 1];
|
||||
const to = points[leg];
|
||||
return from && to ? { from: { lat: from.lat, lng: from.lng }, to: { lat: to.lat, lng: to.lng } } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The hike's points with `pins` set on leg `leg`, right after the point it
|
||||
* starts at; on a round trip the pins of the way back go last, before the
|
||||
* start the way back returns to. Null where the pins would take the hike past
|
||||
* the points one hike is asked through.
|
||||
*/
|
||||
export function pinnedPointsOf(
|
||||
waypoints: readonly HikeStop[],
|
||||
leg: number,
|
||||
pins: readonly WayPin[],
|
||||
): HikeStop[] | null {
|
||||
if (waypoints.length + pins.length > HIKE_MAX_WAYPOINTS) return null;
|
||||
const at = Math.min(leg, waypoints.length);
|
||||
return [...waypoints.slice(0, at), ...pins.map(({ lat, lng }) => ({ lat, lng })), ...waypoints.slice(at)];
|
||||
}
|
||||
|
||||
/** A router's line as a way to compare. */
|
||||
export function roadOf(coordinates: Array<[number, number]>, distance = 0, duration = 0): RoadLine {
|
||||
return { coordinates, distance, duration };
|
||||
}
|
||||
|
||||
/** A signed share as whole percent: 0.084 is 8. */
|
||||
export function percentOf(share: number): number {
|
||||
return Math.round(share * 100);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { noAccess } from '../../mcp/tools/_shared';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, errorResult, ok, type McpContext } from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { TripAccessService } from '../trip-membership/trip-access.service';
|
||||
import { HikeWaysService } from './hike-ways.service';
|
||||
import {
|
||||
hikeLegWayRequestSchema,
|
||||
hikeRoundProposeRequestSchema,
|
||||
idSchema,
|
||||
type HikeLegWayRequest,
|
||||
type HikeRoundProposeRequest,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* RTE-02 and RTE-03 over MCP: the planner's round hikes of a wished length
|
||||
* and its other ways for one leg of a hike. Both read only, as propose_hike
|
||||
* does (the planner offers them to anyone who can see the trip), and answer a
|
||||
* hike proposal of one way per call; the hike is created with create_hike, or
|
||||
* a saved one changed with update_tour, once the traveller chose.
|
||||
*/
|
||||
@McpController()
|
||||
export class HikeWaysMcp {
|
||||
constructor(
|
||||
private readonly ways: HikeWaysService,
|
||||
private readonly access: TripAccessService,
|
||||
// Read by the addon gate of every tool here.
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
name: 'propose_round_hike',
|
||||
description:
|
||||
"Find round hikes of about distance_km out of one start point and back (start: a car park, a station, a hut) and propose one of them, without saving anything, as the Tours planner's round search does: the router plans loops on foot in several directions under max_hiking_difficulty and hiking_preferences, keeps those within a fifth of the length that do not walk the same ground twice, and offers up to three different rounds, a, b and c. One search answers all three, so call it up to three times in one step with round a, b and c, each with along left out, to show them as ways to choose from (a search takes up to about a quarter of a minute). Each answer is the hike proposal propose_hike gives for the round (distance, climb, walking time, SAC grades, schedule and warnings with day_id or date and start_time), with round (key, target_m, deviation_pct, how far it lies off the length, and rounds_found) and create_with, the points to create it through: create_hike with name, create_with.waypoints, round_trip true and the same max_hiking_difficulty and hiking_preferences, only after the traveller chose one. A round that is not there answers found false with ways_found and why (none_found where no round fits, router_unavailable, no_valhalla). The chat shows each round as a card: never list coordinates or figures, say in a sentence what sets the rounds apart.",
|
||||
inputSchema: { tripId: idSchema, ...hikeRoundProposeRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
access: { group: 'trips', mode: 'read' },
|
||||
})
|
||||
async proposeRoundHike({ tripId, ...request }: { tripId: number } & HikeRoundProposeRequest, ctx: McpContext) {
|
||||
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
|
||||
return ok(await this.ways.proposeRound(ctx.userId, tripId, request));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'propose_hike_leg_way',
|
||||
description:
|
||||
"Propose another way for one leg of a hike, as the Tours planner's other ways of a section: the router's other ways on foot between the two points of leg (counted from 1; on a round trip the last leg is the way back) under the hike's max_hiking_difficulty and hiking_preferences, each held by the fewest points on it the router keeps to, at most three, a, b and c. Give the hike as it stands: name, waypoints and round_trip of a proposal, or of a saved hike from get_tour_plan with tour_id (its place id). One search answers all three, so call it up to three times in one step with way a, b and c to show them as ways to choose from. Each answer is the hike proposal propose_hike gives for the whole hike with the leg taken that way, with leg_way (key, leg, ways_found), current (the hike as it runs now: distance_m, ascent_m, duration_minutes) to compare against, and create_with, the hike's points with the way's points set on the leg. Only after the traveller chose one: for a hike not yet saved create_hike with name, create_with.waypoints and create_with.round_trip; for a saved hike update_tour with those waypoints (a round trip ending on its start) and its expected_revision. A way that is not there answers found false with ways_found and why (none_found where the router knows no other way it keeps to). The chat shows each way as a card beside the way it runs now: never list coordinates or figures, say in a sentence how the ways differ.",
|
||||
inputSchema: { tripId: idSchema, ...hikeLegWayRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
access: { group: 'trips', mode: 'read' },
|
||||
})
|
||||
async proposeHikeLegWay({ tripId, ...request }: { tripId: number } & HikeLegWayRequest, ctx: McpContext) {
|
||||
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
|
||||
// The tool's fields are checked one by one; the leg against the hike's points only here.
|
||||
const checked = hikeLegWayRequestSchema.safeParse(request);
|
||||
if (!checked.success) return errorResult(checked.error.issues.map((issue) => issue.message).join('; '));
|
||||
return ok(await this.ways.proposeLegWay(ctx.userId, tripId, checked.data));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
import { logWarn } from '../audit/audit-log.logger';
|
||||
import { badRequest } from '../common/domain-error';
|
||||
import { RoadtripRouterService, RouteRefusal } from '../roadtrip/roadtrip-router.service';
|
||||
import { HikePlanService } from './hike-plan.service';
|
||||
import { joinedLine } from './hike-routing.helpers';
|
||||
import {
|
||||
legEndsOf,
|
||||
legWaysKey,
|
||||
percentOf,
|
||||
pinnedPointsOf,
|
||||
roadOf,
|
||||
roundPointsOf,
|
||||
roundSearchKey,
|
||||
rulesOf,
|
||||
wayIndexOf,
|
||||
wayKeyAt,
|
||||
wayMissing,
|
||||
} from './hike-ways.helpers';
|
||||
import { ToursService } from './tours.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
computeTourMetrics,
|
||||
deviationOf,
|
||||
hikingCosting,
|
||||
HIKE_WAY_KEYS,
|
||||
otherWaysOf,
|
||||
pinWay,
|
||||
searchRoundLoops,
|
||||
TOUR_MAX_SNAP_M,
|
||||
type HikeLegWayProposal,
|
||||
type HikeLegWayRequest,
|
||||
type HikeRoundProposal,
|
||||
type HikeRoundProposeRequest,
|
||||
type HikeStop,
|
||||
type HikeWayMiss,
|
||||
type HikeWayMissing,
|
||||
type HikeWayPoints,
|
||||
type RoadLine,
|
||||
type RoundLoop,
|
||||
type WayPin,
|
||||
} from '@trek/shared';
|
||||
|
||||
type Spot = { lat: number; lng: number };
|
||||
|
||||
/** The day the router is asked for: a hike's way does not depend on it (see HikeRoutingService). */
|
||||
const ANY_DAY = 0;
|
||||
/** How long a search is kept: the rounds or ways of one answer are asked for one after another, and taken later. */
|
||||
const SEARCH_TTL_MS = 15 * 60_000;
|
||||
/** The most searches kept; the oldest goes first. */
|
||||
const SEARCH_MAX = 32;
|
||||
|
||||
/** What a round search found: the rounds, or why there are none. */
|
||||
interface RoundSearch {
|
||||
rounds: RoundLoop[];
|
||||
why: HikeWayMiss | null;
|
||||
}
|
||||
|
||||
/** What the ways of one leg came to: the hike's points with each way pinned on, or why there are none. */
|
||||
interface LegWays {
|
||||
ways: HikeStop[][];
|
||||
why: HikeWayMiss | null;
|
||||
}
|
||||
|
||||
interface Kept<T> {
|
||||
at: number;
|
||||
search: Promise<T>;
|
||||
}
|
||||
|
||||
/** What went wrong, for the log. */
|
||||
function reasonOf(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
/** Why a router that answered nothing answered nothing, in a proposal's words. */
|
||||
function missOf(err: unknown): HikeWayMiss {
|
||||
return err instanceof RouteRefusal ? err.why : 'router_unavailable';
|
||||
}
|
||||
|
||||
/**
|
||||
* RTE-02 and RTE-03 for the assistant: a round hike of about a wished length
|
||||
* out of one point, and the other ways the router knows for one leg of a
|
||||
* hike, each answered as a hike proposal (HikePlanService.propose), so the
|
||||
* chat draws and compares it as it does propose_hike's and creates the one
|
||||
* chosen with create_hike. The search is the planner's (`searchRoundLoops`,
|
||||
* `otherWaysOf`, `pinWay` in @trek/shared), asked of the server's router
|
||||
* under the hike's own costing. One search answers the three ways: the calls
|
||||
* for b and c share the search the call for a started, kept for a while.
|
||||
* Writes nothing.
|
||||
*/
|
||||
@Injectable()
|
||||
export class HikeWaysService {
|
||||
private readonly kept = new Map<string, Kept<RoundSearch | LegWays>>();
|
||||
|
||||
constructor(
|
||||
private readonly router: RoadtripRouterService,
|
||||
private readonly hikes: HikePlanService,
|
||||
private readonly tours: ToursService,
|
||||
) {}
|
||||
|
||||
/** The round `request.round` of the rounds found out of the start, proposed as a hike; missing where there is none. */
|
||||
async proposeRound(
|
||||
userId: number,
|
||||
tripId: number,
|
||||
request: HikeRoundProposeRequest,
|
||||
): Promise<HikeRoundProposal | HikeWayMissing> {
|
||||
const key = roundSearchKey(userId, tripId, request);
|
||||
const search = await this.recall(key, () => this.searchRounds(userId, tripId, request));
|
||||
const { rounds, why } = search as RoundSearch;
|
||||
const index = wayIndexOf(request.round);
|
||||
const round = rounds[index];
|
||||
if (!round) return wayMissing(request.round, rounds.length, why);
|
||||
const points = roundPointsOf(request.start, round.via);
|
||||
const proposal = await this.hikes.propose(userId, tripId, {
|
||||
name: request.name,
|
||||
...points,
|
||||
max_hiking_difficulty: request.max_hiking_difficulty,
|
||||
hiking_preferences: request.hiking_preferences,
|
||||
variant_label: request.variant_label,
|
||||
day_id: request.day_id,
|
||||
date: request.date,
|
||||
start_time: request.start_time,
|
||||
along: false,
|
||||
include_geometry: request.include_geometry,
|
||||
});
|
||||
const targetM = Math.round(request.distance_km * 1000);
|
||||
return {
|
||||
...proposal,
|
||||
found: true,
|
||||
round: {
|
||||
key: wayKeyAt(index),
|
||||
target_m: targetM,
|
||||
deviation_pct: percentOf(deviationOf(proposal.distance_m ?? round.distanceM, targetM)),
|
||||
rounds_found: rounds.length,
|
||||
},
|
||||
create_with: points,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The way `request.way` of the other ways for one leg, proposed as the
|
||||
* whole hike with that leg taken so, beside the hike as it runs now;
|
||||
* missing where there is none. A saved hike named by `tour_id` must be a
|
||||
* hike of the trip.
|
||||
*/
|
||||
async proposeLegWay(
|
||||
userId: number,
|
||||
tripId: number,
|
||||
request: HikeLegWayRequest,
|
||||
): Promise<HikeLegWayProposal | HikeWayMissing> {
|
||||
if (request.tour_id !== undefined) {
|
||||
const { tour } = await this.tours.getTour(String(tripId), String(request.tour_id));
|
||||
if (tour.tour_type !== 'hike') throw badRequest('Only the legs of a hike have other ways here.');
|
||||
}
|
||||
const key = legWaysKey(userId, tripId, request);
|
||||
const search = await this.recall(key, () => this.searchLegWays(userId, tripId, request));
|
||||
const { ways, why } = search as LegWays;
|
||||
const index = wayIndexOf(request.way);
|
||||
const waypoints = ways[index];
|
||||
if (!waypoints) return wayMissing(request.way, ways.length, why);
|
||||
const roundTrip = request.round_trip === true;
|
||||
const base = {
|
||||
name: request.name,
|
||||
max_hiking_difficulty: request.max_hiking_difficulty,
|
||||
hiking_preferences: request.hiking_preferences,
|
||||
day_id: request.day_id,
|
||||
date: request.date,
|
||||
start_time: request.start_time,
|
||||
round_trip: roundTrip,
|
||||
along: false,
|
||||
include_geometry: request.include_geometry,
|
||||
};
|
||||
const current = await this.hikes.propose(userId, tripId, { ...base, waypoints: request.waypoints });
|
||||
const proposal = await this.hikes.propose(userId, tripId, { ...base, waypoints });
|
||||
const points: HikeWayPoints = {
|
||||
waypoints: waypoints.map(({ lat, lng, name, poi_category, stage_end }) => ({
|
||||
lat,
|
||||
lng,
|
||||
...(name === undefined ? {} : { name }),
|
||||
...(poi_category === undefined ? {} : { poi_category }),
|
||||
...(stage_end === true ? { stage_end } : {}),
|
||||
})),
|
||||
round_trip: roundTrip,
|
||||
};
|
||||
return {
|
||||
...proposal,
|
||||
found: true,
|
||||
leg_way: { key: wayKeyAt(index), leg: request.leg, ways_found: ways.length, tour_id: request.tour_id ?? null },
|
||||
current: {
|
||||
distance_m: current.distance_m,
|
||||
ascent_m: current.ascent_m,
|
||||
duration_minutes: current.duration_minutes,
|
||||
},
|
||||
...(request.include_geometry === true && current.line_geometry
|
||||
? { current_geometry: current.line_geometry }
|
||||
: {}),
|
||||
create_with: points,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The search kept under `key`, or a new one started; one asked while
|
||||
* another for the same key runs shares it. A search that failed is not kept.
|
||||
*/
|
||||
private async recall<T extends RoundSearch | LegWays>(key: string, start: () => Promise<T>): Promise<T> {
|
||||
const now = Date.now();
|
||||
for (const [other, entry] of this.kept) if (now - entry.at >= SEARCH_TTL_MS) this.kept.delete(other);
|
||||
const kept = this.kept.get(key);
|
||||
if (kept) return (await kept.search) as T;
|
||||
const search = start();
|
||||
this.kept.set(key, { at: now, search });
|
||||
const [oldest] = this.kept.keys();
|
||||
if (this.kept.size > SEARCH_MAX && oldest !== undefined) this.kept.delete(oldest);
|
||||
try {
|
||||
return await search;
|
||||
} catch (err: unknown) {
|
||||
this.kept.delete(key);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** The rounds out of the start, asked of the router as the planner asks them. */
|
||||
private async searchRounds(userId: number, tripId: number, request: HikeRoundProposeRequest): Promise<RoundSearch> {
|
||||
const { limit, preferences } = rulesOf(request);
|
||||
const costingOptions = hikingCosting(limit, preferences);
|
||||
const start = { lat: request.start.lat, lng: request.start.lng };
|
||||
let refused: HikeWayMiss | null = null;
|
||||
const ask = async (spots: Spot[]): Promise<RoundLoop | null | undefined> => {
|
||||
try {
|
||||
const route = await this.router.route(userId, tripId, ANY_DAY, [start, ...spots, start], 'walking', [], {
|
||||
costingOptions,
|
||||
});
|
||||
if ((route.snapped ?? []).some((point) => point.meters > TOUR_MAX_SNAP_M)) return null;
|
||||
const coordinates = joinedLine(route.leg.line);
|
||||
const via = route.snapped?.slice(1, -1).map(({ at }) => ({ lat: at[0], lng: at[1] })) ?? spots;
|
||||
return { coordinates, via, distanceM: Math.round(computeTourMetrics(coordinates).distanceKm * 1000) };
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof RouteRefusal && err.why !== 'no_valhalla') return null;
|
||||
refused = missOf(err);
|
||||
if (!(err instanceof RouteRefusal)) logWarn(`[Hike] no round for trip ${tripId}: ${reasonOf(err)}`);
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
// Without a Valhalla to ask no round can be found: the search stops at the first answer saying so.
|
||||
const signal = {
|
||||
get aborted() {
|
||||
return refused === 'no_valhalla';
|
||||
},
|
||||
};
|
||||
const state = await searchRoundLoops(start, request.distance_km * 1000, ask, { signal });
|
||||
if (state.answered === 0) return { rounds: [], why: refused ?? 'router_unavailable' };
|
||||
return { rounds: state.found, why: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* The other ways of one leg: the router's ways between its two ends under
|
||||
* the hike's costing, those that are no way already known, each held by
|
||||
* the fewest pins the router keeps to (as the planner holds a way chosen),
|
||||
* and the hike's points with those pins set on the leg. A way the router
|
||||
* does not keep to, or that would take the hike past its points, is left out.
|
||||
*/
|
||||
private async searchLegWays(userId: number, tripId: number, request: HikeLegWayRequest): Promise<LegWays> {
|
||||
const ends = legEndsOf(request.waypoints, request.round_trip, request.leg);
|
||||
if (!ends) throw badRequest('The hike has no such leg');
|
||||
const { limit, preferences } = rulesOf(request);
|
||||
const costingOptions = hikingCosting(limit, preferences);
|
||||
let offers: Array<[number, number][]>;
|
||||
try {
|
||||
offers = await this.router.alternatesOnFoot(userId, ends.from, ends.to, costingOptions, HIKE_WAY_KEYS.length);
|
||||
} catch (err: unknown) {
|
||||
if (!(err instanceof RouteRefusal)) logWarn(`[Hike] no other ways for trip ${tripId}: ${reasonOf(err)}`);
|
||||
return { ways: [], why: missOf(err) };
|
||||
}
|
||||
const [own] = offers;
|
||||
if (!own) return { ways: [], why: 'no_way' };
|
||||
const current = roadOf(own);
|
||||
const route = async (pins: WayPin[]): Promise<RoadLine & { fellBack?: boolean }> => {
|
||||
try {
|
||||
const way = await this.router.route(userId, tripId, ANY_DAY, [ends.from, ...pins, ends.to], 'walking', [], {
|
||||
costingOptions,
|
||||
});
|
||||
return roadOf(joinedLine(way.leg.line), way.leg.seg.distance, way.leg.seg.duration);
|
||||
} catch {
|
||||
// No answer proves nothing: the way is not offered.
|
||||
return { ...roadOf([]), fellBack: true };
|
||||
}
|
||||
};
|
||||
const others = otherWaysOf(
|
||||
current,
|
||||
offers.map((line) => ({ coordinates: line })),
|
||||
HIKE_WAY_KEYS.length,
|
||||
);
|
||||
// One way after another: each check asks the router's one paced queue.
|
||||
const ways = await others.reduce<Promise<HikeStop[][]>>(async (before, offer) => {
|
||||
const held = await before;
|
||||
const proof = await pinWay({ offer: roadOf(offer.coordinates), current, route });
|
||||
const pinned = proof?.held ? pinnedPointsOf(request.waypoints, request.leg, proof.pins) : null;
|
||||
return pinned ? [...held, pinned] : held;
|
||||
}, Promise.resolve([]));
|
||||
return { ways, why: null };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
|
||||
import {
|
||||
McpController,
|
||||
Tool,
|
||||
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
TOOL_ANNOTATIONS_READONLY,
|
||||
ok,
|
||||
type McpContext,
|
||||
} from '../../nest-mcp';
|
||||
import type { HasAddons } 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 { ToursWandererService } from './tours-wanderer.service';
|
||||
import {
|
||||
idSchema,
|
||||
wandererMcpImportRequestSchema,
|
||||
wandererMcpPreviewRequestSchema,
|
||||
wandererMcpSearchRequestSchema,
|
||||
wandererMcpSourceRequestSchema,
|
||||
type WandererMcpImportRequest,
|
||||
type WandererMcpPreviewRequest,
|
||||
type WandererMcpSearchRequest,
|
||||
type WandererMcpSourceRequest,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** Offered only while the admin allows wanderer under Tours, as WandererEnabledGuard lets its routes through. */
|
||||
const wandererOn = (_ctx: McpContext, self: HasAddons): Promise<boolean> => self.addons.isWandererAvailable();
|
||||
|
||||
/**
|
||||
* The trip-side wanderer routes over MCP (ToursWandererController): the
|
||||
* caller's own wanderer trails searched, one previewed, imported as a tour
|
||||
* of the trip, and a tour imported from it checked against its source. Each
|
||||
* runs on the caller's own connection with 'place_edit' on the trip, as REST
|
||||
* asks it of every route there (looking is the first step of importing). The
|
||||
* import writes the snapshot through the same service, which tells the trip
|
||||
* about it (tours:changed and place:created) without leaving out any socket.
|
||||
* A refusal of the service is a DomainError, which the registry answers as an
|
||||
* error result with the text REST sends.
|
||||
*/
|
||||
@McpController()
|
||||
export class ToursWandererMcp {
|
||||
constructor(
|
||||
private readonly wanderer: ToursWandererService,
|
||||
private readonly access: TripAccessService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
// Read by the wanderer gate of every tool here.
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
/** Trip access and 'place_edit', as the REST routes' guards ask them; the refusal to answer, or null. */
|
||||
private async refusal(tripId: number, userId: number) {
|
||||
if (!(await this.access.findAccessible(tripId, userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('place_edit', tripId, userId))) return permissionDenied();
|
||||
return null;
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'search_wanderer_trails',
|
||||
description:
|
||||
"Search the traveller's own wanderer trails (their connected wanderer instance, a trail database) by words (q: a place, summit or region), page and part of the map (bbox), for a trip. The answer lists trails with id, name, description, location, distanceM, durationS, elevationGainM, elevationLossM, difficulty (easy, moderate, difficult), public, author, externalUrl and importedAs (the tours of this trip already imported from the trail), with total, page and pageSize. A traveller without a wanderer connection gets an error saying so. Preview a trail with preview_wanderer_trail before importing it. Needs place editing permission on the trip.",
|
||||
inputSchema: { tripId: idSchema, ...wandererMcpSearchRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: wandererOn,
|
||||
access: { group: 'trips', mode: 'read' },
|
||||
})
|
||||
async searchTrails({ tripId, q, page, bbox }: { tripId: number } & WandererMcpSearchRequest, ctx: McpContext) {
|
||||
const refused = await this.refusal(tripId, ctx.userId);
|
||||
if (refused) return refused;
|
||||
const found = await this.wanderer.search(String(tripId), ctx.userId, { q: q ?? '', page: page ?? 1, bbox });
|
||||
// The instance's simplified lines are for a map; the model plans with the facts.
|
||||
return ok({ ...found, trails: found.trails.map(({ line: _line, ...trail }) => trail) });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'preview_wanderer_trail',
|
||||
description:
|
||||
'Preview one wanderer trail before it is imported into the trip, without writing anything: its facts, distanceKm, elevationGainM and elevationLossM measured from its full GPX, points, contentHash (what import_wanderer_trail takes), state (new: not in the trip yet; unchanged: already imported as it is; changed: imported, and the trail changed since), snapshot (the tour imported last: placeId, name, importedAt, editedLocally) and changes (name, description, route). The chat shows the trail as a card: never list its figures, say in a sentence what matters. Import it only after the traveller said yes. Needs place editing permission on the trip.',
|
||||
inputSchema: { tripId: idSchema, ...wandererMcpPreviewRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: wandererOn,
|
||||
access: { group: 'trips', mode: 'read' },
|
||||
})
|
||||
async previewTrail(
|
||||
{ tripId, trailId, include_geometry }: { tripId: number } & WandererMcpPreviewRequest,
|
||||
ctx: McpContext,
|
||||
) {
|
||||
const refused = await this.refusal(tripId, ctx.userId);
|
||||
if (refused) return refused;
|
||||
const { line, trail, ...preview } = await this.wanderer.preview(String(tripId), ctx.userId, trailId);
|
||||
const { line: _simplified, ...facts } = trail;
|
||||
return ok({ ...preview, trail: facts, ...(include_geometry === true ? { line_geometry: line } : {}) });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'import_wanderer_trail',
|
||||
description:
|
||||
"Import a wanderer trail into the trip as a tour (a hike with the trail's full line, its source noted), as the Tours tab's wanderer import does: trailId and the contentHash preview_wanderer_trail gave. Refused when the trail changed since the preview (preview it again) or when the trip already holds this very content (the error names its placeId). An earlier import of the trail stays as it is: a changed trail comes in as a new tour beside it. The answer is the tour as list_tours reads it (tour.place_id is its id). Needs place editing permission on the trip. Import only after the traveller said yes.",
|
||||
inputSchema: { tripId: idSchema, ...wandererMcpImportRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
when: wandererOn,
|
||||
access: { group: 'trips', mode: 'write' },
|
||||
})
|
||||
async importTrail({ tripId, ...request }: { tripId: number } & WandererMcpImportRequest, ctx: McpContext) {
|
||||
const refused = await this.refusal(tripId, ctx.userId);
|
||||
if (refused) return refused;
|
||||
return ok(await this.wanderer.import(String(tripId), ctx.userId, request));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'check_tour_source',
|
||||
description:
|
||||
"Ask wanderer whether the trail a tour of the trip was imported from (origin wanderer) changed since, without changing the tour. state: unchanged, changed (changes names name, description or route; reimport has the trailId and contentHash to import the trail again as a new tour, which import_wanderer_trail does once the traveller said yes), unknown (imported before TREK kept a fingerprint; reimport is given), unavailable (the trail is gone or no longer the traveller's to read), not_connected (no wanderer connection) or other_instance (the connection is to another instance). editedLocally says whether the tour was changed in TREK since the import. A tour that did not come from wanderer is refused. Needs place editing permission on the trip.",
|
||||
inputSchema: { tripId: idSchema, ...wandererMcpSourceRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: wandererOn,
|
||||
access: { group: 'trips', mode: 'read' },
|
||||
})
|
||||
async checkSource({ tripId, placeId }: { tripId: number } & WandererMcpSourceRequest, ctx: McpContext) {
|
||||
const refused = await this.refusal(tripId, ctx.userId);
|
||||
if (refused) return refused;
|
||||
return ok(await this.wanderer.checkSource(String(tripId), ctx.userId, String(placeId)));
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,8 @@ import { CollectionToursService } from './collection-tours.service';
|
||||
import { HikePlanMcp } from './hike-plan.mcp';
|
||||
import { HikePlanService } from './hike-plan.service';
|
||||
import { HikeRoutingService } from './hike-routing.service';
|
||||
import { HikeWaysMcp } from './hike-ways.mcp';
|
||||
import { HikeWaysService } from './hike-ways.service';
|
||||
import { TourActivitiesController } from './tour-activities.controller';
|
||||
import { TourActivitiesMcp } from './tour-activities.mcp';
|
||||
import { TourActivitiesService } from './tour-activities.service';
|
||||
@@ -77,6 +79,7 @@ import { TourWalkImportMcp } from './tour-walk-import.mcp';
|
||||
import { TourWalkImportService } from './tour-walk-import.service';
|
||||
import { ToursImportController } from './tours-import.controller';
|
||||
import { ToursWandererController } from './tours-wanderer.controller';
|
||||
import { ToursWandererMcp } from './tours-wanderer.mcp';
|
||||
import { ToursWandererService } from './tours-wanderer.service';
|
||||
import { ToursController } from './tours.controller';
|
||||
import { ToursMcp } from './tours.mcp';
|
||||
@@ -99,7 +102,9 @@ import { Module } from '@nestjs/common';
|
||||
* tours' own repositories, is planned on foot by RoadtripModule's router and
|
||||
* is created through ToursService (CW-11). A hike an assistant plans with the
|
||||
* traveller is proposed, created, changed or taken in from a GPX file through
|
||||
* the same writes, its way planned on the server by HikeRoutingService, its
|
||||
* the same writes, its way planned on the server by HikeRoutingService (a
|
||||
* round of a wished length and the other ways of a leg found by HikeWaysService
|
||||
* with the planner's own search), its
|
||||
* day read from WeatherModule's detailed weather and the places along it from
|
||||
* the tours' own search; one created on a day is put there through
|
||||
* AssignmentsService in the same write. A
|
||||
@@ -212,6 +217,7 @@ import { Module } from '@nestjs/common';
|
||||
CityWalkBriefingService,
|
||||
HikeRoutingService,
|
||||
HikePlanService,
|
||||
HikeWaysService,
|
||||
TourChangePreviewService,
|
||||
TourChangeSaveService,
|
||||
TourChangeUndoService,
|
||||
@@ -233,6 +239,8 @@ import { Module } from '@nestjs/common';
|
||||
TourActivityStatsMcp,
|
||||
CollectionToursMcp,
|
||||
TourPackingMcp,
|
||||
HikeWaysMcp,
|
||||
ToursWandererMcp,
|
||||
],
|
||||
})
|
||||
export class ToursModule {}
|
||||
|
||||
@@ -28,7 +28,7 @@ import { makePackingBag, makePackingItem } from '../../helpers/factories/packing
|
||||
import { makeCategory, makePlace, makeTag } from '../../helpers/factories/places';
|
||||
import { makeReservation } from '../../helpers/factories/reservations';
|
||||
import { createRow, findRow, insertRow, updateRows } from '../../helpers/factories/rows';
|
||||
import { setAddonEnabled, setCollabFeature } from '../../helpers/factories/settings';
|
||||
import { setAddonEnabled, setAppSetting, setCollabFeature } from '../../helpers/factories/settings';
|
||||
import { makeTodoItem } from '../../helpers/factories/todos';
|
||||
import { makeTour } from '../../helpers/factories/tours';
|
||||
import { addTripMember, makeTrip, readTripDays } from '../../helpers/factories/trips';
|
||||
@@ -221,6 +221,8 @@ export async function openHarness(): Promise<ParityHarness> {
|
||||
const orm = app.get(MikroORM);
|
||||
await oneByOne(Object.values(ADDON_IDS), (addon) => setAddonEnabled(orm, addon, true));
|
||||
await oneByOne(['chat', 'notes', 'polls', 'whatsnext'] as const, (feature) => setCollabFeature(orm, feature, true));
|
||||
// The wanderer tools show only while wanderer is allowed under Tours.
|
||||
await setAppSetting(orm, 'tours_wanderer_enabled', 'true');
|
||||
// The photo search tools show only while a provider is on.
|
||||
await updateRows(orm, PhotoProviders, { id: { $in: ['immich', 'synologyphotos'] } }, { enabled: 1 });
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ import { TourWaypoints } from '../../../src/db/entities/TourWaypoints.entity';
|
||||
import { Tours } from '../../../src/db/entities/Tours.entity';
|
||||
import { RoadtripRouterService } from '../../../src/nest/roadtrip/roadtrip-router.service';
|
||||
import { proposalIdOf } from '../../../src/nest/tours/tour-change-proposal';
|
||||
import { ToursWandererService } from '../../../src/nest/tours/tours-wanderer.service';
|
||||
import { WandererService } from '../../../src/nest/wanderer/wanderer.service';
|
||||
import { makeDayAssignment } from '../../helpers/factories/itinerary';
|
||||
import { makePlace } from '../../helpers/factories/places';
|
||||
import { createRow, deleteRows, updateRows } from '../../helpers/factories/rows';
|
||||
@@ -192,6 +194,53 @@ const gpxOf = (s: Scene) =>
|
||||
`<gpx><trk><name>Ridge ${s.n}</name><trkseg><trkpt lat="47.6" lon="11.3"><ele>800</ele></trkpt>` +
|
||||
'<trkpt lat="47.61" lon="11.3"><ele>1000</ele></trkpt></trkseg></trk></gpx>';
|
||||
|
||||
/** The fingerprint of the wanderer trail a case's setup previewed, by the scene's number. */
|
||||
const trailHashFor = new Map<number, string>();
|
||||
|
||||
function trailHash(s: Scene): string {
|
||||
const hash = trailHashFor.get(s.n);
|
||||
if (hash === undefined) throw new Error(`scene ${s.n}: the case's setup previewed no trail`);
|
||||
return hash;
|
||||
}
|
||||
|
||||
/** No wanderer instance in a test: the owner's own trail, found and downloaded as the connection would. */
|
||||
function wandererTrail(app: INestApplication): () => void {
|
||||
const wanderer = app.get(WandererService);
|
||||
const summary = {
|
||||
id: 'trail-1',
|
||||
name: 'Kesselberg',
|
||||
description: null,
|
||||
location: 'Kochel',
|
||||
distanceM: 2200,
|
||||
durationS: 3600,
|
||||
elevationGainM: 200,
|
||||
elevationLossM: 0,
|
||||
difficulty: 'moderate' as const,
|
||||
public: false,
|
||||
author: 'owner',
|
||||
line: [],
|
||||
externalUrl: 'https://wanderer.example/trail/view/trail-1',
|
||||
};
|
||||
const found = vi.spyOn(wanderer, 'findTrail').mockResolvedValue(summary);
|
||||
const download = vi.spyOn(wanderer, 'download').mockResolvedValue({
|
||||
instance: 'https://wanderer.example',
|
||||
trail: { id: 'trail-1', name: 'Kesselberg', description: null, author: 'owner', updated: null } as never,
|
||||
gpx:
|
||||
'<gpx><trk><name>Kesselberg</name><trkseg><trkpt lat="47.6" lon="11.3"><ele>800</ele></trkpt>' +
|
||||
'<trkpt lat="47.62" lon="11.3"><ele>1000</ele></trkpt></trkseg></trk></gpx>',
|
||||
});
|
||||
return () => {
|
||||
found.mockRestore();
|
||||
download.mockRestore();
|
||||
};
|
||||
}
|
||||
|
||||
/** The trail previewed first, as the traveller sees it before the import: its fingerprint is what the import takes. */
|
||||
async function previewTrail(s: Scene, app: INestApplication): Promise<void> {
|
||||
const preview = await app.get(ToursWandererService).preview(String(s.trip.id), s.owner.id, 'trail-1');
|
||||
trailHashFor.set(s.n, preview.contentHash);
|
||||
}
|
||||
|
||||
const roadtripDay = (s: Scene) => `/api/trips/${s.trip.id}/roadtrip/days/${s.days[0].id}`;
|
||||
const tourPath = (s: Scene) => `/api/trips/${s.trip.id}/tours/${s.tourPlace.id}`;
|
||||
|
||||
@@ -365,6 +414,18 @@ export const toursRoadtrip: CaseGroup = {
|
||||
twin: 'POST /api/trips/:tripId/tours/import/gpx with the file',
|
||||
expect: ['tours:changed', 'place:created'],
|
||||
},
|
||||
{
|
||||
tool: 'import_wanderer_trail',
|
||||
setup: previewTrail,
|
||||
args: (s) => ({ tripId: s.trip.id, trailId: 'trail-1', contentHash: trailHash(s) }),
|
||||
rest: {
|
||||
method: 'post',
|
||||
path: (s) => `/api/trips/${s.trip.id}/tours/wanderer/import`,
|
||||
body: (s) => ({ trailId: 'trail-1', contentHash: trailHash(s) }),
|
||||
},
|
||||
stub: wandererTrail,
|
||||
expect: ['tours:changed', 'place:created'],
|
||||
},
|
||||
{
|
||||
tool: 'save_tour_change',
|
||||
needs: ['tour'],
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* ASSISTANT-WAYS-TAKE-001 to ASSISTANT-WAYS-TAKE-004: "Plan this" on a round
|
||||
* hike, another way of a leg and a wanderer trail: the change each holds,
|
||||
* taken from the stored proposal, never from the request.
|
||||
*/
|
||||
import { isWayProposal, wayTakeArgsOf } from '../../../../src/nest/assistant/assistant-proposal-ways';
|
||||
import { takeArgsOf } from '../../../../src/nest/assistant/assistant-proposals.service';
|
||||
import { writeToolOf } from '../../../../src/nest/assistant/assistant-tools.constants';
|
||||
import type { TourRouteCard } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const CARD = { kind: 'tourRoute', source: 'proposal', routed: true, placeId: null } as TourRouteCard;
|
||||
const START = { lat: 47.6, lng: 11.3, name: 'Car park', at_m: 0 };
|
||||
const ROUND = {
|
||||
create_with: {
|
||||
waypoints: [START, { lat: 47.61, lng: 11.31 }, { lat: 47.62, lng: 11.3, poi_category: 'peak' }],
|
||||
round_trip: true,
|
||||
},
|
||||
};
|
||||
|
||||
describe('taking a round or a leg’s way', () => {
|
||||
it('ASSISTANT-WAYS-TAKE-001: a round is created through the points it answered, under the rules it was asked with', () => {
|
||||
const args = { name: 'Round', start: START, distance_km: 10, max_hiking_difficulty: 3, day_id: 31, round: 'b' };
|
||||
expect(wayTakeArgsOf('propose_round_hike', args, ROUND, CARD)).toEqual({
|
||||
via: 'create_hike',
|
||||
name: 'Round',
|
||||
max_hiking_difficulty: 3,
|
||||
day_id: 31,
|
||||
round_trip: true,
|
||||
waypoints: [
|
||||
{ lat: 47.6, lng: 11.3, name: 'Car park' },
|
||||
{ lat: 47.61, lng: 11.31 },
|
||||
{ lat: 47.62, lng: 11.3, poi_category: 'peak' },
|
||||
],
|
||||
});
|
||||
expect(takeArgsOf({ toolName: 'propose_round_hike', args, result: ROUND, card: CARD })).toMatchObject({
|
||||
via: 'create_hike',
|
||||
});
|
||||
// A stop a day ends at stays one on a hike over several days.
|
||||
const trek = {
|
||||
create_with: { waypoints: [START, { lat: 47.7, lng: 11.4, stage_end: true }, START], round_trip: false },
|
||||
};
|
||||
expect(wayTakeArgsOf('propose_hike_leg_way', { name: 'Trek' }, trek, CARD)?.waypoints).toEqual([
|
||||
{ lat: 47.6, lng: 11.3, name: 'Car park' },
|
||||
{ lat: 47.7, lng: 11.4, stage_end: true },
|
||||
{ lat: 47.6, lng: 11.3, name: 'Car park' },
|
||||
]);
|
||||
expect(isWayProposal('propose_hike_leg_way')).toBe(true);
|
||||
expect(isWayProposal('toString')).toBe(false);
|
||||
});
|
||||
|
||||
it('ASSISTANT-WAYS-TAKE-002: nothing is taken from a way not planned, a saved hike’s leg or broken points', () => {
|
||||
expect(wayTakeArgsOf('propose_round_hike', {}, ROUND, { ...CARD, routed: false })).toBeNull();
|
||||
expect(wayTakeArgsOf('propose_hike_leg_way', {}, ROUND, { ...CARD, placeId: 61 })).toBeNull();
|
||||
const broken = { create_with: { waypoints: [START, { lat: 'x' }], round_trip: false } };
|
||||
expect(wayTakeArgsOf('propose_hike_leg_way', {}, broken, CARD)).toBeNull();
|
||||
expect(wayTakeArgsOf('propose_hike_leg_way', {}, {}, CARD)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('taking a wanderer trail', () => {
|
||||
it('ASSISTANT-WAYS-TAKE-003: a trail is imported with the fingerprint its preview answered', () => {
|
||||
const result = { contentHash: 'h'.repeat(32), state: 'new' };
|
||||
expect(wayTakeArgsOf('preview_wanderer_trail', { trailId: 'trail-1' }, result, CARD)).toEqual({
|
||||
via: 'import_wanderer_trail',
|
||||
trailId: 'trail-1',
|
||||
contentHash: 'h'.repeat(32),
|
||||
});
|
||||
// The take runs the import itself.
|
||||
expect(writeToolOf('take_proposal', { via: 'import_wanderer_trail' })).toBe('import_wanderer_trail');
|
||||
});
|
||||
|
||||
it('ASSISTANT-WAYS-TAKE-004: a trail already in the trip as it is, or a preview without its fingerprint, is not taken', () => {
|
||||
const args = { trailId: 'trail-1' };
|
||||
expect(wayTakeArgsOf('preview_wanderer_trail', args, { contentHash: 'h', state: 'unchanged' }, CARD)).toBeNull();
|
||||
expect(wayTakeArgsOf('preview_wanderer_trail', args, { state: 'new' }, CARD)).toBeNull();
|
||||
expect(wayTakeArgsOf('preview_wanderer_trail', {}, { contentHash: 'h', state: 'new' }, CARD)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* ASTCARD-TOUR-WAYS-001 to ASTCARD-TOUR-WAYS-008
|
||||
*
|
||||
* The cards of the planner's other searches through the assistant: a round
|
||||
* hike and another way for one leg, drawn as propose_hike's proposals are,
|
||||
* the leg's way beside the hike as it runs now; a wanderer trail previewed
|
||||
* as a way to take in, and its import with a change card and a way back.
|
||||
*/
|
||||
import { buildTripCard } from '../../../../../../src/nest/assistant/assistant-context';
|
||||
import type { CardReader, PreviewContext } from '../../../../../../src/nest/assistant/cards/card-types';
|
||||
import {
|
||||
answerCardOf,
|
||||
ASSISTANT_ARG_POLICY,
|
||||
ASSISTANT_UNDO_MAP,
|
||||
ASSISTANT_WRITE_TOOLS,
|
||||
CARD_PROMPT_LINES,
|
||||
} from '../../../../../../src/nest/assistant/cards/registry';
|
||||
import {
|
||||
IMPORT_WANDERER_TRAIL,
|
||||
legWayCard,
|
||||
roundHikeCard,
|
||||
wandererPreviewCard,
|
||||
wandererTrailCard,
|
||||
} from '../../../../../../src/nest/assistant/cards/tour/tour-ways.cards';
|
||||
import { trekCardSchema } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const card = buildTripCard(1, 7, { trip: { title: 'Bavaria' }, days: [] }, { places: [] }, null);
|
||||
const ctx: PreviewContext = { card, categories: new Map(), locale: 'en-GB', today: '2026-06-01', airport: () => null };
|
||||
|
||||
const LINE: Array<[number, number, number]> = [
|
||||
[47.6, 11.3, 800],
|
||||
[47.61, 11.31, 950],
|
||||
[47.62, 11.3, 1100],
|
||||
[47.6, 11.3, 800],
|
||||
];
|
||||
|
||||
/** A proposal as propose_hike answers it, its way planned, with what the search adds. */
|
||||
function proposal(extra: Record<string, unknown> = {}) {
|
||||
return {
|
||||
found: true,
|
||||
name: 'Round over the Kesselberg',
|
||||
variant_label: null,
|
||||
route: { planned: true },
|
||||
distance_m: 10_400,
|
||||
ascent_m: 300,
|
||||
descent_m: 300,
|
||||
duration_minutes: 190,
|
||||
duration_basis: 'din33466',
|
||||
max_hiking_difficulty: 2,
|
||||
line_geometry: LINE,
|
||||
waypoints: [
|
||||
{ lat: 47.6, lng: 11.3, name: 'Car park', at_m: 0, minutes: 0 },
|
||||
{ lat: 47.61, lng: 11.31, name: null, at_m: 3000, minutes: 60 },
|
||||
{ lat: 47.6, lng: 11.3, name: 'Car park', at_m: 10_400, minutes: 190 },
|
||||
],
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
const answer = (value: unknown, args: Record<string, unknown> = {}) => ({
|
||||
toolCallId: 't1',
|
||||
args,
|
||||
value,
|
||||
card,
|
||||
today: '2026-06-01',
|
||||
});
|
||||
|
||||
describe('a round and another way of a leg', () => {
|
||||
it('ASTCARD-TOUR-WAYS-001: a round found is a hike proposal’s card; one not found draws nothing', () => {
|
||||
const drawn = roundHikeCard(answer(proposal({ round: { key: 'a' } })));
|
||||
expect(drawn).toMatchObject({ kind: 'tourRoute', source: 'proposal', activity: 'hike', distanceM: 10_400 });
|
||||
expect(trekCardSchema.safeParse(drawn).success).toBe(true);
|
||||
expect(roundHikeCard(answer({ found: false, way: 'b', ways_found: 1, why: 'none_found' }))).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-WAYS-002: a leg’s way draws the hike as it runs now beneath it, and names a saved hike', () => {
|
||||
const value = proposal({
|
||||
leg_way: { key: 'b', leg: 1, ways_found: 2, tour_id: 61 },
|
||||
current: { distance_m: 9_800, ascent_m: 280, duration_minutes: 175 },
|
||||
current_geometry: LINE.slice(0, 3),
|
||||
});
|
||||
const drawn = legWayCard(answer(value));
|
||||
expect(drawn?.previous).toMatchObject({ distanceM: 9_800, ascentM: 280, minutes: 175 });
|
||||
expect(drawn?.previous?.line).toHaveLength(3);
|
||||
expect(drawn?.placeId).toBe(61);
|
||||
expect(trekCardSchema.safeParse(drawn).success).toBe(true);
|
||||
const unsaved = legWayCard(answer(proposal({ leg_way: { tour_id: null }, current: {} })));
|
||||
expect(unsaved).toMatchObject({ placeId: null, previous: null });
|
||||
expect(legWayCard(answer({ found: false }))).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-WAYS-003: the planning tools are always asked for their line, and the prompt names them', () => {
|
||||
for (const tool of ['propose_round_hike', 'propose_hike_leg_way', 'preview_wanderer_trail']) {
|
||||
expect(ASSISTANT_ARG_POLICY[tool]?.forced, tool).toEqual({ include_geometry: true });
|
||||
}
|
||||
expect(answerCardOf('propose_round_hike', answer(proposal()))?.kind).toBe('tourRoute');
|
||||
const prompt = CARD_PROMPT_LINES.join(' ');
|
||||
expect(prompt).toContain('propose_round_hike');
|
||||
expect(prompt).toContain('import_wanderer_trail');
|
||||
});
|
||||
});
|
||||
|
||||
const PREVIEW = {
|
||||
trail: {
|
||||
id: 'trail-1',
|
||||
name: 'Herzogstand',
|
||||
location: 'Kochel',
|
||||
difficulty: 'moderate',
|
||||
externalUrl: 'https://w.example/t/1',
|
||||
},
|
||||
distanceKm: 9.1,
|
||||
elevationGainM: 812,
|
||||
elevationLossM: 790,
|
||||
hasElevation: true,
|
||||
points: 900,
|
||||
line_geometry: [
|
||||
[47.6, 11.3],
|
||||
[47.62, 11.33],
|
||||
[47.65, 11.36],
|
||||
],
|
||||
contentHash: 'h'.repeat(32),
|
||||
state: 'new',
|
||||
snapshot: null,
|
||||
changes: [],
|
||||
};
|
||||
|
||||
describe('a wanderer trail', () => {
|
||||
it('ASTCARD-TOUR-WAYS-004: a trail previewed is a hike to take in: its line, length, climb and grade', () => {
|
||||
const drawn = wandererPreviewCard(answer(PREVIEW));
|
||||
expect(drawn).toMatchObject({
|
||||
source: 'proposal',
|
||||
activity: 'hike',
|
||||
placeId: null,
|
||||
name: 'Herzogstand',
|
||||
distanceM: 9100,
|
||||
ascentM: 812,
|
||||
descentM: 790,
|
||||
limit: 2,
|
||||
routed: true,
|
||||
});
|
||||
expect(drawn?.stops.map((stop) => stop.role)).toEqual(['start', 'end']);
|
||||
expect(drawn?.stops[0]?.name).toBe('Kochel');
|
||||
expect(trekCardSchema.safeParse(drawn).success).toBe(true);
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-WAYS-005: one already in the trip as it is reads as that saved tour; a loop has one stop', () => {
|
||||
const kept = wandererPreviewCard(answer({ ...PREVIEW, state: 'unchanged', snapshot: { placeId: 61 } }));
|
||||
expect(kept).toMatchObject({ source: 'saved', placeId: 61 });
|
||||
const loop = wandererTrailCard(
|
||||
{
|
||||
...PREVIEW,
|
||||
trail: { name: 'Loop', difficulty: 'unknown' },
|
||||
line_geometry: [
|
||||
[47.6, 11.3],
|
||||
[47.62, 11.33],
|
||||
[47.6, 11.3],
|
||||
],
|
||||
},
|
||||
'pending',
|
||||
);
|
||||
expect(loop).toMatchObject({ source: 'pending', placeId: null, limit: null });
|
||||
expect(loop?.stops).toHaveLength(1);
|
||||
expect(wandererPreviewCard(answer({ ...PREVIEW, line_geometry: [] }))).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-WAYS-006: a held import reads the trail again and shows it waiting, named and graded', async () => {
|
||||
const read = vi.fn(async () => PREVIEW) as unknown as CardReader;
|
||||
const loaded = await IMPORT_WANDERER_TRAIL.load?.({ trailId: 'trail-1', contentHash: 'x' }, read);
|
||||
expect(read).toHaveBeenCalledWith('preview_wanderer_trail', { trailId: 'trail-1', include_geometry: true });
|
||||
const described = IMPORT_WANDERER_TRAIL.describe?.(ctx, { trailId: 'trail-1' }, loaded ?? null);
|
||||
expect(described?.subject).toBe('Herzogstand');
|
||||
expect(described?.rows.rows.map((row) => [row.labelKey, row.after])).toEqual([
|
||||
['location', 'Kochel'],
|
||||
['difficulty', 'T2'],
|
||||
['link', 'https://w.example/t/1'],
|
||||
]);
|
||||
expect(IMPORT_WANDERER_TRAIL.change?.(ctx, {}, loaded ?? null)).toMatchObject({ source: 'pending' });
|
||||
expect(IMPORT_WANDERER_TRAIL.change?.(ctx, {}, null)).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-WAYS-007: an import without a trail looks nothing up and is named by the trail asked for', async () => {
|
||||
const read = vi.fn() as unknown as CardReader;
|
||||
expect(await IMPORT_WANDERER_TRAIL.load?.({}, read)).toBeNull();
|
||||
expect(read).not.toHaveBeenCalled();
|
||||
expect(IMPORT_WANDERER_TRAIL.describe?.(ctx, { trailId: 'trail-9' }, null).subject).toBe('trail-9');
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-WAYS-008: an import is a tour added, taken back by deleting the tour it made', () => {
|
||||
expect(ASSISTANT_WRITE_TOOLS.import_wanderer_trail).toEqual({ verbKey: 'importTour', entity: 'tour' });
|
||||
expect(ASSISTANT_UNDO_MAP.import_wanderer_trail?.args({}, { tour: { place_id: 72 } }, null)).toEqual({
|
||||
placeId: 72,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* The pure halves of the round hikes and the ways of a leg the assistant
|
||||
* proposes: which way a call asks for, the points a found way runs through,
|
||||
* and the keys a search is kept under.
|
||||
*/
|
||||
import {
|
||||
legEndsOf,
|
||||
legWaysKey,
|
||||
percentOf,
|
||||
pinnedPointsOf,
|
||||
roadOf,
|
||||
roundPointsOf,
|
||||
roundSearchKey,
|
||||
rulesOf,
|
||||
wayIndexOf,
|
||||
wayKeyAt,
|
||||
wayMissing,
|
||||
} from '../../../src/nest/tours/hike-ways.helpers';
|
||||
import { HIKE_MAX_WAYPOINTS, TOURS_MAX_HIKING_DIFFICULTY } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
// HIKE-WAYS-HELP-001 to HIKE-WAYS-HELP-006
|
||||
|
||||
const A = { lat: 47.5, lng: 11.1, name: 'Car park' };
|
||||
const B = { lat: 47.52, lng: 11.14 };
|
||||
const C = { lat: 47.55, lng: 11.2, name: 'Hut' };
|
||||
|
||||
describe('the ways a call asks for', () => {
|
||||
it('HIKE-WAYS-HELP-001: a, b and c are the first, second and third way; a when left out', () => {
|
||||
expect([wayIndexOf(undefined), wayIndexOf('a'), wayIndexOf('b'), wayIndexOf('c')]).toEqual([0, 0, 1, 2]);
|
||||
expect([wayKeyAt(0), wayKeyAt(2), wayKeyAt(7)]).toEqual(['a', 'c', 'a']);
|
||||
expect(wayMissing('b', 1, null)).toEqual({ found: false, way: 'b', ways_found: 1, why: 'none_found' });
|
||||
expect(wayMissing(undefined, 0, 'no_valhalla')).toEqual({
|
||||
found: false,
|
||||
way: 'a',
|
||||
ways_found: 0,
|
||||
why: 'no_valhalla',
|
||||
});
|
||||
});
|
||||
|
||||
it('HIKE-WAYS-HELP-002: the rules default to the hike’s limit and no preferences; shares read as whole percent', () => {
|
||||
expect(rulesOf({})).toEqual({ limit: TOURS_MAX_HIKING_DIFFICULTY, preferences: null });
|
||||
expect(rulesOf({ max_hiking_difficulty: 4 }).limit).toBe(4);
|
||||
expect([percentOf(0.084), percentOf(-0.05)]).toEqual([8, -5]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the keys a search is kept under', () => {
|
||||
it('HIKE-WAYS-HELP-003: one search per user, trip, start to about a metre, length and rules', () => {
|
||||
const round = { name: 'Round', start: A, distance_km: 10 };
|
||||
expect(roundSearchKey(1, 2, round)).toBe(roundSearchKey(1, 2, { ...round, name: 'Other', round: 'c' }));
|
||||
expect(roundSearchKey(1, 2, round)).toBe(roundSearchKey(1, 2, { ...round, start: { ...A, lat: 47.500001 } }));
|
||||
expect(roundSearchKey(1, 2, round)).not.toBe(roundSearchKey(3, 2, round));
|
||||
expect(roundSearchKey(1, 2, round)).not.toBe(roundSearchKey(1, 2, { ...round, distance_km: 12 }));
|
||||
expect(roundSearchKey(1, 2, round)).not.toBe(roundSearchKey(1, 2, { ...round, max_hiking_difficulty: 4 }));
|
||||
const leg = { name: 'Hike', waypoints: [A, B, C], leg: 1 };
|
||||
expect(legWaysKey(1, 2, leg)).toBe(legWaysKey(1, 2, { ...leg, way: 'b' }));
|
||||
expect(legWaysKey(1, 2, leg)).not.toBe(legWaysKey(1, 2, { ...leg, leg: 2 }));
|
||||
expect(legWaysKey(1, 2, leg)).not.toBe(legWaysKey(1, 2, { ...leg, round_trip: true }));
|
||||
});
|
||||
});
|
||||
|
||||
describe('the points of a way', () => {
|
||||
it('HIKE-WAYS-HELP-004: a round runs from its start through the spots its loop was steered through, and back', () => {
|
||||
expect(roundPointsOf(A, [B, { lat: 47.6, lng: 11.3 }])).toEqual({
|
||||
waypoints: [A, { lat: B.lat, lng: B.lng }, { lat: 47.6, lng: 11.3 }],
|
||||
round_trip: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('HIKE-WAYS-HELP-005: a leg runs between its two points, the way back of a round trip to its start', () => {
|
||||
expect(legEndsOf([A, B, C], false, 1)).toEqual({
|
||||
from: { lat: A.lat, lng: A.lng },
|
||||
to: { lat: B.lat, lng: B.lng },
|
||||
});
|
||||
expect(legEndsOf([A, B, C], true, 3)).toEqual({ from: { lat: C.lat, lng: C.lng }, to: { lat: A.lat, lng: A.lng } });
|
||||
expect(legEndsOf([A, B, C], false, 3)).toBeNull();
|
||||
});
|
||||
|
||||
it('HIKE-WAYS-HELP-006: the pins of a leg go right after its first point, those of the way back last', () => {
|
||||
const pin = { lat: 47.51, lng: 11.12 };
|
||||
expect(pinnedPointsOf([A, B, C], 1, [pin])).toEqual([A, pin, B, C]);
|
||||
expect(pinnedPointsOf([A, B, C], 2, [pin])).toEqual([A, B, pin, C]);
|
||||
expect(pinnedPointsOf([A, B, C], 3, [pin])).toEqual([A, B, C, pin]);
|
||||
const full = Array.from({ length: HIKE_MAX_WAYPOINTS }, (_, index) => ({ lat: 47 + index / 100, lng: 11 }));
|
||||
expect(pinnedPointsOf(full, 1, [pin])).toBeNull();
|
||||
expect(roadOf([[47, 11]])).toEqual({ coordinates: [[47, 11]], distance: 0, duration: 0 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,233 @@
|
||||
/**
|
||||
* HikeWaysMcp and HikeWaysService: the planner's round hikes of a wished
|
||||
* length and its other ways for one leg, over MCP. The search is the shared
|
||||
* one, asked of a stubbed RoadtripRouterService that walks straight between
|
||||
* the points it is given; each way found is proposed through a stub of
|
||||
* HikePlanService.propose (its own suite plans the hike). The trip and a
|
||||
* saved hike are seeded through the ORM factories over a snapshot test db.
|
||||
*/
|
||||
import type { McpContext } from '../../../src/nest-mcp';
|
||||
import { RoadtripRouterService, RouteRefusal } from '../../../src/nest/roadtrip/roadtrip-router.service';
|
||||
import { HikePlanService } from '../../../src/nest/tours/hike-plan.service';
|
||||
import { HikeWaysMcp } from '../../../src/nest/tours/hike-ways.mcp';
|
||||
import { ToursModule } from '../../../src/nest/tours/tours.module';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { makePlace } from '../../helpers/factories/places';
|
||||
import { makeTour } from '../../helpers/factories/tours';
|
||||
import { makeTrip } from '../../helpers/factories/trips';
|
||||
import { makeUser } from '../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createTestModule, type TestModule } from '../../helpers/test-module';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import type { HikeProposeRequest } from '@trek/shared';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// HIKE-WAYS-MCP-001 to HIKE-WAYS-MCP-008
|
||||
|
||||
type Spot = { lat: number; lng: number };
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
const route = vi.fn<RoadtripRouterService['route']>();
|
||||
const alternatesOnFoot = vi.fn<RoadtripRouterService['alternatesOnFoot']>();
|
||||
const propose = vi.fn<HikePlanService['propose']>();
|
||||
let t: TestModule;
|
||||
let mcp: HikeWaysMcp;
|
||||
const orm = () => t.get(MikroORM);
|
||||
|
||||
/** The router's answer for points walked straight between, each met where it was asked. */
|
||||
function straight(points: Spot[]) {
|
||||
return {
|
||||
leg: {
|
||||
line: points.map(({ lat, lng }): [number, number] => [lat, lng]),
|
||||
seg: { distance: 0, duration: 0 },
|
||||
},
|
||||
parts: points.slice(1).map(() => ({ distance: 0, duration: 0 })),
|
||||
snapped: points.map(({ lat, lng }) => ({ asked: [lat, lng], at: [lat, lng], meters: 0 })),
|
||||
avoidMissed: [],
|
||||
} as unknown as Awaited<ReturnType<RoadtripRouterService['route']>>;
|
||||
}
|
||||
|
||||
/** The stub's proposal: the request's points given back, a length and a line. */
|
||||
async function proposal(_userId: number, _tripId: number, request: HikeProposeRequest) {
|
||||
return {
|
||||
name: request.name,
|
||||
variant_label: request.variant_label ?? null,
|
||||
route: { planned: true },
|
||||
distance_m: 10_400,
|
||||
ascent_m: 420,
|
||||
duration_minutes: 190,
|
||||
waypoints: request.waypoints,
|
||||
round_trip: request.round_trip ?? false,
|
||||
line_geometry: request.waypoints.map(({ lat, lng }): [number, number] => [lat, lng]),
|
||||
} as unknown as Awaited<ReturnType<HikePlanService['propose']>>;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({
|
||||
db,
|
||||
imports: [ToursModule],
|
||||
overrides: [
|
||||
{ provide: RoadtripRouterService, useValue: { route, alternatesOnFoot } },
|
||||
{ provide: HikePlanService, useValue: { propose } },
|
||||
],
|
||||
});
|
||||
mcp = t.get(HikeWaysMcp);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(db);
|
||||
route.mockReset().mockImplementation(async (_u, _t, _d, points) => straight(points));
|
||||
alternatesOnFoot.mockReset();
|
||||
propose.mockReset().mockImplementation(proposal);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
const ctx = (userId: number) => ({ userId }) as McpContext;
|
||||
|
||||
/** The JSON a tool answered, or the error text it refused with. */
|
||||
function read(result: { content: Array<{ type: string; text: string }>; isError?: boolean }) {
|
||||
const text = result.content[0]?.text ?? '';
|
||||
return result.isError ? { error: text } : JSON.parse(text);
|
||||
}
|
||||
|
||||
async function tripOf() {
|
||||
const { user } = await makeUser(orm());
|
||||
const trip = await makeTrip(orm(), user.id);
|
||||
return { userId: user.id, tripId: trip.id };
|
||||
}
|
||||
|
||||
const START = { lat: 47.5, lng: 11.1, name: 'Car park' };
|
||||
|
||||
describe('propose_round_hike', () => {
|
||||
it('HIKE-WAYS-MCP-001: proposes the round asked for as a hike back to its start, with the points to create it', async () => {
|
||||
const { userId, tripId } = await tripOf();
|
||||
const answer = read(
|
||||
await mcp.proposeRoundHike({ tripId, name: 'Round', start: START, distance_km: 10, round: 'b' }, ctx(userId)),
|
||||
);
|
||||
expect(answer.found).toBe(true);
|
||||
expect(answer.round).toMatchObject({ key: 'b', target_m: 10_000, deviation_pct: 4, rounds_found: 3 });
|
||||
expect(answer.create_with.round_trip).toBe(true);
|
||||
expect(answer.create_with.waypoints).toHaveLength(4);
|
||||
expect(answer.create_with.waypoints[0]).toEqual(START);
|
||||
const [, , asked] = propose.mock.calls[0] ?? [];
|
||||
expect(asked).toMatchObject({ name: 'Round', round_trip: true, along: false });
|
||||
// Every loop was asked on foot under the hike's own costing, out of the start and back.
|
||||
for (const [, , , points, profile, , options] of route.mock.calls) {
|
||||
expect(points[0]).toEqual({ lat: START.lat, lng: START.lng });
|
||||
expect(points.at(-1)).toEqual({ lat: START.lat, lng: START.lng });
|
||||
expect(profile).toBe('walking');
|
||||
expect(options?.costingOptions).toMatchObject({ max_hiking_difficulty: 2 });
|
||||
}
|
||||
});
|
||||
|
||||
it('HIKE-WAYS-MCP-002: the rounds of one search are asked for one after another without asking the router again', async () => {
|
||||
const { userId, tripId } = await tripOf();
|
||||
const request = { tripId, name: 'Round', start: START, distance_km: 10 };
|
||||
await mcp.proposeRoundHike({ ...request, round: 'a' }, ctx(userId));
|
||||
const asked = route.mock.calls.length;
|
||||
const c = read(await mcp.proposeRoundHike({ ...request, round: 'c' }, ctx(userId)));
|
||||
expect(c.round.key).toBe('c');
|
||||
expect(route.mock.calls.length).toBe(asked);
|
||||
});
|
||||
|
||||
it('HIKE-WAYS-MCP-003: a router that never answers, or no Valhalla, finds no round and says why', async () => {
|
||||
const { userId, tripId } = await tripOf();
|
||||
route.mockRejectedValue(new Error('down'));
|
||||
const down = read(await mcp.proposeRoundHike({ tripId, name: 'R', start: START, distance_km: 8 }, ctx(userId)));
|
||||
expect(down).toEqual({ found: false, way: 'a', ways_found: 0, why: 'router_unavailable' });
|
||||
route.mockReset().mockRejectedValue(new RouteRefusal('no_valhalla', 'none'));
|
||||
const none = read(await mcp.proposeRoundHike({ tripId, name: 'R', start: START, distance_km: 9 }, ctx(userId)));
|
||||
expect(none.why).toBe('no_valhalla');
|
||||
// Without a Valhalla the search stops at its first question.
|
||||
expect(route).toHaveBeenCalledTimes(1);
|
||||
expect(propose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('HIKE-WAYS-MCP-004: a trip the caller cannot see is not found', async () => {
|
||||
const { tripId } = await tripOf();
|
||||
const { user: stranger } = await makeUser(orm());
|
||||
const answer = read(
|
||||
await mcp.proposeRoundHike({ tripId, name: 'R', start: START, distance_km: 8 }, ctx(stranger.id)),
|
||||
);
|
||||
expect(answer.error).toBeDefined();
|
||||
expect(route).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
const A = { lat: 47.5, lng: 11.1, name: 'Car park' };
|
||||
const B = { lat: 47.52, lng: 11.1, name: 'Hut' };
|
||||
const OWN: Array<[number, number]> = [
|
||||
[47.5, 11.1],
|
||||
[47.52, 11.1],
|
||||
];
|
||||
const OTHER: Array<[number, number]> = [
|
||||
[47.5, 11.1],
|
||||
[47.51, 11.12],
|
||||
[47.52, 11.1],
|
||||
];
|
||||
|
||||
describe('propose_hike_leg_way', () => {
|
||||
it('HIKE-WAYS-MCP-005: the other way of a leg is the whole hike with the way held by a pin, beside the hike as it runs', async () => {
|
||||
const { userId, tripId } = await tripOf();
|
||||
alternatesOnFoot.mockResolvedValue([OWN, OTHER]);
|
||||
const answer = read(
|
||||
await mcp.proposeHikeLegWay(
|
||||
{ tripId, name: 'Hike', waypoints: [A, B], leg: 1, include_geometry: true },
|
||||
ctx(userId),
|
||||
),
|
||||
);
|
||||
expect(answer.found).toBe(true);
|
||||
expect(answer.leg_way).toEqual({ key: 'a', leg: 1, ways_found: 1, tour_id: null });
|
||||
expect(answer.create_with).toEqual({ waypoints: [A, { lat: 47.51, lng: 11.12 }, B], round_trip: false });
|
||||
expect(answer.current).toEqual({ distance_m: 10_400, ascent_m: 420, duration_minutes: 190 });
|
||||
expect(answer.current_geometry).toHaveLength(2);
|
||||
const [, from, to, costing, count] = alternatesOnFoot.mock.calls[0] ?? [];
|
||||
expect([from, to, count]).toEqual([{ lat: A.lat, lng: A.lng }, { lat: B.lat, lng: B.lng }, 3]);
|
||||
expect(costing).toMatchObject({ max_hiking_difficulty: 2 });
|
||||
});
|
||||
|
||||
it('HIKE-WAYS-MCP-006: a router that knows only its own way, or a way it does not keep to, offers none', async () => {
|
||||
const { userId, tripId } = await tripOf();
|
||||
alternatesOnFoot.mockResolvedValue([OWN, OWN]);
|
||||
const same = read(await mcp.proposeHikeLegWay({ tripId, name: 'H', waypoints: [A, B], leg: 1 }, ctx(userId)));
|
||||
expect(same).toEqual({ found: false, way: 'a', ways_found: 0, why: 'none_found' });
|
||||
alternatesOnFoot.mockResolvedValue([OWN, OTHER]);
|
||||
route.mockRejectedValue(new Error('down'));
|
||||
const held = read(
|
||||
await mcp.proposeHikeLegWay(
|
||||
{ tripId, name: 'H', waypoints: [A, B], leg: 1, max_hiking_difficulty: 3 },
|
||||
ctx(userId),
|
||||
),
|
||||
);
|
||||
expect(held.found).toBe(false);
|
||||
alternatesOnFoot.mockRejectedValue(new RouteRefusal('no_way', 'none'));
|
||||
const none = read(
|
||||
await mcp.proposeHikeLegWay(
|
||||
{ tripId, name: 'H', waypoints: [A, B], leg: 1, max_hiking_difficulty: 4 },
|
||||
ctx(userId),
|
||||
),
|
||||
);
|
||||
expect(none.why).toBe('no_way');
|
||||
});
|
||||
|
||||
it('HIKE-WAYS-MCP-007: a leg the hike does not have is refused', async () => {
|
||||
const { userId, tripId } = await tripOf();
|
||||
const answer = read(await mcp.proposeHikeLegWay({ tripId, name: 'H', waypoints: [A, B], leg: 2 }, ctx(userId)));
|
||||
expect(answer.error).toContain('no such leg');
|
||||
expect(alternatesOnFoot).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('HIKE-WAYS-MCP-008: the way of a saved hike names that hike', async () => {
|
||||
const { userId, tripId } = await tripOf();
|
||||
const place = await makePlace(orm(), tripId, { name: 'Saved hike', lat: A.lat, lng: A.lng });
|
||||
await makeTour(orm(), place.id);
|
||||
alternatesOnFoot.mockResolvedValue([OWN, OTHER]);
|
||||
const answer = read(
|
||||
await mcp.proposeHikeLegWay({ tripId, name: 'H', waypoints: [A, B], leg: 1, tour_id: place.id }, ctx(userId)),
|
||||
);
|
||||
expect(answer.leg_way.tour_id).toBe(place.id);
|
||||
});
|
||||
});
|
||||
@@ -588,3 +588,89 @@ describe('server Roadtrip router, a hike: its costing, heights and ways', () =>
|
||||
await expect(setup().router.wayIds(1, line(3))).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('server Roadtrip router: other ways on foot (RTE-02)', () => {
|
||||
const trip = (points: Array<[number, number]>) => ({
|
||||
legs: [{ shape: valhallaPolyline(points), summary: { length: 1.2, time: 900 } }],
|
||||
});
|
||||
|
||||
it('ROUTER-WAYS-001: asks Valhalla once on foot under the hike’s costing, its own way first', async () => {
|
||||
vi.mocked(safeFetchAdminConfigured).mockResolvedValueOnce(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
trip: trip([
|
||||
[47, 11],
|
||||
[47.01, 11.01],
|
||||
]),
|
||||
alternates: [
|
||||
{
|
||||
trip: trip([
|
||||
[47, 11],
|
||||
[47.02, 11],
|
||||
[47.01, 11.01],
|
||||
]),
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
);
|
||||
const { router } = setup({ valhalla_base_url: 'https://valhalla.internal/' });
|
||||
const ways = await router.alternatesOnFoot(
|
||||
1,
|
||||
{ lat: 47, lng: 11 },
|
||||
{ lat: 47.01, lng: 11.01 },
|
||||
{ max_hiking_difficulty: 3 },
|
||||
3,
|
||||
);
|
||||
expect(ways).toEqual([
|
||||
[
|
||||
[47, 11],
|
||||
[47.01, 11.01],
|
||||
],
|
||||
[
|
||||
[47, 11],
|
||||
[47.02, 11],
|
||||
[47.01, 11.01],
|
||||
],
|
||||
]);
|
||||
const [url, init] = vi.mocked(safeFetchAdminConfigured).mock.calls[0] ?? [];
|
||||
expect(url).toBe('https://valhalla.internal/route');
|
||||
expect(JSON.parse(String((init as RequestInit).body))).toMatchObject({
|
||||
costing: 'pedestrian',
|
||||
costing_options: { pedestrian: { max_hiking_difficulty: 3 } },
|
||||
alternates: 3,
|
||||
locations: [
|
||||
{ lat: 47, lon: 11 },
|
||||
{ lat: 47.01, lon: 11.01 },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('ROUTER-WAYS-002: an answer without alternates is the one way; no Valhalla refuses before asking', async () => {
|
||||
vi.mocked(safeFetchAdminConfigured).mockResolvedValueOnce(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
trip: trip([
|
||||
[47, 11],
|
||||
[47.01, 11.01],
|
||||
]),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const ways = await setup().router.alternatesOnFoot(1, { lat: 47, lng: 11 }, { lat: 47.01, lng: 11.01 }, {}, 0);
|
||||
expect(ways).toHaveLength(1);
|
||||
const body = JSON.parse(String((vi.mocked(safeFetchAdminConfigured).mock.calls[0]?.[1] as RequestInit).body));
|
||||
expect(body.alternates).toBeUndefined();
|
||||
vi.mocked(safeFetchAdminConfigured).mockClear();
|
||||
await expect(
|
||||
setup({ routing_base_url: 'http://router.internal' }).router.alternatesOnFoot(
|
||||
1,
|
||||
{ lat: 47, lng: 11 },
|
||||
{ lat: 47.01, lng: 11.01 },
|
||||
{},
|
||||
3,
|
||||
),
|
||||
).rejects.toMatchObject({ why: 'no_valhalla' });
|
||||
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* ToursWandererMcp: the trip-side wanderer routes over MCP. Each tool checks
|
||||
* trip access and 'place_edit' as the REST guards do, then hands the same
|
||||
* values to ToursWandererService, a stub in this suite (its own suite reads
|
||||
* a stubbed instance); the trip and its members are seeded through the ORM
|
||||
* factories over a snapshot test db.
|
||||
*/
|
||||
import { TripMembers } from '../../../src/db/entities/TripMembers.entity';
|
||||
import type { McpContext } from '../../../src/nest-mcp';
|
||||
import { getEntry, type ClassRef } from '../../../src/nest-mcp/metadata';
|
||||
import { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import { McpToolGuardsService } from '../../../src/nest/mcp-shared/mcp-tool-guards.service';
|
||||
import { ToursWandererMcp } from '../../../src/nest/tours/tours-wanderer.mcp';
|
||||
import { ToursWandererService } from '../../../src/nest/tours/tours-wanderer.service';
|
||||
import { ToursModule } from '../../../src/nest/tours/tours.module';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { insertRow } from '../../helpers/factories/rows';
|
||||
import { makeTrip } from '../../helpers/factories/trips';
|
||||
import { makeUser } from '../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createTestModule, type TestModule } from '../../helpers/test-module';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// WANDERER-MCP-001 to WANDERER-MCP-006
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
const search = vi.fn<ToursWandererService['search']>();
|
||||
const preview = vi.fn<ToursWandererService['preview']>();
|
||||
const importTrail = vi.fn<ToursWandererService['import']>();
|
||||
const checkSource = vi.fn<ToursWandererService['checkSource']>();
|
||||
const hasTripPermission = vi.fn<McpToolGuardsService['hasTripPermission']>();
|
||||
const isWandererAvailable = vi.fn<AddonsService['isWandererAvailable']>();
|
||||
let t: TestModule;
|
||||
let mcp: ToursWandererMcp;
|
||||
const orm = () => t.get(MikroORM);
|
||||
|
||||
const TRAIL = {
|
||||
id: 'trail-1',
|
||||
name: 'Herzogstand',
|
||||
description: null,
|
||||
location: 'Kochel',
|
||||
distanceM: 9000,
|
||||
durationS: 14_400,
|
||||
elevationGainM: 800,
|
||||
elevationLossM: 800,
|
||||
difficulty: 'moderate' as const,
|
||||
public: true,
|
||||
author: null,
|
||||
line: [
|
||||
[47.6, 11.3],
|
||||
[47.62, 11.33],
|
||||
] as Array<[number, number]>,
|
||||
externalUrl: 'https://wanderer.example/trails/trail-1',
|
||||
importedAs: [],
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({
|
||||
db,
|
||||
imports: [ToursModule],
|
||||
overrides: [
|
||||
{ provide: ToursWandererService, useValue: { search, preview, import: importTrail, checkSource } },
|
||||
{ provide: McpToolGuardsService, useValue: { hasTripPermission } },
|
||||
],
|
||||
});
|
||||
mcp = t.get(ToursWandererMcp);
|
||||
vi.spyOn(t.get(AddonsService), 'isWandererAvailable').mockImplementation(isWandererAvailable);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(db);
|
||||
hasTripPermission.mockReset().mockResolvedValue(true);
|
||||
isWandererAvailable.mockReset().mockResolvedValue(true);
|
||||
search.mockReset().mockResolvedValue({ trails: [TRAIL], total: 1, page: 1, pageSize: 20 });
|
||||
preview.mockReset().mockResolvedValue({
|
||||
trail: TRAIL,
|
||||
distanceKm: 9.1,
|
||||
elevationGainM: 812,
|
||||
elevationLossM: 812,
|
||||
hasElevation: true,
|
||||
points: 900,
|
||||
line: TRAIL.line,
|
||||
contentHash: 'h'.repeat(32),
|
||||
state: 'new',
|
||||
snapshot: null,
|
||||
changes: [],
|
||||
});
|
||||
importTrail.mockReset();
|
||||
checkSource.mockReset();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
const ctx = (userId: number) => ({ userId }) as McpContext;
|
||||
|
||||
function read(result: { content: Array<{ type: string; text: string }>; isError?: boolean }) {
|
||||
const text = result.content[0]?.text ?? '';
|
||||
return result.isError ? { error: text } : JSON.parse(text);
|
||||
}
|
||||
|
||||
async function tripOf() {
|
||||
const { user } = await makeUser(orm());
|
||||
const trip = await makeTrip(orm(), user.id);
|
||||
return { userId: user.id, tripId: trip.id };
|
||||
}
|
||||
|
||||
describe('wanderer over MCP', () => {
|
||||
it('WANDERER-MCP-001: a search hands its words on and answers the trails without their lines', async () => {
|
||||
const { userId, tripId } = await tripOf();
|
||||
const answer = read(await mcp.searchTrails({ tripId, q: 'Herzogstand' }, ctx(userId)));
|
||||
expect(search).toHaveBeenCalledWith(String(tripId), userId, { q: 'Herzogstand', page: 1, bbox: undefined });
|
||||
expect(answer.trails[0]).toMatchObject({ id: 'trail-1', name: 'Herzogstand' });
|
||||
expect(answer.trails[0].line).toBeUndefined();
|
||||
expect(hasTripPermission).toHaveBeenCalledWith('place_edit', tripId, userId);
|
||||
});
|
||||
|
||||
it('WANDERER-MCP-002: a preview answers its line for drawing only when asked, as line_geometry', async () => {
|
||||
const { userId, tripId } = await tripOf();
|
||||
const plain = read(await mcp.previewTrail({ tripId, trailId: 'trail-1' }, ctx(userId)));
|
||||
expect(plain.line).toBeUndefined();
|
||||
expect(plain.line_geometry).toBeUndefined();
|
||||
expect(plain.trail.line).toBeUndefined();
|
||||
expect(plain.contentHash).toBe('h'.repeat(32));
|
||||
const drawn = read(await mcp.previewTrail({ tripId, trailId: 'trail-1', include_geometry: true }, ctx(userId)));
|
||||
expect(drawn.line_geometry).toEqual(TRAIL.line);
|
||||
});
|
||||
|
||||
it('WANDERER-MCP-003: the import and the source check run through the service with the caller’s rights', async () => {
|
||||
const { userId, tripId } = await tripOf();
|
||||
importTrail.mockResolvedValue({ tour: { place_id: 9 } } as never);
|
||||
const imported = read(
|
||||
await mcp.importTrail({ tripId, trailId: 'trail-1', contentHash: 'h'.repeat(32) }, ctx(userId)),
|
||||
);
|
||||
expect(imported.tour.place_id).toBe(9);
|
||||
expect(importTrail).toHaveBeenCalledWith(String(tripId), userId, {
|
||||
trailId: 'trail-1',
|
||||
contentHash: 'h'.repeat(32),
|
||||
});
|
||||
checkSource.mockResolvedValue({
|
||||
state: 'unchanged',
|
||||
changes: [],
|
||||
externalUpdated: null,
|
||||
importedUpdated: null,
|
||||
editedLocally: false,
|
||||
reimport: null,
|
||||
});
|
||||
const checked = read(await mcp.checkSource({ tripId, placeId: 9 }, ctx(userId)));
|
||||
expect(checked.state).toBe('unchanged');
|
||||
expect(checkSource).toHaveBeenCalledWith(String(tripId), userId, '9');
|
||||
});
|
||||
|
||||
it('WANDERER-MCP-004: without place editing permission nothing is read or written', async () => {
|
||||
const { userId, tripId } = await tripOf();
|
||||
hasTripPermission.mockResolvedValue(false);
|
||||
expect(read(await mcp.searchTrails({ tripId }, ctx(userId))).error).toBeDefined();
|
||||
expect(
|
||||
read(await mcp.importTrail({ tripId, trailId: 'x', contentHash: 'h'.repeat(32) }, ctx(userId))).error,
|
||||
).toBeDefined();
|
||||
expect(search).not.toHaveBeenCalled();
|
||||
expect(importTrail).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('WANDERER-MCP-005: a trip the caller cannot see is not found', async () => {
|
||||
const { tripId } = await tripOf();
|
||||
const { user: stranger } = await makeUser(orm());
|
||||
expect(read(await mcp.previewTrail({ tripId, trailId: 'trail-1' }, ctx(stranger.id))).error).toBeDefined();
|
||||
expect(preview).not.toHaveBeenCalled();
|
||||
// A member who may not edit places is refused as well.
|
||||
await insertRow(orm(), TripMembers, { trip: tripId, user: stranger.id });
|
||||
hasTripPermission.mockResolvedValue(false);
|
||||
expect(read(await mcp.previewTrail({ tripId, trailId: 'trail-1' }, ctx(stranger.id))).error).toBeDefined();
|
||||
expect(preview).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('WANDERER-MCP-006: the tools are offered only while wanderer is allowed under Tours', async () => {
|
||||
const methods = ['searchTrails', 'previewTrail', 'importTrail', 'checkSource'];
|
||||
const options = methods.map((method) => {
|
||||
const entry = getEntry(ToursWandererMcp as unknown as ClassRef, method);
|
||||
if (!entry || entry.kind !== 'tool') throw new Error(`${method} is no MCP tool`);
|
||||
return entry.options;
|
||||
});
|
||||
expect(options.map((tool) => [tool.name, tool.annotations?.readOnlyHint, tool.access])).toEqual([
|
||||
['search_wanderer_trails', true, { group: 'trips', mode: 'read' }],
|
||||
['preview_wanderer_trail', true, { group: 'trips', mode: 'read' }],
|
||||
['import_wanderer_trail', false, { group: 'trips', mode: 'write' }],
|
||||
['check_tour_source', true, { group: 'trips', mode: 'read' }],
|
||||
]);
|
||||
const gate = options[0]?.when;
|
||||
expect(await gate?.(ctx(1), mcp)).toBe(true);
|
||||
isWandererAvailable.mockResolvedValue(false);
|
||||
expect(await gate?.(ctx(1), mcp)).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user