import { detectPython, execFileCapture, _resetPythonCache } from '../../lib/execUtil'; import type { HandlerContext } from './types'; // [코어 수렴] 실행 래퍼·Python 탐지는 lib/execUtil 단일 구현을 사용한다. // 기존 소비자(runCode·테스트) 호환을 위해 재수출. export { detectPython, _resetPythonCache }; /** * — 수학·논리·수치 계산을 Python 에 위임하는 액션 (ACTION 16). * * 배경: 로컬 소형 모델(4b급)의 대표 약점은 다단계 계산 중의 산술 실수다. * "모델이 직접 계산"을 "모델은 코드로 변환만 → 실행은 Python → 모델은 결과 해석" * 으로 바꾸면 계산 오류의 원천 자체가 사라진다 (모델은 판단만, 계산은 도구가). * * 흐름: 모델이 print(...) 를 emit → 여기서 `python -I -c` 로 * 실행(10초 타임아웃) → stdout/stderr 를 chatHistory 에 internal system 메시지로 * 주입 → agent 루프가 '컨텍스트 주입됨'을 감지해 자동 후속 턴을 돌리고 모델이 * 결과를 해석한다. 에러도 그대로 주입되므로 모델이 코드를 고쳐 다시 emit 하는 * 자가수정 루프가 자연히 성립한다 (read_file 과 동일한 재주입 메커니즘). * * 신뢰 모델: run_command(실제 터미널 실행)와 동일한 로컬 신뢰 수준. 다만 * `-I`(isolated) 플래그로 사용자 site-packages/환경변수 영향을 차단하고, * 타임아웃·출력 상한·회당 실행 횟수 상한을 둔다. */ const CALC_TIMEOUT_MS = 10_000; const MAX_CALC_PER_TURN = 4; // 한 턴에 과도한 실행 방지 const MAX_CODE_CHARS = 4_000; const MAX_OUTPUT_CHARS = 4_000; // 모델 컨텍스트 보호 export async function applyCalculateActions(ctx: HandlerContext): Promise { const { aiMessage, report } = ctx; const calcRegex = /([\s\S]*?)<\/calculate>/gi; let match: RegExpExecArray | null; let ran = 0; while ((match = calcRegex.exec(aiMessage)) !== null) { if (ran >= MAX_CALC_PER_TURN) { report.push(`⚠️ Calculate skipped: 한 턴 실행 한도(${MAX_CALC_PER_TURN}회) 초과`); break; } const code = match[1].trim(); if (!code) continue; if (code.length > MAX_CODE_CHARS) { report.push(`❌ Calculate blocked: 코드가 너무 깁니다 (${code.length}자 > ${MAX_CODE_CHARS})`); continue; } ran++; const python = await detectPython(); if (!python) { report.push('❌ Calculate unavailable: Python 미설치'); ctx.chatHistory.push({ role: 'system', internal: true, content: '[Result of calculate — UNAVAILABLE]\nPython 이 이 컴퓨터에 설치되어 있지 않아 를 실행할 수 없습니다. 계산을 직접 수행하되, 산술 결과는 신중히 검산해서 답하십시오.', }); return; // 인터프리터가 없으면 나머지 calculate 도 전부 불가 } const label = code.replace(/\s+/g, ' ').slice(0, 60); const r = await execFileCapture(python, ['-I', '-c', code], { timeoutMs: CALC_TIMEOUT_MS, maxBuffer: 512 * 1024 }); if (r.timedOut || r.code !== 0) { // 에러도 재주입 — 모델이 코드를 고쳐 재시도하는 자가수정 루프. const tail = (r.stderr || r.stdout || `exit ${r.code}`).trim().split('\n').slice(-8).join('\n').slice(0, 1200); report.push(`❌ Calculate failed: ${label}`); ctx.chatHistory.push({ role: 'system', internal: true, content: `[Result of calculate — ERROR]\n${r.timedOut ? `실행이 ${CALC_TIMEOUT_MS / 1000}초 안에 끝나지 않아 중단되었습니다. 더 효율적인 방법으로 다시 시도하십시오.` : `\`\`\`\n${tail}\n\`\`\`\n에러를 참고해 코드를 고친 뒤 를 다시 emit 하십시오. (표준 라이브러리만 사용 가능)`}`, }); continue; } const out = r.stdout.trim(); if (!out) { // print 누락 — 모델이 스스로 고치도록 힌트를 재주입한다. report.push(`⚠️ Calculated (no output): ${label}`); ctx.chatHistory.push({ role: 'system', internal: true, content: '[Result of calculate — EMPTY OUTPUT]\n코드는 실행됐지만 출력이 없습니다. 결과는 반드시 print(...) 로 출력해야 합니다. print 를 추가해 를 다시 emit 하십시오.', }); } else { const capped = out.length > MAX_OUTPUT_CHARS ? out.slice(0, MAX_OUTPUT_CHARS) + '\n… (truncated)' : out; report.push(`🧮 Calculated: ${label}`); ctx.chatHistory.push({ role: 'system', internal: true, content: `[Result of calculate]\n\`\`\`\n${capped}\n\`\`\`\n이 실행 결과를 신뢰하고 그대로 사용해 답하십시오 (임의로 다시 암산하지 말 것).`, }); } } }