mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
feat(roadtrip): plan and edit trips through MCP without a browser
This commit is contained in:
@@ -11,6 +11,8 @@ import {
|
||||
placeImportListRequestSchema,
|
||||
placeWebsiteSchema,
|
||||
roadtripStopTypeSchema,
|
||||
roadtripGpxImportSchema,
|
||||
type RoadtripGpxImport,
|
||||
type RoadtripStopType,
|
||||
} from '@trek/shared';
|
||||
import { z } from 'zod';
|
||||
@@ -168,9 +170,9 @@ export class PlacesMcp {
|
||||
category_id: z.number().int().positive().optional().describe('Category ID — use list_categories'),
|
||||
price: z.number().optional(),
|
||||
currency: z.string().length(3).optional(),
|
||||
place_time: z.string().max(50).optional().describe('Scheduled time (e.g. "09:00")'),
|
||||
end_time: z.string().max(50).optional().describe('End time (e.g. "11:00")'),
|
||||
duration_minutes: z.number().int().positive().optional(),
|
||||
place_time: z.string().max(50).nullable().optional().describe('Scheduled time (e.g. "09:00"); null clears it'),
|
||||
end_time: z.string().max(50).nullable().optional().describe('End time (e.g. "11:00"); null clears it'),
|
||||
duration_minutes: z.number().int().nonnegative().nullable().optional().describe('Stay duration in minutes; null clears it'),
|
||||
notes: z.string().max(2000).optional(),
|
||||
website: placeWebsiteSchema.optional(),
|
||||
phone: z.string().max(50).optional(),
|
||||
@@ -188,8 +190,8 @@ export class PlacesMcp {
|
||||
async updatePlace(
|
||||
{ tripId, placeId, name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, image_url, transport_mode, osm_id, google_place_id, google_ftid, stop_type, fill_percent }: {
|
||||
tripId: number; placeId: number; name?: string; description?: string; lat?: number; lng?: number;
|
||||
address?: string; category_id?: number; price?: number; currency?: string; place_time?: string;
|
||||
end_time?: string; duration_minutes?: number; notes?: string; website?: string; phone?: string;
|
||||
address?: string; category_id?: number; price?: number; currency?: string; place_time?: string | null;
|
||||
end_time?: string | null; duration_minutes?: number | null; notes?: string; website?: string; phone?: string;
|
||||
image_url?: string | null;
|
||||
transport_mode?: 'walking' | 'driving' | 'cycling' | 'transit' | 'flight'; osm_id?: string;
|
||||
google_place_id?: string; google_ftid?: string; stop_type?: RoadtripStopType | null;
|
||||
@@ -354,6 +356,28 @@ export class PlacesMcp {
|
||||
return ok({ places: result.places, count: result.places.length, listName: result.listName, skipped: result.skipped });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'import_trip_gpx',
|
||||
description: 'Import GPX waypoints, routes and tracks as places in a trip. Uses the same importer as the file upload. Imported tracks retain their geometry and can be followed with add_route_vias. Does not assign places to days. Use list_places for their ids and geometry, then assign_place_to_day and the Roadtrip tools to plan visits. Existing importer deduplication also applies.',
|
||||
inputSchema: roadtripGpxImportSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
access: { group: 'places', mode: 'write' },
|
||||
})
|
||||
async importGpx(input: RoadtripGpxImport, ctx: McpContext) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.db.canAccessTrip(input.tripId, ctx.userId)) return noAccess();
|
||||
if (!this.guards.hasTripPermission('place_edit', input.tripId, ctx.userId)) return permissionDenied();
|
||||
if (!input.importWaypoints && !input.importRoutes && !input.importTracks) return errorResult('No import types selected.');
|
||||
try {
|
||||
const imported = this.places.importGpx(String(input.tripId), Buffer.from(input.gpx, 'utf8'), { importWaypoints: input.importWaypoints, importRoutes: input.importRoutes, importTracks: input.importTracks, defaultName: input.name });
|
||||
if (!imported) return errorResult('No matching places found in GPX.');
|
||||
for (const place of imported.places) this.guards.safeBroadcast(input.tripId, 'place:created', { place });
|
||||
return ok(imported);
|
||||
} catch {
|
||||
return errorResult('Could not import GPX. Check the XML and coordinates.');
|
||||
}
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'export_trip_gpx',
|
||||
description: 'Export a trip as GPX text: its places as waypoints, any imported routes as tracks, and each planned day as a route in visiting order. This is the format handhelds and offline map apps (Organic Maps, OsmAnd, Garmin) read. Prefer export_trip_ics when the user wants the itinerary in a calendar instead.',
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
|
||||
import type Database from 'better-sqlite3';
|
||||
|
||||
type Tone = 'default' | 'success' | 'warn' | 'danger';
|
||||
|
||||
interface RouteWaypointIn {
|
||||
lat: number;
|
||||
lng: number;
|
||||
name?: string;
|
||||
placeId?: number;
|
||||
}
|
||||
|
||||
interface RouteLegOut {
|
||||
distance: number;
|
||||
duration: number;
|
||||
note?: string;
|
||||
}
|
||||
|
||||
interface RouteViaOut {
|
||||
lat: number;
|
||||
lng: number;
|
||||
label?: string;
|
||||
tone: Tone;
|
||||
dwellSeconds?: number;
|
||||
}
|
||||
|
||||
export interface PluginRouteOut {
|
||||
pluginId: string;
|
||||
profile: string;
|
||||
coordinates: Array<[number, number]>;
|
||||
distance: number;
|
||||
duration: number;
|
||||
legs: RouteLegOut[];
|
||||
viaPoints: RouteViaOut[];
|
||||
}
|
||||
|
||||
const TONES: ReadonlySet<string> = new Set(['default', 'success', 'warn', 'danger']);
|
||||
export const PROFILE_RE = /^[a-z][a-z0-9-]{0,23}$/;
|
||||
const MAX_WAYPOINTS = 30;
|
||||
const MAX_COORDINATES = 10_000; // vertex budget for the returned geometry
|
||||
const MAX_VIAS = 40;
|
||||
const MAX_DWELL_S = 86_400; // a "stop" longer than a day is nonsense data
|
||||
const cap = (v: unknown, n: number): string => stripEmoji(String(v ?? '')).slice(0, n);
|
||||
|
||||
function validCoord(lat: unknown, lng: unknown): boolean {
|
||||
const a = Number(lat);
|
||||
const b = Number(lng);
|
||||
return Number.isFinite(a) && Number.isFinite(b) && a >= -90 && a <= 90 && b >= -180 && b <= 180;
|
||||
}
|
||||
|
||||
export function readWaypoints(raw: unknown): RouteWaypointIn[] | null {
|
||||
if (!Array.isArray(raw) || raw.length < 2 || raw.length > MAX_WAYPOINTS) return null;
|
||||
const out: RouteWaypointIn[] = [];
|
||||
for (const w of raw as Array<Record<string, unknown>>) {
|
||||
if (!w || typeof w !== 'object' || !validCoord(w.lat, w.lng)) return null;
|
||||
const name = w.name != null ? cap(w.name, 120) : undefined;
|
||||
const placeId = Number.isInteger(w.placeId) ? (w.placeId as number) : undefined;
|
||||
out.push({
|
||||
lat: Number(w.lat),
|
||||
lng: Number(w.lng),
|
||||
...(name ? { name } : {}),
|
||||
...(placeId !== undefined ? { placeId } : {}),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function nonNeg(v: unknown): number | null {
|
||||
const n = Number(v);
|
||||
return Number.isFinite(n) && n >= 0 ? n : null;
|
||||
}
|
||||
|
||||
export function normalize(
|
||||
pluginId: string,
|
||||
profile: string,
|
||||
waypointCount: number,
|
||||
raw: unknown,
|
||||
): PluginRouteOut | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const r = raw as Record<string, unknown>;
|
||||
|
||||
if (!Array.isArray(r.coordinates) || r.coordinates.length < 2 || r.coordinates.length > MAX_COORDINATES) return null;
|
||||
const coordinates: Array<[number, number]> = [];
|
||||
for (const c of r.coordinates) {
|
||||
if (!Array.isArray(c) || !validCoord(c[0], c[1])) return null;
|
||||
coordinates.push([Number(c[0]), Number(c[1])]);
|
||||
}
|
||||
|
||||
const distance = nonNeg(r.distance);
|
||||
const duration = nonNeg(r.duration);
|
||||
if (distance == null || duration == null) return null;
|
||||
if (!Array.isArray(r.legs) || r.legs.length !== waypointCount - 1) return null;
|
||||
const legs: RouteLegOut[] = [];
|
||||
for (const l of r.legs as Array<Record<string, unknown>>) {
|
||||
if (!l || typeof l !== 'object') return null;
|
||||
const legDistance = nonNeg(l.distance);
|
||||
const legDuration = nonNeg(l.duration);
|
||||
if (legDistance == null || legDuration == null) return null;
|
||||
const note = l.note != null ? cap(l.note, 120) : undefined;
|
||||
legs.push({ distance: legDistance, duration: legDuration, ...(note ? { note } : {}) });
|
||||
}
|
||||
const viaPoints: RouteViaOut[] = [];
|
||||
if (Array.isArray(r.viaPoints)) {
|
||||
for (const v of (r.viaPoints as Array<Record<string, unknown>>).slice(0, MAX_VIAS * 4)) {
|
||||
if (viaPoints.length >= MAX_VIAS) break;
|
||||
if (!v || typeof v !== 'object' || !validCoord(v.lat, v.lng)) continue;
|
||||
const dwell = Number(v.dwellSeconds);
|
||||
const label = v.label != null ? cap(v.label, 80) : undefined;
|
||||
viaPoints.push({
|
||||
lat: Number(v.lat),
|
||||
lng: Number(v.lng),
|
||||
...(label ? { label } : {}),
|
||||
tone: TONES.has(v.tone as string) ? (v.tone as Tone) : 'default',
|
||||
...(Number.isFinite(dwell) && dwell >= 0 ? { dwellSeconds: Math.min(Math.round(dwell), MAX_DWELL_S) } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { pluginId, profile, coordinates, distance, duration, legs, viaPoints };
|
||||
}
|
||||
|
||||
export function declaredProfiles(conn: Database.Database, pluginId: string): string[] {
|
||||
try {
|
||||
const row = conn.prepare('SELECT capabilities FROM plugins WHERE id = ?').get(pluginId) as
|
||||
| { capabilities?: string }
|
||||
| undefined;
|
||||
const c = JSON.parse(row?.capabilities || '{}') as { routeProfiles?: Array<{ id?: unknown }> };
|
||||
if (!Array.isArray(c.routeProfiles)) return [];
|
||||
return c.routeProfiles
|
||||
.map((p) => (p && typeof p === 'object' && typeof p.id === 'string' ? p.id : ''))
|
||||
.filter((id) => PROFILE_RE.test(id));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
import { Body, Controller, Param, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { DatabaseService } from '../../database/database.service';
|
||||
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
import { PluginRouteDto } from '../plugins.dto';
|
||||
import { normalize, declaredProfiles, readWaypoints, PROFILE_RE, type PluginRouteOut } from './plugin-route-normalize';
|
||||
export type { PluginRouteOut } from './plugin-route-normalize';
|
||||
|
||||
/**
|
||||
* POST /api/plugin-routes/:pluginId/:profileId — ask ONE routeProvider plugin to
|
||||
@@ -27,126 +27,6 @@ import { PluginRouteDto } from '../plugins.dto';
|
||||
* the invoke timeout is 20 s — well above the 5 s of the render-blocking hooks;
|
||||
* the client shows the straight-line route until the result lands.
|
||||
*/
|
||||
type Tone = 'default' | 'success' | 'warn' | 'danger';
|
||||
|
||||
interface RouteWaypointIn {
|
||||
lat: number;
|
||||
lng: number;
|
||||
name?: string;
|
||||
placeId?: number;
|
||||
}
|
||||
|
||||
interface RouteLegOut {
|
||||
distance: number;
|
||||
duration: number;
|
||||
note?: string;
|
||||
}
|
||||
|
||||
interface RouteViaOut {
|
||||
lat: number;
|
||||
lng: number;
|
||||
label?: string;
|
||||
tone: Tone;
|
||||
dwellSeconds?: number;
|
||||
}
|
||||
|
||||
export interface PluginRouteOut {
|
||||
pluginId: string;
|
||||
profile: string;
|
||||
coordinates: Array<[number, number]>;
|
||||
distance: number;
|
||||
duration: number;
|
||||
legs: RouteLegOut[];
|
||||
viaPoints: RouteViaOut[];
|
||||
}
|
||||
|
||||
const TONES: ReadonlySet<string> = new Set(['default', 'success', 'warn', 'danger']);
|
||||
const PROFILE_RE = /^[a-z][a-z0-9-]{0,23}$/;
|
||||
const MAX_WAYPOINTS = 30;
|
||||
const MAX_COORDINATES = 10_000; // vertex budget for the returned geometry
|
||||
const MAX_VIAS = 40;
|
||||
const MAX_DWELL_S = 86_400; // a "stop" longer than a day is nonsense data
|
||||
const cap = (v: unknown, n: number): string => stripEmoji(String(v ?? '')).slice(0, n);
|
||||
|
||||
function validCoord(lat: unknown, lng: unknown): boolean {
|
||||
const a = Number(lat);
|
||||
const b = Number(lng);
|
||||
return Number.isFinite(a) && Number.isFinite(b) && a >= -90 && a <= 90 && b >= -180 && b <= 180;
|
||||
}
|
||||
|
||||
/** The caller's waypoint list — invalid input is a client bug, answered with null. */
|
||||
function readWaypoints(raw: unknown): RouteWaypointIn[] | null {
|
||||
if (!Array.isArray(raw) || raw.length < 2 || raw.length > MAX_WAYPOINTS) return null;
|
||||
const out: RouteWaypointIn[] = [];
|
||||
for (const w of raw as Array<Record<string, unknown>>) {
|
||||
if (!w || typeof w !== 'object' || !validCoord(w.lat, w.lng)) return null;
|
||||
const name = w.name != null ? cap(w.name, 120) : undefined;
|
||||
const placeId = Number.isInteger(w.placeId) ? (w.placeId as number) : undefined;
|
||||
out.push({ lat: Number(w.lat), lng: Number(w.lng), ...(name ? { name } : {}), ...(placeId !== undefined ? { placeId } : {}) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function nonNeg(v: unknown): number | null {
|
||||
const n = Number(v);
|
||||
return Number.isFinite(n) && n >= 0 ? n : null;
|
||||
}
|
||||
|
||||
/** The plugin's answer — a malformed route is rejected whole (null), never patched. */
|
||||
function normalize(pluginId: string, profile: string, waypointCount: number, raw: unknown): PluginRouteOut | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const r = raw as Record<string, unknown>;
|
||||
|
||||
if (!Array.isArray(r.coordinates) || r.coordinates.length < 2 || r.coordinates.length > MAX_COORDINATES) return null;
|
||||
const coordinates: Array<[number, number]> = [];
|
||||
for (const c of r.coordinates) {
|
||||
if (!Array.isArray(c) || !validCoord(c[0], c[1])) return null;
|
||||
coordinates.push([Number(c[0]), Number(c[1])]);
|
||||
}
|
||||
|
||||
const distance = nonNeg(r.distance);
|
||||
const duration = nonNeg(r.duration);
|
||||
if (distance == null || duration == null) return null;
|
||||
|
||||
// Exactly one leg per waypoint pair — a mismatched list means the plugin routed
|
||||
// something other than the request, and mis-keyed legs would attach wrong times
|
||||
// to the sidebar connectors.
|
||||
if (!Array.isArray(r.legs) || r.legs.length !== waypointCount - 1) return null;
|
||||
const legs: RouteLegOut[] = [];
|
||||
for (const l of r.legs as Array<Record<string, unknown>>) {
|
||||
if (!l || typeof l !== 'object') return null;
|
||||
const legDistance = nonNeg(l.distance);
|
||||
const legDuration = nonNeg(l.duration);
|
||||
if (legDistance == null || legDuration == null) return null;
|
||||
const note = l.note != null ? cap(l.note, 120) : undefined;
|
||||
legs.push({ distance: legDistance, duration: legDuration, ...(note ? { note } : {}) });
|
||||
}
|
||||
|
||||
// Via points are decorative (charging stops on the drawn route) — a bad entry
|
||||
// is dropped individually, it can't invalidate the route. Slice the raw array so
|
||||
// an all-invalid list can't force unbounded iteration (the output is MAX_VIAS,
|
||||
// but only valid entries advance that counter).
|
||||
const viaPoints: RouteViaOut[] = [];
|
||||
if (Array.isArray(r.viaPoints)) {
|
||||
for (const v of (r.viaPoints as Array<Record<string, unknown>>).slice(0, MAX_VIAS * 4)) {
|
||||
if (viaPoints.length >= MAX_VIAS) break;
|
||||
if (!v || typeof v !== 'object' || !validCoord(v.lat, v.lng)) continue;
|
||||
const dwell = Number(v.dwellSeconds);
|
||||
const label = v.label != null ? cap(v.label, 80) : undefined;
|
||||
viaPoints.push({
|
||||
lat: Number(v.lat),
|
||||
lng: Number(v.lng),
|
||||
...(label ? { label } : {}),
|
||||
// Raw-value enum check, same rationale as the marker tone guard.
|
||||
tone: TONES.has(v.tone as string) ? (v.tone as Tone) : 'default',
|
||||
...(Number.isFinite(dwell) && dwell >= 0 ? { dwellSeconds: Math.min(Math.round(dwell), MAX_DWELL_S) } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { pluginId, profile, coordinates, distance, duration, legs, viaPoints };
|
||||
}
|
||||
|
||||
@Controller('api/plugin-routes')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
export class PluginRoutesController {
|
||||
@@ -186,16 +66,3 @@ export class PluginRoutesController {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function declaredProfiles(conn: Database.Database, pluginId: string): string[] {
|
||||
try {
|
||||
const row = conn.prepare('SELECT capabilities FROM plugins WHERE id = ?').get(pluginId) as { capabilities?: string } | undefined;
|
||||
const c = JSON.parse(row?.capabilities || '{}') as { routeProfiles?: Array<{ id?: unknown }> };
|
||||
if (!Array.isArray(c.routeProfiles)) return [];
|
||||
return c.routeProfiles
|
||||
.map((p) => (p && typeof p === 'object' && typeof p.id === 'string' ? p.id : ''))
|
||||
.filter((id) => PROFILE_RE.test(id));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { DayBoundariesService } from './day-boundaries.service';
|
||||
import { RoadtripPreferencesService } from './roadtrip-preferences.service';
|
||||
import { RoadtripRouterService } from './roadtrip-router.service';
|
||||
import { RoadtripService } from './roadtrip.service';
|
||||
import { Injectable, HttpException } from '@nestjs/common';
|
||||
import { type RoadtripPreferences } from '@trek/shared';
|
||||
import {
|
||||
assembleRoadtrip,
|
||||
foldRouteRun,
|
||||
splitIntoRuns,
|
||||
spillChains,
|
||||
dayWindow,
|
||||
effectiveRangeKm,
|
||||
parseAvoid,
|
||||
type RoadtripStop,
|
||||
type PlanDay,
|
||||
type RoutedLeg,
|
||||
type SnappedWaypoint,
|
||||
type RouteAvoidClass,
|
||||
} from '@trek/shared/roadtrip';
|
||||
|
||||
interface StoredDay {
|
||||
id: number;
|
||||
day_number: number;
|
||||
date: string | null;
|
||||
title: string | null;
|
||||
default_transport_mode: string | null;
|
||||
}
|
||||
interface VisitRow {
|
||||
id: number;
|
||||
day_id: number;
|
||||
place_id: number;
|
||||
name: string;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
time: string | null;
|
||||
duration_minutes: number | null;
|
||||
end_day: number;
|
||||
leg_transport_mode: string | null;
|
||||
incoming_leg_transport_mode: string | null;
|
||||
stop_type: string | null;
|
||||
fill_percent: number | null;
|
||||
}
|
||||
const stopKey = (s: RoadtripStop) =>
|
||||
`${s.lat.toFixed(5)},${s.lng.toFixed(5)},${s.legMode ?? ''},${s.incomingLegMode ?? ''}`;
|
||||
|
||||
@Injectable()
|
||||
export class RoadtripPlanService {
|
||||
constructor(
|
||||
private readonly db: DatabaseService,
|
||||
private readonly settings: SettingsService,
|
||||
private readonly preferences: RoadtripPreferencesService,
|
||||
private readonly router: RoadtripRouterService,
|
||||
private readonly roadtrip: RoadtripService,
|
||||
private readonly boundaries: DayBoundariesService,
|
||||
) {}
|
||||
|
||||
context(tripId: number, userId: number) {
|
||||
if (!this.db.canAccessTrip(tripId, userId)) throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
const days = this.db.all<StoredDay>(
|
||||
'SELECT id, day_number, date, title, default_transport_mode FROM days WHERE trip_id = ? ORDER BY day_number',
|
||||
tripId,
|
||||
);
|
||||
const visits = this.db.all<VisitRow>(
|
||||
`SELECT a.id, a.day_id, a.place_id, p.name, p.lat, p.lng,
|
||||
COALESCE(a.assignment_time, p.place_time) AS time, p.duration_minutes, a.end_day,
|
||||
a.leg_transport_mode, a.incoming_leg_transport_mode, p.stop_type, p.fill_percent
|
||||
FROM day_assignments a JOIN days d ON d.id = a.day_id JOIN places p ON p.id = a.place_id
|
||||
WHERE d.trip_id = ? ORDER BY d.day_number, a.order_index, a.created_at`,
|
||||
tripId,
|
||||
);
|
||||
return {
|
||||
days,
|
||||
visits,
|
||||
settings: this.preferences.read(userId),
|
||||
profiles: this.router.profiles(),
|
||||
vias: this.roadtrip.listForTrip(tripId),
|
||||
tracks: this.roadtrip.tracksForTrip(tripId),
|
||||
boundaries: this.boundaries.list(tripId),
|
||||
};
|
||||
}
|
||||
|
||||
async calculate(tripId: number, userId: number, overrides?: RoadtripPreferences) {
|
||||
const context = this.context(tripId, userId);
|
||||
const preferences = { ...context.settings, ...overrides };
|
||||
const window = dayWindow(
|
||||
preferences.roadtrip_day_start,
|
||||
preferences.roadtrip_day_end,
|
||||
preferences.roadtrip_day_end_mode,
|
||||
);
|
||||
if (preferences.roadtrip_day_start && preferences.roadtrip_day_end && !window)
|
||||
throw new HttpException({ error: 'Day end must be later than day start.' }, 400);
|
||||
const plan: PlanDay[] = context.days.map((day) => ({
|
||||
dayId: day.id,
|
||||
dayNumber: day.day_number,
|
||||
date: day.date,
|
||||
title: day.title,
|
||||
stops: context.visits
|
||||
.filter((v) => v.day_id === day.id && v.lat !== null && v.lng !== null)
|
||||
.map((v, index) => ({
|
||||
assignmentId: v.id,
|
||||
ownerDayId: day.id,
|
||||
ownerIndex: index,
|
||||
placeId: v.place_id,
|
||||
name: v.name,
|
||||
lat: v.lat!,
|
||||
lng: v.lng!,
|
||||
time: v.time,
|
||||
dwellMinutes: v.duration_minutes,
|
||||
endDay: v.end_day === 1,
|
||||
legMode: v.leg_transport_mode,
|
||||
incomingLegMode: v.incoming_leg_transport_mode,
|
||||
stopType: v.stop_type,
|
||||
fillPercent: v.fill_percent,
|
||||
})),
|
||||
}));
|
||||
const allLegs: Record<string, RoutedLeg> = {};
|
||||
const snapByDay: Record<number, Record<string, SnappedWaypoint>> = {};
|
||||
const missedByDay: Record<number, RouteAvoidClass[]> = {};
|
||||
const failures: { fromAssignmentId: number; toAssignmentId: number; reason: string }[] = [];
|
||||
const avoid = parseAvoid(preferences.roadtrip_avoid);
|
||||
const connectDays = preferences.roadtrip_connect_days || window !== null;
|
||||
if (context.visits.length > 150)
|
||||
throw new HttpException({ error: 'This trip exceeds the 150-visit calculation limit.' }, 400);
|
||||
const asked = new Set<string>();
|
||||
const fetchRun = async (stops: RoadtripStop[], dayId: number, profile: string) => {
|
||||
const points: { lat: number; lng: number }[] = [];
|
||||
const stopAt: number[] = [];
|
||||
stops.forEach((stop, index) => {
|
||||
stopAt.push(points.length);
|
||||
points.push({ lat: stop.lat, lng: stop.lng });
|
||||
if (index < stops.length - 1)
|
||||
points.push(
|
||||
...context.vias
|
||||
.filter((v) => v.day_id === stop.ownerDayId && v.after_order_index === stop.ownerIndex)
|
||||
.sort((a, b) => a.sequence - b.sequence)
|
||||
.map((v) => ({ lat: v.lat, lng: v.lng })),
|
||||
);
|
||||
});
|
||||
const pairs = stops.slice(0, -1).map((from, index) => ({ from, to: stops[index + 1] }));
|
||||
pairs.forEach(({ from, to }) => asked.add(stopKey(from) + '>' + stopKey(to)));
|
||||
try {
|
||||
if (points.length > 100) throw new Error('Too many waypoints');
|
||||
const routed = await this.router.route(userId, tripId, dayId, points, profile, avoid);
|
||||
const legs = routed.parts.map((part, index) => ({
|
||||
...routed.leg.seg,
|
||||
...part,
|
||||
from: [points[index].lat, points[index].lng] as [number, number],
|
||||
to: [points[index + 1].lat, points[index + 1].lng] as [number, number],
|
||||
}));
|
||||
Object.assign(
|
||||
allLegs,
|
||||
foldRouteRun(stops, stopAt, { coordinates: routed.leg.line, legs, vias: routed.leg.vias }, profile),
|
||||
);
|
||||
missedByDay[dayId] = [...new Set([...(missedByDay[dayId] ?? []), ...routed.avoidMissed])];
|
||||
stops.forEach((stop, index) => {
|
||||
const snapped = routed.snapped?.[stopAt[index]];
|
||||
if (snapped) (snapByDay[stop.ownerDayId] ??= {})[stopKey(stop)] = snapped;
|
||||
});
|
||||
} catch {
|
||||
pairs.forEach(({ from, to }) =>
|
||||
failures.push({
|
||||
fromAssignmentId: from.assignmentId,
|
||||
toAssignmentId: to.assignmentId,
|
||||
reason:
|
||||
points.length > 100
|
||||
? 'More than 100 waypoints in this run.'
|
||||
: 'Routing provider could not calculate this run. Check the profile, connection and provider limits.',
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
for (const day of plan.filter((d) => d.stops.length > 1)) {
|
||||
const fallback = context.days.find((d) => d.id === day.dayId)?.default_transport_mode || 'driving';
|
||||
for (const run of splitIntoRuns(day.stops, (from) => from.legMode ?? fallback))
|
||||
await fetchRun(run.stops, day.dayId, run.mode);
|
||||
}
|
||||
const chains = window
|
||||
? plan.filter((d) => d.stops.length)
|
||||
: spillChains(
|
||||
plan.filter((d) => d.stops.length > 1),
|
||||
plan.filter((d) => d.stops.length < 2),
|
||||
(a, b) => allLegs[stopKey(a) + '>' + stopKey(b)],
|
||||
);
|
||||
let previous: RoadtripStop | undefined;
|
||||
for (const chain of chains) {
|
||||
const pairs = chain.stops.slice(0, -1).map((from, index) => ({ from, to: chain.stops[index + 1] }));
|
||||
if (connectDays && previous && chain.stops.length) pairs.push({ from: previous, to: chain.stops[0] });
|
||||
for (const { from, to } of pairs) {
|
||||
if (asked.has(stopKey(from) + '>' + stopKey(to))) continue;
|
||||
await fetchRun(
|
||||
[from, to],
|
||||
chain.dayId,
|
||||
from.legMode ?? context.days.find((d) => d.id === chain.dayId)?.default_transport_mode ?? 'driving',
|
||||
);
|
||||
}
|
||||
previous = chain.stops[chain.stops.length - 1] ?? previous;
|
||||
}
|
||||
const vehicleKind = preferences.roadtrip_vehicle || null;
|
||||
const rangeKm =
|
||||
effectiveRangeKm(
|
||||
vehicleKind,
|
||||
{
|
||||
tankLitres: preferences.roadtrip_tank_litres,
|
||||
litresPer100: preferences.roadtrip_litres_per_100,
|
||||
batteryKwh: preferences.roadtrip_battery_kwh,
|
||||
kwhPer100: preferences.roadtrip_kwh_per_100,
|
||||
degradationPercent: preferences.roadtrip_battery_degradation,
|
||||
},
|
||||
preferences.roadtrip_range_km,
|
||||
) || null;
|
||||
const calculated = assembleRoadtrip({
|
||||
plan: plan.filter((d) => d.stops.length > 1),
|
||||
quietDays: plan.filter((d) => d.stops.length < 2),
|
||||
window,
|
||||
allLegs,
|
||||
snapByDay,
|
||||
missedByDay,
|
||||
loading: false,
|
||||
limits: {
|
||||
legMinutes: preferences.roadtrip_leg_minutes || null,
|
||||
dayMinutes: preferences.roadtrip_day_minutes || null,
|
||||
rangeKm,
|
||||
fillPercent: preferences.roadtrip_fill_percent || null,
|
||||
},
|
||||
vehicleKind,
|
||||
connectDays,
|
||||
boundaries: context.boundaries,
|
||||
distanceUnit: this.settings.getUserSettings(userId).distance_unit === 'imperial' ? 'imperial' : 'metric',
|
||||
labels: { start: 'Continue journey', end: 'End of day' },
|
||||
});
|
||||
return {
|
||||
context,
|
||||
preferences,
|
||||
calculated,
|
||||
failures,
|
||||
omittedVisits: context.visits.filter((v) => v.lat === null || v.lng === null).map((v) => v.id),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, errorResult, type McpContext } from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { MapsService } from '../maps/maps.service';
|
||||
import { RoadtripPlanService } from './roadtrip-plan.service';
|
||||
import {
|
||||
roadtripPlanRequestSchema,
|
||||
roadtripCorridorRequestSchema,
|
||||
type RoadtripPlanRequest,
|
||||
type RoadtripCorridorRequest,
|
||||
} from '@trek/shared';
|
||||
import { corridorTiles, projectOntoRoute, simplifyLine } from '@trek/shared/roadtrip';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
const when = addonGate(ADDON_IDS.ROADTRIP);
|
||||
|
||||
@McpController()
|
||||
export class RoadtripPlanningMcp {
|
||||
constructor(
|
||||
private readonly plans: RoadtripPlanService,
|
||||
private readonly maps: MapsService,
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
name: 'get_roadtrip_context',
|
||||
description:
|
||||
'Read the saved roadtrip days, visits, pinned times, stays, stop types, fill levels, travel modes, via points, followed tracks and manual day endings. Includes your personal driving preferences. No routing request and no browser needed. Coordinates missing from a visit prevent it from being routed. Use calculate_roadtrip to get the derived day layout. Edit visits with the existing place and assignment tools; change their saved order with reorder_day_assignments. Settings affect your account; visits and manual boundaries affect the shared trip.',
|
||||
inputSchema: { tripId: z.number().int().positive() },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'trips', mode: 'read' },
|
||||
when,
|
||||
})
|
||||
async context({ tripId }: { tripId: number }, ctx: McpContext) {
|
||||
return ok(this.plans.context(tripId, ctx.userId));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'calculate_roadtrip',
|
||||
description:
|
||||
'Calculate a saved trip without an open browser, using the same daily scheduling and vehicle-range rules as the planner. Returns derived days, arrivals, departures, driving limits, fuel warnings, automatic pauses and routing failures. Fixed visit times retain priority; no accommodation or place is created. Optional settings are a read-only preview, not saved. Distances are metres, durations seconds, dwell times minutes. A failed leg or conflicting window means the output is incomplete: never present its totals as a complete route. Up to 150 legs; requests are paced for public routing servers and can take time. Existing place/assignment tools edit stops, stays and ordering, update_roadtrip_settings saves preferences, set_assignment_end_day and set_day_boundary set exceptions. Recalculate after changes. Plugin profiles follow installed route-provider permissions.',
|
||||
inputSchema: roadtripPlanRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'trips', mode: 'read' },
|
||||
when,
|
||||
})
|
||||
async calculate(input: RoadtripPlanRequest, ctx: McpContext) {
|
||||
const plan = await this.plans.calculate(input.tripId, ctx.userId, input.settings);
|
||||
const { calculated } = plan;
|
||||
return ok({
|
||||
complete: !plan.failures.length && !plan.omittedVisits.length && !calculated.dayWindowIssue,
|
||||
settings: plan.preferences,
|
||||
failures: plan.failures,
|
||||
omittedVisitIds: plan.omittedVisits,
|
||||
dayWindowIssue: calculated.dayWindowIssue,
|
||||
totalDistanceMetres: calculated.totalDistance,
|
||||
totalDurationSeconds: calculated.totalDuration,
|
||||
totalStops: calculated.totalStops,
|
||||
days: calculated.days.map((day) => ({
|
||||
dayId: day.dayId,
|
||||
dayNumber: day.dayNumber,
|
||||
date: day.date,
|
||||
title: day.title,
|
||||
stops: day.stops,
|
||||
schedule: day.schedule,
|
||||
legs: day.legs,
|
||||
distanceMetres: day.distance,
|
||||
durationSeconds: day.duration,
|
||||
driveWarnings: day.driveWarnings,
|
||||
dayWarning: day.dayWarning,
|
||||
avoidMissed: day.avoidMissed,
|
||||
dryPoints: day.dryPoints,
|
||||
...(input.includeGeometry ? { geometry: day.geometry } : {}),
|
||||
})),
|
||||
quietDays: calculated.quietDays,
|
||||
});
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'search_roadtrip_corridor',
|
||||
description:
|
||||
'Search for fuel, charging, rest areas, campsites, food, sights or accommodation along a calculated roadtrip day, without a browser. Uses the routed road, not a straight line. Returns distance along the route and distance from it. Search rectangles are paged in batches of six; continue with nextOffset until null for full coverage. Optional name, socket family and minimum power filter the matches; missing charging details mean unknown. Does not add stops. Add a chosen place and assign it to the appropriate stored day, preserving any via anchors. Routing failures refuse the corridor search rather than searching an invented line.',
|
||||
inputSchema: roadtripCorridorRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'trips', mode: 'read' },
|
||||
when,
|
||||
})
|
||||
async corridor(input: RoadtripCorridorRequest, ctx: McpContext) {
|
||||
const plan = await this.plans.calculate(input.tripId, ctx.userId);
|
||||
if (plan.failures.length || plan.omittedVisits.length || plan.calculated.dayWindowIssue)
|
||||
return errorResult(
|
||||
'Resolve missing coordinates, routing or day-window conflicts before searching this corridor.',
|
||||
);
|
||||
if (input.fromKm != null && input.toKm != null && input.fromKm > input.toKm)
|
||||
return errorResult('fromKm must not exceed toKm.');
|
||||
const day = plan.calculated.days.find((d) => d.dayNumber === input.dayNumber);
|
||||
if (!day?.geometry.length) return errorResult('This day has no routed road.');
|
||||
const line = simplifyLine(
|
||||
day.geometry.map(([lat, lng]) => ({ lat, lng })),
|
||||
Math.max(1, input.widthKm / 3),
|
||||
);
|
||||
const tiles = corridorTiles(line, input.widthKm);
|
||||
const hits = new Map<
|
||||
string,
|
||||
{ poi: Awaited<ReturnType<MapsService['pois']>>['pois'][number]; alongKm: number; distanceKm: number }
|
||||
>();
|
||||
const page = tiles.slice(input.offset, input.offset + 6);
|
||||
const failedAreas: number[] = [];
|
||||
let truncatedAreas = 0;
|
||||
const sources = new Set<string>();
|
||||
for (const bbox of page) {
|
||||
try {
|
||||
const found = await this.maps.pois(input.category, bbox);
|
||||
sources.add(found.source);
|
||||
if (found.truncated || found.clamped) truncatedAreas++;
|
||||
for (const poi of found.pois) {
|
||||
const projection = projectOntoRoute(poi, line);
|
||||
if (!projection || projection.offRouteKm > input.widthKm) continue;
|
||||
if (
|
||||
(input.fromKm != null && projection.alongKm < input.fromKm) ||
|
||||
(input.toKm != null && projection.alongKm > input.toKm)
|
||||
)
|
||||
continue;
|
||||
if (
|
||||
input.name &&
|
||||
!`${poi.name} ${poi.brand ?? ''}`.toLocaleLowerCase().includes(input.name.toLocaleLowerCase())
|
||||
)
|
||||
continue;
|
||||
if (poi.category === 'charging') {
|
||||
if (input.socket && !poi.charging?.sockets.some((socket) => socket.type === input.socket)) continue;
|
||||
if (
|
||||
input.minKw &&
|
||||
poi.charging?.sockets.some((socket) => socket.kw != null) &&
|
||||
!poi.charging.sockets.some((socket) => (socket.kw ?? 0) >= input.minKw!)
|
||||
)
|
||||
continue;
|
||||
}
|
||||
hits.set(poi.osm_id, { poi, alongKm: projection.alongKm, distanceKm: projection.offRouteKm });
|
||||
}
|
||||
} catch {
|
||||
failedAreas.push(input.offset + page.indexOf(bbox));
|
||||
}
|
||||
}
|
||||
return ok({
|
||||
dayNumber: day.dayNumber,
|
||||
sources: [...sources],
|
||||
complete: !failedAreas.length && !truncatedAreas && input.offset + page.length >= tiles.length,
|
||||
failedAreas,
|
||||
truncatedAreas,
|
||||
totalAreas: tiles.length,
|
||||
hits: [...hits.values()].sort((a, b) => a.alongKm - b.alongKm),
|
||||
nextOffset: input.offset + page.length < tiles.length ? input.offset + page.length : null,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import {
|
||||
McpController,
|
||||
Tool,
|
||||
TOOL_ANNOTATIONS_READONLY,
|
||||
TOOL_ANNOTATIONS_WRITE,
|
||||
demoDenied,
|
||||
ok,
|
||||
type McpContext,
|
||||
} from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { RoadtripPreferencesService } from './roadtrip-preferences.service';
|
||||
import { roadtripPreferencesUpdateSchema, type RoadtripPreferences } from '@trek/shared';
|
||||
|
||||
const when = addonGate(ADDON_IDS.ROADTRIP);
|
||||
|
||||
@McpController()
|
||||
export class RoadtripPreferencesMcp {
|
||||
constructor(
|
||||
private readonly preferences: RoadtripPreferencesService,
|
||||
private readonly auth: AuthService,
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
name: 'get_roadtrip_settings',
|
||||
description:
|
||||
'Read your personal driving preferences, including daily start and end times, day-ending behavior, vehicle specifications, range, fill percentage, driving limits, avoided road classes and route display options. These preferences apply to all your trips, not to other travellers. Missing numbers mean no limit, missing daily times disable automatic scheduling, missing vehicle means unspecified, and missing end mode means route. Range and consumption always use kilometres, litres and kWh. Instance URLs and credentials are not exposed.',
|
||||
inputSchema: {},
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'settings', mode: 'read' },
|
||||
when,
|
||||
})
|
||||
async read(_input: Record<string, never>, ctx: McpContext) {
|
||||
return ok({ settings: this.preferences.read(ctx.userId), scope: 'current_user' });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'update_roadtrip_settings',
|
||||
description:
|
||||
'Change personal driving preferences for all your trips. Read get_roadtrip_settings first for relative changes. Daily times use HH:mm; clear either with an empty string to disable automatic daily scheduling. Fixed visit times retain priority. Numeric zero clears a limit. Vehicle specifications take precedence over manual range when complete; clear the relevant specifications to use a manual range. Avoid classes are a comma-separated selection of toll,motorway,ferry. Unspecified fields remain unchanged. End mode route pauses at the cutoff; stop ends at the last reachable visit. Per-visit end_day and dragged boundaries are edited with set_assignment_end_day and set_day_boundary. This never changes instance routing URLs or credentials.',
|
||||
inputSchema: { settings: roadtripPreferencesUpdateSchema },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
access: { group: 'settings', mode: 'write' },
|
||||
when,
|
||||
})
|
||||
async update({ settings }: { settings: RoadtripPreferences }, ctx: McpContext) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
return ok({ settings: this.preferences.update(ctx.userId, settings), scope: 'current_user' });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { HttpException, Injectable } from '@nestjs/common';
|
||||
import {
|
||||
ROADTRIP_PREFERENCE_KEYS,
|
||||
roadtripPreferencesSchema,
|
||||
roadtripPreferencesUpdateSchema,
|
||||
type RoadtripPreferences,
|
||||
} from '@trek/shared';
|
||||
|
||||
@Injectable()
|
||||
export class RoadtripPreferencesService {
|
||||
constructor(
|
||||
private readonly settings: SettingsService,
|
||||
private readonly realtime: RealtimeService,
|
||||
) {}
|
||||
|
||||
read(userId: number): RoadtripPreferences {
|
||||
const settings = this.settings.getUserSettings(userId);
|
||||
const preferences: Record<string, unknown> = {};
|
||||
for (const key of ROADTRIP_PREFERENCE_KEYS) {
|
||||
const parsed = roadtripPreferencesSchema.shape[key].safeParse(settings[key]);
|
||||
if (parsed.success && parsed.data !== undefined) preferences[key] = parsed.data;
|
||||
}
|
||||
return roadtripPreferencesSchema.parse(preferences);
|
||||
}
|
||||
|
||||
update(userId: number, patch: RoadtripPreferences): RoadtripPreferences {
|
||||
const validated = roadtripPreferencesUpdateSchema.parse(patch);
|
||||
const next = { ...this.read(userId), ...validated };
|
||||
if (next.roadtrip_day_start && next.roadtrip_day_end && next.roadtrip_day_end <= next.roadtrip_day_start) {
|
||||
throw new HttpException({ error: 'Day end must be later than day start.' }, 400);
|
||||
}
|
||||
this.settings.bulkUpsertSettings(userId, validated);
|
||||
const saved = this.read(userId);
|
||||
this.realtime.broadcastToUser(userId, { type: 'roadtripPreferences:changed', preferences: saved });
|
||||
return saved;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
import { readCappedJson, discardBody } from '../../utils/cappedFetch';
|
||||
import { safeFetchAdminConfigured } from '../../utils/ssrfGuard';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { normalize, declaredProfiles } from '../plugins/contributions/plugin-route-normalize';
|
||||
import { pluginsEnabled } from '../plugins/kill-switch';
|
||||
import { PluginHooks } from '../plugins/plugin-hooks.service';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
formatDurationShort,
|
||||
haversineKm,
|
||||
type RoutedLeg,
|
||||
type RouteAvoidClass,
|
||||
type SnappedWaypoint,
|
||||
} from '@trek/shared/roadtrip';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
const coordinate = z.tuple([z.number().min(-180).max(180), z.number().min(-90).max(90)]);
|
||||
const osrmSchema = z.object({
|
||||
code: z.literal('Ok'),
|
||||
routes: z
|
||||
.array(
|
||||
z.object({
|
||||
distance: z.number().nonnegative(),
|
||||
duration: z.number().nonnegative(),
|
||||
legs: z
|
||||
.array(z.object({ distance: z.number().nonnegative(), duration: z.number().nonnegative() }))
|
||||
.min(1)
|
||||
.max(99),
|
||||
geometry: z.object({ coordinates: z.array(coordinate).min(2).max(200000) }),
|
||||
}),
|
||||
)
|
||||
.min(1),
|
||||
waypoints: z.array(z.object({ location: coordinate, distance: z.number().nonnegative() })).optional(),
|
||||
});
|
||||
const valhallaSchema = z.object({
|
||||
trip: z.object({
|
||||
legs: z
|
||||
.array(
|
||||
z.object({
|
||||
shape: z.string().max(2000000),
|
||||
summary: z.object({
|
||||
length: z.number().nonnegative(),
|
||||
time: z.number().nonnegative(),
|
||||
has_toll: z.boolean().optional(),
|
||||
has_highway: z.boolean().optional(),
|
||||
has_ferry: z.boolean().optional(),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
.min(1)
|
||||
.max(99),
|
||||
}),
|
||||
});
|
||||
type Point = { lat: number; lng: number };
|
||||
export interface RoadtripRoute {
|
||||
leg: RoutedLeg;
|
||||
parts: { distance: number; duration: number }[];
|
||||
snapped?: SnappedWaypoint[];
|
||||
avoidMissed: RouteAvoidClass[];
|
||||
}
|
||||
|
||||
function decode(shape: string): [number, number][] {
|
||||
const line: [number, number][] = [];
|
||||
let index = 0,
|
||||
lat = 0,
|
||||
lng = 0;
|
||||
while (index < shape.length) {
|
||||
const pair: number[] = [];
|
||||
for (let axis = 0; axis < 2; axis++) {
|
||||
let value = 0,
|
||||
shift = 0,
|
||||
byte: number;
|
||||
do {
|
||||
if (index >= shape.length || shift > 30) throw new Error('Invalid route geometry');
|
||||
byte = shape.charCodeAt(index++) - 63;
|
||||
if (byte < 0 || byte > 63) throw new Error('Invalid route geometry');
|
||||
value |= (byte & 31) << shift;
|
||||
shift += 5;
|
||||
} while (byte >= 32);
|
||||
pair.push(value & 1 ? ~(value >> 1) : value >> 1);
|
||||
}
|
||||
lat += pair[0];
|
||||
lng += pair[1];
|
||||
coordinate.parse([lng / 1e6, lat / 1e6]);
|
||||
line.push([lat / 1e6, lng / 1e6]);
|
||||
}
|
||||
if (line.length < 2) throw new Error('Invalid route geometry');
|
||||
return line;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class RoadtripRouterService {
|
||||
private nextRequest = 0;
|
||||
private queue: Promise<void> = Promise.resolve();
|
||||
private cache = new Map<string, { at: number; route: RoadtripRoute }>();
|
||||
|
||||
constructor(
|
||||
private readonly settings: SettingsService,
|
||||
private readonly hooks: PluginHooks,
|
||||
private readonly db: DatabaseService,
|
||||
) {}
|
||||
|
||||
profiles(): string[] {
|
||||
return [
|
||||
'driving',
|
||||
'walking',
|
||||
'cycling',
|
||||
...(pluginsEnabled()
|
||||
? this.hooks
|
||||
.providersOf('routeProvider')
|
||||
.flatMap((id) => declaredProfiles(this.db.connection, id).map((profile) => `plugin:${id}/${profile}`))
|
||||
: []),
|
||||
];
|
||||
}
|
||||
|
||||
private async request(url: string, body?: unknown): Promise<unknown> {
|
||||
const before = this.queue;
|
||||
let release!: () => void;
|
||||
this.queue = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
await before;
|
||||
try {
|
||||
const delay = this.nextRequest - Date.now();
|
||||
if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));
|
||||
this.nextRequest = Date.now() + 1100;
|
||||
const response = await safeFetchAdminConfigured(url, {
|
||||
signal: AbortSignal.timeout(20000),
|
||||
headers: { 'User-Agent': 'TREK Roadtrip', 'Content-Type': 'application/json', 'X-Client-Id': 'trek' },
|
||||
...(body ? { method: 'POST', body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
discardBody(response);
|
||||
throw new Error(`Routing provider returned ${response.status}`);
|
||||
}
|
||||
const payload = await readCappedJson<unknown>(response, 8 * 1024 * 1024);
|
||||
if (payload === undefined) throw new Error('Routing response is invalid or too large');
|
||||
return payload;
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
async route(
|
||||
userId: number,
|
||||
tripId: number,
|
||||
dayId: number,
|
||||
points: Point[],
|
||||
profile: string,
|
||||
avoid: RouteAvoidClass[],
|
||||
): Promise<RoadtripRoute> {
|
||||
const settings = this.settings.getUserSettings(userId);
|
||||
const key = JSON.stringify([
|
||||
userId,
|
||||
tripId,
|
||||
dayId,
|
||||
points,
|
||||
profile,
|
||||
avoid,
|
||||
settings.routing_base_url,
|
||||
settings.valhalla_base_url,
|
||||
]);
|
||||
const cached = this.cache.get(key);
|
||||
if (!profile.startsWith('plugin:') && cached && Date.now() - cached.at < 300000) return cached.route;
|
||||
let line: [number, number][], distance: number, duration: number;
|
||||
let parts: { distance: number; duration: number }[];
|
||||
let vias: RoutedLeg['vias'] = [];
|
||||
let avoidMissed = profile === 'driving' ? [...avoid] : [];
|
||||
let snapped: SnappedWaypoint[] | undefined;
|
||||
const plugin = /^plugin:([^/]+)\/(.+)$/.exec(profile);
|
||||
if (plugin) {
|
||||
const [, id, name] = plugin;
|
||||
if (
|
||||
points.length > 30 ||
|
||||
!pluginsEnabled() ||
|
||||
!this.hooks.providersOf('routeProvider').includes(id) ||
|
||||
!declaredProfiles(this.db.connection, id).includes(name)
|
||||
)
|
||||
throw new Error('Routing plugin is unavailable or has too many waypoints');
|
||||
const raw = await this.hooks.route(id, { tripId, dayId, profile: name, waypoints: points }, userId);
|
||||
const route = normalize(id, name, points.length, raw);
|
||||
if (!route) throw new Error('Routing plugin could not calculate this leg');
|
||||
line = route.coordinates;
|
||||
distance = route.distance;
|
||||
duration = route.duration;
|
||||
vias = route.viaPoints;
|
||||
parts = route.legs;
|
||||
} else {
|
||||
const mode = profile === 'walking' || profile === 'cycling' ? profile : 'driving';
|
||||
const base =
|
||||
typeof settings.routing_base_url === 'string' ? settings.routing_base_url.trim().replace(/\/+$/, '') : '';
|
||||
const configuredValhalla =
|
||||
typeof settings.valhalla_base_url === 'string' ? settings.valhalla_base_url.trim().replace(/\/+$/, '') : '';
|
||||
const valhalla = configuredValhalla || (base ? '' : 'https://valhalla1.openstreetmap.de');
|
||||
let weighted = false;
|
||||
if (mode === 'driving' && avoid.length && valhalla) {
|
||||
try {
|
||||
const options = {
|
||||
use_tolls: avoid.includes('toll') ? 0 : 1,
|
||||
use_highways: avoid.includes('motorway') ? 0 : 1,
|
||||
use_ferry: avoid.includes('ferry') ? 0 : 1,
|
||||
};
|
||||
const legs: z.infer<typeof valhallaSchema>['trip']['legs'] = [];
|
||||
for (let start = 0; start < points.length - 1; start += 9) {
|
||||
const payload = await this.request(`${valhalla}/route`, {
|
||||
locations: points.slice(start, start + 10).map((p) => ({ lat: p.lat, lon: p.lng, radius: 50 })),
|
||||
costing: 'auto',
|
||||
costing_options: { auto: options },
|
||||
directions_options: { units: 'kilometers' },
|
||||
});
|
||||
legs.push(...valhallaSchema.parse(payload).trip.legs);
|
||||
}
|
||||
if (legs.length !== points.length - 1) throw new Error('Routing response has mismatched legs');
|
||||
const shapes = legs.map((leg) => decode(leg.shape));
|
||||
line = shapes.flat();
|
||||
const locations = [...shapes.map((shape) => shape[0]), shapes[shapes.length - 1].at(-1)!];
|
||||
snapped = locations.map(([lat, lng], index) => ({
|
||||
asked: [points[index].lat, points[index].lng],
|
||||
at: [lat, lng],
|
||||
meters: haversineKm(points[index], { lat, lng }) * 1000,
|
||||
}));
|
||||
distance = legs.reduce((sum, leg) => sum + leg.summary.length * 1000, 0);
|
||||
duration = legs.reduce((sum, leg) => sum + leg.summary.time, 0);
|
||||
parts = legs.map((leg) => ({ distance: leg.summary.length * 1000, duration: leg.summary.time }));
|
||||
avoidMissed = avoid.filter((cls) =>
|
||||
legs.some((leg) =>
|
||||
cls === 'toll'
|
||||
? leg.summary.has_toll
|
||||
: cls === 'motorway'
|
||||
? leg.summary.has_highway
|
||||
: leg.summary.has_ferry,
|
||||
),
|
||||
);
|
||||
weighted = true;
|
||||
} catch {
|
||||
avoidMissed = [...avoid];
|
||||
snapped = undefined;
|
||||
}
|
||||
}
|
||||
if (!weighted) {
|
||||
const path = mode === 'walking' ? 'foot' : mode === 'cycling' ? 'bike' : 'driving';
|
||||
const origin =
|
||||
base ||
|
||||
`https://routing.openstreetmap.de/routed-${mode === 'walking' ? 'foot' : mode === 'cycling' ? 'bike' : 'car'}`;
|
||||
const payload = await this.request(
|
||||
`${origin}/route/v1/${path}/${points.map((p) => `${p.lng},${p.lat}`).join(';')}?overview=full&geometries=geojson&steps=false`,
|
||||
);
|
||||
const parsed = osrmSchema.parse(payload);
|
||||
const route = parsed.routes[0];
|
||||
line = route.geometry.coordinates.map(([lng, lat]) => [lat, lng]);
|
||||
distance = route.distance;
|
||||
duration = route.duration;
|
||||
parts = route.legs;
|
||||
if (parsed.waypoints?.length === points.length)
|
||||
snapped = parsed.waypoints.map((waypoint, index) => ({
|
||||
asked: [points[index].lat, points[index].lng],
|
||||
at: [waypoint.location[1], waypoint.location[0]],
|
||||
meters: waypoint.distance,
|
||||
}));
|
||||
}
|
||||
}
|
||||
const from = line[0],
|
||||
to = line[line.length - 1];
|
||||
const durationText = formatDurationShort(duration);
|
||||
const distanceText = `${Math.round(distance / 100) / 10} km`;
|
||||
if (parts.length !== points.length - 1) throw new Error('Routing response has mismatched legs');
|
||||
const route = {
|
||||
parts,
|
||||
snapped,
|
||||
leg: {
|
||||
line,
|
||||
vias,
|
||||
seg: {
|
||||
from,
|
||||
to,
|
||||
mid: line[Math.floor(line.length / 2)],
|
||||
distance,
|
||||
duration,
|
||||
durationText,
|
||||
distanceText,
|
||||
drivingText: durationText,
|
||||
walkingText: durationText,
|
||||
mode: profile,
|
||||
},
|
||||
snapped: {
|
||||
from: {
|
||||
lat: from[0],
|
||||
lng: from[1],
|
||||
offRoadMeters: haversineKm(points[0], { lat: from[0], lng: from[1] }) * 1000,
|
||||
},
|
||||
to: {
|
||||
lat: to[0],
|
||||
lng: to[1],
|
||||
offRoadMeters: haversineKm(points[points.length - 1], { lat: to[0], lng: to[1] }) * 1000,
|
||||
},
|
||||
},
|
||||
},
|
||||
avoidMissed,
|
||||
};
|
||||
this.cache.set(key, { at: Date.now(), route });
|
||||
if (this.cache.size > 100) this.cache.delete(this.cache.keys().next().value!);
|
||||
return route;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { AuthService } from '../auth/auth.service';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { roadtripViaUpdateRequestSchema, type RoadtripViaUpdateRequest } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The whole surface rides the road trip addon, the same way the controller does
|
||||
@@ -184,6 +185,23 @@ export class RoadtripMcp {
|
||||
return ok({ success: true });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'update_route_via',
|
||||
description: 'Move an existing via point and optionally attach it to another outgoing leg of the same day. This is the same change as dragging a route handle. A via bends the route and does not add a stop or stay.',
|
||||
inputSchema: { tripId: z.number().int().positive(), dayId: z.number().int().positive(), viaId: z.number().int().positive(), ...roadtripViaUpdateRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT, access: { group: 'trips', mode: 'write' }, when: roadtripAddonOn,
|
||||
})
|
||||
async updateVia(input: RoadtripViaUpdateRequest & { tripId: number; dayId: number; viaId: number }, ctx: McpContext) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.db.canAccessTrip(input.tripId, ctx.userId)) return noAccess();
|
||||
if (!this.guards.hasTripPermission('day_edit', input.tripId, ctx.userId)) return permissionDenied();
|
||||
if (!this.roadtrip.dayExists(input.dayId, input.tripId)) return noAccess();
|
||||
const via = this.roadtrip.move(input.viaId, input.dayId, input.lat, input.lng, input.after_order_index);
|
||||
if (!via) return noAccess();
|
||||
this.announce(input.tripId, input.dayId);
|
||||
return ok({ via });
|
||||
}
|
||||
|
||||
/**
|
||||
* Says what this day's drive is routed through now.
|
||||
*
|
||||
|
||||
@@ -10,14 +10,22 @@ import { AddonsModule } from '../addons/addons.module';
|
||||
import { DayBoundariesController } from './day-boundaries.controller';
|
||||
import { DayBoundariesService } from './day-boundaries.service';
|
||||
import { DayBoundariesMcp } from './day-boundaries.mcp';
|
||||
import { SettingsModule } from '../settings/settings.module';
|
||||
import { RoadtripPreferencesService } from './roadtrip-preferences.service';
|
||||
import { RoadtripPreferencesMcp } from './roadtrip-preferences.mcp';
|
||||
import { RoadtripRouterService } from './roadtrip-router.service';
|
||||
import { RoadtripPlanService } from './roadtrip-plan.service';
|
||||
import { RoadtripPlanningMcp } from './roadtrip-planning.mcp';
|
||||
import { PluginsRuntimeModule } from '../plugins/plugins-runtime.module';
|
||||
import { MapsModule } from '../maps/maps.module';
|
||||
|
||||
/** Road trip domain (#1797): the points a drive is routed through. Registered in AppModule. */
|
||||
@Module({
|
||||
// McpShared brings the tool guards, Auth the demo check, Permissions the trip guard,
|
||||
// Addons the enabled-check the MCP tools gate on (the controller has @RequireAddon).
|
||||
imports: [McpSharedModule, PermissionsModule, AuthModule, AddonsModule, RealtimeModule],
|
||||
imports: [McpSharedModule, PermissionsModule, AuthModule, AddonsModule, RealtimeModule, SettingsModule, PluginsRuntimeModule, MapsModule],
|
||||
controllers: [RoadtripController, DayBoundariesController],
|
||||
providers: [RoadtripService, RoadtripMcp, DayBoundariesService, DayBoundariesMcp],
|
||||
providers: [RoadtripService, RoadtripMcp, DayBoundariesService, DayBoundariesMcp, RoadtripPreferencesService, RoadtripPreferencesMcp, RoadtripRouterService, RoadtripPlanService, RoadtripPlanningMcp],
|
||||
exports: [RoadtripService],
|
||||
})
|
||||
export class RoadtripModule {}
|
||||
|
||||
Reference in New Issue
Block a user