feat: kakao_send_message 에이전트 도구화 + 멀티기기 메인챗 세션 동기화 + 터미널 전체화면

- src/tools/kakao.ts: 기존 KakaoNotify를 kakao_send_message 도구로 노출, 코드에디터에서는 차단
- app.js/server-v2.ts: 메인챗 마지막 활성 세션을 서버에 기록해 새 기기에서 열 때 자동 이어보기
- code.html/code.js/styles.css: 서버 터미널 패널 전체화면 토글 (Esc로 종료)
- companion.py: .vbs 자동시작 시 cwd가 System32로 잡히는 문제 방지 위해 홈 디렉터리로 고정
- papa 워크스페이스: 우즈베크어 학습 진행상황, 서버 이름(지서버/클로서버) 메모 갱신

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5 committed 2026-07-05 14:41:57 +09:00
1 parent ce1a99b723
commit 186dc4cb23
11 files changed
+193 -4

No files matched your search

@@ -1,5 +1,11 @@
{
"known": [],
"known": [
"Salom",
"Xayr",
"Ha",
"Yoʻq",
"Iltimos"
],
"lessonsDone": {
"1": true,
"2": true,
@@ -14,6 +14,8 @@
- Name: (not yet assigned)
- "I am SmallClaw, your local AI assistant."
- The local LLM server (HP Z840) is officially named "지서버" (Z-Server). [2026-07-03] [2026-07-03]
- Web server name: 클로서버 (Claw-Server). [2026-07-03] [2026-07-03]
## limits
- Small model — best at structured tasks.
- Limited context — rely on workspace files.
@@ -14,4 +14,10 @@
- Gemma 4 released March 2026 (12B in June 2026), native audio/video multimodal. [2026-06-21]
## hardware_history
- RTX 5060 launched May 19, 2025 ($299); RTX 5060 Ti launched April 16, 2025 ($429 for 16GB). [2026-06-24]
- RTX 5060 launched May 19, 2025 ($299); RTX 5060 Ti launched April 16, 2025 ($429 for 16GB). [2026-06-24]
## projects
- Local LLM Server: HP Z840, 2x RTX 5060 Ti, 64GB RAM, Crucial P310 1TB NVMe. [2026-07-03] [2026-07-03]
- Local LLM Server: HP Z840, 2x RTX 5060 Ti (16GB each, total 32GB VRAM), 64GB RAM, Crucial P310 1TB NVMe. [2026-07-03] [2026-07-03]
- Local LLM Server name: 지서버 (Z-Server). [2026-07-03] [2026-07-03]
- Web server name: 클로서버 (Claw-Server). [2026-07-03] [2026-07-03]
+33 -2
View File
@@ -1290,6 +1290,8 @@ function detectToolCategories(text: string, sessionId?: string): Set<string> {
if (WEATHER.some(k => lower.includes(k))) cats.add('weather');
const EMAIL = ['email', '이메일', '메일', 'inbox', '받은편지함', '받은 메일', '메일함', '메일 보내', '메일 읽', '메일 검색', '메일 삭제', 'email_list', 'email_send', 'email_read', 'email_search', 'email_delete'];
if (EMAIL.some(k => lower.includes(k))) cats.add('email');
const KAKAO = ['카카오톡', '카톡', 'kakao', 'kakaotalk', 'kakao_send_message'];
if (KAKAO.some(k => lower.includes(k))) cats.add('kakao');
const OLLAMA_SEARCH = ['ollama 검색', 'ollama search', 'ollama_web', 'ollama web', '올라마 검색', '올라마로 검색', '올라마 웹'];
if (OLLAMA_SEARCH.some(k => lower.includes(k))) cats.add('ollama_web');
return cats;
@@ -1398,6 +1400,8 @@ RULES: 현재날씨/예보 → weather_search. 대기질(국내) → weather_air
email: `EMAIL TOOLS (멀티 계정 지원): 모든 도구에 account? 파라미터로 계정 ID 지정 가능. 미지정 시 모든 계정 순회. 사용자별 설정에 등록된 계정만 접근 가능. email_list(folder?,limit?,account?) → 받은편지함 목록 (uid·제목·발신자·날짜·읽음여부). email_read(uid,folder?,account?) → 메일 전문 조회. email_send(to,subject,body,cc?,account?) → 메일 발송. email_search(query?,from?,subject?,since?,before?,folder?,limit?,account?) → 메일 검색. email_delete(uid,folder?,account?) → 메일 삭제. RULES: 이메일 관련 요청에는 항상 email_* 도구 사용 — web_search 사용 금지. email_list 결과는 계정별로 그룹핑된 원본 포맷(📬/📭 마커, 번호, UID 포함)을 그대로 사용자에게 전달할 것 — 자의적 재포맷팅 금지.`,
kakao: `KAKAO TOOL: kakao_send_message(text) → 서버에 등록된 카카오 계정으로 "나에게 보내기" 전송 (텍스트/링크만 가능, 이미지 첨부 불가). RULES: 카카오톡 전송을 언급하기 전에 반드시 이 도구를 호출해서 결과를 확인할 것 — 도구 호출 없이 "보내드리겠습니다"라고만 답하지 말 것. 도구가 실패(카카오 미연동 등)하면 실패 사유를 그대로 사용자에게 전달할 것.`,
pdf: `PDF TOOLS: pdf_read(path, page_from?, page_to?, max_chars?) → extract text from a PDF. pdf_extract_images(path, mode?, out_dir?, page_from?, page_to?, dpi?) → extract images/figures from a PDF. mode: "figures" (PREFERRED — OpenCV auto-crop figures/tables, best for academic PDFs), "images" (embedded rasters — raw, often full-page scans), "both" = images+figures (default). out_dir: save to specific folder (e.g. PPTX project folder). Returns workspace-relative paths. NOTE: "pages" mode no longer exists — use "figures" instead. pdf_extract_tables(path, format?, engine?, page_from?, page_to?) → extract tables as structured data. format: "markdown" (default) | "csv" | "json". engine: "auto" (PyMuPDF first, pdfplumber fallback) | "pymupdf" | "pdfplumber". For scanned PDFs use pdf_extract_images mode "figures" 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.`,
@@ -2407,6 +2411,19 @@ function buildTools() {
},
},
},
{
type: 'function',
function: {
name: 'kakao_send_message',
description: '카카오톡 "나에게 보내기"로 텍스트/링크를 본인 카카오톡에 전송. 차트 링크·요약·알림을 카카오톡으로 보내달라는 요청 시 사용. 이미지 첨부는 지원하지 않음 — URL은 텍스트에 그대로 포함해서 보낼 것.',
parameters: {
type: 'object', required: ['text'],
properties: {
text: { type: 'string', description: '보낼 메시지 (URL 포함 가능, 2000자 초과 시 자동 분할)' },
},
},
},
},
{
type: 'function',
function: {
@@ -5042,7 +5059,7 @@ async function handleCodeChat(
const timeStr = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
// Tools available in the editor: everything except browser/messaging/timer/etc.
const codeAiBlockedTools = new Set(['start_task', 'task_control', 'write_note', 'browser_open', 'browser_snapshot', 'browser_click', 'browser_fill', 'browser_press_key', 'browser_wait', 'browser_close', 'image_search', 'image_url', 'image_edit', 'image_info', 'image_read', 'weather_search', 'start_timer', 'send_message', 'send_telegram', 'create_presentation', 'edit_presentation', 'spawn_subagent', 'schedule_job', 'parse_schedule_pattern']);
const codeAiBlockedTools = new Set(['start_task', 'task_control', 'write_note', 'browser_open', 'browser_snapshot', 'browser_click', 'browser_fill', 'browser_press_key', 'browser_wait', 'browser_close', 'image_search', 'image_url', 'image_edit', 'image_info', 'image_read', 'weather_search', 'start_timer', 'send_message', 'send_telegram', 'kakao_send_message', 'create_presentation', 'edit_presentation', 'spawn_subagent', 'schedule_job', 'parse_schedule_pattern']);
// useTools:false → plan/ask phase; pass empty tools so the model generates text only
const tools = useTools ? buildTools().filter((t: any) => !codeAiBlockedTools.has(String(t?.function?.name || ''))) : [];
@@ -5243,7 +5260,7 @@ async function handleChat(
// coder_delete_lines, coder_list_files, shell, python_eval, and web_search to directly
// inspect and fix code. Blocked tools are ones that don't make sense in
// an editor context (browser automation, messaging, timers, presentations, etc.)
const codeAiBlockedTools = new Set(['start_task', 'task_control', 'write_note', 'browser_open', 'browser_snapshot', 'browser_click', 'browser_fill', 'browser_press_key', 'browser_wait', 'browser_close', 'image_search', 'image_url', 'image_edit', 'image_info', 'image_read', 'weather_search', 'start_timer', 'send_message', 'send_telegram', 'create_presentation', 'edit_presentation', 'spawn_subagent', 'schedule_job', 'parse_schedule_pattern']);
const codeAiBlockedTools = new Set(['start_task', 'task_control', 'write_note', 'browser_open', 'browser_snapshot', 'browser_click', 'browser_fill', 'browser_press_key', 'browser_wait', 'browser_close', 'image_search', 'image_url', 'image_edit', 'image_info', 'image_read', 'weather_search', 'start_timer', 'send_message', 'send_telegram', 'kakao_send_message', 'create_presentation', 'edit_presentation', 'spawn_subagent', 'schedule_job', 'parse_schedule_pattern']);
const weatherToolNames = new Set(['weather_search', 'weather_airpollution', 'weather_openmeteo', 'weather_kma', 'weather_airkorea', 'weather_nasa_power', 'weather_era5', 'weather_cds', 'weather_cmip6']);
const legalToolNames = new Set(['korean_law_search', 'korean_law_fetch', 'us_case_search']);
const pptxToolNames = new Set(['create_presentation', 'edit_presentation']);
@@ -8775,7 +8792,15 @@ const activeSessions = new Map<string, SessionInfo>();
const SESSIONS_FILE = path.join(CONFIG_DIR_PATH, 'active-sessions.json');
const SESSION_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
function pruneExpiredSessions(): void {
const now = Date.now();
for (const [token, info] of activeSessions) {
if (now - (info.createdAt || 0) >= SESSION_MAX_AGE_MS) activeSessions.delete(token);
}
}
function saveActiveSessions(): void {
pruneExpiredSessions();
try {
const obj: Record<string, SessionInfo> = {};
for (const [k, v] of activeSessions) obj[k] = v;
@@ -12773,6 +12798,11 @@ app.get('/api/agent/session/:id', (req, res) => {
});
});
// Per-app session ids (see appSessionsPath above) live in the same sessions/ dir
// as main-chat sessions but belong to their own app UI — keep them out of the
// main chat sidebar.
const APP_SESSION_PREFIXES = ['iv_', 'dt_', 'lw_', 'mn_', 'ac_', 'wt_', 'music_'];
// GET /api/chat/sessions — list current user's sessions from disk
app.get('/api/chat/sessions', async (req, res) => {
const user = (req as any).user;
@@ -12796,6 +12826,7 @@ app.get('/api/chat/sessions', async (req, res) => {
// skip code-editor sessions
const id = file.replace(/\.json$/, '');
if (id.startsWith('code_ai_') || id.startsWith('proj-')) continue;
if (APP_SESSION_PREFIXES.some(p => id.startsWith(p))) continue;
const firstUser = String(userMsgs[0]?.content || '').replace(/!\[.*?\]\(.*?\)/g, '').trim();
const title = firstUser.slice(0, 60) || 'New chat';
summaries.push({
+61
View File
@@ -0,0 +1,61 @@
import { ToolResult } from '../types.js';
import { getConfig } from '../config/config.js';
import { getVault } from '../security/vault.js';
import { KakaoNotify } from '../gateway/kakao-notify.js';
function getKakaoNotify(): KakaoNotify | null {
const cm = getConfig();
const cfg = cm.getConfig() as any;
const raw = cfg.channels?.kakao || {};
const vault = getVault(cm.getConfigDir());
const appKey = cm.resolveSecret(raw.appKey) || vault.get('channels.kakao.appKey', 'kakao:init')?.expose() || '';
const refreshToken = cm.resolveSecret(raw.refreshToken) || vault.get('channels.kakao.refreshToken', 'kakao:init')?.expose() || '';
if (!appKey || !refreshToken) return null;
return new KakaoNotify({
appKey,
refreshToken,
onTokenRefreshed: (newToken) => vault.set('channels.kakao.refreshToken', newToken, 'kakao:token'),
});
}
// ── kakao_send_message ──────────────────────────────────────────────────────
export const kakaoSendTool = {
name: 'kakao_send_message',
description: '카카오톡 "나에게 보내기"로 텍스트를 본인 카카오톡에 전송합니다. 차트 링크, 요약, 알림 등을 카카오톡으로 보내달라는 요청에 사용. 이미지 첨부는 지원하지 않으므로 링크/텍스트로만 전송합니다.',
schema: {
text: '보낼 메시지 내용 (URL은 텍스트에 그대로 포함)',
},
jsonSchema: {
type: 'object',
properties: {
text: { type: 'string', description: '보낼 메시지 (URL 포함 가능, 최대 2000자 단위로 자동 분할)' },
},
required: ['text'],
additionalProperties: false,
},
execute: async (args: any): Promise<ToolResult> => {
const text = String(args?.text || '').trim();
if (!text) return { success: false, error: 'text(보낼 내용)가 필요합니다.' };
const notifier = getKakaoNotify();
if (!notifier) {
return {
success: false,
error: '카카오 연동이 설정되어 있지 않습니다. 서버 설정에서 /api/kakao/auth/start 로 먼저 카카오 로그인을 완료하세요.',
};
}
try {
await notifier.send(text);
return {
success: true,
stdout: `✅ 카카오톡(나에게 보내기)으로 전송 완료.\n내용: ${text.slice(0, 200)}${text.length > 200 ? '...' : ''}`,
};
} catch (err: any) {
return { success: false, error: `카카오톡 전송 실패: ${err.message}` };
}
},
};
+3
View File
@@ -22,6 +22,7 @@ import { pythonEvalTool } from './python.js';
import { sqliteTool } from './sqlite.js';
import { weatherSearchTool, weatherAirPollutionTool, weatherOpenMeteoTool, weatherKmaTool, weatherAirKoreaTool, weatherNasaPowerTool, weatherEra5Tool, weatherCdsTool, weatherCmip6Tool } from './weather.js';
import { emailListTool, emailReadTool, emailSendTool, emailSearchTool, emailDeleteTool } from './email.js';
import { kakaoSendTool } from './kakao.js';
import { koreanLawSearchTool, koreanLawFetchTool, usCaseSearchTool } from './legal.js';
import { excelReadTool, excelWriteTool } from './excel.js';
@@ -222,6 +223,8 @@ class ToolRegistry {
this.registerSafe(emailSendTool);
this.registerSafe(emailSearchTool);
this.registerSafe(emailDeleteTool);
// Kakao push (나에게 보내기)
this.registerSafe(kakaoSendTool);
// Legal research tools
this.registerSafe(koreanLawSearchTool);
this.registerSafe(koreanLawFetchTool);
+40
View File
@@ -386,7 +386,9 @@ function loadChatSessions() {
chatSessions = [];
}
if (!Array.isArray(chatSessions)) chatSessions = [];
let isFreshDevice = false;
if (chatSessions.length === 0) {
isFreshDevice = true;
const id = crypto?.randomUUID?.() || ('chat_' + Math.random().toString(36).slice(2));
chatSessions.push({ id, title: 'New chat', history: [], processLog: [], createdAt: Date.now(), updatedAt: Date.now() });
activeChatSessionId = id;
@@ -400,6 +402,41 @@ function loadChatSessions() {
syncActiveChat();
// 서버 세션 목록과 비교해 누락된 세션을 사이드바에 추가
syncServerSessions();
// 새 기기에서 처음 열었다면, 다른 기기에서 이어가던 대화로 자동 복귀
if (isFreshDevice) resumeMainSessionPointer();
}
// 메인챗의 "마지막 활성 세션"을 서버에 기록 — 다른 기기에서 새로 열었을 때 이어보기용
function updateMainSessionPointer(id) {
if (!id) return;
api('/api/user/app-sessions', { method: 'PUT', body: JSON.stringify({ appKey: 'main', sessionId: id }) }).catch(() => {});
}
async function resumeMainSessionPointer() {
try {
const d = await api('/api/user/app-sessions');
const ptr = d && d.main;
if (!ptr) { updateMainSessionPointer(activeChatSessionId); return; } // 최초 로그인: 이 세션을 기준점으로 등록
if (ptr === activeChatSessionId) return;
const cur = chatSessions.find(s => s.id === activeChatSessionId);
if (cur && cur.history && cur.history.length > 0) return; // 이미 이 기기에서 대화가 시작됐으면 건드리지 않음
const hd = await api('/api/chat/sessions/' + encodeURIComponent(ptr));
if (!hd || !hd.success || !Array.isArray(hd.history) || hd.history.length === 0) return;
// 비어있던 자리표시자 세션은 제거하고 포인터가 가리키는 세션으로 전환
chatSessions = chatSessions.filter(s => s.id !== activeChatSessionId);
let existing = chatSessions.find(s => s.id === ptr);
if (!existing) {
existing = { id: ptr, title: makeSessionTitle(hd.history), history: hd.history, processLog: [], createdAt: hd.createdAt || Date.now(), updatedAt: hd.lastActiveAt || Date.now() };
chatSessions.unshift(existing);
} else {
existing.history = hd.history;
delete existing.serverOnly;
}
activeChatSessionId = ptr;
setAgentSessionId(ptr);
saveChatSessions();
syncActiveChat();
} catch { /* 서버 미응답 시 무시 */ }
}
async function syncServerSessions() {
@@ -470,6 +507,7 @@ function newChatSession() {
activeChatSessionId = id;
setAgentSessionId(id);
syncActiveChat();
updateMainSessionPointer(id);
}
function toggleSessionsEditMode() {
@@ -497,6 +535,7 @@ function deleteChatSession(id, ev) {
saveChatSessions();
syncActiveChat();
updateMainSessionPointer(activeChatSessionId);
// 서버 세션 파일도 삭제 (재로드 시 재등장 방지)
api(`/api/chat/sessions/${id}`, { method: 'DELETE' }).catch(() => {});
}
@@ -504,6 +543,7 @@ function deleteChatSession(id, ev) {
function openSession(id) {
activeChatSessionId = id;
setAgentSessionId(id);
updateMainSessionPointer(id);
const sess = chatSessions.find(s => s.id === id);
if (sess && sess.serverOnly && sess.history.length === 0) {
// 서버에서 history 로드 후 렌더
+1
View File
@@ -542,6 +542,7 @@
<button onclick="addCodeTermShell()" title="서버 터미널 탭 추가" style="background:none;border:none;color:#6b7280;cursor:pointer;font-size:11px;padding:0 6px;line-height:1;flex-shrink:0;font-family:'IBM Plex Mono',monospace">☁️</button>
<button id="code-term-ai-error-btn" onclick="_sendActiveTermErrorToAI()" title="터미널 출력을 AI에게 전송" style="background:#1a3a28;color:#22c55e;border:1px solid #2a5a3a;border-radius:4px;padding:1px 7px;font-size:10px;font-weight:700;cursor:pointer;flex-shrink:0;margin-right:2px">🤖</button>
<button onclick="codeTermKill()" title="실행 중단 (Ctrl+C)" style="background:none;border:none;color:#f87171;cursor:pointer;font-size:13px;padding:0 6px;line-height:1;flex-shrink:0">⏹</button>
<button id="code-term-fullscreen-btn" onclick="toggleCodeTermFullscreen()" title="전체화면" style="background:none;border:none;color:#8b8b8b;cursor:pointer;font-size:13px;padding:0 6px;line-height:1;flex-shrink:0">⛶</button>
<button onclick="toggleCodeTerminal()" title="닫기" style="background:none;border:none;color:#3d6b4f;cursor:pointer;font-size:14px;padding:0 8px;line-height:1;flex-shrink:0">&times;</button>
</div>
<div id="code-term-container" style="flex:1;min-height:0;position:relative;overflow:hidden"></div>
+21
View File
@@ -775,6 +775,10 @@ function createXtermShell(container, shellId) {
toggleCodeTerminal();
return false;
}
if (e.type === 'keydown' && e.key === 'Escape' && codeTermFullscreen) {
toggleCodeTermFullscreen();
return false;
}
return true;
});
const inst = { term, fitAddon, ptyReady: false };
@@ -893,6 +897,23 @@ function toggleCodeTerminal() {
}
if (monacoEditor) setTimeout(() => monacoEditor.layout(), 60);
}
let codeTermFullscreen = false;
function toggleCodeTermFullscreen() {
const panel = document.getElementById('code-term-panel');
const btn = document.getElementById('code-term-fullscreen-btn');
if (!panel) return;
codeTermFullscreen = !codeTermFullscreen;
panel.classList.toggle('code-term-fullscreen', codeTermFullscreen);
if (btn) { btn.classList.toggle('active', codeTermFullscreen); btn.title = codeTermFullscreen ? '전체화면 종료 (Esc)' : '전체화면'; }
setTimeout(() => {
const s = codeTermShells.find(s => s.id === activeCodeTermShellId);
if (s?.fitAddon) s.fitAddon.fit();
if (s?.term) s.term.focus();
}, 60);
}
document.addEventListener('keydown', e => {
if (e.key === 'Escape' && codeTermFullscreen) toggleCodeTermFullscreen();
});
// ── Browser Preview Panel ────────────────────────────────────────────────────
let codePreviewOpen = false;
function toggleCodePreview() {
+8
View File
@@ -37,6 +37,14 @@ HOST = '127.0.0.1'
PORT = 9000
IS_WINDOWS = sys.platform == 'win32'
# 자동시작(.vbs)으로 실행되면 프로세스 cwd가 System32로 잡히는 경우가 있어
# (wscript.exe 기본 작업 폴더 상속), 터미널이 엉뚱한 위치에서 열리는 걸 막기
# 위해 항상 홈 디렉터리에서 시작하도록 고정한다.
try:
os.chdir(os.path.expanduser('~'))
except Exception:
pass
def _refresh_env():
"""시작 후 변경된 환경 변수(PATH 등)를 레지스트리에서 실시간으로 반영한다."""
+10
View File
@@ -2536,6 +2536,16 @@
display: flex;
flex-direction: column;
}
#code-term-panel.code-term-fullscreen {
position: fixed !important;
inset: 0 !important;
width: 100vw !important;
height: 100vh !important;
z-index: 2000;
border-top: none !important;
}
#code-term-panel.code-term-fullscreen #code-term-drag { display: none; }
#code-term-fullscreen-btn.active { color: #8b5cf6 !important; }
.code-ai-header {
display: flex; align-items: center; justify-content: space-between;
padding: 9px 12px; border-bottom: 1px solid #1a3a28;