From 376464a928134009187bafb8a83b4a2322a5b729 Mon Sep 17 00:00:00 2001 From: kim Date: Sun, 25 Oct 2026 10:38:29 +0900 Subject: [PATCH] =?UTF-8?q?exchange=5Frate=20=EB=8F=84=EA=B5=AC:=20?= =?UTF-8?q?=ED=99=98=EC=9C=A8=20=EC=A1=B0=ED=9A=8C=C2=B7=ED=99=98=EC=82=B0?= =?UTF-8?q?=20=E2=80=94=20=EC=9C=A0=EB=9F=BD=EC=A4=91=EC=95=99=EC=9D=80?= =?UTF-8?q?=ED=96=89=20=EA=B8=B0=EC=A4=80=ED=99=98=EC=9C=A8(frankfurter.de?= =?UTF-8?q?v)=20=E2=86=92=20ExchangeRate-API=20=EC=9D=BC=EC=9D=BC=20?= =?UTF-8?q?=ED=99=98=EC=9C=A8(open.er-api.com,=20160=EC=97=AC=20=ED=86=B5?= =?UTF-8?q?=ED=99=94)=20=ED=8F=B4=EB=B0=B1,=20=ED=82=A4=20=EB=B6=88?= =?UTF-8?q?=ED=95=84=EC=9A=94,=201=EC=8B=9C=EA=B0=84=20=EC=BA=90=EC=8B=9C.?= =?UTF-8?q?=20=EC=9B=90=ED=99=94=20=EA=B8=B0=EC=A4=80=EC=9C=BC=EB=A1=9C=20?= =?UTF-8?q?=EB=B0=9B=EC=9C=BC=EB=A9=B4=20API=EA=B0=80=20=EC=9C=A0=ED=9A=A8?= =?UTF-8?q?=EC=88=AB=EC=9E=90=202=EC=9E=90=EB=A6=AC=EB=A1=9C=20=EC=9E=98?= =?UTF-8?q?=EB=9D=BC=20=EC=97=AD=ED=99=98=EC=9C=A8=EC=9D=B4=20=ED=8B=80?= =?UTF-8?q?=EC=96=B4=EC=A0=B8(1,316=20vs=201,324)=20=EA=B0=81=20=EC=B6=9C?= =?UTF-8?q?=EC=B2=98=EC=9D=98=20EUR=C2=B7USD=20=ED=91=9C=EC=97=90=EC=84=9C?= =?UTF-8?q?=20=EA=B5=90=EC=B0=A8=20=EA=B3=84=EC=82=B0.=20=ED=95=9C?= =?UTF-8?q?=EA=B5=AD=EC=96=B4=20=ED=86=B5=ED=99=94=EB=AA=85(=EB=8B=AC?= =?UTF-8?q?=EB=9F=AC=C2=B7=EC=97=94=ED=99=94=C2=B7=ED=99=8D=EC=BD=A9=20?= =?UTF-8?q?=EB=8B=AC=EB=9F=AC=E2=80=A6),=20=EA=B8=88=EC=95=A1=20=EB=B2=94?= =?UTF-8?q?=EC=9C=84=20=ED=99=98=EC=82=B0,=20=EC=97=94=C2=B7=EB=8F=99?= =?UTF-8?q?=EC=9D=80=20100=EB=8B=A8=EC=9C=84,=20=EA=B8=B0=EC=A4=80?= =?UTF-8?q?=EC=9D=BC=C2=B7=EC=9D=80=ED=96=89=20=EC=88=98=EC=88=98=EB=A3=8C?= =?UTF-8?q?=20=EC=95=88=EB=82=B4.=20=EA=B2=8C=EC=9D=B4=ED=8A=B8:=20?= =?UTF-8?q?=ED=99=98=EC=9C=A8=C2=B7=ED=86=B5=ED=99=94=20=EC=96=B4=ED=9C=98?= =?UTF-8?q?,=20=EB=98=90=EB=8A=94=20=EC=A7=81=EC=A0=84=20=EB=8B=B5?= =?UTF-8?q?=EC=97=90=20=EC=99=B8=ED=99=94=20=EA=B8=88=EC=95=A1=EC=9D=B4=20?= =?UTF-8?q?=EC=9E=88=EA=B3=A0=20=EC=9D=B4=EB=B2=88=20=EB=A7=90=EC=9D=B4=20?= =?UTF-8?q?=EC=9B=90=ED=99=94=EB=A5=BC=20=EB=AC=BC=EC=9D=84=20=EB=95=8C.?= =?UTF-8?q?=20=EA=B3=84=EA=B8=B0:=20=EB=AA=AC=ED=83=9C=EB=82=98=20?= =?UTF-8?q?=EC=9E=84=EB=8C=80=EB=A3=8C=20=EB=8C=80=ED=99=94=EC=97=90?= =?UTF-8?q?=EC=84=9C=20=EB=AA=A8=EB=8D=B8=EC=9D=B4=20"1=EB=8B=AC=EB=9F=AC?= =?UTF-8?q?=20=EC=95=BD=201,400=EC=9B=90=20=EA=B0=80=EC=A0=95"(=EC=8B=A4?= =?UTF-8?q?=EC=A0=9C=201,324.45=EC=9B=90).=20=EC=9E=AC=ED=98=84:=20"300?= =?UTF-8?q?=EB=A7=8C=20=EC=9B=90=20=EC=A0=95=EB=8F=84=EB=9E=80=20=EA=B1=B0?= =?UTF-8?q?=EC=A7=80=3F"=EC=97=90=20exchange=5Frate(USD,[1600,2400])=202/2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- src/gateway/chat/build-tools.ts | 15 ++++ src/gateway/chat/system-prompt.ts | 2 +- src/gateway/chat/tool-scope.ts | 6 ++ src/tools/exchange-rate.ts | 140 ++++++++++++++++++++++++++++++ src/tools/registry.ts | 3 + tests/exchange-rate.test.ts | 54 ++++++++++++ 6 files changed, 219 insertions(+), 1 deletion(-) create mode 100644 src/tools/exchange-rate.ts create mode 100644 tests/exchange-rate.test.ts diff --git a/src/gateway/chat/build-tools.ts b/src/gateway/chat/build-tools.ts index d32d722..d417c1e 100644 --- a/src/gateway/chat/build-tools.ts +++ b/src/gateway/chat/build-tools.ts @@ -1129,6 +1129,21 @@ export function createBuildTools(isOrchestrationSkillEnabled: () => boolean) { }, }, }, + { + type: 'function', + function: { + name: 'exchange_rate', + description: '실제 환율을 조회하고 금액을 환산한다(유럽중앙은행 기준환율 → 일일 환율 폴백). "달러 환율", "엔화 얼마", "$2,400이면 원화로 얼마" 같은 요청이나, 대화 속 외화 금액을 원화로 바꿔 말할 때 사용. 환율을 기억이나 어림값(1달러 1,400원 등)으로 가정하지 말 것. 범위 금액은 amounts에 양 끝을 모두 넣는다. 답에 기준일을 밝힐 것.', + parameters: { + type: 'object', required: ['from'], + properties: { + from: { type: 'string', description: '바꿀 통화: ISO 코드(USD, JPY…) 또는 한국어 이름(달러, 엔화, 유로…)' }, + to: { type: 'string', description: '대상 통화, 여러 개면 쉼표로(기본 KRW)' }, + amounts: { type: 'array', items: { type: 'number' }, description: '환산할 금액들(from 통화 기준, 선택). 예: [1600, 2400]' }, + }, + }, + }, + }, { type: 'function', function: { diff --git a/src/gateway/chat/system-prompt.ts b/src/gateway/chat/system-prompt.ts index bb766ba..93ac5f7 100644 --- a/src/gateway/chat/system-prompt.ts +++ b/src/gateway/chat/system-prompt.ts @@ -274,7 +274,7 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string { // "지도 열어줘"에 어느 곳이냐고 되물음 / "한달살기로 좋은 곳" 다음 임대료 질문에 장기 계약 시세를 검색 / // "한달에 300만 원 정도란 거지?"($1,600~2,400)에 "아니요"로 시작해 놓고 224만~336만 원이라고 계산. // 이력은 다 넘어갔으니 모델 판단 문제 — 정확성만 말하는 프롬프트가 맥락을 경직시킨 쪽으로 본다. - const continuityRule = 'CONVERSATION CONTINUITY: Read every message as the next line of this conversation. A short or elliptical message ("지도 열어줘", "한달살기로는?", "그럼 가격은?") continues the current topic — fill in the place, people, duration and conditions already established instead of asking the user to repeat them, and carry those conditions into any tool query (e.g. after "한 달 살기" a rent question means short-term monthly rentals, not 12-month leases). A confirmation question ("~란 거지?", "~맞지?") gets 네/아니요 first, judged against your own earlier answer, then one line of why — never open with 아니요 and then confirm the same number. Arithmetic or unit conversion on numbers already in the conversation is reasoning, not a new fact: just do it (state an assumed rate if one is needed). Ask a clarifying question only when the conversation genuinely leaves it open.'; + const continuityRule = `CONVERSATION CONTINUITY: Read every message as the next line of this conversation. A short or elliptical message ("지도 열어줘", "한달살기로는?", "그럼 가격은?") continues the current topic — fill in the place, people, duration and conditions already established instead of asking the user to repeat them, and carry those conditions into any tool query (e.g. after "한 달 살기" a rent question means short-term monthly rentals, not 12-month leases). A confirmation question ("~란 거지?", "~맞지?") gets 네/아니요 first, judged against your own earlier answer, then one line of why — never open with 아니요 and then confirm the same number. Arithmetic or unit conversion on numbers already in the conversation is reasoning, not a new fact: just do it${toolNames.has('exchange_rate') ? ' (for a currency conversion get the real rate from exchange_rate instead of assuming one)' : ' (state an assumed rate if one is needed)'}. Ask a clarifying question only when the conversation genuinely leaves it open.`; const imageEditRuleBlock = toolNames.has('image_edit') ? '\nIMAGE EDITING RULE: Do not call image_edit (or any editing tool) when a user uploads a photo without explicitly requesting edits. Uploading a photo is NOT a request to edit it. Only call image_edit when the user\'s message explicitly asks for an edit (e.g. "수채화로 바꿔줘", "회전해줘"). Violating this rule is a critical error.' : ''; diff --git a/src/gateway/chat/tool-scope.ts b/src/gateway/chat/tool-scope.ts index 3ad7b03..f97d70d 100644 --- a/src/gateway/chat/tool-scope.ts +++ b/src/gateway/chat/tool-scope.ts @@ -192,6 +192,11 @@ export function buildSkillToolFilter(input: ToolScopeInput): (toolName: string) // 후속 발화("거기 전화번호는?")가 앞 턴의 주제를 물려받으므로 topicText로 검사한다. 스테일 매치 비용은 // 스키마 토큰뿐. "병원"은 CMS 병원 성과 질문과 겹쳐서 단독으로는 넣지 않고 근처·위치 어휘와 함께만 본다. const hasPlaceKeyword = /근처|주변|가까운|인근|맛집|약국|식당|카페|편의점|주유소|마트|주차장|지도|길\s*찾|가는\s*길|어디(?:에|야|예요|있)|전화\s*번호|영업\s*시간|몇\s*시까지|주소|위치/i.test(topicText); + // exchange_rate — 환율 조회·환산(2026-10-25). 환율·통화 어휘가 최근 사용자 발화에 있거나, 직전 답에 외화 + // 금액이 있고 이번 말이 원화 금액·환산을 물을 때("한달에 300만 원 정도란 거지?" ← 직전 답 "$1,600~2,400"). + const FX_WORDS = /환율|환전|환산|원화로|달러|엔화|유로|위안|파운드|바트|페소|\$\s?\d|\d\s?(?:엔|위안)(?!진)|\b(?:USD|JPY|EUR|CNY|GBP|AUD|CAD|HKD|TWD|VND|THB)\b|exchange\s*rate|currency/i; + const hasFxKeyword = FX_WORDS.test(topicText) + || (/\$\s?\d|\d\s?(?:USD|EUR|JPY)|€\s?\d|¥\s?\d/.test(String(input.lastAssistantMsg || '')) && /원|얼마|환산|우리\s*돈|한화/.test(message)); // 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); @@ -408,6 +413,7 @@ export function buildSkillToolFilter(input: ToolScopeInput): (toolName: string) if (name === 'nvr_snapshot' && !hasCctvKeyword) return false; if (name === 'place_search' && !hasPlaceKeyword) return false; if (name === 'route_search' && !hasRouteKeyword) return false; + if (name === 'exchange_rate' && !hasFxKeyword) 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/exchange-rate.ts b/src/tools/exchange-rate.ts new file mode 100644 index 0000000..1a4624b --- /dev/null +++ b/src/tools/exchange-rate.ts @@ -0,0 +1,140 @@ +/** + * exchange_rate — 환율 조회·환산 (2026-10-25 사용자 요청 "환율 도구도 추가해줘"). + * + * 계기: 몬태나 임대료 대화에서 모델이 "1달러 약 1,400원으로 가정"하고 계산했는데 그날 실제 기준환율은 + * 1,324원이었다(6% 차이). 환율은 키 없는 공개 API 두 곳에서 받는다. + * 1) frankfurter.dev — 유럽중앙은행(ECB) 고시 기준환율, 약 30개 주요 통화, 영업일마다 갱신 + * 2) open.er-api.com — ExchangeRate-API 무료판, 160여 개 통화, 하루 1회 갱신 + * 1)에 없는 통화(베트남 동·대만 달러 등)이거나 1)이 실패하면 2)를 쓴다. 은행 창구 환율(살 때/팔 때)은 + * 기준환율에 수수료가 붙어 몇 % 다르므로 결과에 그 점을 한 줄 붙인다. + */ +import { ToolResult } from '../types.js'; + +const CACHE_MS = 60 * 60 * 1000; + +/** 한국어 통화 이름 → ISO 코드. 긴 이름을 먼저 본다("홍콩 달러"가 "달러"에 먹히지 않게). */ +const CURRENCY_ALIASES: Array<[RegExp, string]> = [ + [/홍콩\s*달러|홍콩/, 'HKD'], [/대만\s*달러|대만|타이완/, 'TWD'], [/싱가포르\s*달러|싱가포르/, 'SGD'], + [/호주\s*달러|호주/, 'AUD'], [/캐나다\s*달러|캐나다/, 'CAD'], [/뉴질랜드\s*달러|뉴질랜드/, 'NZD'], + [/미국\s*달러|미\s*달러|달러|불/, 'USD'], [/원화|한국\s*원|^원$/, 'KRW'], [/엔화|^엔$|일본/, 'JPY'], + [/유로/, 'EUR'], [/위안|런민비|인민폐|중국/, 'CNY'], [/파운드|영국/, 'GBP'], [/스위스\s*프랑|프랑/, 'CHF'], + [/바트|태국/, 'THB'], [/베트남\s*동|^동$|베트남/, 'VND'], [/페소|필리핀/, 'PHP'], [/루피아|인도네시아/, 'IDR'], + [/링깃|말레이시아/, 'MYR'], [/루피|인도/, 'INR'], [/루블|러시아/, 'RUB'], [/멕시코/, 'MXN'], +]; + +export function toCurrencyCode(raw: string): string | null { + const s = String(raw || '').trim(); + if (!s) return null; + if (/^[A-Za-z]{3}$/.test(s)) return s.toUpperCase(); + for (const [re, code] of CURRENCY_ALIASES) if (re.test(s)) return code; + return null; +} + +export interface RateTable { base: string; date: string; source: string; rates: Record } + +const cache = new Map(); + +async function getJson(url: string): Promise { + const res = await fetch(url, { signal: AbortSignal.timeout(10_000), headers: { 'User-Agent': 'homeclaw/1.0' } }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + return res.json(); +} + +// 원화 같은 작은 단위를 기준(base)으로 받으면 API가 0.00076처럼 유효숫자 두 자리로 잘라 준다(역환율이 +// 1,316원으로 틀어짐). 그래서 각 출처의 기본 기준(EUR·USD) 표 하나만 받아 교차 환율로 계산한다. +async function fetchFrankfurter(): Promise { + const j = await getJson('https://api.frankfurter.dev/v1/latest?base=EUR'); + if (!j?.rates) throw new Error('frankfurter: rates 없음'); + return { base: 'EUR', date: String(j.date || ''), source: '유럽중앙은행(ECB) 고시 기준환율', rates: { ...j.rates, EUR: 1 } }; +} + +async function fetchOpenEr(): Promise { + const base = 'USD'; + const j = await getJson(`https://open.er-api.com/v6/latest/${base}`); + if (j?.result !== 'success' || !j?.rates) throw new Error(`open.er-api: ${j?.['error-type'] || '실패'}`); + const date = j.time_last_update_unix ? new Date(j.time_last_update_unix * 1000).toISOString().slice(0, 10) : ''; + return { base, date, source: 'ExchangeRate-API 일일 환율', rates: j.rates }; +} + +/** base 기준 환율표 — base와 targets가 전부 있는 첫 출처의 표를 base 기준으로 바꿔 돌려준다. */ +async function rateTable(base: string, targets: string[]): Promise { + const errors: string[] = []; + for (const [name, fn] of [['frankfurter', fetchFrankfurter], ['open-er', fetchOpenEr]] as const) { + const hit = cache.get(name); + let table = hit && Date.now() - hit.at < CACHE_MS ? hit.table : null; + if (!table) { + try { table = await fn(); cache.set(name, { at: Date.now(), table }); } + catch (e: any) { errors.push(`${name}: ${e.message}`); continue; } + } + const missing = [base, ...targets].filter((c) => typeof table!.rates[c] !== 'number'); + if (missing.length) { errors.push(`${name}: ${missing.join(',')} 없음`); continue; } + const rates: Record = {}; + for (const t of targets) rates[t] = table.rates[t] / table.rates[base]; + return { base, date: table.date, source: table.source, rates }; + } + throw new Error(errors.join(' / ')); +} + +/** 금액: 1,000 이상은 정수, 그 아래는 소수 둘째 자리. */ +function fmt(n: number): string { + const digits = Math.abs(n) >= 1000 ? 0 : 2; + return n.toLocaleString('en-US', { maximumFractionDigits: digits, minimumFractionDigits: 0 }); +} + +/** 환율: 1 이상은 소수 둘째 자리(1,324.45), 1 미만은 유효숫자 4자리(0.0007550). */ +function fmtRate(r: number): string { + if (Math.abs(r) >= 1) return r.toLocaleString('en-US', { maximumFractionDigits: 2, minimumFractionDigits: 0 }); + return Number(r.toPrecision(4)).toString(); +} + +export function formatRates(t: RateTable, targets: string[], amounts: number[]): string { + const lines = [`기준일 ${t.date} · ${t.source}`]; + for (const to of targets) { + const r = t.rates[to]; + // 엔·동처럼 단위가 작은 통화를 원화로 볼 때는 100단위 관례도 함께. + const per100 = (t.base === 'JPY' || t.base === 'VND') && to === 'KRW' ? `, 100 ${t.base} = ${fmtRate(r * 100)} ${to}` : ''; + lines.push(`1 ${t.base} = ${fmtRate(r)} ${to}${per100} (역환율 1 ${to} = ${fmtRate(1 / r)} ${t.base})`); + for (const a of amounts) lines.push(` ${fmt(a)} ${t.base} = ${fmt(a * r)} ${to}`); + } + lines.push('※ 기준환율이라 은행에서 살 때·팔 때는 수수료만큼(보통 1~2%) 다름. 답에 기준일을 함께 밝힐 것.'); + return lines.join('\n'); +} + +export const exchangeRateTool = { + name: 'exchange_rate', + description: + '실제 환율을 조회하고 금액을 환산한다(키 없는 공개 API, 유럽중앙은행 기준환율 → 일일 환율 폴백). ' + + '"달러 환율", "엔화 얼마", "$2,400이면 원화로 얼마", "300만 원은 달러로" 같은 요청이나, 대화 속 외화 금액을 원화로 바꿔 말해야 할 때 사용. ' + + '환율을 기억이나 어림값(예: 1달러 1,400원)으로 가정하지 말고 이 도구로 확인할 것. 범위 금액은 amounts에 양 끝을 모두 넣는다.', + schema: { from: 'string', to: 'string?', amounts: 'number[]?' }, + jsonSchema: { + type: 'object', + required: ['from'], + properties: { + from: { type: 'string', description: '바꿀 통화: ISO 코드(USD, JPY…) 또는 한국어 이름(달러, 엔화, 유로…)' }, + to: { type: 'string', description: '바꿀 대상 통화, 여러 개면 쉼표로(기본 KRW). 예: "KRW", "KRW,JPY"' }, + amounts: { type: 'array', items: { type: 'number' }, description: '환산할 금액들(from 통화 기준, 선택). 예: [1600, 2400]' }, + }, + additionalProperties: false, + }, + execute: async (args: any): Promise => { + const base = toCurrencyCode(args?.from); + if (!base) return { success: false, error: `통화를 알아보지 못했습니다: "${args?.from}". ISO 코드(USD, JPY 등)로 다시 지정할 것.` }; + const toRaw = String(args?.to || 'KRW').split(/[,\s/]+/).filter(Boolean); + const targets: string[] = []; + for (const r of toRaw) { + const c = toCurrencyCode(r); + if (!c) return { success: false, error: `통화를 알아보지 못했습니다: "${r}".` }; + if (c !== base && !targets.includes(c)) targets.push(c); + } + if (!targets.length) return { success: false, error: 'from과 다른 대상 통화(to)를 지정할 것.' }; + const amounts = (Array.isArray(args?.amounts) ? args.amounts : args?.amounts != null ? [args.amounts] : []) + .map((a: any) => Number(String(a).replace(/,/g, ''))).filter((a: number) => Number.isFinite(a)).slice(0, 6); + try { + const t = await rateTable(base, targets); + return { success: true, stdout: formatRates(t, targets, amounts), data: { base, date: t.date, rates: Object.fromEntries(targets.map((x) => [x, t.rates[x]])) } }; + } catch (e: any) { + return { success: false, error: `환율을 가져오지 못했습니다(${e.message}). 환율을 짐작해서 말하지 말고 조회 실패를 그대로 전할 것.` }; + } + }, +}; diff --git a/src/tools/registry.ts b/src/tools/registry.ts index 4b6c727..cebf0ff 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 { phonePhotoTool } from './phone-photo.js'; +import { exchangeRateTool } from './exchange-rate.js'; import { placeSearchTool } from './kakao-places.js'; import { routeSearchTool } from './kakao-route.js'; import { print3dModelTool } from './print3d.js'; @@ -245,6 +246,8 @@ class ToolRegistry { this.registerSafe(nvrSnapshotTool); // 작업실 채팅 전용: Z Fold 3(무선 ADB)로 촬영·최근 사진 가져오기 → 프로젝트 사진/ (2026-10-25) this.registerSafe(phonePhotoTool); + // 환율 조회·환산(키 없는 공개 API, 2026-10-25) + this.registerSafe(exchangeRateTool); this.registerSafe(placeSearchTool); this.registerSafe(routeSearchTool); this.registerSafe(print3dModelTool); diff --git a/tests/exchange-rate.test.ts b/tests/exchange-rate.test.ts new file mode 100644 index 0000000..7aa30b4 --- /dev/null +++ b/tests/exchange-rate.test.ts @@ -0,0 +1,54 @@ +/** + * exchange_rate — 통화 이름 해석·결과 포맷·툴 스코프 게이트(네트워크 없음). + */ +import { describe, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { toCurrencyCode, formatRates } from '../src/tools/exchange-rate'; +import { buildSkillToolFilter } from '../src/gateway/chat/tool-scope'; + +describe('toCurrencyCode', () => { + test('ISO 코드와 한국어 이름', () => { + assert.equal(toCurrencyCode('usd'), 'USD'); + assert.equal(toCurrencyCode('달러'), 'USD'); + assert.equal(toCurrencyCode('홍콩 달러'), 'HKD'); + assert.equal(toCurrencyCode('엔화'), 'JPY'); + assert.equal(toCurrencyCode('원화'), 'KRW'); + assert.equal(toCurrencyCode('인도네시아 루피아'), 'IDR'); + assert.equal(toCurrencyCode('뭔지모를돈'), null); + }); +}); + +describe('formatRates', () => { + test('기준일·출처·환산 금액·수수료 안내', () => { + const t = formatRates({ base: 'USD', date: '2026-10-23', source: 'ECB', rates: { KRW: 1324.45 } }, ['KRW'], [1600, 2400]); + assert.match(t, /기준일 2026-10-23 · ECB/); + assert.match(t, /1 USD = 1,324\.45 KRW/); + assert.match(t, /1,600 USD = 2,119,120 KRW/); + assert.match(t, /2,400 USD = 3,178,680 KRW/); + assert.match(t, /수수료/); + }); + test('엔→원은 100엔 단위도', () => { + const t = formatRates({ base: 'JPY', date: 'd', source: 's', rates: { KRW: 8.45 } }, ['KRW'], []); + assert.match(t, /100 JPY = 845 KRW/); + assert.match(t, /역환율 1 KRW = 0\.1183 JPY/); + }); +}); + +describe('exchange_rate 게이트', () => { + const filter = (message: string, recentUserText = message, lastAssistantMsg = '') => buildSkillToolFilter({ + message, recentUserText, lastAssistantMsg, sessionId: 'abc', userWorkspace: null, isSkillEnabledForUser: () => true, + } as any)('exchange_rate'); + test('환율 어휘면 연다', () => { + assert.equal(filter('오늘 달러 환율 얼마야?'), true); + assert.equal(filter('100엔이면 우리 돈 얼마?'), true); + assert.equal(filter('$2,400이면?'), true); + }); + test('직전 답에 외화 금액이 있고 원화를 물으면 연다', () => { + assert.equal(filter('한달에 300 만원 정도란 거지?', '한달에 300 만원 정도란 거지?', '2베드룸은 월 $1,600~2,400 선입니다.'), true); + }); + test('관계없는 말엔 닫는다', () => { + assert.equal(filter('내일 날씨 어때?'), false); + assert.equal(filter('엔진 오일 교체 주기'), false); + assert.equal(filter('한달에 300 만원 정도란 거지?'), false); + }); +});