#!/usr/bin/env node /** * patch-r2-tierize-input-cap.js · 2026-04-26 · P3 * 为 pre-compact-handoff.js 的 tierize() 输入加 5 MB 上限, * 防极端 transcript (单条 tool_result > 5 MB) 拖慢 PreCompact hook * * Idempotent: sentinel 'R2-INPUT-CAP-V2' * 风险: 极低 — 仅对 size > 5MB 的单条记录截断, 不影响小输出 */ 'use strict'; const fs = require('fs'); const path = require('path'); const HOOK = path.join(process.env.HOME || process.env.USERPROFILE || 'C:/Users/leesu', '.claude', 'hooks', 'pre-compact-handoff.js'); const SENTINEL = 'R2-INPUT-CAP-V2'; // 自适应行尾 (源文件可能 CRLF) function detectEol(s) { return s.includes('\r\n') ? '\r\n' : '\n'; } function withEol(s, eol) { return s.replace(/\r?\n/g, eol); } const OLD_LF = " const size = Buffer.byteLength(text, 'utf8');\n if (size < 500) continue;\n items.push({ size, text, tool_use_id: part.tool_use_id });"; const NEW_LF = " const size = Buffer.byteLength(text, 'utf8');\n if (size < 500) continue;\n // R2-INPUT-CAP-V2: 单条 tool_result > 5MB 截断, 防 tierize 正则扫描超时\n const MAX_ITEM_BYTES = 5 * 1024 * 1024;\n const safeText = size > MAX_ITEM_BYTES ? text.slice(0, MAX_ITEM_BYTES) : text;\n items.push({ size, text: safeText, tool_use_id: part.tool_use_id, capped: size > MAX_ITEM_BYTES });"; try { let raw = fs.readFileSync(HOOK, 'utf8'); if (raw.includes(SENTINEL)) { console.log('[r2-cap] already applied, skip'); process.exit(0); } const eol = detectEol(raw); const OLD = withEol(OLD_LF, eol); const NEW = withEol(NEW_LF, eol); if (!raw.includes(OLD)) { console.error('[r2-cap] anchor not found, abort'); process.exit(1); } fs.writeFileSync(HOOK + '.bak.r2cap.' + Date.now(), raw, 'utf8'); raw = raw.replace(OLD, NEW); fs.writeFileSync(HOOK, raw, 'utf8'); console.log('[r2-cap] applied'); } catch (e) { console.error('[r2-cap] error:', e.message); process.exit(1); }