Files
connectai/src/agent/actions/calculate.ts
T
koriweb 47b3b9f93a v2.2.299~307: 아키텍처 수렴 + 채팅 정리 + 벤치마킹 강화 + Claude 구독 엔진
- v2.2.299 아키텍처 수렴: coreChat 통일(엔진 휴리스틱 3벌 제거), 기업 모드
  검색 오케스트레이터 승격, lib/execUtil(실행 래퍼 6곳·Python 탐지 3벌 단일화),
  lib/kstSchedule(워처 4개 nowInKst 통합), estimateTokens 통합, 설정 접근 규칙 명문화
- v2.2.300 채팅 화면 정리: LiveReasoningFilter(스트리밍 중 <think>/Harmony 추론
  토큰 단위 차단), 확신도·검토요청 footer 기본 숨김(계산·Reflection 은 유지)
- v2.2.301 문맥·의도 이해: [답변 전 이해 원칙] 상시 주입, 워크플로우 의도 브리핑,
  Report QA 루프(규칙 레지스트리+실측치+회귀 게이트, 블로그_v3 개념 이식)
- v2.2.302 /benchmark 비즈니스 렌즈(가격·수익·운영)+빌드 프롬프트 모드+QA 연계
- v2.2.303 handoff 모드(측정치 무손실 인수인계 문서)+/claude(Claude Code 터미널 위임)
- v2.2.304 이식성: 지식 경로 두뇌-상대 규약(pickWikiDir 상대 해석), 이사 체크리스트
- v2.2.305 Claude 구독 엔진: claude: 프로바이더(CLI 위임, 모델 드롭다운 자동 노출,
  coreChat 지원 — 워크플로우·QA도 구독 모델 가능)
- v2.2.306 Tone Guard: AI 상투어 금지 레지스트리(상담사 화법 실사례 8종+대조 예시)
- v2.2.307 /benchmark 레이아웃 골격(sectionRoles 결정론 분석, 롤링 배너 즉답),
  파트별 실패 격리, 합성 타임아웃 120→300초

검증: tsc 무오류 + jest 888 통과 + esbuild 정상

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 21:02:15 +09:00

92 lines
5.1 KiB
TypeScript

import { detectPython, execFileCapture, _resetPythonCache } from '../../lib/execUtil';
import type { HandlerContext } from './types';
// [코어 수렴] 실행 래퍼·Python 탐지는 lib/execUtil 단일 구현을 사용한다.
// 기존 소비자(runCode·테스트) 호환을 위해 재수출.
export { detectPython, _resetPythonCache };
/**
* <calculate> — 수학·논리·수치 계산을 Python 에 위임하는 액션 (ACTION 16).
*
* 배경: 로컬 소형 모델(4b급)의 대표 약점은 다단계 계산 중의 산술 실수다.
* "모델이 직접 계산"을 "모델은 코드로 변환만 → 실행은 Python → 모델은 결과 해석"
* 으로 바꾸면 계산 오류의 원천 자체가 사라진다 (모델은 판단만, 계산은 도구가).
*
* 흐름: 모델이 <calculate>print(...)</calculate> 를 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<void> {
const { aiMessage, report } = ctx;
const calcRegex = /<calculate>([\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 이 이 컴퓨터에 설치되어 있지 않아 <calculate> 를 실행할 수 없습니다. 계산을 직접 수행하되, 산술 결과는 신중히 검산해서 답하십시오.',
});
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에러를 참고해 코드를 고친 뒤 <calculate> 를 다시 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 를 추가해 <calculate> 를 다시 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이 실행 결과를 신뢰하고 그대로 사용해 답하십시오 (임의로 다시 암산하지 말 것).`,
});
}
}
}