diff --git a/src/tools/news-sources.ts b/src/tools/news-sources.ts new file mode 100644 index 0000000..838df00 --- /dev/null +++ b/src/tools/news-sources.ts @@ -0,0 +1,193 @@ +/** + * news-sources.ts + * + * news_search의 1순위 출처들(2026-10-24, 사용자 결정). NewsData는 이제 마지막 대비책이다. + * + * 나라별 주요 뉴스("오늘 일본 뉴스") → 구글 뉴스 톱기사 RSS → top-headlines.ts 1면 피드 → NewsData + * 검색어 뉴스("무라카미 류 별세") → 시어엔진(SearXNG) 뉴스 → 덕덕고 뉴스 → NewsData + * + * 왜: NewsData는 최신순이라 주요도를 모르고, 일본 1면(야후)은 로이터·AFP 국제 기사가 섞인다. 구글 뉴스 톱기사는 + * 나라마다 국내 기사 위주로 순위가 매겨져 있다(10-24 실측: 일본=황실전범 시행·우크라 정전·태풍). 검색어 쪽은 + * 시어엔진 news 분류(네이버·빙 뉴스)가 요약까지 주고 우리 서버 안이라 막힐 일이 없다. 다만 날짜가 비어 온다. + * 덕덕고 news.js는 요약·원래 주소·날짜를 다 주지만 vqd 토큰을 받아야 하고 많이 쓰면 봇으로 막힐 수 있어 예비로만. + * 구글 뉴스 검색은 요약이 없고 링크가 구글 중계 주소라 검색어 경로에는 넣지 않았다. + * + * 셋 다 비공식 경로다 — 실패는 조용히 []로 돌려 다음 출처로 넘어가게 한다. + */ +import { getConfig } from '../config/config.js'; +import type { Headline } from './top-headlines.js'; + +const FETCH_TIMEOUT_MS = 10_000; +const UA = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36'; + +// 나라 → 구글 뉴스 hl/ceid. 10-24에 하나씩 라이브 확인(qa는 0건이라 뺌). +const GOOGLE_LOCALES: Record = { + kr: ['ko', 'KR:ko'], jp: ['ja', 'JP:ja'], cn: ['zh-CN', 'CN:zh-Hans'], tw: ['zh-TW', 'TW:zh-Hant'], hk: ['zh-HK', 'HK:zh-Hant'], + us: ['en-US', 'US:en'], gb: ['en-GB', 'GB:en'], ca: ['en-CA', 'CA:en'], au: ['en-AU', 'AU:en'], in: ['en-IN', 'IN:en'], + de: ['de', 'DE:de'], fr: ['fr', 'FR:fr'], it: ['it', 'IT:it'], es: ['es', 'ES:es'], nl: ['nl', 'NL:nl'], pl: ['pl', 'PL:pl'], + ru: ['ru', 'RU:ru'], ua: ['uk', 'UA:uk'], tr: ['tr', 'TR:tr'], il: ['he', 'IL:he'], ae: ['ar', 'AE:ar'], sa: ['ar', 'SA:ar'], eg: ['ar', 'EG:ar'], + br: ['pt-BR', 'BR:pt-419'], mx: ['es-419', 'MX:es-419'], ar: ['es-419', 'AR:es-419'], cl: ['es-419', 'CL:es-419'], + co: ['es-419', 'CO:es-419'], pe: ['es-419', 'PE:es-419'], + vn: ['vi', 'VN:vi'], th: ['th', 'TH:th'], id: ['id', 'ID:id'], ph: ['en-PH', 'PH:en'], my: ['en-MY', 'MY:en'], sg: ['en-SG', 'SG:en'], + za: ['en-ZA', 'ZA:en'], ng: ['en-NG', 'NG:en'], ke: ['en-KE', 'KE:en'], gh: ['en-GH', 'GH:en'], +}; +const GOOGLE_PER_COUNTRY = 10; + +// 나라 → 덕덕고 지역(l=). 없는 나라는 wt-wt(전 세계). +const DDG_REGIONS: Record = { + kr: 'kr-kr', jp: 'jp-jp', cn: 'cn-zh', tw: 'tw-tzh', hk: 'hk-tzh', us: 'us-en', gb: 'uk-en', ca: 'ca-en', au: 'au-en', in: 'in-en', + de: 'de-de', fr: 'fr-fr', it: 'it-it', es: 'es-es', nl: 'nl-nl', pl: 'pl-pl', ru: 'ru-ru', ua: 'ua-uk', tr: 'tr-tr', il: 'il-he', + br: 'br-pt', mx: 'mx-es', ar: 'ar-es', cl: 'cl-es', co: 'co-es', pe: 'pe-es', vn: 'vn-vi', th: 'th-th', id: 'id-en', ph: 'ph-en', + my: 'my-en', sg: 'sg-en', za: 'za-en', sa: 'xa-ar', ae: 'xa-ar', eg: 'xa-ar', +}; + +const decode = (s: string) => s + .replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"') + .replace(/�?39;|'/g, "'").replace(/ /g, ' ').replace(/&/g, '&'); +const stripTags = (s: string) => s.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim(); +const hostOf = (url: string) => { try { return new URL(url).hostname.replace(/^www\./, ''); } catch { return ''; } }; + +export function hasGoogleNewsLocale(country: string): boolean { + return String(country || '').toLowerCase().split(',').some(c => !!GOOGLE_LOCALES[c.trim()]); +} + +/** 첫 번째 나라의 언어 — 시어엔진 language= 값으로 쓴다("pt-BR" → "pt"). 모르면 ''. */ +export function languageForCountry(country: string): string { + const first = String(country || '').toLowerCase().split(',')[0]?.trim(); + const loc = first ? GOOGLE_LOCALES[first] : undefined; + return loc ? loc[0].split('-')[0] : ''; +} + +/** + * 구글 뉴스 RSS 항목 → Headline. 제목은 "기사 제목 - 매체명" 꼴이라 매체를 떼어 낸다. 구글은 기사 요약을 주지 + * 않는다 — description은 같은 사건을 다룬 다른 매체 제목 목록이라, 그중 두 개를 요약 자리에 "관련 보도"로 넣어 + * 모델이 제목만 되풀이하지 않게 한다. + */ +export function parseGoogleNewsRss(xml: string, limit = GOOGLE_PER_COUNTRY): Headline[] { + const items = String(xml || '').match(/[\s\S]*?<\/item>/g) || []; + const out: Headline[] = []; + for (const it of items) { + const rawTitle = decode((it.match(/([\s\S]*?)<\/title>/) || [])[1] || '').trim(); + if (!rawTitle) continue; + const srcTag = decode((it.match(/<source[^>]*>([\s\S]*?)<\/source>/) || [])[1] || '').trim(); + const cut = rawTitle.lastIndexOf(' - '); + const title = cut > 0 ? rawTitle.slice(0, cut).trim() : rawTitle; + const source = srcTag || (cut > 0 ? rawTitle.slice(cut + 3).trim() : 'news.google.com'); + const link = decode((it.match(/<link>([\s\S]*?)<\/link>/) || [])[1] || '').trim(); + const published = (it.match(/<pubDate>([\s\S]*?)<\/pubDate>/) || [])[1]?.trim() || ''; + const desc = decode((it.match(/<description>([\s\S]*?)<\/description>/) || [])[1] || ''); + const related = (desc.match(/<li>[\s\S]*?<\/li>/g) || []) + .map(li => { + const t = stripTags((li.match(/<a[^>]*>([\s\S]*?)<\/a>/) || [])[1] || ''); + const s = stripTags((li.match(/<font[^>]*>([\s\S]*?)<\/font>/) || [])[1] || ''); + return t && t !== title ? (s ? `${t} (${s})` : t) : ''; + }) + .filter(Boolean) + .slice(0, 2); + out.push({ title, link, source, summary: related.length ? `관련 보도: ${related.join('; ')}` : '', published }); + if (out.length >= limit) break; + } + return out; +} + +export async function fetchGoogleNewsTop(country: string): Promise<Headline[]> { + const countries = String(country || '').toLowerCase().split(',').map(c => c.trim()).filter(c => GOOGLE_LOCALES[c]); + if (!countries.length) return []; + const settled = await Promise.allSettled(countries.map(async (c) => { + const [hl, ceid] = GOOGLE_LOCALES[c]; + const url = `https://news.google.com/rss?hl=${hl}&gl=${c.toUpperCase()}&ceid=${ceid}`; + const res = await fetch(url, { headers: { 'User-Agent': UA }, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + return parseGoogleNewsRss(await res.text()); + })); + const lists = settled.filter(s => s.status === 'fulfilled').map(s => (s as PromiseFulfilledResult<Headline[]>).value); + // 여러 나라면 번갈아 뽑는다 — top-headlines와 같은 이유(한 나라가 목록을 다 차지하지 않게). + const merged: Headline[] = []; + for (let i = 0; merged.length < 12; i++) { + const before = merged.length; + for (const list of lists) if (list[i] && merged.length < 12) merged.push(list[i]); + if (merged.length === before) break; + } + return merged; +} + +function searxngUrl(): string { + try { + const raw = (getConfig().getConfig() as any)?.search?.searxng_url; + return typeof raw === 'string' ? raw.trim().replace(/\/+$/, '') : ''; + } catch { return ''; } +} + +/** 제목 기준 중복 제거 — 네이버·빙이 같은 기사를 각각 돌려준다. */ +function dedupeByTitle(items: Headline[]): Headline[] { + const seen = new Set<string>(); + return items.filter(h => { + const k = h.title.replace(/\s+/g, '').toLowerCase(); + if (seen.has(k)) return false; + seen.add(k); + return true; + }); +} + +export function parseSearxngNews(json: any, limit = 10): Headline[] { + const results: any[] = Array.isArray(json?.results) ? json.results : []; + return dedupeByTitle(results + .filter(r => r?.title && r?.url) + .map(r => ({ + title: stripTags(decode(String(r.title))), + link: String(r.url), + source: hostOf(String(r.url)), + summary: stripTags(decode(String(r.content || ''))).slice(0, 400), + published: r.publishedDate ? String(r.publishedDate) : '', + }))).slice(0, limit); +} + +/** 하루 범위로 먼저, 3건 미만이면 한 주로 넓힌다(며칠 전 일이 오늘 보도되는 경우 — 무라카미 류는 17일 별세, 23일 보도). */ +export async function searchSearxngNews(query: string, country: string): Promise<Headline[]> { + const base = searxngUrl(); + if (!base || !query) return []; + // 한글 검색어는 나라와 상관없이 한국어 보도를 원한다("일본 지진" + country=jp → 한국 언론의 일본 지진 기사). + const lang = /[가-힣]/.test(query) ? 'ko' : (languageForCountry(country) || 'all'); + const once = async (timeRange: string) => { + const params = new URLSearchParams({ q: query, format: 'json', categories: 'news', language: lang, time_range: timeRange }); + const res = await fetch(`${base}/search?${params}`, { signal: AbortSignal.timeout(20_000) }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + return parseSearxngNews(await res.json()); + }; + try { + const day = await once('day'); + return day.length >= 3 ? day : await once('week'); + } catch { return []; } +} + +export function parseDdgNews(json: any, limit = 10): Headline[] { + const results: any[] = Array.isArray(json?.results) ? json.results : []; + return dedupeByTitle(results + .filter(r => r?.title && r?.url) + .map(r => ({ + title: stripTags(decode(String(r.title))), + link: String(r.url), + source: String(r.source || hostOf(String(r.url))), + summary: stripTags(decode(String(r.excerpt || ''))).slice(0, 400), + published: typeof r.date === 'number' ? new Date(r.date * 1000).toISOString() : '', + }))).slice(0, limit); +} + +export async function searchDdgNews(query: string, country: string): Promise<Headline[]> { + if (!query) return []; + const first = String(country || '').toLowerCase().split(',')[0]?.trim(); + const region = /[가-힣]/.test(query) ? 'kr-kr' : ((first && DDG_REGIONS[first]) || 'wt-wt'); + try { + const page = await fetch(`https://duckduckgo.com/?${new URLSearchParams({ q: query })}`, { + headers: { 'User-Agent': UA }, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), + }); + const vqd = (await page.text()).match(/vqd=["']?([\d-]+)/)?.[1]; + if (!vqd) return []; + const params = new URLSearchParams({ q: query, l: region, o: 'json', noamp: '1', vqd }); + const res = await fetch(`https://duckduckgo.com/news.js?${params}`, { + headers: { 'User-Agent': UA, Referer: 'https://duckduckgo.com/' }, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), + }); + if (!res.ok) return []; + return parseDdgNews(await res.json()); + } catch { return []; } +} diff --git a/src/tools/news.ts b/src/tools/news.ts index 4afc387..caa62d0 100644 --- a/src/tools/news.ts +++ b/src/tools/news.ts @@ -4,7 +4,14 @@ import { getVault } from '../security/vault.js'; import { DISASTER_PATTERN } from '../gateway/guards/prompt-gates.js'; const NEWSDATA_BASE = 'https://newsdata.io/api/1/latest'; -import { fetchTopHeadlines, hasTopHeadlineFeeds, formatHeadlines } from './top-headlines.js'; +import { fetchTopHeadlines, hasTopHeadlineFeeds, formatHeadlines, type Headline } from './top-headlines.js'; +import { fetchGoogleNewsTop, hasGoogleNewsLocale, searchSearxngNews, searchDdgNews } from './news-sources.js'; + +// 멀티콜 다이제스트(handle-chat NEWS DIGEST)는 data.raw를 NewsData 모양으로 읽는다 — 새 출처도 그 모양으로 넘긴다. +const asNewsDataRaw = (items: Headline[]) => items.map(h => ({ + title: h.title, link: h.link, description: h.summary, pubDate: h.published || '', source_name: h.source, +})); +const FRONT_PAGE_HEADER = '[주요 매체 1면 — 편집자가 선별한 톱기사. 이 목록이 답이다 — 다른 분류로 다시 부르지 말 것]'; function getApiKey(): string | undefined { try { @@ -259,7 +266,7 @@ export function stripCategoryWordForRetry(query: string): string { // instead of a headline" failure modes web_search hit for news queries. export const newsSearchTool = { name: 'news_search', - description: 'Get real news headlines from the last 48 hours via NewsData.io — use this instead of web_search for any "오늘 뉴스"/"today\'s news"/breaking news request. Returns real articles with actual publish dates and sources, not generic web pages.', + description: 'Get real news headlines (Google News front page per country, SearXNG/DuckDuckGo news for a topic, NewsData.io as fallback) — use this instead of web_search for any "오늘 뉴스"/"today\'s news"/breaking news request. Returns real articles with actual publish dates and sources, not generic web pages.', schema: { query: 'Optional keyword/topic to filter by (e.g. "economy", "Lula"). Omit for general top headlines. IMPORTANT: this is matched literally against article text, not translated — for a broad "top news for this country/region" request with no specific topic, do NOT pass the user\'s original-language request text as query (e.g. a Korean phrase will match zero articles in a country whose news is written in English/Turkish/etc). Omit query in that case and rely on country/category alone. A region name ("South America", "남미", "Europe") is not a topic either — pass up to 5 of its main country codes as country instead.', country: 'Optional ISO 3166-1 alpha-2 country code (e.g. "kr" for Korea, "us" for USA, "br" for Brazil). Accepts a comma-separated list for multiple countries in one call, MAX 5 (e.g. "de,fr,gb,it,es" — verified working, each result tagged with its source country); if more than 5 are given, only the first 5 are used. There is NO code for continents/regions ("eu"/"europe" will error with "country does not exist") — for a "European news" request, pass up to 5 major European country codes instead (e.g. "de,fr,gb,it,es"). Omit country entirely for worldwide.', @@ -278,28 +285,58 @@ export const newsSearchTool = { }, execute: async (args: any): Promise<ToolResult> => { args = applyRegionQuery(args); - const apiKey = getApiKey(); - if (!apiKey) return { success: false, error: 'NewsData.io API key not configured (set news.newsdata_api_key in .smallclaw/config.json)' }; - const rawQuery = String(args?.query || '').trim(); const { country, language, category } = resolveNewsParams(args); - // 넓은 요청("오늘 미국 주요 뉴스")이면 먼저 1면 피드를 시도한다. NewsData는 시간 역순이라 + // 넓은 요청("오늘 미국 주요 뉴스")이면 먼저 1면을 시도한다. NewsData는 시간 역순이라 // 주요 매체로 좁혀도 "함부르크 아파트 균열" 같은 기사가 톱으로 올라온다 — 편집자가 이미 // 하루를 정렬해 놓은 1면이 이 질문에 대한 답이다([[project_news_top_headlines]]). + // 2026-10-24부터 구글 뉴스 톱기사가 1순위 — 나라별 국내 기사 위주로 순위가 매겨져 있다(news-sources.ts). const broad = !rawQuery && (!category || category === 'top'); + if (broad && hasGoogleNewsLocale(country)) { + const headlines = await fetchGoogleNewsTop(country); + if (headlines.length) { + return { + success: true, + data: { source: 'google-news-top', country, count: headlines.length, raw: asNewsDataRaw(headlines) }, + stdout: `${FRONT_PAGE_HEADER}\n\n${formatHeadlines(headlines)}`, + }; + } + } if (broad && hasTopHeadlineFeeds(country)) { const headlines = await fetchTopHeadlines(country); if (headlines.length) { return { success: true, - data: { source: 'front-page-rss', country, count: headlines.length }, - stdout: `[주요 매체 1면 — 편집자가 선별한 톱기사. 이 목록이 답이다 — 다른 분류로 다시 부르지 말 것]\n\n${formatHeadlines(headlines)}`, + data: { source: 'front-page-rss', country, count: headlines.length, raw: asNewsDataRaw(headlines) }, + stdout: `${FRONT_PAGE_HEADER}\n\n${formatHeadlines(headlines)}`, }; } // 피드가 전부 실패하면 아래 NewsData 경로로 그대로 내려간다. } + // 검색어가 있으면 시어엔진 뉴스(네이버·빙) → 덕덕고 뉴스. NewsData는 q를 기사 본문 글자 그대로 맞춰서 + // 인물·사건 검색에 약하다(10-24: "무라카미 류"는 시어엔진 19건·덕덕고 27건, 둘 다 요약 포함). + if (rawQuery) { + let found = await searchSearxngNews(rawQuery, country); + let source = 'searxng-news'; + if (found.length < 3) { + const ddg = await searchDdgNews(rawQuery, country); + if (ddg.length > found.length) { found = ddg; source = 'ddg-news'; } + } + if (found.length) { + console.log(`[news_search] ${source}: ${found.length} articles for "${rawQuery}"`); + return { + success: true, + data: { source, query: rawQuery, country, count: found.length, raw: asNewsDataRaw(found) }, + stdout: formatHeadlines(found, 10), + }; + } + } + + const apiKey = getApiKey(); + if (!apiKey) return { success: false, error: 'NewsData.io API key not configured (set news.newsdata_api_key in .smallclaw/config.json)' }; + // 주제를 지정한 요청은 손대지 않는다 — 위 applyMajorOutletsForBroadRequest 주석 참고. const scoped = applyMajorOutletsForBroadRequest({ ...args, query: rawQuery, category }, country); const domainurl = String(scoped?.domainurl || '').trim(); diff --git a/src/tools/top-headlines.ts b/src/tools/top-headlines.ts index 6a2aced..f911a0f 100644 --- a/src/tools/top-headlines.ts +++ b/src/tools/top-headlines.ts @@ -42,7 +42,7 @@ const FEEDS: Record<string, string[]> = { const FETCH_TIMEOUT_MS = 10_000; const PER_FEED = 8; // Yahoo!ニュース 主要이 8건 -export interface Headline { title: string; link: string; source: string; summary: string } +export interface Headline { title: string; link: string; source: string; summary: string; published?: string } const decodeEntities = (s: string) => s .replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"') @@ -164,7 +164,7 @@ export function formatHeadlines(items: readonly Headline[], limit = 12): string .map((h, i) => { const lines = [`[${i + 1}] ${normalizeVariants(h.title)}`]; if (h.summary) lines.push(` ${normalizeVariants(h.summary)}`); - lines.push(` ${h.link}`, ` Source: ${h.source}`); + lines.push(` ${h.link}`, h.published ? ` Published: ${h.published} | Source: ${h.source}` : ` Source: ${h.source}`); return lines.join('\n'); }) .join('\n'); diff --git a/tests/news-sources.test.ts b/tests/news-sources.test.ts new file mode 100644 index 0000000..7e8b7f2 --- /dev/null +++ b/tests/news-sources.test.ts @@ -0,0 +1,54 @@ +/** + * news-sources.ts 파서 — 비공식 출처라 형식이 말없이 바뀐다. 조용히 0건이 되는 게 가장 나쁜 실패라 + * 실제 응답 모양(2026-10-24 채취)으로 고정해 둔다. + */ +import { test, describe } from 'node:test'; +import assert from 'node:assert/strict'; +import { parseGoogleNewsRss, parseSearxngNews, parseDdgNews, languageForCountry, hasGoogleNewsLocale } from '../src/tools/news-sources'; + +const GOOGLE_ITEM = `<rss><channel><item><title>改正皇室典範 きょう施行 - NHKニュースhttps://news.google.com/rss/articles/AAA?oc=5Fri, 23 Oct 2026 20:00:08 GMT<ol><li><a href="https://news.google.com/rss/articles/AAA" target="_blank">改正皇室典範 きょう施行</a>&nbsp;&nbsp;<font color="#6f6f6f">NHKニュース</font></li><li><a href="https://news.google.com/rss/articles/BBB" target="_blank">女性皇族の身分保持へ</a>&nbsp;&nbsp;<font color="#6f6f6f">読売新聞</font></li></ol>NHKニュース`; + +describe('parseGoogleNewsRss', () => { + test('splits outlet off the title, keeps date, uses other outlets as related coverage', () => { + const [h] = parseGoogleNewsRss(GOOGLE_ITEM); + assert.equal(h.title, '改正皇室典範 きょう施行'); + assert.equal(h.source, 'NHKニュース'); + assert.equal(h.published, 'Fri, 23 Oct 2026 20:00:08 GMT'); + assert.equal(h.summary, '관련 보도: 女性皇族の身分保持へ (読売新聞)'); + }); + test('garbage → []', () => assert.deepEqual(parseGoogleNewsRss('blocked'), [])); +}); + +describe('parseSearxngNews', () => { + test('dedupes the same story from naver and bing, strips tags', () => { + const out = parseSearxngNews({ results: [ + { title: '무라카미 류 별세', url: 'https://www.hani.co.kr/a/1', content: '무라카미 류가 74세로', engines: ['naver news'] }, + { title: '무라카미 류 별세', url: 'https://n.news.naver.com/2', content: 'x', engines: ['bing news'] }, + { title: '', url: 'https://x' }, + ] }); + assert.equal(out.length, 1); + assert.equal(out[0].source, 'hani.co.kr'); + assert.equal(out[0].summary, '무라카미 류가 74세로'); + }); +}); + +describe('parseDdgNews', () => { + test('maps excerpt/source/unix date', () => { + const [h] = parseDdgNews({ results: [{ title: "'한없이 투명에 가까운 블루' 무라카미 류 별세", url: 'https://news1.kr/1', source: '뉴스1', excerpt: '무라카미 류가 지난 17일', date: 1792800000 }] }); + assert.equal(h.source, '뉴스1'); + assert.equal(h.summary, '무라카미 류가 지난 17일'); + assert.equal(h.published, new Date(1792800000 * 1000).toISOString()); + }); +}); + +describe('locales', () => { + test('country → searxng language', () => { + assert.equal(languageForCountry('jp'), 'ja'); + assert.equal(languageForCountry('br,ar'), 'pt'); + assert.equal(languageForCountry('xx'), ''); + }); + test('multi-country with any known locale counts', () => { + assert.equal(hasGoogleNewsLocale('qa,jp'), true); + assert.equal(hasGoogleNewsLocale(''), false); + }); +});