v2.3.3
This commit is contained in:
1 parent
f92e5ef782
commit
cb131e8047
12 files changed
+870
-122
No files matched your search
@@ -41,7 +41,12 @@
|
||||
"Bash(nc -zw5 mail.evangel.xyz 993)",
|
||||
"Bash(nc -zw5 mail.evangel.xyz 587)",
|
||||
"Bash(pkill -f \"gateway start\")",
|
||||
"Bash(timeout 10 openssl s_client *)"
|
||||
"Bash(timeout 10 openssl s_client *)",
|
||||
"Bash(awk '/async function executeTool/,/^async function [a-zA-Z_]/' /home/kim/homeclaw/src/gateway/server-v2.ts)",
|
||||
"Bash(grep -n \"^ default:\\\\|^ default:\\\\|^ }$\\\\|^ }$\" /home/kim/homeclaw/src/gateway/server-v2.ts)",
|
||||
"Bash(awk -F: '$1>2436 && $1<3700')",
|
||||
"Bash(awk 'NR>=3450 && NR<=3550' /home/kim/homeclaw/src/gateway/server-v2.ts)",
|
||||
"Bash(awk '{print \"server-v2.ts lines:\", $1}')"
|
||||
]
|
||||
},
|
||||
"ANTHROPIC_BASE_URL": "https://openrouter.ai/api",
|
||||
|
||||
@@ -21,12 +21,102 @@
|
||||
"role": "assistant",
|
||||
"content": "오늘 CNN 뉴스의 주요 소식입니다.\n\n* **트럼프, 이란 새 제안 검토**: 트럼프 대통령은 이란의 새로운 제안을 검토하겠다고 밝혔으며, 동시에 중동 동맹국들에 대한 80억 달러 규모의 무기 판매를 가속화하고 있습니다.\n* **이스라엘-헤즈볼라 교전 지속**: 휴전 선언에도 불구하고 양측의 충돌이 64일째 이어지고 있으며, 헤즈볼라는 이스라엘의 탐지를 피하는 신형 무기를 실전 배치했습니다.\n* **아웅산 수치 가택연금 전환**: 미얀마 군부는 구금 중이던 아웅산 수치 전 국가고문을 가택연금으로 옮겼다고 발표했습니다.\n* **런던 유대인 피습 사건**: 런던에서 유대인 남성 2명이 흉기에 찔리는 사건이 발생해 용의자가 살인미수 혐의로 기소되었으며, 키어 스타머 총리는 현장에서 항의 시위대에 직면했습니다.\n* **멕시코 시날로아 주지사 사퇴**: 미국에서 마약 관련 혐의로 기소된 멕시코 시날로아주 주지사가 결국 사임했습니다.",
|
||||
"timestamp": 1777797212373
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "최신 호르무즈 해협 고해상도 사진 2장 검색해줘.",
|
||||
"timestamp": 1777799167512
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "호르무즈 해협과 관련된 고해상도 사진 2장입니다.\n\n\n*📷 Melika Hazrati — Pexels*\n\n\n*📷 Farshid Zabbahi — Pexels*",
|
||||
"timestamp": 1777799176783
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "지금 웹 검색에 어떤 엔진이 쓰였지?",
|
||||
"timestamp": 1777799224117
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "이미지 검색에는 **Pexels**와 **Unsplash** 엔진이 사용되었으며, 일반 웹 검색(뉴스 등)에는 **DuckDuckGo** 엔진을 기반으로 하는 검색 도구를 사용합니다. 필요하시다면 특정 검색 엔진을 지정하여 다시 찾아드릴 수도 있습니다.",
|
||||
"timestamp": 1777799234424
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "올라마에서 제공하는 검색엔진은 없나?",
|
||||
"timestamp": 1777799276018
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "올라마(Ollama) 자체는 로컬 LLM 실행 엔진일 뿐 검색 엔진을 내장하고 있지는 않습니다. 다만, 제가 사용하는 도구 중 `ollama_web_search`는 DuckDuckGo 검색 결과를 올라마 모델이 직접 분석하고 요약해서 전달해 주는 기능을 제공합니다. 필요하시면 이 도구로 더 깊이 있는 검색을 도와드릴까요?",
|
||||
"timestamp": 1777799280363
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "올라마 ui에서는 검색 트리거 버튼이 있던데 뭐지?",
|
||||
"timestamp": 1777799336820
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "Ollama 자체는 터미널 기반의 백엔드 엔진이라 공식 UI가 없지만, 사용 중이신 **Open WebUI** 같은 서드파티 인터페이스의 검색 버튼은 **'웹 검색(Web Search)' 기능**을 활성화하는 트리거입니다.\n\n이 버튼을 켜면 모델이 답변하기 전에 인터넷(SearXNG, Google 등)에서 실시간 정보를 먼저 찾아보고, 그 내용을 바탕으로 답변하는 **RAG(검색 증강 생성)** 모드로 동작하게 됩니다. 덕분에 학습 데이터 이후의 최신 정보나 뉴스도 답변할 수 있게 됩니다.",
|
||||
"timestamp": 1777799344635
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "그럼 올라마가 사용하는 검색 엔진은 뭐지?",
|
||||
"timestamp": 1777799397704
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "올라마(Ollama) 자체는 검색 엔진이 없으며, 사용 중이신 **UI(Open WebUI 등) 설정**에 따라 달라집니다.\n\n보통 다음 중 하나를 연결해서 사용합니다:\n1. **SearXNG**: 여러 검색 엔진(구글, 빙 등)의 결과를 모아주는 오픈소스 메타 검색 엔진 (가장 많이 쓰임)\n2. **Google / Bing API**: 유료 API 키를 등록해 직접 연결\n3. **DuckDuckGo**: 별도 설정 없이 무료로 사용 가능한 기본 옵션\n\n현재 제가 사용하는 `ollama_web_search` 도구는 **DuckDuckGo**를 기본 엔진으로 사용하고 있습니다. 어떤 엔진을 쓰는지 확인하고 싶으시면 UI의 'Settings > Web Search' 메뉴를 보시면 됩니다.",
|
||||
"timestamp": 1777799403846
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "1 번의 엔진은 유료인가?",
|
||||
"timestamp": 1777799449477
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "아니요, **SearXNG는 완전 무료 오픈소스**입니다.\n\n개인 서버나 PC에 직접 설치해서 사용할 수 있으며, 구글·빙·덕덕고 등 수십 개의 검색 엔진 결과를 광고 없이 하나로 모아줍니다. 다만, 직접 설치하기 번거롭다면 공개된 서버(Public Instance)를 연결해 무료로 쓸 수도 있습니다.",
|
||||
"timestamp": 1777799454159
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "이매일 모두 체크해줘.",
|
||||
"timestamp": 1777800728813
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "연결된 3개 계정의 메일을 모두 확인했습니다.\n\n* **daum (8건)**: 오늘 오전 Google Play 영수증, 어제 eBay 할인 혜택 및 '자료검토요청' 메일 등이 도착해 있습니다.\n* **applecherry (3건)**: YouTube Premium 관련 업데이트 및 결제 수단 안내 메일이 있습니다.\n* **evangel**: 새로 도착한 메일이 없습니다.\n\n특정 메일의 내용을 읽어드릴까요?",
|
||||
"timestamp": 1777800740738
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "내일 구미 날씨 어때?",
|
||||
"timestamp": 1777800773856
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "내일(5월 4일) 구미는 최저 9.2°C, 최고 19.7°C로 맑은 하늘이 예상되나, 0.7mm 정도의 가벼운 비 소식이 있습니다. 일교차가 크니 옷차림에 유의하시기 바랍니다.",
|
||||
"timestamp": 1777800782155
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "최신 free gingival graft 술식에 관하여 저널 3개만 찾아줘.",
|
||||
"timestamp": 1777800821418
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "최신 유리치은이식술(FGG) 관련 저널 3개를 요약해 드립니다.\n\n1. **Modified FGG (2023)**: 하악 전치부 치은퇴축 치료 시 기존 방식보다 치근 피복률(91.8%)과 환자 만족도가 유의미하게 높고 수술 후 통증이 적은 변형 술식을 제시했습니다.\n2. **Mesh-FGG (2024)**: 이식편을 그물 모양(Mesh)으로 늘려 채득 부위는 최소화하면서 넓은 부위의 부착치은을 확보하는 혁신적인 접근법입니다.\n3. **Fishnet Suture (2025)**: '그물망 봉합법'이라는 새로운 미세 봉합 기술을 통해 이식편을 골막에 완벽히 고정하고 혈관 재형성을 촉진하여 안정성을 극대화한 사례가 보고되었습니다.",
|
||||
"timestamp": 1777800841224
|
||||
}
|
||||
],
|
||||
"workspace": "/home/kim/homeclaw/.smallclaw/users/papa/workspace",
|
||||
"createdAt": 1777792768975,
|
||||
"lastActiveAt": 1777797212373,
|
||||
"lastActiveAt": 1777800841225,
|
||||
"pendingMemoryFlush": false,
|
||||
"pendingCompaction": false,
|
||||
"contextTokenEstimate": 270
|
||||
"contextTokenEstimate": 1107
|
||||
}
|
||||
@@ -276,3 +276,49 @@
|
||||
* **이스라엘-헤즈볼라 교전 지속**: 휴전 선언에도 불구하고 양측의 충돌이 64일째 이어지고 있으며, 헤즈볼라는 이스라엘의 탐지를 피하는 신형 무기를 실전 배치했습니다.
|
||||
* **아웅산 수치 가택연금 전환**: 미얀마 군부는 구금 중이던 아웅산 수치 전 국가고문을 가택연금으로 옮겼다고 발표했습니다.
|
||||
|
||||
[18:00:22] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[18:00:24] **SmallClaw**: HEARTBEAT_OK
|
||||
[18:06:11] **User**: 최신 호르무즈 해협 고해상도 사진 2장 검색해줘.
|
||||
[18:06:16] **SmallClaw**: 호르무즈 해협과 관련된 고해상도 사진 2장입니다.
|
||||
|
||||

