Live web enrichment (SearXNG) + PostGIS spatial stack
Milestone 1 — live web search: - mock/server.js: /search + /search-status proxy to the self-hosted SearXNG (third leg of the 3-source blend; engine endpoint stays server-side), /spatial + /spatial-status proxy to the spatial service - mock/app.js: background enrichment of suggestion cards — each candidate gets a web element (discovery cards + "you might like" rows) that is checked via SearXNG in the background (one in-flight query per place, 1 h TTL, failures retry in ~5 min) and APPENDS sourced facts with provenance URLs; never reorders/rewrites the plan. New LLM tools: web_search (cite URLs) and poi_near (PostGIS). Status badge gains 'web' / 'spatial'. - styles.css: .cc-web live-facts blocks, t-web verified chip Milestone 2 — PostGIS spatial DB (code complete; needs docker access to run — see spatial/README.md): - spatial/: docker-compose (postgis/postgis:16-3.4 + osm2pgsql:16 one-shot importer + spatiald), schema.sql (poi table w/ GIST index, spatial_extract bookkeeping, refresh_poi()), import.sh for the PBF extracts in ../osm, spatiald (Go, lib/pq): /health, /near (ST_DWithin), /nearest (KNN), /corridor (ST_Buffer along a route), with kind/name/extract/limit filters
This commit is contained in:
+115
-3
@@ -51,7 +51,82 @@ async function checkLLM() {
|
||||
try { const r = await fetch('/llm-status'); const j = await r.json(); llmOn = !!j.llm; }
|
||||
catch { llmOn = false; }
|
||||
}
|
||||
const badgeText = () => '📶 online' + (routerOn ? ' · router' : '') + (llmOn ? ' · llm' : '');
|
||||
// ---------------- web search client (SearXNG via the /search proxy) ------
|
||||
// Live facts (opening hours, fees, seasonal notes) with provenance URLs —
|
||||
// the third leg of the 3-source blend. Enrichment APPENDS to suggestion
|
||||
// cards; it never reorders, removes, or rewrites the plan (DESIGN.md
|
||||
// "streaming enrichment").
|
||||
let webOn = false;
|
||||
async function checkWeb() {
|
||||
try { const r = await fetch('/search-status'); webOn = !!(await r.json()).web; }
|
||||
catch { webOn = false; }
|
||||
}
|
||||
// ---------------- spatial client (PostGIS spatiald via /spatial proxy) --
|
||||
let spatialOn = false, spatialPoi = 0;
|
||||
async function checkSpatial() {
|
||||
try { const r = await fetch('/spatial-status'); const j = await r.json(); spatialOn = !!j.spatial; spatialPoi = j.poi_count || 0; }
|
||||
catch { spatialOn = false; }
|
||||
}
|
||||
const badgeText = () => '📶 online' + (routerOn ? ' · router' : '') + (llmOn ? ' · llm' : '') + (webOn ? ' · web' : '') + (spatialOn ? ' · spatial' : '');
|
||||
const WEB_TTL = 60 * 60 * 1000; // a cached live check is good for an hour
|
||||
const tripCity = () => (M?.trip?.places?.[0]?.name) || (M?.trip?.title || '').split(' ')[0] || '';
|
||||
const webQuery = (c, cat) => {
|
||||
const tail = cat === 'hotel' ? 'price per night reviews'
|
||||
: ['lunch', 'dinner', 'breakfast', 'snack'].includes(cat) ? 'menu prices opening hours'
|
||||
: 'opening hours entry fee';
|
||||
return `"${c.name}" ${tripCity()} ${tail}`;
|
||||
};
|
||||
// Suggestion surfaces (discovery cards, "you might like" rows) embed a web
|
||||
// element via webEl(c, cat); it is re-rendered on every refresh, so results
|
||||
// are kept on the candidate (c.web) and every live node for that place is
|
||||
// refreshed via the data-webfor attribute.
|
||||
const webBusy = new Set();
|
||||
function webEl(c, cat) {
|
||||
const n = el('div', 'cc-web');
|
||||
n.dataset.webfor = c.id;
|
||||
n.dataset.webcat = cat || '';
|
||||
refreshWebEl(n, c);
|
||||
return n;
|
||||
}
|
||||
function refreshWebEl(n, c) {
|
||||
if (!n || !n.isConnected) return;
|
||||
if (c.web) {
|
||||
n.classList.remove('busy');
|
||||
if (c.web.failed) { n.innerHTML = '🌐 live check unavailable (retry in a few minutes)'; return; }
|
||||
const rs = (c.web.results || []).filter(r => r.url);
|
||||
if (!rs.length) { n.innerHTML = '🌐 no live results'; return; }
|
||||
n.innerHTML = rs.slice(0, 3).map(r => {
|
||||
const host = (() => { try { return new URL(r.url).hostname.replace(/^www\./, ''); } catch { return r.source || 'web'; } })();
|
||||
const snip = (r.snippet || r.title || '').replace(/Missing:.*$/i, '').trim();
|
||||
return `<span class="web-src"><a href="${esc(r.url)}" target="_blank" rel="noopener">${esc(host)}</a></span>` +
|
||||
`<span class="web-snip">${esc(snip.slice(0, 150))}${snip.length > 150 ? '…' : ''}</span>`;
|
||||
}).join('<br>');
|
||||
} else if (webBusy.has(c.id)) {
|
||||
n.classList.add('busy');
|
||||
n.innerHTML = '🌐 checking <b>' + esc(c.name) + '</b>…';
|
||||
} else n.innerHTML = '';
|
||||
}
|
||||
// fire-and-forget: at most one in-flight query per place, cached for WEB_TTL
|
||||
async function enrichWeb(c, cat) {
|
||||
if (!webOn || !c) return;
|
||||
if (c.web && Date.now() - c.web.at < WEB_TTL) return;
|
||||
if (webBusy.has(c.id)) return;
|
||||
webBusy.add(c.id);
|
||||
document.querySelectorAll(`[data-webfor="${c.id}"]`).forEach(n => refreshWebEl(n, c));
|
||||
try {
|
||||
const r = await fetch('/search?q=' + encodeURIComponent(webQuery(c, cat)) + '&count=3');
|
||||
const j = await r.json();
|
||||
if (!j.ok) throw new Error(j.error || 'search failed');
|
||||
c.web = { q: webQuery(c, cat), at: Date.now(), results: j.results || [] };
|
||||
} catch {
|
||||
// remember the failure so live nodes can show it, but age it out fast
|
||||
// (retry after ~5 min, not after the full TTL)
|
||||
c.web = { q: webQuery(c, cat), at: Date.now() - (WEB_TTL - 5 * 60 * 1000), results: [], failed: true };
|
||||
} finally {
|
||||
webBusy.delete(c.id);
|
||||
document.querySelectorAll(`[data-webfor="${c.id}"]`).forEach(n => refreshWebEl(n, c));
|
||||
}
|
||||
}
|
||||
const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
// Compact itinerary snapshot (the design doc's LLM context form): stops with
|
||||
// times + stays + bookings. No geometry, no tool output. layout() fills
|
||||
@@ -311,6 +386,36 @@ const TOOLS = {
|
||||
walk_from_hotel_min: hotelWalkMin(p.at), url: c?.url || null, summary: c?.detail?.summary || null };
|
||||
},
|
||||
|
||||
// LIVE web search (SearXNG) — for anything that can change between the
|
||||
// data snapshot and the trip: opening hours, fees, seasonal events, prices.
|
||||
// Results carry provenance URLs; the model must cite the ones it used.
|
||||
web_search: async (a) => {
|
||||
const q = String(a.query || '').trim();
|
||||
if (!q) return { error: 'query is required' };
|
||||
if (!webOn) return { error: 'the web search backend is offline — say so and fall back to what the plan already knows' };
|
||||
const r = await fetch('/search?q=' + encodeURIComponent(q) + '&count=5' + (a.categories ? '&categories=' + encodeURIComponent(a.categories) : ''));
|
||||
const j = await r.json();
|
||||
if (!j.ok) return { error: j.error || 'search failed' };
|
||||
return { count: j.count, results: (j.results || []).map(x => ({ title: x.title, url: x.url, source: x.source, snippet: x.snippet.slice(0, 300) })) };
|
||||
},
|
||||
|
||||
// POI lookup against the local PostGIS extract (native ST_DWithin / KNN /
|
||||
// corridor queries — real OSM data, not the curated demo pools).
|
||||
poi_near: async (a) => {
|
||||
if (!spatialOn) return { error: 'the spatial database is offline — use search_places instead' };
|
||||
const lat = +a.lat, lng = +a.lng, r = Math.min(50000, Math.max(100, +a.radius_m || 500));
|
||||
if (!isFinite(lat) || !isFinite(lng)) return { error: 'lat/lng must be numbers (lat, lng in degrees)' };
|
||||
let qs = `lat=${lat}&lng=${lng}&r=${r}`;
|
||||
if (a.kind) qs += '&kind=' + encodeURIComponent(a.kind); // e.g. amenity=restaurant, tourism=museum
|
||||
if (a.name) qs += '&name=' + encodeURIComponent(a.name);
|
||||
if (a.corridor) qs += '&corridor=' + encodeURIComponent(a.corridor); // 'lng,lat;lng,lat;…' route polyline
|
||||
const rj = await fetch('/spatial/' + (a.corridor ? 'corridor' : 'near') + '?' + qs);
|
||||
const j = await rj.json();
|
||||
if (j.error) return { error: j.error };
|
||||
return { count: (j.results || []).length, results: (j.results || []).map(x =>
|
||||
({ name: x.name, kind: x.kind, dist_m: Math.round(x.dist_m), opening_hours: x.opening_hours || null, fee: x.fee || null, website: x.website || null })) };
|
||||
},
|
||||
|
||||
route_between: async (a) => {
|
||||
const A = resolvePlace(a.from), B = resolvePlace(a.to);
|
||||
if (!A) return { error: `cannot resolve "from" = "${a.from}"` };
|
||||
@@ -535,6 +640,8 @@ function llmSystemPrompt() {
|
||||
' itinerary_summary() — the current plan: bookings, stays, and each day\'s scheduled stops with times.\n' +
|
||||
' search_places(category, region?) — candidate places. category ∈ {' + cats.join(', ') + '} ; region ∈ {' + regions.join(', ') + '} or omit. Returns id, name, price_eur, dur_min, tags, pitch, walk_from_hotel_min.\n' +
|
||||
' place_facts(id) — full facts for one place (id or name): price, duration, tags, pitch, walk from hotel, summary.\n' +
|
||||
' web_search(query) — LIVE web search. Use for anything that can change since the data snapshot: opening hours, entry fees, seasonal events, current prices, whether a place still exists. Returns results with source URLs — always cite the URL(s) you relied on in your answer.\n' +
|
||||
' poi_near(lat, lng, radius_m?, kind?, name?) — real POIs from the local OSM/PostGIS extract (e.g. kind "amenity=restaurant"). Use when the curated pools are empty or the user asks "what is around X".\n' +
|
||||
' route_between(from, to) — real walking minutes + km between two places ("hotel" or a place id/name).\n' +
|
||||
' review_plan(dayId?) — deterministic checks: day overrun vs the waking window, meals at implausible hours, duplicates. dayId optional.\n' +
|
||||
' add_stop(dayId, slot, candidateId, state?) — put a candidate on a day. slot ∈ lunch,dinner,visit. If the slot is taken the current stop is demoted to a backup (a swap). state ∈ planned,idea,backup (default planned). candidateId comes from search_places.\n' +
|
||||
@@ -546,7 +653,7 @@ function llmSystemPrompt() {
|
||||
'Guidelines:\n' +
|
||||
'- dayId is the day id like "D1" or "D2" — shown in brackets in the plan rows, e.g. [D1 · 2026-09-12]. Never use the calendar date as a dayId.\n' +
|
||||
'- Answer concisely (1–4 sentences), plain text, no markdown.\n' +
|
||||
'- For any factual question about times, distances, or prices, CALL the tool — do not guess.\n' +
|
||||
'- For any factual question about times, distances, or prices, CALL the tool — do not guess. For CURRENT facts ("is it open?", "how much now", seasonal), prefer web_search and cite its source URLs.\n' +
|
||||
'- For a requested change, call the matching fix-op, then confirm in one sentence what changed. The user can undo any edit.\n' +
|
||||
'- Before a big rework, consider review_plan() and mention any issues it reports.\n' +
|
||||
'- Be efficient: call each tool at most once unless you need to, and never re-fetch facts you already have. A fix-op alone is enough — do not re-search or re-fetch the stop you are moving/editing.\n' +
|
||||
@@ -1097,6 +1204,8 @@ function candCard(c, anchor, isHotel) {
|
||||
chips.append(el('span', 'pchip', c.price ? '~' + c.price + '€ / ' + (isHotel ? 'night' : 'person') : 'free'));
|
||||
card.append(chips);
|
||||
if (c.tags?.length) card.append(el('div', 'cc-tags', c.tags.map(t => '#' + t).join(' ')));
|
||||
card.append(webEl(c, isHotel ? 'hotel' : disc.cat)); // live web facts + provenance (background)
|
||||
enrichWeb(c, isHotel ? 'hotel' : disc.cat);
|
||||
const acts = el('div', 'cc-acts');
|
||||
const pick = el('button', 'btn primary small', isHotel ? 'Make this the hotel' : 'Choose this');
|
||||
pick.onclick = () => chooseCand(c);
|
||||
@@ -1616,6 +1725,8 @@ function renderSugg() {
|
||||
row.append(el('span', 'sr-name', c.name));
|
||||
row.append(el('span', 'pchip', `↦ ${walkMin(a.at, c.at)} min`));
|
||||
row.append(el('span', 'pchip', c.price ? '~' + c.price + '€' : 'free'));
|
||||
const wn = webEl(c, slot); wn.classList.add('cc-web-sugg'); row.append(wn);
|
||||
enrichWeb(c, slot);
|
||||
const cmp = el('button', 'btn ghost tiny', '⚖');
|
||||
cmp.title = 'Compare';
|
||||
cmp.onclick = () => toggleCompare(itemFromCand(c, slot));
|
||||
@@ -2366,10 +2477,11 @@ function enterTrip(id) {
|
||||
renderHotelMks(); renderModeToggle();
|
||||
renderDocChips();
|
||||
// this trip may live on a different OSRM extract — re-check before routing
|
||||
Promise.all([checkRouter(), checkLLM()]).then(() => {
|
||||
Promise.all([checkRouter(), checkLLM(), checkWeb(), checkSpatial()]).then(() => {
|
||||
const b = $('#offline-badge');
|
||||
if (b && offlineState !== 'ready') b.textContent = badgeText();
|
||||
if (routerOn) enrichLegs(day);
|
||||
if (webOn && $('#sugg-block')) renderSugg(); // web came up late → enrich the suggestion rows now
|
||||
});
|
||||
if (!day.legs.length) rebuildLegs(day); else enrichLegs(day);
|
||||
renderAll();
|
||||
|
||||
@@ -36,6 +36,12 @@ const LLM = {
|
||||
ctx: 131072,
|
||||
maxTokens: +(process.env.LLM_MAX_TOKENS || 8192), // thinking + answer share this budget
|
||||
};
|
||||
// Web search backend: self-hosted SearXNG (JSON API). The UI only ever sends
|
||||
// questions; the engine endpoint stays server-side. This is the third leg of
|
||||
// the DESIGN.md 3-source blend (OSM ground truth → LLM knowledge → live web).
|
||||
const SEARXNG = { base: process.env.SEARXNG_BASE || 'http://192.168.3.4:30053' };
|
||||
// PostGIS spatial service (see ../spatial/): live once the import has run.
|
||||
const SPATIAL = { url: process.env.SPATIAL_URL || 'http://localhost:5005' };
|
||||
const routerFor = (u) => ROUTERS[u.searchParams.get('router') || 'northeast'] || ROUTERS.northeast;
|
||||
const PROFILE = { foot: 'walking', walk: 'walking', bike: 'cycling', cycle: 'cycling', car: 'driving', drive: 'driving', transit: 'driving' };
|
||||
const CACHE = path.join(__dirname, '.tilecache');
|
||||
@@ -371,6 +377,79 @@ http.createServer((req, res) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// ---- web search (proxy -> SearXNG) --------------------------------
|
||||
// GET /search-status — availability probe (HEAD on the root; it does NOT
|
||||
// touch the upstream engines, unlike a real query)
|
||||
if (u.pathname === '/search-status') {
|
||||
fetch(SEARXNG.base + '/', { method: 'HEAD', signal: AbortSignal.timeout(4000) })
|
||||
.then(r => {
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
res.writeHead(200);
|
||||
res.end(JSON.stringify({ web: r.ok, base: SEARXNG.base }));
|
||||
})
|
||||
.catch(() => {
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.setHeader('Content-Type', 'application/json'); res.writeHead(200);
|
||||
res.end(JSON.stringify({ web: false, base: SEARXNG.base }));
|
||||
});
|
||||
return;
|
||||
}
|
||||
// GET /search?q=…&categories=…&count=… — normalized result list with
|
||||
// provenance (url + engine). SearXNG's JSON API wants format=json; the
|
||||
// proxy caps results and strips the noise fields the UI doesn't render.
|
||||
if (u.pathname === '/search') {
|
||||
const q = u.searchParams.get('q') || '';
|
||||
const count = Math.min(10, Math.max(1, +(u.searchParams.get('count') || 5)));
|
||||
const cats = u.searchParams.get('categories') || 'general';
|
||||
if (!q.trim()) { res.writeHead(400, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify({ ok: false, error: 'q is required' })); }
|
||||
const up = `${SEARXNG.base}/search?q=${encodeURIComponent(q)}&format=json&categories=${encodeURIComponent(cats)}&pageno=1`;
|
||||
const t0 = Date.now();
|
||||
fetch(up, { signal: AbortSignal.timeout(20000) }).then(async r => {
|
||||
if (!r.ok) throw new Error('searxng http ' + r.status);
|
||||
const j = await r.json();
|
||||
const results = (j.results || []).slice(0, count).map(x => ({
|
||||
title: String(x.title || ''), url: String(x.url || ''),
|
||||
source: String(x.engine || ''), snippet: String(x.content || ''),
|
||||
})).filter(x => x.url);
|
||||
console.log(`[search] ${JSON.stringify(q).slice(0, 80)} → ${results.length} results in ${Date.now() - t0}ms`);
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
res.writeHead(200);
|
||||
res.end(JSON.stringify({ ok: true, query: q, count: results.length, results }));
|
||||
}).catch(e => {
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.setHeader('Content-Type', 'application/json'); res.writeHead(200);
|
||||
res.end(JSON.stringify({ ok: false, error: 'search failed: ' + e.message }));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// ---- spatial backend (proxy -> PostGIS spatiald) -------------------
|
||||
// /spatial-status probes /health; /spatial/<path> forwards verbatim
|
||||
// (query string included) — /near, /nearest, /corridor.
|
||||
if (u.pathname === '/spatial-status' || u.pathname.startsWith('/spatial/')) {
|
||||
const up = u.pathname === '/spatial-status'
|
||||
? SPATIAL.url + '/health'
|
||||
: SPATIAL.url + u.pathname.slice('/spatial'.length); // keep query string
|
||||
const isProbe = u.pathname === '/spatial-status';
|
||||
fetch(up, { signal: AbortSignal.timeout(15000) }).then(async r => {
|
||||
const t = await r.text();
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
res.writeHead(200);
|
||||
if (!isProbe) return res.end(t); // forward the service body verbatim
|
||||
let j = {}; try { j = JSON.parse(t); } catch {}
|
||||
res.end(JSON.stringify({ spatial: r.ok && !!j.ok, url: SPATIAL.url, ...j }));
|
||||
}).catch(() => {
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.setHeader('Content-Type', 'application/json'); res.writeHead(200);
|
||||
if (u.pathname === '/spatial-status') return res.end(JSON.stringify({ spatial: false, url: SPATIAL.url }));
|
||||
res.end(JSON.stringify({ error: 'spatial backend unreachable at ' + SPATIAL.url }));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// ---- document ingestion (flight/booking → text) --------------------
|
||||
// POST /parse-doc — body { filename, mime, b64 }. Returns { ok, kind,
|
||||
// name, text, chars, truncated }. PDFs go through pdftotext; emails (.eml
|
||||
|
||||
@@ -132,6 +132,17 @@ button { font: inherit; }
|
||||
.t-search::before { content: "~"; font-weight: 800; }
|
||||
.t-llm { background: transparent; border: 1.5px dashed #b9c0cc; color: var(--ink2); }
|
||||
.t-llm::after { content: "est"; font-size: 9px; opacity: .8; }
|
||||
.t-web { background: #e3f4e6; color: #1d7a35; }
|
||||
.t-web::before { content: "✓"; font-weight: 800; }
|
||||
/* live web facts on suggestion cards (background SearXNG enrichment) */
|
||||
.cc-web { margin-top: 7px; font-size: 11px; color: var(--ink2); line-height: 1.5;
|
||||
border-top: 1px dashed var(--line); padding-top: 6px; }
|
||||
.cc-web:empty { display: none; }
|
||||
.cc-web.busy { opacity: .75; font-style: italic; }
|
||||
.cc-web .web-src a { color: #1d4f9c; font-weight: 700; text-decoration: none; }
|
||||
.cc-web .web-src a:hover { text-decoration: underline; }
|
||||
.cc-web .web-snip { display: block; margin: 1px 0 3px; }
|
||||
.cc-web-sugg { border-top: none; padding-top: 2px; }
|
||||
.pchip { font-size: 11.5px; color: var(--ink2); font-weight: 600; white-space: nowrap; }
|
||||
.sug-note { font-size: 11px; color: var(--ink2); font-style: italic; }
|
||||
|
||||
|
||||
Reference in New Issue
Block a user