From b0a701b8d0f06d37f5ed6e5ea56f6f5c5c8241f7 Mon Sep 17 00:00:00 2001 From: kim Date: Wed, 14 Oct 2026 12:29:18 +0900 Subject: [PATCH] =?UTF-8?q?feat(route=5Fsearch):=20=EC=B9=B4=EC=B9=B4?= =?UTF-8?q?=EC=98=A4=EB=AA=A8=EB=B9=8C=EB=A6=AC=ED=8B=B0=20=EC=9E=90?= =?UTF-8?q?=EB=8F=99=EC=B0=A8=20=EA=B8=B8=EC=B0=BE=EA=B8=B0=20=EC=B1=84?= =?UTF-8?q?=ED=8C=85=20=EB=8F=84=EA=B5=AC=20(=EC=B6=9C=EB=B0=9C=EC=A7=80?= =?UTF-8?q?=20=EA=B8=B0=EB=B3=B8=20=EA=B5=AC=EB=AF=B8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 거리·소요시간·통행료·택시요금 추정·주요 도로·정체 구간 길이와 카카오맵 길찾기 링크를 돌려준다. 경유지(최대 5)·우선순위·회피 옵션 지원, 지점 해석은 place_search의 resolveCenter 재사용. 길찾기·통행료·소요시간 어휘에만 도구를 열고, 시스템 프롬프트에 "시간·요금을 기억으로 추정하지 말 것" 규칙 추가. markdown.js는 map.kakao.com/link/by/... 한 줄 URL도 지도(경로) 임베드. Co-Authored-By: Claude Sonnet 5.5 --- src/gateway/chat/build-tools.ts | 17 ++++ src/gateway/chat/system-prompt.ts | 5 +- src/gateway/chat/tool-scope.ts | 4 + src/tools/kakao-places.ts | 2 +- src/tools/kakao-route.ts | 152 ++++++++++++++++++++++++++++++ src/tools/registry.ts | 2 + tests/kakao-route.test.ts | 85 +++++++++++++++++ web-ui/js/app/markdown.js | 2 +- 8 files changed, 266 insertions(+), 3 deletions(-) create mode 100644 src/tools/kakao-route.ts create mode 100644 tests/kakao-route.test.ts diff --git a/src/gateway/chat/build-tools.ts b/src/gateway/chat/build-tools.ts index ab21f12..54d2806 100644 --- a/src/gateway/chat/build-tools.ts +++ b/src/gateway/chat/build-tools.ts @@ -1091,6 +1091,23 @@ export function createBuildTools(isOrchestrationSkillEnabled: () => boolean) { }, }, }, + { + type: 'function', + function: { + name: 'route_search', + description: '카카오모빌리티로 국내 자동차 길찾기: 거리·소요시간·통행료·택시 요금 추정·주요 도로·정체 구간·카카오맵 길찾기 링크를 돌려준다. "구미에서 현풍까지 얼마나 걸려?", "OO까지 가는 길", "통행료 얼마야" 요청에 사용. 출발지 기본값은 구미시. 대중교통·도보·자전거·해외는 불가(그땐 돌려주는 카카오맵 링크로 안내). 시간·요금은 도구 값만 말할 것.', + parameters: { + type: 'object', required: ['destination'], + properties: { + destination: { type: 'string', description: '도착지 지역·역·건물·장소 이름(예: "현풍", "서울역", "대구 엑스코")' }, + origin: { type: 'string', description: '출발지(선택, 기본 구미시). 예: "구미역", "대구"' }, + waypoints: { type: 'array', items: { type: 'string' }, description: '경유지 이름 목록(선택, 최대 5개)' }, + priority: { type: 'string', enum: ['RECOMMEND', 'TIME', 'DISTANCE'], description: '경로 기준(기본 추천, TIME 최단시간, DISTANCE 최단거리)' }, + avoid: { type: 'array', items: { type: 'string', enum: ['toll', 'motorway', 'ferries', 'schoolzone', 'uturn'] }, description: '피할 것(선택)' }, + }, + }, + }, + }, { type: 'function', function: { diff --git a/src/gateway/chat/system-prompt.ts b/src/gateway/chat/system-prompt.ts index 3e84295..2229d61 100644 --- a/src/gateway/chat/system-prompt.ts +++ b/src/gateway/chat/system-prompt.ts @@ -225,6 +225,9 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string { const placeSearchRuleBlock = toolNames.has('place_search') ? '\nPLACE SEARCH: For a specific place, business, or "near X" request in Korea (restaurants, pharmacies, stations, an address or phone number), call place_search FIRST and answer from its results — never write an address or phone number from memory. Default reference point is 구미시; pass location for another area. Put the 카카오맵 `지도:` URL from the result for the top place on its own line so it renders as an inline map, and mention the others by name. Opening hours are not in the result: point to its 상세 link instead of guessing.' : ''; + const routeSearchRuleBlock = toolNames.has('route_search') + ? '\nROUTE SEARCH: For driving directions, travel time, distance, or toll questions within Korea, call route_search and answer ONLY from its numbers — never estimate a drive time or toll from memory. Default origin is 구미시; pass origin if the user names one. Give the 길찾기 지도 link from the result on its own line. For 대중교통/도보/자전거 say route_search covers driving only and give that link.' + : ''; const mapsRuleBlock = /지도|맵으로|위치(를|가|는)?|주소|어디(에|야|예요|에요|입니까|인가|니|냐|쯤|메)|어디\s*(있|찾|가|계|위치|살|사는|근처)|길\s*찾|가는\s*길|찾아가|찾아오|약도|도로명|지번|좌표|경위도|근처|인근|부근|가까운|\bmap\b|\baddress\b|directions|navigate|where\s+is|how\s+(do\s+i\s+|to\s+)get\s+to|nearby|landmark/i .test(String(input.message || '')) ? '\nMAPS: When the user asks where a place is, for its address, or to see a map of a location, output the map URL on its own line — the client turns that standalone line into an inline map. For places IN KOREA use 카카오맵: `https://map.kakao.com/link/map/,,` when you have coordinates (e.g. from place_search), otherwise `https://map.kakao.com/link/search/`. Use Google only for places OUTSIDE Korea: `https://www.google.com/maps/search/` (URL-encode, add city/country when ambiguous). Do NOT call browser_open for it and do NOT wrap it in `![](...)`. Still answer in text as well — the map is an addition, not a replacement. Not for pure route/turn-by-turn directions (those do not render).' @@ -265,6 +268,6 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string { : ''; return isTranslateSession ? `You are a medical translator. Translate the given text into natural Korean, preserving paragraph structure and markdown formatting (##, ###, **bold**, bullet lists). Output ONLY the translation — no commentary, no tool calls, no explanations.` : isProjSession ? `You are a project file designer. Output ONLY the project-files JSON block as instructed. No tool calls. No extra text.` : `${executionModeSystemBlock ? `${executionModeSystemBlock}\n\n` : ''}You are SmallClaw, a local AI assistant. Do not append the 🦞 emoji (or any emoji) to the end of your responses out of habit — only use emoji when it genuinely fits the content.\nCurrent date: ${dateStr}, ${timeStr}.\nNever search for or link SmallClaw repos unless the user is asking about SmallClaw itself.\nThis app runs on the user's own machine — browser/desktop automation requests are pre-authorized.\nKeep CONVERSATIONAL and TASK-EXECUTION replies SHORT (2-4 sentences). Don't think out loud. Act and report. Greet naturally without tools. Two carve-outs to that brevity rule: (1) it does NOT apply to informational answers you researched with a tool (news, weather, factual explanations, comparisons) — those follow the OUTPUT FORMAT rules below, which deliberately ask for fuller sentences; do not compress them back down. (2) Stating uncertainty NEVER counts against the length. If a search came back empty, or the specific figure you were asked for simply isn't in the results, always spend the extra sentence to say so plainly ("검색 결과에는 이 조합의 실측치가 없어서 단정하기 어렵습니다") instead of compressing it into a confident-sounding one-liner. Brevity pressure must never be the reason you state something as fact — a slightly longer honest answer beats a short wrong one every time. ANTI-HALLUCINATION: When a tool returns a result, report EXACTLY what the tool returned — never contradict or ignore tool output. If a tool says "(no rows)", say so. Never invent data, file contents, table names, or command output. If you don't know something, call a tool to find out or say you don't know.${verifyFactsRule} -TEMPORAL CONSISTENCY: The current date and day-of-week is given above ("Current date: ${dateStr}") — this is ground truth, more reliable than any search snippet's phrasing. Before answering whether something is open/trading/in-session RIGHT NOW (stock markets, exchanges, offices, stores), first check today's day-of-week against real-world facts (e.g. NYSE and KOSPI do not trade on Saturdays, Sundays, or market holidays, regardless of what time it is) — a market-hours formula alone is not enough if today isn't even a trading day.${searchReadingRule}${searchPersistenceRule}${fileSearchRule}${imageEditRuleBlock}${mediaGenRuleBlock}${browserRuleBlock}${chemistryRuleBlock}${mapsRuleBlock}${placeSearchRuleBlock}${codeOutputRuleBlock}${packageInstallRuleBlock} +TEMPORAL CONSISTENCY: The current date and day-of-week is given above ("Current date: ${dateStr}") — this is ground truth, more reliable than any search snippet's phrasing. Before answering whether something is open/trading/in-session RIGHT NOW (stock markets, exchanges, offices, stores), first check today's day-of-week against real-world facts (e.g. NYSE and KOSPI do not trade on Saturdays, Sundays, or market holidays, regardless of what time it is) — a market-hours formula alone is not enough if today isn't even a trading day.${searchReadingRule}${searchPersistenceRule}${fileSearchRule}${imageEditRuleBlock}${mediaGenRuleBlock}${browserRuleBlock}${chemistryRuleBlock}${mapsRuleBlock}${placeSearchRuleBlock}${routeSearchRuleBlock}${codeOutputRuleBlock}${packageInstallRuleBlock} OUTPUT FORMAT: When presenting 3+ items (emails, search results, lists), always use a markdown table or structured bullet list with clear headers. Never dump them as a long paragraph.${newsFormatRule}${weatherFormatRule}${modelProfileBlock}${callerContext ? '\n\n' + callerContext : ''}${browserStateCtx}${personalityCtx}${skillsCtx}`; } diff --git a/src/gateway/chat/tool-scope.ts b/src/gateway/chat/tool-scope.ts index 764461f..0657ca2 100644 --- a/src/gateway/chat/tool-scope.ts +++ b/src/gateway/chat/tool-scope.ts @@ -192,6 +192,9 @@ export function buildSkillToolFilter(input: ToolScopeInput): (toolName: string) // 후속 발화("거기 전화번호는?")가 앞 턴의 주제를 물려받으므로 topicText로 검사한다. 스테일 매치 비용은 // 스키마 토큰뿐. "병원"은 CMS 병원 성과 질문과 겹쳐서 단독으로는 넣지 않고 근처·위치 어휘와 함께만 본다. const hasPlaceKeyword = /근처|주변|가까운|인근|맛집|약국|식당|카페|편의점|주유소|마트|주차장|지도|길\s*찾|가는\s*길|어디(?:에|야|예요|있)|전화\s*번호|영업\s*시간|몇\s*시까지|주소|위치/i.test(topicText); + // route_search — 카카오모빌리티 자동차 길찾기(2026-10-14). 길·소요시간·통행료 어휘에만 연다. + // "얼마나 걸려"는 일반 문장에서도 흔해서 이동 수단·목적지 어휘와 함께 있을 때만 본다. + const hasRouteKeyword = /길\s*찾|길\s*안내|내비|네비|가는\s*길|오는\s*길|경로|통행료|톨게이트|하이패스|고속도로|운전해서|차로|자동차로|까지\s*(?:얼마나|몇\s*분|몇\s*시간|가는|거리)|(?:얼마나|몇\s*시간|몇\s*분)\s*(?:걸려|걸려요|걸리|소요)|소요\s*시간|걸리는\s*시간|거리(?:가|는)?\s*(?:얼마|몇)|\bdirections?\b|route|navigate/i.test(topicText); // print3d_model — STL 슬라이싱+K2 프린터 업로드. topicText로 검사(prepare→start 확인 // 왕복이 여러 턴 걸치므로 nvr_snapshot과 같은 이유로 최근 대화 전체를 봄). const hasPrint3dKeyword = /3d\s*프린트|3d\s*print|stl|슬라이싱|슬라이서|g-?code|출력해|프린터로|k2\s*(?:콤보|프린터)?/i.test(topicText); @@ -401,6 +404,7 @@ export function buildSkillToolFilter(input: ToolScopeInput): (toolName: string) if ((name === 'eonet_events' || name === 'satellite_snapshot') && !hasSatelliteKeyword) return false; if (name === 'nvr_snapshot' && !hasCctvKeyword) return false; if (name === 'place_search' && !hasPlaceKeyword) return false; + if (name === 'route_search' && !hasRouteKeyword) return false; if (name === 'print3d_model' && !hasPrint3dKeyword) return false; // model_search/model_download — 09-23: 3D 모델 저장소(Printables/MakerWorld/Thingiverse) // 검색·다운로드. 작업실 세션(ws_)에선 항상 노출, 메인 채팅에선 print3d_model과 같은 diff --git a/src/tools/kakao-places.ts b/src/tools/kakao-places.ts index 130c96b..0604222 100644 --- a/src/tools/kakao-places.ts +++ b/src/tools/kakao-places.ts @@ -85,7 +85,7 @@ async function kakaoGet(endpoint: string, params: Record, key: s return JSON.parse(text); } -async function resolveCenter(location: string, key: string): Promise<{ lat: number; lon: number; name: string; found: boolean }> { +export async function resolveCenter(location: string, key: string): Promise<{ lat: number; lon: number; name: string; found: boolean }> { const loc = String(location || '').trim(); if (!loc) return { ...DEFAULT_CENTER, found: true }; const cm = getConfig(); diff --git a/src/tools/kakao-route.ts b/src/tools/kakao-route.ts new file mode 100644 index 0000000..fc18e2d --- /dev/null +++ b/src/tools/kakao-route.ts @@ -0,0 +1,152 @@ +/** + * kakao-route.ts — 카카오모빌리티 자동차 길찾기 채팅 도구(route_search). + * + * "구미에서 현풍까지 얼마나 걸려?", "구미역까지 가는 길" 류. 거리·소요시간·통행료·택시요금과 + * 주요 도로 구성, 정체 구간 길이를 돌려주고 카카오맵 길찾기 링크를 붙인다. + * 키는 place_search와 같은 REST 키(vault channels.kakao.appKey). 별도 신청 없이 호출된다(2026-10-14 확인). + * 출발지 기본값은 구미시. 지점 해석은 place_search의 resolveCenter(주소 REGION → 키워드 첫 결과)를 쓴다. + */ +import { ToolResult } from '../types.js'; +import { getConfig } from '../config/config.js'; +import { getVault } from '../security/vault.js'; +import { resolveCenter, DEFAULT_CENTER } from './kakao-places.js'; + +const NAVI_BASE = 'https://apis-navi.kakaomobility.com/v1/directions'; + +function getRestKey(): string | undefined { + try { + const cm = getConfig(); + return cm.resolveSecret((cm.getConfig() as any).channels?.kakao?.appKey) + || getVault(cm.getConfigDir()).get('channels.kakao.appKey', 'kakao:route')?.expose(); + } catch { return undefined; } +} + +export function fmtDuration(sec: number): string { + const m = Math.round(sec / 60); + if (m < 60) return `${m}분`; + const h = Math.floor(m / 60), r = m % 60; + return r ? `${h}시간 ${r}분` : `${h}시간`; +} + +export function fmtKm(m: number): string { + return m >= 1000 ? `${(m / 1000).toFixed(m >= 100_000 ? 0 : 1)}km` : `${Math.round(m)}m`; +} + +export interface RoadSeg { name?: string; distance?: number; traffic_state?: number } + +/** 연속된 같은 도로를 합쳐 minMeters 이상인 것만 순서대로. 이름 없는 구간은 버린다. */ +export function mainRoads(roads: RoadSeg[], minMeters = 2000, limit = 8): Array<{ name: string; meters: number }> { + const merged: Array<{ name: string; meters: number }> = []; + for (const r of roads || []) { + const name = String(r.name || '').trim() || '(이름 없는 도로)'; + const d = Number(r.distance) || 0; + const last = merged[merged.length - 1]; + if (last && last.name === name) last.meters += d; + else merged.push({ name, meters: d }); + } + return merged.filter(x => x.meters >= minMeters && x.name !== '(이름 없는 도로)').slice(0, limit); +} + +/** traffic_state 1(정체)·2(지체)·3(서행) 구간 합. */ +export function congestedMeters(roads: RoadSeg[]): number { + return (roads || []).reduce((s, r) => s + ([1, 2, 3].includes(Number(r.traffic_state)) ? (Number(r.distance) || 0) : 0), 0); +} + +const encName = (n: string) => encodeURIComponent(n).replace(/[()!'*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase()); + +/** 카카오맵 자동차 길찾기 링크. 출발·도착 좌표를 박아 둔다. */ +export function kakaoRouteLink(o: { name: string; lat: number; lon: number }, d: { name: string; lat: number; lon: number }): string { + return `https://map.kakao.com/link/by/car/${encName(o.name)},${o.lat},${o.lon}/${encName(d.name)},${d.lat},${d.lon}`; +} + +export interface RoutePoint { name: string; lat: number; lon: number } + +export function formatRoute(route: any, origin: RoutePoint, dest: RoutePoint, via: RoutePoint[], priority: string): string { + const s = route.summary || {}; + const roads: RoadSeg[] = (route.sections || []).flatMap((x: any) => x.roads || []); + const lines: string[] = []; + lines.push(`출발: ${origin.name} → 도착: ${dest.name}${via.length ? ` (경유: ${via.map(v => v.name).join(', ')})` : ''}`); + lines.push(`거리 ${fmtKm(Number(s.distance) || 0)} · 소요 ${fmtDuration(Number(s.duration) || 0)} (자동차, ${priority === 'TIME' ? '최단시간' : priority === 'DISTANCE' ? '최단거리' : '추천'} 경로)`); + const fare = s.fare || {}; + const money: string[] = []; + if (fare.toll != null) money.push(`통행료 ${Number(fare.toll).toLocaleString('ko-KR')}원`); + if (fare.taxi != null) money.push(`택시 요금 추정 ${Number(fare.taxi).toLocaleString('ko-KR')}원`); + if (money.length) lines.push(money.join(' · ')); + const main = mainRoads(roads); + if (main.length) lines.push(`주요 도로: ${main.map(m => `${m.name} ${fmtKm(m.meters)}`).join(' → ')}`); + const cong = congestedMeters(roads); + lines.push(cong >= 500 ? `정체·지체·서행 구간 약 ${fmtKm(cong)}` : '정체 구간 거의 없음'); + lines.push(`길찾기 지도: ${kakaoRouteLink(origin, dest)}`); + return lines.join('\n'); +} + +async function navi(params: URLSearchParams, key: string): Promise { + const res = await fetch(`${NAVI_BASE}?${params}`, { headers: { Authorization: `KakaoAK ${key}` }, signal: AbortSignal.timeout(15_000) }); + const text = await res.text(); + if (!res.ok) { + let msg = text.slice(0, 160); + try { const j = JSON.parse(text); msg = j.msg || j.message || msg; } catch { /* keep */ } + throw new Error(`카카오모빌리티 길찾기 ${res.status}: ${msg}`); + } + return JSON.parse(text); +} + +const AVOID_OK = new Set(['toll', 'motorway', 'ferries', 'schoolzone', 'uturn']); + +export const routeSearchTool = { + name: 'route_search', + description: + '카카오모빌리티로 국내 자동차 길찾기를 한다: 거리·소요시간·통행료·택시 요금 추정·주요 도로·정체 구간·카카오맵 길찾기 링크를 돌려준다. ' + + '"구미에서 현풍까지 얼마나 걸려?", "OO까지 가는 길", "통행료 얼마야" 같은 요청에 사용. 출발지 기본값은 구미시. ' + + '대중교통·도보·자전거는 지원하지 않는다(그럴 땐 돌려주는 카카오맵 링크로 안내). 한국 밖은 불가. 시간·요금은 도구 값만 말할 것.', + schema: { destination: 'string', origin: 'string?', waypoints: 'string[]?', priority: 'string?', avoid: 'string[]?' }, + jsonSchema: { + type: 'object', + required: ['destination'], + properties: { + destination: { type: 'string', description: '도착지 지역·역·건물·장소 이름(예: "현풍", "서울역", "대구 엑스코")' }, + origin: { type: 'string', description: '출발지(선택, 기본 구미시). 예: "구미역", "대구"' }, + waypoints: { type: 'array', items: { type: 'string' }, description: '경유지 이름 목록(선택, 최대 5개)' }, + priority: { type: 'string', enum: ['RECOMMEND', 'TIME', 'DISTANCE'], description: '경로 기준(기본 RECOMMEND 추천, TIME 최단시간, DISTANCE 최단거리)' }, + avoid: { type: 'array', items: { type: 'string', enum: ['toll', 'motorway', 'ferries', 'schoolzone', 'uturn'] }, description: '피할 것(선택): toll 유료도로, motorway 자동차전용도로, ferries, schoolzone, uturn' }, + }, + additionalProperties: false, + }, + execute: async (args: any): Promise => { + const destName = String(args?.destination || '').trim(); + if (!destName) return { success: false, error: 'destination is required' }; + const key = getRestKey(); + if (!key) return { success: false, error: '카카오 REST 키가 없습니다(vault channels.kakao.appKey).' }; + const priority = ['TIME', 'DISTANCE'].includes(String(args?.priority)) ? String(args.priority) : 'RECOMMEND'; + const avoid = (Array.isArray(args?.avoid) ? args.avoid : []).map(String).filter((a: string) => AVOID_OK.has(a)); + const viaNames: string[] = (Array.isArray(args?.waypoints) ? args.waypoints : []).map((w: any) => String(w).trim()).filter(Boolean).slice(0, 5); + try { + const o = await resolveCenter(String(args?.origin || ''), key); + if (!o.found) return { success: false, error: `출발지 "${args.origin}"를 찾지 못했습니다. 더 구체적인 지역·역 이름으로 다시 시도할 것.` }; + const d = await resolveCenter(destName, key); + if (!d.found) return { success: false, error: `도착지 "${destName}"를 찾지 못했습니다. 더 구체적인 지역·역 이름으로 다시 시도할 것.` }; + const via: RoutePoint[] = []; + for (const w of viaNames) { + const v = await resolveCenter(w, key); + if (!v.found) return { success: false, error: `경유지 "${w}"를 찾지 못했습니다.` }; + via.push({ name: v.name, lat: v.lat, lon: v.lon }); + } + const params = new URLSearchParams({ + origin: `${o.lon},${o.lat}`, destination: `${d.lon},${d.lat}`, priority, + }); + if (via.length) params.set('waypoints', via.map(v => `${v.lon},${v.lat}`).join('|')); + if (avoid.length) params.set('avoid', avoid.join('|')); + const j = await navi(params, key); + const route = j?.routes?.[0]; + if (!route) return { success: false, error: '경로 응답이 비어 있습니다.' }; + if (route.result_code !== 0) { + return { success: false, error: `길찾기 실패: ${route.result_msg || route.result_code} (출발 ${o.name} → 도착 ${d.name})` }; + } + const origin: RoutePoint = { name: o.name || DEFAULT_CENTER.name, lat: o.lat, lon: o.lon }; + const dest: RoutePoint = { name: d.name, lat: d.lat, lon: d.lon }; + return { success: true, stdout: formatRoute(route, origin, dest, via, priority) }; + } catch (err: any) { + return { success: false, error: err.message }; + } + }, +}; diff --git a/src/tools/registry.ts b/src/tools/registry.ts index 289147e..1610f0a 100644 --- a/src/tools/registry.ts +++ b/src/tools/registry.ts @@ -32,6 +32,7 @@ import { cmsHospitalCompareTool } from './cms.js'; import { drugDurCheckTool } from './mfds.js'; import { nvrSnapshotTool } from './nvr.js'; import { placeSearchTool } from './kakao-places.js'; +import { routeSearchTool } from './kakao-route.js'; import { print3dModelTool } from './print3d.js'; import { modelSearchTool, modelDownloadTool } from './model-search.js'; import { workshopProjectTool } from './workshop-project.js'; @@ -242,6 +243,7 @@ class ToolRegistry { // 집 CCTV 한 프레임 캡처 → 비전 모델이 직접 확인 (감시카메라/마당/현관/택배 확인 요청) this.registerSafe(nvrSnapshotTool); this.registerSafe(placeSearchTool); + this.registerSafe(routeSearchTool); this.registerSafe(print3dModelTool); // 3D 모델 저장소 검색+다운로드 (Printables/MakerWorld/Thingiverse, 2026-09-23) this.registerSafe(modelSearchTool); diff --git a/tests/kakao-route.test.ts b/tests/kakao-route.test.ts new file mode 100644 index 0000000..608157b --- /dev/null +++ b/tests/kakao-route.test.ts @@ -0,0 +1,85 @@ +/** + * route_search — 포맷·도로 병합·링크·툴 스코프 게이트(네트워크 없음). + */ +import { describe, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { fmtDuration, fmtKm, mainRoads, congestedMeters, kakaoRouteLink, formatRoute } from '../src/tools/kakao-route'; +import { buildSkillToolFilter } from '../src/gateway/chat/tool-scope'; + +describe('format helpers', () => { + test('소요시간', () => { + assert.equal(fmtDuration(2700), '45분'); + assert.equal(fmtDuration(3443), '57분'); + assert.equal(fmtDuration(3600), '1시간'); + assert.equal(fmtDuration(13680), '3시간 48분'); + }); + test('거리', () => { + assert.equal(fmtKm(420), '420m'); + assert.equal(fmtKm(64768), '64.8km'); + assert.equal(fmtKm(248000), '248km'); + }); +}); + +describe('mainRoads / congestedMeters', () => { + const roads = [ + { name: '', distance: 60, traffic_state: 0 }, + { name: '경부고속도로', distance: 20000, traffic_state: 4 }, + { name: '경부고속도로', distance: 13433, traffic_state: 2 }, + { name: '논공로', distance: 3614, traffic_state: 1 }, + { name: '골목길', distance: 300, traffic_state: 4 }, + ]; + test('연속 같은 도로를 합치고 짧은 구간·이름 없는 구간은 뺀다', () => { + assert.deepEqual(mainRoads(roads), [ + { name: '경부고속도로', meters: 33433 }, + { name: '논공로', meters: 3614 }, + ]); + }); + test('정체(1)·지체(2)·서행(3) 구간 합', () => { + assert.equal(congestedMeters(roads), 13433 + 3614); + }); +}); + +describe('formatRoute', () => { + const o = { name: '경북 구미시', lat: 36.1196, lon: 128.3442 }; + const d = { name: '대구 달성군 현풍읍', lat: 35.6972, lon: 128.4476 }; + const route = { + summary: { distance: 64768, duration: 3443, fare: { taxi: 89800, toll: 3600 } }, + sections: [{ roads: [{ name: '경부고속도로', distance: 33433, traffic_state: 4 }, { name: '논공로', distance: 3614, traffic_state: 1 }] }], + }; + test('거리·시간·요금·도로·링크를 낸다', () => { + const t = formatRoute(route, o, d, [], 'RECOMMEND'); + assert.match(t, /출발: 경북 구미시 → 도착: 대구 달성군 현풍읍/); + assert.match(t, /거리 64\.8km · 소요 57분 \(자동차, 추천 경로\)/); + assert.match(t, /통행료 3,600원 · 택시 요금 추정 89,800원/); + assert.match(t, /주요 도로: 경부고속도로 33\.4km → 논공로 3\.6km/); + assert.match(t, /map\.kakao\.com\/link\/by\/car\//); + }); + test('경유지·최단시간 표기', () => { + const t = formatRoute(route, o, d, [{ name: '칠곡', lat: 36, lon: 128 }], 'TIME'); + assert.match(t, /\(경유: 칠곡\)/); + assert.match(t, /최단시간 경로/); + }); + test('정체가 거의 없으면 그렇게 말한다', () => { + const r2 = { ...route, sections: [{ roads: [{ name: '경부고속도로', distance: 33433, traffic_state: 4 }] }] }; + assert.match(formatRoute(r2, o, d, [], 'RECOMMEND'), /정체 구간 거의 없음/); + }); +}); + +describe('kakaoRouteLink', () => { + test('이름은 인코딩하고 ( ) 도 인코딩한다', () => { + const l = kakaoRouteLink({ name: '구미역(경부선)', lat: 1, lon: 2 }, { name: '서울역', lat: 3, lon: 4 }); + assert.ok(!/[()]/.test(l)); + assert.match(l, /^https:\/\/map\.kakao\.com\/link\/by\/car\/.+,1,2\/.+,3,4$/); + }); +}); + +describe('route_search 툴 스코프', () => { + const base = { sessionId: 's', userWorkspace: null, isSkillEnabledForUser: () => true }; + const f = (m: string) => buildSkillToolFilter({ ...base, message: m })('route_search'); + test('길찾기 질문엔 열린다', () => { + for (const m of ['구미에서 현풍까지 얼마나 걸려?', '서울역 가는 길 알려줘', '대구까지 통행료 얼마야', '네비 찍어줘', '현풍까지 몇 시간 걸려']) assert.equal(f(m), true, m); + }); + test('무관한 질문엔 닫힌다', () => { + for (const m of ['안녕', '내일 구미 날씨', '이 코드 고쳐줘']) assert.equal(f(m), false, m); + }); +}); diff --git a/web-ui/js/app/markdown.js b/web-ui/js/app/markdown.js index 6f0eb1e..977165c 100644 --- a/web-ui/js/app/markdown.js +++ b/web-ui/js/app/markdown.js @@ -272,7 +272,7 @@ function renderMarkdown(text, opts) { // Kakao Map URLs on their own line → inline iframe (2026-10-14: 국내 지도는 구글 대신 카카오맵). // map.kakao.com/link/map|search|to/... 는 이름·좌표만으로 열리는 공개 링크 형식이다(키 불필요). - html = html.replace(/((?:^|\n)[ \t]*)(https:\/\/map\.kakao\.com\/link\/(?:map|search|to)\/[^\s<>")\n]+)([ \t]*)(?=\n|$)/gim, function(m, pre, url, post) { + html = html.replace(/((?:^|\n)[ \t]*)(https:\/\/map\.kakao\.com\/link\/(?:map|search|to|by)\/[^\s<>")\n]+)([ \t]*)(?=\n|$)/gim, function(m, pre, url, post) { var safeEmbed = url.replace(/"/g, '"'); return pre + '' + post; });