v4.3.22: 도구 선택 로직을 tool-scope.ts로 분리 + 테스트 17개 — 버그 3개 발견
handleChat()에서 도구 선택 로직(145줄)을 순수 모듈로 추출. 이 로직은 2,959줄
함수 안의 클로저라 테스트가 불가능했고, 게이트를 확인하려면 게이트웨이를 띄우고
실제 채팅을 보내 SSE의 토큰 수를 읽는 수밖에 없었음.
- src/gateway/chat/tool-scope.ts (신규) — I/O 없는 순수 함수.
buildSkillToolFilter()는 스키마 객체가 아니라 도구 '이름'을 받게 해서
테스트에서 문자열만으로 구동 가능하도록 함
- tests/tool-scope.test.ts — 17개. 비용(불필요한 도구 미노출)과
도달성(요청한 도구는 반드시 노출) 양쪽을 모두 고정
- handle-chat.ts 3,131 → 2,992줄
추출과 동시에 테스트가 버그 3종을 찾음:
1. 한글 뒤 \b 는 절대 매칭되지 않음 (죽은 패턴 5개)
\b는 ASCII 단어경계라 한글 음절 뒤에서는 성립하지 않음. `메일\b`가 그 예로,
"메일 확인해줘"가 게이트를 통과하지 못해 이메일 도구가 아예 노출되지 않았음
("이메일"이라고 써야만 동작). 같은 죽은 패턴이 hasCodeKeyword(함수/클래스/
버그), hasNewsKeyword(기사), hasPptxKeyword(덱)에도 있었음. 배포 후 확인:
"메일 확인해줘"가 email_list를 정상 호출함
2. pptx 게이트 조건 반전
`presenterEnabled && !hasPptxKeyword`라 스킬이 '꺼진' 경우 배제가 아예
동작하지 않았음. 스킬이 꺼졌으면 더 제한해야 하는데 반대로 열려 있었던 것.
실제 영향 범위(skills_state.json 대조): papa·cherry는 presenter=true라 무관,
jasmine만 매 턴 ~1,600토큰(create_presentation 833은 최대 스키마)을 지고
있었음. weather/legal과 같은 형태로 정정
3. (테스트 작성 중) 원문을 줄여 쓴 케이스가 실패 → 이전 커밋에서 수정한
SPEC_CONTEXT_KEYWORD 구멍과 동일 계열임을 재확인
전체 47개 테스트 통과. 실측 오버헤드는 papa 기준 3,574로 동일(위 2번이
papa에겐 원래 정상 동작했으므로 예상된 결과).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2ba39bca76
commit
6461e73a5e
3 files changed
+377
-145
No files matched your search
@@ -70,6 +70,7 @@ import { createCodeChat, type HandleChatResult as CodeChatHandleChatResult } fro
|
||||
import { createPreflightAdvisor, type PreflightAdvisorCtx } from './preflight-advisor';
|
||||
import { createBrowserDesktopAdvisors, type BrowserDesktopAdvisorCtx } from './browser-desktop-advisor';
|
||||
import type { SkillsManager } from '../skills-manager';
|
||||
import { selectToolsForTurn, bootAllowedTools, codeAiBlockedTools } from './tool-scope';
|
||||
|
||||
const MAX_TOOL_ROUNDS = 50;
|
||||
type ExecutionMode = 'interactive' | 'background_task' | 'heartbeat' | 'cron';
|
||||
@@ -183,7 +184,6 @@ async function handleChat(
|
||||
): Promise<HandleChatResult> {
|
||||
const ollama = getOllamaClient();
|
||||
const isBootStartupTurn = /\bBOOT\.md\b/i.test(String(callerContext || ''));
|
||||
const bootAllowedTools = new Set(['coder_list_files', 'coder_read_file']);
|
||||
const configuredWorkspace = getConfig().getWorkspacePath();
|
||||
const sessionWorkspace = getWorkspace(sessionId, username);
|
||||
// Session workspace (user-specific) takes priority over global configured workspace
|
||||
@@ -202,150 +202,11 @@ async function handleChat(
|
||||
const isCodeAiSession = String(sessionId || '').startsWith('code_ai_');
|
||||
const isTranslateSession = String(sessionId || '').startsWith('translate-');
|
||||
const isProjSession = String(sessionId || '').startsWith('proj-');
|
||||
// ── Code AI session: allow file/shell tools, block inappropriate ones ────
|
||||
// Code AI can now use coder_read_file, coder_write_file, coder_overwrite_lines, coder_insert_lines,
|
||||
// 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', 'weather_map_screenshot', 'start_timer', 'send_message', 'send_telegram', 'kakao_send_message', 'create_presentation', 'edit_presentation', 'spawn_subagent', 'schedule_job', 'parse_schedule_pattern',
|
||||
// desktop_* is Windows-only (desktop-tools.ts throws off process.platform); every call on
|
||||
// this Linux server fails, same reasoning as dormantDesktopTools below for the main filter.
|
||||
...(process.platform !== 'win32' ? ['desktop_screenshot', 'desktop_find_window', 'desktop_focus_window', 'desktop_click', 'desktop_drag', 'desktop_wait', 'desktop_press_key', 'desktop_type', 'desktop_set_clipboard', 'desktop_get_clipboard'] : [])]);
|
||||
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']);
|
||||
// In practice these are only ever used while building an academic presentation (gather
|
||||
// papers → create_presentation), not in standalone chat — gate them the same way as the
|
||||
// pptx tools themselves rather than always loading 5 more schemas.
|
||||
const academicToolNames = new Set(['pubmed_search', 'pubmed_fetch', 'pubmed_fulltext', 'openalex_search', 'semantic_search']);
|
||||
// coder_* (10 tools) is the file-authoring toolkit for actual code/script work — it has its
|
||||
// own dedicated branch for isCodeAiSession (code.html) below, so this only affects the
|
||||
// general chat path (main app + app-specific tabs like ac_/wt_/lw_/dental_/mn_, none of which
|
||||
// are coding contexts). Ungated, it rode along on every single turn regardless of topic.
|
||||
const coderToolNames = new Set(['coder_read_file', 'coder_write_file', 'coder_overwrite_lines', 'coder_insert_lines', 'coder_delete_lines', 'coder_str_replace', 'coder_patch_file', 'coder_delete_file', 'coder_move_file', 'coder_list_files']);
|
||||
const hasCodeKeyword = /코드|스크립트|소스\s*코드|알고리즘|파이썬|python|javascript|typescript|자바스크립트|타입스크립트|프로그램|함수\b|클래스\b|디버그|버그\b|리팩터|refactor|\.py\b|\.js\b|\.ts\b|\.html\b|\.css\b|\.json\b|\.sh\b|\bcode\b|script|algorithm/i.test(message);
|
||||
// Email/kakao/db/image-edit — same story as excel: no dedicated skill toggle or app tab,
|
||||
// so gate purely on keyword. shell's own description tells the model to pair it with
|
||||
// coder_write_file, so it rides the same code-intent gate rather than its own.
|
||||
const emailToolNames = new Set(['email_list', 'email_read', 'email_send', 'email_search', 'email_delete']);
|
||||
const hasEmailKeyword = /이메일|메일\b|email|inbox|받은편지함/i.test(message);
|
||||
const hasKakaoKeyword = /카카오|kakao/i.test(message);
|
||||
const hasSqliteKeyword = /데이터베이스|sqlite|쿼리|query\b|\.db\b/i.test(message);
|
||||
const hasImageEditKeyword = /편집|보정|자르기|리사이즈|크롭|워터마크|배경\s*제거|필터|흑백|그레이스케일|스타일화|crop|resize|watermark|remove.?bg|grayscale|stylize/i.test(message);
|
||||
// news_search is the single biggest ungated schema (2,035 chars, mostly usage guidance for
|
||||
// its country/category/language params) yet was included on every turn regardless of topic.
|
||||
const hasNewsKeyword = /뉴스|시사|헤드라인|속보|기사\b|news|headline/i.test(message);
|
||||
// image_read (OCR) only makes sense once an actual image is in play — the upload flow
|
||||
// inserts attachments as markdown image links (), so detect that
|
||||
// directly instead of guessing at phrasing like the other keyword gates.
|
||||
const hasImageAttachment = /\.(png|jpe?g|webp|bmp|tiff?|gif)\b/i.test(message);
|
||||
const hasRunCommandKeyword = /실행해|열어줘|띄워줘|런칭|실행시켜|메모장|notepad|vscode|vs\s*code|launch\s+(app|the|notepad|vscode)/i.test(message);
|
||||
// Same shape as hasImageAttachment — pdf_read/pdf_extract_images (1,792 chars combined, the
|
||||
// biggest remaining pair) only make sense once a PDF is actually referenced.
|
||||
const hasPdfAttachment = /\.pdf\b|pdf\s*(파일|읽어|추출)/i.test(message);
|
||||
const hasScheduleKeyword = /예약|스케줄|반복|매일|매주|매월|정기적|주기적|cron|schedule|recurring/i.test(message);
|
||||
// eonet_events/satellite_snapshot — casual "what's happening on Earth" feature,
|
||||
// not relevant to unrelated turns.
|
||||
const hasSatelliteKeyword = /위성|자연재해|산불|태풍|화산|지진|산사태|가뭄|황사|연무|해빙|satellite|wildfire|volcano|eonet|natural\s*disaster/i.test(message);
|
||||
const meteorologistEnabled = isSkillEnabledForUser('meteorologist', userWorkspace);
|
||||
const lawyerEnabled = isSkillEnabledForUser('lawyer', userWorkspace);
|
||||
const presenterEnabled = isSkillEnabledForUser('presenter', userWorkspace);
|
||||
const hasPptxKeyword = /슬라이드|발표|pptx|ppt\b|프레젠테이션|피피티|덱\b|presentation/i.test(message);
|
||||
// Weather/legal skills being ON means the user does that kind of work sometimes, not that
|
||||
// every single turn is about it — without a keyword gate the full 9 weather / 3 legal tools
|
||||
// rode along on unrelated turns too. Mirrors the pptx pattern (skill + keyword) below.
|
||||
const hasWeatherKeyword = /날씨|기온|강수|미세먼지|대기질|태풍|기후|일기예보|장마|폭염|한파|자외선|황사|weather|forecast/i.test(message);
|
||||
const hasLegalKeyword = /법률|판례|소송|변호사|법원|법조문|조항|계약서|형법|민법|법령|legal|lawsuit|court|statute/i.test(message);
|
||||
// excel_read/excel_write have no dedicated skill toggle (accountant-app.html's persona is
|
||||
// page-local, not a registered skill) — gate on the accountant app tab (ac_ sessions) or an
|
||||
// explicit excel/spreadsheet keyword, same shape as the weather/legal gates above. Previously
|
||||
// ungated, so both tool schemas rode along on every single chat turn regardless of app.
|
||||
const hasExcelKeyword = /엑셀|xlsx|xls\b|스프레드시트|spreadsheet|excel/i.test(message);
|
||||
// ollama_web_search/ollama_web_fetch are explicitly self-deprecating in their own descriptions
|
||||
// ("web_search가 없는 환경에서만 fallback으로 사용") — and the provider fallback they exist for
|
||||
// is already handled server-side inside executeWebSearch, so the model never needs to reach for
|
||||
// them on its own. Advertising them cost 214 tokens per turn to tell the model not to use a
|
||||
// tool. Gate on the same explicit phrasing personality-context.ts already uses for its
|
||||
// ollama_web hint block, so the pair stays available when the user actually asks for it by name
|
||||
// (otherwise that hint would describe tools no longer in the schema).
|
||||
const ollamaWebToolNames = new Set(['ollama_web_search', 'ollama_web_fetch']);
|
||||
const hasOllamaWebKeyword = /ollama[\s_]?(웹|web|검색|search)|올라마\s*(웹|검색|로\s*검색)/i.test(message);
|
||||
// Sub-agent/task-orchestration tools that tool_audit.log shows near-zero real usage for
|
||||
// (2026-05-04~2026-07-12: start_task/request_secondary_assist/subagent_spawn/
|
||||
// delegate_to_specialist/spawn_subagent = 0 calls; task_control/parse_schedule_pattern/
|
||||
// spawn_agent = a handful, all stale). Kept registered for future agent-composition work,
|
||||
// just not sent to the model in normal chat. schedule_job is excluded from this set — it's
|
||||
// self-contained (list/create/update/pause/resume/delete/run_now) and still actively used.
|
||||
const dormantAgentTools = new Set(['start_task', 'task_control', 'parse_schedule_pattern', 'request_secondary_assist', 'subagent_spawn', 'delegate_to_specialist', 'spawn_subagent', 'spawn_agent']);
|
||||
// Browser automation — parked. tool_audit.log shows every browser_open call from 07-09
|
||||
// onward failing with "Chrome launched but did not respond on port 9222". Repeated debug
|
||||
// runs showed the live `tools` array alternates between two mutually-exclusive sets for the
|
||||
// SAME "ping" request against the SAME running process — open/snapshot/click/fill/press_key/
|
||||
// wait/close one time, scroll/get_images the next — apparently some live Chrome-reachability
|
||||
// probe swapping which schema set gets exposed. Excluding all 9 names covers both variants.
|
||||
// Re-enable by removing this set once browser automation is fixed / needed (e.g. home shopping).
|
||||
const dormantBrowserTools = new Set(['browser_open', 'browser_snapshot', 'browser_click', 'browser_fill', 'browser_press_key', 'browser_wait', 'browser_close', 'browser_scroll', 'browser_get_images']);
|
||||
// desktop_* (10 tools, ~2.7k of the tool-schema overhead) is Windows-only remote-desktop
|
||||
// control (mouse/keyboard/screenshot) — desktop-tools.ts itself throws "Desktop tools are
|
||||
// currently supported on Windows only." off process.platform, and tool_audit.log shows every
|
||||
// desktop_screenshot call ever made on this server failing with exactly that. Mirror the same
|
||||
// platform check here so the schemas aren't sent on a platform where every call is guaranteed
|
||||
// to fail (auto-recovers if this ever runs on Windows, unlike a hardcoded exclude).
|
||||
const dormantDesktopTools = process.platform !== 'win32'
|
||||
? new Set(['desktop_screenshot', 'desktop_find_window', 'desktop_focus_window', 'desktop_click', 'desktop_drag', 'desktop_wait', 'desktop_press_key', 'desktop_type', 'desktop_set_clipboard', 'desktop_get_clipboard'])
|
||||
: new Set<string>();
|
||||
// MCP database servers built for a specific dedicated app tab (dental-agent.html →
|
||||
// 'dental_' sessions, mind-app.html → 'mn_' sessions) — 62% of the tool-schema overhead
|
||||
// (12,124 of 19,531 tokens measured) came from these 3 servers × 8 sub-tools each, riding
|
||||
// along on every main-chat turn for every user even though they're single-purpose lookup
|
||||
// tables for one app. Scope them to the app session that actually uses them.
|
||||
const isDentalAppSession = /^dental_/.test(String(sessionId || ''));
|
||||
const isMindAppSession = /^mn_/.test(String(sessionId || ''));
|
||||
// Weather/lawyer have their own dedicated app tabs (weather-app.html → 'wt_' sessions,
|
||||
// lawyer-app.html → 'lw_' sessions). Inside those apps the skill+keyword gate below is
|
||||
// wrong — a "wt_" session IS the weather context even if a given message has no weather
|
||||
// keyword (e.g. a follow-up "내일은?"), so always include the tools there.
|
||||
const isWeatherAppSession = /^wt_/.test(String(sessionId || ''));
|
||||
const isLawyerAppSession = /^lw_/.test(String(sessionId || ''));
|
||||
const isAccountantAppSession = /^ac_/.test(String(sessionId || ''));
|
||||
const skillToolFilter = (t: any) => {
|
||||
const name = String(t?.function?.name || '');
|
||||
if (dormantAgentTools.has(name)) return false;
|
||||
if (dormantBrowserTools.has(name)) return false;
|
||||
if (dormantDesktopTools.has(name)) return false;
|
||||
if (name.startsWith('mcp__dental-dict-sqlite__') && !isDentalAppSession) return false;
|
||||
if ((name.startsWith('mcp__psychotherapy-cases-sqlite__') || name.startsWith('mcp__psychiatry-cases-sqlite__')) && !isMindAppSession) return false;
|
||||
if (weatherToolNames.has(name) && !isWeatherAppSession && !(meteorologistEnabled && hasWeatherKeyword)) return false;
|
||||
// Windy map screenshots only make sense inside the dedicated weather app tab (the
|
||||
// model there has already generated the embed.windy.com URL to capture) — unlike the
|
||||
// other weather tools, not offered via the meteorologist skill in general chat.
|
||||
if (name === 'weather_map_screenshot' && !isWeatherAppSession) return false;
|
||||
if (ollamaWebToolNames.has(name) && !hasOllamaWebKeyword) return false;
|
||||
if (legalToolNames.has(name) && !isLawyerAppSession && !(lawyerEnabled && hasLegalKeyword)) return false;
|
||||
if ((name === 'excel_read' || name === 'excel_write') && !isAccountantAppSession && !hasExcelKeyword) return false;
|
||||
if (coderToolNames.has(name) && !hasCodeKeyword) return false;
|
||||
if (name === 'shell' && !hasCodeKeyword) return false;
|
||||
if (pptxToolNames.has(name) && presenterEnabled && !hasPptxKeyword) return false;
|
||||
if (academicToolNames.has(name) && !hasPptxKeyword) return false;
|
||||
if (emailToolNames.has(name) && !hasEmailKeyword) return false;
|
||||
if (name === 'kakao_send_message' && !hasKakaoKeyword) return false;
|
||||
if (name === 'sqlite_query' && !hasSqliteKeyword) return false;
|
||||
if (name === 'image_edit' && !hasImageEditKeyword) return false;
|
||||
if (name === 'image_read' && !hasImageAttachment) return false;
|
||||
if (name === 'news_search' && !hasNewsKeyword) return false;
|
||||
if ((name === 'pdf_read' || name === 'pdf_extract_images') && !hasPdfAttachment) return false;
|
||||
if (name === 'schedule_job' && !hasScheduleKeyword) return false;
|
||||
if ((name === 'eonet_events' || name === 'satellite_snapshot') && !hasSatelliteKeyword) return false;
|
||||
if (name === 'run_command' && !hasRunCommandKeyword) return false;
|
||||
return true;
|
||||
};
|
||||
const tools = isBootStartupTurn
|
||||
? buildTools().filter((t: any) => bootAllowedTools.has(String(t?.function?.name || '')))
|
||||
: isTranslateSession || isProjSession
|
||||
? []
|
||||
: isCodeAiSession
|
||||
? buildTools().filter((t: any) => !codeAiBlockedTools.has(String(t?.function?.name || '')))
|
||||
: buildTools().filter((t: any) => skillToolFilter(t));
|
||||
// 도구 선택 로직은 tool-scope.ts로 분리됨(2026-07-29) — handleChat 안의 클로저라 테스트가
|
||||
// 불가능했고, 게이트 하나가 조용히 어긋나도 아무 에러 없이 프롬프트만 뚱뚱해지던 구간.
|
||||
const tools = selectToolsForTurn(buildTools(),
|
||||
{ message, sessionId, userWorkspace, isSkillEnabledForUser },
|
||||
{ isBootStartupTurn, isCodeAiSession, isTranslateSession, isProjSession });
|
||||
const allToolResults: ToolResult[] = [];
|
||||
let allThinking = '';
|
||||
let lastUsage: { promptTokens: number; completionTokens: number; ctxWindow: number } | undefined;
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
/**
|
||||
* tool-scope.ts
|
||||
*
|
||||
* Decides WHICH tools the model is offered on a given turn.
|
||||
*
|
||||
* Extracted from handleChat() on 2026-07-29. It had lived as a closure inside a 2,959-line
|
||||
* function, which made it untestable — the only way to check a gate was to boot the gateway,
|
||||
* send a real chat message, and read the token count back out of an SSE event. Every condition
|
||||
* here exists because some tool was riding along on unrelated turns and costing schema tokens,
|
||||
* so a silent regression is invisible: nothing breaks, the prompt just quietly gets fatter or a
|
||||
* needed tool quietly disappears.
|
||||
*
|
||||
* Pure by construction: no I/O, no config reads, no clock. Everything it needs arrives in
|
||||
* ToolScopeInput, which is what makes it testable.
|
||||
*
|
||||
* Gating philosophy — two kinds, do not mix them up:
|
||||
* - APP SESSION gates (wt_/lw_/ac_ prefixes) are unconditional inside that app's tab, because
|
||||
* a follow-up like "내일은?" carries no keyword but is still a weather turn.
|
||||
* - KEYWORD gates are a cost optimisation and are allowed to be wrong: worst case the model
|
||||
* lacks a tool it could have used and says so. Never gate a SAFETY rule this way — see the
|
||||
* system-prompt blocks in handle-chat.ts, which gate on tool availability instead precisely
|
||||
* because a missed keyword there would drop a suppression rule.
|
||||
*/
|
||||
|
||||
export interface ToolScopeInput {
|
||||
/** The user's message for this turn — every keyword gate tests against it. */
|
||||
message: string;
|
||||
/** Session id; the wt_/lw_/ac_ prefixes select app-specific tool sets. */
|
||||
sessionId: string;
|
||||
/** Workspace path used for per-user skill toggles; null when unauthenticated. */
|
||||
userWorkspace: string | null;
|
||||
/** Injected so this module stays free of config/disk access. */
|
||||
isSkillEnabledForUser: (slug: string, workspace: string | null) => boolean;
|
||||
}
|
||||
|
||||
/** Boot (BOOT.md) turns get a read-only pair — they summarise state, they do not act. */
|
||||
export const bootAllowedTools = new Set(['coder_list_files', 'coder_read_file']);
|
||||
|
||||
/**
|
||||
* Code-editor sessions (code_ai_*) allow file/shell/search tools but block the ones that make
|
||||
* no sense in an editor: browser automation, messaging, timers, presentations, image tools.
|
||||
*/
|
||||
export 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', 'weather_map_screenshot', 'start_timer', 'send_message', 'send_telegram', 'kakao_send_message', 'create_presentation', 'edit_presentation', 'spawn_subagent', 'schedule_job', 'parse_schedule_pattern',
|
||||
// desktop_* is Windows-only (desktop-tools.ts throws off process.platform); every call on
|
||||
// this Linux server fails, same reasoning as dormantDesktopTools below for the main filter.
|
||||
...(process.platform !== 'win32' ? ['desktop_screenshot', 'desktop_find_window', 'desktop_focus_window', 'desktop_click', 'desktop_drag', 'desktop_wait', 'desktop_press_key', 'desktop_type', 'desktop_set_clipboard', 'desktop_get_clipboard'] : [])]);
|
||||
|
||||
/**
|
||||
* Builds the per-turn predicate. Returns a function of the tool NAME (not the whole schema
|
||||
* object) so tests can drive it with plain strings.
|
||||
*/
|
||||
export function buildSkillToolFilter(input: ToolScopeInput): (toolName: string) => boolean {
|
||||
const message = String(input.message || '');
|
||||
const sessionId = String(input.sessionId || '');
|
||||
const userWorkspace = input.userWorkspace;
|
||||
const isSkillEnabledForUser = input.isSkillEnabledForUser;
|
||||
|
||||
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']);
|
||||
// In practice these are only ever used while building an academic presentation (gather
|
||||
// papers → create_presentation), not in standalone chat — gate them the same way as the
|
||||
// pptx tools themselves rather than always loading 5 more schemas.
|
||||
const academicToolNames = new Set(['pubmed_search', 'pubmed_fetch', 'pubmed_fulltext', 'openalex_search', 'semantic_search']);
|
||||
// coder_* (10 tools) is the file-authoring toolkit for actual code/script work — it has its
|
||||
// own dedicated branch for isCodeAiSession (code.html) below, so this only affects the
|
||||
// general chat path (main app + app-specific tabs like ac_/wt_/lw_/dental_/mn_, none of which
|
||||
// are coding contexts). Ungated, it rode along on every single turn regardless of topic.
|
||||
const coderToolNames = new Set(['coder_read_file', 'coder_write_file', 'coder_overwrite_lines', 'coder_insert_lines', 'coder_delete_lines', 'coder_str_replace', 'coder_patch_file', 'coder_delete_file', 'coder_move_file', 'coder_list_files']);
|
||||
const hasCodeKeyword = /코드|스크립트|소스\s*코드|알고리즘|파이썬|python|javascript|typescript|자바스크립트|타입스크립트|프로그램|함수|클래스|디버그|버그|리팩터|refactor|\.py\b|\.js\b|\.ts\b|\.html\b|\.css\b|\.json\b|\.sh\b|\bcode\b|script|algorithm/i.test(message);
|
||||
// Email/kakao/db/image-edit — same story as excel: no dedicated skill toggle or app tab,
|
||||
// so gate purely on keyword. shell's own description tells the model to pair it with
|
||||
// coder_write_file, so it rides the same code-intent gate rather than its own.
|
||||
const emailToolNames = new Set(['email_list', 'email_read', 'email_send', 'email_search', 'email_delete']);
|
||||
// 2026-07-29 bugfix (found by tests/tool-scope.test.ts). A Hangul syllable followed by a
|
||||
// word-boundary anchor can NEVER match: \b is an ASCII boundary and Hangul is not an ASCII
|
||||
// word character, so there is no boundary between 일 and a following space. "메일 확인해줘"
|
||||
// therefore failed this gate outright and the email tools stayed hidden; only the separate
|
||||
// "이메일" alternative ever fired. The same dead pattern was removed from hasCodeKeyword
|
||||
// (함수/클래스/버그), hasNewsKeyword (기사) and hasPptxKeyword (덱) in the same pass — all of
|
||||
// them were silently no-op alternatives. Dropping the anchor is safe for Korean: these words
|
||||
// are unambiguous as substrings (카카오메일, 기사 등). Keep \b only on ASCII tokens like ppt\b.
|
||||
const hasEmailKeyword = /이메일|메일|email|inbox|받은편지함/i.test(message);
|
||||
const hasKakaoKeyword = /카카오|kakao/i.test(message);
|
||||
const hasSqliteKeyword = /데이터베이스|sqlite|쿼리|query\b|\.db\b/i.test(message);
|
||||
const hasImageEditKeyword = /편집|보정|자르기|리사이즈|크롭|워터마크|배경\s*제거|필터|흑백|그레이스케일|스타일화|crop|resize|watermark|remove.?bg|grayscale|stylize/i.test(message);
|
||||
// news_search is the single biggest ungated schema (2,035 chars, mostly usage guidance for
|
||||
// its country/category/language params) yet was included on every turn regardless of topic.
|
||||
const hasNewsKeyword = /뉴스|시사|헤드라인|속보|기사|news|headline/i.test(message);
|
||||
// image_read (OCR) only makes sense once an actual image is in play — the upload flow
|
||||
// inserts attachments as markdown image links (), so detect that
|
||||
// directly instead of guessing at phrasing like the other keyword gates.
|
||||
const hasImageAttachment = /\.(png|jpe?g|webp|bmp|tiff?|gif)\b/i.test(message);
|
||||
const hasRunCommandKeyword = /실행해|열어줘|띄워줘|런칭|실행시켜|메모장|notepad|vscode|vs\s*code|launch\s+(app|the|notepad|vscode)/i.test(message);
|
||||
// Same shape as hasImageAttachment — pdf_read/pdf_extract_images (1,792 chars combined, the
|
||||
// biggest remaining pair) only make sense once a PDF is actually referenced.
|
||||
const hasPdfAttachment = /\.pdf\b|pdf\s*(파일|읽어|추출)/i.test(message);
|
||||
const hasScheduleKeyword = /예약|스케줄|반복|매일|매주|매월|정기적|주기적|cron|schedule|recurring/i.test(message);
|
||||
// eonet_events/satellite_snapshot — casual "what's happening on Earth" feature,
|
||||
// not relevant to unrelated turns.
|
||||
const hasSatelliteKeyword = /위성|자연재해|산불|태풍|화산|지진|산사태|가뭄|황사|연무|해빙|satellite|wildfire|volcano|eonet|natural\s*disaster/i.test(message);
|
||||
const meteorologistEnabled = isSkillEnabledForUser('meteorologist', userWorkspace);
|
||||
const lawyerEnabled = isSkillEnabledForUser('lawyer', userWorkspace);
|
||||
const presenterEnabled = isSkillEnabledForUser('presenter', userWorkspace);
|
||||
const hasPptxKeyword = /슬라이드|발표|pptx|ppt\b|프레젠테이션|피피티|덱|presentation/i.test(message);
|
||||
// Weather/legal skills being ON means the user does that kind of work sometimes, not that
|
||||
// every single turn is about it — without a keyword gate the full 9 weather / 3 legal tools
|
||||
// rode along on unrelated turns too. Mirrors the pptx pattern (skill + keyword) below.
|
||||
const hasWeatherKeyword = /날씨|기온|강수|미세먼지|대기질|태풍|기후|일기예보|장마|폭염|한파|자외선|황사|weather|forecast/i.test(message);
|
||||
const hasLegalKeyword = /법률|판례|소송|변호사|법원|법조문|조항|계약서|형법|민법|법령|legal|lawsuit|court|statute/i.test(message);
|
||||
// excel_read/excel_write have no dedicated skill toggle (accountant-app.html's persona is
|
||||
// page-local, not a registered skill) — gate on the accountant app tab (ac_ sessions) or an
|
||||
// explicit excel/spreadsheet keyword, same shape as the weather/legal gates above. Previously
|
||||
// ungated, so both tool schemas rode along on every single chat turn regardless of app.
|
||||
const hasExcelKeyword = /엑셀|xlsx|xls\b|스프레드시트|spreadsheet|excel/i.test(message);
|
||||
// ollama_web_search/ollama_web_fetch are explicitly self-deprecating in their own descriptions
|
||||
// ("web_search가 없는 환경에서만 fallback으로 사용") — and the provider fallback they exist for
|
||||
// is already handled server-side inside executeWebSearch, so the model never needs to reach for
|
||||
// them on its own. Advertising them cost 214 tokens per turn to tell the model not to use a
|
||||
// tool. Gate on the same explicit phrasing personality-context.ts already uses for its
|
||||
// ollama_web hint block, so the pair stays available when the user actually asks for it by name
|
||||
// (otherwise that hint would describe tools no longer in the schema).
|
||||
const ollamaWebToolNames = new Set(['ollama_web_search', 'ollama_web_fetch']);
|
||||
const hasOllamaWebKeyword = /ollama[\s_]?(웹|web|검색|search)|올라마\s*(웹|검색|로\s*검색)/i.test(message);
|
||||
// Sub-agent/task-orchestration tools that tool_audit.log shows near-zero real usage for
|
||||
// (2026-05-04~2026-07-12: start_task/request_secondary_assist/subagent_spawn/
|
||||
// delegate_to_specialist/spawn_subagent = 0 calls; task_control/parse_schedule_pattern/
|
||||
// spawn_agent = a handful, all stale). Kept registered for future agent-composition work,
|
||||
// just not sent to the model in normal chat. schedule_job is excluded from this set — it's
|
||||
// self-contained (list/create/update/pause/resume/delete/run_now) and still actively used.
|
||||
const dormantAgentTools = new Set(['start_task', 'task_control', 'parse_schedule_pattern', 'request_secondary_assist', 'subagent_spawn', 'delegate_to_specialist', 'spawn_subagent', 'spawn_agent']);
|
||||
// Browser automation — parked. tool_audit.log shows every browser_open call from 07-09
|
||||
// onward failing with "Chrome launched but did not respond on port 9222". Repeated debug
|
||||
// runs showed the live `tools` array alternates between two mutually-exclusive sets for the
|
||||
// SAME "ping" request against the SAME running process — open/snapshot/click/fill/press_key/
|
||||
// wait/close one time, scroll/get_images the next — apparently some live Chrome-reachability
|
||||
// probe swapping which schema set gets exposed. Excluding all 9 names covers both variants.
|
||||
// Re-enable by removing this set once browser automation is fixed / needed (e.g. home shopping).
|
||||
const dormantBrowserTools = new Set(['browser_open', 'browser_snapshot', 'browser_click', 'browser_fill', 'browser_press_key', 'browser_wait', 'browser_close', 'browser_scroll', 'browser_get_images']);
|
||||
// desktop_* (10 tools, ~2.7k of the tool-schema overhead) is Windows-only remote-desktop
|
||||
// control (mouse/keyboard/screenshot) — desktop-tools.ts itself throws "Desktop tools are
|
||||
// currently supported on Windows only." off process.platform, and tool_audit.log shows every
|
||||
// desktop_screenshot call ever made on this server failing with exactly that. Mirror the same
|
||||
// platform check here so the schemas aren't sent on a platform where every call is guaranteed
|
||||
// to fail (auto-recovers if this ever runs on Windows, unlike a hardcoded exclude).
|
||||
const dormantDesktopTools = process.platform !== 'win32'
|
||||
? new Set(['desktop_screenshot', 'desktop_find_window', 'desktop_focus_window', 'desktop_click', 'desktop_drag', 'desktop_wait', 'desktop_press_key', 'desktop_type', 'desktop_set_clipboard', 'desktop_get_clipboard'])
|
||||
: new Set<string>();
|
||||
// MCP database servers built for a specific dedicated app tab (dental-agent.html →
|
||||
// 'dental_' sessions, mind-app.html → 'mn_' sessions) — 62% of the tool-schema overhead
|
||||
// (12,124 of 19,531 tokens measured) came from these 3 servers × 8 sub-tools each, riding
|
||||
// along on every main-chat turn for every user even though they're single-purpose lookup
|
||||
// tables for one app. Scope them to the app session that actually uses them.
|
||||
const isDentalAppSession = /^dental_/.test(String(sessionId || ''));
|
||||
const isMindAppSession = /^mn_/.test(String(sessionId || ''));
|
||||
// Weather/lawyer have their own dedicated app tabs (weather-app.html → 'wt_' sessions,
|
||||
// lawyer-app.html → 'lw_' sessions). Inside those apps the skill+keyword gate below is
|
||||
// wrong — a "wt_" session IS the weather context even if a given message has no weather
|
||||
// keyword (e.g. a follow-up "내일은?"), so always include the tools there.
|
||||
const isWeatherAppSession = /^wt_/.test(String(sessionId || ''));
|
||||
const isLawyerAppSession = /^lw_/.test(String(sessionId || ''));
|
||||
const isAccountantAppSession = /^ac_/.test(String(sessionId || ''));
|
||||
const filter = (name: string): boolean => {
|
||||
if (dormantAgentTools.has(name)) return false;
|
||||
if (dormantBrowserTools.has(name)) return false;
|
||||
if (dormantDesktopTools.has(name)) return false;
|
||||
if (name.startsWith('mcp__dental-dict-sqlite__') && !isDentalAppSession) return false;
|
||||
if ((name.startsWith('mcp__psychotherapy-cases-sqlite__') || name.startsWith('mcp__psychiatry-cases-sqlite__')) && !isMindAppSession) return false;
|
||||
if (weatherToolNames.has(name) && !isWeatherAppSession && !(meteorologistEnabled && hasWeatherKeyword)) return false;
|
||||
// Windy map screenshots only make sense inside the dedicated weather app tab (the
|
||||
// model there has already generated the embed.windy.com URL to capture) — unlike the
|
||||
// other weather tools, not offered via the meteorologist skill in general chat.
|
||||
if (name === 'weather_map_screenshot' && !isWeatherAppSession) return false;
|
||||
if (ollamaWebToolNames.has(name) && !hasOllamaWebKeyword) return false;
|
||||
if (legalToolNames.has(name) && !isLawyerAppSession && !(lawyerEnabled && hasLegalKeyword)) return false;
|
||||
if ((name === 'excel_read' || name === 'excel_write') && !isAccountantAppSession && !hasExcelKeyword) return false;
|
||||
if (coderToolNames.has(name) && !hasCodeKeyword) return false;
|
||||
if (name === 'shell' && !hasCodeKeyword) return false;
|
||||
// 2026-07-29 bugfix (found by tests/tool-scope.test.ts on extraction): the condition used to
|
||||
// be `presenterEnabled && !hasPptxKeyword`, i.e. the exclusion only ran when the presenter
|
||||
// skill was ENABLED. With the skill OFF the gate never fired at all and both schemas rode
|
||||
// along on every turn — inverted, since a disabled skill should restrict more, not less.
|
||||
// Scope of the actual impact (checked against skills_state.json the same day): papa and
|
||||
// cherry have presenter=true so they were unaffected; jasmine has it false and was carrying
|
||||
// ~1,600 tokens of presentation API surface (create_presentation alone is 833, the largest
|
||||
// tool schema in the codebase) on every turn including plain greetings.
|
||||
// Now matches the weather/legal shape directly above: exclude unless skill AND keyword agree.
|
||||
if (pptxToolNames.has(name) && !(presenterEnabled && hasPptxKeyword)) return false;
|
||||
if (academicToolNames.has(name) && !hasPptxKeyword) return false;
|
||||
if (emailToolNames.has(name) && !hasEmailKeyword) return false;
|
||||
if (name === 'kakao_send_message' && !hasKakaoKeyword) return false;
|
||||
if (name === 'sqlite_query' && !hasSqliteKeyword) return false;
|
||||
if (name === 'image_edit' && !hasImageEditKeyword) return false;
|
||||
if (name === 'image_read' && !hasImageAttachment) return false;
|
||||
if (name === 'news_search' && !hasNewsKeyword) return false;
|
||||
if ((name === 'pdf_read' || name === 'pdf_extract_images') && !hasPdfAttachment) return false;
|
||||
if (name === 'schedule_job' && !hasScheduleKeyword) return false;
|
||||
if ((name === 'eonet_events' || name === 'satellite_snapshot') && !hasSatelliteKeyword) return false;
|
||||
if (name === 'run_command' && !hasRunCommandKeyword) return false;
|
||||
return true;
|
||||
};
|
||||
return filter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the right tool set for the turn. The four branches are mutually exclusive and
|
||||
* ordered by specificity: boot < inert sessions < code editor < normal chat.
|
||||
*/
|
||||
export function selectToolsForTurn(
|
||||
allTools: any[],
|
||||
input: ToolScopeInput,
|
||||
flags: { isBootStartupTurn: boolean; isCodeAiSession: boolean; isTranslateSession: boolean; isProjSession: boolean },
|
||||
): any[] {
|
||||
const nameOf = (t: any) => String(t?.function?.name || '');
|
||||
if (flags.isBootStartupTurn) return allTools.filter(t => bootAllowedTools.has(nameOf(t)));
|
||||
// Translation and project-file sessions answer from the prompt alone; handing them tools only
|
||||
// invites a stray call that corrupts a strict output format.
|
||||
if (flags.isTranslateSession || flags.isProjSession) return [];
|
||||
if (flags.isCodeAiSession) return allTools.filter(t => !codeAiBlockedTools.has(nameOf(t)));
|
||||
const filter = buildSkillToolFilter(input);
|
||||
return allTools.filter(t => filter(nameOf(t)));
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* tool-scope.test.ts
|
||||
*
|
||||
* Which tools the model is offered on a given turn. Until 2026-07-29 this logic lived as a
|
||||
* closure inside handleChat() and could only be exercised by booting the gateway and reading
|
||||
* a token count out of an SSE event — so it had never been tested at all, and a mis-gated tool
|
||||
* showed up only as a slightly larger prompt or a mysteriously missing capability.
|
||||
*
|
||||
* Two properties matter and they pull in opposite directions:
|
||||
* 1. cost — a tool nobody needs must not ride along (that is why the gates exist)
|
||||
* 2. reach — a tool the user clearly asked for must be there (a gate that is too tight
|
||||
* silently removes a feature, which is far worse than a few wasted tokens)
|
||||
* Every test below pins one or the other.
|
||||
*/
|
||||
|
||||
import { test, describe } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { buildSkillToolFilter, selectToolsForTurn, codeAiBlockedTools, bootAllowedTools } from '../src/gateway/chat/tool-scope';
|
||||
|
||||
const base = {
|
||||
sessionId: 'default',
|
||||
userWorkspace: null as string | null,
|
||||
isSkillEnabledForUser: () => false,
|
||||
};
|
||||
/** 모든 스킬이 켜진 상태 — 스킬+키워드 두 조건을 함께 요구하는 게이트를 검증할 때 사용. */
|
||||
const allSkills = { ...base, isSkillEnabledForUser: () => true };
|
||||
|
||||
const filterFor = (message: string, extra: Partial<typeof base> = {}) =>
|
||||
buildSkillToolFilter({ ...base, ...extra, message });
|
||||
|
||||
describe('키워드 게이트 — 관련 없는 턴에서 도구가 따라붙지 않는다', () => {
|
||||
test('평범한 인사에는 앱 전용 도구가 전부 빠진다', () => {
|
||||
const f = filterFor('안녕');
|
||||
for (const name of ['weather_kma', 'news_search', 'email_list', 'create_presentation',
|
||||
'korean_law_search', 'sqlite_query', 'image_edit', 'schedule_job',
|
||||
'coder_read_file', 'shell', 'excel_read', 'eonet_events']) {
|
||||
assert.equal(f(name), false, `${name} 이(가) 인사말 턴에 노출됨`);
|
||||
}
|
||||
});
|
||||
|
||||
test('핵심 도구는 항상 남는다', () => {
|
||||
const f = filterFor('안녕');
|
||||
for (const name of ['web_search', 'web_fetch', 'memory_read', 'python_eval']) {
|
||||
assert.equal(f(name), true, `${name} 이(가) 사라짐`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('키워드 게이트 — 필요할 때 확실히 나타난다', () => {
|
||||
test('뉴스 요청', () => {
|
||||
assert.equal(filterFor('오늘 미국 주요 뉴스')('news_search'), true);
|
||||
});
|
||||
|
||||
test('날씨는 스킬+키워드 둘 다 필요', () => {
|
||||
// 스킬이 꺼져 있으면 키워드만으로는 안 열린다.
|
||||
assert.equal(filterFor('내일 날씨 어때')('weather_kma'), false);
|
||||
assert.equal(buildSkillToolFilter({ ...allSkills, message: '내일 날씨 어때' })('weather_kma'), true);
|
||||
});
|
||||
|
||||
test('코드 관련 표현이면 편집/셸 도구가 열린다', () => {
|
||||
const f = filterFor('이 파이썬 스크립트 디버그해줘');
|
||||
assert.equal(f('coder_read_file'), true);
|
||||
assert.equal(f('shell'), true);
|
||||
});
|
||||
|
||||
test('이메일 / DB / 엑셀 / 일정', () => {
|
||||
assert.equal(filterFor('메일 확인해줘')('email_list'), true);
|
||||
assert.equal(filterFor('sqlite 쿼리 돌려줘')('sqlite_query'), true);
|
||||
assert.equal(filterFor('엑셀 파일 읽어줘')('excel_read'), true);
|
||||
assert.equal(filterFor('매일 아침에 반복 실행해줘')('schedule_job'), true);
|
||||
});
|
||||
|
||||
test('첨부가 있어야 열리는 도구', () => {
|
||||
assert.equal(filterFor('이거 읽어줘')('image_read'), false);
|
||||
assert.equal(filterFor(' 이거 읽어줘')('image_read'), true);
|
||||
assert.equal(filterFor('report.pdf 요약해줘')('pdf_read'), true);
|
||||
});
|
||||
|
||||
test('[2026-07-29] ollama_web_* 는 명시 요청에만 — 평소엔 214토큰 낭비였다', () => {
|
||||
assert.equal(filterFor('RTX 5090 검색해줘')('ollama_web_search'), false);
|
||||
assert.equal(filterFor('올라마로 검색해줘')('ollama_web_search'), true);
|
||||
assert.equal(filterFor('ollama web search 해줘')('ollama_web_fetch'), true);
|
||||
});
|
||||
|
||||
test('위성/재난 도구', () => {
|
||||
assert.equal(filterFor('안녕')('satellite_snapshot'), false);
|
||||
assert.equal(filterFor('산불 위성사진 보여줘')('satellite_snapshot'), true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('앱 세션 게이트 — 탭 안에서는 키워드 없이도 열려 있어야 한다', () => {
|
||||
test('날씨 앱 탭에서는 후속 질문에 키워드가 없어도 도구가 유지된다', () => {
|
||||
// "내일은?" 같은 후속엔 날씨 키워드가 없다 — 세션 접두사가 그걸 메운다.
|
||||
const f = buildSkillToolFilter({ ...base, sessionId: 'wt_abc123', message: '내일은?' });
|
||||
assert.equal(f('weather_kma'), true);
|
||||
assert.equal(f('weather_map_screenshot'), true);
|
||||
});
|
||||
|
||||
test('일반 세션에서는 windy 스크린샷이 열리지 않는다', () => {
|
||||
assert.equal(buildSkillToolFilter({ ...allSkills, message: '날씨 알려줘' })('weather_map_screenshot'), false);
|
||||
});
|
||||
|
||||
test('변호사 / 회계 앱 탭', () => {
|
||||
assert.equal(buildSkillToolFilter({ ...base, sessionId: 'lw_1', message: '이거 봐줘' })('korean_law_search'), true);
|
||||
assert.equal(buildSkillToolFilter({ ...base, sessionId: 'ac_1', message: '이거 봐줘' })('excel_read'), true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('휴면 도구 — 실사용 0건이거나 이 플랫폼에서 동작하지 않는 것들', () => {
|
||||
test('오케스트레이션/브라우저 도구는 어떤 문구로도 열리지 않는다', () => {
|
||||
const f = filterFor('브라우저 열어서 작업 시작해줘');
|
||||
assert.equal(f('spawn_subagent'), false);
|
||||
assert.equal(f('start_task'), false);
|
||||
assert.equal(f('browser_open'), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('selectToolsForTurn — 세션 종류별 분기', () => {
|
||||
const tools = ['web_search', 'coder_read_file', 'image_edit', 'start_task', 'shell', 'memory_read']
|
||||
.map(n => ({ type: 'function', function: { name: n } }));
|
||||
const names = (r: any[]) => r.map(t => t.function.name).sort();
|
||||
const flags = { isBootStartupTurn: false, isCodeAiSession: false, isTranslateSession: false, isProjSession: false };
|
||||
|
||||
test('부팅 턴은 읽기 전용 두 개만', () => {
|
||||
const r = selectToolsForTurn(tools, { ...base, message: 'boot' }, { ...flags, isBootStartupTurn: true });
|
||||
assert.deepEqual(names(r), ['coder_read_file']);
|
||||
assert.ok(bootAllowedTools.has('coder_list_files'));
|
||||
});
|
||||
|
||||
test('번역/프로젝트 세션은 도구 없음 — 엄격한 출력 형식을 도구 호출이 깨뜨리지 않게', () => {
|
||||
assert.deepEqual(selectToolsForTurn(tools, { ...base, message: 'x' }, { ...flags, isTranslateSession: true }), []);
|
||||
assert.deepEqual(selectToolsForTurn(tools, { ...base, message: 'x' }, { ...flags, isProjSession: true }), []);
|
||||
});
|
||||
|
||||
test('코드 에디터 세션은 차단 목록만 제외하고 전부 통과 (키워드 게이트 미적용)', () => {
|
||||
const r = selectToolsForTurn(tools, { ...base, message: '아무 말' }, { ...flags, isCodeAiSession: true });
|
||||
// 키워드가 없어도 coder_/shell 이 살아있어야 한다 — 에디터에선 매 턴이 코드 맥락이다.
|
||||
assert.ok(names(r).includes('coder_read_file'));
|
||||
assert.ok(names(r).includes('shell'));
|
||||
assert.ok(!names(r).includes('start_task'));
|
||||
assert.ok(!names(r).includes('image_edit'));
|
||||
assert.ok(codeAiBlockedTools.has('image_edit'));
|
||||
});
|
||||
|
||||
test('일반 채팅은 키워드 필터를 탄다', () => {
|
||||
const r = selectToolsForTurn(tools, { ...base, message: '안녕' }, flags);
|
||||
assert.deepEqual(names(r), ['memory_read', 'web_search']);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user