v2.2.292-296: 메모리·발열 최적화 + Pixel Office 완전 제거 + 소형 모델 추론 강화(calculate/run_code/지식 스코프)

- v2.2.292 메모리·발열: 헬스체크 워크스페이스 쓰기→fs.access(워처 연쇄 제거)·git 검사 비동기 30분 주기,
  웹뷰 retainContextWhenHidden 정리(채팅만 유지), 브레인 인덱스 유휴 30분 TTL 해제,
  채팅 DOM 200개 상한, @lmstudio/sdk 지연 로드
- v2.2.293 Pixel Office 시각화 폐기: astraOffice 모듈·사이드바 매니저 3종·스프라이트 17MB 삭제,
  sidebarProvider collector 섹션 통삭제 (기업 모드 판단 로직 무변경, vsix 12.2MB→1.3MB)
- v2.2.294 도구 메뉴 'NotebookLM 백엔드 실행/종료' 버튼: OS 자동 감지, 프로젝트 자동 탐색+폴더 선택 저장,
  포트 정리 폴백 (터미널 없이 Research 백엔드 켜고 끄기)
- v2.2.295 추론 강화 1탄: [ACTION 16] <calculate> Python 계산 위임(결과 재주입·자가수정 루프),
  단계별 지식 스코프(General+Specialty, 결정적 도메인 분류, 설정 지식·기억 탭 UI)
- v2.2.296 추론 강화 2탄: [ACTION 17] <run_code> 실행 확인(stdout 회수→수정→재실행 루프),
  문법 오류 재주입 자가수정, 도구 라우팅 힌트(dynamicBlocks), Grounding rescue 도메인 스코프 확장
- 검증: jest 818 통과(신규 29개), tsc 무오류, esbuild 정상

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-05 18:59:47 +09:00
parent fa397d7fa1
commit bb7cd6b879
466 changed files with 1285 additions and 6588 deletions
+115
View File
@@ -0,0 +1,115 @@
import { execFile } from 'child_process';
import type { HandlerContext } from './types';
/**
* <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; // 모델 컨텍스트 보호
/** 감지된 Python 실행 파일 캐시 (프로세스 생존 동안 유지, null = 미탐지/없음). */
let _pythonCmd: string | null | undefined;
function execFileP(cmd: string, args: string[], timeout: number): Promise<{ stdout: string; stderr: string }> {
return new Promise((resolve, reject) => {
execFile(cmd, args, { timeout, maxBuffer: 512 * 1024 }, (err, stdout, stderr) => {
if (err) reject(Object.assign(err, { stdout: String(stdout || ''), stderr: String(stderr || '') }));
else resolve({ stdout: String(stdout || ''), stderr: String(stderr || '') });
});
});
}
/** python3 → python → py 순으로 실행 가능한 인터프리터 탐지 (OS 자동 대응, run_code 도 공유). */
export async function detectPython(): Promise<string | null> {
if (_pythonCmd !== undefined) return _pythonCmd;
for (const cmd of ['python3', 'python', 'py']) {
try {
await execFileP(cmd, ['--version'], 3_000);
_pythonCmd = cmd;
return cmd;
} catch { /* 다음 후보 */ }
}
_pythonCmd = null;
return null;
}
/** 테스트용 — 캐시 초기화. */
export function _resetPythonCache(): void { _pythonCmd = undefined; }
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);
try {
const { stdout } = await execFileP(python, ['-I', '-c', code], CALC_TIMEOUT_MS);
const out = 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이 실행 결과를 신뢰하고 그대로 사용해 답하십시오 (임의로 다시 암산하지 말 것).`,
});
}
} catch (err: any) {
// 에러도 재주입 — 모델이 코드를 고쳐 재시도하는 자가수정 루프.
const tail = String(err?.stderr || err?.message || err).trim().split('\n').slice(-8).join('\n').slice(0, 1200);
const timedOut = err?.killed || /ETIMEDOUT|timed? ?out/i.test(String(err?.message || ''));
report.push(`❌ Calculate failed: ${label}`);
ctx.chatHistory.push({
role: 'system', internal: true,
content: `[Result of calculate — ERROR]\n${timedOut ? `실행이 ${CALC_TIMEOUT_MS / 1000}초 안에 끝나지 않아 중단되었습니다. 더 효율적인 방법으로 다시 시도하십시오.` : `\`\`\`\n${tail}\n\`\`\`\n에러를 참고해 코드를 고친 뒤 <calculate> 를 다시 emit 하십시오. (표준 라이브러리만 사용 가능)`}`,
});
}
}
}