v2.3.1
No files matched your search
@@ -28,7 +28,9 @@
|
||||
"Bash(npm run *)",
|
||||
"Bash(curl *)",
|
||||
"Bash(ollama list *)",
|
||||
"WebSearch"
|
||||
"WebSearch",
|
||||
"Bash(pdftotext -v)",
|
||||
"Bash(pm2 list *)"
|
||||
]
|
||||
},
|
||||
"ANTHROPIC_BASE_URL": "https://openrouter.ai/api",
|
||||
|
||||
@@ -106,12 +106,172 @@
|
||||
"role": "assistant",
|
||||
"content": "제시해주신 논문 **\"상보적 리보솜 프로파일링 접근법을 이용한 대장균(Escherichia coli) 내 새로운 번역 소형 오픈 리딩 프레임(sORF)의 식별\"**의 전문 번역입니다. 내용이 방대하여 핵심 학술 내용을 중심으로 매끄럽게 번역해 드립니다.\n\n# 상보적 리보솜 프로파일링 접근법을 이용한 대장균 내 새로운 번역 소형 오픈 리딩 프레임(sORF)의 식별\n\n## [초록]\n51개 미만의 아미노산으로 구성된 소형 단백질은 모든 생명 영역에 풍부하게 존재하지만, 크기가 작아 컴퓨터 예측이 어렵고 표준 단백질 분석법으로 검출하기 힘들어 간과되는 경우가 많습니다. 리보솜 프로파일링은 오픈 리딩 프레임(ORF)의 번역을 감지하여 소형 단백질의 존재를 추론하는 데 사용되어 왔습니다. 본 연구에서는 개시 코돈 또는 종결 코돈에서 리보솜을 멈추게 하는 항생제를 처리한 대장균의 리보솜 프로파일링 데이터를 결합 분석했습니다. 이를 통해 약 400개의 새로운 ORF 후보를 높은 감도로 식별했으며, 이 중 365개는 51개 미만의 아미노산으로 구성된 소형 단백질을 인코딩합니다. 우리는 선택된 여러 sORF의 번역을 검증했으며, 많은 수가 불안정한 단백질을 인코딩할 가능성이 높음을 보여주었습니다. 또한, 새로 식별된 대부분의 sORF가 정화 선택(purifying selection) 하에 있지 않음을 확인했으며, 이는 이들이 세포 적합성(fitness)에 영향을 미치지 않는 '만연한 번역(pervasive translation)'의 산물임을 시사합니다.\n\n## [서론]\n수만 개의 박테리아 게놈이 서열 분석되었지만, ORF 예측 파이프라인은 주로 길이를 기준으로 삼기 때문에 50개 이상의 아미노산을 인코딩하는 ORF를 우선적으로 식별합니다. 그러나 최근 연구들은 51개 미만의 아미노산을 가진 소형 ORF(sORF)가 다수 존재한다는 강력한 증거를 제시하고 있습니다. 대장균 K-12에는 118개의 sORF가 기술되어 있으며, 이들은 하위 유전자의 조절 인자나 단백질 복합체의 활성 조절자로 기능할 수 있습니다.\n\n본 연구에서는 개시 지점을 찾는 Ribo-RET 기법과 종결 지점을 찾는 Ribo-Api/Pmn 기법을 결합하여 위양성률(FDR)을 2.2%까지 낮춘 고정밀 sORF 식별 방법을 제시합니다.\n\n## [결과]\n\n### 1. Ribo-RET 및 Ribo-Api 데이터를 이용한 ORF 식별\n* **Ribo-RET 재분석:** 리보솜이 개시 코돈에 머무는 위치(IERF)를 분석하여 7,936개의 잠재적 개시 코돈을 식별했습니다.\n* **Ribo-Api 재분석:** 리보솜이 종결 코돈에 머무는 위치(TERF)를 분석하여 6,877개의 잠재적 종결 코돈을 식별했습니다.\n* **데이터 결합:** 개시 신호와 종결 신호가 일치하는 쌍을 찾아 1,839개의 ORF를 확정했습니다. 이 중 1,005개는 기존 주석과 일치했고, 437개는 이형(isoform), **397개는 완전히 새로운(novel) ORF**로 분류되었습니다.\n\n### 2. 새로운 ORF의 특징\n새로운 ORF의 27%는 유전자 사이(intergenic) 영역에 위치하며, 44%는 기존 유전자와 같은 방��¥으로 완전히 겹쳐 있습니다. 이들의 길이는 중앙값 15개 코돈으로 매우 짧았습니다. 또한, 이들의 개시 코돈 주변은 활발하게 번역되는 ORF에서 나타나는 특징인 낮은 RNA 2차 구조 에너지를 보였습니다.\n\n### 3. 실험적 검증\n17개의 sORF를 선택하여 SPA 태그를 부착한 후 웨스턴 블로팅을 실시했습니다.\n* 10개의 sORF에서 안정적인 단백질 발현을 확인했습니다.\n* 나머지 중 일부는 ClpP 프로테아제 억제제(bortezomib)를 처리했을 때만 검출되었습니다. 이는 많은 sORF가 실제로 번역되지만, 생성 직후 빠르게 분해되는 불안정한 단백질임을 의미합니다.\n\n### 4. 기능성 분석\n대부분의 새로운 sORF는 코돈 편향성(codon bias)이나 서열 보존성이 낮았습니다. 이는 이들이 특정 생물학적 기능을 수행하기보다는 게놈 전반에서 일어나는 '만연한 번역'의 결과물일 가능성이 높음을 시사합니다. 다만, 일부 sORF는 다른 종에서도 보존된 서열을 보여 기능적 중요성을 가질 가능성이 있습니다.\n\n## [고찰]\nRibo-RET와 Ribo-Api/Pmn을 결합하는 방식은 번역의 시작과 끝을 동시에 증명하므로 매우 높은 신뢰도를 제공합니다. 대장균은 우리가 이전에 알았던 것보다 훨씬 더 많은 소형 단백질을 생산하고 있으며, 이들 중 상당수는 불안정한 상태로 존재합니다. 특히 수평적으로 획득된 유전자(horizontally acquired genes) 영역에서 내부 번역 개시가 빈번하게 일어나는 경향을 확인했습니Line truncated
|
||||
"timestamp": 1777636039588
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "플라스틱 대체재에 관한 최신 논문 5편.",
|
||||
"timestamp": 1777648304046
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "플라스틱 대체재 및 생분해성 고분자에 관한 최신 논문(2026~2027년 발표 예정 및 최신작) 5편입니다.\n\n1. **면 폐기물을 이용한 셀룰로오스 기반 폼 개발 (2027)**\n * **제목:** Developing Cellulose-Based Foams from Cotton Waste\n * **내용:** 스티로폼(PS)과 우레탄(PU) 폼을 대체하기 위해 면 폐기물에서 추출한 셀룰로오스를 활용한 경량·다공성 포장재 연구.\n2. **히알루론산-PVP 혼합물을 이용한 친환경 플라스틱 (2026)**\n * **제목:** Properties of Hyaluronic Acid–Polyvinylpyrrolidone Blends as Green Plastic Materials\n * **내용:** 천연 유래 성분인 히알루론산(HA)과 수용성 고분자(PVP)를 결합하여 독성이 없고 생분해성이 뛰어난 필름 형태의 바이오 플라스틱 개발.\n3. **농업 부산물 가치 제고를 위한 순환 재료 프레임워크 (2026)**\n * **제목:** A Circular Material Value Retention Framework for Agricultural By-Product Valorisation\n * **내용:** EU와 영국의 농업 부산물을 활용하여 환경 오염을 최소화하고 플라스틱을 대체할 수 있는 지속 가능한 순환 경제 모델 제시.\n4. **전기방사 PHBH 바이오페이퍼의 개발 및 특성 분석 (2026)**\n * **제목:** Development and Characterization of Electrospun Poly(3-hydroxybutyrate-co-3-hydroxyhexanoate) (PHBH) Biopapers\n * **내용:** 미생물 합성 고분자인 PHBH를 전기방사 기법으로 가공하여, 기존 플라스틱 필름을 대체할 수 있는 고성능 바이오 종이(Biopaper) 제작 연구.\n5. **올리브 잎 추출물과 그래핀을 첨가한 키토산 필름의 포장 특성 비교 (2026)**\n * **제목:** Comparative study of the packaging properties of olive leaf extract and graphene nanoplate filled chitosan films\n * **내용:** 유기 폐기물인 올리브 잎 추출물과 키토산을 결합하여 식품 포장용 플라스틱을 대체할 수 있는 항균·항산화 기능성 바이오 패키징 연구.\n\n관심 있는 논문의 전문(Full-text)이나 상세 요약이 필요하시면 말씀해 주세요.",
|
||||
"timestamp": 1777648318040
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "1",
|
||||
"timestamp": 1777648388687
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "플라스틱 대체재에 관한 최신 논문 6편을 추가하여 총 11편을 채워 드립니다.\n\n6. **전분 기반 지속 가능 식품 포장재의 최신 진전 (2025)**\n - **제목:** An Overview of Starch-Based Materials for Sustainable Food Packaging\n - **내용:** 석유 유래 플라스틱의 대안으로 전분 기반 필름의 수분 저항성과 기계적 강도를 개선하는 최신 기술 연구.\n\n7. **일회용 플라스틱 재고: 혁신, 정책 및 시장 형성 (2025)**\n - **제목:** Rethinking single-use plastics: Innovations, polices, and market shaping\n - **내용:** 포장 산업에서 생분해성 솔루션을 시장에 정착시키기 위한 정책적 혁신과 소비자 인식 변화 분석.\n\n8. **석유 기반 제품을 식물성 재료로 대체하는 지속 가능 에너지 리뷰 (2025)**\n - **제목:** Replacement of Petroleum Based Products With Plant-Based Materials\n - **내용:** 기후 변화와 화석 연료 고갈에 대응하여 바이오 자원을 활용한 플라스틱 대체재의 잠재력 검토.\n\n9. **적층 제조 공정을 통한 PHB 바이오폴리머의 열적·기계적 특성 수정 (2025)**\n - **제목:** Review of Biopolymer Polyhydroxybutyrate (PHB) and Blends\n - **내용:** 높은 결정성을 가진 PHB의 단점을 보완하여 3D 프린팅 등 산업 현장에서 플라스틱 대안으로 활용하는 방법 연구.\n\n10. **산업 퇴비화 조건에서의 상업용 생분해성 플라스틱 분해 연구 (2025)**\n - **제목:** Disintegration of commercial biodegradable plastic products\n - **내용:** 시중의 생분해성 플라스틱 제품 10종이 실제 산업용 퇴비화 환경에서 얼마나 효과적으로 분해되는지 실증 분석.\n\n11. **해양 환경에서의 바이오 플라스틱 생분해 메커니즘 분석 (2025)**\n - **제목:** Biodegradation mechanisms of bioplastics in marine environments\n - **내용:** 미세 플라스틱 문제를 해결하기 위해 해양 생태계에서 자연 분해되는 새로운 고분자 소재의 설계 원리 제시.\n\n추가로 궁금한 점이나 특정 논문의 전문이 필요하시면 말씀해 주세요.",
|
||||
"timestamp": 1777648419628
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "면 폐기물을 이용한 셀룰로오스 기반 폼 개발 전문 있으면 다운로드.",
|
||||
"timestamp": 1777648496314
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "요청하신 논문 **\"Developing Cellulose-Based Foams from Cotton Waste\" (Kundavi Thanda, 2027/2025)**는 워싱턴 주립대학교(WSU)의 석사 학위 논문으로 확인되었습니다.\n\n현재 해당 논문은 대학 리포지토리(WSU Research Exchange)에 등록되어 있으나, 학위 논문의 특성상 외부 공개가 제한되어 있거나 직접적인 PDF 다운로드 링크가 활성화되지 않은 상태입니다. 대신, 유사한 주제의 최신 오픈 액세스 논문을 찾아드릴까요?",
|
||||
"timestamp": 1777648534517
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "해수 담수화 최신기술 논문 10개",
|
||||
"timestamp": 1777649592274
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "해수 담수화 최신 기술(2024~2026년 발표)에 관한 주요 논문 10편을 정리해 드립니다.\n\n1. **스마트 나노소재를 이용한 해수 담수화의 진전 (2026)**\n - **제목:** Smart nanomaterials in seawater desalination: Advances from molecular engineering to water security\n - **내용:** 분자 공학 기술을 적용한 스마트 나노소재가 담수화 효율과 수자원 보안에 미치는 영향을 분석한 최신 리뷰.\n\n2. **MXene 기반 하이드로젤/에어로젤을 이용한 태양광 계면 증발 담수화 (2026)**\n - **제목:** Emerging Platforms for High-Efficiency Solar-Driven Interfacial Evaporation Desalination: MXene-Based Hydrogels/Aerogels\n - **내용:** 태양 에너지를 직접 활용하여 물을 증발시키는 계면 증발 기술(SIED)에서 MXene 소재의 고효율성을 입증.\n\n3. **해수 담수화를 위한 부직포 막의 구조 설계 및 기능화 전략 (2026)**\n - **제목:** Nonwoven membranes for seawater desalination: Structural design, functionalization strategies, and system-level performance\n - **내용:** 높은 다공성과 기계적 강도를 가진 부직포 소재를 차세대 담수화 분리막으로 활용하기 위한 설계 전략 제시.\n\n4. **고성능 축전식 탈염(CDI)을 위한 바이오매스 유래 탄소 전극 연구 (2026)**\n - **제목:** Synergistic MnHCF/Biomass-Derived Carbon Asymmetric Electrodes for High-Performance Capacitive Deionization\n - **내용:** 에너지 효율이 높은 담수화 기술인 CDI에서 지속 가능한 바이오매스 소재를 전극으로 사용하여 성능을 극대화한 연구.\n\n5. **도시 기후 회복력 강화를 위한 지속 가능한 분리막 기술 (2026)**\n - **제목:** Sustainable Membrane Technologies for Enhancing Urban Climate Resilience\n - **내용:** 물 부족 해결을 위해 하수 재이용 및 담수화 공정에 적용되는 지속 가능한 분리막 기술의 정책적·기술적 검토.\n\n6. **산업 폐수 처리를 위한 하이브리드 담수화 시스템의 최적화 (2026)**\n - **제목:** Systems-Level Optimization of Hybrid Produced Water Treatment Systems\n - **내용:** 고염도 폐수 처리를 위해 여러 담수화 기술을 결합한 하이브리드 시스템의 효율성 최적화 방안 연구.\n\n7. **다중 오염물질 동시 제거를 위한 유·무기 복합 PVDF 분리막 개발 (2026)**\n - **제목:** Organic-Inorganic Co-Modified PVDF Membrane for High-Flux Oil/Water Separation\n - **내용:** 해수 내 유분과 중금속 등 복합 오염물질을 한 번에 제거할 수 있는 고투과성 복합막 제조 기술.\n\n8. **미세 플라스틱과 유분 혼합물 제거를 위한 초친수성 분리막 (2026)**\n - **제목:** High-performance caffeic acid-based superhydrophilic membranes\n - **내용:** 담수화 전처리 과정에서 문제가 되는 미세 플라스틱과 유분을 효과적으로 분리하는 새로운 친환경 분리막 연구.\n\n9. **산업 폐수 내 방사성 물질 제거를 위한 첨단 분리막 기술 (2026)**\n - **제목:** Advanced Membrane Technologies for Sustainable Removal of NORMs\n - **내용:** 담수화 과정에서 발생할 수 있는 천연 방사성 물질(NORM)을 안전하게 제거하기 위한 하이브리드 처리 시스템 분석.\n\n10. **순환 경제 관점에서의 수자원 회수 및 담수화 시스템 리뷰 (2026)**\n - **제목:** Beyond the flush: a review of wastewater circular systems\n - **내용:** 폐수를 단순 처리가 아닌 자원 회수의 관점에서 접근하여 담수화 기술과 결합한 순환 경제 모델 제시.\n\n특정 논문의 전문(Full-text)이나 상세한 기술적 내용이 필요하시면 말씀해 주세요.",
|
||||
"timestamp": 1777649615914
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "1. 스마트 나노소재를 이용한 해수 담수화의 진전 (2026) -- 상세히",
|
||||
"timestamp": 1777649781067
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "---\n요청하신 논문 **\"Smart nanomaterials in seawater desalination: Advances from molecular engineering to water security\" (2026)**의 상세 내용입니다.\n\n### **1. 연구 배경 및 목적**\n전 세계적인 수자원 부족 문제를 해결하기 위해 해수 담수화 기술이 필수적이지만, 기존의 역삼투압(RO) 방식은 높은 에너지 소비와 분리막 오염(fouling)이라는 한계가 있습니다. 본 논문은 **분자 공학(Molecular Engineering)**을 통해 설계된 '스마트 나노소재'가 어떻게 이러한 한계를 극복하고 수자원 보안을 강화할 수 있는지 분석합니다.\n\n### **2. 핵심 기술: 스마트 나노소재의 역할**\n* **분자 수준의 정밀 설계:** 나노미터 단위에서 기공의 크기와 화학적 성질을 조절하여, 물 분자는 빠르게 통과시키고 염분(이온)은 완벽하게 차단하는 고선택성 분리막을 구현합니다.\n* **자극 응답성(Stimuli-Responsive):** 외부 환경(pH, 온도, 빛, 전기장 등)에 반응하여 물리적·화학적 특성이 변하는 소재를 사용하여, 오염 물질이 달라붙었을 때 스스로 세척하거나 투과도를 조절합니다.\n* **오염 방지(Anti-fouling) 특성:** 나노 코팅 기술을 통해 분리막 표면의 친수성을 극대화하거나 전하를 조절하여 미생물 및 유기물이 흡착되는 것을 원천적으로 차단합니다.\n\n### **3. 주요 진전 사항 (Advances)**\n* **에너지 효율 극대화:** 나노 채널(예: 탄소 나노튜브, 그래핀 옥사이드)을 이용해 물의 마찰 저항을 최소화함으로써, 담수화에 필요한 압력과 에너지를 획기적으로 줄였습니다.\n* **차세대 담수화 공정 결합:** 스마트 나노소재를 **축전식 탈염(CDI)**이나 **정삼투(FO)** 공정에 적용하여, 기존 RO 방식보다 낮은 비용으로 고염도 해수를 처리하는 기술적 토대를 마련했습니다.\n* **내구성 및 수명 연장:** 가혹한 해수 환경에서도 화학적 안정성을 유지하는 나노 복합 재료를 개발하여 분리막의 교체 주기를 대폭 늘렸습니다.\n\n### **4. 수자원 보안(Water Security)에의 기여**\n이 논문은 스마트 나노소재가 단순히 기술적 성능 향상을 넘어, 저비용·고효율 담수화를 가능하게 함으로써 물 부족 국가의 수자원 자립도를 높이고 글로벌 수자원 보안을 달성하는 핵심 동력이 될 것이라고 강조합니다.\n\n---\n**추가 정보가 필요하신가요?** 이 논문에서 다룬 특정 소재(예: MXene, MOF 등)에 대한 상세 설명이나, 다른 번호의 논문 상세 분석이 필요하시면 말씀해 주세요.",
|
||||
"timestamp": 1777649832984
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "유튜브에 그랜드 스타렉스 캠핑카 개조 영상 몇 개 찾아줘.",
|
||||
"timestamp": 1777694099865
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "유튜브에서 찾은 그랜드 스타렉스 캠핑카 개조 관련 영상들입니다.\n\n1. **[600만원대 가성비 개조]** 12인승을 600만원대로 개조한 사례 (인버터, 배터리 포함)\n * [영상 보기](https://www.youtube.com/watch?v=z4x4uBtBb3k)\n2. **[스타렉스 3밴 개조 과정]** 중고 3밴을 구입해 집 같은 분위기로 꾸미는 전체 과정\n * [영상 보기](https://www.youtube.com/watch?v=DBcJ04rWZbs)\n3. **[자작 캠핑카 만들기]** 구조변경 승인 없이 직접 만드는 DIY 중간 완성 영상\n * [영상 보기](https://www.youtube.com/watch?v=x7iqukSTRfw)\n4. **[차박 입문 끝판왕]** 1,700만원대(차량 포함)로 완성된 풀옵션 캠핑카 소개\n * [영상 보기](https://www.youtube.com/watch?v=Nmz9QSnUhCg)\n5. **[찜질방 컨셉 개조]** 겨울철 차박에 특화된 찜질방 스타일의 독특한 개조 사례\n * [영상 보기](https://www.youtube.com/watch?v=iBzrCiZQiA8)\n\n원하시는 스타일(가성비, DIY, 풀옵션 등)이 있다면 더 구체적으로 찾아드릴 수 있습니다.",
|
||||
"timestamp": 1777694129719
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "오늘 밤 구미 날씨 어때?",
|
||||
"timestamp": 1777721304679
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "오늘 밤 구미는 대체로 맑거나 구름이 조금 낀 날씨가 예상됩니다. 기온은 14~16도 사이로 선선하겠으니, 외출 시 가벼운 겉옷을 챙기시는 것이 좋겠습니다.",
|
||||
"timestamp": 1777721368442
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "오늘 bbc 뉴스 요약해줘.",
|
||||
"timestamp": 1777721587535
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "현재 시간(2026년 5월 2일) 기준 BBC의 주요 글로벌 뉴스를 요약해 드립니다.\n\n1. **중동 긴장 지속 및 인도적 지원**: 가자 지구 내 인도적 위기에 대한 국제사회의 우려가 계속되는 가운데, 구호 물자 전달을 위한 새로운 경로 확보와 휴전 협상에 대한 논의가 주요 이슈로 다뤄지고 있습니다.\n2. **우크라이나 전황**: 우크라이나 동부 전선에서의 교전이 격화되고 있으며, 서방 국가들의 추가 군사 지원 물량의 도착 시점과 그에 따른 전장 영향에 대한 분석이 보도되고 있습니다.\n3. **영국 지방 선거 결과 분석**: 최근 치러진 영국 지방 선거에서 노동당이 큰 승리를 거두고 보수당이 고전함에 따라, 향후 총선 향방과 리시 수낙 총리의 리더십에 대한 정치적 분석이 집중 보도 중입니다.\n4. **글로벌 경제 및 금리**: 주요국의 인플레이션 둔화 속도와 중앙은행들의 금리 결정 전망이 세계 경제의 불확실성을 높이고 있다는 소식이 경제 섹션의 핵심입니다.\n\n더 구체적인 분야(정치, 과학, 기술 등)의 뉴스가 궁금하시면 말씀해 주세요.",
|
||||
"timestamp": 1777721644146
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "맹금류 사진 몇 장 찾아줘",
|
||||
"timestamp": 1777722400374
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "멋진 맹금류 사진들입니다.\n\n\n\n\n\n\n\n추가로 독수리나 부엉이 같은 특정 종의 사진이 더 필요하시면 말씀해 주세요.",
|
||||
"timestamp": 1777722410770
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "사진 편집은 할 수 없지?",
|
||||
"timestamp": 1777722451711
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "직접적인 GUI 편집 도구는 없지만, **파이썬(Pillow, OpenCV 등) 코드를 작성해 사진을 편집**할 수 있습니다.\n\n작업 공간에 사진을 업로드하고 원하는 편집 내용(크기 조절, 자르기, 회전, 필터 적용 등)을 말씀해 주시면 바로 처리해 드릴게요. 어떤 편집이 필요하신가요?",
|
||||
"timestamp": 1777722461074
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "사진 내용 묘사 할 수 있니?",
|
||||
"timestamp": 1777722489446
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "네, 사진의 내용을 상세히 묘사할 수 있습니다.\n\n작업 공간에 사진 파일을 업로드하거나 이미지 URL을 주시면, **이미지 분석 도구**를 사용해 사진 속 인물, 사물, 배경, 분위기 등을 파악하여 설명해 드릴게요. 분석하고 싶은 사진이 있다면 바로 공유해 주세요!",
|
||||
"timestamp": 1777722498323
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "위에 3번째 사진 될까?",
|
||||
"timestamp": 1777722525501
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "세 번째 사진인 **송골매(Peregrine Falcon)**의 모습은 다음과 같습니다.\n\n* **주요 피사체:** 날카로운 부리와 강렬한 눈빛을 가진 송골매의 상반신이 클로즈업되어 있습니다. 깃털은 짙은 회색과 흰색이 섞인 정교한 패턴을 띠고 있어 매우 위엄 있는 분위기를 자아냅니다.\n* **배경:** 배경은 부드럽게 아웃포커싱(보케 효과) 처리되어 있어, 매의 디테일한 깃털 질감과 눈동자가 더욱 돋보입니다.\n* **분위기:** 사냥감을 노리는 듯한 고도의 집중력과 맹금류 특유의 강인함이 잘 느껴지는 사진입니다.\n\n이 사진에 대해 더 궁금한 점이나, 다른 사진의 묘사가 필요하시면 말씀해 주세요!",
|
||||
"timestamp": 1777722534399
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "맹금류 사진 5장 찾아서 슬라이드 만들어줘.",
|
||||
"timestamp": 1777725540673
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "맹금류 5종의 사진을 담은 슬라이드 제작을 완료했습니다.\n\n* **포함된 맹금류:** 흰머리수리, 송골매, 수리부엉이, 붉은꼬리매, 물수리\n* **파일:** [맹금류_갤러리.pptx](sandbox:/맹금류_갤러리/맹금류_갤러리.pptx)\n\n각 슬라이드는 맹금류의 특징을 잘 보여주는 이미지와 함께 구성되었습니다. 더 필요한 내용이 있으면 말씀해 주세요!",
|
||||
"timestamp": 1777725556479
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "사진마다 간략한 설명 붙여서 편집해줘.",
|
||||
"timestamp": 1777725847731
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "각 맹금류의 특징(사냥 방식, 외형적 특징 등)을 담은 설명을 추가하여 슬라이드를 편집했습니다.\n\n* **업데이트된 파일:** [맹금류_갤러리.pptx](sandbox:/맹금류_갤러리/맹금류_갤러리.pptx)\n\n송골매의 속도, 흰머리수리의 위엄, 수리부엉이의 야행성 등 핵심 정보를 사진과 함께 확인하실 수 있습니다.",
|
||||
"timestamp": 1777725858699
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "말 품종 슬라이드 만들자.",
|
||||
"timestamp": 1777726379007
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "아라비안, 서러브레드 등 대표적인 말 품종 5종을 소개하는 슬라이드를 제작했습니다.\n\n* **파일:** [말_품종_가이드.pptx](sandbox:/말_품종_가이드/말_품종_가이드.pptx)\n\n각 품종의 기원과 주요 특징을 사진과 함께 정리해 두었습니다. 확인해 보세요!",
|
||||
"timestamp": 1777726397357
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "고양이 품종에 관한 슬라이드 만들자.",
|
||||
"timestamp": 1777726953883
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "고양이 품종 5종(아비시니안, 렉돌, 메인쿤 등)의 특징과 사진을 담은 슬라이드를 제작했습니다.\n\n* **파일:** [고양이_품종_가이드.pptx](/api/files/%EA%B3%A0%EC%96%91%EC%9D%B4_%ED%92%88%EC%A2%85_%EA%B0%80%EC%9D%B4%EB%93%9C/%EA%B3%A0%EC%96%91%EC%9D%B4_%ED%92%88%EC%A2%85_%EA%B0%80%EC%9D%B4%EB%93%9C.pptx)\n\n각 품종의 성격과 외형적 특징을 간략한 설명과 함께 확인하실 수 있습니다.",
|
||||
"timestamp": 1777726971773
|
||||
}
|
||||
],
|
||||
"workspace": "/home/kim/homeclaw/.smallclaw/users/papa/workspace",
|
||||
"createdAt": 1777629542985,
|
||||
"lastActiveAt": 1777636039589,
|
||||
"lastActiveAt": 1777726971773,
|
||||
"pendingMemoryFlush": false,
|
||||
"pendingCompaction": false,
|
||||
"contextTokenEstimate": 1773
|
||||
"contextTokenEstimate": 4831
|
||||
}
|
||||
@@ -315,3 +315,42 @@ https://www.ncbi.nlm.nih.gov/pmc/articles/PMC8765432/
|
||||
[21:05:38] **SmallClaw**: HEARTBEAT_OK
|
||||
[21:35:47] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[21:35:49] **SmallClaw**: HEARTBEAT_OK
|
||||
[00:11:47] **User**: 플라스틱 대체재에 관한 최신 논문 5편.
|
||||
[00:11:58] **SmallClaw**: 플라스틱 대체재 및 생분해성 고분자에 관한 최신 논문(2026~2027년 발표 예정 및 최신작) 5편입니다.
|
||||
|
||||
1. **면 폐기물을 이용한 셀룰로오스 기반 폼 개발 (2027)**
|
||||
* **제목:** Developing Cellulose-Based Foams from Cotton Waste
|
||||
* **내용:** 스티로폼(PS)과 우레탄(PU) 폼을 대체하기 위해 면 폐기물에서 추출한 셀룰로오스를 활용한 경량·다공성 포장재 연구.
|
||||
2. **히알루론산-PVP 혼합물을 이용한 친환경 플라스틱 (2026)**
|
||||
*
|
||||
[00:13:13] **User**: 1
|
||||
[00:13:39] **SmallClaw**: 플라스틱 대체재에 관한 최신 논문 6편을 추가하여 총 11편을 채워 드립니다.
|
||||
|
||||
6. **전분 기반 지속 가능 식품 포장재의 최신 진전 (2025)**
|
||||
- **제목:** An Overview of Starch-Based Materials for Sustainable Food Packaging
|
||||
- **내용:** 석유 유래 플라스틱의 대안으로 전분 기반 필름의 수분 저항성과 기계적 강도를 개선하는 최신 기술 연구.
|
||||
|
||||
7. **일회용 플라스틱 재고: 혁신, 정책 및 시장 형성 (2025)**
|
||||
- **제목:** Rethin
|
||||
[00:15:02] **User**: 면 폐기물을 이용한 셀룰로오스 기반 폼 개발 전문 있으면 다운로드.
|
||||
[00:15:34] **SmallClaw**: 요청하신 논문 **"Developing Cellulose-Based Foams from Cotton Waste" (Kundavi Thanda, 2027/2025)**는 워싱턴 주립대학교(WSU)의 석사 학위 논문으로 확인되었습니다.
|
||||
|
||||
현재 해당 논문은 대학 리포지토리(WSU Research Exchange)에 등록되어 있으나, 학위 논문의 특성상 외부 공개가 제한되어 있거나 직접적인 PDF 다운로드 링크가 활성화되지 않은 상태입니다. 대신, 유사한 주제의 최신 오픈 액세스 논문을 찾아드릴까요?
|
||||
[00:33:16] **User**: 해수 담수화 최신기술 논문 10개
|
||||
[00:33:35] **SmallClaw**: 해수 담수화 최신 기술(2024~2026년 발표)에 관한 주요 논문 10편을 정리해 드립니다.
|
||||
|
||||
1. **스마트 나노소재를 이용한 해수 담수화의 진전 (2026)**
|
||||
- **제목:** Smart nanomaterials in seawater desalination: Advances from molecular engineering to water security
|
||||
- **내용:** 분자 공학 기술을 적용한 스마트 나노소재가 담수화 효율과 수자원 보안에 미치는 영향을 분석한 최신 리뷰.
|
||||
|
||||
2. **MXene 기반 하이드로젤/에
|
||||
[00:36:26] **User**: 1. 스마트 나노소재를 이용한 해수 담수화의 진전 (2026) -- 상세히
|
||||
[00:37:12] **SmallClaw**: ---
|
||||
요청하신 논문 **"Smart nanomaterials in seawater desalination: Advances from molecular engineering to water security" (2026)**의 상세 내용입니다.
|
||||
|
||||
### **1. 연구 배경 및 목적**
|
||||
전 세계적인 수자원 부족 문제를 해결하기 위해 해수 담수화 기술이 필수적이지만, 기존의 역삼투압(RO) 방식은 높은 에너지 소비와 분리막 오염(fouling)이라는 한계가 있습니다. 본 논문은 **분자 공학(Molecular Engineering)**을
|
||||
[08:10:41] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[08:10:42] **SmallClaw**: HEARTBEAT_OK
|
||||
[08:40:46] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[08:40:52] **SmallClaw**: HEARTBEAT_OK
|
||||
@@ -0,0 +1,111 @@
|
||||
[09:10:55] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[09:10:56] **SmallClaw**: HEARTBEAT_OK
|
||||
[09:41:00] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[09:41:02] **SmallClaw**: HEARTBEAT_OK
|
||||
[10:11:06] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[10:11:11] **SmallClaw**: HEARTBEAT_OK
|
||||
[10:41:17] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[10:41:18] **SmallClaw**: HEARTBEAT_OK
|
||||
[11:11:24] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[11:11:26] **SmallClaw**: HEARTBEAT_OK
|
||||
[11:41:36] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[11:41:44] **SmallClaw**: HEARTBEAT_OK
|
||||
[12:11:48] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[12:11:50] **SmallClaw**: HEARTBEAT_OK
|
||||
[12:55:02] **User**: 유튜브에 그랜드 스타렉스 캠핑카 개조 영상 몇 개 찾아줘.
|
||||
[12:55:29] **SmallClaw**: 유튜브에서 찾은 그랜드 스타렉스 캠핑카 개조 관련 영상들입니다.
|
||||
|
||||
1. **[600만원대 가성비 개조]** 12인승을 600만원대로 개조한 사례 (인버터, 배터리 포함)
|
||||
* [영상 보기](https://www.youtube.com/watch?v=z4x4uBtBb3k)
|
||||
2. **[스타렉스 3밴 개조 과정]** 중고 3밴을 구입해 집 같은 분위기로 꾸미는 전체 과정
|
||||
* [영상 보기](https://www.youtube.com/watch?v=DBcJ04rWZbs)
|
||||
3. **[자작 캠핑카 만들기]** 구조변경 승
|
||||
[13:24:47] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[13:24:48] **SmallClaw**: HEARTBEAT_OK
|
||||
[13:54:51] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[13:54:53] **SmallClaw**: HEARTBEAT_OK
|
||||
[14:24:59] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[14:25:01] **SmallClaw**: HEARTBEAT_OK
|
||||
[14:55:04] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[14:55:06] **SmallClaw**: HEARTBEAT_OK
|
||||
[15:25:10] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[15:25:12] **SmallClaw**: HEARTBEAT_OK
|
||||
[15:55:16] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[15:55:18] **SmallClaw**: HEARTBEAT_OK
|
||||
[16:25:27] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[16:25:30] **SmallClaw**: HEARTBEAT_OK
|
||||
[16:55:35] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[16:55:37] **SmallClaw**: HEARTBEAT_OK
|
||||
[17:25:42] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[17:25:44] **SmallClaw**: HEARTBEAT_OK
|
||||
[17:55:48] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[17:55:49] **SmallClaw**: HEARTBEAT_OK
|
||||
[18:25:54] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[18:25:55] **SmallClaw**: HEARTBEAT_OK
|
||||
[18:56:00] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[18:56:02] **SmallClaw**: HEARTBEAT_OK
|
||||
[19:26:08] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[19:26:10] **SmallClaw**: HEARTBEAT_OK
|
||||
[19:56:16] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[19:56:18] **SmallClaw**: HEARTBEAT_OK
|
||||
[20:26:36] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[20:26:37] **SmallClaw**: HEARTBEAT_OK
|
||||
[20:29:23] **User**: 오늘 밤 구미 날씨 어때?
|
||||
[20:29:28] **SmallClaw**: 오늘 밤 구미는 대체로 맑거나 구름이 조금 낀 날씨가 예상됩니다. 기온은 14~16도 사이로 선선하겠으니, 외출 시 가벼운 겉옷을 챙기시는 것이 좋겠습니다.
|
||||
[20:33:59] **User**: 오늘 bbc 뉴스 요약해줘.
|
||||
[20:34:04] **SmallClaw**: 현재 시간(2026년 5월 2일) 기준 BBC의 주요 글로벌 뉴스를 요약해 드립니다.
|
||||
|
||||
1. **중동 긴장 지속 및 인도적 지원**: 가자 지구 내 인도적 위기에 대한 국제사회의 우려가 계속되는 가운데, 구호 물자 전달을 위한 새로운 경로 확보와 휴전 협상에 대한 논의가 주요 이슈로 다뤄지고 있습니다.
|
||||
2. **우크라이나 전황**: 우크라이나 동부 전선에서의 교전이 격화되고 있으며, 서방 국가들의 추가 군사 지원 물량의 도착 시점과 그에 따른 전장 영향에 대한 분석이 보도되고 있습니다.
|
||||
3. **영국 지방 선거 결과 분석**: 최근
|
||||
[20:46:45] **User**: 맹금류 사진 몇 장 찾아줘
|
||||
[20:46:50] **SmallClaw**: 멋진 맹금류 사진들입니다.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
 코드를 작성해 사진을 편집**할 수 있습니다.
|
||||
|
||||
작업 공간에 사진을 업로드하고 원하는 편집 내용(크기 조절, 자르기, 회전, 필터 적용 등)을 말씀해 주시면 바로 처리해 드릴게요. 어떤 편집이 필요하신가요?
|
||||
[20:48:16] **User**: 사진 내용 묘사 할 수 있니?
|
||||
[20:48:18] **SmallClaw**: 네, 사진의 내용을 상세히 묘사할 수 있습니다.
|
||||
|
||||
작업 공간에 사진 파일을 업로드하거나 이미지 URL을 주시면, **이미지 분석 도구**를 사용해 사진 속 인물, 사물, 배경, 분위기 등을 파악하여 설명해 드릴게요. 분석하고 싶은 사진이 있다면 바로 공유해 주세요!
|
||||
[20:48:49] **User**: 위에 3번째 사진 될까?
|
||||
[20:48:54] **SmallClaw**: 세 번째 사진인 **송골매(Peregrine Falcon)**의 모습은 다음과 같습니다.
|
||||
|
||||
* **주요 피사체:** 날카로운 부리와 강렬한 눈빛을 가진 송골매의 상반신이 클로즈업되어 있습니다. 깃털은 짙은 회색과 흰색이 섞인 정교한 패턴을 띠고 있어 매우 위엄 있는 분위기를 자아냅니다.
|
||||
* **배경:** 배경은 부드럽게 아웃포커싱(보케 효과) 처리되어 있어, 매의 디테일한 깃털 질감과 눈동자가 더욱 돋보입니다.
|
||||
* **분위기:** 사냥감을 노리는 듯한 고도의 집중력과 맹금류 특유의 강인함이 잘 느껴지는 사진입니다.
|
||||
|
||||
이
|
||||
[21:02:38] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[21:02:59] **SmallClaw**: HEARTBEAT_OK
|
||||
[21:39:05] **User**: 맹금류 사진 5장 찾아서 슬라이드 만들어줘.
|
||||
[21:39:16] **SmallClaw**: 맹금류 5종의 사진을 담은 슬라이드 제작을 완료했습니다.
|
||||
|
||||
* **포함된 맹금류:** 흰머리수리, 송골매, 수리부엉이, 붉은꼬리매, 물수리
|
||||
* **파일:** [맹금류_갤러리.pptx](sandbox:/맹금류_갤러리/맹금류_갤러리.pptx)
|
||||
|
||||
각 슬라이드는 맹금류의 특징을 잘 보여주는 이미지와 함께 구성되었습니다. 더 필요한 내용이 있으면 말씀해 주세요!
|
||||
[21:44:12] **User**: 사진마다 간략한 설명 붙여서 편집해줘.
|
||||
[21:44:18] **SmallClaw**: 각 맹금류의 특징(사냥 방식, 외형적 특징 등)을 담은 설명을 추가하여 슬라이드를 편집했습니다.
|
||||
|
||||
* **업데이트된 파일:** [맹금류_갤러리.pptx](sandbox:/맹금류_갤러리/맹금류_갤러리.pptx)
|
||||
|
||||
송골매의 속도, 흰머리수리의 위엄, 수리부엉이의 야행성 등 핵심 정보를 사진과 함께 확인하실 수 있습니다.
|
||||
[21:53:05] **User**: 말 품종 슬라이드 만들자.
|
||||
[21:53:17] **SmallClaw**: 아라비안, 서러브레드 등 대표적인 말 품종 5종을 소개하는 슬라이드를 제작했습니다.
|
||||
|
||||
* **파일:** [말_품종_가이드.pptx](sandbox:/말_품종_가이드/말_품종_가이드.pptx)
|
||||
|
||||
각 품종의 기원과 주요 특징을 사진과 함께 정리해 두었습니다. 확인해 보세요!
|
||||
[22:02:39] **User**: 고양이 품종에 관한 슬라이드 만들자.
|
||||
[22:02:51] **SmallClaw**: 고양이 품종 5종(아비시니안, 렉돌, 메인쿤 등)의 특징과 사진을 담은 슬라이드를 제작했습니다.
|
||||
|
||||
* **파일:** [고양이_품종_가이드.pptx](/api/files/%EA%B3%A0%EC%96%91%EC%9D%B4_%ED%92%88%EC%A2%85_%EA%B0%80%EC%9D%B4%EB%93%9C/%EA%B3%A0%EC%96%91%EC%9D%B4_%ED%92%88%EC%A2%85_%EA%B0%80%EC%9D%B4%EB%93%9C.pptx)
|
||||
|
||||
각 품종의 성격과 외형적 특징을 간략한 설명과 함께 확인하실 수 있습니다.
|
||||
@@ -0,0 +1,24 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>고양이 품종 가이드 - 다운로드</title>
|
||||
<style>
|
||||
body { font-family: 'Malgun Gothic', sans-serif; max-width: 600px; margin: 60px auto; padding: 20px; text-align: center; background: #f8f9fa; }
|
||||
.card { background: white; border-radius: 12px; padding: 40px 30px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); }
|
||||
h1 { color: #1a1a2e; font-size: 24px; margin-bottom: 10px; }
|
||||
p { color: #5f6f86; margin-bottom: 30px; }
|
||||
.btn { display: inline-block; background: #1668e3; color: white; text-decoration: none; padding: 14px 36px; border-radius: 8px; font-size: 16px; font-weight: bold; transition: background 0.2s; }
|
||||
.btn:hover { background: #1255bb; }
|
||||
.meta { margin-top: 20px; font-size: 12px; color: #888; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<h1>고양이 품종 가이드</h1>
|
||||
<p>슬라이드 6장이 준비되었습니다.</p>
|
||||
<a class="btn" href="고양이_품종_가이드.pptx" download>프레젠테이션 다운로드</a>
|
||||
<div class="meta">/home/kim/homeclaw/.smallclaw/users/papa/workspace/고양이_품종_가이드/고양이_품종_가이드.pptx</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 147 KiB |
|
After Width: | Height: | Size: 127 KiB |
|
After Width: | Height: | Size: 172 KiB |
|
After Width: | Height: | Size: 152 KiB |
|
After Width: | Height: | Size: 135 KiB |
|
After Width: | Height: | Size: 191 KiB |
|
After Width: | Height: | Size: 111 KiB |
|
After Width: | Height: | Size: 225 KiB |
|
After Width: | Height: | Size: 206 KiB |
|
After Width: | Height: | Size: 122 KiB |
@@ -0,0 +1,24 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>말 품종 가이드 - 다운로드</title>
|
||||
<style>
|
||||
body { font-family: 'Malgun Gothic', sans-serif; max-width: 600px; margin: 60px auto; padding: 20px; text-align: center; background: #f8f9fa; }
|
||||
.card { background: white; border-radius: 12px; padding: 40px 30px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); }
|
||||
h1 { color: #1a1a2e; font-size: 24px; margin-bottom: 10px; }
|
||||
p { color: #5f6f86; margin-bottom: 30px; }
|
||||
.btn { display: inline-block; background: #1668e3; color: white; text-decoration: none; padding: 14px 36px; border-radius: 8px; font-size: 16px; font-weight: bold; transition: background 0.2s; }
|
||||
.btn:hover { background: #1255bb; }
|
||||
.meta { margin-top: 20px; font-size: 12px; color: #888; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<h1>말 품종 가이드</h1>
|
||||
<p>슬라이드 6장이 준비되었습니다.</p>
|
||||
<a class="btn" href="말_품종_가이드.pptx" download>프레젠테이션 다운로드</a>
|
||||
<div class="meta">/home/kim/homeclaw/.smallclaw/users/papa/workspace/말_품종_가이드/말_품종_가이드.pptx</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 125 KiB |
|
After Width: | Height: | Size: 170 KiB |
|
After Width: | Height: | Size: 178 KiB |
|
After Width: | Height: | Size: 195 KiB |
|
After Width: | Height: | Size: 196 KiB |
|
After Width: | Height: | Size: 204 KiB |
|
After Width: | Height: | Size: 294 KiB |
|
After Width: | Height: | Size: 328 KiB |
|
After Width: | Height: | Size: 648 KiB |
|
After Width: | Height: | Size: 476 KiB |
@@ -0,0 +1,24 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Presentation - 다운로드</title>
|
||||
<style>
|
||||
body { font-family: 'Malgun Gothic', sans-serif; max-width: 600px; margin: 60px auto; padding: 20px; text-align: center; background: #f8f9fa; }
|
||||
.card { background: white; border-radius: 12px; padding: 40px 30px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); }
|
||||
h1 { color: #1a1a2e; font-size: 24px; margin-bottom: 10px; }
|
||||
p { color: #5f6f86; margin-bottom: 30px; }
|
||||
.btn { display: inline-block; background: #1668e3; color: white; text-decoration: none; padding: 14px 36px; border-radius: 8px; font-size: 16px; font-weight: bold; transition: background 0.2s; }
|
||||
.btn:hover { background: #1255bb; }
|
||||
.meta { margin-top: 20px; font-size: 12px; color: #888; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<h1>Presentation</h1>
|
||||
<p>슬라이드 11장이 준비되었습니다.</p>
|
||||
<a class="btn" href="맹금류_갤러리.pptx" download>프레젠테이션 다운로드</a>
|
||||
<div class="meta">/home/kim/homeclaw/.smallclaw/users/papa/workspace/맹금류_갤러리/맹금류_갤러리.pptx</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 150 KiB |
|
After Width: | Height: | Size: 159 KiB |
|
After Width: | Height: | Size: 196 KiB |
|
After Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 113 KiB |
|
After Width: | Height: | Size: 200 KiB |
|
After Width: | Height: | Size: 212 KiB |
|
After Width: | Height: | Size: 270 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 138 KiB |
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"workbench.preferredDarkColorTheme": "Tomorrow Night Blue",
|
||||
"workbench.colorTheme": "Kimbie Dark"
|
||||
}
|
||||
@@ -547,7 +547,15 @@ def make_section_slide(prs, slide_spec, colors, fs):
|
||||
|
||||
|
||||
def make_content_slide(prs, slide_spec, project_dir, workspace_path, colors, is_dark, fs, warnings, bg_image=None):
|
||||
"""Generate a content slide with title + bullets/body."""
|
||||
"""Generate a content slide.
|
||||
|
||||
Layouts (slide_spec["layout"]):
|
||||
"split-right" (default) — small title top, text left, image right
|
||||
"split-left" — small title top, image left, text right
|
||||
"text" — full-width text, image ignored
|
||||
"fullscreen" — image fills slide, title/text overlaid at bottom
|
||||
"""
|
||||
layout = (slide_spec.get("layout") or "split-right").lower()
|
||||
slide = prs.slides.add_slide(prs.slide_layouts[6])
|
||||
|
||||
# Background
|
||||
@@ -557,7 +565,35 @@ def make_content_slide(prs, slide_spec, project_dir, workspace_path, colors, is_
|
||||
set_slide_bg(slide, colors["background"])
|
||||
|
||||
has_title = bool(slide_spec.get("title"))
|
||||
has_image = bool(slide_spec.get("image_path"))
|
||||
has_image = bool(slide_spec.get("image_path")) and layout != "text"
|
||||
|
||||
# ── Fullscreen layout: image fills slide, text/title overlaid ─────────────
|
||||
if layout == "fullscreen" and has_image:
|
||||
resolved = resolve_image_path(slide_spec["image_path"], project_dir, workspace_path)
|
||||
add_image_or_placeholder(slide, resolved,
|
||||
Inches(0), Inches(0), SLIDE_W, SLIDE_H,
|
||||
warnings, fit_mode="cover")
|
||||
# Semi-transparent dark bar at bottom for text legibility
|
||||
bar_h = Inches(2.0)
|
||||
bar_y = SLIDE_H - bar_h
|
||||
add_shape_rect(slide, Inches(0), bar_y, SLIDE_W, bar_h, "000000")
|
||||
bar_shape = slide.shapes[-1]
|
||||
bar_shape.fill.fore_color.rgb = hex_to_rgb("000000")
|
||||
bar_shape.fill.transparency = 0.45
|
||||
# Title and body overlaid on dark bar
|
||||
if has_title:
|
||||
add_text_box(slide, Inches(0.6), bar_y + Inches(0.15), Inches(12.0), Inches(0.7),
|
||||
slide_spec["title"], font_size=Pt(fs["slide_title"]),
|
||||
color_hex="FFFFFF", bold=True)
|
||||
body_text = slide_spec.get("body") or slide_spec.get("content")
|
||||
bullets = slide_spec.get("bullets") or slide_spec.get("bullet_points")
|
||||
if bullets:
|
||||
body_text = " ● ".join(str(b) for b in bullets)
|
||||
if body_text:
|
||||
add_text_box(slide, Inches(0.6), bar_y + Inches(0.9), Inches(12.0), Inches(0.9),
|
||||
body_text, font_size=Pt(fs["body"]), color_hex="E0E0E0")
|
||||
return slide
|
||||
|
||||
content_y = Inches(1.5) if has_title else Inches(0.5)
|
||||
content_h = SLIDE_H - content_y - Inches(0.3)
|
||||
|
||||
@@ -568,13 +604,23 @@ def make_content_slide(prs, slide_spec, project_dir, workspace_path, colors, is_
|
||||
add_shape_rect(slide, L_MARGIN, Inches(1.15), Inches(2), Inches(0.04),
|
||||
colors["accent"])
|
||||
|
||||
# ── Two-column layout when image present ──────────────────────────────────
|
||||
# ── Column geometry ───────────────────────────────────────────────────────
|
||||
if has_image:
|
||||
text_ratio = _auto_text_ratio(slide_spec)
|
||||
text_col_w = CONTENT_W * text_ratio - COL_GAP / 2
|
||||
img_col_x = L_MARGIN + text_col_w + COL_GAP
|
||||
img_col_w = CONTENT_W * (1 - text_ratio) - COL_GAP / 2
|
||||
if layout == "split-left":
|
||||
# Image left, text right
|
||||
img_col_x = L_MARGIN
|
||||
img_col_w = CONTENT_W * (1 - text_ratio) - COL_GAP / 2
|
||||
text_col_x = img_col_x + img_col_w + COL_GAP
|
||||
text_col_w = CONTENT_W * text_ratio - COL_GAP / 2
|
||||
else:
|
||||
# split-right (default): text left, image right
|
||||
text_col_x = L_MARGIN
|
||||
text_col_w = CONTENT_W * text_ratio - COL_GAP / 2
|
||||
img_col_x = L_MARGIN + text_col_w + COL_GAP
|
||||
img_col_w = CONTENT_W * (1 - text_ratio) - COL_GAP / 2
|
||||
else:
|
||||
text_col_x = L_MARGIN
|
||||
text_col_w = CONTENT_W
|
||||
img_col_x = None
|
||||
img_col_w = None
|
||||
@@ -587,16 +633,16 @@ def make_content_slide(prs, slide_spec, project_dir, workspace_path, colors, is_
|
||||
bullet_fs = Pt(override) if override else Pt(fs["bullets"])
|
||||
|
||||
if bullet_items and len(bullet_items) > 0:
|
||||
add_bullet_list(slide, L_MARGIN, content_y, text_col_w, content_h,
|
||||
add_bullet_list(slide, text_col_x, content_y, text_col_w, content_h,
|
||||
bullet_items, font_size=bullet_fs,
|
||||
color_hex=colors["body"],
|
||||
bullet_color_hex=colors["accent"])
|
||||
elif body_text:
|
||||
add_text_box(slide, L_MARGIN, content_y, text_col_w, content_h,
|
||||
add_text_box(slide, text_col_x, content_y, text_col_w, content_h,
|
||||
body_text, font_size=body_fs, color_hex=colors["body"])
|
||||
|
||||
# ── Image column ──────────────────────────────────────────────────────────
|
||||
if has_image:
|
||||
if has_image and img_col_x is not None:
|
||||
resolved = resolve_image_path(slide_spec["image_path"], project_dir, workspace_path)
|
||||
add_image_or_placeholder(slide, resolved,
|
||||
img_col_x, content_y, img_col_w, content_h,
|
||||
|
||||
@@ -1,171 +1,11 @@
|
||||
/**
|
||||
* prompts.ts — SmallClaw workflow orchestration system prompt
|
||||
*
|
||||
* This was the missing piece from the original plan. It guides the LLM
|
||||
* on exactly when to call which tools and how to handle each conversation flow.
|
||||
*
|
||||
* File location: src/config/prompts.ts
|
||||
*
|
||||
* Usage in server-v2.ts:
|
||||
* import { buildSystemPrompt } from './config/prompts';
|
||||
* const systemPrompt = buildSystemPrompt(); // call at request time, not startup
|
||||
* prompts.ts — workflow context helpers
|
||||
* BASE_WORKFLOW_PROMPT was removed (dead code — never imported by active code paths).
|
||||
* Workflow context is injected via getWorkflowContextBlock() in server-v2.ts.
|
||||
*/
|
||||
|
||||
import { getWorkflowContextBlock } from '../gateway/agent-builder-integration';
|
||||
|
||||
// ─── Base Prompt ──────────────────────────────────────────────────────────────
|
||||
|
||||
const BASE_WORKFLOW_PROMPT = `
|
||||
## Workflow Automation — How To Behave
|
||||
|
||||
You are SmallClaw, a local AI assistant with the ability to build and run automated workflows through Agent Builder.
|
||||
|
||||
### RULE 1: Always Search Before Building
|
||||
When the user asks you to automate ANYTHING:
|
||||
1. **FIRST** call search_workflow_templates() with their intent as the query
|
||||
2. If results come back → use execute_workflow_template() with the matching workflow_id
|
||||
3. Only call architect_workflow() if search returns nothing
|
||||
|
||||
This saves time, API credits, and prevents clutter. Users hate duplicate workflows.
|
||||
|
||||
### RULE 2: The Full Build Flow (only when search finds nothing)
|
||||
When you need to create a NEW workflow, follow this exact sequence:
|
||||
\`\`\`
|
||||
1. architect_workflow(description)
|
||||
→ Returns: workflow_id, credentials_needed, status
|
||||
|
||||
2. If credentials_needed is NOT empty:
|
||||
→ Tell user: "I need [X API, Gmail, etc.] credentials to run this."
|
||||
→ Tell user: "Go to Agent Builder → Settings → Credentials and add them."
|
||||
→ Wait for user to confirm they've added credentials
|
||||
→ Call verify_workflow_credentials(workflow_id)
|
||||
→ Repeat until all_credentials_present = true
|
||||
|
||||
3. test_workflow(workflow_id)
|
||||
→ If test fails, report what went wrong. Do NOT deploy.
|
||||
→ If test passes, continue.
|
||||
|
||||
4. deploy_workflow(workflow_id, name, description, type, action, tags, ...)
|
||||
→ This saves the workflow permanently. SmallClaw will remember it.
|
||||
→ After this: tell the user the workflow is live and how to call it.
|
||||
\`\`\`
|
||||
|
||||
### RULE 3: Executing Existing Workflows
|
||||
For requests like "post to X about AI" or "send that daily digest":
|
||||
1. Search: search_workflow_templates("post to x")
|
||||
2. Found match → execute_workflow_template(workflow_id, { text: "..." })
|
||||
3. Tell user: "Done — posted using your existing X workflow."
|
||||
|
||||
Do NOT say "I'll set up a workflow for that" if one already exists.
|
||||
|
||||
### RULE 4: Credential Conversations
|
||||
Handle credentials gracefully. Don't make it technical.
|
||||
|
||||
BAD: "Error: 401 Unauthorized. The OAuth2 token has expired."
|
||||
GOOD: "I need your X API credentials to post tweets. Go to Agent Builder → Settings → Credentials, add the X API key and secret, then let me know when it's done."
|
||||
|
||||
BAD: "Missing: TWITTER_API_KEY, TWITTER_API_SECRET, TWITTER_ACCESS_TOKEN"
|
||||
GOOD: "You need to connect your X (Twitter) account. It takes about 2 minutes in Agent Builder settings."
|
||||
|
||||
### RULE 5: Status and Memory
|
||||
- When a user asks "what workflows do you have?" or "what can you automate?" → use get_workflow_status or summarize from your workflow memory block
|
||||
- When a user asks "did that post go out?" → use get_workflow_status(workflow_id)
|
||||
- You remember all deployed workflows. Reference them by name, not just ID.
|
||||
|
||||
### RULE 6: Handling Ambiguity
|
||||
- "Post about AI" → search for X/Twitter post template first (most common)
|
||||
- "Set up a daily thing" → ask: "Daily post on X, or a different kind of automation?"
|
||||
- "Run that workflow" → ask: "Which one? Here are your active workflows: [list them]"
|
||||
- "Create a workflow to..." → treat as architect request, but search first
|
||||
|
||||
### RULE 7: Telling Users What Happened
|
||||
After any workflow action, tell the user:
|
||||
- What ran
|
||||
- What the result was
|
||||
- If it's a new workflow: how to trigger it again ("Just say 'post to X about [topic]'")
|
||||
- If it's a recurring workflow: when it next runs
|
||||
|
||||
### RULE 8: user_message is Sacred — Always Relay It
|
||||
When any tool result contains a \`user_message\` field, you MUST present it to the user.
|
||||
Do not summarize it, do not rewrite it, do not skip it. Output it directly.
|
||||
This is the notification bridge between Agent Builder and the user — it contains execution
|
||||
results, credential links, and error details that the user needs to see.
|
||||
|
||||
Examples:
|
||||
- Tool returns \`user_message: "✅ X Daily Posts ran successfully. Completed in 1.2s."\`
|
||||
→ You say exactly that to the user.
|
||||
- Tool returns \`user_message\` with credential deep-links
|
||||
→ You present those links formatted so the user can click them.
|
||||
- Tool returns \`user_message: "❌ X Daily Posts failed. Error: 401 Unauthorized."\`
|
||||
→ You tell the user exactly that, then offer to help debug.
|
||||
|
||||
### RULE 9: Credential Messages Must Include the Links
|
||||
When verify_workflow_credentials returns missing credentials, read the \`user_message\`
|
||||
field and present it exactly as formatted — it already contains the clickable deep-links
|
||||
that open Agent Builder to the right credential form. Do not invent your own instructions.
|
||||
Just show the message and wait for the user to say they\'ve added them.
|
||||
|
||||
### EXAMPLE CONVERSATIONS
|
||||
|
||||
**First-time setup:**
|
||||
User: "Set up daily X posts at 9 AM about tech news"
|
||||
You: [search_workflow_templates("daily x posts scheduled")] → no results
|
||||
You: [architect_workflow("Daily X posts at 9 AM using AI to generate tech news content")]
|
||||
You: "I've designed the workflow. I need your X API credentials — go to Agent Builder → Settings → Credentials and add the X API key. Let me know when done."
|
||||
User: "Done"
|
||||
You: [verify_workflow_credentials(wf_id)]
|
||||
You: [test_workflow(wf_id)]
|
||||
You: [deploy_workflow(wf_id, "X Daily Tech Posts", ...)]
|
||||
You: "Done! Your X daily tech posts are live. They'll run every day at 9 AM. I've saved this workflow — next time you say 'post to X', I'll use it."
|
||||
|
||||
**Recurring execution (after setup):**
|
||||
User: "Post to X about the Fed rate cut"
|
||||
You: [search_workflow_templates("post to x action")] → finds "X Quick Post" [wf_abc123]
|
||||
You: [execute_workflow_template("wf_abc123", { text: "Breaking: Fed cuts rates by 0.25%..." }, trigger_phrase: "post to x")]
|
||||
You: "Posted to X. Your existing X post workflow handled it instantly."
|
||||
|
||||
**User asks what you have:**
|
||||
User: "What workflows do you have set up?"
|
||||
You: [describe from workflow memory block]
|
||||
You: "Here's what I have running for you:
|
||||
- **X Daily Posts** — posts every day at 9 AM (ran 14 times)
|
||||
- **X Quick Post** — posts immediately on demand (ran 27 times)
|
||||
- **Daily Email Digest** — emails you a digest at 8 AM (ran 6 times)
|
||||
Say 'run [workflow name]' to trigger any of them."
|
||||
`.trim();
|
||||
|
||||
// ─── Builder ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Build the complete system prompt, injecting live workflow memory.
|
||||
*
|
||||
* Call this at request time (not module load time) so it reflects
|
||||
* the latest state of the workflow store.
|
||||
*
|
||||
* @param basePrompt - Your existing SmallClaw system prompt (appended after)
|
||||
*/
|
||||
export function buildSystemPrompt(basePrompt?: string): string {
|
||||
const workflowContext = getWorkflowContextBlock();
|
||||
|
||||
const parts = [
|
||||
BASE_WORKFLOW_PROMPT,
|
||||
'',
|
||||
workflowContext,
|
||||
];
|
||||
|
||||
if (basePrompt && basePrompt.trim()) {
|
||||
parts.push('', '---', '', basePrompt.trim());
|
||||
}
|
||||
|
||||
return parts.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight version — just the workflow memory block, for injecting
|
||||
* into an existing system prompt without the full instructions.
|
||||
*/
|
||||
export function getWorkflowMemoryOnly(): string {
|
||||
return getWorkflowContextBlock();
|
||||
}
|
||||
|
||||
export { BASE_WORKFLOW_PROMPT };
|
||||
@@ -933,13 +933,8 @@ export function getWorkflowContextBlock(): string {
|
||||
|
||||
const summary = workflowStore.toLLMSummary();
|
||||
return [
|
||||
'---',
|
||||
'## Your Workflow Memory',
|
||||
`You have ${stats.total_workflows} workflow(s) registered (${stats.active_workflows} active).`,
|
||||
'These are ALREADY BUILT AND DEPLOYED. Do not recreate them.',
|
||||
'ALWAYS call search_workflow_templates() before architect_workflow().',
|
||||
`[WORKFLOWS] ${stats.total_workflows} registered (${stats.active_workflows} active). Do not recreate — search first.`,
|
||||
'',
|
||||
summary,
|
||||
'---'
|
||||
].join('\n');
|
||||
}
|
||||
@@ -543,6 +543,10 @@ let lastMainSessionId = 'default';
|
||||
|
||||
let wss: WebSocketServer | undefined;
|
||||
|
||||
// Boot greeting stored here if no WS clients are connected at boot time.
|
||||
// Delivered to the first client that connects within 5 minutes of boot.
|
||||
let _pendingBootGreeting: { text: string; sessionId: string; expiresAt: number } | null = null;
|
||||
|
||||
function broadcastWS(data: object): void {
|
||||
if (!wss) return;
|
||||
const msg = JSON.stringify(data);
|
||||
@@ -847,7 +851,13 @@ hookBus.register('gateway:startup', async ({ workspacePath }) => {
|
||||
setWorkspace(effectiveSessionId, workspacePath);
|
||||
const result = await handleChat(message, effectiveSessionId, sendSSE, undefined, undefined, bootContext);
|
||||
if (result?.text) {
|
||||
broadcastWS({ type: 'boot_greeting', text: result.text, sessionId: effectiveSessionId });
|
||||
const connected = wss && [...wss.clients].some((c: any) => c.readyState === 1);
|
||||
if (connected) {
|
||||
broadcastWS({ type: 'boot_greeting', text: result.text, sessionId: effectiveSessionId });
|
||||
} else {
|
||||
// No clients yet — park the greeting for delivery on next WS connect
|
||||
_pendingBootGreeting = { text: result.text, sessionId: effectiveSessionId, expiresAt: Date.now() + 5 * 60_000 };
|
||||
}
|
||||
}
|
||||
return { text: result.text };
|
||||
});
|
||||
@@ -929,6 +939,7 @@ function detectToolCategories(text: string): Set<string> {
|
||||
const MEMORY = ['remember', 'note that', 'save that', 'write that down', 'dont forget', "don't forget", 'keep in mind', 'update my', 'add to my', 'i prefer', 'i like', 'i hate', 'i use', 'my name', 'call me', 'i work', 'my project', 'my stack'];
|
||||
const PPTX = ['pptx', 'powerpoint', 'presentation', '슬라이드', '발표 자료', '프레젠테이션'];
|
||||
const PUBMED = ['pubmed', 'pmc', 'pmid', 'ncbi', 'medline', 'pubmed_search', 'pubmed_fetch', 'pubmed_fulltext', '논문', 'fulltext', 'full text', '전문 다운', '전문다운', 'abstract', 'mesh'];
|
||||
const SCHOLAR = ['openalex', 'semantic scholar', 'openalex_search', 'semantic_search', 'google scholar', 'semanticscholar', 'paper search', '논문 검색', '학술 검색', '학술논문', 'citation', '인용', 'arxiv', 'preprint'];
|
||||
// 'why' removed — matches casual questions; keep specific error/debug terms
|
||||
const DEBUG = ['error', 'failed', 'how does', 'architecture', 'debug', 'caused', 'broke', 'not working', 'explain how', 'whats wrong', "what's wrong"];
|
||||
const WORKFLOW = ['workflow', 'agent builder', 'architect_workflow', 'deploy workflow', 'workflow template', 'build workflow'];
|
||||
@@ -943,6 +954,15 @@ function detectToolCategories(text: string): Set<string> {
|
||||
if (MEMORY.some(k => lower.includes(k))) cats.add('memory');
|
||||
if (PPTX.some(k => lower.includes(k))) cats.add('pptx');
|
||||
if (PUBMED.some(k => lower.includes(k)) || /PMC\d+|PMID\s*\d+/i.test(text)) cats.add('pubmed');
|
||||
if (SCHOLAR.some(k => lower.includes(k))) cats.add('scholar');
|
||||
const PDF = ['pdf', '.pdf', 'pdf_read', '피디에프', '논문 파일', 'pdf 파일'];
|
||||
const IMAGE_OCR = ['ocr', 'image_read', '이미지 읽기', '이미지 텍스트', '스크린샷 텍스트', 'extract text from image', 'read image'];
|
||||
const PYTHON = ['python', 'python_eval', '파이썬', 'pandas', 'numpy', 'matplotlib', 'scipy', 'csv 분석', 'csv 처리', 'data analysis', '데이터 분석', '수식 계산', 'calculate', 'compute'];
|
||||
const SQLITE = ['sqlite', 'sqlite_query', '.db', 'database query', 'sql query', 'sql 쿼리', '데이터베이스', '쿼리'];
|
||||
if (PDF.some(k => lower.includes(k))) cats.add('pdf');
|
||||
if (IMAGE_OCR.some(k => lower.includes(k))) cats.add('image_ocr');
|
||||
if (PYTHON.some(k => lower.includes(k))) cats.add('python');
|
||||
if (SQLITE.some(k => lower.includes(k))) cats.add('sqlite');
|
||||
const SPAWN = ['논문 리서치', '논문 분석', '논문 요약', '여러 논문', '다수 논문', 'pubmed_researcher', 'spawn_agent'];
|
||||
if (SPAWN.some(k => lower.includes(k))) cats.add('spawn');
|
||||
if (DEBUG.some(k => lower.includes(k))) cats.add('debug');
|
||||
@@ -955,11 +975,11 @@ function detectToolCategories(text: string): Set<string> {
|
||||
const TOOL_BLOCKS: Record<string, string> = {
|
||||
web: `WEB TOOLS: web_search(query) → headlines+snippets. web_fetch(url) → full page text. Use web_search first to get URLs, then web_fetch to read. For Reddit: web_search with site:reddit.com "keyword", then web_fetch post URLs — never open browser for Reddit. IMPORTANT: NEVER use web_fetch or web_search for local URLs (localhost, 127.0.0.1, /api/files/...) — they are NOT web pages. Local files are already accessible in chat via  or [name](/api/files/name.pptx).`,
|
||||
|
||||
browser: `BROWSER TOOLS: browser_open(url) → opens+returns snapshot. browser_snapshot() → refresh elements. browser_click(ref) → click by @ref. browser_fill(ref,text) → fill input. browser_press_key(key) → Enter/Tab/Escape. browser_wait(ms) → wait then snapshot. browser_close() → close tab. Chrome profile is persistent — already logged into sites. IMPORTANT: NEVER use browser_open for local file URLs (/api/files/...) — local images and files are already displayed inline in the chat. Just include  or [file.pptx](/api/files/file.pptx) in your response text. Use browser_open ONLY for external websites. SNAPSHOT RULE: browser_open, browser_fill, browser_wait, and browser_click ALL return a fresh snapshot automatically — do NOT call browser_snapshot immediately after any of them. Only call browser_snapshot when you have NOT received a snapshot recently.`,
|
||||
browser: `BROWSER TOOLS: browser_open(url) → opens+returns snapshot. browser_snapshot() → refresh. browser_click(ref) → click by @ref. browser_fill(ref,text) → fill input. browser_press_key(key) → Enter/Tab/Escape. browser_wait(ms) → wait+snapshot. browser_close() → close tab. Chrome profile is persistent. NEVER use browser_open for local /api/files/ URLs — those are already inline in chat. SNAPSHOT RULE: browser_open/fill/wait/click all return a snapshot automatically — do NOT call browser_snapshot after them; only call it when you haven't received a fresh snapshot recently.`,
|
||||
|
||||
desktop: `DESKTOP TOOLS: desktop_screenshot() → capture+OCR. desktop_find_window(name) → find window. desktop_focus_window(name) → bring to front (use SHORT process name: msedge, chrome, code). desktop_click(x,y,button) → click coords (button: "left" or "right"). desktop_type(text) → type. desktop_press_key(key) → key combo. desktop_drag(x1,y1,x2,y2) → drag. desktop_get_clipboard()/set_clipboard(text). Always screenshot first. Focus window before click/type. Fail twice on focus → stop and report. IMAGE DOWNLOAD: prefer shell("curl -o <path> <url>") or shell("python -c ...urllib...") for downloading images. Only use desktop right-click (desktop_click(x,y,"right") → screenshot → click "Save as") as a last resort when shell download fails due to auth or hotlink protection.`,
|
||||
|
||||
files: `FILE TOOLS: read_file(filename) → contents with line numbers. Always read before editing. replace_lines(filename,start,end,content) → surgical edit. insert_after(filename,line,content) → insert. delete_lines(filename,start,end) → delete. find_replace(filename,find,replace) → exact text swap. create_file(filename,content) → new only (fails if exists). delete_file(filename). RULES: (1) ALWAYS call list_files first to see what already exists before creating any file. (2) If a file already exists, read it first and use replace_lines/edit instead of create_file. (3) Never recreate a file that already exists — read and edit it. (4) read first, surgical edits only, never rewrite whole file for partial changes. FILE LINKS IN RESPONSES: Use /api/files/<relative-path> where relative-path is the path relative to the workspace root. Uploaded files are at /api/files/uploads/filename. Generated files (PPTX etc.) use the path returned by the tool, e.g. /api/files/project_folder/file.pptx. NEVER use sandbox:, file://, /mnt/data/, /mnt/user-data/, or any absolute filesystem path — these URLs are invalid and will fail for the user.`,
|
||||
files: `FILE TOOLS: read_file(filename) → contents+line numbers. replace_lines(f,start,end,content) → surgical edit. insert_after(f,line,content). delete_lines(f,start,end). find_replace(f,find,replace). create_file(f,content) → new only (fails if exists). delete_file(f). list_files(dir?). RULES: list first; read before edit; surgical edits only — never rewrite whole file for small changes. FILE LINKS: /api/files/<path-relative-to-workspace> — e.g. user uploads are at /api/files/uploads/name.jpg. PPTX/tool output files are at /api/files/<project-folder>/<filename>.pptx — NEVER use uploads/ for PPTX. Never use sandbox:/file:///mnt paths.`,
|
||||
|
||||
task: `TASK TOOLS: task_control(action,...) actions: list/get/resume/rerun/pause/delete. start_task(title,prompt) → launch new background task. Check for existing tasks first before creating — never duplicate. Do NOT use read_file to check task state.`,
|
||||
|
||||
@@ -971,15 +991,25 @@ const TOOL_BLOCKS: Record<string, string> = {
|
||||
|
||||
pubmed: `PUBMED TOOLS: pubmed_search(query, max_results?, sort?, min_year?) → search PubMed, returns PMIDs + titles + authors. pubmed_fetch(pmids) → get abstract + metadata for comma-separated PMIDs. pubmed_fulltext(pmcid, format?, save_path?) → download full text or PDF of an open-access PMC article to workspace. RULES: NEVER use web_search or browser_open for PubMed/PMC queries — they return no useful results. NEVER use browser_open on pubmed.ncbi.nlm.nih.gov URLs — call pubmed_fetch or pubmed_fulltext instead. When user gives you a PMC ID (e.g. PMC8765432) and asks for full text/전문: call pubmed_fulltext immediately. For multi-paper research tasks (여러 논문, 다수 논문, N편 검색+요약): use spawn_agent(agentId="pubmed_researcher") instead.`,
|
||||
|
||||
scholar: `SCHOLAR TOOLS: openalex_search(query, max_results?, min_year?, open_access_only?, sort?) → search 200M+ papers across all fields via OpenAlex (no API key needed). semantic_search(query, max_results?, year_from?) → search Semantic Scholar (great for CS/AI, has citation influence metrics; add api_key to config for higher rate limits). Use openalex_search as the default broad search. Use semantic_search for CS/AI papers or when influential citation count matters. NEVER use web_search for academic paper searches — use openalex_search or semantic_search instead.`,
|
||||
|
||||
spawn: `SPAWN TOOL: spawn_agent(agentId, task, context?) → 전문 서브에이전트 실행 후 결과 반환. 사용 가능한 에이전트: "pubmed_researcher" (논문 다건 검색·요약·전문 수집 자율 수행). 단순 1건 조회는 pubmed_search/pubmed_fetch 직접 사용. 다건 리서치(논문 요약, 여러 논문 분석 등)는 spawn_agent 사용.`,
|
||||
|
||||
debug: `DEBUG: If asked about errors or architecture, use read_source(file) to inspect SmallClaw source. SELF.md has architecture overview. Workspace files: IDENTITY.md, SOUL.md, USER.md, TOOLS.md, SELF.md. Read the relevant one before diagnosing.`,
|
||||
|
||||
pptx: `PPTX WORKFLOW — MANDATORY: When the user asks for ANY PPTX / PowerPoint / presentation / slide deck, you MUST use the create_presentation tool. NO EXCEPTIONS. (1) Call create_presentation ONCE with ALL slides in a single spec. The tool auto-creates the project folder from the title. (2) Slide type field is called type — valid values: "title", "content", "section", "image", "blank". Do NOT use layout. (3) For slide images, put image_url directly in the slide spec — the Python engine downloads it automatically into the project folder. Do NOT write Python scripts to download images. Do NOT call shell("curl ...") to download images — before OR after create_presentation. create_presentation handles ALL image downloading internally. (4) If image_url fails or you have a local file, use image_path relative to the project folder (e.g. "uploads/photo.jpg"). image_url takes priority if both are set. (5) Missing images become red "[Image not found]" placeholders — this is expected, not an error. NEVER retry a failed image download, NEVER recreate the presentation, and NEVER call create_presentation again for the same topic. (6) PREFERRED IMAGE SOURCES: Use Unsplash, Pexels, or Pixabay direct image URLs. AVOID Wikipedia / Wikimedia Commons image URLs — they often return 403/400. (7) The .pptx file is saved inside the project folder. IMPORTANT: Always combine ALL slides into a SINGLE create_presentation call. NEVER create multiple presentations for the same topic. After create_presentation returns successfully, the task is DONE. Do not make any follow-up tool calls. (8) To ADD slides to an existing presentation, use edit_presentation(path, spec) — do NOT write Python scripts to edit PPTX files.`,
|
||||
pptx: `PPTX: Use create_presentation for ALL slide deck requests. (1) Single call with ALL slides — never call twice for same topic. type: "title"|"content"|"section"|"image"|"blank". (2) Layout (per slide): "split-right" (default: small title top, text left, image right), "split-left" (image left, text right), "text" (full-width text), "fullscreen" (image fills slide, overlay text). (3) Images: use image_search for auto-download, image_url for direct URL — do NOT use shell/curl. (4) Missing image → gray placeholder, not an error — do not retry. (5) After success: task done, no follow-up calls. (6) Add slides to existing .pptx: edit_presentation(path, spec). DOWNLOAD LINK: use only the URL returned by the tool — NEVER construct /api/files/uploads/... for PPTX, it is WRONG. PPTX is at /api/files/<project-folder>/filename.pptx.`,
|
||||
|
||||
workflow: `WORKFLOW TOOLS: ALWAYS call search_workflow_templates(intent) FIRST before creating anything — reuse existing workflows. If no match: (1) architect_workflow(desc) → (2) verify_workflow_credentials(wf_id) if creds needed → wait for user → (3) test_workflow(wf_id) → (4) deploy_workflow(wf_id, name, ...). Never call architect_workflow if search returns a match. Always relay tool user_message fields verbatim to the user.`,
|
||||
|
||||
photo: `PHOTO SEARCH: search_images(query, count?) → searches Pexels + Unsplash and returns embeddable image URLs. Display results as markdown images in your response. Use when the user asks to find, show, or search for photos or images.`,
|
||||
|
||||
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.`,
|
||||
|
||||
image_ocr: `IMAGE OCR TOOL: image_read(path, lang?) → extract text from an image file via OCR. Supported formats: PNG, JPG, WEBP, BMP, TIFF. lang: "eng" (English, default), "kor" (Korean), "kor+eng" (both). Returns extracted text and confidence score. Useful for screenshots, scanned documents, and diagrams containing text.`,
|
||||
|
||||
python: `PYTHON TOOL: python_eval(code, timeout?, packages?) → execute Python code in the workspace directory. Returns stdout/stderr. timeout default 15s, max 60s. packages: comma-separated pip packages to install if missing (e.g. "numpy,pandas"). Standard library and pre-installed packages available. Use for math, data analysis, CSV/JSON processing, charting (save chart to workspace file).`,
|
||||
|
||||
sqlite: `SQLITE TOOL: sqlite_query(db_path, query, write?, max_rows?) → query a SQLite .db file in the workspace. SELECT queries allowed by default. Set write=true for INSERT/UPDATE/DELETE/CREATE/DROP. Returns formatted table. db_path is relative to workspace or absolute (must be inside workspace).`,
|
||||
};
|
||||
|
||||
// Read memory categories for a specific file (for category-aware injection)
|
||||
@@ -1026,7 +1056,7 @@ function readMemorySnippets(workspacePath: string, categories: string[], fileCac
|
||||
snippets.push(`[${file}:${currentSection}]\n${sectionLines.join('\n')}`);
|
||||
}
|
||||
}
|
||||
return snippets.slice(0, 6).join('\n\n');
|
||||
return snippets.slice(0, 3).join('\n\n');
|
||||
}
|
||||
|
||||
// Map tool categories to memory category keywords
|
||||
@@ -1112,10 +1142,13 @@ async function buildPersonalityContext(
|
||||
// Self.md for debug (cached with fileCache)
|
||||
const self = cats.has('debug') ? loadFile('SELF.md', 600) : '';
|
||||
|
||||
// SOUL only when tool categories are detected — pure conversational turns don't need it
|
||||
const soulContent = cats.size > 0 ? loadFile('SOUL.md', 600) : '';
|
||||
|
||||
const parts = [
|
||||
loadFile('IDENTITY.md', 400) ? `[IDENTITY]\n${loadFile('IDENTITY.md', 400)}` : '',
|
||||
loadFile('USER.md', 500) ? `[USER]\n${loadFile('USER.md', 500)}` : '',
|
||||
loadFile('SOUL.md', 600) ? `[SOUL]\n${loadFile('SOUL.md', 600)}` : '',
|
||||
soulContent ? `[SOUL]\n${soulContent}` : '',
|
||||
intradayNotes ? `[TODAY_NOTES]\n${intradayNotes}` : '',
|
||||
toolBlockParts.length > 0 ? `[TOOLS]\n${toolBlockParts.join('\n\n')}${toolsHint}` : (toolsHint ? `[TOOLS]${toolsHint}` : ''),
|
||||
memorySnippets ? `[RELEVANT_MEMORY]\n${memorySnippets}` : '',
|
||||
@@ -1635,6 +1668,7 @@ function buildTools() {
|
||||
type: 'object',
|
||||
properties: {
|
||||
type: { type: 'string', description: 'Slide type: "title", "content", "section", "image", or "blank"' },
|
||||
layout: { type: 'string', description: 'Column layout: "split-right" (default: title top, text left, image right), "split-left" (title top, image left, text right), "text" (full-width text only), "fullscreen" (image fills slide, title/text overlaid)' },
|
||||
title: { type: 'string', description: 'Slide title text' },
|
||||
subtitle: { type: 'string', description: 'Subtitle (for title slides)' },
|
||||
bullets: { type: 'array', items: { type: 'string' }, description: 'Bullet point texts' },
|
||||
@@ -1679,6 +1713,7 @@ function buildTools() {
|
||||
type: 'object',
|
||||
properties: {
|
||||
type: { type: 'string', description: 'Slide type: "title", "content", "section", "image", or "blank"' },
|
||||
layout: { type: 'string', description: 'Column layout: "split-right" (default: title top, text left, image right), "split-left" (title top, image left, text right), "text" (full-width text only), "fullscreen" (image fills slide, title/text overlaid)' },
|
||||
title: { type: 'string', description: 'Slide title text' },
|
||||
subtitle: { type: 'string', description: 'Subtitle (for title slides)' },
|
||||
bullets: { type: 'array', items: { type: 'string' }, description: 'Bullet point texts' },
|
||||
@@ -1767,6 +1802,100 @@ function buildTools() {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'openalex_search',
|
||||
description: 'Search OpenAlex for academic papers across all fields (200M+ works). Returns title, authors, year, journal, DOI, citation count, and open-access status. No API key required. Use instead of web_search for any academic/scholarly paper search.',
|
||||
parameters: {
|
||||
type: 'object', required: ['query'],
|
||||
properties: {
|
||||
query: { type: 'string', description: 'Search query (title words, author, topic, etc.)' },
|
||||
max_results: { type: 'number', description: 'Number of results (1–10, default 5)' },
|
||||
min_year: { type: 'number', description: 'Minimum publication year (e.g. 2020)' },
|
||||
open_access_only: { type: 'boolean', description: 'Only return open-access papers' },
|
||||
sort: { type: 'string', description: '"relevance" (default) | "cited_by_count" | "publication_date"' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'semantic_search',
|
||||
description: 'Search Semantic Scholar for academic papers. Returns title, authors, abstract, year, citation count, influential citation count, and open-access PDF if available. Excellent for CS, AI, and interdisciplinary research. Use instead of web_search.',
|
||||
parameters: {
|
||||
type: 'object', required: ['query'],
|
||||
properties: {
|
||||
query: { type: 'string', description: 'Search query' },
|
||||
max_results: { type: 'number', description: 'Number of results (1–10, default 5)' },
|
||||
year_from: { type: 'number', description: 'Minimum publication year (e.g. 2020)' },
|
||||
fields: { type: 'string', description: 'Extra fields, e.g. "tldr,references"' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'pdf_read',
|
||||
description: 'Extract text from a PDF file in the workspace. Returns full text, optionally limited to a page range.',
|
||||
parameters: {
|
||||
type: 'object', required: ['path'],
|
||||
properties: {
|
||||
path: { type: 'string', description: 'Path to the PDF file (relative to workspace or absolute)' },
|
||||
page_from: { type: 'number', description: 'First page (1-indexed)' },
|
||||
page_to: { type: 'number', description: 'Last page (inclusive)' },
|
||||
max_chars: { type: 'number', description: 'Max chars to return (default: 20000)' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'image_read',
|
||||
description: 'Extract text from an image file via OCR. Supports PNG, JPG, WEBP, BMP, TIFF. Useful for screenshots, scanned documents, and diagrams.',
|
||||
parameters: {
|
||||
type: 'object', required: ['path'],
|
||||
properties: {
|
||||
path: { type: 'string', description: 'Path to the image file (relative to workspace or absolute)' },
|
||||
lang: { type: 'string', description: 'OCR language: "eng" (default), "kor", "kor+eng"' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'python_eval',
|
||||
description: 'Execute Python code in the workspace directory. Returns stdout/stderr. Useful for math, data analysis, CSV/JSON processing.',
|
||||
parameters: {
|
||||
type: 'object', required: ['code'],
|
||||
properties: {
|
||||
code: { type: 'string', description: 'Python code to execute' },
|
||||
timeout: { type: 'number', description: 'Timeout in seconds (default: 15, max: 60)' },
|
||||
packages: { type: 'string', description: 'Comma-separated pip packages to install if missing' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'sqlite_query',
|
||||
description: 'Query a SQLite .db file in the workspace. SELECT only by default; set write=true for INSERT/UPDATE/DELETE/CREATE.',
|
||||
parameters: {
|
||||
type: 'object', required: ['db_path', 'query'],
|
||||
properties: {
|
||||
db_path: { type: 'string', description: 'Path to the .db file (relative to workspace)' },
|
||||
query: { type: 'string', description: 'SQL query' },
|
||||
write: { type: 'boolean', description: 'Allow write operations (default: false)' },
|
||||
max_rows: { type: 'number', description: 'Max rows for SELECT (default: 100)' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
registerAgentBuilderTools(toolDefs);
|
||||
@@ -2320,6 +2449,41 @@ async function executeTool(name: string, args: any, workspacePath: string, sessi
|
||||
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 '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();
|
||||
@@ -3244,7 +3408,17 @@ function sanitizeFinalReply(
|
||||
prevNorm = norm;
|
||||
}
|
||||
|
||||
return deduped.join('\n\n').trim();
|
||||
let result = deduped.join('\n\n').trim();
|
||||
|
||||
// Strip markdown links to PPTX/PDF files via the wrong /api/files/uploads/... path.
|
||||
// PPTX files are saved in {workspace}/{project-slug}/, not in uploads/.
|
||||
// The tool result already contains the correct link — the AI must not construct a second one.
|
||||
result = result.replace(/\[([^\]]*)\]\(\/api\/files\/uploads\/[^\)]*\.pptx[^\)]*\)/gi, '');
|
||||
result = result.replace(/\[([^\]]*)\]\(\/api\/pptx\/preview\?path=uploads[^\)]*\)/gi, '');
|
||||
// Also strip bare /api/files/uploads/...pptx URLs (unlinked)
|
||||
result = result.replace(/\/api\/files\/uploads\/[^\s)]+\.pptx/gi, '');
|
||||
|
||||
return result.trim();
|
||||
}
|
||||
|
||||
function stripExplicitThinkTags(text: string): { cleaned: string; thinking: string } {
|
||||
@@ -3916,7 +4090,7 @@ async function handleChat(
|
||||
// PPTX tools: when successful, signal completion instead of pushing the goal reminder
|
||||
const goalReminder = ((toolName === 'create_presentation' || toolName === 'edit_presentation')
|
||||
&& !toolResult.error)
|
||||
? '\n\n[TASK COMPLETE: The presentation has been created. Summarize the result and STOP — do not call any more tools.]'
|
||||
? '\n\n[TASK COMPLETE: Presentation created. The download link is already in the tool result above — do NOT write any /api/files/... link in your response (the user already sees the correct link). Confirm completion in 1-2 sentences only. STOP — no more tool calls.]'
|
||||
: `\n\n[GOAL REMINDER: Your task is still: "${message.slice(0, 120)}". Stay focused on this goal only.]`;
|
||||
const isBrowserTool = isBrowserToolName(toolName);
|
||||
const isDesktopTool = isDesktopToolName(toolName);
|
||||
@@ -5002,7 +5176,7 @@ RULES:
|
||||
// PPTX tools: when successful, signal completion instead of pushing the goal reminder
|
||||
const goalReminder = ((toolName === 'create_presentation' || toolName === 'edit_presentation')
|
||||
&& !toolResult.error)
|
||||
? '\n\n[TASK COMPLETE: The presentation has been created. Summarize the result and STOP — do not call any more tools.]'
|
||||
? '\n\n[TASK COMPLETE: Presentation created. The download link is already in the tool result above — do NOT write any /api/files/... link in your response (the user already sees the correct link). Confirm completion in 1-2 sentences only. STOP — no more tool calls.]'
|
||||
: `\n\n[GOAL REMINDER: Your task is still: "${message.slice(0, 120)}". Stay focused on this goal only.]`;
|
||||
const isBrowserTool = isBrowserToolName(toolName);
|
||||
const isDesktopTool = isDesktopToolName(toolName);
|
||||
@@ -5701,7 +5875,6 @@ RULES:
|
||||
finalText = finalText.split(/\n+/)[0].slice(0, 220).trim();
|
||||
}
|
||||
finalText = sanitizeFinalReply(finalText, { preflightReason: preflightReasonForTurn }) || 'Hey! How can I help?';
|
||||
console.log(`[v2] FINAL: ${finalText.slice(0, 150)}`);
|
||||
|
||||
logToDaily(workspacePath, 'SmallClaw', finalText);
|
||||
if (fileOpV2Active) {
|
||||
@@ -6302,7 +6475,7 @@ RULES:
|
||||
// PPTX tools: when successful, signal completion instead of pushing the goal reminder
|
||||
const goalReminder = ((toolName === 'create_presentation' || toolName === 'edit_presentation')
|
||||
&& !toolResult.error)
|
||||
? '\n\n[TASK COMPLETE: The presentation has been created. Summarize the result and STOP — do not call any more tools.]'
|
||||
? '\n\n[TASK COMPLETE: Presentation created. The download link is already in the tool result above — do NOT write any /api/files/... link in your response (the user already sees the correct link). Confirm completion in 1-2 sentences only. STOP — no more tool calls.]'
|
||||
: `\n\n[GOAL REMINDER: Your task is still: "${message.slice(0, 120)}". Stay focused on this goal only.]`;
|
||||
// When orchestrator is active, LLM never sees raw snapshot/browser data.
|
||||
// Full data still flows to advisor via getBrowserAdvisorPacket().
|
||||
@@ -10056,6 +10229,15 @@ wss.on('connection', (ws: WebSocket, req: http.IncomingMessage) => {
|
||||
(ws as any).isAlive = true;
|
||||
ws.on('pong', () => { (ws as any).isAlive = true; });
|
||||
console.log(`[v2] WS connected${user ? ` (user: ${user.username})` : ''}`);
|
||||
|
||||
// Deliver pending boot greeting if it hasn't expired
|
||||
if (_pendingBootGreeting && Date.now() < _pendingBootGreeting.expiresAt) {
|
||||
try {
|
||||
ws.send(JSON.stringify({ type: 'boot_greeting', text: _pendingBootGreeting.text, sessionId: _pendingBootGreeting.sessionId }));
|
||||
} catch {}
|
||||
_pendingBootGreeting = null;
|
||||
}
|
||||
|
||||
ws.on('message', (d) => { try { JSON.parse(d.toString()); } catch {} });
|
||||
ws.on('close', () => console.log(`[v2] WS disconnected${user ? ` (user: ${user.username})` : ''}`));
|
||||
});
|
||||
|
||||
@@ -237,11 +237,20 @@ export class SkillsManager {
|
||||
this.enabledState[id] = true;
|
||||
this.saveEnabledState();
|
||||
|
||||
// Reload
|
||||
this.scanSkills();
|
||||
|
||||
const skill = this.skills.get(id);
|
||||
if (!skill) throw new Error('Skill creation failed');
|
||||
// Insert directly — no need to rescan all skills from disk
|
||||
const stat = fs.statSync(skillMdPath);
|
||||
const skill: Skill = {
|
||||
id,
|
||||
name: data.name,
|
||||
description: data.description || '',
|
||||
emoji: data.emoji || '🧩',
|
||||
version: '1.0.0',
|
||||
enabled: true,
|
||||
instructions: data.instructions,
|
||||
filePath: skillMdPath,
|
||||
createdAt: stat.ctimeMs || Date.now(),
|
||||
};
|
||||
this.skills.set(id, skill);
|
||||
|
||||
console.log(`[Skills] Created: ${data.name} (${id})`);
|
||||
return skill;
|
||||
@@ -297,8 +306,12 @@ export class SkillsManager {
|
||||
const newContent = frontmatterLines.join('\n') + '\n\n' + newBody;
|
||||
fs.writeFileSync(skill.filePath, newContent, 'utf-8');
|
||||
|
||||
this.scanSkills();
|
||||
return this.skills.get(id) || null;
|
||||
// Update in-memory skill directly — no need to rescan all skills from disk
|
||||
if (data.name !== undefined) skill.name = data.name;
|
||||
if (data.description !== undefined) skill.description = data.description;
|
||||
if (data.emoji !== undefined) skill.emoji = data.emoji;
|
||||
if (data.instructions !== undefined) skill.instructions = newBody;
|
||||
return skill;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -177,17 +177,22 @@ function getLocalConfigFilePath(): string {
|
||||
return fsSync.existsSync(projectCfg) ? projectCfg : path.join(os.homedir(), '.smallclaw', 'config.json');
|
||||
}
|
||||
|
||||
let _retrievalModeCache: { mode: RetrievalMode; expiresAt: number } | null = null;
|
||||
|
||||
function getRetrievalMode(): RetrievalMode {
|
||||
const now = Date.now();
|
||||
if (_retrievalModeCache && now < _retrievalModeCache.expiresAt) return _retrievalModeCache.mode;
|
||||
let mode: RetrievalMode = 'standard';
|
||||
try {
|
||||
const p = getLocalConfigFilePath();
|
||||
if (!fsSync.existsSync(p)) return 'standard';
|
||||
const raw = JSON.parse(fsSync.readFileSync(p, 'utf-8'));
|
||||
const mode = String(raw?.agent_policy?.retrieval_mode || 'standard').toLowerCase();
|
||||
if (mode === 'fast' || mode === 'deep') return mode;
|
||||
return 'standard';
|
||||
} catch {
|
||||
return 'standard';
|
||||
}
|
||||
if (fsSync.existsSync(p)) {
|
||||
const raw = JSON.parse(fsSync.readFileSync(p, 'utf-8'));
|
||||
const m = String(raw?.agent_policy?.retrieval_mode || 'standard').toLowerCase();
|
||||
if (m === 'fast' || m === 'deep') mode = m;
|
||||
}
|
||||
} catch {}
|
||||
_retrievalModeCache = { mode, expiresAt: now + 60_000 };
|
||||
return mode;
|
||||
}
|
||||
|
||||
function retrievalMaxLines(mode: RetrievalMode): number {
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { spawn } from 'child_process';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { getConfig } from '../config/config.js';
|
||||
import { ToolResult } from '../types.js';
|
||||
|
||||
function getWorkspacePath(): string {
|
||||
try {
|
||||
return getConfig().getConfig()?.workspace?.path || path.join(process.cwd(), 'workspace');
|
||||
} catch {
|
||||
return path.join(process.cwd(), 'workspace');
|
||||
}
|
||||
}
|
||||
|
||||
const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.tiff', '.tif']);
|
||||
|
||||
// Runs OCR in a child process so the tesseract worker doesn't block the main event loop.
|
||||
const OCR_SCRIPT = `
|
||||
(async () => {
|
||||
const imagePath = process.argv[2];
|
||||
const lang = process.argv[3] || 'eng';
|
||||
try {
|
||||
const mod = await import('tesseract.js');
|
||||
const createWorker = mod?.createWorker || mod?.default?.createWorker;
|
||||
if (typeof createWorker !== 'function') {
|
||||
process.stdout.write(JSON.stringify({ error: 'tesseract not available' }));
|
||||
return;
|
||||
}
|
||||
const worker = await createWorker(lang);
|
||||
if (worker && typeof worker.loadLanguage === 'function') {
|
||||
await worker.loadLanguage(lang);
|
||||
await worker.initialize(lang);
|
||||
}
|
||||
const out = await worker.recognize(imagePath);
|
||||
if (worker && typeof worker.terminate === 'function') await worker.terminate();
|
||||
const text = String(out?.data?.text || '')
|
||||
.replace(/\\r/g, '')
|
||||
.replace(/[ \\t]+\\n/g, '\\n')
|
||||
.replace(/\\n{3,}/g, '\\n\\n')
|
||||
.trim();
|
||||
process.stdout.write(JSON.stringify({ text, confidence: Number(out?.data?.confidence || 0) }));
|
||||
} catch (e) {
|
||||
process.stdout.write(JSON.stringify({ error: String(e?.message || e) }));
|
||||
}
|
||||
})().catch(e => process.stdout.write(JSON.stringify({ error: String(e?.message || e) })));
|
||||
`;
|
||||
|
||||
export const imageReadTool = {
|
||||
name: 'image_read',
|
||||
description: 'Read an image file and extract text via OCR. Returns filename, file size, and extracted text. Useful for screenshots, scanned documents, and diagrams containing text.',
|
||||
schema: {
|
||||
path: 'Path to the image file (PNG, JPG, WEBP, BMP, TIFF) — absolute or relative to workspace',
|
||||
lang: 'OCR language: "eng" (English, default), "kor" (Korean), "kor+eng" (both)',
|
||||
},
|
||||
jsonSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
path: { type: 'string', description: 'Path to the image file' },
|
||||
lang: { type: 'string', description: 'OCR language code: "eng" | "kor" | "kor+eng" (default: "eng")' },
|
||||
},
|
||||
required: ['path'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
execute: async (args: any): Promise<ToolResult> => {
|
||||
const filePath = String(args?.path || '').trim();
|
||||
if (!filePath) return { success: false, error: 'path is required' };
|
||||
|
||||
const workspacePath = getWorkspacePath();
|
||||
const resolved = path.isAbsolute(filePath) ? filePath : path.resolve(workspacePath, filePath);
|
||||
|
||||
if (!fs.existsSync(resolved)) {
|
||||
return { success: false, error: `File not found: ${resolved}` };
|
||||
}
|
||||
const ext = path.extname(resolved).toLowerCase();
|
||||
if (!IMAGE_EXTS.has(ext)) {
|
||||
return { success: false, error: `Unsupported format "${ext}". Supported: ${[...IMAGE_EXTS].join(', ')}` };
|
||||
}
|
||||
|
||||
const stat = fs.statSync(resolved);
|
||||
const sizeMB = (stat.size / 1024 / 1024).toFixed(2);
|
||||
const lang = String(args?.lang || 'eng').replace(/[^a-zA-Z+]/g, '');
|
||||
|
||||
const ocrResult = await new Promise<{ text?: string; confidence?: number; error?: string }>((resolve) => {
|
||||
const child = spawn(process.execPath, ['--input-type=module', '-e', OCR_SCRIPT, resolved, lang], {
|
||||
timeout: 90_000,
|
||||
env: { ...process.env },
|
||||
});
|
||||
let out = '';
|
||||
child.stdout.on('data', (d: Buffer) => { out += d.toString(); });
|
||||
child.on('close', () => {
|
||||
try { resolve(JSON.parse(out || '{}')); } catch { resolve({ error: 'Failed to parse OCR output' }); }
|
||||
});
|
||||
child.on('error', (e: Error) => resolve({ error: e.message }));
|
||||
});
|
||||
|
||||
const lines: string[] = [
|
||||
`File: ${path.basename(resolved)}`,
|
||||
`Size: ${sizeMB} MB | Format: ${ext.slice(1).toUpperCase()} | Lang: ${lang}`,
|
||||
];
|
||||
|
||||
if (ocrResult.error) {
|
||||
lines.push(`OCR Error: ${ocrResult.error}`);
|
||||
return { success: false, error: lines.join('\n') };
|
||||
}
|
||||
|
||||
if (!ocrResult.text) {
|
||||
lines.push('OCR: No text detected in image.');
|
||||
} else {
|
||||
lines.push(`OCR Confidence: ${(ocrResult.confidence ?? 0).toFixed(1)}%`, '');
|
||||
lines.push('[Extracted Text]');
|
||||
lines.push(ocrResult.text.slice(0, 15_000));
|
||||
if (ocrResult.text.length > 15_000) lines.push('[... truncated]');
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
stdout: lines.join('\n'),
|
||||
data: {
|
||||
path: resolved,
|
||||
size_bytes: stat.size,
|
||||
ocr_text: ocrResult.text || '',
|
||||
confidence: ocrResult.confidence ?? 0,
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,86 @@
|
||||
import { execFile } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { getConfig } from '../config/config.js';
|
||||
import { ToolResult } from '../types.js';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
function getWorkspacePath(): string {
|
||||
try {
|
||||
return getConfig().getConfig()?.workspace?.path || path.join(process.cwd(), 'workspace');
|
||||
} catch {
|
||||
return path.join(process.cwd(), 'workspace');
|
||||
}
|
||||
}
|
||||
|
||||
export const pdfReadTool = {
|
||||
name: 'pdf_read',
|
||||
description: 'Extract text from a PDF file. Returns full text content, optionally limited to a page range. Ideal for reading research papers, reports, and documents.',
|
||||
schema: {
|
||||
path: 'Path to the PDF file (absolute, or relative to workspace)',
|
||||
page_from: 'First page to extract, 1-indexed (default: 1)',
|
||||
page_to: 'Last page to extract, inclusive (default: last page)',
|
||||
max_chars: 'Maximum characters to return (default: 20000, max: 100000)',
|
||||
},
|
||||
jsonSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
path: { type: 'string', description: 'Path to the PDF file' },
|
||||
page_from: { type: 'number', description: 'First page (1-indexed)' },
|
||||
page_to: { type: 'number', description: 'Last page (inclusive)' },
|
||||
max_chars: { type: 'number', description: 'Max chars to return (default: 20000)' },
|
||||
},
|
||||
required: ['path'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
execute: async (args: any): Promise<ToolResult> => {
|
||||
const filePath = String(args?.path || '').trim();
|
||||
if (!filePath) return { success: false, error: 'path is required' };
|
||||
|
||||
const workspacePath = getWorkspacePath();
|
||||
const resolved = path.isAbsolute(filePath) ? filePath : path.resolve(workspacePath, filePath);
|
||||
|
||||
if (!fs.existsSync(resolved)) {
|
||||
return { success: false, error: `File not found: ${resolved}` };
|
||||
}
|
||||
if (path.extname(resolved).toLowerCase() !== '.pdf') {
|
||||
return { success: false, error: 'File must have a .pdf extension' };
|
||||
}
|
||||
|
||||
const maxChars = Math.min(100_000, Math.max(1_000, Number(args?.max_chars ?? 20_000)));
|
||||
const cmdArgs: string[] = ['-layout', '-enc', 'UTF-8'];
|
||||
if (args?.page_from) cmdArgs.push('-f', String(Math.max(1, Math.floor(Number(args.page_from)))));
|
||||
if (args?.page_to) cmdArgs.push('-l', String(Math.max(1, Math.floor(Number(args.page_to)))));
|
||||
cmdArgs.push(resolved, '-');
|
||||
|
||||
let stdout: string;
|
||||
try {
|
||||
const result = await execFileAsync('pdftotext', cmdArgs, { maxBuffer: 20 * 1024 * 1024, timeout: 30_000 });
|
||||
stdout = result.stdout;
|
||||
} catch (err: any) {
|
||||
const msg = String(err.message || '');
|
||||
if (msg.toLowerCase().includes('encrypt') || msg.toLowerCase().includes('password')) {
|
||||
return { success: false, error: 'PDF is password-protected or encrypted' };
|
||||
}
|
||||
return { success: false, error: `pdftotext failed: ${msg}` };
|
||||
}
|
||||
|
||||
const text = stdout.replace(/\r/g, '').trim();
|
||||
if (!text) {
|
||||
return { success: false, error: 'No text extracted. The PDF may be scanned (image-based). Try image_read with OCR instead.' };
|
||||
}
|
||||
|
||||
const truncated = text.length > maxChars;
|
||||
const output = truncated ? text.slice(0, maxChars) : text;
|
||||
|
||||
return {
|
||||
success: true,
|
||||
stdout: truncated
|
||||
? `${output}\n\n[Truncated at ${maxChars.toLocaleString()} chars. Full length: ~${text.length.toLocaleString()} chars]`
|
||||
: output,
|
||||
data: { chars: text.length, truncated },
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -415,6 +415,7 @@ export const pptxTool: import('./registry.js').Tool = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
type: { type: 'string', description: 'Slide type: "title", "content", "section", "image", or "blank"' },
|
||||
layout: { type: 'string', description: 'Column layout: "split-right" (default: small title top, text left, image right), "split-left" (small title top, image left, text right), "text" (full-width text only), "fullscreen" (image fills slide, title/text overlaid at bottom)' },
|
||||
title: { type: 'string', description: 'Slide title text' },
|
||||
subtitle: { type: 'string', description: 'Subtitle (for title slides)' },
|
||||
bullets: { type: 'array', items: { type: 'string' }, description: 'Bullet point texts' },
|
||||
@@ -548,6 +549,7 @@ export const editPptxTool: import('./registry.js').Tool = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
type: { type: 'string', description: 'Slide type: "title", "content", "section", "image", or "blank"' },
|
||||
layout: { type: 'string', description: 'Column layout: "split-right" (default: small title top, text left, image right), "split-left" (small title top, image left, text right), "text" (full-width text only), "fullscreen" (image fills slide, title/text overlaid at bottom)' },
|
||||
title: { type: 'string', description: 'Slide title text' },
|
||||
subtitle: { type: 'string', description: 'Subtitle (for title slides)' },
|
||||
bullets: { type: 'array', items: { type: 'string' }, description: 'Bullet point texts' },
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { spawn } from 'child_process';
|
||||
import path from 'path';
|
||||
import { getConfig } from '../config/config.js';
|
||||
import { ToolResult } from '../types.js';
|
||||
|
||||
function getWorkspacePath(): string {
|
||||
try {
|
||||
return getConfig().getConfig()?.workspace?.path || path.join(process.cwd(), 'workspace');
|
||||
} catch {
|
||||
return path.join(process.cwd(), 'workspace');
|
||||
}
|
||||
}
|
||||
|
||||
// Patterns blocked to prevent filesystem damage and network abuse.
|
||||
// os.system / subprocess allow arbitrary shell — not allowed.
|
||||
// socket / urllib / requests would still work for reading; only server-creation
|
||||
// and raw socket misuse would need further restrictions if desired.
|
||||
const BLOCKED: RegExp[] = [
|
||||
/\bos\s*\.\s*system\s*\(/,
|
||||
/\bsubprocess\s*\.\s*(run|Popen|call|check_output|check_call|getoutput|getstatusoutput)\s*\(/,
|
||||
/\bos\s*\.\s*(remove|unlink|rmdir|removedirs|rename|replace|makedirs|mkdir)\s*\(/,
|
||||
/\bshutil\s*\.\s*(rmtree|move|copy2?|copytree)\s*\(/,
|
||||
/\b__import__\s*\(/,
|
||||
/\bimportlib\s*\.\s*import_module\s*\(/,
|
||||
];
|
||||
|
||||
export const pythonEvalTool = {
|
||||
name: 'python_eval',
|
||||
description: 'Execute Python code and return stdout/stderr. Runs in the workspace directory. Useful for math, data analysis, CSV/JSON processing, and scripting tasks. Standard library and installed packages (numpy, pandas, etc.) are available.',
|
||||
schema: {
|
||||
code: 'Python code to execute',
|
||||
timeout: 'Execution timeout in seconds (default: 15, max: 60)',
|
||||
packages: 'Comma-separated pip packages to install if missing before running (e.g. "numpy,pandas")',
|
||||
},
|
||||
jsonSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
code: { type: 'string', description: 'Python code to execute' },
|
||||
timeout: { type: 'number', description: 'Timeout in seconds (default: 15, max: 60)' },
|
||||
packages: { type: 'string', description: 'Comma-separated packages to pip install if missing' },
|
||||
},
|
||||
required: ['code'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
execute: async (args: any): Promise<ToolResult> => {
|
||||
const code = String(args?.code || '').trim();
|
||||
if (!code) return { success: false, error: 'code is required' };
|
||||
|
||||
for (const pattern of BLOCKED) {
|
||||
if (pattern.test(code)) {
|
||||
return { success: false, error: `Blocked: ${pattern.source.replace(/\\b|\\s\*/g, '').replace(/\\\./g, '.')} is not allowed` };
|
||||
}
|
||||
}
|
||||
|
||||
const timeoutSec = Math.min(60, Math.max(1, Number(args?.timeout ?? 15)));
|
||||
const workspacePath = getWorkspacePath();
|
||||
|
||||
if (args?.packages) {
|
||||
const pkgs = String(args.packages).split(',').map((p: string) => p.trim()).filter((p: string) => /^[a-zA-Z0-9_\-\.]+$/.test(p));
|
||||
for (const pkg of pkgs) {
|
||||
await new Promise<void>((resolve) => {
|
||||
const pip = spawn('python3', ['-m', 'pip', 'install', '--quiet', '--user', pkg], {
|
||||
cwd: workspacePath,
|
||||
timeout: 60_000,
|
||||
});
|
||||
pip.on('close', resolve);
|
||||
pip.on('error', resolve);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const result = await new Promise<{ stdout: string; stderr: string; exitCode: number; timedOut: boolean }>((resolve) => {
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
let timedOut = false;
|
||||
let settled = false;
|
||||
|
||||
const child = spawn('python3', ['-u', '-c', code], {
|
||||
cwd: workspacePath,
|
||||
env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1', PYTHONUNBUFFERED: '1' },
|
||||
});
|
||||
|
||||
const killTimer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
child.kill('SIGKILL');
|
||||
}, timeoutSec * 1000);
|
||||
|
||||
child.stdout.on('data', (d: Buffer) => {
|
||||
stdout += d.toString();
|
||||
if (stdout.length > 50_000) child.kill('SIGKILL');
|
||||
});
|
||||
child.stderr.on('data', (d: Buffer) => { stderr += d.toString(); });
|
||||
child.on('close', (code: number | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(killTimer);
|
||||
resolve({ stdout, stderr, exitCode: code ?? -1, timedOut });
|
||||
});
|
||||
child.on('error', (err: NodeJS.ErrnoException) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(killTimer);
|
||||
resolve({ stdout, stderr, exitCode: -1, timedOut });
|
||||
});
|
||||
});
|
||||
|
||||
if (result.timedOut) {
|
||||
return { success: false, error: `Execution timed out after ${timeoutSec}s` };
|
||||
}
|
||||
|
||||
const parts: string[] = [];
|
||||
if (result.stdout.trim()) parts.push(`[stdout]\n${result.stdout.trim().slice(0, 20_000)}`);
|
||||
if (result.stderr.trim()) parts.push(`[stderr]\n${result.stderr.trim().slice(0, 3_000)}`);
|
||||
if (!result.stdout.trim() && !result.stderr.trim()) parts.push('(no output)');
|
||||
parts.push(`[exit ${result.exitCode}]`);
|
||||
|
||||
return {
|
||||
success: result.exitCode === 0,
|
||||
stdout: parts.join('\n\n'),
|
||||
error: result.exitCode !== 0 ? `Python exited with code ${result.exitCode}` : undefined,
|
||||
data: { exit_code: result.exitCode, stdout: result.stdout, stderr: result.stderr },
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -13,6 +13,11 @@ import { proposeRepairTool } from './self-repair.js';
|
||||
import { personaReadTool, personaUpdateTool } from './persona.js';
|
||||
import { pptxTool, editPptxTool } from './pptx.js';
|
||||
import { pubmedSearchTool, pubmedFetchTool, pubmedFulltextTool } from './pubmed.js';
|
||||
import { openalexSearchTool, semanticSearchTool } from './scholar.js';
|
||||
import { pdfReadTool } from './pdf.js';
|
||||
import { imageReadTool } from './image.js';
|
||||
import { pythonEvalTool } from './python.js';
|
||||
import { sqliteTool } from './sqlite.js';
|
||||
|
||||
export interface Tool {
|
||||
name: string;
|
||||
@@ -47,6 +52,10 @@ const TOOL_PROFILE_TOOL_NAMES: Record<Exclude<ToolProfile, 'full'>, ReadonlySet<
|
||||
'apply_patch',
|
||||
'memory_search',
|
||||
'memory_write',
|
||||
'pdf_read',
|
||||
'image_read',
|
||||
'python_eval',
|
||||
'sqlite_query',
|
||||
]),
|
||||
web: new Set([
|
||||
'web_search',
|
||||
@@ -56,6 +65,10 @@ const TOOL_PROFILE_TOOL_NAMES: Record<Exclude<ToolProfile, 'full'>, ReadonlySet<
|
||||
'pubmed_search',
|
||||
'pubmed_fetch',
|
||||
'pubmed_fulltext',
|
||||
'openalex_search',
|
||||
'semantic_search',
|
||||
'pdf_read',
|
||||
'image_read',
|
||||
]),
|
||||
};
|
||||
|
||||
@@ -161,6 +174,14 @@ class ToolRegistry {
|
||||
this.registerSafe(pubmedSearchTool);
|
||||
this.registerSafe(pubmedFetchTool);
|
||||
this.registerSafe(pubmedFulltextTool);
|
||||
// OpenAlex / Semantic Scholar tools
|
||||
this.registerSafe(openalexSearchTool);
|
||||
this.registerSafe(semanticSearchTool);
|
||||
// Document & data tools
|
||||
this.registerSafe(pdfReadTool);
|
||||
this.registerSafe(imageReadTool);
|
||||
this.registerSafe(pythonEvalTool);
|
||||
this.registerSafe(sqliteTool);
|
||||
// Multi-agent spawn tool
|
||||
this.registerSafe(spawnAgentTool);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import { ToolResult } from '../types.js';
|
||||
|
||||
const OPENALEX_BASE = 'https://api.openalex.org';
|
||||
const S2_BASE = 'https://api.semanticscholar.org/graph/v1';
|
||||
const POLITE_EMAIL = 'research@smallclaw.local';
|
||||
|
||||
function getScholarConfig(): { s2Key?: 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'));
|
||||
return { s2Key: data.semantic_scholar?.api_key || '' };
|
||||
}
|
||||
} catch {}
|
||||
return {};
|
||||
}
|
||||
|
||||
async function fetchJson(url: string, headers?: Record<string, string>): Promise<any> {
|
||||
const res = await fetch(url, {
|
||||
signal: AbortSignal.timeout(20_000),
|
||||
headers: { 'Accept': 'application/json', 'User-Agent': 'SmallClaw/1.0', ...headers },
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text().catch(() => '')}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
function reconstructAbstract(inv: Record<string, number[]> | null | undefined): string {
|
||||
if (!inv) return '';
|
||||
const words: Record<number, string> = {};
|
||||
for (const [word, positions] of Object.entries(inv)) {
|
||||
for (const pos of positions) words[pos] = word;
|
||||
}
|
||||
return Object.keys(words)
|
||||
.sort((a, b) => Number(a) - Number(b))
|
||||
.map(k => words[Number(k)])
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
// ── openalex_search ───────────────────────────────────────────────────────────
|
||||
|
||||
export const openalexSearchTool = {
|
||||
name: 'openalex_search',
|
||||
description: 'Search OpenAlex for academic papers across all fields (200M+ works). Returns title, authors, year, journal, DOI, citation count, and open-access status. No API key required.',
|
||||
schema: {
|
||||
query: 'Search query (title words, author, topic, etc.)',
|
||||
max_results: 'Number of results (1-10, default 5)',
|
||||
min_year: 'Filter to papers from this year onwards (e.g. 2020)',
|
||||
open_access_only:'Return only open-access papers (true/false)',
|
||||
sort: 'Sort order: "relevance" (default), "cited_by_count", "publication_date"',
|
||||
},
|
||||
jsonSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: 'Search query' },
|
||||
max_results: { type: 'number', description: 'Number of results (1–10, default 5)' },
|
||||
min_year: { type: 'number', description: 'Minimum publication year (e.g. 2020)' },
|
||||
open_access_only: { type: 'boolean', description: 'Only return open-access papers' },
|
||||
sort: { type: 'string', description: '"relevance" | "cited_by_count" | "publication_date"' },
|
||||
},
|
||||
required: ['query'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
execute: async (args: any): Promise<ToolResult> => {
|
||||
const query = String(args?.query || '').trim();
|
||||
if (!query) return { success: false, error: 'query is required' };
|
||||
|
||||
const limit = Math.min(Math.max(1, Number(args?.max_results ?? 5)), 10);
|
||||
const sortMap: Record<string, string> = {
|
||||
relevance: 'relevance_score:desc',
|
||||
cited_by_count: 'cited_by_count:desc',
|
||||
publication_date: 'publication_date:desc',
|
||||
};
|
||||
const sortKey = sortMap[String(args?.sort || 'relevance')] ?? 'relevance_score';
|
||||
|
||||
const filters: string[] = ['type:article'];
|
||||
if (args?.min_year) filters.push(`publication_year:${args.min_year}-`);
|
||||
if (args?.open_access_only) filters.push('is_oa:true');
|
||||
|
||||
const params = new URLSearchParams({
|
||||
search: query,
|
||||
'per-page': String(limit),
|
||||
sort: sortKey,
|
||||
filter: filters.join(','),
|
||||
select: 'id,doi,display_name,publication_year,cited_by_count,open_access,authorships,abstract_inverted_index,primary_location',
|
||||
mailto: POLITE_EMAIL,
|
||||
});
|
||||
|
||||
let data: any;
|
||||
try {
|
||||
data = await fetchJson(`${OPENALEX_BASE}/works?${params}`);
|
||||
} catch (err: any) {
|
||||
return { success: false, error: `OpenAlex request failed: ${err.message}` };
|
||||
}
|
||||
|
||||
const results: any[] = data?.results ?? [];
|
||||
if (!results.length) {
|
||||
return { success: false, error: `No results found on OpenAlex for: "${query}"` };
|
||||
}
|
||||
|
||||
const lines: string[] = [`OpenAlex results for: "${query}" (${data?.meta?.count ?? '?'} total)\n`];
|
||||
for (let i = 0; i < results.length; i++) {
|
||||
const r = results[i];
|
||||
const title = r.display_name || '(no title)';
|
||||
const year = r.publication_year ?? '';
|
||||
const doi = r.doi ? String(r.doi).replace('https://doi.org/', '') : '';
|
||||
const journal = r.primary_location?.source?.display_name || '';
|
||||
const authors = (r.authorships || [])
|
||||
.slice(0, 6)
|
||||
.map((a: any) => a?.author?.display_name || '')
|
||||
.filter(Boolean)
|
||||
.join(', ') + ((r.authorships || []).length > 6 ? ' et al.' : '');
|
||||
const citations = r.cited_by_count ?? 0;
|
||||
const isOa = r.open_access?.is_oa ?? false;
|
||||
const oaUrl = r.open_access?.oa_url || '';
|
||||
const abstract = reconstructAbstract(r.abstract_inverted_index).slice(0, 400);
|
||||
|
||||
lines.push(`[${i + 1}] ${title}`);
|
||||
if (authors) lines.push(` Authors: ${authors}`);
|
||||
lines.push(` Year: ${year}${journal ? ` | Journal: ${journal}` : ''}${citations ? ` | Citations: ${citations}` : ''}`);
|
||||
if (doi) lines.push(` DOI: https://doi.org/${doi}`);
|
||||
if (isOa) lines.push(` Open Access: YES${oaUrl ? ` — ${oaUrl}` : ''}`);
|
||||
if (abstract) lines.push(` Abstract: ${abstract}${abstract.length >= 400 ? '...' : ''}`);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
stdout: lines.join('\n'),
|
||||
data: { query, count: data?.meta?.count, results: results.map((r: any) => ({
|
||||
title: r.display_name,
|
||||
year: r.publication_year,
|
||||
doi: r.doi ? String(r.doi).replace('https://doi.org/', '') : '',
|
||||
citations: r.cited_by_count,
|
||||
is_oa: r.open_access?.is_oa,
|
||||
oa_url: r.open_access?.oa_url,
|
||||
authors: (r.authorships || []).slice(0, 6).map((a: any) => a?.author?.display_name).filter(Boolean),
|
||||
})) },
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
// ── semantic_search ───────────────────────────────────────────────────────────
|
||||
|
||||
export const semanticSearchTool = {
|
||||
name: 'semantic_search',
|
||||
description: 'Search Semantic Scholar for academic papers. Returns title, authors, abstract, year, citation count, influential citation count, and open-access PDF link if available. Recommended for CS, AI, and interdisciplinary research.',
|
||||
schema: {
|
||||
query: 'Search query',
|
||||
max_results: 'Number of results (1-10, default 5)',
|
||||
year_from: 'Filter to papers from this year onwards (e.g. 2020)',
|
||||
fields: 'Extra fields to request (comma-separated), e.g. "references,tldr"',
|
||||
},
|
||||
jsonSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: 'Search query' },
|
||||
max_results: { type: 'number', description: 'Number of results (1–10, default 5)' },
|
||||
year_from: { type: 'number', description: 'Minimum publication year (e.g. 2020)' },
|
||||
fields: { type: 'string', description: 'Extra fields, e.g. "tldr,references"' },
|
||||
},
|
||||
required: ['query'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
execute: async (args: any): Promise<ToolResult> => {
|
||||
const query = String(args?.query || '').trim();
|
||||
if (!query) return { success: false, error: 'query is required' };
|
||||
|
||||
const limit = Math.min(Math.max(1, Number(args?.max_results ?? 5)), 10);
|
||||
const cfg = getScholarConfig();
|
||||
const headers: Record<string, string> = {};
|
||||
if (cfg.s2Key) headers['x-api-key'] = cfg.s2Key;
|
||||
|
||||
const baseFields = 'title,authors,abstract,year,externalIds,openAccessPdf,citationCount,influentialCitationCount';
|
||||
const extraFields = args?.fields ? `,${String(args.fields).replace(/\s/g, '')}` : '';
|
||||
const fields = baseFields + extraFields;
|
||||
|
||||
const params = new URLSearchParams({
|
||||
query,
|
||||
limit: String(limit),
|
||||
fields,
|
||||
});
|
||||
if (args?.year_from) params.set('year', `${args.year_from}-`);
|
||||
|
||||
let data: any;
|
||||
try {
|
||||
data = await fetchJson(`${S2_BASE}/paper/search?${params}`, headers);
|
||||
} catch (err: any) {
|
||||
const msg = String(err.message || '');
|
||||
if (msg.includes('429') || msg.toLowerCase().includes('too many')) {
|
||||
return {
|
||||
success: false,
|
||||
error: [
|
||||
'Semantic Scholar rate limit exceeded.',
|
||||
'Free tier allows ~1 req/sec. To get a higher limit:',
|
||||
' 1. Apply at https://www.semanticscholar.org/product/api#api-key-form',
|
||||
' 2. Add your key to .smallclaw/config.json: { "semantic_scholar": { "api_key": "<key>" } }',
|
||||
'Alternatively, try openalex_search which has no rate limits.',
|
||||
].join('\n'),
|
||||
};
|
||||
}
|
||||
return { success: false, error: `Semantic Scholar request failed: ${msg}` };
|
||||
}
|
||||
|
||||
const papers: any[] = data?.data ?? [];
|
||||
if (!papers.length) {
|
||||
return { success: false, error: `No results found on Semantic Scholar for: "${query}"` };
|
||||
}
|
||||
|
||||
const lines: string[] = [`Semantic Scholar results for: "${query}" (${data?.total ?? '?'} total)\n`];
|
||||
for (let i = 0; i < papers.length; i++) {
|
||||
const p = papers[i];
|
||||
const title = p.title || '(no title)';
|
||||
const year = p.year ?? '';
|
||||
const authors = (p.authors || []).slice(0, 6).map((a: any) => a.name || '').filter(Boolean).join(', ')
|
||||
+ ((p.authors || []).length > 6 ? ' et al.' : '');
|
||||
const doi = p.externalIds?.DOI || '';
|
||||
const pmid = p.externalIds?.PubMed || '';
|
||||
const oaPdf = p.openAccessPdf?.url || '';
|
||||
const abstract = String(p.abstract || '').slice(0, 400);
|
||||
const cites = p.citationCount ?? 0;
|
||||
const inflCites= p.influentialCitationCount ?? 0;
|
||||
const tldr = p.tldr?.text ? `TL;DR: ${p.tldr.text}` : '';
|
||||
|
||||
lines.push(`[${i + 1}] ${title}`);
|
||||
if (authors) lines.push(` Authors: ${authors}`);
|
||||
lines.push(` Year: ${year}${cites ? ` | Citations: ${cites}` : ''}${inflCites ? ` | Influential: ${inflCites}` : ''}`);
|
||||
if (doi) lines.push(` DOI: https://doi.org/${doi}`);
|
||||
if (pmid) lines.push(` PMID: ${pmid}`);
|
||||
if (oaPdf) lines.push(` Open Access PDF: ${oaPdf}`);
|
||||
if (tldr) lines.push(` ${tldr}`);
|
||||
else if (abstract) lines.push(` Abstract: ${abstract}${abstract.length >= 400 ? '...' : ''}`);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
stdout: lines.join('\n'),
|
||||
data: { query, total: data?.total, papers: papers.map((p: any) => ({
|
||||
title: p.title,
|
||||
year: p.year,
|
||||
doi: p.externalIds?.DOI,
|
||||
pmid: p.externalIds?.PubMed,
|
||||
citations: p.citationCount,
|
||||
inf_citations: p.influentialCitationCount,
|
||||
oa_pdf: p.openAccessPdf?.url,
|
||||
authors: (p.authors || []).slice(0, 6).map((a: any) => a.name),
|
||||
})) },
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -20,6 +20,19 @@ function isPathInsideDir(base: string, target: string): boolean {
|
||||
return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
|
||||
}
|
||||
|
||||
// Compiled once at module load — never recreated per execution
|
||||
const DANGEROUS_COMMANDS: Array<[RegExp, string]> = [
|
||||
[/rm\s+-rf\s+\//, 'rm -rf /'],
|
||||
[/mkfs/, 'filesystem format'],
|
||||
[/dd\s+if=/, 'disk write'],
|
||||
[/>\s*\/dev\//, 'device write'],
|
||||
[/\bsudo\b/, 'privilege escalation'],
|
||||
[/\bsu\s/, 'user switch'],
|
||||
[/chmod\s+777/, 'world-writable permission'],
|
||||
[/\bcurl\b.*\|.*\bbash\b/, 'curl-pipe-bash'],
|
||||
[/\bwget\b.*-O.*\s*-\s*\|/, 'wget-pipe'],
|
||||
];
|
||||
|
||||
// ── Absolute-path detector ────────────────────────────────────────────────────
|
||||
// Catches commands that contain absolute paths outside the workspace even when
|
||||
// cwd is inside it — e.g. `type C:\Windows\System32\config\SAM`
|
||||
@@ -80,20 +93,7 @@ export async function executeShell(args: ShellToolArgs): Promise<ToolResult> {
|
||||
}
|
||||
}
|
||||
|
||||
// Hardcoded dangerous command patterns
|
||||
const dangerousCommands: Array<[RegExp, string]> = [
|
||||
[/rm\s+-rf\s+\//, 'rm -rf /'],
|
||||
[/mkfs/, 'filesystem format'],
|
||||
[/dd\s+if=/, 'disk write'],
|
||||
[/>\s*\/dev\//, 'device write'],
|
||||
[/\bsudo\b/, 'privilege escalation'],
|
||||
[/\bsu\s/, 'user switch'],
|
||||
[/chmod\s+777/, 'world-writable permission'],
|
||||
[/\bcurl\b.*\|.*\bbash\b/, 'curl-pipe-bash'],
|
||||
[/\bwget\b.*-O.*\s*-\s*\|/, 'wget-pipe'],
|
||||
];
|
||||
|
||||
for (const [pattern, label] of dangerousCommands) {
|
||||
for (const [pattern, label] of DANGEROUS_COMMANDS) {
|
||||
if (pattern.test(args.command)) {
|
||||
log.warn('[shell] Blocked dangerous command:', label);
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { getConfig } from '../config/config.js';
|
||||
import { ToolResult } from '../types.js';
|
||||
|
||||
function getWorkspacePath(): string {
|
||||
try {
|
||||
return getConfig().getConfig()?.workspace?.path || path.join(process.cwd(), 'workspace');
|
||||
} catch {
|
||||
return path.join(process.cwd(), 'workspace');
|
||||
}
|
||||
}
|
||||
|
||||
function isPathInsideDir(base: string, target: string): boolean {
|
||||
const resolvedBase = path.resolve(base);
|
||||
const resolvedTarget = path.resolve(target);
|
||||
if (resolvedBase === resolvedTarget) return true;
|
||||
const rel = path.relative(resolvedBase, resolvedTarget);
|
||||
return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
|
||||
}
|
||||
|
||||
function formatTable(columns: string[], rows: any[][]): string {
|
||||
if (!rows.length) return '(no rows)';
|
||||
const widths = columns.map((c, i) =>
|
||||
Math.min(40, Math.max(c.length, ...rows.map(r => String(r[i] ?? '').length)))
|
||||
);
|
||||
const pad = (s: string, w: number) => String(s ?? '').padEnd(w).slice(0, w);
|
||||
const sep = widths.map(w => '-'.repeat(w)).join('-+-');
|
||||
const header = columns.map((c, i) => pad(c, widths[i])).join(' | ');
|
||||
return [header, sep, ...rows.map(r => r.map((cell, i) => pad(String(cell ?? ''), widths[i])).join(' | '))].join('\n');
|
||||
}
|
||||
|
||||
const WRITE_RE = /^\s*(INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|REPLACE|TRUNCATE|ATTACH|DETACH)\s/i;
|
||||
|
||||
export const sqliteTool = {
|
||||
name: 'sqlite_query',
|
||||
description: 'Execute SQL queries on a SQLite database file inside the workspace. SELECT queries are allowed by default. Set write=true to run INSERT/UPDATE/DELETE/CREATE/DROP.',
|
||||
schema: {
|
||||
db_path: 'Path to the .db file (relative to workspace, or absolute)',
|
||||
query: 'SQL query to execute',
|
||||
write: 'Allow write queries: INSERT/UPDATE/DELETE/CREATE/DROP (default: false)',
|
||||
max_rows: 'Maximum rows to return for SELECT (default: 100)',
|
||||
},
|
||||
jsonSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
db_path: { type: 'string', description: 'Path to the SQLite database file' },
|
||||
query: { type: 'string', description: 'SQL query' },
|
||||
write: { type: 'boolean', description: 'Allow write operations (default: false)' },
|
||||
max_rows: { type: 'number', description: 'Max rows returned for SELECT (default: 100)' },
|
||||
},
|
||||
required: ['db_path', 'query'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
execute: async (args: any): Promise<ToolResult> => {
|
||||
const dbPath = String(args?.db_path || '').trim();
|
||||
const query = String(args?.query || '').trim();
|
||||
if (!dbPath) return { success: false, error: 'db_path is required' };
|
||||
if (!query) return { success: false, error: 'query is required' };
|
||||
|
||||
const workspacePath = getWorkspacePath();
|
||||
const resolved = path.isAbsolute(dbPath) ? dbPath : path.resolve(workspacePath, dbPath);
|
||||
|
||||
if (!isPathInsideDir(workspacePath, resolved)) {
|
||||
return { success: false, error: 'db_path must be inside the workspace directory' };
|
||||
}
|
||||
|
||||
const allowWrite = Boolean(args?.write);
|
||||
const isWrite = WRITE_RE.test(query);
|
||||
if (isWrite && !allowWrite) {
|
||||
return { success: false, error: 'Write query requires write=true. Set write=true to allow INSERT/UPDATE/DELETE/CREATE.' };
|
||||
}
|
||||
|
||||
let Database: any;
|
||||
try {
|
||||
const mod = await import('better-sqlite3');
|
||||
Database = mod.default ?? mod;
|
||||
} catch (err: any) {
|
||||
return { success: false, error: `better-sqlite3 unavailable: ${err.message}` };
|
||||
}
|
||||
|
||||
let db: any;
|
||||
try {
|
||||
db = new Database(resolved, { readonly: !allowWrite });
|
||||
} catch (err: any) {
|
||||
return { success: false, error: `Cannot open database: ${err.message}` };
|
||||
}
|
||||
|
||||
try {
|
||||
const maxRows = Math.min(1_000, Math.max(1, Number(args?.max_rows ?? 100)));
|
||||
const stmt = db.prepare(query);
|
||||
|
||||
if (isWrite || !query.trim().toUpperCase().startsWith('SELECT')) {
|
||||
const info = stmt.run();
|
||||
return {
|
||||
success: true,
|
||||
stdout: `OK\nRows affected: ${info.changes} | Last insert rowid: ${info.lastInsertRowid}`,
|
||||
data: { changes: info.changes, lastInsertRowid: info.lastInsertRowid },
|
||||
};
|
||||
}
|
||||
|
||||
const rows: any[] = stmt.all().slice(0, maxRows);
|
||||
if (!rows.length) return { success: true, stdout: '(no rows returned)', data: { rows: [] } };
|
||||
|
||||
const columns = Object.keys(rows[0]);
|
||||
const table = formatTable(columns, rows.map((r: any) => columns.map(c => r[c])));
|
||||
|
||||
let total = rows.length;
|
||||
try {
|
||||
// Wrap query in subquery to get total row count
|
||||
const countRow = db.prepare(`SELECT COUNT(*) AS _cnt FROM (${query})`).get();
|
||||
total = Number(countRow?._cnt ?? rows.length);
|
||||
} catch {}
|
||||
|
||||
const note = rows.length < total ? `\n\n[Showing ${rows.length} of ${total} rows. Use max_rows to increase limit.]` : '';
|
||||
return {
|
||||
success: true,
|
||||
stdout: table + note,
|
||||
data: { columns, row_count: rows.length, total, rows },
|
||||
};
|
||||
} catch (err: any) {
|
||||
return { success: false, error: `Query error: ${err.message}` };
|
||||
} finally {
|
||||
try { db.close(); } catch {}
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -4,6 +4,24 @@ import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
type SearchResultItem = { title: string; url: string; snippet: string };
|
||||
|
||||
// Shared HTML → plain text stripper used by fetchCleanArticle and executeWebFetch.
|
||||
// preserveStructure=true keeps paragraph breaks (\s{3,}→\n\n); false collapses all whitespace.
|
||||
function stripHtml(html: string, preserveStructure = false): string {
|
||||
const text = html
|
||||
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
|
||||
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
|
||||
.replace(/<nav[\s\S]*?<\/nav>/gi, ' ')
|
||||
.replace(/<footer[\s\S]*?<\/footer>/gi, ' ')
|
||||
.replace(/<header[\s\S]*?<\/header>/gi, ' ')
|
||||
.replace(/<!--[\s\S]*?-->/g, ' ')
|
||||
.replace(/<[^>]+>/g, ' ')
|
||||
.replace(/ /g, ' ').replace(/&/g, '&').replace(/</g, '<')
|
||||
.replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'");
|
||||
return preserveStructure
|
||||
? text.replace(/\s{3,}/g, '\n\n').trim()
|
||||
: text.replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
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 };
|
||||
@@ -252,20 +270,7 @@ async function fetchCleanArticle(url: string, maxChars = 5000): Promise<string>
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const ct = String(res.headers.get('content-type') || '');
|
||||
if (!/text|html|json/i.test(ct)) throw new Error(`Unsupported content-type: ${ct}`);
|
||||
const html = await res.text();
|
||||
const text = html
|
||||
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
|
||||
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
|
||||
.replace(/<nav[\s\S]*?<\/nav>/gi, ' ')
|
||||
.replace(/<footer[\s\S]*?<\/footer>/gi, ' ')
|
||||
.replace(/<header[\s\S]*?<\/header>/gi, ' ')
|
||||
.replace(/<!--[\s\S]*?-->/g, ' ')
|
||||
.replace(/<[^>]+>/g, ' ')
|
||||
.replace(/ /g, ' ').replace(/&/g, '&').replace(/</g, '<')
|
||||
.replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'")
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
return text.slice(0, maxChars);
|
||||
return stripHtml(await res.text()).slice(0, maxChars);
|
||||
}
|
||||
|
||||
function extractEvidenceSentences(query: string, text: string, max = 4): string[] {
|
||||
@@ -459,30 +464,26 @@ function rankResults(query: string, results: SearchResultItem[]) {
|
||||
}
|
||||
|
||||
// ── Load optional API keys from ~/.smallclaw/config.json ─────────────────────
|
||||
function getSearchConfig(): {
|
||||
preferred: 'tavily' | 'google' | 'brave' | 'ddg';
|
||||
tavilyKey?: string;
|
||||
googleKey?: string;
|
||||
googleCx?: string;
|
||||
braveKey?: string;
|
||||
} {
|
||||
// Cached with 5-minute TTL so config changes are picked up without restart.
|
||||
type SearchConfig = { preferred: 'tavily' | 'google' | 'brave' | 'ddg'; tavilyKey?: string; googleKey?: string; googleCx?: string; braveKey?: string };
|
||||
let _searchConfigCache: { value: SearchConfig; expiresAt: number } | null = null;
|
||||
|
||||
function getSearchConfig(): SearchConfig {
|
||||
const now = Date.now();
|
||||
if (_searchConfigCache && now < _searchConfigCache.expiresAt) return _searchConfigCache.value;
|
||||
let value: SearchConfig = { preferred: 'ddg' };
|
||||
try {
|
||||
const projectCfg = path.join(process.cwd(), '.smallclaw', 'config.json');
|
||||
const cfg = fs.existsSync(projectCfg) ? projectCfg : path.join(os.homedir(), '.smallclaw', 'config.json');
|
||||
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'].includes(preferredRaw) ? preferredRaw : 'ddg') as 'tavily' | 'google' | 'brave' | 'ddg';
|
||||
return {
|
||||
preferred,
|
||||
tavilyKey: data.search?.tavily_api_key,
|
||||
googleKey: data.search?.google_api_key,
|
||||
googleCx: data.search?.google_cx,
|
||||
braveKey: data.search?.brave_api_key,
|
||||
};
|
||||
const preferred = (['tavily', 'google', 'brave', 'ddg'].includes(preferredRaw) ? preferredRaw : 'ddg') as SearchConfig['preferred'];
|
||||
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 };
|
||||
}
|
||||
} catch {}
|
||||
return { preferred: 'ddg' };
|
||||
_searchConfigCache = { value, expiresAt: now + 5 * 60_000 };
|
||||
return value;
|
||||
}
|
||||
// ── Google Custom Search API ─────────────────────────────────────────────---
|
||||
async function searchGoogle(query: string, limit: number, apiKey: string, cx: string): Promise<ToolResult> {
|
||||
@@ -833,19 +834,7 @@ export async function executeWebFetch(args: { url: string; max_chars?: number })
|
||||
return { success: false, error: `Non-text content-type: ${contentType}` };
|
||||
}
|
||||
|
||||
const html = await res.text();
|
||||
let text = html
|
||||
.replace(/<script[\s\S]*?<\/script>/gi, '')
|
||||
.replace(/<style[\s\S]*?<\/style>/gi, '')
|
||||
.replace(/<nav[\s\S]*?<\/nav>/gi, '')
|
||||
.replace(/<footer[\s\S]*?<\/footer>/gi, '')
|
||||
.replace(/<header[\s\S]*?<\/header>/gi, '')
|
||||
.replace(/<!--[\s\S]*?-->/g, '')
|
||||
.replace(/<[^>]+>/g, ' ')
|
||||
.replace(/ /g, ' ').replace(/&/g, '&').replace(/</g, '<')
|
||||
.replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'")
|
||||
.replace(/\s{3,}/g, '\n\n')
|
||||
.trim();
|
||||
let text = stripHtml(await res.text(), true);
|
||||
|
||||
if (text.length > maxChars) text = text.slice(0, maxChars) + '\n\n[...truncated]';
|
||||
|
||||
|
||||
@@ -5623,10 +5623,11 @@ function connectWS() {
|
||||
log(`Job created: ${msg.jobId}`, 'info');
|
||||
}
|
||||
if (msg.type === 'boot_greeting') {
|
||||
// Inject boot greeting as first message in current fresh session
|
||||
// Show boot greeting in current session regardless of existing history
|
||||
const bootSess = chatSessions.find(s => s.id === activeChatSessionId);
|
||||
if (bootSess && (!bootSess.history || bootSess.history.length === 0)) {
|
||||
bootSess.history = [{ role: 'assistant', content: msg.text }];
|
||||
if (bootSess) {
|
||||
if (!bootSess.history) bootSess.history = [];
|
||||
bootSess.history.push({ role: 'assistant', content: msg.text });
|
||||
bootSess.updatedAt = Date.now();
|
||||
saveChatSessions();
|
||||
syncActiveChat();
|
||||
|
||||
@@ -1,182 +0,0 @@
|
||||
# SmallClaw 작업 내용 요약
|
||||
작성일: 2026-04-30 (최종 업데이트: 2026-04-30 — staged attachments 추가)
|
||||
|
||||
---
|
||||
|
||||
## 1. 멀티유저 워크스페이스 격리
|
||||
|
||||
### `src/config/config.ts`
|
||||
- `getUserWorkspace(username)`: 실제 유저별 경로 반환
|
||||
- `legacy` / 빈 값 → 글로벌 워크스페이스
|
||||
- 일반 유저 → `.smallclaw/users/<username>/workspace`
|
||||
- `ensureUserWorkspace(username)`: 유저 워크스페이스 초기화
|
||||
- 디렉토리 없으면 생성
|
||||
- 글로벌 워크스페이스에서 `SOUL.md`, `USER.md` 등 부트스트랩 파일 복사
|
||||
- `memory/`, `reports/`, `drafts/` 서브디렉토리 자동 생성
|
||||
|
||||
### `src/gateway/session.ts`
|
||||
- `Session` 인터페이스에 `username?: string` 추가
|
||||
- `SESSION_DIR` 상수 → `getSessionDir(username?)` 함수로 교체
|
||||
- `getSession(id, username?)`: 유저 디렉토리 우선 탐색, 글로벌 폴백
|
||||
- `saveSession` / `flushSession`: `session.username` 기반 경로 사용
|
||||
- `cleanupSessions`: 글로벌 + 전체 유저 디렉토리 스캔
|
||||
- `migrateGlobalSessionsToUser(username)` 추가:
|
||||
- 글로벌 세션을 유저 디렉토리로 복사
|
||||
- username/workspace 주입
|
||||
- `.migrated-from-global` 마커로 중복 실행 방지
|
||||
|
||||
### `src/gateway/server-v2.ts`
|
||||
- `/api/chat` 핸들러: 요청마다 `ensureUserWorkspace` + `setWorkspace` 호출
|
||||
- `/api/clear-history`, `/api/agent/session/:id`: username 기반 세션 조회
|
||||
- 서버 시작 시 전체 유저 자동 마이그레이션 실행
|
||||
|
||||
---
|
||||
|
||||
## 2. 로그인 / 로그아웃
|
||||
|
||||
### `web-ui/index.html`
|
||||
- 헤더 상태바에 유저 정보 필 + 로그아웃 버튼 추가
|
||||
- `checkAuth()`: 로그인 상태 확인 후 유저명 표시
|
||||
- `logout()`: `/api/auth/logout` POST → `login.html` 리다이렉트
|
||||
|
||||
---
|
||||
|
||||
## 3. UI 한글화
|
||||
|
||||
### `web-ui/index.html`
|
||||
- 웰컴 화면: "로컬 모델과 직접 대화하세요..."
|
||||
- 사이드바: 세션 / 🧩 스킬 / + 새 채팅 / 편집
|
||||
- 헤더 모드 버튼: 채팅 / 작업 / 일정
|
||||
- 채팅 영역: 모드 / 컨텍스트 / 대기 중인 프롬프트 / 전송 / 새로고침 등
|
||||
- 백그라운드 작업 / 일정 뷰 전체
|
||||
- 스킬 모달, 시스템 통계 패널, 에이전트 설정 등
|
||||
|
||||
### `web-ui/login.html`
|
||||
- 로그인 화면 전체 한글화
|
||||
- 에러 메시지, 플레이스홀더, 버튼 텍스트 모두 포함
|
||||
|
||||
### `src/gateway/boot.ts`
|
||||
- 부팅 인사말 프롬프트 → 한국어로 2-3문장 요약 지시
|
||||
|
||||
### `src/gateway/server-v2.ts`
|
||||
- 부팅 요약 지시에 `in Korean` 추가
|
||||
|
||||
### `workspace/SOUL.md` (글로벌 + cherry + papa 유저)
|
||||
- `Language`: "항상 한국어로 응답, 사용자가 다른 언어로 쓸 때만 전환"
|
||||
|
||||
---
|
||||
|
||||
## 4. 파일 첨부 기능 확장
|
||||
|
||||
### `web-ui/index.html`
|
||||
- 이미지 업로드 버튼 → 파일 첨부 버튼 (📎) 으로 변경
|
||||
- `accept` 속성 확장: `image/*, .pdf, .txt, .md, .csv, .xlsx, .xls, .docx, .pptx`
|
||||
- `handleFileUpload()` 함수 추가 — 파일 타입별 처리:
|
||||
|
||||
| 파일 타입 | 처리 방식 |
|
||||
|-----------|-----------|
|
||||
| 이미지 | 서버 업로드 → `![이미지]()` 마크다운 삽입 |
|
||||
| txt / md | FileReader로 직접 읽어 코드 블록 삽입 |
|
||||
| CSV | FileReader → ` ```csv ``` ` 블록 삽입 |
|
||||
| Excel (.xlsx/.xls) | SheetJS 동적 로드 → 마크다운 테이블 변환 삽입 |
|
||||
| **PDF** | PDF.js 텍스트 추출 + 서버 업로드 → 내용 직접 채팅에 삽입 |
|
||||
| 기타 (docx/pptx 등) | 서버 업로드 → 파일 링크 삽입 |
|
||||
|
||||
- `insertIntoChatInput(text)`: 채팅 입력창 삽입 헬퍼 (이미지 전용)
|
||||
- `loadSheetJS(cb)`: SheetJS CDN 동적 로드 (xlsx 0.18.5, 최초 1회)
|
||||
- `loadPdfJs(cb)`: PDF.js CDN 동적 로드 (pdf.js 3.11.174, 최초 1회)
|
||||
- PDF 링크 렌더링: 📄 새 탭 열기 + ◄ 미리보기(iframe) + ↙ 저장
|
||||
|
||||
### `src/gateway/server-v2.ts`
|
||||
- `/api/upload/file` 엔드포인트 추가:
|
||||
- `multipart/form-data`의 `file` 필드 파싱
|
||||
- 최대 50MB 제한
|
||||
- 유저 워크스페이스 `uploads/` 에 저장
|
||||
- `{ success, path, url, filename, size, type }` 반환
|
||||
- `/api/files` 파일 서빙:
|
||||
- `res.sendFile` → `fs.createReadStream().pipe(res)` 로 교체 (Express 5 호환)
|
||||
- `Content-Length` 헤더 명시
|
||||
- PDF/txt/csv/md → `Content-Disposition: inline` (브라우저 뷰어)
|
||||
- xlsx/docx/pptx/zip 등 → `Content-Disposition: attachment` (다운로드)
|
||||
|
||||
---
|
||||
|
||||
## 5. 파일 스테이징 (채팅창 첨부 카드 표시)
|
||||
|
||||
### `web-ui/index.html`
|
||||
|
||||
**배경**: 파일을 채팅 입력창 텍스트에 바로 삽입하면 너무 길어지고 PDF 미리보기가 불가능.
|
||||
→ 전송 전까지 카드 형태로 별도 영역에 표시하는 "staged attachments" 패턴으로 변경.
|
||||
|
||||
**HTML 추가**:
|
||||
```html
|
||||
<!-- .chat-input-row 위쪽 -->
|
||||
<div id="staged-attachments" style="display:none;flex-wrap:wrap;gap:8px;padding:8px 12px 0;border-top:1px solid var(--line)"></div>
|
||||
```
|
||||
|
||||
**JS 함수**:
|
||||
|
||||
| 함수 | 역할 |
|
||||
|------|------|
|
||||
| `stageAttachment(name, url, content, type)` | 첨부 배열에 추가 후 카드 렌더링 |
|
||||
| `removeStagedAttachment(id)` | ✕ 버튼으로 개별 제거 |
|
||||
| `clearStagedAttachments()` | 전송 후 전체 초기화 |
|
||||
| `renderStagedAttachments()` | `#staged-attachments` 에 카드 HTML 생성 |
|
||||
| `toggleStagedPdfPreview(id)` | PDF 카드 내 iframe 펼치기/접기 |
|
||||
|
||||
**카드 표시 형태**:
|
||||
- txt/md → 📝 + 파일명 + ✕
|
||||
- csv → 📋 + 파일명 + ✕
|
||||
- xlsx/xls → 📊 + 파일명 + ✕
|
||||
- pdf → 📄 + 파일명 + **미리보기** 버튼(iframe 토글) + ✕
|
||||
|
||||
**파일 타입별 처리 변경** (`handleFileUpload`):
|
||||
|
||||
| 파일 타입 | 이전 | 이후 |
|
||||
|-----------|------|------|
|
||||
| txt/md | `insertIntoChatInput(코드블록)` | `stageAttachment(..., 'text')` |
|
||||
| csv | `insertIntoChatInput(csv블록)` | `stageAttachment(..., 'csv')` |
|
||||
| xlsx/xls | `insertIntoChatInput(마크다운테이블)` | `stageAttachment(..., 'excel')` |
|
||||
| pdf | `insertIntoChatInput(추출텍스트)` | `stageAttachment(name, url, content, 'pdf')` |
|
||||
| 이미지 | `insertIntoChatInput('')` | 동일 (카드 없이 유지) |
|
||||
|
||||
**sendChat 패치**:
|
||||
```javascript
|
||||
// 스테이징된 첨부파일 내용을 메시지에 포함
|
||||
let fullMessage = message;
|
||||
if (stagedAttachments.length > 0) {
|
||||
const attachParts = stagedAttachments.map(a =>
|
||||
a.content || ('[첨부: ' + a.name + '](' + (a.url||'') + ')')
|
||||
);
|
||||
fullMessage = attachParts.join('\n\n') + (message ? '\n\n' + message : '');
|
||||
clearStagedAttachments();
|
||||
}
|
||||
chatHistory.push({ role: 'user', content: fullMessage });
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 변경된 파일 목록
|
||||
|
||||
| 파일 | 변경 내용 |
|
||||
|------|-----------|
|
||||
| `src/config/config.ts` | getUserWorkspace, ensureUserWorkspace |
|
||||
| `src/gateway/session.ts` | 멀티유저 세션 격리, 마이그레이션 |
|
||||
| `src/gateway/server-v2.ts` | 채팅 핸들러, 파일 업로드/서빙, 부팅 |
|
||||
| `src/gateway/boot.ts` | 부팅 인사말 한글 지시 |
|
||||
| `web-ui/index.html` | UI 한글화, 파일 첨부, PDF 미리보기, 스테이징 카드 |
|
||||
| `web-ui/login.html` | 로그인 화면 한글화 |
|
||||
| `workspace/SOUL.md` | 기본 언어 한국어 설정 |
|
||||
| `.smallclaw/users/*/workspace/SOUL.md` | 동일 |
|
||||
|
||||
---
|
||||
|
||||
## 주요 트러블슈팅 이력
|
||||
|
||||
| 증상 | 원인 | 해결 |
|
||||
|------|------|------|
|
||||
| Edit 툴이 큰 파일을 자름 | Edit 툴의 대형 파일 덮어쓰기 버그 | Python 바이트 단위 꼬리 복구 스크립트 |
|
||||
| PDF 500 에러 | Express 5에서 `res.sendFile` 미동작 | `fs.createReadStream().pipe(res)` 교체 |
|
||||
| PDF가 다운로드됨 | `Content-Disposition: attachment` | `inlineExts` 목록 추가 → `inline` |
|
||||
| AI가 PDF 내용 못 읽음 | 업로드 경로 ≠ AI 워크스페이스 경로 | 클라이언트 PDF.js 텍스트 추출 후 메시지에 직접 삽입 |
|
||||
| 채팅 입력창이 파일 내용으로 가득 참 | 텍스트 직접 삽입 방식 | staged attachments 카드 패턴으로 전환 |
|
||||