|
||||
*📷 Melika Hazrati — Pexels*
|
||||
|
||||
![Elegant woman in red dress posing on Hormuz I
|
||||
[18:07:06] **User**: 지금 웹 검색에 어떤 엔진이 쓰였지?
|
||||
[18:07:14] **SmallClaw**: 이미지 검색에는 **Pexels**와 **Unsplash** 엔진이 사용되었으며, 일반 웹 검색(뉴스 등)에는 **DuckDuckGo** 엔진을 기반으로 하는 검색 도구를 사용합니다. 필요하시다면 특정 검색 엔진을 지정하여 다시 찾아드릴 수도 있습니다.
|
||||
[18:07:58] **User**: 올라마에서 제공하는 검색엔진은 없나?
|
||||
[18:08:00] **SmallClaw**: 올라마(Ollama) 자체는 로컬 LLM 실행 엔진일 뿐 검색 엔진을 내장하고 있지는 않습니다. 다만, 제가 사용하는 도구 중 `ollama_web_search`는 DuckDuckGo 검색 결과를 올라마 모델이 직접 분석하고 요약해서 전달해 주는 기능을 제공합니다. 필요하시면 이 도구로 더 깊이 있는 검색을 도와드릴까요?
|
||||
[18:08:59] **User**: 올라마 ui에서는 검색 트리거 버튼이 있던데 뭐지?
|
||||
[18:09:04] **SmallClaw**: Ollama 자체는 터미널 기반의 백엔드 엔진이라 공식 UI가 없지만, 사용 중이신 **Open WebUI** 같은 서드파티 인터페이스의 검색 버튼은 **'웹 검색(Web Search)' 기능**을 활성화하는 트리거입니다.
|
||||
|
||||
이 버튼을 켜면 모델이 답변하기 전에 인터넷(SearXNG, Google 등)에서 실시간 정보를 먼저 찾아보고, 그 내용을 바탕으로 답변하는 **RAG(검색 증강 생성)** 모드로 동작하게 됩니다. 덕분에 학습 데이터 이후의 최신 정보나 뉴스도 답변할 수 있게 됩니다.
|
||||
[18:10:00] **User**: 그럼 올라마가 사용하는 검색 엔진은 뭐지?
|
||||
[18:10:03] **SmallClaw**: 올라마(Ollama) 자체는 검색 엔진이 없으며, 사용 중이신 **UI(Open WebUI 등) 설정**에 따라 달라집니다.
|
||||
|
||||
보통 다음 중 하나를 연결해서 사용합니다:
|
||||
1. **SearXNG**: 여러 검색 엔진(구글, 빙 등)의 결과를 모아주는 오픈소스 메타 검색 엔진 (가장 많이 쓰임)
|
||||
2. **Google / Bing API**: 유료 API 키를 등록해 직접 연결
|
||||
3. **DuckDuckGo**: 별도 설정 없이 무료로 사용 가능한 기본 옵션
|
||||
|
||||
현재 제가 사용하는 `ollama_web_search` 도구는 **Duck
|
||||
[18:10:51] **User**: 1 번의 엔진은 유료인가?
|
||||
[18:10:54] **SmallClaw**: 아니요, **SearXNG는 완전 무료 오픈소스**입니다.
|
||||
|
||||
개인 서버나 PC에 직접 설치해서 사용할 수 있으며, 구글·빙·덕덕고 등 수십 개의 검색 엔진 결과를 광고 없이 하나로 모아줍니다. 다만, 직접 설치하기 번거롭다면 공개된 서버(Public Instance)를 연결해 무료로 쓸 수도 있습니다.
|
||||
[18:32:15] **User**: 이매일 모두 체크해줘.
|
||||
[18:32:20] **SmallClaw**: 연결된 3개 계정의 메일을 모두 확인했습니다.
|
||||
|
||||
* **daum (8건)**: 오늘 오전 Google Play 영수증, 어제 eBay 할인 혜택 및 '자료검토요청' 메일 등이 도착해 있습니다.
|
||||
* **applecherry (3건)**: YouTube Premium 관련 업데이트 및 결제 수단 안내 메일이 있습니다.
|
||||
* **evangel**: 새로 도착한 메일이 없습니다.
|
||||
|
||||
특정 메일의 내용을 읽어드릴까요?
|
||||
[18:32:58] **User**: 내일 구미 날씨 어때?
|
||||
[18:33:02] **SmallClaw**: 내일(5월 4일) 구미는 최저 9.2°C, 최고 19.7°C로 맑은 하늘이 예상되나, 0.7mm 정도의 가벼운 비 소식이 있습니다. 일교차가 크니 옷차림에 유의하시기 바랍니다.
|
||||
[18:33:44] **User**: 최신 free gingival graft 술식에 관하여 저널 3개만 찾아줘.
|
||||
[18:34:01] **SmallClaw**: 최신 유리치은이식술(FGG) 관련 저널 3개를 요약해 드립니다.
|
||||
|
||||
1. **Modified FGG (2023)**: 하악 전치부 치은퇴축 치료 시 기존 방식보다 치근 피복률(91.8%)과 환자 만족도가 유의미하게 높고 수술 후 통증이 적은 변형 술식을 제시했습니다.
|
||||
2. **Mesh-FGG (2024)**: 이식편을 그물 모양(Mesh)으로 늘려 채득 부위는 최소화하면서 넓은 부위의 부착치은을 확보하는 혁신적인 접근법입니다.
|
||||
3. **Fishnet Suture (2025)**: '그물망 봉합법'이라는 새로운 미세 봉합 기술을
|
||||
@@ -0,0 +1,510 @@
|
||||
╭─── Claude Code v2.1.126 ─────────────────────────────────────────────────────╮
|
||||
│ │ Tips for getting │
|
||||
│ Welcome back sanggyoo! │ started │
|
||||
│ │ Run /init to create a … │
|
||||
│ ▐▛███▜▌ │ ─────────────────────── │
|
||||
│ ▝▜█████▛▘ │ What's new │
|
||||
│ ▘▘ ▝▝ │ The `/model` picker no… │
|
||||
│ Opus 4.7 · Claude Pro · kimsgms@hanmail.net's │ - Added `claude projec… │
|
||||
│ Organization │ `--dangerously-skip-pe… │
|
||||
│ ~/homeclaw │ /release-notes for more │
|
||||
╰──────────────────────────────────────────────────────────────────────────────╯
|
||||
|
||||
❯ /clear
|
||||
⎿ (no content)
|
||||
|
||||
❯ SearXNG provider 추가해줘
|
||||
|
||||
● Explore(Explore search provider architecture)
|
||||
⎿ Done (14 tool uses · 51.0k tokens · 48s)
|
||||
(ctrl+o to expand)
|
||||
|
||||
● Let me verify key code details before designing.
|
||||
|
||||
Read 4 files (ctrl+o to expand)
|
||||
|
||||
● 전체적인 구조 파악 완료. 몇 가지만 확인하고 플랜을 마무리할게요.
|
||||
|
||||
● User answered Claude's questions:
|
||||
⎿ · SearXNG 인스턴스 인증 방식은 어떻게 되나요? → 공개/무인증 (URL만)
|
||||
· fallback 체인에서 SearXNG의 우선순위를 어디에 둘까요? → 최우선
|
||||
(preferred로 선택 시 1순위, 미선택 시 tavily 다음)
|
||||
|
||||
● Plan 파일을 작성할게요.
|
||||
|
||||
● Updated plan
|
||||
⎿ /plan to preview
|
||||
|
||||
● User approved Claude's plan
|
||||
⎿ Plan saved to: ~/.claude/plans/searxng-provider-logical-sutton.md · /plan
|
||||
to edit
|
||||
SearXNG Search Provider 추가
|
||||
|
||||
Context
|
||||
|
||||
현재 src/tools/web.ts의 executeWebSearch는 Tavily / Google CSE / Brave /
|
||||
DDG (JSON+HTML 폴백) 4개 프로바이더를 fallback chain으로 시도한다. 사용자는
|
||||
self-hosted 또는 public SearXNG 인스턴스(메타서치 엔진)를 신규
|
||||
프로바이더로 추가하길 원한다.
|
||||
|
||||
- 인증: 무인증 (인스턴스 URL만 설정)
|
||||
- 우선순위: 최우선 — preferred로 선택 시 1순위, 미선택 시 tavily 다음
|
||||
(chain: ['tavily', 'searxng', 'google', 'brave', 'ddg'])
|
||||
- API 사양: GET {base}/search?q=<query>&format=json → { results: [{ title,
|
||||
url, content, ... }] }
|
||||
|
||||
기대 결과: SearXNG 인스턴스 URL을 .smallclaw/config.json에 설정하면 다른
|
||||
프로바이더와 동일한 fallback / diagnostics / 결과 후처리(rankResults,
|
||||
buildDirectPriceAnswer, augmentEventContract) 흐름을 그대로 받는다.
|
||||
|
||||
Files to modify
|
||||
|
||||
- src/tools/web.ts — provider type, getSearchConfig, searchSearXNG 추가,
|
||||
executeWebSearch 분기
|
||||
- src/types.ts:343-350 — SmallclawConfig.search에 searxng_url 필드
|
||||
- .smallclaw/config.json:227-231 — search.searxng_url 예시 빈 값 추가
|
||||
(사용자 직접 채움)
|
||||
|
||||
Vault SECRET_FIELD_MAP (src/config/config.ts:286-300) 변경 불필요 —
|
||||
무인증이므로 URL은 plaintext로 둔다.
|
||||
|
||||
Changes
|
||||
|
||||
1) src/tools/web.ts:28 — provider type 확장
|
||||
|
||||
type SearchProvider = 'tavily' | 'google' | 'brave' | 'ddg' | 'ddg_html' |
|
||||
'searxng';
|
||||
|
||||
SearchDiagnostics의 preferred_provider / provider_order 유니언도 'searxng'
|
||||
포함하도록 확장 (web.ts:38-39).
|
||||
|
||||
2) src/tools/web.ts:468 — SearchConfig / getSearchConfig 확장
|
||||
|
||||
type SearchConfig = {
|
||||
preferred: 'tavily' | 'google' | 'brave' | 'ddg' | 'searxng';
|
||||
tavilyKey?: string; googleKey?: string; googleCx?: string; braveKey?:
|
||||
string;
|
||||
searxngUrl?: string;
|
||||
};
|
||||
|
||||
getSearchConfig (web.ts:471):
|
||||
- preferred 화이트리스트에 'searxng' 추가
|
||||
- 기본값은 'ddg' 유지
|
||||
- searxngUrl: data.search?.searxng_url 매핑 (trailing slash trim)
|
||||
|
||||
3) src/tools/web.ts — searchSearXNG 함수 신규 추가 (Brave 패턴 복제)
|
||||
|
||||
searchBrave (web.ts:558-583) 바로 아래에 삽입:
|
||||
|
||||
// ── SearXNG (self-hosted metasearch, no key)
|
||||
─────────────────────────────────
|
||||
async function searchSearXNG(query: string, limit: number, baseUrl:
|
||||
string): Promise<ToolResult> {
|
||||
const base = baseUrl.replace(/\/+$/, '');
|
||||
const url = `${base}/search?q=${encodeURIComponent(query)}&format=json`;
|
||||
const res = await fetch(url, {
|
||||
headers: { 'Accept': 'application/json', 'User-Agent': 'SmallClaw/1.0'
|
||||
},
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`SearXNG HTTP ${res.status}`);
|
||||
const data: any = await res.json();
|
||||
|
||||
const raw = (data.results || []).slice(0, limit).map((r: any) => ({
|
||||
title: r.title || '',
|
||||
url: r.url || '',
|
||||
snippet: r.content || '',
|
||||
}));
|
||||
const ranked = rankResults(query, raw);
|
||||
const answer = buildDirectPriceAnswer(query, ranked);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: { query, results: ranked, answer: answer || undefined },
|
||||
stdout: (answer ? `${answer}\n\n` : '') + ranked.map((r: any, i:
|
||||
number) =>
|
||||
`[${i + 1}] ${r.title}\n ${r.url}\n ${r.snippet.slice(0, 400)}`
|
||||
).join('\n\n'),
|
||||
};
|
||||
}
|
||||
|
||||
근거: SearXNG /search?format=json은 results[].content가 스니펫이고
|
||||
results[].url / results[].title은 표준이다. 응답 스키마는 Tavily/Brave와
|
||||
동일한 ToolResult shape으로 정규화한다.
|
||||
|
||||
4) src/tools/web.ts:765 — executeWebSearch 분기 추가
|
||||
|
||||
candidates 배열 갱신:
|
||||
const candidates: Array<'tavily' | 'searxng' | 'google' | 'brave' | 'ddg'>
|
||||
=
|
||||
['tavily', 'searxng', 'google', 'brave', 'ddg'];
|
||||
|
||||
SearchDiagnostics 타입의 union도 위와 동기화.
|
||||
|
||||
skip 체크 (web.ts:776 블록 안에):
|
||||
if (provider === 'searxng' && !cfg.searxngUrl) {
|
||||
diagnostics.attempted.push({ provider, status: 'skipped', reason:
|
||||
'missing_searxng_url' });
|
||||
continue;
|
||||
}
|
||||
|
||||
실행 분기 (web.ts:805 google 블록 위에):
|
||||
if (provider === 'searxng') {
|
||||
const res = await searchSearXNG(args.query, limit, cfg.searxngUrl as
|
||||
string);
|
||||
await augmentEventContract(args.query, res);
|
||||
const resultCount = Array.isArray(res.data?.results) ?
|
||||
res.data.results.length : 0;
|
||||
diagnostics.attempted.push({
|
||||
provider, status: 'success',
|
||||
duration_ms: Date.now() - started,
|
||||
result_count: resultCount,
|
||||
});
|
||||
diagnostics.selected_provider = 'searxng';
|
||||
res.data = { ...(res.data || {}), provider: 'searxng',
|
||||
search_diagnostics: diagnostics };
|
||||
return res;
|
||||
}
|
||||
|
||||
기존 searchTavily / searchBrave 분기와 1:1 동일 패턴 —
|
||||
후처리(augmentEventContract), diagnostics 기록, provider 태깅을 동일하게
|
||||
유지한다.
|
||||
|
||||
5) src/types.ts:343-350 — config 스키마 확장
|
||||
|
||||
search?: {
|
||||
preferred_provider?: string;
|
||||
tavily_api_key?: string;
|
||||
google_api_key?: string;
|
||||
google_cx?: string;
|
||||
brave_api_key?: string;
|
||||
searxng_url?: string; // 신규: self-hosted/public SearXNG base URL
|
||||
search_rigor?: string;
|
||||
};
|
||||
|
||||
6) .smallclaw/config.json:227-231 — 예시 키 추가
|
||||
|
||||
"search": {
|
||||
"preferred_provider": "ddg",
|
||||
"search_rigor": "verified",
|
||||
"google_cx": "",
|
||||
"searxng_url": ""
|
||||
}
|
||||
|
||||
빈 문자열로 두면 cfg.searxngUrl이 falsy여서 skip되므로 기존 동작에 영향
|
||||
없음. 사용자가 본인 인스턴스 URL을 채우면 활성화된다.
|
||||
|
||||
Verification
|
||||
|
||||
1. 타입 체크: npx tsc --noEmit (또는 프로젝트 빌드 명령) — 새 union 멤버가
|
||||
모든 사용처에 반영됐는지 확인.
|
||||
2. 무설정 회귀 테스트: searxng_url이 빈 값일 때 — 기존 chain (tavily →
|
||||
google → brave → ddg)이 그대로 동작하는지 확인. diagnostics에 searxng:
|
||||
skipped, reason: missing_searxng_url 한 줄만 추가되어야 한다.
|
||||
3. 활성화 테스트: 공개 인스턴스(예: https://searx.be)를 searxng_url에 넣고
|
||||
web_search 툴 호출:
|
||||
- preferred_provider: "searxng" 설정 시 — selected_provider: 'searxng',
|
||||
data.results에 결과 5개 이상.
|
||||
- preferred_provider를 다른 값으로 두고 다른 프로바이더 키를 모두 비워 —
|
||||
fallback에서 SearXNG가 선택되는지.
|
||||
4. 실패 동작: 잘못된 URL(http://localhost:9999) 설정 시 — attempted에
|
||||
searxng: failed, reason: <error>로 기록되고 다음 프로바이더로 넘어가는지.
|
||||
5. 결과 형태: data.results[].snippet이 SearXNG의 content 필드에서
|
||||
정상적으로 채워졌는지, rankResults 정렬과 buildDirectPriceAnswer 가공이
|
||||
적용됐는지 (가격 쿼리로 확인).
|
||||
|
||||
Out of scope
|
||||
|
||||
- SearXNG의 categories, engines, language, time_range 등 고급 파라미터 —
|
||||
다른 프로바이더와 시그니처를 맞추기 위해 1차 버전은 q, format만 사용.
|
||||
- Vault 통합 — 무인증 가정이므로 미적용. 추후 인증이 필요해지면
|
||||
SECRET_FIELD_MAP에 ['search', 'searxng_api_key'] 추가하면 됨.
|
||||
- 캐싱 / 레이트리밋 — 기존 5분 config TTL(_searchConfigCache)에 따라가며
|
||||
별도 추가 없음.
|
||||
⎿ Interrupted · What should Claude do instead?
|
||||
|
||||
※ recap: SmallClaw 효율성 개선 3건(보안 vault 이전, node-pty 지연 로드, executeTool switch 슬림화)을 마쳤습니다. 다음은 서버를 재시작해서 이메일 등 기존 도구가 정상 동작하는지 확인하는 것입니다.
|
||||
|
||||
❯ go
|
||||
● 타입부터 확장.
|
||||
|
||||
● Update(src/tools/web.ts)
|
||||
⎿ Added 3 lines, removed 3 lines
|
||||
25 type StructuredSource = { id: number; tier: 'A' | 'B' | 'C'; ti
|
||||
tle: string; url: string; snippet: string; score: number };
|
||||
26 type StructuredEvidence = { id: number; source_id: number; exce
|
||||
rpt: string; score: number };
|
||||
27 type StructuredFact = { id: number; claim: string; evidence_ids
|
||||
: number[]; source_ids: number[]; confidence: number };
|
||||
28 -type SearchProvider = 'tavily' | 'google' | 'brave' | 'ddg' | '
|
||||
-ddg_html';
|
||||
28 +type SearchProvider = 'tavily' | 'google' | 'brave' | 'ddg' | '
|
||||
+ddg_html' | 'searxng';
|
||||
29 type SearchProviderAttempt = {
|
||||
30 provider: SearchProvider;
|
||||
31 status: 'success' | 'failed' | 'skipped';
|
||||
...
|
||||
35 };
|
||||
36 type SearchDiagnostics = {
|
||||
37 query: string;
|
||||
38 - preferred_provider: 'tavily' | 'google' | 'brave' | 'ddg';
|
||||
39 - provider_order: Array<'tavily' | 'google' | 'brave' | 'ddg'>;
|
||||
38 + preferred_provider: 'tavily' | 'google' | 'brave' | 'ddg' | '
|
||||
+searxng';
|
||||
39 + provider_order: Array<'tavily' | 'google' | 'brave' | 'ddg' |
|
||||
+ 'searxng'>;
|
||||
40 attempted: SearchProviderAttempt[];
|
||||
41 selected_provider?: SearchProvider;
|
||||
42 };
|
||||
|
||||
● Update(src/tools/web.ts)
|
||||
⎿ Added 11 lines, removed 3 lines
|
||||
465
|
||||
466 // ── Load optional API keys from ~/.smallclaw/config.json ───
|
||||
──────────────────
|
||||
467 // Cached with 5-minute TTL so config changes are picked up wi
|
||||
thout restart.
|
||||
468 -type SearchConfig = { preferred: 'tavily' | 'google' | 'brave'
|
||||
- | 'ddg'; tavilyKey?: string; googleKey?: string; googleCx?: s
|
||||
-tring; braveKey?: string };
|
||||
468 +type SearchConfig = { preferred: 'tavily' | 'google' | 'brave'
|
||||
+ | 'ddg' | 'searxng'; tavilyKey?: string; googleKey?: string;
|
||||
+googleCx?: string; braveKey?: string; searxngUrl?: string };
|
||||
469 let _searchConfigCache: { value: SearchConfig; expiresAt: numb
|
||||
er } | null = null;
|
||||
470
|
||||
471 function getSearchConfig(): SearchConfig {
|
||||
...
|
||||
478 if (fs.existsSync(cfg)) {
|
||||
479 const data = JSON.parse(fs.readFileSync(cfg, 'utf-8'));
|
||||
480 const preferredRaw = String(data.search?.preferred_provi
|
||||
der || 'ddg').toLowerCase();
|
||||
481 - const preferred = (['tavily', 'google', 'brave', 'ddg'].
|
||||
-includes(preferredRaw) ? preferredRaw : 'ddg') as SearchConfig
|
||||
-['preferred'];
|
||||
482 - value = { preferred, tavilyKey: data.search?.tavily_api_
|
||||
-key, googleKey: data.search?.google_api_key, googleCx: data.se
|
||||
-arch?.google_cx, braveKey: data.search?.brave_api_key };
|
||||
481 + const preferred = (['tavily', 'google', 'brave', 'ddg',
|
||||
+'searxng'].includes(preferredRaw) ? preferredRaw : 'ddg') as S
|
||||
+earchConfig['preferred'];
|
||||
482 + const searxngRaw = typeof data.search?.searxng_url === '
|
||||
+string' ? data.search.searxng_url.trim().replace(/\/+$/, '') :
|
||||
+ '';
|
||||
483 + value = {
|
||||
484 + preferred,
|
||||
485 + tavilyKey: data.search?.tavily_api_key,
|
||||
486 + googleKey: data.search?.google_api_key,
|
||||
487 + googleCx: data.search?.google_cx,
|
||||
488 + braveKey: data.search?.brave_api_key,
|
||||
489 + searxngUrl: searxngRaw || undefined,
|
||||
490 + };
|
||||
491 }
|
||||
492 } catch {}
|
||||
493 _searchConfigCache = { value, expiresAt: now + 5 * 60_000 };
|
||||
|
||||
● Update(src/tools/web.ts)
|
||||
⎿ Added 28 lines
|
||||
590 };
|
||||
591 }
|
||||
592
|
||||
593 +// ── SearXNG (self-hosted/public metasearch, no key) ────────
|
||||
+──────────────────
|
||||
594 +async function searchSearXNG(query: string, limit: number, bas
|
||||
+eUrl: string): Promise<ToolResult> {
|
||||
595 + const base = baseUrl.replace(/\/+$/, '');
|
||||
596 + const url = `${base}/search?q=${encodeURIComponent(query)}&f
|
||||
+ormat=json`;
|
||||
597 + const res = await fetch(url, {
|
||||
598 + headers: { 'Accept': 'application/json', 'User-Agent': 'Sm
|
||||
+allClaw/1.0' },
|
||||
599 + signal: AbortSignal.timeout(15_000),
|
||||
600 + });
|
||||
601 + if (!res.ok) throw new Error(`SearXNG HTTP ${res.status}`);
|
||||
602 + const data: any = await res.json();
|
||||
603 +
|
||||
604 + const raw: SearchResultItem[] = (data.results || []).slice(0
|
||||
+, limit).map((r: any) => ({
|
||||
605 + title: r.title || '',
|
||||
606 + url: r.url || '',
|
||||
607 + snippet: r.content || '',
|
||||
608 + }));
|
||||
609 + const ranked = rankResults(query, raw);
|
||||
610 + const answer = buildDirectPriceAnswer(query, ranked);
|
||||
611 +
|
||||
612 + return {
|
||||
613 + success: true,
|
||||
614 + data: { query, results: ranked, answer: answer || undefine
|
||||
+d },
|
||||
615 + stdout: (answer ? `${answer}\n\n` : '') + ranked.map((r, i
|
||||
+) =>
|
||||
616 + `[${i + 1}] ${r.title}\n ${r.url}\n ${r.snippet.sl
|
||||
+ice(0, 400)}`
|
||||
617 + ).join('\n\n'),
|
||||
618 + };
|
||||
619 +}
|
||||
620 +
|
||||
621 // ── DuckDuckGo JSON endpoint (no key, more stable than HTML
|
||||
scrape) ───────────
|
||||
622 async function searchDDG(query: string, limit: number): Promis
|
||||
e<ToolResult> {
|
||||
623 // DDG instant answer API — gives structured results without
|
||||
scraping HTML
|
||||
|
||||
● Update(src/tools/web.ts)
|
||||
⎿ Added 1 line, removed 1 line
|
||||
798
|
||||
799 const cfg = getSearchConfig();
|
||||
800
|
||||
801 - const candidates: Array<'tavily' | 'google' | 'brave' | 'ddg
|
||||
-'> = ['tavily', 'google', 'brave', 'ddg'];
|
||||
801 + const candidates: Array<'tavily' | 'searxng' | 'google' | 'b
|
||||
+rave' | 'ddg'> = ['tavily', 'searxng', 'google', 'brave', 'ddg
|
||||
+'];
|
||||
802 const providerOrder = [cfg.preferred, ...candidates.filter(p
|
||||
=> p !== cfg.preferred)];
|
||||
803 const diagnostics: SearchDiagnostics = {
|
||||
804 query: args.query,
|
||||
|
||||
● Update(src/tools/web.ts)
|
||||
⎿ Added 4 lines
|
||||
821 diagnostics.attempted.push({ provider, status: 'skipped'
|
||||
, reason: 'missing_brave_api_key' });
|
||||
822 continue;
|
||||
823 }
|
||||
824 + if (provider === 'searxng' && !cfg.searxngUrl) {
|
||||
825 + diagnostics.attempted.push({ provider, status: 'skipped'
|
||||
+, reason: 'missing_searxng_url' });
|
||||
826 + continue;
|
||||
827 + }
|
||||
828
|
||||
829 const started = Date.now();
|
||||
830 try {
|
||||
|
||||
● Update(src/tools/web.ts)
|
||||
⎿ Added 14 lines
|
||||
842 res.data = { ...(res.data || {}), provider: 'tavily',
|
||||
search_diagnostics: diagnostics };
|
||||
843 return res;
|
||||
844 }
|
||||
845 + if (provider === 'searxng') {
|
||||
846 + const res = await searchSearXNG(args.query, limit, cfg
|
||||
+.searxngUrl as string);
|
||||
847 + await augmentEventContract(args.query, res);
|
||||
848 + const resultCount = Array.isArray(res.data?.results) ?
|
||||
+ res.data.results.length : 0;
|
||||
849 + diagnostics.attempted.push({
|
||||
850 + provider,
|
||||
851 + status: 'success',
|
||||
852 + duration_ms: Date.now() - started,
|
||||
853 + result_count: resultCount,
|
||||
854 + });
|
||||
855 + diagnostics.selected_provider = 'searxng';
|
||||
856 + res.data = { ...(res.data || {}), provider: 'searxng',
|
||||
+ search_diagnostics: diagnostics };
|
||||
857 + return res;
|
||||
858 + }
|
||||
859 if (provider === 'google') {
|
||||
860 const res = await searchGoogle(args.query, limit, cfg.
|
||||
googleKey as string, cfg.googleCx as string);
|
||||
861 await augmentEventContract(args.query, res);
|
||||
|
||||
● Update(src/types.ts)
|
||||
⎿ Added 1 line
|
||||
346 google_api_key?: string;
|
||||
347 google_cx?: string;
|
||||
348 brave_api_key?: string;
|
||||
349 + searxng_url?: string;
|
||||
350 search_rigor?: string;
|
||||
351 };
|
||||
352 pubmed?: {
|
||||
● Update(.smallclaw/config.json)
|
||||
⎿ Added 2 lines, removed 1 line
|
||||
227 "search": {
|
||||
228 "preferred_provider": "ddg",
|
||||
229 "search_rigor": "verified",
|
||||
230 - "google_cx": ""
|
||||
230 + "google_cx": "",
|
||||
231 + "searxng_url": ""
|
||||
232 },
|
||||
233 "pubmed": {
|
||||
234 "api_key": "8640a3585292307d30ebe2a5325ad6dce908"
|
||||
|
||||
● Bash(npx tsc --noEmit 2>&1 | head -80)
|
||||
⎿ (No output)
|
||||
⎿ (timeout 3m)
|
||||
|
||||
● Bash(npx tsc --noEmit; echo "EXIT=$?")
|
||||
⎿ EXIT=0
|
||||
|
||||
● 타입체크 통과. 변경 사항 한눈에 확인.
|
||||
|
||||
● Bash(git diff --stat src/tools/web.ts src/types.ts .smallclaw/config.json)
|
||||
⎿ src/tools/web.ts | 160 +++++++++++++++++++++++++++++++++++++++++++---
|
||||
---------
|
||||
src/types.ts | 1 +
|
||||
2 files changed, 128 insertions(+), 33 deletions(-)
|
||||
|
||||
● Bash(git diff .smallclaw/config.json | head -30)
|
||||
⎿ (No output)
|
||||
|
||||
Searched for 1 pattern (ctrl+o to expand)
|
||||
|
||||
● Bash(git status --short .smallclaw/config.json && git diff --
|
||||
.smallclaw/config.json | head -20)
|
||||
⎿ (No output)
|
||||
|
||||
● Bash(cat .gitignore 2>/dev/null | grep -i smallclaw; git check-ignore -v
|
||||
.smallclaw/config.json 2>&1)
|
||||
⎿ .smallclaw/config.json
|
||||
.smallclaw/credentials/
|
||||
.smallclaw/vault/
|
||||
… +20 lines (ctrl+o to expand)
|
||||
|
||||
● .smallclaw/config.json은 gitignore 대상(사용자 로컬 설정). 변경은 정상
|
||||
반영됐고, 이미 "searxng_url": ""로 들어있음.
|
||||
|
||||
● 완료. 변경 요약:
|
||||
|
||||
- src/tools/web.ts
|
||||
- SearchProvider 유니언과 SearchDiagnostics에 'searxng' 추가 (web.ts:28-42)
|
||||
- SearchConfig에 searxngUrl, getSearchConfig에서 searxng_url 읽고 trailing
|
||||
slash trim (web.ts:468-498)
|
||||
- searchSearXNG() 함수 추가 — GET {base}/search?q=...&format=json →
|
||||
results[].{title,url,content} 정규화 + rankResults + buildDirectPriceAnswer
|
||||
(web.ts:586-612)
|
||||
- executeWebSearch candidates에 'searxng' 2번째 위치 삽입, skip 체크와 실행
|
||||
분기를 기존 패턴과 동일하게 추가
|
||||
- src/types.ts:343-351 — SmallclawConfig.search.searxng_url?: string 필드 추가
|
||||
- .smallclaw/config.json:227-232 — "searxng_url": "" stub (gitignore됨,
|
||||
사용자가 본인 인스턴스 URL로 채움)
|
||||
|
||||
tsc --noEmit 통과. 사용하려면 .smallclaw/config.json의 search.searxng_url을
|
||||
인스턴스 URL로 채우고, 1순위로 쓰려면 preferred_provider: "searxng"로 변경하면
|
||||
됨. 무설정 상태에선 기존 fallback 체인이 그대로 동작하고 diagnostics에
|
||||
searxng: skipped, reason: missing_searxng_url 한 줄만 추가됨.
|
||||
|
||||
✻ Worked for 2m 4s
|
||||
|
||||
❯ 그럼 searxng 로컬 서버가 있어야 한다는 거지?
|
||||
|
||||
● 꼭 로컬일 필요는 없고, JSON API를 노출하는 SearXNG 인스턴스 URL 하나만 있으면
|
||||
됩니다. 세 가지 선택지가 있어요:
|
||||
|
||||
1. 공개 인스턴스 사용 — 가장 빠름. 예: https://searx.be,
|
||||
https://search.brave4u.com 같은 public 인스턴스 목록은 https://searx.space에
|
||||
있음.
|
||||
- 단, 공개 인스턴스는 보통 JSON 포맷이 비활성화되어 있는 경우가 많음 (대부분
|
||||
HTML만 허용). 인스턴스의 /config 엔드포인트 또는 searx.space에서 format: json
|
||||
지원 여부를 확인해야 함.
|
||||
- 레이트리밋, 가용성 보장 없음, 검색어가 운영자에게 노출됨.
|
||||
2. self-host (도커) — 가장 권장. 5분이면 띄울 수 있음:
|
||||
docker run -d --name searxng -p 8080:8080 searxng/searxng
|
||||
2. 그 후 searxng_url: "http://localhost:8080" 설정. JSON 포맷은 settings.yml의
|
||||
search.formats에 json 추가해야 활성화됨 (기본 비활성).
|
||||
3. 사내/원격 서버 — 회사·홈서버에 한 번 띄워놓고 여러 머신에서 공유.
|
||||
|
||||
요약: 이 클라이언트는 인스턴스를 띄우지 않습니다 — URL을 가리키는 어댑터만
|
||||
추가했어요. 가장 안정적인 건 도커로 self-host 하는 방법.
|
||||
|
||||
✻ Cooked for 11s
|
||||
@@ -1 +1 @@
|
||||
claude --resume 02c8af7b-caa0-4d70-a465-13b2dfa93a1f
|
||||
claude --resume a7fdc7e1-3943-4bdc-b176-5381ec6c51ce
|
||||
+15
-6
@@ -326,18 +326,27 @@ function migrateSecretsToVault(config: any, configDir: string): any {
|
||||
const copy = JSON.parse(JSON.stringify(config)); // deep clone
|
||||
const vault = getVault(configDir);
|
||||
|
||||
const isPlaintext = (v: any): v is string =>
|
||||
typeof v === 'string' && v.length > 0 && !v.startsWith('vault:') && !v.startsWith('env:') && v !== '••••••••';
|
||||
|
||||
for (const [fieldPath, vaultKey] of SECRET_FIELD_MAP) {
|
||||
const value = deepGet(copy, fieldPath);
|
||||
if (!value) continue;
|
||||
// Skip if already a vault reference or env: reference
|
||||
if (value.startsWith('vault:') || value.startsWith('env:')) continue;
|
||||
// Skip masked placeholder from UI
|
||||
if (value === '••••••••') continue;
|
||||
// It's a real plaintext secret — move it to vault
|
||||
if (!isPlaintext(value)) continue;
|
||||
vault.set(vaultKey, value, 'config:migrate');
|
||||
deepSet(copy, fieldPath, `vault:${vaultKey}`);
|
||||
}
|
||||
|
||||
// Email accounts: array form needs per-account handling
|
||||
const accounts = copy?.email?.accounts;
|
||||
if (Array.isArray(accounts)) {
|
||||
for (const acc of accounts) {
|
||||
if (!acc?.id || !isPlaintext(acc.password)) continue;
|
||||
const vaultKey = `email.accounts.${acc.id}.password`;
|
||||
vault.set(vaultKey, acc.password, 'config:migrate');
|
||||
acc.password = `vault:${vaultKey}`;
|
||||
}
|
||||
}
|
||||
|
||||
return copy;
|
||||
}
|
||||
|
||||
|
||||
+52
-76
@@ -632,9 +632,8 @@ function normalizeWhatsAppConfig(raw: any): WhatsAppChannelConfig {
|
||||
function resolveChannelsConfig(): ChannelsConfig {
|
||||
const cfg = getConfig().getConfig() as any;
|
||||
const channels = cfg.channels || {};
|
||||
const legacyTelegram = cfg.telegram || {};
|
||||
return {
|
||||
telegram: normalizeTelegramConfig({ ...(channels.telegram || {}), ...legacyTelegram }),
|
||||
telegram: normalizeTelegramConfig(channels.telegram || {}),
|
||||
discord: normalizeDiscordConfig(channels.discord || {}),
|
||||
whatsapp: normalizeWhatsAppConfig(channels.whatsapp || {}),
|
||||
};
|
||||
@@ -990,6 +989,8 @@ function detectToolCategories(text: string): Set<string> {
|
||||
if (WEATHER.some(k => lower.includes(k))) cats.add('weather');
|
||||
const EMAIL = ['email', '이메일', '메일', 'inbox', '받은편지함', '받은 메일', '메일함', '메일 보내', '메일 읽', '메일 검색', '메일 삭제', 'email_list', 'email_send', 'email_read', 'email_search', 'email_delete'];
|
||||
if (EMAIL.some(k => lower.includes(k))) cats.add('email');
|
||||
const OLLAMA_SEARCH = ['ollama 검색', 'ollama search', 'ollama_web', 'ollama web', '올라마 검색', '올라마로 검색', '올라마 웹'];
|
||||
if (OLLAMA_SEARCH.some(k => lower.includes(k))) cats.add('ollama_web');
|
||||
return cats;
|
||||
}
|
||||
|
||||
@@ -1027,6 +1028,8 @@ const TOOL_BLOCKS: Record<string, string> = {
|
||||
|
||||
weather: `WEATHER TOOL: weather_search(location, type?, units?) → real-time weather via OpenWeather API. location: city name (e.g. "Seoul"), "City,CountryCode" (e.g. "London,GB"), or "lat,lon". type: "current" (default) or "forecast" (5-day). units: "metric" °C (default), "imperial" °F. RULES: ALWAYS use weather_search for any weather / forecast / temperature query — NEVER use web_search for weather. Examples: weather_search({location:"Incheon"}) for current, weather_search({location:"Seoul",type:"forecast"}) for 5-day forecast.`,
|
||||
|
||||
ollama_web: `OLLAMA WEB TOOLS: ollama_web_search(query, max_results?) → Ollama 모델이 DDG 검색 후 결과를 자연어로 요약 반환. ollama_web_fetch(url, instruction?) → URL 내용을 가져와 Ollama가 요약. instruction 예: "주요 수치만 뽑아줘". 일반 web_search/web_fetch보다 느리지만 모델이 결과를 직접 해석해서 반환.`,
|
||||
|
||||
email: `EMAIL TOOLS (멀티 계정 지원): 모든 도구에 account? 파라미터 추가 가능 (예: "applecherry", "evangel", "daum"). 미지정 시 default 계정 사용. 등록된 계정: applecherry(kim@applecherry.net), evangel(kim@evangel.xyz), daum(kimsgms@hanmail.net). email_list(folder?,limit?,account?) → 받은편지함 목록 (uid·제목·발신자·날짜·읽음여부). email_read(uid,folder?,account?) → 메일 전문 조회. email_send(to,subject,body,cc?,account?) → 메일 발송. email_search(query?,from?,subject?,since?,before?,folder?,limit?,account?) → 메일 검색. email_delete(uid,folder?,account?) → 메일 삭제. RULES: 이메일 관련 요청에는 항상 email_* 도구 사용 — web_search 사용 금지.`,
|
||||
|
||||
pdf: `PDF TOOL: pdf_read(path, page_from?, page_to?, max_chars?) → extract text from a PDF file in the workspace. path is relative to workspace or absolute. Use page_from/page_to to read specific page ranges. Default max_chars is 20000. If the PDF is scanned (image-only), it returns an error — use image_read with OCR instead.`,
|
||||
@@ -1351,6 +1354,34 @@ function buildTools() {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'ollama_web_search',
|
||||
description: 'Ollama 모델이 DuckDuckGo 웹 검색을 수행하고 결과를 자연어로 종합해서 반환합니다. 검색 결과 해석·요약이 필요할 때 web_search 대신 사용.',
|
||||
parameters: {
|
||||
type: 'object', required: ['query'],
|
||||
properties: {
|
||||
query: { type: 'string', description: '검색 질문 또는 키워드' },
|
||||
max_results: { type: 'number', description: '최대 검색 결과 수 (기본 5)' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'ollama_web_fetch',
|
||||
description: 'URL을 가져온 후 Ollama 모델이 내용을 요약합니다. 원문 대신 모델 요약이 필요할 때 web_fetch 대신 사용.',
|
||||
parameters: {
|
||||
type: 'object', required: ['url'],
|
||||
properties: {
|
||||
url: { type: 'string', description: '가져올 URL (https:// 포함)' },
|
||||
instruction: { type: 'string', description: '요약 지시 (선택, 예: "주요 수치만 뽑아줘")' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
@@ -2132,6 +2163,16 @@ async function webSearch(query: string): Promise<string> {
|
||||
const tavilyKey = searchCfg.tavily_api_key || '';
|
||||
console.log(`[v2] webSearch via ${provider}: ${query.slice(0, 80)}`);
|
||||
|
||||
if (provider === 'ollama') {
|
||||
try {
|
||||
const { executeWebSearch } = await import('../tools/web.js');
|
||||
const res = await executeWebSearch({ query, max_results: 5 });
|
||||
if (res.success && res.stdout) return res.stdout;
|
||||
} catch (err: any) {
|
||||
console.warn('[v2] webSearch ollama failed, falling back to DDG:', err.message);
|
||||
}
|
||||
return duckDuckGoSearch(query);
|
||||
}
|
||||
if (provider === 'tavily' && tavilyKey) {
|
||||
return tavilySearch(query, tavilyKey);
|
||||
}
|
||||
@@ -2565,78 +2606,6 @@ async function executeTool(name: string, args: any, workspacePath: string, sessi
|
||||
};
|
||||
}
|
||||
|
||||
case 'pubmed_search':
|
||||
case 'pubmed_fetch':
|
||||
case 'pubmed_fulltext': {
|
||||
const { pubmedSearchTool, pubmedFetchTool, pubmedFulltextTool } = await import('../tools/pubmed.js');
|
||||
const toolMap: Record<string, any> = {
|
||||
pubmed_search: pubmedSearchTool,
|
||||
pubmed_fetch: pubmedFetchTool,
|
||||
pubmed_fulltext: pubmedFulltextTool,
|
||||
};
|
||||
const tool = toolMap[name];
|
||||
const tr = await tool.execute({ ...args, _workspacePath: workspacePath });
|
||||
return { name, args, result: tr.stdout || tr.error || '', error: !tr.success };
|
||||
}
|
||||
|
||||
case 'openalex_search':
|
||||
case 'semantic_search': {
|
||||
const { openalexSearchTool, semanticSearchTool } = await import('../tools/scholar.js');
|
||||
const toolMap: Record<string, any> = {
|
||||
openalex_search: openalexSearchTool,
|
||||
semantic_search: semanticSearchTool,
|
||||
};
|
||||
const tr = await toolMap[name].execute(args);
|
||||
return { name, args, result: tr.stdout || tr.error || '', error: !tr.success };
|
||||
}
|
||||
|
||||
case 'weather_search': {
|
||||
const { weatherSearchTool } = await import('../tools/weather.js');
|
||||
const tr = await weatherSearchTool.execute(args);
|
||||
return { name, args, result: tr.stdout || tr.error || '', error: !tr.success };
|
||||
}
|
||||
|
||||
case 'email_list':
|
||||
case 'email_read':
|
||||
case 'email_send':
|
||||
case 'email_search':
|
||||
case 'email_delete': {
|
||||
const { emailListTool, emailReadTool, emailSendTool, emailSearchTool, emailDeleteTool } = await import('../tools/email.js');
|
||||
const toolMap: Record<string, any> = {
|
||||
email_list: emailListTool,
|
||||
email_read: emailReadTool,
|
||||
email_send: emailSendTool,
|
||||
email_search: emailSearchTool,
|
||||
email_delete: emailDeleteTool,
|
||||
};
|
||||
const tr = await toolMap[name].execute({ ...args, _workspace: workspacePath });
|
||||
return { name, args, result: tr.stdout || tr.error || '', error: !tr.success };
|
||||
}
|
||||
|
||||
case 'pdf_read': {
|
||||
const { pdfReadTool } = await import('../tools/pdf.js');
|
||||
const tr = await pdfReadTool.execute(args);
|
||||
return { name, args, result: tr.stdout || tr.error || '', error: !tr.success };
|
||||
}
|
||||
|
||||
case 'image_read': {
|
||||
const { imageReadTool } = await import('../tools/image.js');
|
||||
const tr = await imageReadTool.execute(args);
|
||||
return { name, args, result: tr.stdout || tr.error || '', error: !tr.success };
|
||||
}
|
||||
|
||||
case 'python_eval': {
|
||||
const { pythonEvalTool } = await import('../tools/python.js');
|
||||
const tr = await pythonEvalTool.execute(args);
|
||||
return { name, args, result: tr.stdout || tr.error || '', error: !tr.success };
|
||||
}
|
||||
|
||||
case 'sqlite_query': {
|
||||
const { sqliteTool } = await import('../tools/sqlite.js');
|
||||
const tr = await sqliteTool.execute(args);
|
||||
return { name, args, result: tr.stdout || tr.error || '', error: !tr.success };
|
||||
}
|
||||
|
||||
case 'shell': {
|
||||
const workspacePath = getWorkspace(sessionId) || getConfig().getConfig().workspace.path;
|
||||
const command = String(args.command || '').trim();
|
||||
@@ -3419,8 +3388,15 @@ async function executeTool(name: string, args: any, workspacePath: string, sessi
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
return { name, args, result: `Unknown tool: ${name}`, error: true };
|
||||
default: {
|
||||
// Fallback: delegate to registry. Any tool registered in tools/registry.ts
|
||||
// works without an explicit case here. Custom-logic cases above (file ops,
|
||||
// browser/desktop, memory, workflow, presentation) keep their own branches.
|
||||
const tool = getToolRegistry().get(name);
|
||||
if (!tool) return { name, args, result: `Unknown tool: ${name}`, error: true };
|
||||
const tr = await tool.execute({ ...args, _workspace: workspacePath, _workspacePath: workspacePath });
|
||||
return { name, args, result: tr.stdout || tr.error || '', error: !tr.success };
|
||||
}
|
||||
}
|
||||
} catch (err: any) {
|
||||
return { name, args, result: `Error: ${err.message}`, error: true };
|
||||
|
||||
+15
-1
@@ -2,6 +2,7 @@ import fs from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import { ToolResult } from '../types.js';
|
||||
import { getVault } from '../security/vault.js';
|
||||
|
||||
// ── Config ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -40,6 +41,19 @@ function getEmailConfig(accountId?: string): EmailConfig | null {
|
||||
}
|
||||
|
||||
if (!e?.imap_host || !e?.username) return null;
|
||||
|
||||
// Resolve vault: references for password
|
||||
let password = e.password || '';
|
||||
if (password.startsWith('vault:')) {
|
||||
try {
|
||||
const vault = getVault(path.dirname(cfgPath));
|
||||
const secret = vault.get(password.slice(6), 'email:resolve');
|
||||
password = secret ? secret.expose() : '';
|
||||
} catch {
|
||||
password = '';
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
imap_host: e.imap_host,
|
||||
imap_port: Number(e.imap_port ?? 993),
|
||||
@@ -50,7 +64,7 @@ function getEmailConfig(accountId?: string): EmailConfig | null {
|
||||
smtp_secure: e.smtp_secure === true,
|
||||
smtp_reject_unauthorized: e.smtp_reject_unauthorized !== false,
|
||||
username: e.username,
|
||||
password: e.password || '',
|
||||
password,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ToolResult } from '../types.js';
|
||||
import { shellTool } from './shell.js';
|
||||
import { readTool, writeTool, editTool, listTool, deleteTool, renameTool, copyTool, mkdirTool, statTool, appendTool, applyPatchTool } from './files.js';
|
||||
import { webSearchTool, webFetchTool } from './web.js';
|
||||
import { webSearchTool, webFetchTool, ollamaWebSearchTool, ollamaWebFetchTool } from './web.js';
|
||||
import { memorySearchTool, memoryWriteTool } from './memory.js';
|
||||
import { memoryReadTool } from './memory-read.js';
|
||||
import { memoryFileSearchTool } from './memory-file-search.js';
|
||||
@@ -147,6 +147,8 @@ class ToolRegistry {
|
||||
// Web tools
|
||||
this.registerSafe(webSearchTool);
|
||||
this.registerSafe(webFetchTool);
|
||||
this.registerSafe(ollamaWebSearchTool);
|
||||
this.registerSafe(ollamaWebFetchTool);
|
||||
// Memory tools
|
||||
this.registerSafe(memoryWriteTool);
|
||||
this.registerSafe(memorySearchTool);
|
||||
|
||||
+2
-1
@@ -1,4 +1,3 @@
|
||||
import PTYManager from '../gateway/pty-manager';
|
||||
import path from 'path';
|
||||
import { getConfig } from '../config/config.js';
|
||||
import { ToolResult } from '../types.js';
|
||||
@@ -104,6 +103,8 @@ export async function executeShell(args: ShellToolArgs): Promise<ToolResult> {
|
||||
}
|
||||
|
||||
try {
|
||||
// Lazy-load node-pty (63MB native module) only when shell is actually invoked
|
||||
const { default: PTYManager } = await import('../gateway/pty-manager.js');
|
||||
const pty = PTYManager.getInstance();
|
||||
const output = await pty.runCommand(args.command);
|
||||
return {
|
||||
|
||||
+127
-33
@@ -25,7 +25,7 @@ function stripHtml(html: string, preserveStructure = false): string {
|
||||
type StructuredSource = { id: number; tier: 'A' | 'B' | 'C'; title: string; url: string; snippet: string; score: number };
|
||||
type StructuredEvidence = { id: number; source_id: number; excerpt: string; score: number };
|
||||
type StructuredFact = { id: number; claim: string; evidence_ids: number[]; source_ids: number[]; confidence: number };
|
||||
type SearchProvider = 'tavily' | 'google' | 'brave' | 'ddg' | 'ddg_html' | 'ollama';
|
||||
type SearchProvider = 'tavily' | 'google' | 'brave' | 'ddg' | 'ddg_html' | 'searxng';
|
||||
type SearchProviderAttempt = {
|
||||
provider: SearchProvider;
|
||||
status: 'success' | 'failed' | 'skipped';
|
||||
@@ -35,8 +35,8 @@ type SearchProviderAttempt = {
|
||||
};
|
||||
type SearchDiagnostics = {
|
||||
query: string;
|
||||
preferred_provider: 'tavily' | 'google' | 'brave' | 'ddg';
|
||||
provider_order: Array<'tavily' | 'google' | 'brave' | 'ddg'>;
|
||||
preferred_provider: 'tavily' | 'google' | 'brave' | 'ddg' | 'searxng';
|
||||
provider_order: Array<'tavily' | 'google' | 'brave' | 'ddg' | 'searxng'>;
|
||||
attempted: SearchProviderAttempt[];
|
||||
selected_provider?: SearchProvider;
|
||||
};
|
||||
@@ -465,7 +465,7 @@ function rankResults(query: string, results: SearchResultItem[]) {
|
||||
|
||||
// ── Load optional API keys from ~/.smallclaw/config.json ─────────────────────
|
||||
// Cached with 5-minute TTL so config changes are picked up without restart.
|
||||
type SearchConfig = { preferred: 'tavily' | 'google' | 'brave' | 'ddg' | 'ollama'; tavilyKey?: string; googleKey?: string; googleCx?: string; braveKey?: string; ollamaEndpoint?: string; ollamaModel?: string };
|
||||
type SearchConfig = { preferred: 'tavily' | 'google' | 'brave' | 'ddg' | 'searxng'; tavilyKey?: string; googleKey?: string; googleCx?: string; braveKey?: string; searxngUrl?: string };
|
||||
let _searchConfigCache: { value: SearchConfig; expiresAt: number } | null = null;
|
||||
|
||||
function getSearchConfig(): SearchConfig {
|
||||
@@ -478,15 +478,15 @@ function getSearchConfig(): SearchConfig {
|
||||
if (fs.existsSync(cfg)) {
|
||||
const data = JSON.parse(fs.readFileSync(cfg, 'utf-8'));
|
||||
const preferredRaw = String(data.search?.preferred_provider || 'ddg').toLowerCase();
|
||||
const preferred = (['tavily', 'google', 'brave', 'ddg', 'ollama'].includes(preferredRaw) ? preferredRaw : 'ddg') as SearchConfig['preferred'];
|
||||
const preferred = (['tavily', 'google', 'brave', 'ddg', 'searxng'].includes(preferredRaw) ? preferredRaw : 'ddg') as SearchConfig['preferred'];
|
||||
const searxngRaw = typeof data.search?.searxng_url === 'string' ? data.search.searxng_url.trim().replace(/\/+$/, '') : '';
|
||||
value = {
|
||||
preferred,
|
||||
tavilyKey: data.search?.tavily_api_key,
|
||||
googleKey: data.search?.google_api_key,
|
||||
googleCx: data.search?.google_cx,
|
||||
braveKey: data.search?.brave_api_key,
|
||||
ollamaEndpoint: data.search?.ollama_endpoint || data.ollama?.endpoint || 'http://localhost:11434',
|
||||
ollamaModel: data.search?.ollama_model || data.models?.primary || data.ollama?.providers?.ollama?.model || '',
|
||||
tavilyKey: data.search?.tavily_api_key,
|
||||
googleKey: data.search?.google_api_key,
|
||||
googleCx: data.search?.google_cx,
|
||||
braveKey: data.search?.brave_api_key,
|
||||
searxngUrl: searxngRaw || undefined,
|
||||
};
|
||||
}
|
||||
} catch {}
|
||||
@@ -590,6 +590,34 @@ async function searchBrave(query: string, limit: number, apiKey: string): Promis
|
||||
};
|
||||
}
|
||||
|
||||
// ── SearXNG (self-hosted/public metasearch, no key) ──────────────────────────
|
||||
async function searchSearXNG(query: string, limit: number, baseUrl: string): Promise<ToolResult> {
|
||||
const base = baseUrl.replace(/\/+$/, '');
|
||||
const url = `${base}/search?q=${encodeURIComponent(query)}&format=json`;
|
||||
const res = await fetch(url, {
|
||||
headers: { 'Accept': 'application/json', 'User-Agent': 'SmallClaw/1.0' },
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`SearXNG HTTP ${res.status}`);
|
||||
const data: any = await res.json();
|
||||
|
||||
const raw: SearchResultItem[] = (data.results || []).slice(0, limit).map((r: any) => ({
|
||||
title: r.title || '',
|
||||
url: r.url || '',
|
||||
snippet: r.content || '',
|
||||
}));
|
||||
const ranked = rankResults(query, raw);
|
||||
const answer = buildDirectPriceAnswer(query, ranked);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: { query, results: ranked, answer: answer || undefined },
|
||||
stdout: (answer ? `${answer}\n\n` : '') + ranked.map((r, i) =>
|
||||
`[${i + 1}] ${r.title}\n ${r.url}\n ${r.snippet.slice(0, 400)}`
|
||||
).join('\n\n'),
|
||||
};
|
||||
}
|
||||
|
||||
// ── DuckDuckGo JSON endpoint (no key, more stable than HTML scrape) ───────────
|
||||
async function searchDDG(query: string, limit: number): Promise<ToolResult> {
|
||||
// DDG instant answer API — gives structured results without scraping HTML
|
||||
@@ -770,30 +798,11 @@ export async function executeWebSearch(args: { query: string; max_results?: numb
|
||||
|
||||
const cfg = getSearchConfig();
|
||||
|
||||
// Ollama provider: model-assisted search (bypasses normal provider loop)
|
||||
if (cfg.preferred === 'ollama') {
|
||||
const endpoint = cfg.ollamaEndpoint || 'http://localhost:11434';
|
||||
const model = cfg.ollamaModel || '';
|
||||
if (!model) {
|
||||
console.warn('[web_search] ollama provider: no model configured, falling back to DDG');
|
||||
} else {
|
||||
const started = Date.now();
|
||||
try {
|
||||
const res = await searchOllama(args.query, limit, endpoint, model);
|
||||
res.data = { ...(res.data || {}), provider: 'ollama', duration_ms: Date.now() - started };
|
||||
return res;
|
||||
} catch (err: any) {
|
||||
console.warn('[web_search] ollama search failed, falling back to DDG:', err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const candidates: Array<'tavily' | 'google' | 'brave' | 'ddg'> = ['tavily', 'google', 'brave', 'ddg'];
|
||||
const preferredFallback = cfg.preferred === 'ollama' ? 'ddg' : cfg.preferred as 'tavily' | 'google' | 'brave' | 'ddg';
|
||||
const providerOrder = [preferredFallback, ...candidates.filter(p => p !== preferredFallback)];
|
||||
const candidates: Array<'tavily' | 'searxng' | 'google' | 'brave' | 'ddg'> = ['tavily', 'searxng', 'google', 'brave', 'ddg'];
|
||||
const providerOrder = [cfg.preferred, ...candidates.filter(p => p !== cfg.preferred)];
|
||||
const diagnostics: SearchDiagnostics = {
|
||||
query: args.query,
|
||||
preferred_provider: preferredFallback,
|
||||
preferred_provider: cfg.preferred,
|
||||
provider_order: providerOrder,
|
||||
attempted: [],
|
||||
};
|
||||
@@ -812,6 +821,10 @@ export async function executeWebSearch(args: { query: string; max_results?: numb
|
||||
diagnostics.attempted.push({ provider, status: 'skipped', reason: 'missing_brave_api_key' });
|
||||
continue;
|
||||
}
|
||||
if (provider === 'searxng' && !cfg.searxngUrl) {
|
||||
diagnostics.attempted.push({ provider, status: 'skipped', reason: 'missing_searxng_url' });
|
||||
continue;
|
||||
}
|
||||
|
||||
const started = Date.now();
|
||||
try {
|
||||
@@ -829,6 +842,20 @@ export async function executeWebSearch(args: { query: string; max_results?: numb
|
||||
res.data = { ...(res.data || {}), provider: 'tavily', search_diagnostics: diagnostics };
|
||||
return res;
|
||||
}
|
||||
if (provider === 'searxng') {
|
||||
const res = await searchSearXNG(args.query, limit, cfg.searxngUrl as string);
|
||||
await augmentEventContract(args.query, res);
|
||||
const resultCount = Array.isArray(res.data?.results) ? res.data.results.length : 0;
|
||||
diagnostics.attempted.push({
|
||||
provider,
|
||||
status: 'success',
|
||||
duration_ms: Date.now() - started,
|
||||
result_count: resultCount,
|
||||
});
|
||||
diagnostics.selected_provider = 'searxng';
|
||||
res.data = { ...(res.data || {}), provider: 'searxng', search_diagnostics: diagnostics };
|
||||
return res;
|
||||
}
|
||||
if (provider === 'google') {
|
||||
const res = await searchGoogle(args.query, limit, cfg.googleKey as string, cfg.googleCx as string);
|
||||
await augmentEventContract(args.query, res);
|
||||
@@ -968,3 +995,70 @@ export const webFetchTool = {
|
||||
max_chars: 'number (optional, default 10000) - Max characters to return',
|
||||
},
|
||||
};
|
||||
|
||||
function getOllamaConfig(): { endpoint: string; model: string } {
|
||||
try {
|
||||
const projectCfg = path.join(process.cwd(), '.smallclaw', 'config.json');
|
||||
const cfgPath = fs.existsSync(projectCfg) ? projectCfg : path.join(os.homedir(), '.smallclaw', 'config.json');
|
||||
if (fs.existsSync(cfgPath)) {
|
||||
const data = JSON.parse(fs.readFileSync(cfgPath, 'utf-8'));
|
||||
const endpoint = String(data.ollama?.endpoint || 'http://localhost:11434');
|
||||
const model = String(data.llm?.providers?.ollama?.model || data.models?.primary || 'llama3');
|
||||
return { endpoint, model };
|
||||
}
|
||||
} catch {}
|
||||
return { endpoint: 'http://localhost:11434', model: 'llama3' };
|
||||
}
|
||||
|
||||
export const ollamaWebSearchTool = {
|
||||
name: 'ollama_web_search',
|
||||
description: 'Ollama 모델이 DuckDuckGo 웹 검색을 수행하고 결과를 종합해서 자연어로 반환합니다. 일반 web_search와 달리 모델이 검색 결과를 해석·요약해서 답변합니다.',
|
||||
schema: {
|
||||
query: 'string (required) - 검색 질문 또는 키워드',
|
||||
max_results: 'number (optional, default 5) - 최대 검색 결과 수',
|
||||
},
|
||||
execute: async (args: { query: string; max_results?: number }): Promise<ToolResult> => {
|
||||
if (!args.query?.trim()) return { success: false, error: 'query is required' };
|
||||
const { endpoint, model } = getOllamaConfig();
|
||||
const limit = Math.min(args.max_results ?? 5, 10);
|
||||
try {
|
||||
return await searchOllama(args.query, limit, endpoint, model);
|
||||
} catch (err: any) {
|
||||
return { success: false, error: `ollama_web_search failed: ${err.message}` };
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export const ollamaWebFetchTool = {
|
||||
name: 'ollama_web_fetch',
|
||||
description: 'URL을 가져온 후 Ollama 모델이 내용을 요약합니다. web_fetch로 가져온 원문 대신 모델이 핵심만 정리해서 반환합니다.',
|
||||
schema: {
|
||||
url: 'string (required) - 가져올 URL (https:// 포함)',
|
||||
instruction: 'string (optional) - 요약 지시 (예: "주요 수치만 뽑아줘", "3줄 요약")',
|
||||
},
|
||||
execute: async (args: { url: string; instruction?: string }): Promise<ToolResult> => {
|
||||
if (!args.url?.trim()) return { success: false, error: 'url is required' };
|
||||
const { endpoint, model } = getOllamaConfig();
|
||||
try {
|
||||
const fetchResult = await executeWebFetch({ url: args.url, max_chars: 8000 });
|
||||
if (!fetchResult.success) return fetchResult;
|
||||
const pageText = fetchResult.stdout || '';
|
||||
const prompt = args.instruction
|
||||
? `다음 웹 페이지 내용을 읽고 "${args.instruction}":\n\n${pageText}`
|
||||
: `다음 웹 페이지 내용을 핵심 위주로 간결하게 요약해줘:\n\n${pageText}`;
|
||||
const res = await fetch(`${endpoint}/api/chat`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ model, messages: [{ role: 'user', content: prompt }], stream: false }),
|
||||
signal: AbortSignal.timeout(60_000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`Ollama HTTP ${res.status}`);
|
||||
const data: any = await res.json();
|
||||
const answer = String(data.message?.content || '');
|
||||
if (!answer) throw new Error('Ollama returned empty response');
|
||||
return { success: true, stdout: answer, data: { url: args.url, provider: 'ollama', answer } };
|
||||
} catch (err: any) {
|
||||
return { success: false, error: `ollama_web_fetch failed: ${err.message}` };
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -346,6 +346,7 @@ export interface SmallClawConfig {
|
||||
google_api_key?: string;
|
||||
google_cx?: string;
|
||||
brave_api_key?: string;
|
||||
searxng_url?: string;
|
||||
search_rigor?: string;
|
||||
};
|
||||
pubmed?: {
|
||||
|
||||
Reference in new issue
Block a user