v4.3.23: 시스템 프롬프트 조립을 system-prompt.ts로 분리 + 테스트 19개
tool-scope.ts와 같은 이유로 추출. 시스템 메시지는 모델 동작을 가장 크게 좌우 하는 단일 문자열인데, 2,900줄 함수 안에서 인라인으로 조립돼 결과를 보려면 실제 채팅을 보내 SSE의 tool_overhead를 읽는 수밖에 없었음. - src/gateway/chat/system-prompt.ts (신규) — buildChatSystemPrompt(input). 날짜/모델프로필/성격/스킬 컨텍스트는 호출자가 해결해 넘기므로 순수 함수 - tests/system-prompt.test.ts — 19개 - handle-chat.ts 2,992 → 2,936줄 (오늘 누적 3,131 → 2,936) 테스트가 고정한 핵심 불변식: 도구를 억제하는 규칙은 그 도구가 호출 가능한 한 반드시 함께 온다. image_edit이 스키마에 있으면 "함부로 편집하지 말라"가 없을 수 없다 — 이걸 사용자 문구로 게이팅했다면 정규식이 놓친 표현에서 규칙만 조용히 사라졌을 것. 반대로 tool-scope.ts의 키워드 게이팅은 최악의 경우가 "도구가 없어 못 한다"이므로 허용된다. 두 모듈 헤더에 이 구분을 명시해둠. 동작 무변경 검증: 리팩터 전후 tool_overhead가 "안녕" 3,574 / "RTX 5090 스펙 비교" 3,724로 바이트 단위 동일. 전체 66개 테스트 통과. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6461e73a5e
commit
4f31af0593
3 files changed
+278
-71
No files matched your search
@@ -71,6 +71,7 @@ import { createPreflightAdvisor, type PreflightAdvisorCtx } from './preflight-ad
|
||||
import { createBrowserDesktopAdvisors, type BrowserDesktopAdvisorCtx } from './browser-desktop-advisor';
|
||||
import type { SkillsManager } from '../skills-manager';
|
||||
import { selectToolsForTurn, bootAllowedTools, codeAiBlockedTools } from './tool-scope';
|
||||
import { buildChatSystemPrompt } from './system-prompt';
|
||||
|
||||
const MAX_TOOL_ROUNDS = 50;
|
||||
type ExecutionMode = 'interactive' | 'background_task' | 'heartbeat' | 'cron';
|
||||
@@ -629,80 +630,24 @@ async function handleChat(
|
||||
const now = new Date();
|
||||
const dateStr = now.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', timeZone: 'Asia/Seoul' });
|
||||
const timeStr = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', timeZone: 'Asia/Seoul' });
|
||||
const executionModeSystemBlock = (() => {
|
||||
if (executionMode === 'background_task') {
|
||||
return [
|
||||
'EXECUTION MODE: Autonomous background task.',
|
||||
'You are running without user oversight. Do not ask clarifying questions.',
|
||||
'Make decisions based on available context. Use tools precisely.',
|
||||
'If truly blocked: return a concise blocked reason and the best next action.',
|
||||
].join('\n');
|
||||
}
|
||||
if (executionMode === 'heartbeat') {
|
||||
return [
|
||||
'EXECUTION MODE: Heartbeat check.',
|
||||
'Run concise, decisive checks and report only actionable issues.',
|
||||
].join('\n');
|
||||
}
|
||||
if (executionMode === 'cron') {
|
||||
return [
|
||||
'EXECUTION MODE: Scheduled cron task.',
|
||||
'Act autonomously and complete the prompt without asking follow-up questions.',
|
||||
].join('\n');
|
||||
}
|
||||
return '';
|
||||
})();
|
||||
|
||||
// browser_* tools are excluded from the default tool list (dormantBrowserTools, parked
|
||||
// until a dedicated use case). The BROWSER RULE paragraph below only makes sense when the
|
||||
// model actually has browser tools to be tempted to misuse — skip it otherwise so it isn't
|
||||
// dead weight on every single main-chat turn.
|
||||
const toolNames = new Set(tools.map((t: any) => String(t?.function?.name || '')));
|
||||
const hasToolPrefix = (p: string) => tools.some((t: any) => String(t?.function?.name || '').startsWith(p));
|
||||
const hasBrowserTools = hasToolPrefix('browser_');
|
||||
const browserRuleBlock = hasBrowserTools
|
||||
? '\nBROWSER RULE: NEVER call browser_open, browser_snapshot, browser_click, browser_fill, browser_scroll, or any browser_* tool unless the user EXPLICITLY asks to use the browser (e.g. "브라우저로 열어줘", "Chrome으로 봐줘", "사이트 직접 들어가봐"). "열어줘" or "보여줘" alone is NOT a browser request — answer from knowledge, use web_fetch/web_search, or output the relevant URL/embed. Pasting a URL or asking a question is also NOT a browser request.'
|
||||
: '';
|
||||
|
||||
// Same tool-availability gating as BROWSER RULE above, applied to the other four blocks that
|
||||
// only exist to constrain a specific tool (2026-07-29). Each was unconditional, costing every
|
||||
// turn — including pure-conversation ones — the tokens for rules about tools the model may not
|
||||
// even have been given. Measured static cost: image-edit 90, media-gen 225, code-output 154,
|
||||
// package-install 79 ≈ 548 tokens per turn.
|
||||
//
|
||||
// Gate on the TOOL LIST, never on the user's message wording: a rule that suppresses a
|
||||
// dangerous tool call ("never call image_edit on an uploaded photo") must be present whenever
|
||||
// that tool is callable, and message-regex gating would drop it on exactly the paraphrase the
|
||||
// regex missed. Tool availability is the same condition that makes the rule matter at all.
|
||||
//
|
||||
// CHEMISTRY NOTATION (180) is deliberately left unconditional: it constrains output FORMAT,
|
||||
// not a tool, so there is no tool to key on, and this user's dental/medical questions can lead
|
||||
// the model into drawing structures without any chemistry keyword in the prompt — the ASCII-art
|
||||
// garbling it prevents would come back on precisely those turns.
|
||||
const imageEditRuleBlock = toolNames.has('image_edit')
|
||||
? '\nIMAGE EDITING RULE: NEVER call image_edit (or any editing tool) when a user uploads a photo without explicitly requesting edits. Uploading a photo is NOT a request to edit it. Only call image_edit when the user\'s message explicitly asks for an edit (e.g. "수채화로 바꿔줘", "회전해줘"). Violating this rule is a critical error.'
|
||||
: '';
|
||||
const mediaGenRuleBlock = (toolNames.has('image_generate') || toolNames.has('video_generate'))
|
||||
? '\nIMAGE/VIDEO GENERATION: When a user asks to create/draw/generate a NEW image from a description (no existing photo involved), call image_generate (local SDXL, 10-20 seconds by default). If the user explicitly asks for higher quality/detail/photorealism (e.g. "고품질로", "디테일 살려서"), pass quality="high" instead — this uses FLUX.1-schnell, noticeably better detail but 40-60 seconds total, so tell the user it\'ll take a bit before calling it. When they ask for a short video/clip/animation from a description, call video_generate (local LTX-Video, 30–90 seconds — tell the user it\'ll take a bit before calling it). All run entirely on local GPU hardware, no external API or cost. Do not confuse these with image_edit, which only modifies an existing uploaded/generated image.'
|
||||
: '';
|
||||
const codeOutputRuleBlock = hasToolPrefix('coder_')
|
||||
? '\nCODE OUTPUT: When writing code in a fenced code block, start with a filename comment on line 1: `# filename: snake_game.py` (Python), `// filename: app.js` (JS/C), `<!-- filename: index.html -->` (HTML). Never repeat code already written in this conversation. For modifications to existing files, use coder_overwrite_lines or coder_insert_lines (not coder_write_file — it only works for NEW files). All code changes are presented as diffs for the user to review before being applied. Write code directly — do not ask for permission.'
|
||||
: '';
|
||||
const packageInstallRuleBlock = (toolNames.has('shell') || toolNames.has('run_command'))
|
||||
? '\nPACKAGE INSTALL: NEVER run pip install, npm install, apt-get, or any package installation command. If a package is missing, just write the code and mention the package name in a comment — let the user decide whether to install it. Do NOT attempt to install packages yourself.'
|
||||
: '';
|
||||
// Resolved with the same call chatWithThinkingStream makes internally for its first
|
||||
// attempt. If that call later falls back to models.fallback mid-turn (quota/retirement),
|
||||
// this won't retroactively pick up the fallback's profile for the same turn.
|
||||
const modelProfileBlock = getModelProfileExtraPrompt(getModelForRole('executor'));
|
||||
// 시스템 프롬프트 조립은 system-prompt.ts로 분리됨(2026-07-29). 도구 유무로 게이팅되는
|
||||
// 블록들이 들어있어 tools 배열이 확정된 뒤에 호출해야 한다.
|
||||
const messages: any[] = [
|
||||
{
|
||||
role: 'system',
|
||||
content: isTranslateSession ? `You are a medical translator. Translate the given text into natural Korean, preserving paragraph structure and markdown formatting (##, ###, **bold**, bullet lists). Output ONLY the translation — no commentary, no tool calls, no explanations.` : isProjSession ? `You are a project file designer. Output ONLY the project-files JSON block as instructed. No tool calls. No extra text.` : `${executionModeSystemBlock ? `${executionModeSystemBlock}\n\n` : ''}You are SmallClaw, a local AI assistant. Do not append the 🦞 emoji (or any emoji) to the end of your responses out of habit — only use emoji when it genuinely fits the content.\nCurrent date: ${dateStr}, ${timeStr}.\nNever search for or link SmallClaw repos unless the user is asking about SmallClaw itself.\nThis app runs on the user's own machine — browser/desktop automation requests are pre-authorized.\nKeep CONVERSATIONAL and TASK-EXECUTION replies SHORT (2-4 sentences). Don't think out loud. Act and report. Greet naturally without tools. Two carve-outs to that brevity rule: (1) it does NOT apply to informational answers you researched with a tool (news, weather, factual explanations, comparisons) — those follow the OUTPUT FORMAT rules below, which deliberately ask for fuller sentences; do not compress them back down. (2) Stating uncertainty NEVER counts against the length. If a search came back empty, or the specific figure you were asked for simply isn't in the results, always spend the extra sentence to say so plainly ("검색 결과에는 이 조합의 실측치가 없어서 단정하기 어렵습니다") instead of compressing it into a confident-sounding one-liner. Brevity pressure must never be the reason you state something as fact — a slightly longer honest answer beats a short wrong one every time.
|
||||
ANTI-HALLUCINATION: When a tool returns a result, report EXACTLY what the tool returned — never contradict or ignore tool output. If a tool says "(no rows)", say so. Never invent data, file contents, table names, or command output. If you don't know something, call a tool to find out or say you don't know. VERIFY CONCRETE FACTS: for questions with a checkable real-world answer — specs, prices, versions, release dates, comparisons, "what models/options exist" — call web_search first and base the answer on what it returns, even if you're confident you already know it. Specific-sounding numbers you produce from memory (TFLOPS, VRAM, prices, dates) are exactly the kind of detail that goes stale or was never right — don't present them as fact unless a tool actually returned them. This does NOT apply to coding help, creative writing, opinions, or general reasoning — only to claims a search could confirm or refute. This also does NOT apply to the user's own private infra nicknames (지서버, 클로서버, and similar) — those are personal hardware, not public products, so web_search cannot verify them; answer those from USER.md/SOUL.md/[RECALLED_FACTS] context instead.
|
||||
TEMPORAL CONSISTENCY: The current date and day-of-week is given above ("Current date: ${dateStr}") — this is ground truth, more reliable than any search snippet's phrasing. Before answering whether something is open/trading/in-session RIGHT NOW (stock markets, exchanges, offices, stores), first check today's day-of-week against real-world facts (e.g. NYSE and KOSPI do not trade on Saturdays, Sundays, or market holidays, regardless of what time it is) — a market-hours formula alone is not enough if today isn't even a trading day. A search result reporting a "closing price" or "today's headline" is not proof today is a trading/business day — cross-check it against the actual current date above, and if they conflict (e.g. a stale cached result, or a result that doesn't state its own date), trust the current date and say so explicitly rather than presenting the search result as if it were live.${imageEditRuleBlock}${mediaGenRuleBlock}${browserRuleBlock}
|
||||
CHEMISTRY NOTATION: NEVER draw molecular structures as ASCII art (H/C/#/=/\\/| characters arranged to look like a diagram) — it always renders as garbled, misaligned text. Instead: for a formula or reaction, use LaTeX inside $...$ (e.g. $\\ce{C4H10}$, $\\ce{2H2 + O2 -> 2H2O}$ — mhchem extension is loaded). For an actual 2D structure with real bond lines (rings, branches), output a \`\`\`smiles\`\`\` code block containing the SMILES string (e.g. \`\`\`smiles\\nc1ccccc1\\n\`\`\` for benzene, \`\`\`smiles\\nCC(=O)Oc1ccccc1C(=O)O\\n\`\`\` for aspirin) — the client automatically renders it as a proper 2D diagram with bond lines.${codeOutputRuleBlock}${packageInstallRuleBlock}
|
||||
OUTPUT FORMAT: When presenting 3+ items (emails, search results, lists), always use a markdown table or structured bullet list with clear headers. Never dump them as a long paragraph. For news specifically: use a table with columns 제목|요약|출처, but write each 요약 as 2-3 full sentences covering the article's actual content — not a headline fragment restated. Include EVERY distinct article the news tool returned (it returns up to 10 per call and they are already filtered to the last 48 hours) — do not cherry-pick 3 of them into a "highlights" table. If several calls returned overlapping stories, merge duplicates but keep the union, aiming for a 8-10 row digest whenever that many distinct articles came back. For weather: do NOT force a table — explain current conditions and forecast in natural, fuller sentences (trend, precipitation chance, notable changes vs yesterday/normal), not just bare numbers.${modelProfileBlock}${callerContext ? '\n\n' + callerContext : ''}${browserStateCtx}${personalityCtx}${skillsManager.buildPromptContextForUser(username ? getUserWorkspace(username) : null, 16000, message)}`,
|
||||
content: buildChatSystemPrompt({
|
||||
executionMode,
|
||||
toolNames: tools.map((t: any) => String(t?.function?.name || '')),
|
||||
dateStr,
|
||||
timeStr,
|
||||
isTranslateSession,
|
||||
isProjSession,
|
||||
modelProfileBlock: getModelProfileExtraPrompt(getModelForRole('executor')),
|
||||
callerContext,
|
||||
browserStateCtx,
|
||||
personalityCtx,
|
||||
skillsCtx: skillsManager.buildPromptContextForUser(username ? getUserWorkspace(username) : null, 16000, message),
|
||||
}),
|
||||
},
|
||||
];
|
||||
// Emit the fixed-overhead size (system prompt + tool schemas) as soon as both are known —
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* system-prompt.ts
|
||||
*
|
||||
* Assembles the system message for a chat turn.
|
||||
*
|
||||
* Extracted from handleChat() on 2026-07-29, same reasoning as tool-scope.ts: this is the
|
||||
* single string that most determines how the model behaves, and it was built inline inside a
|
||||
* 2,900-line function where the only way to inspect the result was to send a real message and
|
||||
* read the tool_overhead SSE event back.
|
||||
*
|
||||
* Two rules worth keeping in mind when editing the blocks below:
|
||||
*
|
||||
* 1. TOOL-GATED, NOT MESSAGE-GATED. Blocks that exist to suppress a specific tool
|
||||
* (image edit / media gen / code output / package install / browser) are keyed on whether
|
||||
* that tool is in this turn's schema. They must never be keyed on the user's wording — a
|
||||
* suppression rule has to be present whenever the tool is callable, and a regex that misses
|
||||
* an unusual paraphrase would drop the rule on exactly the turn that needed it. Contrast
|
||||
* tool-scope.ts, where keyword gating is fine because the worst case is a missing tool.
|
||||
*
|
||||
* 2. CHEMISTRY NOTATION stays unconditional. It constrains output FORMAT rather than a tool,
|
||||
* so there is no tool to key on, and dental/medical questions can lead the model into
|
||||
* drawing structures with no chemistry keyword anywhere in the prompt.
|
||||
*
|
||||
* Pure: no config reads, no clock, no I/O. The caller resolves date, model profile, personality
|
||||
* and skill context and passes them in.
|
||||
*/
|
||||
|
||||
export interface SystemPromptInput {
|
||||
/** '' for normal chat; background_task / heartbeat / cron get an autonomy preamble. */
|
||||
executionMode?: string;
|
||||
/** Names of the tools offered THIS turn — drives the tool-gated blocks. */
|
||||
toolNames: readonly string[];
|
||||
/** Pre-formatted current date and time (Asia/Seoul) — ground truth for TEMPORAL CONSISTENCY. */
|
||||
dateStr: string;
|
||||
timeStr: string;
|
||||
/** Sessions with a strict output contract get a minimal prompt and no behavioural blocks. */
|
||||
isTranslateSession?: boolean;
|
||||
isProjSession?: boolean;
|
||||
/** Per-model reminder from config (models.profiles[x].extraSystemPrompt), already formatted. */
|
||||
modelProfileBlock?: string;
|
||||
callerContext?: string;
|
||||
browserStateCtx?: string;
|
||||
personalityCtx?: string;
|
||||
/** Skill context blob the caller resolved for this user/message. */
|
||||
skillsCtx?: string;
|
||||
}
|
||||
|
||||
export function buildChatSystemPrompt(input: SystemPromptInput): string {
|
||||
const executionMode = String(input.executionMode || '');
|
||||
const dateStr = input.dateStr;
|
||||
const timeStr = input.timeStr;
|
||||
const isTranslateSession = !!input.isTranslateSession;
|
||||
const isProjSession = !!input.isProjSession;
|
||||
const modelProfileBlock = input.modelProfileBlock || '';
|
||||
const callerContext = input.callerContext || '';
|
||||
const browserStateCtx = input.browserStateCtx || '';
|
||||
const personalityCtx = input.personalityCtx || '';
|
||||
const skillsCtx = input.skillsCtx || '';
|
||||
const tools = input.toolNames.map(n => ({ function: { name: n } }));
|
||||
|
||||
const executionModeSystemBlock = (() => {
|
||||
if (executionMode === 'background_task') {
|
||||
return [
|
||||
'EXECUTION MODE: Autonomous background task.',
|
||||
'You are running without user oversight. Do not ask clarifying questions.',
|
||||
'Make decisions based on available context. Use tools precisely.',
|
||||
'If truly blocked: return a concise blocked reason and the best next action.',
|
||||
].join('\n');
|
||||
}
|
||||
if (executionMode === 'heartbeat') {
|
||||
return [
|
||||
'EXECUTION MODE: Heartbeat check.',
|
||||
'Run concise, decisive checks and report only actionable issues.',
|
||||
].join('\n');
|
||||
}
|
||||
if (executionMode === 'cron') {
|
||||
return [
|
||||
'EXECUTION MODE: Scheduled cron task.',
|
||||
'Act autonomously and complete the prompt without asking follow-up questions.',
|
||||
].join('\n');
|
||||
}
|
||||
return '';
|
||||
})();
|
||||
|
||||
// browser_* tools are excluded from the default tool list (dormantBrowserTools, parked
|
||||
// until a dedicated use case). The BROWSER RULE paragraph below only makes sense when the
|
||||
// model actually has browser tools to be tempted to misuse — skip it otherwise so it isn't
|
||||
// dead weight on every single main-chat turn.
|
||||
const toolNames = new Set(tools.map((t: any) => String(t?.function?.name || '')));
|
||||
const hasToolPrefix = (p: string) => tools.some((t: any) => String(t?.function?.name || '').startsWith(p));
|
||||
const hasBrowserTools = hasToolPrefix('browser_');
|
||||
const browserRuleBlock = hasBrowserTools
|
||||
? '\nBROWSER RULE: NEVER call browser_open, browser_snapshot, browser_click, browser_fill, browser_scroll, or any browser_* tool unless the user EXPLICITLY asks to use the browser (e.g. "브라우저로 열어줘", "Chrome으로 봐줘", "사이트 직접 들어가봐"). "열어줘" or "보여줘" alone is NOT a browser request — answer from knowledge, use web_fetch/web_search, or output the relevant URL/embed. Pasting a URL or asking a question is also NOT a browser request.'
|
||||
: '';
|
||||
|
||||
// Same tool-availability gating as BROWSER RULE above, applied to the other four blocks that
|
||||
// only exist to constrain a specific tool (2026-07-29). Each was unconditional, costing every
|
||||
// turn — including pure-conversation ones — the tokens for rules about tools the model may not
|
||||
// even have been given. Measured static cost: image-edit 90, media-gen 225, code-output 154,
|
||||
// package-install 79 ≈ 548 tokens per turn.
|
||||
//
|
||||
// Gate on the TOOL LIST, never on the user's message wording: a rule that suppresses a
|
||||
// dangerous tool call ("never call image_edit on an uploaded photo") must be present whenever
|
||||
// that tool is callable, and message-regex gating would drop it on exactly the paraphrase the
|
||||
// regex missed. Tool availability is the same condition that makes the rule matter at all.
|
||||
//
|
||||
// CHEMISTRY NOTATION (180) is deliberately left unconditional: it constrains output FORMAT,
|
||||
// not a tool, so there is no tool to key on, and this user's dental/medical questions can lead
|
||||
// the model into drawing structures without any chemistry keyword in the prompt — the ASCII-art
|
||||
// garbling it prevents would come back on precisely those turns.
|
||||
const imageEditRuleBlock = toolNames.has('image_edit')
|
||||
? '\nIMAGE EDITING RULE: NEVER call image_edit (or any editing tool) when a user uploads a photo without explicitly requesting edits. Uploading a photo is NOT a request to edit it. Only call image_edit when the user\'s message explicitly asks for an edit (e.g. "수채화로 바꿔줘", "회전해줘"). Violating this rule is a critical error.'
|
||||
: '';
|
||||
const mediaGenRuleBlock = (toolNames.has('image_generate') || toolNames.has('video_generate'))
|
||||
? '\nIMAGE/VIDEO GENERATION: When a user asks to create/draw/generate a NEW image from a description (no existing photo involved), call image_generate (local SDXL, 10-20 seconds by default). If the user explicitly asks for higher quality/detail/photorealism (e.g. "고품질로", "디테일 살려서"), pass quality="high" instead — this uses FLUX.1-schnell, noticeably better detail but 40-60 seconds total, so tell the user it\'ll take a bit before calling it. When they ask for a short video/clip/animation from a description, call video_generate (local LTX-Video, 30–90 seconds — tell the user it\'ll take a bit before calling it). All run entirely on local GPU hardware, no external API or cost. Do not confuse these with image_edit, which only modifies an existing uploaded/generated image.'
|
||||
: '';
|
||||
const codeOutputRuleBlock = hasToolPrefix('coder_')
|
||||
? '\nCODE OUTPUT: When writing code in a fenced code block, start with a filename comment on line 1: `# filename: snake_game.py` (Python), `// filename: app.js` (JS/C), `<!-- filename: index.html -->` (HTML). Never repeat code already written in this conversation. For modifications to existing files, use coder_overwrite_lines or coder_insert_lines (not coder_write_file — it only works for NEW files). All code changes are presented as diffs for the user to review before being applied. Write code directly — do not ask for permission.'
|
||||
: '';
|
||||
const packageInstallRuleBlock = (toolNames.has('shell') || toolNames.has('run_command'))
|
||||
? '\nPACKAGE INSTALL: NEVER run pip install, npm install, apt-get, or any package installation command. If a package is missing, just write the code and mention the package name in a comment — let the user decide whether to install it. Do NOT attempt to install packages yourself.'
|
||||
: '';
|
||||
return isTranslateSession ? `You are a medical translator. Translate the given text into natural Korean, preserving paragraph structure and markdown formatting (##, ###, **bold**, bullet lists). Output ONLY the translation — no commentary, no tool calls, no explanations.` : isProjSession ? `You are a project file designer. Output ONLY the project-files JSON block as instructed. No tool calls. No extra text.` : `${executionModeSystemBlock ? `${executionModeSystemBlock}\n\n` : ''}You are SmallClaw, a local AI assistant. Do not append the 🦞 emoji (or any emoji) to the end of your responses out of habit — only use emoji when it genuinely fits the content.\nCurrent date: ${dateStr}, ${timeStr}.\nNever search for or link SmallClaw repos unless the user is asking about SmallClaw itself.\nThis app runs on the user's own machine — browser/desktop automation requests are pre-authorized.\nKeep CONVERSATIONAL and TASK-EXECUTION replies SHORT (2-4 sentences). Don't think out loud. Act and report. Greet naturally without tools. Two carve-outs to that brevity rule: (1) it does NOT apply to informational answers you researched with a tool (news, weather, factual explanations, comparisons) — those follow the OUTPUT FORMAT rules below, which deliberately ask for fuller sentences; do not compress them back down. (2) Stating uncertainty NEVER counts against the length. If a search came back empty, or the specific figure you were asked for simply isn't in the results, always spend the extra sentence to say so plainly ("검색 결과에는 이 조합의 실측치가 없어서 단정하기 어렵습니다") instead of compressing it into a confident-sounding one-liner. Brevity pressure must never be the reason you state something as fact — a slightly longer honest answer beats a short wrong one every time.
|
||||
ANTI-HALLUCINATION: When a tool returns a result, report EXACTLY what the tool returned — never contradict or ignore tool output. If a tool says "(no rows)", say so. Never invent data, file contents, table names, or command output. If you don't know something, call a tool to find out or say you don't know. VERIFY CONCRETE FACTS: for questions with a checkable real-world answer — specs, prices, versions, release dates, comparisons, "what models/options exist" — call web_search first and base the answer on what it returns, even if you're confident you already know it. Specific-sounding numbers you produce from memory (TFLOPS, VRAM, prices, dates) are exactly the kind of detail that goes stale or was never right — don't present them as fact unless a tool actually returned them. This does NOT apply to coding help, creative writing, opinions, or general reasoning — only to claims a search could confirm or refute. This also does NOT apply to the user's own private infra nicknames (지서버, 클로서버, and similar) — those are personal hardware, not public products, so web_search cannot verify them; answer those from USER.md/SOUL.md/[RECALLED_FACTS] context instead.
|
||||
TEMPORAL CONSISTENCY: The current date and day-of-week is given above ("Current date: ${dateStr}") — this is ground truth, more reliable than any search snippet's phrasing. Before answering whether something is open/trading/in-session RIGHT NOW (stock markets, exchanges, offices, stores), first check today's day-of-week against real-world facts (e.g. NYSE and KOSPI do not trade on Saturdays, Sundays, or market holidays, regardless of what time it is) — a market-hours formula alone is not enough if today isn't even a trading day. A search result reporting a "closing price" or "today's headline" is not proof today is a trading/business day — cross-check it against the actual current date above, and if they conflict (e.g. a stale cached result, or a result that doesn't state its own date), trust the current date and say so explicitly rather than presenting the search result as if it were live.${imageEditRuleBlock}${mediaGenRuleBlock}${browserRuleBlock}
|
||||
CHEMISTRY NOTATION: NEVER draw molecular structures as ASCII art (H/C/#/=/\\/| characters arranged to look like a diagram) — it always renders as garbled, misaligned text. Instead: for a formula or reaction, use LaTeX inside $...$ (e.g. $\\ce{C4H10}$, $\\ce{2H2 + O2 -> 2H2O}$ — mhchem extension is loaded). For an actual 2D structure with real bond lines (rings, branches), output a \`\`\`smiles\`\`\` code block containing the SMILES string (e.g. \`\`\`smiles\\nc1ccccc1\\n\`\`\` for benzene, \`\`\`smiles\\nCC(=O)Oc1ccccc1C(=O)O\\n\`\`\` for aspirin) — the client automatically renders it as a proper 2D diagram with bond lines.${codeOutputRuleBlock}${packageInstallRuleBlock}
|
||||
OUTPUT FORMAT: When presenting 3+ items (emails, search results, lists), always use a markdown table or structured bullet list with clear headers. Never dump them as a long paragraph. For news specifically: use a table with columns 제목|요약|출처, but write each 요약 as 2-3 full sentences covering the article's actual content — not a headline fragment restated. Include EVERY distinct article the news tool returned (it returns up to 10 per call and they are already filtered to the last 48 hours) — do not cherry-pick 3 of them into a "highlights" table. If several calls returned overlapping stories, merge duplicates but keep the union, aiming for a 8-10 row digest whenever that many distinct articles came back. For weather: do NOT force a table — explain current conditions and forecast in natural, fuller sentences (trend, precipitation chance, notable changes vs yesterday/normal), not just bare numbers.${modelProfileBlock}${callerContext ? '\n\n' + callerContext : ''}${browserStateCtx}${personalityCtx}${skillsCtx}`;
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* system-prompt.test.ts
|
||||
*
|
||||
* The system message is the single biggest lever on model behaviour, and until 2026-07-29 it
|
||||
* was assembled inline inside handleChat() where the only way to see the result was to send a
|
||||
* real chat message and read tool_overhead off an SSE event.
|
||||
*
|
||||
* The property these tests protect is narrow but important: a rule that suppresses a tool must
|
||||
* be present whenever that tool is callable. Dropping one is silent — nothing errors, the model
|
||||
* just loses a guardrail on exactly the turn that needed it.
|
||||
*/
|
||||
|
||||
import { test, describe } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { buildChatSystemPrompt, type SystemPromptInput } from '../src/gateway/chat/system-prompt';
|
||||
|
||||
const build = (over: Partial<SystemPromptInput> = {}) => buildChatSystemPrompt({
|
||||
toolNames: [],
|
||||
dateStr: 'Tuesday, July 29, 2026',
|
||||
timeStr: '03:00 PM',
|
||||
...over,
|
||||
});
|
||||
|
||||
describe('무조건 들어가는 블록', () => {
|
||||
test('도구가 하나도 없어도 핵심 규칙은 남는다', () => {
|
||||
const p = build();
|
||||
for (const block of ['ANTI-HALLUCINATION', 'TEMPORAL CONSISTENCY', 'OUTPUT FORMAT']) {
|
||||
assert.ok(p.includes(block), `${block} 누락`);
|
||||
}
|
||||
});
|
||||
|
||||
test('CHEMISTRY NOTATION은 도구와 무관하게 항상 — 출력 형식 제약이라 키로 삼을 도구가 없다', () => {
|
||||
assert.ok(build().includes('CHEMISTRY NOTATION'));
|
||||
assert.ok(build({ toolNames: ['web_search'] }).includes('CHEMISTRY NOTATION'));
|
||||
});
|
||||
|
||||
test('현재 날짜/시각이 주입된다 — TEMPORAL CONSISTENCY의 근거값', () => {
|
||||
const p = build({ dateStr: 'Monday, January 5, 2026', timeStr: '09:30 AM' });
|
||||
assert.ok(p.includes('Monday, January 5, 2026'));
|
||||
assert.ok(p.includes('09:30 AM'));
|
||||
});
|
||||
|
||||
test('불확실성 표현은 길이 제한에서 면제된다는 조항이 살아있다', () => {
|
||||
// 이 조항이 빠지면 1-2문장 압박이 "모른다"를 밀어내고 환각을 확신형 한 줄로 포장한다.
|
||||
const p = build();
|
||||
assert.ok(/Stating uncertainty NEVER counts against the length/i.test(p));
|
||||
});
|
||||
});
|
||||
|
||||
describe('도구 게이팅 — 도구가 있을 때만 규칙이 붙는다', () => {
|
||||
const cases: Array<[string, string[], string]> = [
|
||||
['IMAGE EDITING RULE', ['image_edit'], 'image_edit'],
|
||||
['IMAGE/VIDEO GENERATION', ['image_generate'], 'image_generate'],
|
||||
['IMAGE/VIDEO GENERATION', ['video_generate'], 'video_generate'],
|
||||
['CODE OUTPUT', ['coder_read_file'], 'coder_*'],
|
||||
['PACKAGE INSTALL', ['shell'], 'shell'],
|
||||
['PACKAGE INSTALL', ['run_command'], 'run_command'],
|
||||
['BROWSER RULE', ['browser_open'], 'browser_*'],
|
||||
];
|
||||
|
||||
for (const [block, toolNames, label] of cases) {
|
||||
test(`${block} — ${label} 있을 때만`, () => {
|
||||
assert.ok(build({ toolNames }).includes(block), `${label} 있는데 ${block} 없음`);
|
||||
assert.ok(!build({ toolNames: ['web_search'] }).includes(block), `${label} 없는데 ${block} 붙음`);
|
||||
});
|
||||
}
|
||||
|
||||
test('억제 규칙은 도구가 호출 가능한 한 반드시 함께 온다', () => {
|
||||
// 핵심 불변식: image_edit이 스키마에 있으면 "함부로 편집하지 말라"가 없을 수 없다.
|
||||
// 사용자 문구로 게이팅했다면 정규식이 놓친 표현에서 이 규칙이 사라졌을 것.
|
||||
const p = build({ toolNames: ['image_edit'] });
|
||||
assert.ok(p.includes('IMAGE EDITING RULE'));
|
||||
assert.ok(/NEVER call image_edit/i.test(p));
|
||||
});
|
||||
});
|
||||
|
||||
describe('전용 세션 — 엄격한 출력 계약', () => {
|
||||
test('번역 세션은 번역 지시만 받는다', () => {
|
||||
const p = build({ isTranslateSession: true, toolNames: ['image_edit', 'shell'] });
|
||||
assert.ok(/medical translator/i.test(p));
|
||||
// 행동 규칙 블록이 섞이면 출력 형식이 오염된다.
|
||||
assert.ok(!p.includes('ANTI-HALLUCINATION'));
|
||||
assert.ok(!p.includes('IMAGE EDITING RULE'));
|
||||
});
|
||||
|
||||
test('프로젝트 파일 세션도 마찬가지', () => {
|
||||
const p = build({ isProjSession: true });
|
||||
assert.ok(/project file designer/i.test(p));
|
||||
assert.ok(!p.includes('OUTPUT FORMAT'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('실행 모드 프리앰블', () => {
|
||||
test('배경 작업/하트비트/크론은 자율 실행 지시가 앞에 붙는다', () => {
|
||||
assert.ok(/Autonomous background task/i.test(build({ executionMode: 'background_task' })));
|
||||
assert.ok(/Heartbeat check/i.test(build({ executionMode: 'heartbeat' })));
|
||||
assert.ok(/Scheduled cron task/i.test(build({ executionMode: 'cron' })));
|
||||
});
|
||||
|
||||
test('일반 대화에는 붙지 않는다', () => {
|
||||
assert.ok(!/EXECUTION MODE/i.test(build({ executionMode: 'interactive' })));
|
||||
assert.ok(!/EXECUTION MODE/i.test(build()));
|
||||
});
|
||||
});
|
||||
|
||||
describe('주입되는 컨텍스트', () => {
|
||||
test('모델 프로필/호출자/성격/스킬 컨텍스트가 그대로 실린다', () => {
|
||||
const p = build({
|
||||
modelProfileBlock: '\nMODEL-SPECIFIC NOTE: 테스트 노트',
|
||||
callerContext: 'CALLER_MARK',
|
||||
personalityCtx: 'PERSONA_MARK',
|
||||
skillsCtx: 'SKILL_MARK',
|
||||
browserStateCtx: 'BROWSER_MARK',
|
||||
});
|
||||
for (const m of ['테스트 노트', 'CALLER_MARK', 'PERSONA_MARK', 'SKILL_MARK', 'BROWSER_MARK']) {
|
||||
assert.ok(p.includes(m), `${m} 누락`);
|
||||
}
|
||||
});
|
||||
|
||||
test('선택 입력이 없어도 undefined 문자열이 새지 않는다', () => {
|
||||
const p = build();
|
||||
assert.ok(!p.includes('undefined'), '프롬프트에 "undefined" 유출');
|
||||
});
|
||||
});
|
||||
|
||||
describe('비용', () => {
|
||||
test('도구 없는 최소 프롬프트가 조건부 블록 전부 켠 것보다 확실히 작다', () => {
|
||||
const bare = build().length;
|
||||
const full = build({ toolNames: ['image_edit', 'image_generate', 'coder_read_file', 'shell', 'browser_open'] }).length;
|
||||
assert.ok(full > bare, '조건부 블록이 전혀 늘지 않음 — 게이팅이 깨졌을 가능성');
|
||||
// 게이팅이 통째로 무력화되면(항상 켜짐) 이 차이가 0이 된다.
|
||||
assert.ok(full - bare > 1500, `조건부 블록 총량이 예상보다 작음 (${full - bare}자)`);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user