feat(assistant): plan and save every tour type, bike tours, runs, paddle and ski tours included

The assistant can now plan and save every type the Tours tab plans. A bike
tour or a run is proposed and created through the hike's own plan and save
(propose_tour, create_tour), routed on the server with the costing of its
profile, now kept once in shared and read by the planner as well. A paddle
or ski tour planned with plan_paddle_route or plan_ski_route is saved with
create_paddle_tour or create_ski_tour, and "Plan this" takes those plans,
bike tours and runs too. Every create has its card and its way back.
This commit is contained in:
Maurice
2026-10-23 18:59:37 +02:00
parent 79fb71bc92
commit 6e43490ba0
79 changed files with 3664 additions and 168 deletions
@@ -244,7 +244,7 @@ function lookOf(
const centre = area ? nearbyName(card, (area.south + area.north) / 2, (area.west + area.east) / 2) : null;
return { label: centre, area };
}
if (toolName === 'propose_hike') return hikeLook(args);
if (toolName === 'propose_hike' || toolName === 'propose_tour') return hikeLook(args);
if (toolName === 'search_place') {
const bias = recordOf(args.locationBias);
const area = pointArea(bias.lat, bias.lng, bias.radius, BIAS_RADIUS_M);
+11 -1
View File
@@ -93,10 +93,20 @@ function foundPlaceOutcome(part: ToolCallPart): string {
return `The user picked ${place} from the search results for ${day}; it waits for them to add or discard it.`;
}
/** What a taken proposal created, by the tool it went through; a hike for any other. */
const TAKEN_WORDS: Readonly<Record<string, string>> = {
create_city_walk: 'city walk',
'create_tour:bike': 'bike tour',
'create_tour:run': 'run',
create_paddle_tour: 'paddle tour',
create_ski_tour: 'ski tour',
};
/** What became of a proposal the user took from an answer to add it to the trip, as its stored part says. */
function takenProposalOutcome(part: ToolCallPart): string {
const name = quoted(part.args.name);
const what = part.args.via === 'create_city_walk' ? 'city walk' : 'hike';
const via = part.args.via === 'create_tour' ? `create_tour:${String(part.args.activity)}` : String(part.args.via);
const what = TAKEN_WORDS[via] ?? 'hike';
if (part.approval?.approved === true) {
return part.isError ? `The ${what} ${name} could not be added.` : `The ${what} ${name} was added to the trip.`;
}
@@ -0,0 +1,132 @@
import { recordOf, type Row } from './cards/card-values';
import { haversineMetres } from '@trek/shared';
import { SUPPORTED_LANGUAGE_CODES } from '@trek/shared/i18n';
/**
* "Plan this" on a paddle or ski plan an answer showed (plan_paddle_route,
* plan_ski_route): the create it holds, from the plan's own arguments and
* its answer read again whole. The legs of a plan must run on from one to
* the next to be one tour; its points are the first leg's start and every
* leg's end. A paddle tour's water is read from the plan (a river where any
* stretch is on running water, else a lake), its name from the waters it
* runs on, a ski tour's from its ski areas; where neither names one, the
* tour type's own word in the user's language.
*/
/** The plans a tour can be taken from, and the create each one is saved through. */
export const SPORT_CREATES = {
plan_paddle_route: 'create_paddle_tour',
plan_ski_route: 'create_ski_tour',
} as const;
export type SportPlanTool = keyof typeof SPORT_CREATES;
/** Whether a tool is one of the plans a tour can be taken from. */
export function isSportPlan(toolName: string): toolName is SportPlanTool {
return Object.hasOwn(SPORT_CREATES, toolName);
}
/** How near one leg's end must lie to the next leg's start for the two to be one tour, in metres. */
const JOINED_M = 5;
/** The longest name a tour is given from its waters or areas, well inside a tour's name. */
const NAME_CHARS = 120;
/** A point as the plan names it, or null. */
function pointOf(value: unknown): { lat: number; lng: number } | null {
const point = recordOf(value);
return typeof point.lat === 'number' && typeof point.lng === 'number' ? { lat: point.lat, lng: point.lng } : null;
}
/** The points of a plan's legs, the first leg's start then every leg's end; null where the legs do not join. */
export function waypointsOfLegs(legs: unknown): Array<{ lat: number; lng: number }> | null {
const rows = Array.isArray(legs) ? legs.map(recordOf) : [];
const first = pointOf(rows[0]?.from);
if (!first) return null;
const points = [first];
for (const [index, leg] of rows.entries()) {
const from = pointOf(leg.from);
const to = pointOf(leg.to);
const before = points[index];
if (!from || !to || !before || haversineMetres(before.lat, before.lng, from.lat, from.lng) > JOINED_M) return null;
points.push(to);
}
return points.length >= 2 ? points : null;
}
/** Each planned leg of an answer; null where one failed, which takes the whole plan out of reach. */
function plannedLegs(result: Row): Row[] | null {
const legs = Array.isArray(result.legs) ? result.legs.map(recordOf) : [];
return legs.length > 0 && legs.every((leg) => leg.status === 'ok') ? legs : null;
}
/** "Isar → Ammersee": the first and last names given, each once, clipped. */
function namedAlong(names: readonly unknown[]): string {
const kept = names.flatMap((name) => (typeof name === 'string' && name.trim() !== '' ? [name.trim()] : []));
const ends = [...new Set([kept[0], kept.at(-1)])].filter((name): name is string => !!name);
const name = ends.join(' → ');
return name.length > NAME_CHARS ? `${name.slice(0, NAME_CHARS - 1)}…` : name;
}
/** The water a paddle plan runs on: a river where any stretch is on running water, else a lake. */
function waterOf(legs: readonly Row[]): 'river' | 'lake' {
const kinds = legs.flatMap((leg) => (Array.isArray(leg.segments) ? leg.segments.map((s) => recordOf(s).kind) : []));
return kinds.some((kind) => kind === 'water' || kind === 'rapids' || kind === 'pass') ? 'river' : 'lake';
}
/**
* The create a taken paddle or ski plan holds: its points, the plan's own
* settings and a name; null where a leg failed or the legs do not join.
*/
export function sportTakeArgsOf(toolName: SportPlanTool, args: Row, result: Row, fallbackName: string): Row | null {
const legs = plannedLegs(result);
const waypoints = waypointsOfLegs(args.legs);
if (!legs || !waypoints) return null;
const via = SPORT_CREATES[toolName];
if (via === 'create_paddle_tour') {
const waters = legs.flatMap((leg) =>
Array.isArray(leg.segments) ? leg.segments.map((s) => recordOf(s).name) : [],
);
const take: Row = { via, name: namedAlong(waters) || fallbackName, waypoints, water_context: waterOf(legs) };
if (args.boat !== undefined) take.boat_type = args.boat;
if (args.lake_style !== undefined) take.lake_style = args.lake_style;
if (args.lock_policy !== undefined) take.lock_policy = args.lock_policy;
return take;
}
const areas = Array.isArray(result.area_names) ? result.area_names : [];
const take: Row = { via, name: namedAlong(areas) || fallbackName, waypoints, discipline: args.discipline };
if (args.technique !== undefined && args.technique !== null) take.technique = args.technique;
if (args.options !== undefined) take.options = args.options;
return take;
}
/** The locale key each plan's tour type is named by. */
const TYPE_WORD_KEYS: Readonly<Record<SportPlanTool, string>> = {
plan_paddle_route: 'tourTypes.kayak',
plan_ski_route: 'tourTypes.ski',
};
/** The words of one locale's table, or none when it cannot be read. */
async function wordsOf(language: string): Promise<Record<string, unknown>> {
try {
// A supported code only, so the path is one of the package's own locale entries.
const loaded: unknown = await import(`@trek/shared/i18n/${language}`);
const words = (loaded as { default?: unknown } | null)?.default;
return words !== null && typeof words === 'object' ? (words as Record<string, unknown>) : {};
} catch {
return {};
}
}
/** A plan's tour type in the user's language ("Paddeltour"), English where the language has no table. */
export async function tourTypeWord(locale: string, toolName: SportPlanTool): Promise<string> {
const language = locale.split('-')[0] ?? 'en';
const code = SUPPORTED_LANGUAGE_CODES.includes(locale)
? locale
: SUPPORTED_LANGUAGE_CODES.includes(language)
? language
: 'en';
const key = TYPE_WORD_KEYS[toolName];
const own = (await wordsOf(code))[key];
if (typeof own === 'string') return own;
const english = (await wordsOf('en'))[key];
return typeof english === 'string' ? english : 'Tour';
}
@@ -22,13 +22,14 @@ 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 { isSportPlan, SPORT_CREATES, sportTakeArgsOf, tourTypeWord } from './assistant-proposal-sports';
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';
import { AssistantCardContext } from './cards/card-context';
import { recordOf, type Row } from './cards/card-values';
import { argText } from './cards/tour/tour-card-values';
import { cityWalkCard } from './cards/tour/tour-sport.cards';
import { cityWalkCard, paddleCard, skiCard } from './cards/tour/tour-sport.cards';
import { describeToolCall } from './tool-call-preview.helpers';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
@@ -49,8 +50,17 @@ import { randomUUID } from 'node:crypto';
*/
const WALK_READ = 'propose_city_walk';
/** What a taken proposal reads: the trip's days and places, the category names its card writes with, a walk again. */
const TRIP_READS: ReadonlySet<string> = new Set(['get_trip_summary', 'list_places', 'list_categories', WALK_READ]);
/**
* What a taken proposal reads: the trip's days and places, the category names
* its card writes with, a walk or a paddle or ski plan again.
*/
const TRIP_READS: ReadonlySet<string> = new Set([
'get_trip_summary',
'list_places',
'list_categories',
WALK_READ,
...Object.keys(SPORT_CREATES),
]);
/** Message rows searched for the proposal; the history a turn sends the provider. */
const SEARCHED_ROWS = 40;
@@ -69,9 +79,11 @@ 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_tour: 'create_tour',
propose_city_walk: 'create_city_walk',
...SPORT_CREATES,
};
const PROPOSING: ReadonlySet<string> = new Set(Object.keys(CREATES));
@@ -103,6 +115,26 @@ function walkName(stations: readonly Row[], result: Row): string {
return name.length > WALK_NAME_CHARS ? `${name.slice(0, WALK_NAME_CHARS - 1)}…` : name;
}
/**
* A paddle or ski plan asked again with the arguments it was planned with:
* the stored answer is the model's shortened copy, and its legs' stretches
* name the water or the areas the tour is called after. The card is drawn
* again from the whole answer (the stored one when none can be drawn). Null
* when the plan cannot be read now.
*/
async function planAgain(
read: (name: string, args: Row) => Promise<ToolRun>,
proposal: StoredProposal,
trip: TripCard,
today: string,
): Promise<StoredProposal | null> {
const run = await read(proposal.toolName, proposal.args);
if (!run.ok) return null;
const input = { toolCallId: '', args: proposal.args, value: run.value, card: trip, today };
const drawn = proposal.toolName === 'plan_ski_route' ? skiCard(input) : paddleCard(input);
return { ...proposal, result: recordOf(run.value), card: drawn ?? proposal.card };
}
/**
* A walk asked again with the arguments it was proposed with: the stations to
* create from the tool's own answer, and the card drawn from that answer (the
@@ -133,7 +165,7 @@ export function pendingCardOf(card: TourRouteCard, args: Row): TourRouteCard {
return { ...card, source: 'pending', name: argText(args.name, 120) ?? card.name, label: null, schedule };
}
/** The fields of a propose_hike create_hike takes as they are. */
/** The fields of a propose_hike create_hike takes as they are, and those of a propose_tour create_tour takes. */
const HIKE_FIELDS = [
'name',
'waypoints',
@@ -143,21 +175,42 @@ const HIKE_FIELDS = [
'day_id',
'start_time',
] as const;
const TOUR_FIELDS = [
'name',
'activity',
'bike_profile',
'run_profile',
'run_pace_seconds_per_km',
'waypoints',
'round_trip',
'day_id',
'start_time',
] as const;
/**
* The change a taken proposal holds: create_hike with the proposal's own
* arguments for a hike whose way was planned, create_city_walk with the
* The change a taken proposal holds: create_hike (create_tour for a bike
* tour or a run) with the proposal's own arguments for a way that was
* planned, create_paddle_tour or create_ski_tour with a plan's points and
* settings, create_city_walk with the
* stations it answered for a walk that can be created. Null for a proposal
* nothing can be created from.
*/
export function takeArgsOf(proposal: StoredProposal): Row | null {
export function takeArgsOf(proposal: StoredProposal, fallbackName = ''): Row | null {
const via = CREATES[proposal.toolName];
if (via === 'create_hike') {
if (via === 'create_hike' || via === 'create_tour') {
if (!proposal.card.routed) return null;
// A run is saved with the runner's pace only, as the planner saves one.
if (via === 'create_tour' && proposal.args.activity === 'run' && proposal.args.run_pace_seconds_per_km == null) {
return null;
}
const args: Row = { via };
for (const key of HIKE_FIELDS) if (proposal.args[key] !== undefined) args[key] = proposal.args[key];
for (const key of via === 'create_hike' ? HIKE_FIELDS : TOUR_FIELDS) {
if (proposal.args[key] !== undefined) args[key] = proposal.args[key];
}
return args;
}
if (isSportPlan(proposal.toolName))
return sportTakeArgsOf(proposal.toolName, proposal.args, proposal.result, fallbackName);
const stations = Array.isArray(proposal.result.stations_for_create) ? proposal.result.stations_for_create : [];
if (proposal.result.can_create === false || stations.length < 2) return null;
return { via, name: walkName(stations.map(recordOf), proposal.result), stations };
@@ -227,7 +280,8 @@ export class AssistantProposalsService {
const id = randomUUID();
const today = todayIn(req.timeZone, new Date());
const { card, categories, proposal } = await this.tripOf(userId, tripId, stored, today);
const args = proposal ? takeArgsOf(proposal) : null;
const fallback = isSportPlan(stored.toolName) ? await tourTypeWord(req.locale, stored.toolName) : '';
const args = proposal ? takeArgsOf(proposal, fallback) : null;
if (!proposal || !args) throw aiRefusal('generic', 'Nothing can be created from this proposal: ask for it again');
const ctx = this.cardContext.contextOf(card, categories, req.locale, today);
// The proposal it came from, so the thread tells which card was taken, whatever way it creates.
@@ -294,13 +348,24 @@ export class AssistantProposalsService {
return {
card,
categories: new Map(categories.map((category): [number, string] => [category.id, category.name])),
proposal: stored.toolName === WALK_READ ? await walkAgain(read, stored, card, today) : stored,
proposal: await this.again(read, stored, card, today),
};
} finally {
await session.close();
}
}
/** The proposal as it is taken: a walk or a paddle or ski plan asked again, a hike or tour as it was stored. */
private async again(
read: (name: string, args: Row) => Promise<ToolRun>,
stored: StoredProposal,
card: TripCard,
today: string,
): Promise<StoredProposal | null> {
if (stored.toolName === WALK_READ) return await walkAgain(read, stored, card, today);
return isSportPlan(stored.toolName) ? await planAgain(read, stored, card, today) : stored;
}
/** The newest answer of the thread as the client shows it, with what became of its changes. */
private async answerOf(threadId: number): Promise<AssistantMessage> {
const rows = await this.messages.listLatest(threadId, THREAD_ROWS);
@@ -226,14 +226,16 @@ type ToolGroups = Readonly<Record<string, { about: string; controllers: readonly
const CORE_TOOL_GROUPS: ToolGroups = {
tours: {
about:
'Tours: hikes (also over several days in stages), city walks, bike tours, runs, rides, paddling and ski ' +
'routes; plan, create, change and export them (hikes with their heights and SAC grades), search along a ' +
'Tours: hikes (also over several days in stages), city walks, bike tours (road, gravel, mountain bike), ' +
'runs (road and trail), rides, paddling and ski and winter tours; plan and save every one of them, change ' +
'and export them (hikes with their heights and SAC grades), search along a ' +
'tour, check off a city walk under way, the recorded tracks and tour stats, their packing, tours in ' +
'collections, the tour library and imports from GPX files and Google Maps walks.',
controllers: [
'ToursMcp',
'CityWalkMcp',
'HikePlanMcp',
'TourPlanMcp',
'TourChangeMcp',
'TourChangeUndoMcp',
'TourLibraryMcp',
@@ -145,8 +145,14 @@ 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 bike tour or a run, a city walk, a paddle or ski tour. */
const PROPOSAL_VIA: ReadonlySet<string> = new Set([
'create_hike',
'create_tour',
'create_city_walk',
'create_paddle_tour',
'create_ski_tour',
]);
/**
* Changes the server applies itself: a booking from an attached file, a search
@@ -6,6 +6,7 @@ import {
createHikeCard,
createHikeEffect,
loadCreateHike,
loadCreateTour,
loadUpdateTour,
updateTourCard,
type TourLoaded,
@@ -13,6 +14,13 @@ import {
import { TOUR_DESCRIBERS } from './tour-describe';
import { tourListCard } from './tour-lists.cards';
import { proposalCard, savedTourCard } from './tour-route.cards';
import {
createPaddleCard,
createSkiCard,
loadCreatePaddle,
loadCreateSki,
type SportLoaded,
} from './tour-sport-change.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';
@@ -47,6 +55,34 @@ const createHike: ToolCards<TourLoaded> = {
undo: DELETE_CREATED_TOUR,
};
/** create_tour: a bike tour or a run, drawn and taken back as a hike is, its effect on the day too. */
const createTour: ToolCards<TourLoaded> = {
write: { verbKey: 'addTour', entity: 'tour' },
describe: TOUR_DESCRIBERS.create_tour,
load: loadCreateTour,
change: createHikeCard,
effect: createHikeEffect,
applied: appliedTourCard,
undo: DELETE_CREATED_TOUR,
};
/** A paddle or ski tour saved from its plan: the plan's card waiting, the receipt opening the tour, its delete the way back. */
function sportCreate(
describe: ToolCards<SportLoaded>['describe'],
load: NonNullable<ToolCards<SportLoaded>['load']>,
change: NonNullable<ToolCards<SportLoaded>['change']>,
): ToolCards<SportLoaded> {
return {
write: { verbKey: 'addTour', entity: 'tour' },
describe,
load,
change,
effect: createHikeEffect,
applied: appliedTourCard,
undo: DELETE_CREATED_TOUR,
};
}
const updateTour: ToolCards<TourLoaded> = {
write: { verbKey: 'updateTour', entity: 'tour' },
describe: TOUR_DESCRIBERS.update_tour,
@@ -60,6 +96,7 @@ export const TOUR_CARDS: DomainCards = {
id: 'tour',
tools: {
propose_hike: { argPolicy: WITH_GEOMETRY, answer: proposalCard },
propose_tour: { argPolicy: WITH_GEOMETRY, answer: proposalCard },
propose_city_walk: { argPolicy: WITH_GEOMETRY, answer: cityWalkCard },
plan_paddle_route: { argPolicy: WITH_GEOMETRY, answer: paddleCard },
plan_ski_route: { argPolicy: WITH_GEOMETRY, answer: skiCard },
@@ -67,6 +104,9 @@ export const TOUR_CARDS: DomainCards = {
list_tours: { answer: tourListCard },
find_tours_for_day: { answer: tourListCard },
create_hike: createHike,
create_tour: createTour,
create_paddle_tour: sportCreate(TOUR_DESCRIBERS.create_paddle_tour, loadCreatePaddle, createPaddleCard),
create_ski_tour: sportCreate(TOUR_DESCRIBERS.create_ski_tour, loadCreateSki, createSkiCard),
create_city_walk: {
write: { verbKey: 'addTour', entity: 'tour' },
describe: TOUR_DESCRIBERS.create_city_walk,
@@ -94,6 +134,8 @@ export const TOUR_CARDS: DomainCards = {
},
},
prompt: [
"Every tour type can be planned and saved. Pick the tool by what the user does: a hike (also a trek over several days) propose_hike then create_hike; a bike tour or a run propose_tour (activity bike or run) then create_tour; a city walk propose_city_walk then create_city_walk; a paddle tour plan_paddle_route then create_paddle_tour (it needs water_context river or lake); a ski or winter tour (alpine, snowboard, cross-country, ski touring, snowshoe, winter hike) plan_ski_route then create_ski_tour with the same points, discipline and options. Pass the plan's points in order as waypoints: the from of the first leg and the to of every leg.",
"Profiles: a bike tour is touring for a city or trekking bike on paved ways and cycle paths (the default), road for a road bike on asphalt only, gravel for a gravel bike on gravel and farm tracks, mtb for a mountain bike on rough tracks and trails; a run is running on mostly paved ways (the default) or trail on forest tracks and natural paths. Choose from what the user rides or how they run; ask when it is not clear. A run needs the runner's pace (run_pace_seconds_per_km, 330 for 5:30 min/km) for its time and to be created: ask for it, never guess one.",
'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).',
],
@@ -18,7 +18,7 @@ import {
straightMetres,
whole,
} from './tour-card-values';
import { hikeCard } from './tour-route.cards';
import { hikeCard, landSportOf } from './tour-route.cards';
import {
hikingPreferencesOf,
TOUR_ROUTE_LIMITS,
@@ -118,8 +118,12 @@ function heldProblem(card: TourRouteCard | null): TourRouteCard['problem'] {
return refuses && card?.problem ? card.problem : { why: 'not_planned', position: null, snappedM: null };
}
/** The points of a held hike or walk joined straight, as stops along the straight line. */
function straightCard(points: readonly Row[], activity: 'hike' | 'walk', fields: Partial<TourRouteCard>) {
/** The points of a held tour joined straight, as stops along the straight line. */
export function straightCard(
points: readonly Row[],
activity: TourRouteCard['activity'],
fields: Partial<TourRouteCard>,
): TourRouteCard | null {
const stops = points.flatMap((point) => {
const at = latLngOf(point);
return at ? [{ ...at, point }] : [];
@@ -155,19 +159,45 @@ function hikePoints(args: ToolArgs): Row[] {
return args.round_trip === true && points[0] ? [...points, points[0]] : points;
}
/** create_hike: the planned way as the proposal drew it, else the points straight. */
/**
* create_hike and create_tour: the planned way as the proposal drew it, else
* the points straight, a hike's under its limit, a bike tour's or a run's
* under its profile.
*/
export function createHikeCard(ctx: PreviewContext, args: ToolArgs, loaded: TourLoaded | null): TourRouteCard | null {
const name = argText(args.name, 120);
const planned = loaded ? hikeCard(loaded.plan, args, ctx.card, 'pending') : null;
if (planned?.routed) return fitted({ ...planned, name: name ?? planned.name, label: null });
const straight = straightCard(hikePoints(args), 'hike', {
const sport = landSportOf({}, args);
const own = sport ?? { limit: sacStepOf(args.max_hiking_difficulty) ?? TOURS_MAX_HIKING_DIFFICULTY };
const straight = straightCard(hikePoints(args), sport?.activity ?? 'hike', {
name,
limit: sacStepOf(args.max_hiking_difficulty) ?? TOURS_MAX_HIKING_DIFFICULTY,
...own,
problem: heldProblem(planned),
});
return straight ? fitted(straight) : null;
}
/** The fields propose_tour takes of a create_tour, as the planner's memo keys its way. */
const TOUR_PLAN_FIELDS = [
'name',
'activity',
'bike_profile',
'run_profile',
'run_pace_seconds_per_km',
'waypoints',
'round_trip',
'day_id',
'start_time',
] as const;
/** create_tour: plans the way through the points as propose_tour did (the planner's memo answers a recent one). */
export async function loadCreateTour(args: ToolArgs, read: CardReader): Promise<TourLoaded> {
const plan: ToolArgs = { along: false };
for (const key of TOUR_PLAN_FIELDS) if (args[key] !== undefined) plan[key] = args[key];
return { plan: await read('propose_tour', plan), saved: null };
}
/** create_city_walk: the stations joined straight; the way on foot is planned when the walk is saved. */
export function createCityWalkCard(_ctx: PreviewContext, args: ToolArgs): TourRouteCard | null {
const straight = straightCard(rowsIn(args.stations), 'walk', { name: argText(args.name, 120) });
@@ -5,8 +5,8 @@ import { TOURS_MAX_HIKING_DIFFICULTY } from '@trek/shared';
/**
* The change cards of the tours an assistant creates and changes: a hike, a
* city walk, a change to a saved hike, tours taken in from a GPX file. The
* route reads as the names of its points in order, a hike's limit as its SAC
* bike tour, a run, a paddle or ski tour, a city walk, a change to a saved
* hike, tours taken in from a GPX file. The route reads as the names of its points in order, a hike's limit as its SAC
* grade (T1 to T6), a planned time in hours and minutes.
*/
@@ -58,6 +58,17 @@ function gpxName(gpx: unknown): string {
return close < 0 ? '' : text(gpx.slice(open + '<name>'.length, close));
}
/** A tour of another type than a hike created from its plan: its points in order, its day, its planned time and words. */
function describeSportCreate(ctx: PreviewContext, args: ToolArgs): Described {
const day = onDay(ctx, id(args, 'day_id'), args.start_time);
const rows = new Rows()
.add('route', routeOf(ctx, args.waypoints, args.round_trip))
.add('day', day)
.add('time', hours(args.planned_duration_minutes))
.add('description', text(args.description));
return { subject: text(args.name), rows, dayId: day ? id(args, 'day_id') : null, placeIds: [] };
}
export const TOUR_DESCRIBERS = {
create_hike: (ctx, args) => {
const day = onDay(ctx, id(args, 'day_id'), args.start_time);
@@ -69,6 +80,10 @@ export const TOUR_DESCRIBERS = {
.add('description', text(args.description));
return { subject: text(args.name), rows, dayId: day ? id(args, 'day_id') : null, placeIds: [] };
},
// A bike tour, a run, a paddle or ski tour: its points and day; its profile and figures are on the route card below.
create_tour: describeSportCreate,
create_paddle_tour: describeSportCreate,
create_ski_tour: describeSportCreate,
create_city_walk: (ctx, args) => {
const rows = new Rows().add('route', routeOf(ctx, args.stations, false)).add('description', text(args.description));
return { subject: text(args.name), rows, dayId: null, placeIds: linkedPlaceIds(ctx, args.stations) };
@@ -28,10 +28,12 @@ import {
type RoutePoint,
} from './tour-card-values';
import {
BIKE_PROFILES,
cumulativeMetres,
HIKE_UNROUTED_REASONS,
legMinutes,
nearestAlongM,
RUN_PROFILES,
TOUR_ROUTE_LIMITS,
TOUR_WARNING_KINDS,
tourTypeKeySchema,
@@ -42,7 +44,8 @@ import {
} from '@trek/shared';
/**
* The cards of a hike the assistant proposed (propose_hike) and of a saved
* The cards of a hike, a bike tour or a run the assistant proposed
* (propose_hike, propose_tour) and of a saved
* tour it read (get_tour_plan), built from the tool's raw answer. A proposal
* draws its line only when the tool added it for drawing (the assistant
* always asks), so without `line_geometry` there is no card. A way that was
@@ -56,6 +59,35 @@ const SAME_SUMMIT_M = 150;
const LOOP_END_M = 60;
const UNROUTED: ReadonlySet<string> = new Set(HIKE_UNROUTED_REASONS);
const BIKE: ReadonlySet<string> = new Set(BIKE_PROFILES);
const RUN: ReadonlySet<string> = new Set(RUN_PROFILES);
/** A planned way's activity on land beyond a hike: a bike tour or a run, with its profile and a run's pace. */
type RoutingProfile = NonNullable<TourRouteCard['routingProfile']>;
type LandSport = Pick<TourRouteCard, 'activity' | 'routingProfile' | 'paceSecondsPerKm'>;
/**
* The bike tour or run a proposal (propose_tour) or its arguments name, with
* its profile (the planner's own where none is named) and a run's pace; null
* for a hike, whose card names none of them.
*/
export function landSportOf(plan: Row, args: Row): LandSport | null {
const activity = plan.activity ?? args.activity;
if (activity === 'bike') {
const profile = plan.bike_profile ?? args.bike_profile;
return {
activity,
routingProfile: typeof profile === 'string' && BIKE.has(profile) ? (profile as RoutingProfile) : 'touring',
};
}
if (activity !== 'run') return null;
const profile = plan.run_profile ?? args.run_profile;
return {
activity,
routingProfile: typeof profile === 'string' && RUN.has(profile) ? (profile as RoutingProfile) : 'running',
paceSecondsPerKm: whole(plan.run_pace_seconds_per_km ?? args.run_pace_seconds_per_km, 60, 3_600),
};
}
const WARNINGS: ReadonlySet<string> = new Set(TOUR_WARNING_KINDS);
/** Graded stretches merged where the step repeats, at most the card's share, the hardest kept. */
@@ -197,9 +229,11 @@ function unroutedHike(value: Row, args: Row, source: TourRouteCard['source']): T
const unreachable = recordOf(value.unreachable);
const why = typeof route.why === 'string' && UNROUTED.has(route.why) ? route.why : 'not_planned';
const along = straightMetres(points);
const sport = landSportOf(value, args);
return routeCard({
source,
activity: 'hike',
...sport,
name: clipped(value.name ?? args.name, 120),
label: clipped(value.variant_label ?? args.variant_label, 40),
limit: sacStepOf(value.max_hiking_difficulty ?? args.max_hiking_difficulty),
@@ -235,11 +269,16 @@ export function hikeCard(
const sac = plan.sac === null || plan.sac === undefined ? null : recordOf(plan.sac);
const start = clockOf(plan.start_time);
const own = waypointStops(rowsIn(plan.waypoints), start);
const basis = plan.duration_basis === 'din33466' || plan.duration_basis === 'router' ? plan.duration_basis : null;
const basis =
plan.duration_basis === 'din33466' || plan.duration_basis === 'router' || plan.duration_basis === 'pace'
? plan.duration_basis
: null;
const unknown = finite(sac?.unknown_share);
const sport = landSportOf(plan, args);
return routeCard({
source,
activity: 'hike',
...sport,
name: clipped(plan.name, 120),
label: clipped(plan.variant_label, 40),
distanceM: metresOf(plan.distance_m),
@@ -261,7 +300,7 @@ export function hikeCard(
});
}
/** propose_hike: the proposal as a card. */
/** propose_hike and propose_tour: the proposal as a card, a hike's or a bike tour's or a run's. */
export function proposalCard({ value, args, card }: AnswerInput): TourRouteCard | null {
const proposal = hikeCard(value, args, card, 'proposal');
return proposal ? fitted(proposal) : null;
@@ -347,6 +386,13 @@ export function savedTourCard({ value }: AnswerInput): TourRouteCard | null {
line,
stops: sortedStops(stops),
stages: whole(tour.stage_count, 2, 60),
...savedSportOf(activity.data, tour),
}),
);
}
/** A saved bike tour's or run's profile and a run's pace, as its card names them; nothing for any other type. */
function savedSportOf(activity: TourRouteCard['activity'], tour: Row): Partial<TourRouteCard> {
if (activity !== 'bike' && activity !== 'run') return {};
return landSportOf({ activity, ...tour }, {}) ?? {};
}
@@ -0,0 +1,78 @@
import type { CardReader, PreviewContext, ToolArgs } from '../card-types';
import { recordOf, type Row } from '../card-values';
import { argText, fitted, latLngOf, rowsIn } from './tour-card-values';
import { straightCard } from './tour-change.cards';
import { paddleCard, skiCard } from './tour-sport.cards';
import type { TourRouteCard } from '@trek/shared';
/**
* The change cards of a paddle or ski tour the assistant saves from its plan
* (create_paddle_tour, create_ski_tour): the legs between its points planned
* again as the plan planned them, drawn as the plan's card was, waiting, under
* the name the tour is saved with. Where the plan cannot be read now, the
* points are drawn straight and the way is planned when the change is applied.
*/
/** What a held paddle or ski tour looked up: the plan of its legs, null where it could not be read. */
export interface SportLoaded {
plan: unknown;
}
/** The legs a tour's points make, each from one to the next, as the planning tools take them. */
export function legArgsOf(
args: ToolArgs,
): Array<{ from: { lat: number; lng: number }; to: { lat: number; lng: number } }> {
const points = rowsIn(args.waypoints).flatMap((point) => latLngOf(point) ?? []);
return points.slice(1).map((to, index) => ({ from: points[index] ?? to, to }));
}
/** The fields of a create a plan was asked with besides its legs, as the planning tool names them. */
function planArgs(args: ToolArgs, fields: Readonly<Record<string, string>>): ToolArgs {
const plan: ToolArgs = { legs: legArgsOf(args) };
for (const [from, to] of Object.entries(fields)) if (args[from] !== undefined) plan[to] = args[from];
return plan;
}
/** create_paddle_tour: its legs planned on the water as plan_paddle_route planned them. */
export async function loadCreatePaddle(args: ToolArgs, read: CardReader): Promise<SportLoaded | null> {
const plan = planArgs(args, { boat_type: 'boat', lake_style: 'lake_style', lock_policy: 'lock_policy' });
if (rowsIn(plan.legs).length === 0) return null;
return { plan: await read('plan_paddle_route', plan) };
}
/** create_ski_tour: its legs planned on the piste data as plan_ski_route planned them. */
export async function loadCreateSki(args: ToolArgs, read: CardReader): Promise<SportLoaded | null> {
const plan = planArgs(args, { discipline: 'discipline', technique: 'technique', options: 'options' });
if (rowsIn(plan.legs).length === 0) return null;
return { plan: await read('plan_ski_route', plan) };
}
/** A plan's card, waiting under the name the tour is saved with; else the points straight. */
function heldCard(
ctx: PreviewContext,
args: ToolArgs,
loaded: SportLoaded | null,
activity: 'kayak' | 'ski',
): TourRouteCard | null {
const name = argText(args.name, 120);
const input = { toolCallId: '', args: { legs: legArgsOf(args) } as Row, card: ctx.card, today: ctx.today };
const value = loaded ? recordOf(loaded.plan) : null;
const drawn = value ? (activity === 'kayak' ? paddleCard : skiCard)({ ...input, value }) : null;
if (drawn && drawn.warnings.every((warning) => warning.kind !== 'legs_failed')) {
return fitted({ ...drawn, source: 'pending', name });
}
const straight = straightCard(rowsIn(args.waypoints), activity, { name });
return straight ? fitted(straight) : null;
}
export function createPaddleCard(
ctx: PreviewContext,
args: ToolArgs,
loaded: SportLoaded | null,
): TourRouteCard | null {
return heldCard(ctx, args, loaded, 'kayak');
}
export function createSkiCard(ctx: PreviewContext, args: ToolArgs, loaded: SportLoaded | null): TourRouteCard | null {
return heldCard(ctx, args, loaded, 'ski');
}
@@ -101,14 +101,16 @@ export interface RouteOptions {
*/
footOnly?: boolean;
/**
* A hike's own pedestrian costing (its hiking limit and preferences, as
* `hikingCosting` builds them), sent to Valhalla as the planner in the
* browser sends it. Only Valhalla knows a hiking limit: OSRM's foot profile
* takes a T5 ridge as readily as a forest road. So a walk asked with one is
* asked of Valhalla alone and fails rather than fall back to OSRM, with a
* `RouteRefusal` of `no_valhalla` where there is no Valhalla to ask.
* A tour's own costing, sent to Valhalla as the planner in the browser
* sends it: on foot a hike's (its hiking limit and preferences, as
* `hikingCosting` builds them) or a run's (`runCosting`), by bike the
* bicycle costing of its profile (`bikeCosting`). Only Valhalla knows these:
* OSRM's foot profile takes a T5 ridge as readily as a forest road, and its
* bike profile knows no road bike from a mountain bike. So a way asked with
* one is asked of Valhalla alone and fails rather than fall back to OSRM,
* with a `RouteRefusal` of `no_valhalla` where there is no Valhalla to ask.
*/
costingOptions?: Readonly<Record<string, number>>;
costingOptions?: Readonly<Record<string, number | string>>;
}
export type { TracedWay };
@@ -304,7 +306,8 @@ export class RoadtripRouterService {
): Promise<RoadtripRoute> {
const settings = await this.settings.getUserSettings(userId);
const footOnly = options.footOnly === true && profile === 'walking';
const hiking = profile === 'walking' ? options.costingOptions : undefined;
// A tour's own costing goes with a way on foot or by bike; a drive has its avoidances instead.
const hiking = profile === 'walking' || profile === 'cycling' ? options.costingOptions : undefined;
const key = JSON.stringify([
userId,
tripId,
@@ -348,8 +351,11 @@ export class RoadtripRouterService {
const { base, valhalla } = routersOf(settings);
let weighted = false;
if (hiking) {
if (!valhalla) throw new RouteRefusal('no_valhalla', 'No Valhalla is set to plan a hike with');
const legs = await this.valhallaLegs(valhalla, points, 'pedestrian', { ...hiking });
const cycling = mode === 'cycling';
if (!valhalla) {
throw new RouteRefusal('no_valhalla', `No Valhalla is set to plan a ${cycling ? 'bike tour' : 'hike'} with`);
}
const legs = await this.valhallaLegs(valhalla, points, cycling ? 'bicycle' : 'pedestrian', { ...hiking });
({ line, distance, duration, parts, snapped } = routeOfLegs(points, legs));
weighted = true;
} else if (footOnly && valhalla) {
@@ -473,8 +479,8 @@ export class RoadtripRouterService {
private async valhallaLegs(
valhalla: string,
points: Point[],
costing: 'auto' | 'pedestrian',
options: Record<string, number>,
costing: 'auto' | 'pedestrian' | 'bicycle',
options: Record<string, number | string>,
offBoatLines = false,
): Promise<ValhallaLegs> {
const legs: ValhallaLegs = [];
@@ -38,5 +38,7 @@ function routerRunner() {
TrekPlacesWinterService,
{ provide: SKI_ROUTER_RUNNER, useFactory: routerRunner },
],
// A ski tour the assistant planned is planned again when it is saved (ToursModule).
exports: [SkiRoutingService],
})
export class SkiRoutingModule {}
+22 -4
View File
@@ -321,6 +321,19 @@ export interface HikeProposalContext {
along: HikeAlongPlace[] | null;
/** Null where none was asked or it could not be had. */
weather: WeatherResult | null;
/**
* A bike tour's or a run's own time on the move, in minutes, which stands
* for the plan's and is shared out over the legs by their length: a ride's
* is the router's for its profile, a run's its distance at the pace (null
* without one). A hike leaves it out and keeps the signposts' rule.
*/
movingMinutes?: number | null;
}
/** The minutes from the start to each point, the whole time shared out by how far along the way each lies. */
function minutesByLength(positions: readonly number[], total: number): number[] {
const length = positions.at(-1) ?? 0;
return positions.map((at) => (length > 0 ? Math.round((total * at) / length) : 0));
}
/**
@@ -341,16 +354,21 @@ export function hikeProposalOf(
const routed = plan.kind === 'routed' ? plan : null;
const positions = routed ? waypointPositionsOf(planned, points) : null;
const heights = routed?.has_heights && line ? heightRangeOf(line) : null;
const minutes = routed && line && positions ? waypointMinutesOf(line, positions, routed.duration_minutes) : null;
const own = context.movingMinutes !== undefined;
const total = routed ? (own ? (context.movingMinutes ?? null) : routed.duration_minutes) : null;
let minutes: number[] | null = null;
if (line && positions && total !== null) {
minutes = own ? minutesByLength(positions, total) : waypointMinutesOf(line, positions, total);
}
const arrivals = arrivalsOf(request.start_time ?? null, minutes ?? points.map(() => null));
// One day's sun and hours say nothing about a hike over several days.
const day =
routed && context.date && hikeStagesOf(points) === 1
total !== null && context.date && hikeStagesOf(points) === 1
? hikeScheduleOf({
date: context.date,
dayId: context.dayId,
start: request.start_time ?? null,
minutes: routed.duration_minutes,
minutes: total,
weather: context.weather,
})
: null;
@@ -362,7 +380,7 @@ export function hikeProposalOf(
distance_m: routed?.distance_m ?? null,
ascent_m: routed?.ascent_m ?? null,
descent_m: routed?.descent_m ?? null,
duration_minutes: routed?.duration_minutes ?? null,
duration_minutes: total,
duration_basis: routed?.duration_basis ?? null,
heights_known: heights !== null,
min_ele_m: heights?.min ?? null,
+102 -17
View File
@@ -17,8 +17,20 @@ import {
weatherPointOf,
type KeptWay,
} from './hike-plan.helpers';
import { HikeRoutingService, type PlannedHike } from './hike-routing.service';
import { HikeRoutingService, type PlannedActivity, type PlannedHike } from './hike-routing.service';
import { noTrackFound } from './tour-file-import.helpers';
import {
ALONG_CATEGORIES,
asHikeCreate,
asHikeProposal,
checkedRequest,
movingMinutesOf,
plannedActivityOf,
refusesSave,
tourCreateCommandOf,
tourProposalOf,
unplannedTourMessage,
} from './tour-plan.helpers';
import { TourPoiSearchService } from './tour-poi-search.service';
import { tourRevisionConflict } from './tour-revision';
import { thinnedLine } from './tours.helpers';
@@ -26,13 +38,14 @@ import { ToursService, type ImportGpxAsTourResult, type TourCreateCommand } from
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import {
HIKE_ALONG_CATEGORIES,
HIKE_ALONG_CORRIDOR_M,
HIKE_PLAN_MAX_WAYPOINTS,
hikeStageIssues,
hikingPreferencesOf,
TOUR_POI_MAX_LINE_POINTS,
tourGpxImportFieldsSchema,
tourPlanCreateRequestSchema,
tourProposeRequestSchema,
TOURS_MAX_HIKING_DIFFICULTY,
type GeometryPoint,
type HikeAlongPlace,
@@ -45,6 +58,9 @@ import {
type TourCreateResponse,
type TourDetailResponse,
type TourGpxImportRequest,
type TourPlanCreateRequest,
type TourProposal,
type TourProposeRequest,
type HikeRouteOutcome,
type TourUpdateRequest,
type TourWaypoint,
@@ -157,6 +173,7 @@ export class HikePlanService {
limit: number | undefined,
preferences: HikingPreferences | null | undefined,
grades: boolean,
activity: PlannedActivity | null = null,
): Promise<PlannedHike> {
// The router takes the points only: where a stage ends is the hike's, not the way's.
const waypoints = points.map(({ lat, lng, name, poi_category }) => ({
@@ -169,7 +186,8 @@ export class HikePlanService {
userId,
tripId,
{ waypoints, max_hiking_difficulty: limit, hiking_preferences: preferences },
{ grades },
// A hike asks as it always has; a ride or a run names its activity and reads no grades.
activity ? { grades: false, activity } : { grades },
);
}
@@ -181,17 +199,41 @@ export class HikePlanService {
* best effort: without them the proposal still answers.
*/
async propose(userId: number, tripId: number, request: HikeProposeRequest): Promise<HikeProposal> {
return await this.proposed(userId, tripId, request, null, null);
}
/**
* A bike tour or a run proposed the way a hike is: the same points, day,
* places along the way and weather, planned for its profile and timed by
* its own time (a ride the router's, a run its distance at the pace).
*/
async proposeTour(userId: number, tripId: number, request: TourProposeRequest): Promise<TourProposal> {
const asked = checkedRequest<TourProposeRequest>(tourProposeRequestSchema, request);
const activity = plannedActivityOf(asked);
const base = await this.proposed(userId, tripId, asHikeProposal(asked), activity, asked.run_pace_seconds_per_km);
return tourProposalOf(base, asked, activity);
}
/** The proposal of a hike, or with `activity` of a ride or a run, timed by its own time. */
private async proposed(
userId: number,
tripId: number,
request: HikeProposeRequest,
activity: PlannedActivity | null,
pace: number | null | undefined,
): Promise<HikeProposal> {
refuseBadStages(request.waypoints, request.round_trip);
const day = await this.dayOf(tripId, request.day_id, request.date);
const points = hikePointsOf(request.waypoints, request.round_trip);
const { max_hiking_difficulty: limit, hiking_preferences: preferences } = request;
const planned = await this.plan(userId, tripId, points, limit, preferences, true);
const planned = await this.plan(userId, tripId, points, limit, preferences, activity === null, activity);
const line = planned.plan.kind === 'routed' ? planned.line : null;
const [along, weather] = await Promise.all([
line && request.along !== false ? this.alongOf(line) : null,
line && request.along !== false ? this.alongOf(line, activity?.activity ?? 'hike') : null,
line && day.date ? this.weatherOf(weatherPointOf(points, planned), day.date) : null,
]);
return hikeProposalOf(request, points, planned, { ...day, along, weather });
const timed = activity ? { movingMinutes: movingMinutesOf(activity, pace, planned) } : {};
return hikeProposalOf(request, points, planned, { ...day, along, weather, ...timed });
}
/** The trip's day a hike is planned on and its date, or the date given without a day. */
@@ -206,17 +248,24 @@ export class HikePlanService {
return { dayId: day.id, date: day.date };
}
/** Summits, huts, water and viewpoints near the way, or null where the search could not be made. */
private async alongOf(line: readonly GeometryPoint[]): Promise<HikeAlongPlace[] | null> {
/**
* The places near the way the activity stops for (summits, huts, water and
* viewpoints on a hike), or null where the search could not be made.
*/
private async alongOf(
line: readonly GeometryPoint[],
type: keyof typeof ALONG_CATEGORIES,
): Promise<HikeAlongPlace[] | null> {
const categories = ALONG_CATEGORIES[type];
try {
const found = await this.poiSearch.search({
tour_type: 'hike',
categories: [...HIKE_ALONG_CATEGORIES],
tour_type: type,
categories: [...categories],
corridor_m: HIKE_ALONG_CORRIDOR_M,
line: thinnedLine(line, TOUR_POI_MAX_LINE_POINTS).map(([lat, lng]): [number, number] => [lat, lng]),
});
// Not one kind could be searched: nothing found would read as nothing there.
if (found.unavailable.length === HIKE_ALONG_CATEGORIES.length) return null;
if (found.unavailable.length === categories.length) return null;
return alongPlacesOf(found.pois, line);
} catch (err: unknown) {
logWarn(`[Hike] no places along the way: ${reasonOf(err)}`);
@@ -258,17 +307,53 @@ export class HikePlanService {
throw notRouted(unplannedCreateMessage(way.route));
}
const command = hikeCreateCommandOf(request, points, way, planned.plan.max_hiking_difficulty);
if (day?.dayId == null) {
return await this.saveOnDay(tripId, command, day?.dayId ?? null, request.start_time, way.route);
}
/**
* A bike tour or a run created the way a hike is (create): planned again
* through its points for its profile, saved with its line and heights, its
* time (a ride the router's, a run its distance at the pace), its profile
* and pace, put on its day in the same write. A router that did not answer
* saves its points only; any other reason refuses it, and nothing is saved.
*/
async createTour(userId: number, tripId: number, request: TourPlanCreateRequest): Promise<HikeCreated> {
const asked = checkedRequest<TourPlanCreateRequest>(tourPlanCreateRequestSchema, request);
const activity = plannedActivityOf(asked);
const hike = asHikeCreate(asked);
const day = hike.day_id === undefined ? null : await this.dayOf(tripId, hike.day_id, undefined);
const points = hikePointsOf(hike.waypoints, hike.round_trip);
const planned = await this.plan(userId, tripId, points, undefined, undefined, false, activity);
const way = keptWayOf(planned);
if (refusesSave(way.route)) throw notRouted(unplannedTourMessage(way.route, activity.activity));
const minutes = movingMinutesOf(activity, asked.run_pace_seconds_per_km, planned);
const command = tourCreateCommandOf(asked, points, way, activity, minutes);
return await this.saveOnDay(tripId, command, day?.dayId ?? null, hike.start_time, way.route);
}
/**
* A planned tour saved through the creation the planner's save uses. With
* a day it is put on that day in the same write, its start kept as the
* visit's, and the trip is told of the tour and the visit once both are
* saved, as the planner's save and its drop onto the day tell it.
*/
async saveOnDay(
tripId: number,
command: TourCreateCommand,
dayId: number | null,
startTime: string | undefined,
route: HikeRouteOutcome,
): Promise<HikeCreated> {
if (dayId === null) {
const created = await this.tours.createTour(String(tripId), command);
return { ...created, route: way.route, assignment: null };
return { ...created, route, assignment: null };
}
const dayId = day.dayId;
const written = await this.uow.transactional(async () => {
const placeId = await this.tours.insertTour(tripId, command);
const added = await this.assignments.createAssignment(dayId, placeId, null);
if (!added) throw new Error('Created visit could not be loaded');
if (!request.start_time) return { placeId, assignment: added, reordered: null, vias: null };
const timed = await this.assignments.updateTime(added.id, request.start_time, null);
if (!startTime) return { placeId, assignment: added, reordered: null, vias: null };
const timed = await this.assignments.updateTime(added.id, startTime, null);
return { placeId, ...timed, assignment: timed.assignment ?? added };
});
const trip = String(tripId);
@@ -278,7 +363,7 @@ export class HikePlanService {
if (written.reordered) this.assignments.broadcast(trip, 'assignment:reordered', written.reordered, undefined);
if (written.vias) this.assignments.broadcast(trip, 'roadtripVia:changed', written.vias, undefined);
await this.assignments.reconcile(tripId);
return { ...created, route: way.route, assignment: { id: written.assignment.id, day_id: dayId } };
return { ...created, route, assignment: { id: written.assignment.id, day_id: dayId } };
}
/**
+53 -10
View File
@@ -6,6 +6,7 @@ import { TourTrailGradeService } from './tour-trail-grade.service';
import { thinnedLine } from './tours.helpers';
import { Injectable } from '@nestjs/common';
import {
bikeCosting,
computeTourMetrics,
HIKE_MAX_LINE_POINTS,
HIKE_PLAN_LINE_POINTS,
@@ -14,14 +15,18 @@ import {
hikingCosting,
hikingPreferencesOf,
hikingTimeMinutes,
runCosting,
sacStepOf,
TOUR_MAX_SNAP_M,
TOUR_TRAIL_GRADE_MAX_WAYS,
TOURS_MAX_HIKING_DIFFICULTY,
type BikeProfile,
type GeometryPoint,
type HikePlan,
type HikePlanRequest,
type HikingPreferences,
type HikeTrailGrades,
type RunProfile,
type SacStep,
type UnroutedHikePlan,
} from '@trek/shared';
@@ -79,14 +84,26 @@ interface KeptPlan {
planned: PlannedHike;
}
/** The request as the memo keys it: who asked in which trip, the points to about a metre, the limit, the preferences. */
function memoKeyOf(userId: number, tripId: number, request: HikePlanRequest): string {
/**
* A tour planned through the same way as a hike but for another activity: a
* bike tour by bike for its profile, a run on foot for its profile. Neither
* takes a hiking limit, preferences or SAC grades.
*/
export type PlannedActivity = { activity: 'bike'; profile: BikeProfile } | { activity: 'run'; profile: RunProfile };
/**
* The request as the memo keys it: who asked in which trip, the points to
* about a metre, the limit, the preferences, and for a bike tour or a run its
* activity and profile.
*/
function memoKeyOf(userId: number, tripId: number, request: HikePlanRequest, activity: PlannedActivity | null): string {
const points = request.waypoints.map(({ lat, lng }) => [
Number(lat.toFixed(PLAN_MEMO_DECIMALS)),
Number(lng.toFixed(PLAN_MEMO_DECIMALS)),
]);
const limit = request.max_hiking_difficulty ?? TOURS_MAX_HIKING_DIFFICULTY;
return JSON.stringify([userId, tripId, points, limit, hikingPreferencesOf(request.hiking_preferences)]);
const key = [userId, tripId, points, limit, hikingPreferencesOf(request.hiking_preferences)];
return JSON.stringify(activity ? [...key, activity.activity, activity.profile] : key);
}
/** What a plan asks for besides the way and its heights. */
@@ -96,6 +113,27 @@ export interface HikePlanOptions {
* trail grades): a proposal shows them, a hike being saved keeps none.
*/
grades: boolean;
/**
* A bike tour or a run, planned with its own costing and timed by the
* router; a hike when left out. Its limit and preferences are a hike's and
* go unread.
*/
activity?: PlannedActivity;
}
/**
* How a way is asked of the router: on foot with a hike's limit and
* preferences, by bike with its profile's bicycle costing, on foot with a
* run's pedestrian costing.
*/
function costingOf(
activity: PlannedActivity | null,
limit: number,
preferences: HikingPreferences | null,
): ['walking' | 'cycling', Readonly<Record<string, number | string>>] {
if (activity?.activity === 'bike') return ['cycling', bikeCosting(activity.profile)];
if (activity?.activity === 'run') return ['walking', runCosting(activity.profile)];
return ['walking', hikingCosting(limit, preferences)];
}
/** What went wrong, for the log. */
@@ -139,14 +177,16 @@ export class HikeRoutingService {
request: HikePlanRequest,
options?: HikePlanOptions,
): Promise<PlannedHike> {
const withGrades = options?.grades ?? true;
const activity = options?.activity ?? null;
// SAC grades are a hike's: a bike tour or a run never reads them.
const withGrades = activity === null && (options?.grades ?? true);
// The tools check their own requests; a change plans through the points a hike has saved, held here to the same.
const checked = hikePlanRequestSchema.safeParse(request);
if (!checked.success) throw badRequest(checked.error.issues.map((issue) => issue.message).join('; '));
const key = memoKeyOf(userId, tripId, request);
const key = memoKeyOf(userId, tripId, request, activity);
const kept = this.recall(key, withGrades);
if (kept) return kept;
const planned = await this.planned(userId, tripId, request, withGrades);
const planned = await this.planned(userId, tripId, request, withGrades, activity);
// Only a way with every height is kept: one without is asked again, and its heights with it.
if (planned.plan.kind === 'routed' && planned.plan.has_heights && planned.line) {
const grades = withGrades && planned.plan.grades !== null;
@@ -193,6 +233,7 @@ export class HikeRoutingService {
tripId: number,
request: HikePlanRequest,
withGrades: boolean,
activity: PlannedActivity | null,
): Promise<PlannedHike> {
const limit = request.max_hiking_difficulty ?? TOURS_MAX_HIKING_DIFFICULTY;
const preferences = hikingPreferencesOf(request.hiking_preferences);
@@ -205,8 +246,8 @@ export class HikeRoutingService {
let route: RoadtripRoute;
try {
const points = request.waypoints.map(({ lat, lng }) => ({ lat, lng }));
const costingOptions = hikingCosting(limit, preferences);
route = await this.router.route(userId, tripId, ANY_DAY, points, 'walking', [], { costingOptions });
const [mode, costingOptions] = costingOf(activity, limit, preferences);
route = await this.router.route(userId, tripId, ANY_DAY, points, mode, [], { costingOptions });
} catch (err: unknown) {
if (!(err instanceof RouteRefusal)) logWarn(`[Hike] no way for trip ${tripId}: ${reasonOf(err)}`);
return unrouted(whyNot(err));
@@ -226,6 +267,8 @@ export class HikeRoutingService {
const ascent = metrics.elevationGainM;
const descent = metrics.elevationLossM;
const heights = ascent !== null && descent !== null;
// The signposts' rule is a walker's: a ride keeps the router's time for its profile, and a run's pace is set later.
const byRule = heights && activity === null;
return {
plan: {
kind: 'routed',
@@ -234,10 +277,10 @@ export class HikeRoutingService {
distance_m: Math.round(lengthM),
ascent_m: heights ? Math.round(ascent) : null,
descent_m: heights ? Math.round(descent) : null,
duration_minutes: heights
duration_minutes: byRule
? hikingTimeMinutes(metrics.distanceKm, ascent, descent)
: Math.round(route.leg.seg.duration / 60),
duration_basis: heights ? 'din33466' : 'router',
duration_basis: byRule ? 'din33466' : 'router',
has_heights: heights,
line: thinnedLine(line, HIKE_PLAN_LINE_POINTS),
profile: profileOf(line, HIKE_PLAN_PROFILE_SAMPLES),
@@ -0,0 +1,158 @@
import type { TourCreateCommand } from './tours.service';
import {
cumulativeMetres,
estimatePaddleTime,
paddleLayoutOfTrack,
paddleMovingSeconds,
recommendedPaddleSpeedKmh,
skiOptionsForDiscipline,
type GeometryPoint,
type PaddleRouteLeg,
type PaddleTourCreateRequest,
type SkiRouteLeg,
type SkiTourCreateRequest,
type SportTourPoint,
type TourWaypoint,
type TrackMarks,
} from '@trek/shared';
/**
* The pure halves of a paddle or ski tour saved from a plan
* (SportTourCreateService): the legs between its points, the portages and
* locks the paddle router found laid along the whole line, the joined line of
* a ski tour with its time, and the write each one makes, as the planner's
* save writes it.
*/
/** What a save keeps of a plan: the whole line with its heights (null without them) and a paddle tour's marks. */
export interface SportPlanned {
line: GeometryPoint[] | null;
marks: TrackMarks | null;
}
/** The legs a tour's points make, each from one point to the next. */
export function legsOf(points: readonly SportTourPoint[]): Array<{ from: SportTourPoint; to: SportTourPoint }> {
return points.slice(1).map((to, index) => ({ from: points[index] as SportTourPoint, to }));
}
type PlannedPaddleLeg = Extract<PaddleRouteLeg, { status: 'ok' }>;
/**
* The portages and locks of the planned legs, in metres along the whole
* line as the legs are joined: each leg's stretches placed by its own line,
* after the length of the legs before it. A lock has no time of its own
* entered, which the estimate names as unknown rather than zero.
*/
export function paddleMarksOf(legs: readonly PlannedPaddleLeg[]): TrackMarks {
const marks: TrackMarks = { portages: [], locks: [] };
let offset = 0;
for (const leg of legs) {
const along = cumulativeMetres(leg.geometry.map(([lat, lng]) => [lat, lng] as const));
for (const segment of leg.segments) {
const from = offset + (along[segment.from] ?? 0);
const to = offset + (along[segment.to] ?? 0);
if (segment.kind === 'portage' && to > from) marks.portages.push({ from_m: from, to_m: to, extra_minutes: null });
if (segment.kind === 'lock') {
marks.locks.push({ at_m: (from + to) / 2, wait_minutes: null, transit_minutes: null });
}
}
offset += along.at(-1) ?? 0;
}
return marks;
}
/** The length of a line in metres. */
function lengthOf(line: readonly GeometryPoint[]): number {
return cumulativeMetres(line.map(([lat, lng]) => [lat, lng] as const)).at(-1) ?? 0;
}
/**
* The write of a paddle tour, as the planner's save writes one: its boat and
* water, the speeds its time is reckoned with (the boat's starting speed where
* none is given) and that time, the moving part of the planner's estimate.
*/
export function paddleCommandOf(
request: PaddleTourCreateRequest,
waypoints: TourWaypoint[],
planned: SportPlanned,
): TourCreateCommand {
const boat = request.boat_type ?? 'kayak';
const speed = request.paddle_speed_kmh ?? recommendedPaddleSpeedKmh(boat);
const portageSpeed = request.portage_speed_kmh ?? null;
const estimate = planned.line
? estimatePaddleTime(paddleLayoutOfTrack(lengthOf(planned.line), planned.marks), {
paddleSpeedKmh: speed,
portageSpeedKmh: portageSpeed,
breakMinutes: null,
})
: null;
return {
name: request.name,
description: request.description,
tour_type: 'kayak',
route_geometry: planned.line,
duration_seconds: estimate ? paddleMovingSeconds(estimate) : null,
max_hiking_difficulty: null,
hiking_preferences: null,
boat_type: boat,
water_context: request.water_context,
paddle_speed_kmh: speed,
portage_speed_kmh: portageSpeed,
paddle_lake_style: request.lake_style ?? null,
...(request.planned_duration_minutes !== undefined
? { planned_duration_minutes: request.planned_duration_minutes }
: {}),
waypoints,
};
}
type PlannedSkiLeg = Extract<SkiRouteLeg, { status: 'ok' }>;
/**
* The planned legs of a ski tour as one line, each point with its height
* where the piste data has one, a point repeating the one before it left out,
* and the piste router's time: skiing, lifts, waiting and walking together.
*/
export function skiLineOf(legs: readonly PlannedSkiLeg[]): { line: GeometryPoint[]; seconds: number } {
const line: GeometryPoint[] = [];
for (const [lat, lng, height] of legs.flatMap((leg) => leg.geometry)) {
const last = line.at(-1);
if (last && last[0] === lat && last[1] === lng) continue;
line.push(height === null ? [lat, lng] : [lat, lng, height]);
}
const seconds = legs.reduce((sum, { seconds: parts }) => sum + parts.ski + parts.lift + parts.wait + parts.walk, 0);
return { line, seconds };
}
/**
* The write of a ski tour, as the planner's save writes one: its discipline
* (and a cross-country technique), the options the piste router was asked
* with as the discipline reads them, the build its legs were planned on, every
* leg as planned by it, and its time, given only with the line it belongs to.
*/
export function skiCommandOf(
request: SkiTourCreateRequest,
waypoints: TourWaypoint[],
planned: SportPlanned,
plan: { build: string | null; seconds: number; legs: number },
): TourCreateCommand {
const crossCountry = request.discipline === 'cross_country';
return {
name: request.name,
description: request.description,
tour_type: 'ski',
route_geometry: planned.line,
duration_seconds: planned.line ? Math.round(plan.seconds) : null,
max_hiking_difficulty: null,
hiking_preferences: null,
ski_discipline: request.discipline,
ski_technique: crossCountry ? (request.technique ?? null) : null,
ski_options: skiOptionsForDiscipline(request.discipline, request.options ?? {}),
ski_route_build: plan.build,
ski_planned_legs: Array.from({ length: plan.legs }, (_, index) => index),
...(request.planned_duration_minutes !== undefined
? { planned_duration_minutes: request.planned_duration_minutes }
: {}),
waypoints,
};
}
@@ -0,0 +1,167 @@
import { Tours } from '../../db/entities/Tours.entity';
import type { ToursRepository } from '../../db/repositories/Tours.repository';
import { logWarn } from '../audit/audit-log.logger';
import { DomainError, notFound } from '../common/domain-error';
import { PaddleRoutingService } from '../paddle-routing/paddle-routing.service';
import { RoadtripRouterService } from '../roadtrip/roadtrip-router.service';
import { SkiRoutingService } from '../ski-routing/ski-routing.service';
import { hikeWaypointsOf } from './hike-plan.helpers';
import { HikePlanService, type HikeCreated } from './hike-plan.service';
import { heightsOrNone, joinedLine } from './hike-routing.helpers';
import {
legsOf,
paddleCommandOf,
paddleMarksOf,
skiCommandOf,
skiLineOf,
type SportPlanned,
} from './sport-tour-create.helpers';
import { checkedRequest } from './tour-plan.helpers';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import {
paddleRouteRequestSchema,
paddleTourCreateRequestSchema,
skiRouteRequestSchema,
skiTourCreateRequestSchema,
type GeometryPoint,
type HikeRouteOutcome,
type PaddleTourCreateRequest,
type SkiTourCreateRequest,
} from '@trek/shared';
/** A leg the router could not plan: the tour is refused, as a 422 the tools answer with its text. */
function legRefused(index: number, code: string, where: string): DomainError {
return new DomainError(
422,
`Leg ${index + 1} could not be planned ${where} (${code}): move its points or plan it again. Nothing was saved.`,
{ code: 'tour_not_routed' },
);
}
function reasonOf(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
/**
* A paddle tour or a ski tour the assistant planned (plan_paddle_route,
* plan_ski_route) saved once the traveller said yes, the way the planner's
* save writes one. Its legs run from each point to the next and are planned
* again by the same router, on the water or on the piste data; a leg that
* cannot be planned refuses the tour and nothing is saved. The legs are
* joined into one line with the height of every point (the piste data's
* where it has them all, else Valhalla's, as for a hike); where the heights
* cannot be read the tour is saved with its points only (route_pending), and
* the planner plans it when it is opened. A paddle tour is timed with the
* planner's estimate (water at the paddling speed, each portage the router
* carries round at the carrying speed), a ski tour with the piste router's
* time. With a day it is put on that day in the same write (HikePlanService's
* save, so a tour of any type lands on its day alike).
*/
@Injectable()
export class SportTourCreateService {
constructor(
private readonly paddle: PaddleRoutingService,
private readonly ski: SkiRoutingService,
private readonly router: RoadtripRouterService,
private readonly hikes: HikePlanService,
@InjectRepository(Tours) private readonly toursRepo: ToursRepository,
) {}
async createPaddle(userId: number, tripId: number, request: PaddleTourCreateRequest): Promise<HikeCreated> {
const asked = checkedRequest<PaddleTourCreateRequest>(paddleTourCreateRequestSchema, request);
const dayId = await this.dayOf(tripId, asked.day_id);
const planned = await this.paddle.route(
paddleRouteRequestSchema.parse({
legs: legsOf(asked.waypoints),
boat: asked.boat_type ?? 'kayak',
lake_style: asked.lake_style,
lock_policy: asked.lock_policy,
}),
);
const legs = planned.legs.map((leg, index) => {
if (leg.status === 'failed') throw legRefused(index, leg.code, 'on the water');
return leg;
});
const flat = joinedLine(legs.flatMap((leg) => leg.geometry.map(([lat, lng]): [number, number] => [lat, lng])));
const line = await this.withHeights(userId, flat);
const saved = this.planned(line, paddleMarksOf(legs));
return await this.save(
tripId,
paddleCommandOf(asked, hikeWaypointsOf(asked.waypoints), saved),
dayId,
asked,
saved,
);
}
async createSki(userId: number, tripId: number, request: SkiTourCreateRequest): Promise<HikeCreated> {
const asked = checkedRequest<SkiTourCreateRequest>(skiTourCreateRequestSchema, request);
const dayId = await this.dayOf(tripId, asked.day_id);
const planned = await this.ski.route(
skiRouteRequestSchema.parse({
legs: legsOf(asked.waypoints),
discipline: asked.discipline,
technique: asked.discipline === 'cross_country' ? (asked.technique ?? null) : null,
options: asked.options ?? {},
}),
);
const legs = planned.legs.map((leg, index) => {
if (leg.status === 'failed') throw legRefused(index, leg.code, 'on the piste data');
return leg;
});
const { line, seconds } = skiLineOf(legs);
// The piste data's heights where it has one for every point, else Valhalla's, as the planner reads them.
const measured = line.every((point) => point.length === 3)
? line
: await this.withHeights(
userId,
line.map(([lat, lng]): [number, number] => [lat, lng]),
);
const saved = this.planned(measured, null);
const command = skiCommandOf(asked, hikeWaypointsOf(asked.waypoints), saved, {
build: planned.build,
seconds,
legs: legs.length,
});
return await this.save(tripId, command, dayId, asked, saved);
}
/** The joined line as it is kept: whole with its heights, or none where a height is missing. */
private planned(line: GeometryPoint[], marks: SportPlanned['marks']): SportPlanned {
const heights = line.length >= 2 && line.every((point) => point.length === 3);
return { line: heights ? line : null, marks };
}
/** The line with the height of every point, or as it was where the heights could not all be read. */
private async withHeights(userId: number, flat: Array<[number, number]>): Promise<GeometryPoint[]> {
try {
return heightsOrNone(flat, await this.router.heights(userId, flat));
} catch (err: unknown) {
logWarn(`[SportTour] no heights: ${reasonOf(err)}`);
return heightsOrNone(flat, null);
}
}
/** The trip's day a tour is put on; a day of another trip is not found. */
private async dayOf(tripId: number, dayId: number | undefined): Promise<number | null> {
if (dayId === undefined) return null;
const day = await this.toursRepo.dayOfTrip(tripId, dayId);
if (!day) throw notFound('Day not found');
return day.id;
}
private async save(
tripId: number,
command: Parameters<HikePlanService['saveOnDay']>[1],
dayId: number | null,
asked: { start_time?: string },
saved: SportPlanned,
): Promise<HikeCreated> {
// Without its heights the tour waits for its way, as a hike does when the router did not answer.
const route: HikeRouteOutcome = saved.line
? { planned: true }
: { planned: false, why: 'router_unavailable', position: null };
return await this.hikes.saveOnDay(tripId, command, dayId, asked.start_time, route);
}
}
+180
View File
@@ -0,0 +1,180 @@
import { badRequest } from '../common/domain-error';
import { hikeWaypointsOf, type KeptWay } from './hike-plan.helpers';
import type { PlannedActivity, PlannedHike } from './hike-routing.service';
import type { TourCreateCommand } from './tours.service';
import {
HIKE_ALONG_CATEGORIES,
runMinutesAtPace,
TOUR_MAX_SNAP_M,
type HikeCreateRequest,
type HikeProposal,
type HikeProposeRequest,
type HikeRouteOutcome,
type HikeStop,
type TourPlanActivity,
type TourPlanCreateRequest,
type TourPoiCategory,
type TourProposal,
type TourProposeRequest,
type UnroutedHikePlan,
} from '@trek/shared';
import type { z } from 'zod';
/**
* The pure halves of a bike tour or a run an assistant plans over MCP
* (propose_tour, create_tour), on top of a hike's (hike-plan.helpers): the
* profile it is planned for, the places looked for along it, its time on the
* move, the proposal it answers and the write it makes. One plan and one save
* for every activity; only these differ.
*/
/** The activity and profile a request plans for, the planner's own profile where none is named. */
export function plannedActivityOf(request: {
activity: TourPlanActivity;
bike_profile?: PlannedActivity['profile'];
run_profile?: PlannedActivity['profile'];
}): PlannedActivity {
if (request.activity === 'bike') {
const profile = request.bike_profile;
return {
activity: 'bike',
profile: profile === 'road' || profile === 'gravel' || profile === 'mtb' ? profile : 'touring',
};
}
return { activity: 'run', profile: request.run_profile === 'trail' ? 'trail' : 'running' };
}
/** What a proposal looks for along the way, by activity: a hike its summits and huts, a ride and a run what they stop for. */
export const ALONG_CATEGORIES: Readonly<Record<'hike' | TourPlanActivity, readonly TourPoiCategory[]>> = {
hike: HIKE_ALONG_CATEGORIES,
bike: ['drinking_water', 'bike_repair', 'food', 'viewpoint'],
run: ['drinking_water', 'toilets', 'viewpoint', 'park'],
};
/** A request of propose_tour as a hike's proposal reads it: the same points, day and words, no hiking limit. */
export function asHikeProposal({
activity: _activity,
bike_profile: _bike,
run_profile: _run,
run_pace_seconds_per_km: _pace,
...request
}: TourProposeRequest): HikeProposeRequest {
return request;
}
/** A request of create_tour as a hike's create reads it: the same points, day, words and planned time. */
export function asHikeCreate({
activity: _activity,
bike_profile: _bike,
run_profile: _run,
run_pace_seconds_per_km: _pace,
...request
}: TourPlanCreateRequest): HikeCreateRequest {
return request;
}
/**
* A bike tour's or a run's time on the move, in whole minutes: a ride the
* router's for its profile, a run its distance at the runner's pace and
* nothing else (null without a pace, never the router's walking time). Null
* where no way was planned.
*/
export function movingMinutesOf(
activity: PlannedActivity,
pace: number | null | undefined,
{ plan }: PlannedHike,
): number | null {
if (plan.kind !== 'routed') return null;
if (activity.activity === 'bike') return plan.duration_minutes;
return pace == null ? null : runMinutesAtPace(plan.distance_m / 1000, pace);
}
/**
* The proposal of a bike tour or a run, from a hike's proposal of the same
* points timed by its own time: its activity, profile and pace, how its time
* was reckoned, and nothing of a hike's limit, preferences or grades.
*/
export function tourProposalOf(
base: HikeProposal,
request: TourProposeRequest,
activity: PlannedActivity,
): TourProposal {
const bike = activity.activity === 'bike';
const pace = bike ? null : (request.run_pace_seconds_per_km ?? null);
let basis: TourProposal['duration_basis'] = null;
if (base.duration_minutes !== null) basis = bike ? 'router' : 'pace';
return {
...base,
activity: activity.activity,
bike_profile: bike ? activity.profile : null,
run_profile: bike ? null : activity.profile,
run_pace_seconds_per_km: pace,
duration_basis: basis,
max_hiking_difficulty: null,
hiking_preferences: null,
sac: null,
} as TourProposal;
}
/**
* The write of a bike tour or a run created from its points, as the
* planner's save writes one: the way it keeps with its heights, its time on
* the move, its profile (and a run's pace), and nothing of a hike's.
*/
export function tourCreateCommandOf(
request: TourPlanCreateRequest,
points: readonly HikeStop[],
way: KeptWay,
activity: PlannedActivity,
minutes: number | null,
): TourCreateCommand {
const bike = activity.activity === 'bike';
return {
name: request.name,
description: request.description,
tour_type: activity.activity,
route_geometry: way.line,
duration_seconds: way.line && minutes !== null ? minutes * 60 : null,
max_hiking_difficulty: null,
hiking_preferences: null,
bike_profile: bike ? activity.profile : null,
run_profile: bike ? null : activity.profile,
run_pace_seconds_per_km: bike ? null : (request.run_pace_seconds_per_km ?? null),
...(request.planned_duration_minutes !== undefined
? { planned_duration_minutes: request.planned_duration_minutes }
: {}),
waypoints: hikeWaypointsOf(points),
};
}
/** Why no way was planned for a ride or a run, in words that say what to do about it. */
const UNPLANNED: Readonly<Record<UnroutedHikePlan['why'], (named: string, position: number | null) => string>> = {
no_valhalla: (named) => `TREK has no Valhalla router here to plan ${named} with its profile.`,
router_unavailable: () => 'The router did not answer, for the way or for its heights; try again in a moment.',
no_way: (named) => `No way for ${named} of this profile joins these points: try another profile or move the points.`,
point_off_the_way: (_named, position) =>
`Point ${position ?? ''} is further than ${TOUR_MAX_SNAP_M} m from any way: move it onto a way.`,
too_long: (named) => `The way is too long to plan as ${named}: split it into shorter tours.`,
};
/** The refusal of a bike tour or a run whose way could not be planned: nothing is saved. */
export function unplannedTourMessage(
{ why, position }: Pick<UnroutedHikePlan, 'why' | 'position'>,
activity: TourPlanActivity,
): string {
const named = activity === 'bike' ? 'a bike tour' : 'a run';
return `${UNPLANNED[why](named, position)} Nothing was saved.`;
}
/** Whether a way that was not planned refuses the save: every reason but a router that did not answer. */
export function refusesSave(route: HikeRouteOutcome): route is Extract<HikeRouteOutcome, { planned: false }> {
return 'why' in route && route.why !== 'router_unavailable';
}
/** A request checked whole, its refinements included: an MCP tool reads only its schema's shape. */
export function checkedRequest<T>(schema: z.ZodType<T>, value: unknown): T {
const result = schema.safeParse(value);
if (result.error) throw badRequest(result.error.issues.map((issue) => issue.message).join('; '));
return result.data as T;
}
+121
View File
@@ -0,0 +1,121 @@
import { ADDON_IDS } from '../../addons';
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
import {
McpController,
Tool,
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
TOOL_ANNOTATIONS_READONLY,
ok,
type McpContext,
} from '../../nest-mcp';
import { addonGate } from '../addons/addon-gate';
import { AddonsService } from '../addons/addons.service';
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
import { TripAccessService } from '../trip-membership/trip-access.service';
import { HikePlanService } from './hike-plan.service';
import { SportTourCreateService } from './sport-tour-create.service';
import {
idSchema,
paddleTourCreateRequestSchema,
skiTourCreateRequestSchema,
tourPlanCreateRequestSchema,
tourProposeRequestSchema,
type PaddleTourCreateRequest,
type SkiTourCreateRequest,
type TourPlanCreateRequest,
type TourProposeRequest,
} from '@trek/shared';
/** What every create here says of the day it may be put on, and of where to go on from it. */
const ON_A_DAY =
'With day_id the tour is put on that day of the trip in the same write, start_time kept as the start of that visit (which needs day editing permission too); assignment names the visit, null without a day. The answer is the tour as list_tours reads it (tour.place_id is the tour id, its revision 1), route and assignment. Put it on a day later with assign_place_to_day, link it to the packing list with link_tour_packing, export it with export_tour_gpx. Needs place editing permission on the trip. Create it only after the traveller said yes.';
/**
* Every tour type besides a hike and a city walk planned and saved with the
* traveller over MCP: a bike tour or a run proposed and created through the
* hike's own plan and save (HikePlanService, one path for every activity on
* land), a paddle or ski tour planned with plan_paddle_route or
* plan_ski_route saved through SportTourCreateService. A proposal reads only;
* a create writes through the creation the planner's save uses, with
* 'place_edit' on the trip as REST asks (ToursController), and 'day_edit' as
* well for a tour put on a day (AssignmentsController). A refusal of the
* service is a DomainError, which the registry answers as an error result
* with the text REST sends.
*/
@McpController()
export class TourPlanMcp {
constructor(
private readonly hikes: HikePlanService,
private readonly sports: SportTourCreateService,
private readonly access: TripAccessService,
private readonly guards: McpToolGuardsService,
// Read by the addon gate of every tool here.
readonly addons: AddonsService,
) {}
/** Whether the user may create a tour in the trip, and put it on a day where one is named. */
private async mayCreate(tripId: number, userId: number, dayId: number | undefined): Promise<boolean> {
if (!(await this.guards.hasTripPermission('place_edit', tripId, userId))) return false;
// Putting it on a day is what REST's assignment route asks 'day_edit' for.
return dayId === undefined || (await this.guards.hasTripPermission('day_edit', tripId, userId));
}
@Tool({
name: 'propose_tour',
description:
"Plan a bike tour (activity bike) or a run (activity run) for a trip and show it to the traveller, without saving anything; give it a name. A hike is planned with propose_hike, a city walk with propose_city_walk, a paddle tour with plan_paddle_route, a ski or winter tour with plan_ski_route. The way runs through waypoints in order (the start, the points on the way, the end; with round_trip back to the start), planned by TREK's Valhalla router as the tour planner plans it for the profile: a bike tour's bike_profile touring (paved ways, cycle paths and quiet roads, for a city or trekking bike, the default), road (asphalt only, a road bike), gravel (gravel and farm tracks) or mtb (rough tracks and trails, a mountain bike); a run's run_profile running (runnable, mostly paved ways, the default) or trail (forest tracks and natural paths up to T2). Pick the profile from what the traveller rides or how they like to run, and ask when it is not clear. A bike tour's time (duration_minutes, duration_basis router) is the router's riding time for its profile; a run's is its distance at run_pace_seconds_per_km, the runner's own pace (duration_basis pace), and a run without a pace has no time: ask for the pace. The answer gives distance_m, ascent_m, descent_m, min_ele_m, max_ele_m, high_point, every point with at_m, snapped_m, minutes and, with start_time, its arrival, and along: water, food, toilets, viewpoints (a bike repair shop on a ride, a park on a run) near the way. With day_id or date, schedule gives the day with sunrise, sunset and the weather by the hour, and warnings name a start in the dark, an arrival after sunset, thunder or rain. Where no way was planned, route says why as propose_hike does (no_valhalla, router_unavailable, no_way, point_off_the_way, too_long). To compare ways, propose each with its own variant_label and along false, the one you recommend first. The chat shows the route, its profile, times and weather as a card: never list coordinates or the figures, sum it up in a sentence. Create it with create_tour only after the traveller said yes.",
inputSchema: { tripId: idSchema, ...tourProposeRequestSchema.shape },
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'read' },
})
async proposeTour({ tripId, ...request }: { tripId: number } & TourProposeRequest, ctx: McpContext) {
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
return ok(await this.hikes.proposeTour(ctx.userId, tripId, request));
}
@Tool({
name: 'create_tour',
description: `Create a bike tour or a run in a trip from points the traveller confirmed, usually the name, activity, profile and waypoints of a proposal of propose_tour with its round_trip. A run is created only with run_pace_seconds_per_km, the runner's pace. It is saved the way the planner saves one: a tour of type bike or run with its points in order, the way planned by the same router for the same profile and kept whole with its heights, its distance, ascent, descent and time (a bike tour the router's riding time, a run its distance at the pace), its bike_profile or run_profile and pace, and planned_duration_minutes (the time out, breaks included) where given. Where the router did not answer, for the way or its heights (route planned false, why router_unavailable), the tour is saved with its points only (route_pending true) and TREK plans the way when someone opens it in the planner. Any other reason refuses the tour with why, and nothing is saved. ${ON_A_DAY}`,
inputSchema: { tripId: idSchema.describe('The trip to create the tour in'), ...tourPlanCreateRequestSchema.shape },
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'write' },
})
async createTour({ tripId, ...request }: { tripId: number } & TourPlanCreateRequest, ctx: McpContext) {
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
if (!(await this.mayCreate(tripId, ctx.userId, request.day_id))) return permissionDenied();
return ok(await this.hikes.createTour(ctx.userId, tripId, request));
}
@Tool({
name: 'create_paddle_tour',
description: `Create a paddle tour in a trip from a plan of plan_paddle_route the traveller confirmed: waypoints are the put-in, the points on the way and the take-out (the from of the first leg and the to of every leg, in order), with the boat_type, lake_style and lock_policy the plan was asked with, and water_context (river or lake), which the tour needs. Each leg is planned again on the water by the same router and the tour is saved as the planner saves one: its points, the whole line with its heights, its distance and its time on the move by the planner's estimate (water at paddle_speed_kmh, the boat's starting speed when left out, each portage the router carries round at portage_speed_kmh, locks without a time of their own). A leg that cannot be planned on the water refuses the tour and nothing is saved. Where the heights could not be read the tour is saved with its points only (route_pending true). ${ON_A_DAY}`,
inputSchema: {
tripId: idSchema.describe('The trip to create the tour in'),
...paddleTourCreateRequestSchema.shape,
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'write' },
})
async createPaddleTour({ tripId, ...request }: { tripId: number } & PaddleTourCreateRequest, ctx: McpContext) {
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
if (!(await this.mayCreate(tripId, ctx.userId, request.day_id))) return permissionDenied();
return ok(await this.sports.createPaddle(ctx.userId, tripId, request));
}
@Tool({
name: 'create_ski_tour',
description: `Create a ski or winter tour in a trip from a plan of plan_ski_route the traveller confirmed: waypoints are the start, the points on the way and the end (the from of the first leg and the to of every leg, in order), with the discipline, technique (cross_country only, and needed there) and options the plan was asked with. Each leg is planned again on the piste data by the same router and the tour is saved as the planner saves one: its points, the whole line with its heights, its distance, climb and descent, the piste router's time (skiing, lifts, waiting and walking), its discipline and options and the piste data build it was planned on. A leg that cannot be planned refuses the tour and nothing is saved (loading: the ski area is still being downloaded, try again in a moment). Where the heights could not be read the tour is saved with its points only (route_pending true). ${ON_A_DAY}`,
inputSchema: { tripId: idSchema.describe('The trip to create the tour in'), ...skiTourCreateRequestSchema.shape },
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'write' },
})
async createSkiTour({ tripId, ...request }: { tripId: number } & SkiTourCreateRequest, ctx: McpContext) {
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
if (!(await this.mayCreate(tripId, ctx.userId, request.day_id))) return permissionDenied();
return ok(await this.sports.createSki(ctx.userId, tripId, request));
}
}
+12 -1
View File
@@ -21,11 +21,13 @@ import { NotificationsModule } from '../notifications/notifications.module';
import { OverpassModule } from '../overpass/overpass.module';
import { PackingModule } from '../packing/packing.module';
import { PaddleObstaclesModule } from '../paddle-obstacles/paddle-obstacles.module';
import { PaddleRoutingModule } from '../paddle-routing/paddle-routing.module';
import { PermissionsModule } from '../permissions/permissions.module';
import { PlaceImportModule } from '../place-import/place-import.module';
import { PlacesModule } from '../places/places.module';
import { RoadtripModule } from '../roadtrip/roadtrip.module';
import { SchedulingModule } from '../scheduling/scheduling.module';
import { SkiRoutingModule } from '../ski-routing/ski-routing.module';
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
import { WandererModule } from '../wanderer/wanderer.module';
import { WeatherModule } from '../weather/weather.module';
@@ -38,6 +40,7 @@ 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 { SportTourCreateService } from './sport-tour-create.service';
import { TourActivitiesController } from './tour-activities.controller';
import { TourActivitiesMcp } from './tour-activities.mcp';
import { TourActivitiesService } from './tour-activities.service';
@@ -64,6 +67,7 @@ import { TourPackingMcp } from './tour-packing.mcp';
import { PaddleCheckCache } from './tour-paddle-check.cache';
import { TourPaddleCheckService } from './tour-paddle-check.service';
import { TourPaddlePlanService } from './tour-paddle-plan.service';
import { TourPlanMcp } from './tour-plan.mcp';
import { TourPoiSearchController } from './tour-poi-search.controller';
import { TourPoiSearchService } from './tour-poi-search.service';
import { TourSkiController } from './tour-ski.controller';
@@ -102,7 +106,9 @@ import { Module } from '@nestjs/common';
* the same writes, its way planned on the server by HikeRoutingService, 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
* AssignmentsService in the same write. A bike tour or a run goes the same
* way for its profile, and a paddle or ski tour an assistant planned is saved
* after PaddleRoutingModule's or SkiRoutingModule's router planned its legs again. A
* change to a saved city walk an assistant prepares for review is laid onto
* its saved points and planned on foot by the same router, and saves nothing
* (MCP-T02); once the traveller
@@ -155,6 +161,9 @@ import { Module } from '@nestjs/common';
SchedulingModule,
// A proposed hike's day reads the detailed weather at its highest point: sun, hours and warnings.
WeatherModule,
// A paddle or ski tour the assistant planned is planned again by its own router when it is saved.
PaddleRoutingModule,
SkiRoutingModule,
MikroOrmModule.forFeature([
CollectionTours,
Tours,
@@ -212,6 +221,7 @@ import { Module } from '@nestjs/common';
CityWalkBriefingService,
HikeRoutingService,
HikePlanService,
SportTourCreateService,
TourChangePreviewService,
TourChangeSaveService,
TourChangeUndoService,
@@ -227,6 +237,7 @@ import { Module } from '@nestjs/common';
TourWalkImportMcp,
CityWalkMcp,
HikePlanMcp,
TourPlanMcp,
TourChangeMcp,
TourChangeUndoMcp,
TourActivitiesMcp,