billion-context 0.0.12075-pr.2425.f90bb4e → 0.0.12076-pr.5475.f1fdd18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/dsh-native.js +1 -1
- package/dist/agent/omp-native.js +1 -1
- package/dist/agent/opencode-native.js +1 -1
- package/dist/agent/opencode.js +1 -1
- package/dist/agent/pi-native.js +1 -1
- package/dist/build-info.json +1 -1
- package/dist/index.js +1 -1
- package/docs/configuration.md +1 -1
- package/docs/configuration.zh-CN.md +1 -0
- package/package.json +1 -1
package/dist/agent/dsh-native.js
CHANGED
|
@@ -272,7 +272,7 @@ ${e}`;continue}out.push(e);headerOnlyIdx=hasRef&&nl===-1?out.length-1:-1}else{ou
|
|
|
272
272
|
Some tool results end with a ${ABSORB_PROMPT_MARKER} instruction. When you see one, your IMMEDIATE next action must be calling ${toolName}({ ref, summary }) \u2014 distill that tool result's essentials into summary: outcome, key values, exact paths:lines, error text verbatim, decisions. The original output is then removed from context; your ${toolName} summary becomes the only durable record of it, so distill carefully. Never call another tool or answer the user before absorbing a marked result. Do not re-run the original tool afterwards \u2014 work from your summary. ${toolName} calls are ordinary context: the regular compression system may fold them later like any other message.`}function isAcpOrConfiguredTool(toolName,cfg){if(!toolName)return false;if(toolName===cfg.toolName)return true;return ACP_TOOL_NAMES.has(toolName)||BLOCK_OP_TOOL_NAMES.has(toolName)}function isAbsorbCandidate(msg,config,latest,protectedCallIds,failedCompressCallIds){if(msg.contentType!=="tool-result"||!msg.toolCallId)return false;if(isStoredPlaceholderText(msg.text??""))return false;const cfg=resolveAbsorbConfig(config);if(isAcpOrConfiguredTool(msg.toolName,cfg))return false;if(isMessageProtectedWithPairing(msg,config,protectedCallIds??NO_PROTECTED_CALLS,failedCompressCallIds))return false;if(latest&&isMessageLatestProtected(msg,latest))return false;for(const pattern of cfg.excludeTools){if(msg.toolName&&matchToolPattern(msg.toolName,pattern))return false}if(cfg.mediaOnly&&!hasMediaPayload(msg))return false;return true}function hideAbsorbedMessages(messages,state8){const records=state8.absorbed??[];if(records.length===0)return messages;const hidden=new Set;for(const record3 of records){if(record3.callMessageId)hidden.add(record3.callMessageId);if(record3.resultMessageId)hidden.add(record3.resultMessageId)}return messages.filter(msg=>!hidden.has(msg.id))}function appendAbsorbPrompts(messages,state8,config,tokenCount,countTokens){const cfg=resolveAbsorbConfig(config);if(!cfg.enabled)return{messages,promptedCount:0};const limit=config.modelContextLimit;if(cfg.contextThresholdPct>0&&limit>0&&tokenCount<cfg.contextThresholdPct*limit){return{messages,promptedCount:0}}const absorbedIds=new Set;for(const record3 of state8.absorbed??[]){if(record3.resultMessageId)absorbedIds.add(record3.resultMessageId)}let promptedCount=0;const latest=collectLatestProtected(messages,config);const protectedCallIds=collectProtectedToolCallIds(messages,config);const failedCompressCallIds=collectFailedCompressCallIds(messages,config);const out=messages.map(msg=>{if(!isAbsorbCandidate(msg,config,latest,protectedCallIds,failedCompressCallIds))return msg;if(absorbedIds.has(msg.id))return msg;const text2=msg.text??"";if(text2.includes(ABSORB_PROMPT_MARKER))return msg;const tokens=countTokens(text2);const mediaExempt=cfg.mediaOnly&&hasMediaPayload(msg);if(!mediaExempt&&tokens<cfg.minToolTokens)return msg;const ref=refForRaw(state8.messageRefs,msg.id);if(!ref||ref===BLOCKED_REF)return msg;promptedCount++;return{...msg,text:text2+"\n\n"+buildAbsorbPrompt(ref,tokens,cfg.toolName)}});return{messages:out,promptedCount}}function parseAbsorbInput(input,callId,onWarn){let obj=null;if(typeof input==="string"){try{const parsed=JSON.parse(input);if(parsed&&typeof parsed==="object"){obj=parsed}}catch{obj=null}}else if(input&&typeof input==="object"){obj=input}if(!obj){onWarn?.(`[acp-absorb-input] rejected: not an object (${typeof input})`);return null}const ref=pickString(obj,"ref","messageId","of");const summary=pickString(obj,"summary","content");if(typeof ref!=="string"||typeof summary!=="string"){onWarn?.(`[acp-absorb-input] rejected: need ref (string) + summary (string); keys: ${Object.keys(obj).join(",")}`);return null}return{ref:ref.trim(),summary,...callId?{absorbCallId:callId}:{}}}function pickString(obj,...keys){for(const key2 of keys){const value=obj[key2];if(typeof value==="string")return value}return void 0}function applyAbsorb(input){const countTokens=input.countTokens??(text2=>Math.ceil(text2.length/4));const summary=input.summary?.trim()??"";if(!summary){return{state:input.state,ok:false,resultText:"absorb failed: summary is empty \u2014 provide the distilled key info of the tool result."}}const cfg=resolveAbsorbConfig(input.config);const rawId=rawForRef(input.state.messageRefs,input.ref.trim());if(!rawId){return{state:input.state,ok:false,resultText:`absorb failed: ref ${input.ref} does not exist in this session (it may be hidden, already compressed, or stale).`}}const existing=(input.state.absorbed??[]).find(record22=>record22.resultMessageId===rawId);if(existing){return{state:input.state,ok:true,resultText:`already absorbed (${input.ref}) \u2014 no change.`}}const target=input.messages.find(m2=>m2.id===rawId);if(!target){return{state:input.state,ok:false,resultText:`absorb failed: ref ${input.ref} is not visible in this session (hidden or compressed).`}}if(target.contentType!=="tool-result"){return{state:input.state,ok:false,resultText:`absorb failed: ref ${input.ref} is a ${target.contentType}, not a tool result.`}}if(cfg.mediaOnly&&!hasMediaPayload(target)){return{state:input.state,ok:false,resultText:`absorb failed: ${input.ref} carries no media payload \u2014 absorb is scoped to image-bearing results (compress.absorb.mediaOnly).`}}if(isAcpOrConfiguredTool(target.toolName,cfg)){return{state:input.state,ok:false,resultText:`absorb failed: ${target.toolName} is an ACP-managed tool result \u2014 it is not absorbable.`}}if(isMessageProtectedWithPairing(target,input.config,collectProtectedToolCallIds(input.messages,input.config),collectFailedCompressCallIds(input.messages,input.config))||isMessageLatestProtected(target,collectLatestProtected(input.messages,input.config))){return{state:input.state,ok:false,resultText:`absorb failed: ${target.toolName} is a protected tool \u2014 its results must stay visible.`}}if(!target.toolCallId){return{state:input.state,ok:false,resultText:`absorb failed: ref ${input.ref} has no tool-call id \u2014 cannot pair it for hiding.`}}const call=input.messages.find(m2=>m2.contentType==="tool-call"&&m2.toolCallId===target.toolCallId);const tokens=countTokens(target.text??"");const summaryTokens=countTokens(summary);const record3={toolCallId:target.toolCallId,callMessageId:call?.id??"",resultMessageId:target.id,...input.absorbCallId?{absorbCallId:input.absorbCallId}:{},summary,tokensReclaimed:tokens,createdAt:Date.now()};const state8={...input.state,absorbed:[...input.state.absorbed??[],record3],stats:{...input.state.stats,absorbedTokens:(input.state.stats.absorbedTokens??0)+tokens},viewLatches:void 0};const bloat=summaryTokens>=tokens&&tokens>0?` WARNING: your summary (~${formatTokenCount(summaryTokens)} tokens) is not smaller than the original (~${formatTokenCount(tokens)} tokens) \u2014 distill harder next time.`:"";return{state:state8,ok:true,resultText:`absorbed ${input.ref} (~${formatTokenCount(tokens)} tokens \u2192 summary ~${formatTokenCount(summaryTokens)}). The original tool output is now hidden; your summary is the durable record.${bloat}`}}function isPlainObject(v2){if(typeof v2!=="object"||v2===null||Array.isArray(v2))return false;const p2=Object.getPrototypeOf(v2);return p2===null||p2===Object.prototype}function classifyCrushText(text2){const trimmed=text2.trim();if(trimmed.startsWith("{")&&trimmed.endsWith("}")||trimmed.startsWith("[")&&trimmed.endsWith("]"))return"json";if(detectLanguage(text2)!==null)return"code";return"log"}function crushText(text2,options={}){const countTokens=options.countTokens??defaultCountTokens;const minReduction=options.minReduction??DEFAULT_CRUSH_CONFIG.minReduction;const meta=options.meta??{};if(text2.length===0||text2.length>MAX_INPUT_CHARS)return null;const rawTok=countTokens(text2);if(rawTok<=0)return null;const kind=classifyCrushText(text2);const wanted=options.plugins??registeredPlugins();for(const plugin of wanted){let res;try{if(!Array.isArray(plugin.kinds)||!plugin.kinds.includes(kind))continue;res=plugin.run(text2,meta)}catch{continue}if(!res||typeof res.text!=="string"||res.text===""||res.text===text2)continue;const newTok=countTokens(res.text);const reduction=(rawTok-newTok)/rawTok;if(reduction<minReduction)continue;if(kind==="log"&&res.lossy&&!errorLinesSurvive(text2,res.text))continue;const out={text:res.text,strategy:plugin.id,lossy:res.lossy};if(res.stats)out.stats=res.stats;return out}return null}function canonOf(v2,cache22){if(!isPlainObject(v2)&&!Array.isArray(v2))return JSON.stringify(v2)??"null";const key2=v2;const hit=cache22.get(key2);if(hit!==void 0)return hit;let s3;if(Array.isArray(v2)){s3=`[${v2.map(e=>canonOf(e,cache22)).join(",")}]`}else{const entries2=Object.entries(v2).map(([k2,val])=>`${JSON.stringify(k2)}:${canonOf(val,cache22)}`).sort();s3=`{${entries2.join(",")}}`}cache22.set(key2,s3);return s3}function strLen(v2){return JSON.stringify(v2).length}function compactValue(v2,depth,stats2,cache22){if(depth>MAX_DEPTH||stats2.folds>=MAX_FOLDS)return v2;if(Array.isArray(v2))return compactArray(v2,depth,stats2,cache22);if(isPlainObject(v2)){let changed=false;const out={};for(const[k2,val]of Object.entries(v2)){const nv=compactValue(val,depth+1,stats2,cache22);out[k2]=nv;if(nv!==val)changed=true}return changed?out:v2}return v2}function compactArray(arr,depth,stats2,cache22){const n=arr.length;if(n<RUN_MIN&&n<HOIST_MIN)return arr.map(e=>compactValue(e,depth+1,stats2,cache22));if(stats2.folds>=MAX_FOLDS)return arr;const plainStats={folds:0};const plain=arr.map(e=>compactValue(e,depth+1,plainStats,cache22));let winner=plain;let winnerLen=strLen(plain);let winnerFolds=plainStats.folds;if(n>=RUN_MIN){const rf=buildRunFold(arr,depth,cache22);if(rf&&rf.len<winnerLen){winner=rf.value;winnerLen=rf.len;winnerFolds=rf.folds}}if(n>=HOIST_MIN&&arr.every(e=>isPlainObject(e))){const hc=buildConstHoist(arr,depth,cache22);if(hc&&hc.len<winnerLen){winner=hc.value;winnerLen=hc.len;winnerFolds=hc.folds}}stats2.folds+=winnerFolds;return winner}function isRunMarker(v2){return isPlainObject(v2)&&v2[CRUSH_KEY]==="identical-run"}function buildRunFold(arr,depth,cache22){const n=arr.length;const canon2=arr.map(e=>canonOf(e,cache22));const segs=[];let runs=0;let i=0;while(i<n){let j2=i;while(j2+1<n&&canon2[j2+1]===canon2[i])j2++;const runLen=j2-i+1;if(runLen>=RUN_MIN){segs.push({[CRUSH_KEY]:"identical-run",count:runLen,item:arr[i]});runs++}else{for(let k2=i;k2<=j2;k2++)segs.push(arr[k2])}i=j2+1}if(runs===0)return null;const inner={folds:0};const final=segs.map(s3=>isRunMarker(s3)?{...s3,item:compactValue(s3.item,depth+1,inner,cache22)}:compactValue(s3,depth+1,inner,cache22));return{value:final,len:strLen(final),folds:runs+inner.folds}}function buildConstHoist(arr,depth,cache22){const n=arr.length;const keys=[];const seen=new Set;for(const e of arr){for(const k2 of Object.keys(e)){if(!seen.has(k2)){seen.add(k2);keys.push(k2)}}}const first=arr[0];if(!first)return null;const constKeys=[];for(const k2 of keys){if(!(k2 in first))continue;const c0=canonOf(first[k2],cache22);let constant=true;for(let i=1;i<n;i++){const row=arr[i];if(!(k2 in row)||canonOf(row[k2],cache22)!==c0){constant=false;break}}if(constant)constKeys.push(k2)}if(constKeys.length===0)return null;const constSet=new Set(constKeys);const constObj={};for(const k2 of constKeys)constObj[k2]=first[k2];const items=arr.map(e=>{const o={};for(const[k2,v2]of Object.entries(e)){if(!constSet.has(k2))o[k2]=v2}return o});const hasVarying=items.some(o=>Object.keys(o).length>0);const inner={folds:0};const env={[CRUSH_KEY]:"rows",rows:n,const:compactValue(constObj,depth+1,inner,cache22)};if(hasVarying)env.items=items.map(it2=>compactValue(it2,depth+1,inner,cache22));const len=strLen(env);if(len>=strLen(arr))return null;return{value:env,len,folds:1+inner.folds}}function crushJson(text2){const parsed=JSON.parse(text2);const cache22=new Map;const stats2={folds:0};const out=compactValue(parsed,0,stats2,cache22);if(stats2.folds===0)return null;const s3=JSON.stringify(out);return s3.length<text2.length?s3:null}function detectLanguage(text2){const sample=text2.split(/\r?\n/).slice(0,300);let py=0;let js2=0;for(const line of sample){if(/^\s*#!.*python/.test(line))py+=4;if(/^\s*(async\s+)?def\s+\w/.test(line)||/^\s*class\s+\w/.test(line))py+=2;if(/\bfrom\s+['"]/.test(line)||/^\s*import\s+['"]/.test(line))js2+=2;else if(/^\s*(import|from)\s+[A-Za-z_]\w*/.test(line))py+=1;if(/^\s*(function\b|const\s|let\s|var\s)/.test(line))js2+=2;if(/=>/.test(line))js2+=1;if(/^\s*(public|private|protected|static|final|void|return)\b/.test(line))js2+=1;if(/;\s*$/.test(line)&&line.trim().length>0)js2+=1;if(/\bself\./.test(line)||/^\s*(elif|except|yield)\b/.test(line))py+=1;if(/\bconsole\.log\b|\brequire\s*\(|module\.exports|\bawait\s/.test(line))js2+=1}const MARGIN=1.5;if(py>=3&&py>js2*MARGIN)return"python";if(js2>=4&&js2>py*MARGIN)return"js";return null}function finalizeTrimmed(original,emitted){if(emitted.length>=original.split(/\r?\n/).length)return null;const out=emitted.join("\n")+(original.endsWith("\n")?"\n":"");return out.length<original.length*CODE_KEEP_RATIO?out:null}function trimPython(text2){const lines=text2.split(/\r?\n/);const emitted=[];let pending=0;const flush=()=>{if(pending>0){emitted.push(`# [acp-crush: elided ${pending} line${pending===1?"":"s"}]`);pending=0}};let state8="code";let quote="";let isDocstring=false;let blankRun=0;let atModuleStart=true;let pendingDefClass=false;let docstringSlot=false;const classifySig=codePart=>{const t=codePart.trim();if(/^(async\s+)?(def|class)\b/.test(t))pendingDefClass=true;if(t.endsWith(":")){docstringSlot=pendingDefClass;pendingDefClass=false}else if(t.length>0&&!t.startsWith("@")){docstringSlot=false}atModuleStart=false};for(let li2=0;li2<lines.length;li2++){const line=lines[li2];if(state8==="triple"){const close=findTripleClose(line,quote);if(close===-1){if(isDocstring)pending++;else emitted.push(line);continue}state8="code";const rest=line.slice(close+3).trim();if(rest.length>0){flush();emitted.push(line);classifySig(rest)}else{if(isDocstring)pending++;else emitted.push(line)}isDocstring=false;docstringSlot=false;pendingDefClass=false;atModuleStart=false;blankRun=0;continue}if(line.trim().length===0){blankRun++;if(blankRun>=3){flush();emitted.push("");blankRun=1}continue}if(li2===0&&line.startsWith("#!")){flush();emitted.push(line);blankRun=0;continue}const m2=line.match(/^\s*("""|''')/);if(m2){flush();const q2=m2[1];const opensHere=line.indexOf(q2);const closeOnSameLine=findTripleClose(line.slice(opensHere+3),q2);if(closeOnSameLine!==-1){const restAfter=line.slice(opensHere+3+closeOnSameLine+3).trim();if(restAfter.length>0){emitted.push(line);classifySig(restAfter)}else if(atModuleStart||docstringSlot){pending++;atModuleStart=false;docstringSlot=false;pendingDefClass=false}else{emitted.push(line)}blankRun=0;continue}state8="triple";quote=q2;isDocstring=atModuleStart||docstringSlot;atModuleStart=false;docstringSlot=false;if(!isDocstring)emitted.push(line);blankRun=0;continue}const probe=findCommentOrTriple(line);if(probe.kind==="comment-full"){pending++;continue}if(probe.kind==="triple-mid"){flush();state8="triple";quote=probe.quote;isDocstring=false;emitted.push(line);classifySig(line.slice(0,probe.idx));blankRun=0;continue}flush();emitted.push(line);classifySig(line);blankRun=0}if(state8==="triple")return null;flush();return finalizeTrimmed(text2,emitted)}function findTripleClose(line,quote){let i=0;while(i<line.length){if(line[i]==="\\"){i+=2;continue}if(line.startsWith(quote,i))return i;i++}return-1}function findCommentOrTriple(line){let i=0;let inStr=null;while(i<line.length){const c=line[i];if(inStr){if(c==="\\")i+=2;else if(c===inStr)inStr=null;else i++;continue}if(c==="'"||c==='"'){inStr=c;i++;continue}if(c==="#"){return{kind:line.slice(0,i).trim().length===0?"comment-full":"none",idx:i,quote:""}}if(line.startsWith('"""',i)||line.startsWith("'''",i)){return{kind:"triple-mid",idx:i,quote:line.slice(i,i+3)}}i++}return{kind:"none",idx:-1,quote:""}}function scanTemplateRest(line,from,st2){let m2=st2.mode;let q2=st2.quote;let d=st2.depth;let i=from;while(i<line.length){const c=line[i];if(m2==="str"){if(c==="\\")i+=2;else if(c===q2)m2="expr";else i++;continue}if(m2==="expr"){if(c==="'"||c==='"'){q2=c;m2="str";i++;continue}if(c==="`")return{mode:m2,quote:q2,depth:d,closed:false,bail:true,consumed:0};if(c==="{")d++;else if(c==="}"){d--;if(d===0)m2="tpl"}i++;continue}if(c==="\\"){i+=2;continue}if(c==="`")return{mode:"tpl",quote:"",depth:0,closed:true,bail:false,consumed:i-from+1};if(c==="$"&&line[i+1]==="{"){m2="expr";d=1;i+=2;continue}i++}return{mode:m2,quote:q2,depth:d,closed:false,bail:false,consumed:0}}function regexAllowedAfter(prev){if(prev===null)return true;if(/[A-Za-z0-9_]/.test(prev))return false;return!".'\"`) ]".includes(prev)}function prevSigChar(line,i){for(let j2=i-1;j2>=0;j2--){const c=line[j2];if(c===" "||c===" ")continue;return c}return null}function scanRegexLiteral(line,i){let j2=i+1;let inClass=false;while(j2<line.length){const c=line[j2];if(c==="\\"){j2+=2;continue}if(inClass){if(c==="]")inClass=false}else if(c==="["){inClass=true}else if(c==="/"){let f2=j2+1;while(f2<line.length&&/[a-z]/i.test(line[f2]))f2++;return f2}j2++}return null}function scanJsCodeLine(line){let i=0;let inStr=null;while(i<line.length){const c=line[i];if(inStr){if(c==="\\")i+=2;else if(c===inStr)inStr=null;else i++;continue}if(c==="'"||c==='"'){inStr=c;i++;continue}if(c==="`"){const r=scanTemplateRest(line,i,{mode:"tpl",quote:"",depth:0});if(r.bail)return{kind:"code",bail:true};if(!r.closed)return{kind:"template-open",tmpl:{mode:r.mode,quote:r.quote,depth:r.depth}};i+=r.consumed;continue}if(c==="/"){const nxt=line[i+1];if(nxt==="/"){return{kind:line.slice(0,i).trim().length===0?"comment-full":"code"}}if(nxt!=="*"){if(regexAllowedAfter(prevSigChar(line,i))){const end=scanRegexLiteral(line,i);if(end!==null){i=end;continue}}i++;continue}const close=line.indexOf("*/",i+2);const before=line.slice(0,i).trim().length>0;if(close===-1)return{kind:before?"block-open-mid":"block-open-only"};const rest=line.slice(close+2).trim();if(rest.length===0)return{kind:before?"code":"comment-full"};i=close+2;continue}i++}return{kind:"code"}}function trimJsTs(text2){const lines=text2.split(/\r?\n/);const emitted=[];let pending=0;const flush=()=>{if(pending>0){emitted.push(`// [acp-crush: elided ${pending} line${pending===1?"":"s"}]`);pending=0}};let state8="code";let tmpl={mode:"tpl",quote:"",depth:0};let blankRun=0;for(const line of lines){if(state8==="block"){const close=line.indexOf("*/");if(close===-1){pending++;continue}state8="code";if(line.slice(close+2).trim().length===0)pending++;else{flush();emitted.push(line)}blankRun=0;continue}if(state8==="template"){const r=scanTemplateRest(line,0,tmpl);if(r.bail)return null;tmpl={mode:r.mode,quote:r.quote,depth:r.depth};if(r.closed)state8="code";emitted.push(line);blankRun=0;continue}if(line.trim().length===0){blankRun++;if(blankRun>=3){flush();emitted.push("");blankRun=1}continue}const scan=scanJsCodeLine(line);if(scan.bail)return null;if(scan.kind==="comment-full"){pending++;continue}if(scan.kind==="block-open-only"){pending++;state8="block";continue}if(scan.kind==="block-open-mid"){flush();state8="block";emitted.push(line);blankRun=0;continue}if(scan.kind==="template-open"){flush();state8="template";tmpl=scan.tmpl??{mode:"tpl",quote:"",depth:0};emitted.push(line);blankRun=0;continue}flush();emitted.push(line);blankRun=0}if(state8!=="code")return null;flush();return finalizeTrimmed(text2,emitted)}function crushCode(text2){const lang=detectLanguage(text2);if(lang===null)return null;if(lang==="python")return trimPython(text2);return trimJsTs(text2)}function classifyLevel(line){for(const[level,re2]of LEVEL_PATTERNS){if(re2.test(line))return level}return"unknown"}function isLogSummaryLine(line){if(line.startsWith("===")||line.startsWith("---"))return true;let d=0;while(d<line.length&&line.charCodeAt(d)>=48&&line.charCodeAt(d)<=57)d++;if(d>0&&line[d]===" "){const rest=line.slice(d+1);if(rest.startsWith("passed")||rest.startsWith("failed")||rest.startsWith("skipped")||rest.startsWith("error")||rest.startsWith("warning"))return true}for(const prefix of["Test ","Tests ","Tests:","Test:","Suite ","Suites ","Suites:","Suite:"]){if(line.startsWith(prefix)){const m2=line.slice(prefix.length).match(/\S/);if(m2!==null&&m2[0].charCodeAt(0)>=48&&m2[0].charCodeAt(0)<=57)return true}}if(line.startsWith("TOTAL")||line.startsWith("Total")||line.startsWith("Summary"))return true;for(const prefix of["Build","Compile","Test"]){if(line.startsWith(prefix)&&(line.includes("succeeded")||line.includes("failed")||line.includes("complete")))return true}return false}function isDigitChar(c){return c>="0"&&c<="9"}function isAsciiAlnum(c){const n=c.charCodeAt(0);return n>=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57}function hasLineColSuffix(s3){for(let i=0;i+1<s3.length;i++){if(s3[i]===":"&&isDigitChar(s3[i+1])){let j2=i+1;while(j2<s3.length&&isDigitChar(s3[j2]))j2++;if(j2+1<s3.length&&s3[j2]===":"&&isDigitChar(s3[j2+1]))return true}}return false}function isPythonFileFrame(s3){return s3.startsWith('File "')&&s3.includes('", line ')&&s3.length>0&&isDigitChar(s3[s3.length-1])}function isJsAtFrame(s3){return s3.startsWith("at ")&&s3.includes("(")&&s3.includes(")")&&hasLineColSuffix(s3)}function isJavaAtFrame(s3){if(!s3.startsWith("at ")||!s3.includes("("))return false;const open=s3.indexOf("(");const body=s3.slice(3,open);if(body.length===0)return false;for(const c of body){if(!(isAsciiAlnum(c)||c==="."||c==="_"||c==="$"||c==="/"))return false}return true}function isRustPanicOpener(s3){return s3.startsWith("thread '")&&s3.includes("panicked at")}function isGoroutineHeader(line){if(!line.startsWith("goroutine "))return false;const rest=line.slice(10);let d=0;while(d<rest.length&&isDigitChar(rest[d]))d++;return d>0&&rest.slice(d).startsWith(" [")}function isGoPanicOpener(line){return line.startsWith("panic: ")||line.startsWith("fatal error: ")||isGoroutineHeader(line)}function isGoFileFrame(line){return line.startsWith(" ")&&line.includes(".go:")&&line.includes(" +0x")}function isGoCallFrame(line){if(line.startsWith("created by "))return true;if(line.startsWith(" ")||line.startsWith(" ")||!line.endsWith(")"))return false;const open=line.indexOf("(");if(open===-1)return false;const symbol=line.slice(0,open);if(symbol.length===0||!symbol.includes("."))return false;for(const c of symbol){if(!(isAsciiAlnum(c)||c==="."||c==="_"||c==="/"||c==="*"))return false}return true}function isDotnetFrame(s3){return s3.startsWith("at ")&&s3.includes(") in ")&&s3.includes(":line ")}function isDotnetExceptionHead(trimmed){const colon=trimmed.indexOf(":");if(colon===-1)return false;const head=trimmed.slice(0,colon);if(!head.endsWith("Exception")||!head.includes("."))return false;for(const c of head){if(!(isAsciiAlnum(c)||c==="."||c==="_"||c==="`"||c==="+"))return false}return true}function isRustBacktraceFrame(s3){const t=s3.trimStart();let i=0;while(i<t.length&&isDigitChar(t[i]))i++;if(i===0||t[i]!==":")return false;i++;while(i<t.length&&t[i]===" ")i++;const rest=t.slice(i);if(!rest.startsWith("0x"))return false;let h=0;for(const c of rest.slice(2)){if(c>="0"&&c<="9"||c>="a"&&c<="f"||c>="A"&&c<="F")h++;else break}return h>0}function isJavaMoreSummary(trimmed){if(!trimmed.startsWith("... "))return false;const rest=trimmed.slice(4);let d=0;while(d<rest.length&&isDigitChar(rest[d]))d++;return d>0&&rest.slice(d).trim()==="more"}function traceFlavorFor(line){const t=line.trimStart();if(t.startsWith("Traceback (most recent call last)")||isPythonFileFrame(t))return"py";if(t.startsWith("Unhandled exception.")||isDotnetFrame(t))return"dotnet";if(isJsAtFrame(t))return"js";if(isJavaAtFrame(t))return"java";if(t.startsWith("--> ")&&hasLineColSuffix(t))return"rust-error";if(isRustPanicOpener(t)||t.startsWith("stack backtrace:")||isRustBacktraceFrame(line))return"rust-backtrace";if(isGoPanicOpener(line))return"go-panic";return null}function traceTerminates(flavor,line,linesSoFar){const t=line.trimStart();switch(flavor){case"py":{const indentedOrBlank=line.startsWith(" ")||line.startsWith(" ")||line.length===0;const continuation=t.startsWith("Traceback")||t.startsWith("File ")||t.startsWith("During handling")||t.startsWith("The above exception");if(indentedOrBlank||continuation)return false;return!(t.length>0&&t[0]>="A"&&t[0]<="Z")}case"js":return!t.startsWith("at ")&&line.length!==0;case"java":{const chain=t.startsWith("Caused by:")||t.startsWith("Suppressed:")||isJavaMoreSummary(t);return!t.startsWith("at ")&&!chain&&line.length!==0}case"dotnet":{if(line.length===0)return false;const continues=t.startsWith("at ")||t.startsWith("--->")||t.startsWith("--- End of")||isDotnetExceptionHead(t);return!continues}case"rust-error":return!t.startsWith("--> ")&&line.length!==0;case"rust-backtrace":{if(line.length===0||linesSoFar===1)return false;const isFrame=t.length>0&&isDigitChar(t[0]);const continuation=line.startsWith(" ")||line.startsWith(" ")||t.startsWith("stack backtrace:")||t.startsWith("note: run with");return!isFrame&&!continuation}case"go-panic":{if(line.length===0)return false;const continues=line.startsWith(" ")||isGoroutineHeader(line)||isGoCallFrame(line)||line.startsWith("panic: ")||line.startsWith("fatal error: ")||line.startsWith("[signal ");return!continues}}}function scoreLogLine(l){const base=l.level==="error"||l.level==="fail"?1:l.level==="warn"?.5:l.level==="info"||l.level==="unknown"?.1:l.level==="debug"?.05:.02;return Math.min(base+(l.isStack?.3:0)+(l.isSummary?.4:0),1)}function parseLogLines(lines){const out=new Array(lines.length);let active=null;let traceLines=0;for(let i=0;i<lines.length;i++){const line=lines[i];const entry={i,content:line,level:classifyLevel(line),isStack:false,isSummary:isLogSummaryLine(line),score:0};if(active!==null){const flavor=active;if(traceLines>=LOG_STACK_MAX_LINES||traceTerminates(flavor,line,traceLines)){const capHit=traceLines>=LOG_STACK_MAX_LINES;active=null;traceLines=0;const nf=traceFlavorFor(line);if(nf!==null){active=nf;traceLines=1;entry.isStack=true}else if(capHit&&!traceTerminates(flavor,line,2)){active=flavor;traceLines=1;entry.isStack=true}}else{entry.isStack=true;traceLines++}}else{const f2=traceFlavorFor(line);if(f2!==null){active=f2;traceLines=1;entry.isStack=true}}entry.score=scoreLogLine(entry);out[i]=entry}return out}function selectWithFirstLast(arr,maxCount){if(arr.length<=maxCount)return arr.slice();const out=[];const seen=new Set;const push=l=>{if(seen.add(l.i))out.push(l)};push(arr[0]);push(arr[arr.length-1]);if(out.length<maxCount){const byScore=arr.slice().sort((a,b2)=>b2.score-a.score||a.i-b2.i);for(const l of byScore){if(!seen.has(l.i)){push(l);if(out.length>=maxCount)break}}}return out}function normalizeForDedupe(content){let splitAt=content.length;for(let i=0;i<content.length;i++){if(content[i]===":"||content[i]==="="){splitAt=i;break}}const suffix=content.slice(splitAt).replace(/\d+/g,"N").replace(/0x[0-9a-fA-F]+/g,"ADDR").replace(/\/[\w/]+\//g,"/PATH/");return content.slice(0,splitAt)+suffix}function isFrameLine(content){const t=content.trimStart();return t.startsWith("at ")||t.startsWith('File "')&&t.includes('", line ')||isRustBacktraceFrame(content)||isGoFileFrame(content)||isGoCallFrame(content)}function isChainHeadLine(content){const t=content.trimStart();return t.startsWith("Caused by:")||t.startsWith("Suppressed:")||t.startsWith("... ")||t.startsWith("--->")||t.startsWith("--- End of")||t.startsWith("During handling")||t.startsWith("The above exception")}function isRuntimeFrame(content){const t=content.trimStart();return RUNTIME_FRAME_PREFIXES.some(p2=>t.startsWith(p2))||RUNTIME_FRAME_MARKERS.some(m2=>content.includes(m2))}function collapseTraceFrames(stack,headFrames,appFrames){const kept=[];const dropped=new Set;let framesSeen=0;let appKept=0;let runStart=-1;let runLen=0;let prevDropped=false;const flushRun=()=>{if(runStart!==-1){kept.push({i:runStart,content:` [... ${runLen} frames collapsed]`,level:"unknown",isStack:true,isSummary:false,score:.8});runStart=-1;runLen=0}};for(const line of stack){if(isFrameLine(line.content)&&!isChainHeadLine(line.content)){framesSeen++;const runtime=isRuntimeFrame(line.content);const keep=framesSeen<=headFrames||!runtime&&appKept<appFrames;if(keep){if(!runtime)appKept++;flushRun();kept.push(line);prevDropped=false}else{if(runStart===-1)runStart=line.i;runLen++;dropped.add(line.i);prevDropped=true}}else if(prevDropped&&(line.content.startsWith(" ")||line.content.startsWith(" "))&&!isChainHeadLine(line.content)){runLen++;dropped.add(line.i)}else{flushRun();kept.push(line);prevDropped=false}}flushRun();return{kept,dropped}}function selectLogLines(all){const errors=[];const fails=[];const warnings=[];const summaries=[];const stacks=[];let current=[];for(const l of all){if(l.level==="error")errors.push(l);else if(l.level==="fail")fails.push(l);else if(l.level==="warn")warnings.push(l);if(l.isStack)current.push(l);else if(current.length>0){stacks.push(current);current=[]}if(l.isSummary)summaries.push(l)}if(current.length>0)stacks.push(current);const selected=new Map;for(const l of selectWithFirstLast(errors,LOG_MAX_ERRORS))selected.set(l.i,l);for(const l of selectWithFirstLast(fails,LOG_MAX_ERRORS))selected.set(l.i,l);const seenWarn=new Set;const dedupedWarnings=[];for(const w2 of warnings){const key2=normalizeForDedupe(w2.content);if(!seenWarn.has(key2)){seenWarn.add(key2);dedupedWarnings.push(w2)}}for(const w2 of dedupedWarnings.slice(0,LOG_MAX_WARNINGS))selected.set(w2.i,w2);for(const stack of stacks.slice(0,LOG_MAX_STACK_TRACES)){if(stack.length>LOG_STACK_MAX_LINES){const collapsed=collapseTraceFrames(stack,LOG_TRACE_HEAD_FRAMES,LOG_TRACE_APP_FRAMES);for(const i of collapsed.dropped)selected.delete(i);for(const l of collapsed.kept.slice(0,LOG_STACK_MAX_LINES))selected.set(l.i,l)}else{for(const l of stack)selected.set(l.i,l)}}for(const s3 of summaries)selected.set(s3.i,s3);for(const idx of Array.from(selected.keys())){const lo2=Math.max(0,idx-LOG_ERROR_CONTEXT);const hi2=Math.min(all.length,idx+LOG_ERROR_CONTEXT+1);for(let i=lo2;i<hi2;i++){if(i!==idx&&!selected.has(i))selected.set(i,all[i])}}let ordered=Array.from(selected.values());if(ordered.length>LOG_MAX_TOTAL_LINES){ordered.sort((a,b2)=>b2.score-a.score||a.i-b2.i);ordered=ordered.slice(0,LOG_MAX_TOTAL_LINES);ordered.sort((a,b2)=>a.i-b2.i)}return ordered}function formatLogOutput(selected,all){const count=lv=>all.reduce((n,l)=>l.level===lv?n+1:n,0);const output=selected.map(l=>l.content);const omitted=all.length-selected.length;if(omitted>0){const parts=[];const e=count("error");const f2=count("fail");const w2=count("warn");const inf=count("info");if(e>0)parts.push(`${e} ERROR`);if(f2>0)parts.push(`${f2} FAIL`);if(w2>0)parts.push(`${w2} WARN`);if(inf>0)parts.push(`${inf} INFO`);if(parts.length>0)output.push(`[${omitted} lines omitted: ${parts.join(", ")}]`)}return output.join("\n")}function detectLogFormat(lines){const sample=lines.slice(0,100);let best="generic";let bestScore=0;for(const[name2,pats]of LOG_FORMAT_TABLE){let score=0;for(const line of sample){if(pats.some(p2=>line.includes(p2)))score++}if(score>bestScore){bestScore=score;best=name2}}return best}function crushLog(text2){const lines=text2.split(/\r?\n/);if(lines.length<LOG_MIN_LINES)return null;let classified=0;let summaries=0;let traces=0;for(const line of lines){const lv=classifyLevel(line);if(lv!=="unknown")classified++;if(isLogSummaryLine(line))summaries++;if(traceFlavorFor(line)!==null)traces++}if(!(classified>=LOG_CLASSIFIED_GATE||traces>=1||summaries>=LOG_SUMMARY_GATE||detectLogFormat(lines)!=="generic"))return null;const parsed=parseLogLines(lines);const selected=selectLogLines(parsed);if(selected.length>=lines.length)return null;const out=formatLogOutput(selected,parsed);if(out.length>=text2.length)return null;return out}function errorLinesSurvive(input,output){const kept=new Set(output.split(/\r?\n/).map(l=>l.trim()).filter(l=>l.length>0));for(const line of input.split(/\r?\n/)){const level=classifyLevel(line);if(level!=="error"&&level!=="fail")continue;const t=line.trim();if(t.length>0&&!kept.has(t))return false}return true}function registeredPlugins(){return Array.from(crushRegistry.values())}function resolveCrushConfig(config){return{...DEFAULT_CRUSH_CONFIG,...config.crush??{}}}function effectivePlugins(crush,meta){const toolName=meta.toolName;return registeredPlugins().filter(p2=>{const ov=crush.strategies?.[p2.id];if(ov?.enabled===false)return false;if(toolName&&ov?.excludeTools?.some(pat=>matchToolPattern(toolName,pat)))return false;return true})}function evaluateToolResult(input){const{absorb,crush,tokenCount,modelContextLimit,meta={}}=input;const countTokens=input.countTokens??defaultCountTokens;const text2=input.text;const rawTokens=countTokens(text2);if(absorb.contextThresholdPct>0&&modelContextLimit>0&&tokenCount<absorb.contextThresholdPct*modelContextLimit){return{kind:"skip",text:text2,rawTokens}}if(rawTokens<absorb.minToolTokens){return{kind:"skip",text:text2,rawTokens}}const out=crushText(text2,{minReduction:crush.minReduction,countTokens,meta,plugins:effectivePlugins(crush,meta)});if(!out)return{kind:"distill",text:text2,rawTokens};const newTokens=countTokens(out.text);return{kind:newTokens<absorb.minToolTokens?"crushed":"distill",text:out.text,rawTokens,newTokens,reduction:(rawTokens-newTokens)/rawTokens,strategy:out.strategy,lossy:out.lossy}}function applyCrushToMessages(messages,config,tokenCount,countTokens){const absorb=resolveAbsorbConfig(config);const crush=resolveCrushConfig(config);const protectedCallIds=collectProtectedToolCallIds(messages,config);let crushedCount=0;let distilledCount=0;let changed=false;const out=[];for(const msg of messages){if(!isAbsorbCandidate(msg,config,void 0,protectedCallIds)){out.push(msg);continue}const text2=msg.text??"";const markerAt=text2.indexOf(ABSORB_PROMPT_MARKER);const payload=markerAt>=0?text2.slice(0,markerAt):text2;const ev=evaluateToolResult({text:payload,absorb,crush,tokenCount,modelContextLimit:config.modelContextLimit,meta:{toolName:msg.toolName},countTokens});if(ev.kind==="skip"){out.push(msg);continue}changed=true;if(ev.kind==="crushed")crushedCount++;else distilledCount++;out.push({...msg,text:ev.text})}return{messages:changed?out:messages,crushedCount,distilledCount}}function latchKeyEqual(a,b2){if(!a||!b2)return!a&&!b2;if(Object.keys(a).length!==Object.keys(b2).length)return false;for(const[k2,v2]of Object.entries(a)){const o=b2[k2];if(!o||o.text!==v2.text||o.hidden!==v2.hidden)return false}return true}function viewLatchConfigDigest(ctx){return JSON.stringify({absorb:resolveAbsorbConfig(ctx.config),crush:resolveCrushConfig(ctx.config),ccr:resolveCcrConfig(ctx.config),filters:{enabled:ctx.config.messageFilters?.enabled??false,filters:ctx.config.messageFilters?.filters??null}})}function applyViewLatch(io2,ctx){const pre=io2.effects.preTransformMessages;if(!pre)return io2;const digest=ctx?viewLatchConfigDigest(ctx):void 0;const configChanged=digest!==void 0&&digest!==io2.state.viewLatchConfigDigest;const prev=configChanged?void 0:io2.state.viewLatches;const post=new Map;for(const m2 of io2.messages)if(m2.id)post.set(m2.id,m2);const out=[];const latches={};let latchedTransform=false;for(const m2 of pre){if(!m2.id||m2.id.startsWith(RETRIEVED_ID_PREFIX)){const t=post.get(m2.id);if(t)out.push(t);continue}const ref=io2.state.messageRefs.byRaw[m2.id];if(!ref||ref===BLOCKED_REF){const t=post.get(m2.id);if(t)out.push(t);continue}const transformed=post.get(m2.id);const prevEntry=prev?.[ref];if(prevEntry){if(prevEntry.hidden){latches[ref]=prevEntry;continue}if(prevEntry.text===null){if(transformed)out.push(m2);latches[ref]=prevEntry;continue}latchedTransform=true;if(transformed&&transformed.text===prevEntry.text)out.push(transformed);else out.push({...m2,text:prevEntry.text});latches[ref]=prevEntry}else{if(!transformed){latches[ref]={text:null,hidden:true};continue}if(transformed.text!==m2.text){latches[ref]={text:transformed.text??null};latchedTransform=true;out.push(transformed)}else{latches[ref]={text:null};out.push(m2)}}}if(!configChanged&&digest===io2.state.viewLatchConfigDigest&&latchKeyEqual(io2.state.viewLatches,latches)){return{...io2,messages:out}}if(!prev&&!latchedTransform)return io2;return{...io2,messages:out,state:{...io2.state,viewLatches:latches,...digest!==void 0?{viewLatchConfigDigest:digest}:{}}}}function listMessageFilters(){return[...registry.values()]}function applyMessageFilters(messages,config){if(!config?.enabled){return{messages,partsFiltered:0,partsDropped:0,partsModified:0}}const active=listMessageFilters().filter(filter=>config.filters?.[filter.name]?.enabled!==false);if(active.length===0){return{messages,partsFiltered:0,partsDropped:0,partsModified:0}}let working=messages.map(message=>({...message}));const tally={partsFiltered:0,partsDropped:0,partsModified:0};const total=working.length;const immediate=active.filter(filter=>!filter.keepLastOnly);for(let index=0;index<working.length;index++){const message=working[index];const text2=message.text??"";if(text2.length===0)continue;let current=text2;const baseCtx={text:current,role:message.role,messageIndex:index,totalMessages:total,toolName:message.toolName};for(const filter of immediate){let decision;try{decision=filter.filter(baseCtx)}catch{continue}if(decision.action==="keep")continue;tally.partsFiltered++;if(decision.action==="drop"){current="";tally.partsDropped++}else if(decision.action==="modify"&&decision.text!==void 0){current=decision.text;tally.partsModified++}baseCtx.text=current}if(current!==text2)working[index]={...message,text:current}}const keepLast=active.filter(filter=>filter.keepLastOnly);for(const filter of keepLast){let foundLast=false;for(let index=working.length-1;index>=0;index--){const message=working[index];const text2=message.text??"";if(text2.length===0)continue;const ctx={text:text2,role:message.role,messageIndex:index,totalMessages:total,toolName:message.toolName};let decision;try{decision=filter.filter(ctx)}catch{continue}if(decision.action!=="drop"&&decision.action!=="modify")continue;if(foundLast){tally.partsFiltered++;tally.partsDropped++;working[index]={...message,text:""}}else{foundLast=true;if(decision.action==="modify"&&decision.text!==void 0){tally.partsFiltered++;tally.partsModified++;working[index]={...message,text:decision.text}}}}}return{messages:working,...tally}}function refNum2(ref){const m2=ref.match(/\d+/);return m2?parseInt(m2[0],10):0}function resolveBlockSpan(block,byRaw){if(block.startRef&&block.endRef&&M_REF.test(block.startRef)&&M_REF.test(block.endRef)){const[startRef,endRef]=orderedRefPair(block.startRef,block.endRef);return{startRef,endRef}}const refs=block.effectiveMessageIds.map(id=>byRaw[id]).filter(r=>typeof r==="string"&&r!=="BLOCKED");if(refs.length===0)return null;const sorted=[...refs].sort((a,b2)=>refNum2(a)-refNum2(b2));return{startRef:sorted[0],endRef:sorted[sorted.length-1]}}function activeBlockSpans(state8){const spans=[];for(const block of state8.blocks){if(!block.active)continue;const span=resolveBlockSpan(block,state8.messageRefs.byRaw);if(!span)continue;spans.push({blockId:block.blockId,tier:block.tier,...span})}return spans}function formatTokens(tokens){if(tokens<1e3)return String(tokens);if(tokens<1e4)return(tokens/1e3).toFixed(1)+"K";return Math.round(tokens/1e3)+"K"}function formatTagTime(ms2){const d=new Date(ms2);const p2=(n,w2=2)=>String(n).padStart(w2,"0");return p2(d.getFullYear(),4)+"-"+p2(d.getMonth()+1)+"-"+p2(d.getDate())+" "+p2(d.getHours())+":"+p2(d.getMinutes())+":"+p2(d.getSeconds())}function classifyType(message){if(message.contentType==="tool-call"||message.contentType==="tool-result"){return message.toolName||"tool"}return message.contentType}function escapeRegex(s3){return s3.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function acpTag(ref,tokens,type,ts2){return TAG_OPEN+'tokens="'+formatTokens(tokens)+'" type="'+type+'"'+(typeof ts2==="number"?' time="'+formatTagTime(ts2)+'"':"")+GT+ref+TAG_CLOSE}function renderMessage(message,map,countTokens,strategy,snapshot=null,deferred=null,timestamps=false){const ref=refForRaw(map,message.id);if(!ref||ref===BLOCKED_REF)return message;if(deferred?.has(ref))return message;if(strategy==="none")return message;if(strategy==="text-only"&&message.contentType!=="text"){return message}const ownTagRe=new RegExp("^"+escapeRegex(TAG_OPEN)+"[^>]*"+GT+escapeRegex(ref)+escapeRegex(TAG_CLOSE)+"\\n?");const cleanText=(message.text||"").replace(ownTagRe,"");const textTokens=snapshot?snapshot[ref]??(snapshot[ref]=countTokens(cleanText)):countTokens(cleanText);const tokens=textTokens+thinkingTokenValue(message.thinkingTokens);const type=classifyType(message);const prefix=acpTag(ref,tokens,type,timestamps?message.ts:void 0)+"\n";if(!cleanText)return{...message,text:prefix};return{...message,text:prefix+cleanText}}function renderWithSnapshot(messages,state8,countTokens=text2=>Math.ceil(text2.length/4),strategy="all",timestamps=false){const map=state8.messageRefs;const snapshot={...state8.tokenSnapshot??{}};const deferred=state8.renderDeferredRefs?new Set(state8.renderDeferredRefs):null;const rendered=messages.map(message=>renderMessage(message,map,countTokens,strategy,snapshot,deferred,timestamps));return{messages:rendered,tokenSnapshot:snapshot}}function createRenderRefsNode(strategy,options){const timestamps=options?.timestamps===true;return{name:"render-refs",run(io2,ctx){const{messages,tokenSnapshot}=renderWithSnapshot(io2.messages,io2.state,ctx.countTokens,strategy,timestamps);const prev=io2.state.tokenSnapshot;const changed=!prev||Object.keys(tokenSnapshot).length!==Object.keys(prev).length;return changed?{...io2,messages,state:{...io2.state,tokenSnapshot}}:{...io2,messages}}}}function isToolMessage(message){return message.contentType==="tool-call"||message.contentType==="tool-result"}function isAssistantAct(msg){return msg.role==="assistant"&&(msg.contentType==="text"||msg.contentType==="tool-call")}function computeTurnGroups(messages){const resultIdByCallId=new Map;for(const msg of messages){if(msg.contentType==="tool-result"&&typeof msg.toolCallId==="string"&&msg.id){if(!resultIdByCallId.has(msg.toolCallId))resultIdByCallId.set(msg.toolCallId,msg.id)}}const grouped=new Set;const groups=[];for(let i=0;i<messages.length;i++){const msg=messages[i];if(!msg.id||grouped.has(msg.id))continue;if(!(msg.contentType==="reasoning"||isAssistantAct(msg)))continue;let reasoningStart=i;if(msg.contentType==="reasoning"){while(reasoningStart>0&&messages[reasoningStart-1].contentType==="reasoning"){reasoningStart--}}else{let s3=i;while(s3>0&&isAssistantAct(messages[s3-1]))s3--;reasoningStart=s3;while(reasoningStart>0&&messages[reasoningStart-1].contentType==="reasoning"){reasoningStart--}}const burstStart=(()=>{let s3=reasoningStart;while(s3<messages.length&&messages[s3].contentType==="reasoning")s3++;return s3})();if(burstStart>=messages.length||!isAssistantAct(messages[burstStart])){continue}let burstEnd=burstStart;while(burstEnd+1<messages.length&&isAssistantAct(messages[burstEnd+1])){burstEnd++}const members=new Set;for(let k2=reasoningStart;k2<=burstEnd;k2++){const m2=messages[k2];if(!m2.id)continue;members.add(m2.id);if(m2.role==="assistant"&&m2.contentType==="tool-call"&&typeof m2.toolCallId==="string"){const rid=resultIdByCallId.get(m2.toolCallId);if(rid)members.add(rid)}}for(const id of members)grouped.add(id);groups.push([...members])}return groups}function buildIntegrityPre(messages){const reasoningIds=new Set;const callIds=new Set;const callMessages=[];const callIdByMessageId=new Map;const resultIdByCallId=new Map;for(const m2 of messages){if(!m2.id)continue;if(m2.contentType==="reasoning")reasoningIds.add(m2.id);if(m2.role==="assistant"&&m2.contentType==="tool-call"){callIds.add(m2.id);callMessages.push(m2);if(typeof m2.toolCallId==="string"){callIdByMessageId.set(m2.id,m2.toolCallId)}}if(m2.contentType==="tool-result"&&typeof m2.toolCallId==="string"){if(!resultIdByCallId.has(m2.toolCallId)){resultIdByCallId.set(m2.toolCallId,m2.id)}}}return{reasoningIds,callIds,callMessages,callIdByMessageId,resultIdByCallId,groups:computeTurnGroups(messages)}}function computeIntegrityWithdrawals(messages,foldedIds,pre,invisibleIds){const remaining=new Set(foldedIds);const withdrawn=new Set;const handledTurns=new Set;const handledPairs=new Set;const built=pre??buildIntegrityPre(messages);const reasoningIds=built.reasoningIds;const callIds=built.callIds;const callIdByMessageId=built.callIdByMessageId;const resultIdByCallId=built.resultIdByCallId;const groups=built.groups;let changed=true;while(changed){changed=false;for(let g2=0;g2<groups.length;g2++){if(handledTurns.has(g2))continue;const group=groups[g2];const foldHasReasoning=group.some(id=>remaining.has(id)&&reasoningIds.has(id));if(!foldHasReasoning)continue;const keptHasCall=group.some(id=>!remaining.has(id)&&callIds.has(id)&&!invisibleIds?.has(id));if(!keptHasCall)continue;handledTurns.add(g2);for(const id of group){remaining.delete(id);withdrawn.add(id)}changed=true}for(const m2 of built.callMessages){const callId=callIdByMessageId.get(m2.id);if(callId===void 0||handledPairs.has(callId))continue;const resultId=resultIdByCallId.get(callId);if(resultId===void 0)continue;if(remaining.has(m2.id)===remaining.has(resultId))continue;handledPairs.add(callId);remaining.delete(m2.id);remaining.delete(resultId);withdrawn.add(m2.id);withdrawn.add(resultId);changed=true}}return{withdrawn,splitTurnCount:handledTurns.size,splitPairCount:handledPairs.size}}function adjustBoundariesForReasoningPairs(startIndex,endIndex,messages){if(startIndex>endIndex){return{startIndex,endIndex}}let newStartIndex=startIndex;let newEndIndex=endIndex;for(let i=startIndex;i<=endIndex&&i<messages.length;i++){const msg=messages[i];if(!msg)continue;if(msg.contentType==="reasoning"){let j2=i;while(j2+1<messages.length&&messages[j2+1].contentType==="reasoning"){j2++}const companion=messages[j2+1];if(companion!==void 0&&companion.role==="assistant"&&(companion.contentType==="text"||companion.contentType==="tool-call")){let e=j2+1;while(e+1<messages.length&&messages[e+1].role==="assistant"&&(messages[e+1].contentType==="text"||messages[e+1].contentType==="tool-call")){e++}if(e>newEndIndex)newEndIndex=e}}if(msg.role==="assistant"&&(msg.contentType==="text"||msg.contentType==="tool-call")){let k2=i-1;while(k2>=0&&messages[k2].contentType==="reasoning"){k2--}const runStart=k2+1;if(runStart<i&&runStart>=0&&messages[runStart].contentType==="reasoning"&&runStart<newStartIndex){newStartIndex=runStart}}}return{startIndex:newStartIndex,endIndex:newEndIndex}}function buildToolPairExtremes(messages){const extremes=new Map;for(let i=0;i<messages.length;i++){const msg=messages[i];if(!msg||!msg.toolCallId)continue;const cur=extremes.get(msg.toolCallId);if(cur===void 0){extremes.set(msg.toolCallId,[i,i])}else{if(i<cur[0])cur[0]=i;if(i>cur[1])cur[1]=i}}return extremes}function adjustBoundariesForToolPairs(startIndex,endIndex,messages,extremes){const pairExtremes=extremes??buildToolPairExtremes(messages);let newStartIndex=startIndex;let newEndIndex=endIndex;const settled=new Set;let changed=true;while(changed){changed=false;for(let i=newStartIndex;i<=newEndIndex&&i<messages.length;i++){const msg=messages[i];if(!msg||!msg.toolCallId)continue;if(settled.has(msg.toolCallId))continue;if(msg.toolName==="compress")continue;settled.add(msg.toolCallId);const ext=pairExtremes.get(msg.toolCallId);if(ext[0]<newStartIndex){newStartIndex=ext[0];changed=true}if(ext[1]>newEndIndex){newEndIndex=ext[1];changed=true}}}return{startIndex:newStartIndex,endIndex:newEndIndex}}function projectUnit(input){const warnings=input.warnings??[];let withdrawnIds=new Set;let splitTurnCount=0;let splitPairCount=0;const shared=input.shared;const byId2=shared?.byId;const msgById=id=>byId2===void 0?input.messages.find(m2=>m2.id===id):input.messages[byId2.get(id)??-1];const resolved=resolveBoundaries({startRef:input.startRef,endRef:input.endRef,messages:input.messages,state:input.state,indexByMessageId:byId2});const plainRange=resolved.boundaryKind!=="block";const liveCarrierIds=new Set(plainRange?shared?.liveCarrierIds:void 0);if(plainRange&&!shared){for(const message of input.messages){if(isLiveCheckpointCarrier(message,input.state)){liveCarrierIds.add(message.id)}}}const clampIndexById=byId2??(input.preExistingCoverage.size>0?buildIndexByMessageId(input.messages):void 0);const clampBlockSpans=input.preExistingCoverage.size>0?shared?.blockSpans??buildBlockIndexSpans(input.state,clampIndexById):void 0;const adjustedIds=clampAdjustmentAtCoverage(applyPairBoundaryAdjustments(resolved,input.messages,shared),resolved,input.messages,input.preExistingCoverage,clampIndexById,clampBlockSpans);const skippedCarrierIds=adjustedIds.filter(id=>liveCarrierIds.has(id));if(skippedCarrierIds.length>0){warnings.push(`Excluded ${skippedCarrierIds.length} checkpoint message(s) ${skippedCarrierIds.join(", ")} from the compression range \u2014 they carry the visible summary of still-active block(s), which a plain message-ref range does not supersede. The checkpoints stay visible; to fold them, reference the block ids (bN..bM) instead.`)}const rangeMessageIds=adjustedIds.filter(id=>!isSummaryMessageId(id)&&!liveCarrierIds.has(id));if(rangeMessageIds.length>resolved.messageIds.length){const indexByMessageId=shared?.byId??buildIndexByMessageId(input.messages);const adjustedStart=rangeMessageIds.length>0?indexByMessageId.get(rangeMessageIds[0])??resolved.startIndex:resolved.startIndex;const adjustedEnd=rangeMessageIds.length>0?indexByMessageId.get(rangeMessageIds[rangeMessageIds.length-1])??resolved.endIndex:resolved.endIndex;const nestedSeen=new Set(resolved.nestedBlockIds);for(const block of activeBlocks(input.state)){if(nestedSeen.has(block.blockId))continue;if(blockVisibleInRange(block,indexByMessageId,adjustedStart,adjustedEnd)){nestedSeen.add(block.blockId);resolved.nestedBlockIds.push(block.blockId)}}}const isBlockBoundary=resolved.boundaryKind==="block";const targetTier=resolveTargetTier(input.state,resolved.nestedBlockIds,isBlockBoundary);const outputTier=isBlockBoundary?Math.min(3,targetTier+1):1;const excludedNestedBlockIds=input.excludeNestedBlockIds?resolved.nestedBlockIds.filter(id=>input.excludeNestedBlockIds.has(id)):[];let consumedBlockIds=resolved.nestedBlockIds.filter(id=>{if(input.excludeNestedBlockIds?.has(id))return false;const block=blockById(input.state,id);return block?.active&&block.tier===targetTier});const effectiveMessageIds=new Set(rangeMessageIds);for(const consumedId of consumedBlockIds){const consumed=blockById(input.state,consumedId);if(consumed){for(const id of consumed.effectiveMessageIds)effectiveMessageIds.add(id)}}const directMessageIds=[...effectiveMessageIds].filter(id=>!input.preExistingCoverage.has(id));let filteredIds=filterProtectedToolMessages(directMessageIds,input.messages,input.config,shared);if(filteredIds.length<directMessageIds.length){const kept=new Set(filteredIds);for(const id of directMessageIds){if(!kept.has(id))effectiveMessageIds.delete(id)}}const mediaExcluded=directMessageIds.filter(id=>{const msg=msgById(id);return!!msg&&hasUnrecoverableMediaPayload(msg)});if(mediaExcluded.length>0){warnings.push(`Excluded ${mediaExcluded.length} message(s) carrying unrecoverable media (no stored bytes and no re-access handle in the message) from compression range \u2014 folding would destroy them permanently (billion-context#1188/#2609). Ref-based media (remote URL / file id) folds normally since #5620 with its handle recorded in the summary; inline images fold normally too and stay restorable via decompress({ imageRef }).`)}const protectedRefs=input.protectedMessageIds;const hitProtectedRaw=protectedRefs?filteredIds.filter(id=>{const ref=input.state.messageRefs.byRaw[id];return ref!==void 0&&protectedRefs.has(ref)}):[];if(hitProtectedRaw.length>0){const protectedSet=new Set(hitProtectedRaw);const firstProtectedIdx=filteredIds.findIndex(id=>protectedSet.has(id));let truncatedAfter=0;if(firstProtectedIdx>=0){const truncatable=filteredIds.length-firstProtectedIdx-hitProtectedRaw.length;const pairByCallId=shared?.pairByCallId??buildPairMap(input.messages);const keptIds=filteredIds.slice(0,firstProtectedIdx);const droppedIds=filteredIds.slice(firstProtectedIdx);const droppedSet=new Set(droppedIds);const strandsPair=keptIds.some(id=>{const m2=msgById(id);if(!m2||m2.contentType!=="tool-call"&&m2.contentType!=="tool-result")return false;const pair=pairByCallId.get(m2.toolCallId??m2.id);return!!pair&&pair.some(half=>half!==""&&half!==id&&droppedSet.has(half))});if(truncatable>0&&firstProtectedIdx>0&&!strandsPair){truncatedAfter=truncatable;filteredIds=keptIds;for(const id of droppedIds)effectiveMessageIds.delete(id)}}filteredIds=filteredIds.filter(id=>!protectedSet.has(id));for(const id of hitProtectedRaw)effectiveMessageIds.delete(id);const hitRefs=hitProtectedRaw.map(id=>input.state.messageRefs.byRaw[id]).filter(v2=>typeof v2==="string");if(filteredIds.length===0&&consumedBlockIds.length===0){const recentN=input.config.preserveRecentMessages;const excludedFatal=excludedNestedBlockIds.length>0?new Error(`Merging ${resolved.nestedBlockIds.join(", ")} cannot proceed: excluding ${excludedNestedBlockIds.join(", ")} (their coverage would strand a live turn-integrity conflict) leaves nothing left to fold in ${input.startRef}..${input.endRef}. Fold the stranded visible partner(s) first with a plain message-range compress so the turn closes, or retry once those block(s) can fold whole.`):null;return finish2({fatal:{kind:excludedFatal?"split":"zone",error:excludedFatal??new Error(`Range is entirely within the protected zone (the last ${recentN} messages and/or the most recent user message): ${hitRefs.join(", ")}. Adjust startId/endId to older messages.`)}})}const anchorMsg=shared?shared.anchorMessage:lastUserAnchor(input.messages,coveredMessageIds(input.state),input.config);const anchorRef=anchorMsg?input.state.messageRefs.byRaw[anchorMsg.id]:void 0;const anchorNote=anchorRef&&anchorRef!=="BLOCKED"?` Last-user anchor (historical quote, NOT a new user message): ${anchorRef} "${(anchorMsg.text??"").replace(/\s+/g," ").slice(0,40)}".`:"";warnings.push(`Excluded ${hitProtectedRaw.length} protected message(s) ${hitRefs.join(", ")} from compression range (recent/last-user zone) \u2014 they stay visible outside the new block; do not target them in another compress call.`+anchorNote+(truncatedAfter>0?` Range truncated at that boundary \u2014 ${truncatedAfter} later message(s) (including replies to the protected message) stay visible too, so no summary can land above the question it answers (#3953).`:""))}{const isMerge=consumedBlockIds.length>0;let consumedCoverage=new Set;let survivingCoverage=new Set;if(isMerge){const consumedSet=new Set(consumedBlockIds);for(const block of activeBlocks(input.state)){const target=consumedSet.has(block.blockId)?consumedCoverage:survivingCoverage;for(const id of block.effectiveMessageIds)target.add(id)}}let foldedRef=effectiveMessageIds;if(isMerge){foldedRef=new Set(effectiveMessageIds);for(const id of survivingCoverage)foldedRef.add(id)}const initial=computeIntegrityWithdrawals(input.messages,foldedRef,shared?.integrityPre,isMerge?void 0:input.preExistingCoverage);splitTurnCount=initial.splitTurnCount;splitPairCount=initial.splitPairCount;if(initial.withdrawn.size>0){const splitDesc=[splitTurnCount>0?`${splitTurnCount} turn(s)`:null,splitPairCount>0?`${splitPairCount} tool call/result pair(s)`:null].filter(part=>part!==null).join(" and ");if(!isMerge){withdrawnIds=initial.withdrawn;for(const id of initial.withdrawn)effectiveMessageIds.delete(id);const beforeWithdraw=filteredIds.length;filteredIds=filteredIds.filter(id=>!initial.withdrawn.has(id));if(filteredIds.length===0&&consumedBlockIds.length===0){return finish2({fatal:{kind:"split",degradable:true,error:new Error(`Range would split ${splitDesc} at the protected-zone boundary: a visible tool-call must keep its reasoning run and its results (strict providers reject a rebuilt request that lost either). Shrink the range to end before the turn starts, or wait until the whole turn ages out of the protected zone.`)}})}warnings.push(`Withdrawn ${beforeWithdraw-filteredIds.length} message(s) from compression range to keep ${splitDesc} intact (visible tool-call would lose its reasoning run or its results).`)}else{const unfoldable=new Set([...effectiveMessageIds].filter(id=>!consumedCoverage.has(id)));const unfolded=new Set;let current=initial.withdrawn;let guard=unfoldable.size+2;let stuck=false;while(current.size>0&&guard-- >0){let progress=false;for(const id of current){if(unfoldable.has(id)&&!unfolded.has(id)){unfolded.add(id);progress=true}}if(!progress){stuck=true;break}const recheck=new Set(effectiveMessageIds);for(const id of unfolded)recheck.delete(id);for(const id of survivingCoverage)recheck.add(id);current=computeIntegrityWithdrawals(input.messages,recheck,shared?.integrityPre).withdrawn}if(stuck||current.size>0){const mergeOwned=new Set([...filteredIds,...consumedCoverage]);const relevantUnresolved=[...current].filter(id=>mergeOwned.has(id));if(relevantUnresolved.length===0){warnings.push(`Inherited a pre-existing turn-integrity conflict this merge does not touch (${[...current].slice(0,6).map(id=>input.state.messageRefs.byRaw[id]??id).join(", ")}): the partner(s) are already covered by other blocks or still visible. Left as-is \u2014 fold the visible partner(s) into coverage to clear it.`)}else{const refOf5919=id=>input.state.messageRefs.byRaw[id]??id;const isNeverFoldable5919=id=>{const ref=refOf5919(id);const msg=msgById(id);if(ref==="BLOCKED"||!msg)return true;if(input.protectedMessageIds?.has(ref))return true;if(filterProtectedToolMessages([id],input.messages,input.config,shared).length===0)return true;return hasUnrecoverableMediaPayload(msg)};const isContentFreeBlocked5919=id=>{const ref=refOf5919(id);if(ref!=="BLOCKED")return false;if(input.protectedMessageIds?.has(ref))return false;if(filterProtectedToolMessages([id],input.messages,input.config,shared).length===0)return false;const msg=msgById(id);if(msg!==void 0&&hasUnrecoverableMediaPayload(msg))return false;return true};const visibleStranded=[...current].filter(id=>!survivingCoverage.has(id)&&!consumedCoverage.has(id));const doomedStranded=visibleStranded.filter(id=>isNeverFoldable5919(id)&&!isContentFreeBlocked5919(id));if(doomedStranded.length>0){const foldablePartners=visibleStranded.filter(id=>!isNeverFoldable5919(id));warnings.push(`Merge of ${consumedBlockIds.join(", ")} skipped \u2014 its turn cannot be closed now: ${doomedStranded.map(refOf5919).join(", ")} ${doomedStranded.length===1?"is":"are"} protected (never foldable) while the rest of their turn is covered by block(s). Do not retry this merge.${foldablePartners.length>0?` The foldable partner(s) ${foldablePartners.map(refOf5919).join(", ")} can only close their turn together with the protected member(s) \u2014 they stay visible until the protection lifts.`:""}`);consumedBlockIds=[];filteredIds=[];return finish2({fatal:null})}let extended5919=false;const tryExtend5919=()=>{if(extended5919||visibleStranded.length===0||visibleStranded.length>16)return false;const extended=new Set(effectiveMessageIds);for(const id of unfolded)extended.delete(id);for(const id of visibleStranded)extended.add(id);const checkBase=new Set(extended);for(const id of survivingCoverage)checkBase.add(id);let clean=false;let check=new Set(checkBase);for(let guard2=0;guard2<8;guard2++){const w2=computeIntegrityWithdrawals(input.messages,check,shared?.integrityPre).withdrawn;if(w2.size===0){clean=true;break}let touchesFold=false;for(const id of w2){if(extended.has(id)){touchesFold=true;break}}if(touchesFold)break;const next=new Set(check);for(const id of w2)next.delete(id);if(next.size===check.size)break;check=next}if(!clean)return false;for(const id of visibleStranded){if(skippedCarrierIds.includes(id))continue;effectiveMessageIds.add(id);if(!directMessageIds.includes(id))directMessageIds.push(id);if(!filteredIds.includes(id))filteredIds.push(id)}warnings.push(`Extended this merge to fold stranded partner(s) ${visibleStranded.map(refOf5919).join(", ")} so the turn closes (billion-context#5919) \u2014 the new block's coverage includes them.`);extended5919=true;return true};let retried=null;if((input.excludeNestedBlockIds?.size??0)<64){const ownerByMessageId=new Map;for(const bid of consumedBlockIds){const block=blockById(input.state,bid);if(!block)continue;for(const id of block.effectiveMessageIds)ownerByMessageId.set(id,bid)}const offending=[...new Set(relevantUnresolved.filter(id=>!survivingCoverage.has(id)).map(id=>ownerByMessageId.get(id)).filter(bid=>bid!==void 0))].sort();if(offending.length>0){retried=projectUnit({...input,excludeNestedBlockIds:new Set([...input.excludeNestedBlockIds??[],...offending])});const retriedFoldedNothing=retried.fatal===null&&retried.filteredIds.length===0&&retried.consumedBlockIds.length===0;if(retried.fatal===null&&!retriedFoldedNothing){warnings.push(`Excluded ${offending.join(", ")} from this merge \u2014 their coverage cuts through a turn group whose partner(s) are still visible outside the span, and unfolding them would drop their only coverage. They stay ACTIVE (coverage intact); the merge proceeded around them.`);return retried}tryExtend5919()}else{tryExtend5919()}}else{tryExtend5919()}if(!extended5919){if(retried!==null&&retried.fatal===null){return retried}return finish2({fatal:{kind:"split",error:new Error(actionableSplitError(consumedBlockIds,current,input))}})}}}withdrawnIds=unfolded;for(const id of unfolded)effectiveMessageIds.delete(id);const beforeWithdraw=filteredIds.length;filteredIds=filteredIds.filter(id=>!unfolded.has(id));if(beforeWithdraw!==filteredIds.length){warnings.push(`Withdrew ${beforeWithdraw-filteredIds.length} newly-folded message(s) from the merge to keep ${splitDesc} intact while preserving the existing coverage of ${consumedBlockIds.join(", ")}.`)}}}}return finish2({fatal:null});function finish2(partial){return{...partial,rangeMessageIds,skippedCarrierIds,nestedBlockIds:[...resolved.nestedBlockIds],consumedBlockIds,effectiveMessageIds,directMessageIds,filteredIds,withdrawnIds,splitTurnCount,splitPairCount,targetTier,outputTier,isBlockBoundary}}}function buildProjectionShared(messages,state8,config){const liveCarrierIds=new Set;for(const message of messages){if(isLiveCheckpointCarrier(message,state8))liveCarrierIds.add(message.id)}const failedCompressCallIds=collectFailedCompressCallIds(messages,config);const latestProtected=collectLatestProtected(messages,config);const agedCompressCallIds=collectAgedCompressCallIds(messages,config);const baseProtectedCallIds=new Set(latestProtected.callIds);const isExemptFold=msg=>!!msg.toolCallId&&agedCompressCallIds.has(msg.toolCallId);for(const msg of messages){if(isMessageProtected(msg,config,failedCompressCallIds)&&msg.toolCallId&&!isExemptFold(msg)){baseProtectedCallIds.add(msg.toolCallId)}}const byId2=buildIndexByMessageId(messages);return{byId:byId2,liveCarrierIds,failedCompressCallIds,latestProtected,agedCompressCallIds,baseProtectedCallIds,pairByCallId:buildPairMap(messages),toolPairExtremes:buildToolPairExtremes(messages),anchorMessage:lastUserAnchor(messages,coveredMessageIds(state8),config),integrityPre:buildIntegrityPre(messages),blockSpans:buildBlockIndexSpans(state8,byId2)}}function buildBlockIndexSpans(state8,byId2){const spans=[];for(const block of activeBlocks(state8)){let start;let end;for(const id of block.effectiveMessageIds??[]){const idx=byId2.get(id);if(idx===void 0)continue;if(start===void 0||idx<start)start=idx;if(end===void 0||idx>end)end=idx}if(start!==void 0&&end!==void 0)spans.push({start,end})}spans.sort((a,b2)=>a.start-b2.start);return spans}function buildPairMap(messages){const pairByCallId=new Map;for(const m2 of messages){if(m2.contentType==="tool-call"||m2.contentType==="tool-result"){const key2=m2.toolCallId??m2.id;const pair=pairByCallId.get(key2)??["",""];if(m2.contentType==="tool-call")pair[0]=m2.id;else pair[1]=m2.id;pairByCallId.set(key2,pair)}}return pairByCallId}function collectCoverage(state8){const coverage=new Set;for(const block of activeBlocks(state8)){for(const id of block.effectiveMessageIds)coverage.add(id)}return coverage}function applyPairBoundaryAdjustments(resolved,messages,shared){if(resolved.boundaryKind==="block"){return resolved.messageIds}let startIndex=resolved.startIndex;let endIndex=resolved.endIndex;for(let pass=0;pass<2;pass++){const reasoningAdjusted=adjustBoundariesForReasoningPairs(startIndex,endIndex,messages);const toolAdjusted=adjustBoundariesForToolPairs(reasoningAdjusted.startIndex,reasoningAdjusted.endIndex,messages,shared?.toolPairExtremes);const changed=toolAdjusted.startIndex!==startIndex||toolAdjusted.endIndex!==endIndex;startIndex=toolAdjusted.startIndex;endIndex=toolAdjusted.endIndex;if(!changed)break}if(startIndex===resolved.startIndex&&endIndex===resolved.endIndex){return resolved.messageIds}const ids=[];for(let i=startIndex;i<=endIndex;i++){const msg=messages[i];if(msg)ids.push(msg.id)}return ids}function clampAdjustmentAtCoverage(adjustedIds,resolved,messages,coverage,indexById,blockSpans){if(!coverage||coverage.size===0||adjustedIds.length===0){return adjustedIds}let startIdx;let endIdx;if(indexById){startIdx=indexById.get(adjustedIds[0]);endIdx=indexById.get(adjustedIds[adjustedIds.length-1])}else{const built=new Map;for(let i=0;i<messages.length;i++){const id=messages[i]?.id;if(id!==void 0)built.set(id,i)}startIdx=built.get(adjustedIds[0]);endIdx=built.get(adjustedIds[adjustedIds.length-1])}if(startIdx===void 0||endIdx===void 0)return adjustedIds;const isCovered2=i=>{const id=messages[i]?.id;return id!==void 0&&coverage.has(id)};const spanAt=i=>{if(!blockSpans)return void 0;for(const span of blockSpans){if(i>=span.start&&i<=span.end)return span}return void 0};const intersectsRequested=span=>resolved.startIndex<=span.end&&resolved.endIndex>=span.start;let clamped=false;for(let i=resolved.endIndex+1;i<=endIdx;){if(!isCovered2(i)){i++;continue}const span=spanAt(i);if(span&&intersectsRequested(span)){if(endIdx<span.end){endIdx=span.end;clamped=true}i=span.end+1;continue}endIdx=i-1;clamped=true;break}for(let i=resolved.startIndex-1;i>=startIdx;){if(!isCovered2(i)){i--;continue}const span=spanAt(i);if(span&&intersectsRequested(span)){if(startIdx>span.start){startIdx=span.start;clamped=true}i=span.start-1;continue}startIdx=i+1;clamped=true;break}if(!clamped)return adjustedIds;const ids=[];for(let i=startIdx;i<=endIdx;i++){const msg=messages[i];if(msg)ids.push(msg.id)}return ids}function filterProtectedToolMessages(directMessageIds,messages,config,shared){const failedCompressCallIds=shared?.failedCompressCallIds??collectFailedCompressCallIds(messages,config);const protectedCallIds=new Set(shared?.baseProtectedCallIds??[]);const removedIds=new Set;const latest=shared?.latestProtected??collectLatestProtected(messages,config);const agedCompressCallIds=shared?.agedCompressCallIds??collectAgedCompressCallIds(messages,config);const isExemptFold=msg=>!!msg.toolCallId&&agedCompressCallIds.has(msg.toolCallId);if(!shared){for(const id of latest.callIds)protectedCallIds.add(id);for(const msg of messages){if(isMessageProtected(msg,config,failedCompressCallIds)&&msg.toolCallId&&!isExemptFold(msg)){protectedCallIds.add(msg.toolCallId)}}}const byId2=shared?.byId;const lookupMsg=id=>byId2===void 0?messages.find(m2=>m2.id===id):messages[byId2.get(id)??-1];for(const id of directMessageIds){const msg=lookupMsg(id);if(!msg)continue;if(hasUnrecoverableMediaPayload(msg)||isMessageProtected(msg,config,failedCompressCallIds)&&!isExemptFold(msg)||isMessageLatestProtected(msg,latest)){removedIds.add(id);if(msg.toolCallId)protectedCallIds.add(msg.toolCallId)}}for(const id of directMessageIds){if(removedIds.has(id))continue;const msg=lookupMsg(id);if(!msg)continue;if(msg.contentType==="tool-result"&&msg.toolCallId&&protectedCallIds.has(msg.toolCallId)){removedIds.add(id)}}return directMessageIds.filter(id=>!removedIds.has(id))}function resolveTargetTier(state8,nestedBlockIds,isBlockBoundary){if(!isBlockBoundary)return 1;if(nestedBlockIds.length===0)return 1;let minTier=3;for(const id of nestedBlockIds){const block=blockById(state8,id);if(block&&block.tier<minTier)minTier=block.tier}return minTier}function actionableSplitError(consumedBlockIds,unresolved,input){const refOf=id=>input.state.messageRefs.byRaw[id]??id;const consumedOwners=new Map;const survivingOwners=new Map;for(const block of activeBlocks(input.state)){const map=consumedBlockIds.includes(block.blockId)?consumedOwners:survivingOwners;for(const id of block.effectiveMessageIds)map.set(id,block.blockId)}const detail=[...unresolved].slice(0,6).map(id=>{const ref=refOf(id);const owner=consumedOwners.get(id)??survivingOwners.get(id);return owner?`${ref} (covered by ${owner})`:`${ref} (visible)`}).join(", ");const survivingOffenders=[...new Set([...unresolved].map(id=>survivingOwners.get(id)).filter(bid=>bid!==void 0))];const visibleRefs=[...unresolved].filter(id=>!consumedOwners.has(id)&&!survivingOwners.has(id)).map(refOf).sort((a,b2)=>refNum5919(a)-refNum5919(b2)||a.localeCompare(b2)).slice(0,6);const unblockHint=visibleRefs.length>0?` The exact unblock: one plain message-range compress over ${visibleRefs[0]}..${visibleRefs[visibleRefs.length-1]} (it may cover extra messages \u2014 that is fine), then retry this merge \u2014 the conflict clears once those partner(s) are covered.`:` The exact unblock: fold the stranded partner(s) listed above into coverage with a plain message-range compress, then retry this merge.`;const tail=survivingOffenders.length>0?` Block(s) ${survivingOffenders.join(", ")} stay active with their current coverage; this merge will not touch them.`:` Merge a sub-span that stops before or resumes after the offending block instead.`;return`Merging ${consumedBlockIds.join(", ")} cannot satisfy turn integrity without dropping existing coverage: folding would strand ${detail}. Do not retry the same span \u2014 fold the stranded visible partner(s) first with a plain message-range compress so the turn closes.${unblockHint}${tail}`;function refNum5919(ref){const m2=/^m(\d+)$/.exec(ref);return m2?Number(m2[1]):Number.MAX_SAFE_INTEGER}}function parseBlockIdArg(arg){const normalized=arg.trim().toLowerCase();const refMatch=/^b0*(\d+)$/.exec(normalized);if(refMatch&&refMatch[1]!==void 0)return`b${refMatch[1]}`;const numMatch=/^(\d+)$/.exec(normalized);if(numMatch&&numMatch[1]!==void 0)return`b${numMatch[1]}`;return null}function deactivateBlock(state8,blockIds,options={}){const targets=new Set(blockIds);const updated=state8.blocks.map(block=>{if(!targets.has(block.blockId)||!block.active)return block;return{...block,active:false,durationMs:block.durationMs,createdAt:block.createdAt}});let final=updated;if(options.deep){const visited=new Set;const queue=[];for(const id of blockIds){const block=updated.find(b2=>b2.blockId===id);if(block)queue.push(...block.directBlockIds)}while(queue.length>0){const id=queue.shift();if(visited.has(id))continue;visited.add(id);final=final.map(block=>{if(block.blockId!==id)return block;queue.push(...block.directBlockIds);return block.active?{...block,active:false}:block})}}return{...state8,blocks:final}}function collectBlockContent(state8,block,messages,options={}){const full=options.full??false;const targetIds=new Set(block.effectiveMessageIds);if(full){const msgs=messages.filter(m2=>targetIds.has(m2.id));if(msgs.length===0)return{text:"",count:0};return{text:msgs.map(formatMessage).join("\n\n"),count:msgs.length}}const nestedChildren=[];const nestedCovered=new Set;for(const childId of block.directBlockIds){const child2=state8.blocks.find(b2=>b2.blockId===childId);if(!child2?.active)continue;nestedChildren.push(child2);for(const id of child2.effectiveMessageIds)nestedCovered.add(id)}const parts=[];for(const child2 of nestedChildren){const label=child2.topic?`${child2.blockId}: ${child2.topic}`:child2.blockId;parts.push(`${SUMMARY_HEADER} \u2014 ${label}
|
|
273
273
|
${child2.summary}`)}let directCount=0;for(const m2 of messages){if(targetIds.has(m2.id)&&!nestedCovered.has(m2.id)){parts.push(formatMessage(m2));directCount++}}const count=directCount+nestedChildren.length;if(count===0)return{text:"",count:0};return{text:parts.join("\n\n"),count}}function formatMessage(message){const text2=message.text??"";if(message.toolName&&message.contentType!=="text"){return`[${message.role} \u2022 ${message.toolName}]
|
|
274
274
|
${text2}`}return`[${message.role}]
|
|
275
|
-
${text2}`}function markBlockRestoredInline(state8,blockId){const existing=state8.blocks.find(b2=>b2.blockId===blockId);if(!existing)return{state:state8,result:null};const blocks=state8.blocks.map(block=>block.blockId===blockId?{...block,restoredInline:true}:block);const span=resolveBlockSpan(existing,state8.messageRefs.byRaw);const result={restored:true,blockId,...span?{restoredStartRef:span.startRef,restoredEndRef:span.endRef}:{}};return{state:{...state8,blocks},result}}function activeAncestorIds(state8,blockId){const out=[];const visited=new Set([blockId]);let frontier=[blockId];while(frontier.length>0){const next=[];for(const block of state8.blocks){if(visited.has(block.blockId))continue;if(!block.directBlockIds.some(id=>frontier.includes(id)))continue;visited.add(block.blockId);if(block.active)out.push(block.blockId);next.push(block.blockId)}frontier=next}return out}function requestedRefoldSpan(state8,spec){const nums=[];for(const ref of[spec.startRef,spec.endRef]){const parsed=parseBoundary(ref);if(!parsed)return null;if(parsed.kind==="message"){nums.push(parsed.numericId);continue}const block=blockById(state8,`b${parsed.numericId}`);if(!block)return null;const span=resolveBlockSpan(block,state8.messageRefs.byRaw);if(!span)return null;const lo2=parseBoundary(span.startRef);const hi2=parseBoundary(span.endRef);if(!lo2||!hi2)return null;nums.push(lo2.numericId,hi2.numericId)}return{lo:Math.min(...nums),hi:Math.max(...nums)}}function evaluateRefold(state8,spec){const span=requestedRefoldSpan(state8,spec);if(!span)return{kind:"blocked",reasons:[]};const reasons=[];const blocks=[];for(const block of state8.blocks){if(!block.active)continue;const resolved=resolveBlockSpan(block,state8.messageRefs.byRaw);if(!resolved){reasons.push(`partially covered ${block.blockId}`);continue}const ownLo=parseBoundary(resolved.startRef)?.numericId;const ownHi=parseBoundary(resolved.endRef)?.numericId;if(ownLo===void 0||ownHi===void 0)continue;if(ownHi<span.lo||ownLo>span.hi)continue;if(!block.restoredInline){reasons.push(`blocked by ${block.blockId} (not restored)`);continue}if(ownLo<span.lo||ownHi>span.hi){reasons.push(`partially covered ${block.blockId}`);continue}const blockers=activeAncestorIds(state8,block.blockId).filter(ancestorId=>!blockById(state8,ancestorId)?.restoredInline);if(blockers.length>0){for(const id of blockers)reasons.push(`blocked by ${id} (not restored)`);continue}blocks.push(block)}const uniqueReasons=[...new Set(reasons)];if(uniqueReasons.length>0)return{kind:"blocked",reasons:uniqueReasons};if(blocks.length>0)return{kind:"refold",blocks};return{kind:"blocked",reasons:[]}}function segmentGroups(items){const groups=[];let cur=null;for(const item of items){if(cur!==null&&(item.isUser&&cur.length>=3||item.gapBefore)){groups.push(cur);cur=null}if(cur===null)cur=[item];else cur.push(item)}if(cur!==null)groups.push(cur);return groups}function estimateTextTokens(text2){return Math.ceil(text2.length/4)}function isSyntheticOrPruned(message,covered){if(message.text?.startsWith(SUMMARY_HEADER))return true;return covered.has(message.id)}function computeProtectedRefs(messages,state8,config,countTokens=estimateTextTokens){const preserveN=config.preserveRecentMessages;const preserveTokens=config.preserveRecentTokens;const covered=coveredMessageIds(state8);const result=new Set;const visible=[];for(const msg of messages){if(isSyntheticOrPruned(msg,covered))continue;if(isNeverPreserveRecent(msg,config.neverPreserveRecentTools,config.preserveRecentTools))continue;const ref=state8.messageRefs.byRaw[msg.id];if(!ref||ref==="BLOCKED")continue;visible.push({ref,tokens:countMessageTokens(msg,countTokens)})}if(preserveN>0){for(const m2 of visible.slice(-preserveN)){result.add(m2.ref)}}if(preserveTokens>0){let tokenAccum=0;for(let i=visible.length-1;i>=0&&tokenAccum<preserveTokens;i--){result.add(visible[i].ref);tokenAccum+=visible[i].tokens}}if(preserveN>0){const anchor=lastUserAnchor(messages,covered,config);if(anchor){const ref=state8.messageRefs.byRaw[anchor.id];if(ref&&ref!=="BLOCKED")result.add(ref)}}{const msgByRef=new Map;for(const m2 of messages){const ref=m2.id?state8.messageRefs.byRaw[m2.id]:void 0;if(ref&&ref!=="BLOCKED")msgByRef.set(ref,m2)}const callRefByToolCallId=new Map;const resultRefByToolCallId=new Map;for(const m2 of messages){if(!m2.id||typeof m2.toolCallId!=="string")continue;if(isSyntheticOrPruned(m2,covered))continue;const ref=state8.messageRefs.byRaw[m2.id];if(!ref||ref==="BLOCKED")continue;if(m2.contentType==="tool-call")callRefByToolCallId.set(m2.toolCallId,ref);else if(m2.contentType==="tool-result")resultRefByToolCallId.set(m2.toolCallId,ref)}for(const ref of[...result]){const m2=msgByRef.get(ref);if(!m2||typeof m2.toolCallId!=="string")continue;if(m2.contentType==="tool-call"){const r=resultRefByToolCallId.get(m2.toolCallId);if(r)result.add(r)}else if(m2.contentType==="tool-result"){const c=callRefByToolCallId.get(m2.toolCallId);if(c)result.add(c)}}}return result}function refNumber(ref){const m2=/^m(\d+)$/i.exec(ref);return m2?Number(m2[1]):null}function hasDeadRefBetween(deadRefNums,lo2,hi2){for(const n of deadRefNums)if(n>lo2&&n<hi2)return true;return false}function markNoMergeAcrossDeadHoles(ranges,deadRefNums){if(deadRefNums.size===0||ranges.length<2)return;const startPos=r=>r.startIndex??refNumber(r.startRef)??0;const order=[...ranges].sort((a,b2)=>startPos(a)-startPos(b2));for(let i=1;i<order.length;i++){const prevEnd=refNumber(order[i-1].endRef);const curStart=refNumber(order[i].startRef);if(prevEnd===null||curStart===null)continue;const lo2=Math.min(prevEnd,curStart);const hi2=Math.max(prevEnd,curStart);if(hi2-lo2>1&&hasDeadRefBetween(deadRefNums,lo2,hi2)){order[i].noMergeBefore=true}}}function buildCompressibleRanges(messages,state8,config,protectedZoneRefs,countTokens=estimateTextTokens,integritySource){let compressibleMsgs=[];const protectedMsgs=[];const covered=coveredMessageIds(state8);const protectedCallIds=collectProtectedToolCallIds(messages,config);const failedCompressCallIds=collectFailedCompressCallIds(messages,config);const latest=collectLatestProtected(messages,config);for(const id of latest.callIds)protectedCallIds.add(id);let skipSinceCompressible=false;let skipSinceProtected=false;let hardGapSinceCompressible=false;let msgIndex=-1;const deadRefNums=new Set((state8.deadRefs??[]).map(ref=>refNumber(ref)).filter(n=>n!==null));let lastCompressibleRefNum=null;for(const msg of messages){msgIndex++;const ref=state8.messageRefs.byRaw[msg.id];if(!ref||ref==="BLOCKED"){hardGapSinceCompressible=true;continue}if(isSyntheticOrPruned(msg,covered)){skipSinceCompressible=true;skipSinceProtected=true;hardGapSinceCompressible=true;continue}if(isLiveCheckpointCarrier(msg,state8)){skipSinceCompressible=true;skipSinceProtected=true;hardGapSinceCompressible=true;continue}if(hasUnrecoverableMediaPayload(msg)){skipSinceCompressible=true;skipSinceProtected=true;hardGapSinceCompressible=true;continue}if(isMessageProtectedWithPairing(msg,config,protectedCallIds,failedCompressCallIds)||isMessageLatestProtected(msg,latest)){protectedMsgs.push({ref,gapBefore:skipSinceProtected,tokens:countMessageTokens(msg,countTokens),tools:msg.toolName?[msg.toolName]:[],index:msgIndex});skipSinceProtected=false;skipSinceCompressible=true;continue}if(protectedZoneRefs?.has(ref)){skipSinceCompressible=true;skipSinceProtected=true;hardGapSinceCompressible=true;continue}const curRefNum=refNumber(ref);if(deadRefNums.size>0&&curRefNum!==null&&lastCompressibleRefNum!==null){const lo2=Math.min(curRefNum,lastCompressibleRefNum);const hi2=Math.max(curRefNum,lastCompressibleRefNum);if(hi2-lo2>1&&hasDeadRefBetween(deadRefNums,lo2,hi2)){skipSinceCompressible=true;hardGapSinceCompressible=true}}compressibleMsgs.push({id:msg.id,ref,gapBefore:skipSinceCompressible,gapHard:hardGapSinceCompressible,tokens:countMessageTokens(msg,countTokens),chars:(msg.text??"").length,isTool:isToolMessage(msg),isUser:msg.role==="user",index:msgIndex});if(curRefNum!==null)lastCompressibleRefNum=curRefNum;skipSinceCompressible=false;skipSinceProtected=true;hardGapSinceCompressible=false}const unfoldedIds=computeIntegrityWithdrawals(integritySource??messages,new Set(compressibleMsgs.map(info=>info.id)),void 0,covered).withdrawn;if(unfoldedIds.size>0){let gapPending=false;let pendingHard=false;const kept=[];for(const info of compressibleMsgs){if(unfoldedIds.has(info.id)){gapPending=true;pendingHard=pendingHard||info.gapHard;continue}kept.push(gapPending?{...info,gapBefore:true,gapHard:pendingHard||info.gapHard}:info);gapPending=false;pendingHard=false}compressibleMsgs=kept}const compressible=[];for(const group of segmentGroups(compressibleMsgs)){const first=group[0];const range={startRef:first.ref,endRef:first.ref,startIndex:first.index,endIndex:first.index,count:1,tokens:first.tokens,chars:first.chars,toolPct:first.isTool?100:0,textPct:first.isTool?0:100,userMsgs:first.isUser?1:0,...first.gapBefore&&!first.gapHard?{bridgeableGapBefore:true}:{}};for(let i=1;i<group.length;i++){const info=group[i];range.endRef=info.ref;range.endIndex=info.index;range.count++;range.tokens+=info.tokens;range.chars=(range.chars??0)+info.chars;if(info.isUser)range.userMsgs=(range.userMsgs??0)+1;if(info.isTool){range.toolPct=Math.round((range.toolPct*(range.count-1)+100)/range.count)}else{range.toolPct=Math.round(range.toolPct*(range.count-1)/range.count)}range.textPct=100-range.toolPct}compressible.push(range)}const protectedRanges=[];let pcur=null;for(const info of protectedMsgs){if(pcur&&info.gapBefore){protectedRanges.push(pcur);pcur=null}if(!pcur){pcur={startRef:info.ref,endRef:info.ref,count:1,tokens:info.tokens,tools:[...info.tools],startIndex:info.index,endIndex:info.index}}else{pcur.endRef=info.ref;pcur.endIndex=info.index;pcur.count++;pcur.tokens+=info.tokens;for(const t of info.tools){if(!pcur.tools.includes(t))pcur.tools.push(t)}}}if(pcur)protectedRanges.push(pcur);markNoMergeAcrossDeadHoles([...compressible,...protectedRanges],deadRefNums);return{compressible:compressible.filter(g2=>g2.tokens>0),protected:protectedRanges}}function mergeBatch(batch){const first=batch[0];const last=batch[batch.length-1];const count=batch.reduce((s3,r)=>s3+r.count,0);const tokens=batch.reduce((s3,r)=>s3+r.tokens,0);const chars=batch.reduce((s3,r)=>s3+rangeChars(r),0);const toolPct=Math.round(batch.reduce((s3,r)=>s3+r.toolPct*r.count,0)/count);const merged={startRef:first.startRef,endRef:last.endRef,count,tokens,chars,toolPct,textPct:100-toolPct,userMsgs:batch.reduce((s3,r)=>s3+(r.userMsgs??0),0)};if(first.startIndex!==void 0&&last.endIndex!==void 0){merged.startIndex=Math.min(...batch.map(r=>r.startIndex??Infinity));merged.endIndex=Math.max(...batch.map(r=>r.endIndex??-Infinity))}if(batch.some(r=>r.dangerous===true)){merged.dangerous=true}if(first.noMergeBefore===true)merged.noMergeBefore=true;if(first.bridgeableGapBefore===true)merged.bridgeableGapBefore=true;return merged}function rangeChars(r){return r.chars??r.tokens*4}function mergeRangesToThreshold(ranges,minChars){if(minChars<=0||ranges.length===0)return ranges;const result=[];let batch=[];let batchChars=0;const closeBatch=()=>{if(batch.length>0){if(batchChars>=minChars)result.push(mergeBatch(batch));batch=[];batchChars=0}};for(const r of ranges){if(r.noMergeBefore)closeBatch();const prev=batch[batch.length-1];if(prev&&prev.endIndex!==void 0&&r.startIndex!==void 0&&r.startIndex>prev.endIndex+1&&!r.bridgeableGapBefore){closeBatch()}batch.push(r);batchChars+=rangeChars(r);if(batchChars>=minChars)closeBatch()}if(batch.length>0&&result.length>0){const prev=result[result.length-1];const contiguous=!batch[0].noMergeBefore&&(prev.endIndex===void 0||batch[0].startIndex===void 0||batch[0].startIndex<=prev.endIndex+1||batch[0].bridgeableGapBefore===true);if(contiguous){result[result.length-1]=mergeBatch([prev,...batch])}else if(batchChars>=minChars){result.push(mergeBatch(batch))}}return result}function screenRecommendedUnits(units,source,state8,config,protectedRefs){if(units.length===0)return units;const coverage=collectCoverage(state8);const shared=buildProjectionShared(source,state8,config);return units.filter(unit=>{let projection;try{projection=projectUnit({messages:source,state:state8,config,startRef:unit.startRef,endRef:unit.endRef,preExistingCoverage:coverage,protectedMessageIds:protectedRefs,shared})}catch(err2){if(!(err2 instanceof BoundaryNotFoundError)){warnScreenDrop(`dropped unit ${unit.startRef}..${unit.endRef} after projection error: ${err2 instanceof Error?err2.message:String(err2)}`)}return false}if(!projection||projection.fatal!==null){if(projection?.fatal){warnScreenDrop(`dropped unit ${unit.startRef}..${unit.endRef}: ${projection.fatal.error.message}`)}return false}if(projection.filteredIds.length===0&&projection.consumedBlockIds.length===0){warnScreenDrop(`dropped unit ${unit.startRef}..${unit.endRef}: nothing foldable in span (filteredIds=0, consumedBlocks=0)`);return false}if(projection.filteredIds.length===0&&projection.consumedBlockIds.length>0&&!projection.isBlockBoundary&&evaluateRefold(state8,unit).kind!=="refold"){warnScreenDrop(`dropped unit ${unit.startRef}..${unit.endRef}: consumes only active block(s), not a refold`);return false}return true})}function warnScreenDrop(detail){screenDropWarnCount+=1;if(screenDropWarnCount>SCREEN_DROP_WARN_BUDGET&&screenDropWarnCount%SCREEN_DROP_WARN_STRIDE!==0){return}console.warn(`[acp-kernel] screenRecommendedUnits ${detail}`)}function runPipeline(nodes,initial,ctx){let io2=initial;for(const node of nodes){if(node.enabled&&!node.enabled(io2,ctx))continue;io2=node.run(io2,ctx)}return io2}function rangeError(spec,message){return`range ${spec.startRef}..${spec.endRef}: ${message}`}function numericBlockId(id){const parsed=/^b(\d+)$/.exec(id);return parsed?Number(parsed[1]):0}function refGateDiagnostics(state8,requestedRanges,unknownCount){const highest=highestUsedIndex(state8.messageRefs);const highestRef=highest>0?indexToRef(highest):"none";return`[diagnostics: session highest allocated ref=${highestRef} (the ref space is sparse \u2014 numbers at or below it are NOT necessarily allocated, so probing numbers will not find a valid one; use only refs acp_status lists), unknown ranges in request=${unknownCount}/${requestedRanges}, session history=${state8.stats.compressionCount} compression(s), ${state8.blocks.length} block(s)]`}function danglingMessageRefs(state8,messages,spec){const visible=new Set(messages.map(m2=>m2.id));const dangling=[];for(const ref of[spec.startRef,spec.endRef]){const parsed=parseBoundary(ref);if(!parsed||parsed.kind!=="message")continue;const rawId=state8.messageRefs.byRef[parsed.raw]??state8.messageRefs.byRef[indexToRef(parsed.numericId)];if(!rawId){const padded=indexToRef(parsed.numericId);if(state8.deadRefs?.includes(parsed.raw)||state8.deadRefs?.includes(padded)){dangling.push(padded)}continue}if(visible.has(rawId))continue;const covered=state8.blocks.some(block=>block.active&&block.effectiveMessageIds.includes(rawId));if(!covered)dangling.push(parsed.raw)}return dangling}function coveringBlockIds(state8,spec){const found=new Set;for(const ref of[spec.startRef,spec.endRef]){const parsed=parseBoundary(ref);if(!parsed)continue;let rawIds=[];if(parsed.kind==="message"){const rawId=state8.messageRefs.byRef[parsed.raw]??state8.messageRefs.byRef[indexToRef(parsed.numericId)];if(rawId)rawIds=[rawId]}else{rawIds=blockById(state8,`b${parsed.numericId}`)?.effectiveMessageIds??[]}if(rawIds.length===0)continue;for(const candidate of activeBlocks(state8)){if(rawIds.some(id=>candidate.effectiveMessageIds.includes(id))){found.add(candidate.blockId)}}}return[...found].sort((x,y)=>numericBlockId(x)-numericBlockId(y))}function tierActionHint(config,state8){if(!config.tiers.enabled)return"";const live=activeBlocks(state8).filter(b2=>!b2.retired);const t2=live.filter(b2=>b2.tier===2);if(t2.length>=config.tiers.tier3Trigger){return` Tier condensation is actionable now: compress({ content: "${t2[0].blockId}\u2013${t2[t2.length-1].blockId} optional topic\\nsummary markdown..." }) merges those tier-2 blocks into one tier-3 block.`}const t1=live.filter(b2=>b2.tier===1);if(t1.length>=config.tiers.tier2Trigger){return` Tier distillation is actionable now: compress({ content: "${t1[0].blockId}\u2013${t1[t1.length-1].blockId} optional topic\\nsummary markdown..." }) merges those tier-1 blocks into one tier-2 block.`}return""}function applyRefolds(input){validateSummaryLength(input.spec,input.config.compress,{skipMin:input.minFloorCovered===true});const targets=new Set(input.blockIds);input.state.blocks=input.state.blocks.map(block=>{if(!targets.has(block.blockId))return block;const carriedRefs=parseMediaRefsSection(block.summary).map(scrubLoneSurrogates2);return{...block,summary:appendMediaRefsSection(input.spec.summary,carriedRefs),topic:input.spec.topic??block.topic,runId:input.runId,restoredInline:false}})}function createCore(ports={}){const countTokens=ports.countTokens??defaultCountTokens;const timestampsOn=ports.timestamps===true;function applyCompression(input){const state8=cloneState(input.state);for(const spec of input.ranges){if(spec.summary)spec.summary=scrubLoneSurrogates2(spec.summary)}let allocatedRunId=null;const runIdOf=()=>allocatedRunId??=allocateRunId(state8);let blocksCreated=0;let tokensCompressed=0;const errors=[];const warnings=[];const notes=[];const protectedMessageIds=input.protectedMessageIds??computeProtectedRefs(input.messages,input.state,input.config,countTokens);let preExistingCoverage=collectCoverage(state8);const classifications=new Map;const classificationErrors=[];const consumedRanges=[];for(const spec of input.ranges){try{const resolved=resolveBoundaries({startRef:spec.startRef,endRef:spec.endRef,messages:input.messages,state:state8});classifications.set(spec,{status:"ok",resolved})}catch(error){if(error instanceof BoundaryNotFoundError){classifications.set(spec,error.kind==="unknown"?{status:"unknown",error}:{status:"consumed",error});if(error.kind==="consumed"){consumedRanges.push(spec)}else{classificationErrors.push(rangeError(spec,error.message))}}else{classifications.set(spec,{status:"invalid",error:error instanceof Error?error:new Error(String(error))});classificationErrors.push(rangeError(spec,error instanceof Error?error.message:String(error)))}}}const visibleIdsForDead=new Set(input.messages.map(m2=>m2.id));let deadRefs=(state8.deadRefs??[]).filter(ref=>{const rawId=state8.messageRefs.byRef[ref];return!(rawId!==void 0&&visibleIdsForDead.has(rawId))});const danglingBySpec=new Map;for(const spec of input.ranges){const resolution=classifications.get(spec);if(resolution===void 0||resolution.status!=="consumed")continue;const dangling=danglingMessageRefs(state8,input.messages,spec);if(dangling.length===0)continue;danglingBySpec.set(spec,dangling);for(const ref of dangling){if(!deadRefs.includes(ref))deadRefs.push(ref)}}if(deadRefs.length>0){state8.deadRefs=[...new Set(deadRefs)].sort((a,b2)=>Number(a.replace(/^m/,""))-Number(b2.replace(/^m/,"")))}else{state8.deadRefs=void 0}let resolvableCount=0;let unknownCount=0;for(const resolution of classifications.values()){if(resolution.status==="ok")resolvableCount++;else if(resolution.status==="unknown")unknownCount++}const refoldDecisions=new Map;const isRefoldCandidate=resolution=>resolution.status==="consumed"||resolution.status==="ok"&&resolution.resolved.boundaryKind!=="block"&&resolution.resolved.messageIds.every(id=>preExistingCoverage.has(id));for(const[spec,resolution]of classifications){if(isRefoldCandidate(resolution)){refoldDecisions.set(spec,evaluateRefold(state8,spec))}}const allRefold=input.ranges.length>0&&unknownCount===0&&[...classifications.entries()].every(([spec,resolution])=>isRefoldCandidate(resolution)&&refoldDecisions.get(spec)?.kind==="refold");const rangeSpans=[];for(const[spec,resolution]of classifications){if(resolution.status!=="ok")continue;rangeSpans.push({spec,start:resolution.resolved.startIndex,end:resolution.resolved.endIndex})}const sortedRanges=[...rangeSpans].sort((a,b2)=>a.start-b2.start);const skipSpecs=new Set;let acceptedMaxIndex=-1;for(const entry of sortedRanges){if(entry.start<=acceptedMaxIndex){skipSpecs.add(entry.spec);warnings.push(`Skipped range (${entry.spec.startRef}..${entry.spec.endRef}) \u2014 overlaps an earlier range in the batch; the earlier range takes precedence. Keep ranges disjoint.`);continue}if(entry.end>acceptedMaxIndex)acceptedMaxIndex=entry.end}if(input.config.compress.minCompressRange>0&&input.ranges.length>0){let totalRangeChars=0;let hasBlockBoundaryRange=false;let countedRanges=0;for(const[spec,resolution]of classifications){if(resolution.status!=="ok"||skipSpecs.has(spec))continue;if(resolution.resolved.boundaryKind==="block"){hasBlockBoundaryRange=true;continue}countedRanges++;for(const id of resolution.resolved.messageIds){const msg=input.messages.find(m2=>m2.id===id);totalRangeChars+=msg?.text?.length??0}}if(!allRefold&&!hasBlockBoundaryRange&&totalRangeChars<input.config.compress.minCompressRange){const diagnostics=refGateDiagnostics(state8,input.ranges.length,unknownCount);const firstConsumed=consumedRanges[0];const covering=firstConsumed?coveringBlockIds(state8,firstConsumed):[];const coverDetail=covering.length>0?`its content is already summarized in active block(s) ${covering.join(", ")}${covering.length===1?` \u2014 use search_context or decompress ${covering[0]} if you need details from it`:""}`:`its refs no longer point to directly compressible content (stale block ref(s) distilled or consumed by higher-tier blocks)`;const refoldReasons=[...new Set(consumedRanges.flatMap(spec=>{const decision=refoldDecisions.get(spec);return decision?.kind==="blocked"?decision.reasons:[]}))];const refoldSuffix=reasons=>reasons.length>0?` Refold blocked: ${reasons.join("; ")}. Restore the affected block(s) inline (decompress with inline:true), then recompressing the same range updates them in place`:"";const refoldDetail=refoldSuffix(refoldReasons);const okBlockedReasons=[...new Set([...classifications.entries()].flatMap(([spec,resolution])=>{if(skipSpecs.has(spec)||resolution.status!=="ok")return[];const decision=refoldDecisions.get(spec);return decision?.kind==="blocked"?decision.reasons:[]}))];const danglingRefs=consumedRanges.flatMap(spec=>danglingBySpec.get(spec)??[]);const unknownEndpoints=new Set;for(const[spec,resolution]of classifications){if(resolution.status!=="unknown")continue;const endpoint=resolution.error.endpoint;unknownEndpoints.add(`${endpoint}Id=${endpoint==="start"?spec.startRef:spec.endRef}`)}let gateMessage=resolvableCount===0&&consumedRanges.length===0&&unknownCount>0?`None of the ${input.ranges.length} requested range(s) resolved \u2014 every ref is unknown to this session${unknownEndpoints.size>0?`, failing endpoints: ${[...unknownEndpoints].join(", ")}`:""}. Refs are per-session snapshots, assigned once when a message is first rendered; no compress reassigns them. An unknown ref is usually a stale artifact from an earlier generation (switching model or upstream mid-conversation starts a fresh session whose refs restart at m00001, and a native-compaction rebase resets them the same way) or a typo \u2014 but a number at or below the highest allocated ref may also simply be an unallocated gap: the ref space is sparse. ${diagnostics} Do not probe for valid numbers. Run acp_status, then call the compress tool again using only the refs it reports.`:consumedRanges.length>0?danglingRefs.length>0?`Requested range(s) cannot be anchored (e.g. ${firstConsumed.startRef}..${firstConsumed.endRef}): refs ${danglingRefs.join(", ")} are known to this session but no longer back any visible or folded message \u2014 the client rewrote or dropped those messages (an edit reissues a new ref; host-native compaction or a bulk history rewrite drops them outright), and no active block covers them. These refs are now recorded as DEAD: no range that includes them can compress now or later, whatever the neighbors. Do not retry this range in any form \u2014 run acp_status and target only the live refs it reports. ${diagnostics}`:`Requested range(s) already compressed (e.g. ${firstConsumed.startRef}..${firstConsumed.endRef}) \u2014 ${coverDetail}${refoldDetail}. Nothing new to compress in that window. ${diagnostics} Continue the task, or run acp_status and target one of the CURRENT compressible ranges it reports.${tierActionHint(input.config,state8)}`:countedRanges>0?`Total compressible content too small (${totalRangeChars} chars across ${countedRanges} range(s), min ${input.config.compress.minCompressRange}). Combine more messages into your range(s) to meet the threshold.${refoldSuffix(okBlockedReasons)}`:null;if(gateMessage===null){return{state:input.state,result:{blocksCreated:0,tokensCompressed:0,errors:[...classificationErrors],warnings:[]}}}const reversalNotes=[];for(const[spec,resolution]of classifications){if(resolution.status==="ok"&&!skipSpecs.has(spec)){const note=resolution.resolved.reversedNote;if(note)reversalNotes.push(note)}}if(reversalNotes.length>0){gateMessage+=` ${reversalNotes.join(" ")}`}const pureResubmit=countedRanges===0&&consumedRanges.length>0&&danglingRefs.length===0&&unknownCount===0;if(pureResubmit){return{state:state8,result:{blocksCreated:0,tokensCompressed:0,errors:[],warnings:[`${gateMessage} Nothing failed and nothing needed redoing \u2014 do not resend these ranges.`],noop:true}}}return{state:state8,result:{blocksCreated:0,tokensCompressed:0,errors:[gateMessage,...classificationErrors],warnings:[]}}}}let batchFloorByTotal=false;{const foldCandidates=[];for(const spec of input.ranges){if(skipSpecs.has(spec))continue;const resolution=classifications.get(spec);if(resolution===void 0)continue;const foldsFresh=resolution.status==="ok";const foldsRefold=resolution.status==="consumed"&&refoldDecisions.get(spec)?.kind==="refold";if(!foldsFresh&&!foldsRefold)continue;foldCandidates.push(spec)}const lengthFailures=[];const failureKinds=new Set;const minLen=input.config.compress.minSummaryLength;if(foldCandidates.length===1){const solo=foldCandidates[0];try{validateSummaryLength(solo,input.config.compress)}catch(error){if(isSummaryLengthError(error))failureKinds.add(error.kind);lengthFailures.push(rangeError(solo,error instanceof Error?error.message:String(error)))}}else{for(const spec of foldCandidates){try{validateSummaryLength(spec,input.config.compress,{skipMin:true})}catch(error){if(isSummaryLengthError(error))failureKinds.add(error.kind);lengthFailures.push(rangeError(spec,error instanceof Error?error.message:String(error)))}}if(minLen>0&&foldCandidates.length>1){const total=foldCandidates.reduce((sum,spec)=>sum+(spec.summary?.trim()??"").length,0);if(total<minLen){failureKinds.add("tooShort");lengthFailures.push(`Batch summary too short (${total} chars across ${foldCandidates.length} ranges, min ${minLen}). The combined summaries must capture the compressed content's key information.`)}}}batchFloorByTotal=foldCandidates.length>1;if(lengthFailures.length>0){return{state:state8,result:{blocksCreated:0,tokensCompressed:0,errors:[`Batch rejected before folding any range \u2014 ${lengthFailures.length} of ${input.ranges.length} requested range(s) failed summary-length validation: ${lengthFailures.join(" | ")}. Nothing was folded, so no prefix was rewritten. ${lengthRemediation(failureKinds)}`,...classificationErrors],warnings:[]}}}}const preLoopState=cloneState(state8);const applyErrors=[];const warningsBase=warnings.length;const preFoldBlockIds=new Set(state8.blocks.map(b2=>b2.blockId));for(const spec of input.ranges){preExistingCoverage=collectCoverage(state8);if(skipSpecs.has(spec))continue;const resolution=classifications.get(spec);if(resolution===void 0)continue;if(resolution.status==="consumed"){const decision=refoldDecisions.get(spec);if(decision?.kind==="refold"){try{applyRefolds({spec,state:state8,runId:runIdOf(),config:input.config,blockIds:decision.blocks.map(block=>block.blockId),minFloorCovered:batchFloorByTotal});blocksCreated+=decision.blocks.length}catch(error){applyErrors.push(rangeError(spec,error instanceof Error?error.message:String(error)))}continue}const reasons=decision?.kind==="blocked"?decision.reasons:[];const dangling=danglingBySpec.get(spec);warnings.push(dangling&&dangling.length>0?`Skipped range (${spec.startRef}..${spec.endRef}) \u2014 its refs ${dangling.join(", ")} are DEAD (the client rewrote or dropped those messages); this range can never compress, do not retry it.`:`Skipped range (${spec.startRef}..${spec.endRef}) \u2014 already compressed${reasons.length>0?`: ${reasons.join("; ")}`:" (messages consumed by existing block(s))"}; nothing to compress.`);continue}if(resolution.status==="unknown"||resolution.status==="invalid"){errors.push(rangeError(spec,resolution.error.message));continue}warnings.push(...resolution.resolved.snappedBoundaries);const note=resolution.resolved.reversedNote;if(note)notes.push(note);try{const outcome=applySingleRange({spec,messages:input.messages,state:state8,runId:runIdOf(),config:input.config,protectedMessageIds,countTokens,preExistingCoverage,minFloorCovered:batchFloorByTotal});blocksCreated+=outcome.noop?0:outcome.refolded?outcome.refolded.length:1;tokensCompressed+=outcome.tokens;warnings.push(...outcome.warnings)}catch(error){applyErrors.push(rangeError(spec,error instanceof Error?error.message:String(error)))}}if(applyErrors.length>0){return{state:preLoopState,result:{blocksCreated:0,tokensCompressed:0,errors:[`Batch rejected before folding any range \u2014 ${applyErrors.length} of ${input.ranges.length} requested range(s) failed during application: ${applyErrors.join(" | ")}. Nothing was folded, so no prefix was rewritten. Fix or drop the offending range(s), then resend the whole batch.`,...classificationErrors],warnings:warnings.slice(0,warningsBase)}}}state8.stats.compressionCount+=blocksCreated;state8.stats.tokensCompressed+=tokensCompressed;if(blocksCreated>0){let foldStartRef;for(const b2 of state8.blocks){if(preFoldBlockIds.has(b2.blockId))continue;for(const id of b2.effectiveMessageIds){const num7=refNum(state8.messageRefs.byRaw[id]);if(num7!==null&&(foldStartRef===void 0||num7<foldStartRef)){foldStartRef=num7}}}if(foldStartRef!==void 0){state8.pendingOrphanSweepMinRef=state8.pendingOrphanSweepMinRef===void 0?foldStartRef:Math.min(state8.pendingOrphanSweepMinRef,foldStartRef)}state8.nudge.lastPerMessageNudgeTokens=0;state8.nudge.lastNudgeShownTokens=0;state8.nudge.lastShownByTier={};state8.nudge.absorbedDebt=0;state8.nudge.absorbCount=0;const distilled=state8.blocks.filter(b2=>!preFoldBlockIds.has(b2.blockId)).some(b2=>(b2.tier??1)>1);const firePending=state8.nudge.lastT1FirePending;if(distilled){state8.nudge.t1HarvestStall=false;state8.nudge.lastT1FirePending=void 0}else if(firePending!==void 0&&firePending>0){state8.nudge.t1HarvestStall=tokensCompressed<STALL_HARVEST_RATIO*firePending;state8.nudge.lastT1FirePending=void 0}state8.terminalStreak=0;state8.emergencyTruncateLatch=void 0;state8.renderDeferredRefs=void 0;state8.viewLatches=void 0}return{state:state8,result:{blocksCreated,tokensCompressed,errors,warnings,...notes.length>0?{notes}:{},...blocksCreated===0&&errors.length===0?{noop:true}:{}}}}function processTurn(input){const configErrors=validateConfig(input.config);if(configErrors.length>0){console.warn(`[acp-kernel] Config validation warnings: ${configErrors.join("; ")}. Thresholds may not fire correctly.`)}const contentStore=input.contentStore??createContentStore();const ctx={config:input.config,tokenCount:input.tokenCount,tokenCountSource:input.tokenCountSource,countTokens,contentStore};const initial={messages:input.messages,state:input.state,effects:{applyView:input.applyView}};const strategy=input.renderTags??"all";const nodes=buildNodes(strategy);const inboundIds=input.messages.map(m2=>m2.id);const result=runPipeline(nodes,initial,ctx);let deadRefs=result.state.deadRefs;if(deadRefs&&deadRefs.length>0){const inboundSet=new Set(inboundIds);const kept=deadRefs.filter(ref=>{const rawId=result.state.messageRefs.byRef[ref];return!(rawId!==void 0&&inboundSet.has(rawId))});deadRefs=kept.length>0?kept:void 0}const state8={...result.state,lastPassIds:inboundIds,deadRefs};const ccrEffect=result.effects.ccr;return{messages:result.messages,state:state8,nudge:result.effects.nudge,terminalEscape:result.effects.terminalEscape,truncationSkipped:result.effects.truncationSkipped,contentStore:ccrEffect?.store??contentStore}}function retrieve(store2,ref,opts){return applyRetrieve({store:store2,ref,...opts})}function decompress(blockId,state8){return blockById(state8,blockId)}function search(query,state8){const terms=query.toLowerCase().split(/\s+/).filter(term=>term.length>0);if(terms.length===0)return[];const scored=activeBlocks(state8).map(block=>({block,score:scoreRelevance(block,terms)})).filter(entry=>entry.score>0).sort((left,right)=>right.score-left.score);return scored.map(entry=>entry.block)}function status(state8,tokenCount,config){const active=activeBlocks(state8);const usage=config.modelContextLimit>0?tokenCount/config.modelContextLimit:0;return{contextUsage:usage,tokenCount,modelContextLimit:config.modelContextLimit,activeBlocks:active.length,totalBlocks:state8.blocks.length,tokensCompressed:state8.stats.tokensCompressed,breakdown:{active:active.length,total:state8.blocks.length,storedMessages:state8.stats.storedCount??0,retrievals:state8.stats.retrievalCount??0}}}function defaultNodes(){return buildNodes("all")}function buildNodes(strategy){const base=[reconcileLiveIdsNode,createStampTimestampsNode(timestampsOn),assignRefsNode,syncBlocksNode,pruneNode,preTransformSnapshotNode,ccrStoreNode,absorbHideNode,crushNode,absorbPromptNode,filterNode,hideCompressCallsNode,viewLatchNode,recommendNode,nudgeNode,emergencyTruncateNode];if(strategy==="none")return base;return[...base,createRenderRefsNode(strategy,{timestamps:timestampsOn})]}return{processTurn,retrieve,applyCompression,defaultNodes,decompress,search,status}}function createStampTimestampsNode(enabled){if(!enabled)return{name:"stamp-timestamps",run(io2){return io2}};return{name:"stamp-timestamps",run(io2){const stamps={...io2.state.tsStamps??{}};const knownIds=io2.state.messageRefs.byRaw;let changed=false;const hwmFresh=io2.state.timestampsHighWaterRefSeq===void 0;const hwm=hwmFresh?highestUsedIndex(io2.state.messageRefs):io2.state.timestampsHighWaterRefSeq;const suppressed=io2.state.suppressMintingOnce===true;const messages=io2.messages.map(m2=>{if(!m2.id||m2.id.startsWith(RETRIEVED_ID_PREFIX))return m2;const stamped=stamps[m2.id];if(stamped!==void 0){if(m2.ts===stamped)return m2;const cur=knownIds[m2.id];const seq=cur===void 0?null:refToIndex(cur);if(seq===null||seq<=hwm)return m2;changed=true;return{...m2,ts:stamped}}const carried=typeof m2.ts==="number"?m2.ts:void 0;const ts2=carried??(!suppressed&&knownIds[m2.id]===void 0?Date.now():void 0);if(ts2===void 0)return m2;stamps[m2.id]=ts2;changed=true;return{...m2,ts:ts2}});if(!changed&&!hwmFresh&&!suppressed)return io2;const nextState={...io2.state,tsStamps:stamps,timestampsHighWaterRefSeq:hwm};if(suppressed)delete nextState.suppressMintingOnce;return{...io2,messages,state:nextState}}}}function applySingleRange(input){const warnings=[];const projection=projectUnit({messages:input.messages,state:input.state,config:input.config,startRef:input.spec.startRef,endRef:input.spec.endRef,preExistingCoverage:input.preExistingCoverage,protectedMessageIds:input.protectedMessageIds,warnings});if(projection.fatal){if(projection.fatal.kind==="zone"){const highest=highestUsedIndex(input.state.messageRefs);return{tokens:0,warnings:[`Range ${input.spec.startRef}..${input.spec.endRef} folded nothing \u2014 it lies entirely inside the protected zone (the last ${input.config.preserveRecentMessages} messages and/or the most recent user message), which always stays visible. Nothing failed; do not resend this range. Session highest allocated ref is ${highest>0?indexToRef(highest):"none"} \u2014 target older ranges only.`],noop:true}}if(projection.fatal.kind==="split"&&projection.fatal.degradable){const highest=highestUsedIndex(input.state.messageRefs);return{tokens:0,warnings:[`Range ${input.spec.startRef}..${input.spec.endRef} folded nothing \u2014 the integrity gate keeps every visible tool call's reasoning run and its results together, and folding this range would split that turn at the protected-zone boundary, so the range was withdrawn in full instead of split. Nothing failed; do not resend this range as-is \u2014 it cannot fold until the whole turn ages out of the protected zone. Session highest allocated ref is ${highest>0?indexToRef(highest):"none"} \u2014 target older ranges only.`],noop:true}}throw projection.fatal.error}const{filteredIds,consumedBlockIds,effectiveMessageIds,outputTier,isBlockBoundary}=projection;const retiredConsumed=consumedBlockIds.filter(id=>blockById(input.state,id)?.retired===true);if(retiredConsumed.length>0){throw new Error(`Range ${input.spec.startRef}..${input.spec.endRef} would consume retired block(s) ${retiredConsumed.join(", ")} \u2014 their summaries are out of the resident view by explicit user decision. Re-target the range excluding them, or call acp_restore({ blockId }) first if they should be foldable again.`)}if(!isBlockBoundary&&filteredIds.length===0&&consumedBlockIds.length>0){const decision=evaluateRefold(input.state,input.spec);if(decision.kind==="refold"){applyRefolds({spec:input.spec,state:input.state,runId:input.runId,config:input.config,blockIds:decision.blocks.map(block2=>block2.blockId),minFloorCovered:input.minFloorCovered});return{tokens:0,warnings,refolded:decision.blocks.map(block2=>block2.blockId)}}const first=consumedBlockIds[0];const last=consumedBlockIds[consumedBlockIds.length-1];return{tokens:0,warnings:[`Range ${input.spec.startRef}..${input.spec.endRef} folded nothing \u2014 every message in it is already covered by active block(s) ${consumedBlockIds.join(", ")}. Nothing failed and nothing needed redoing; do not resend this range. To rewrite or merge those blocks, reference them by block ID (${first}..${last}) instead.`],noop:true}}validateCompressionRange(input);if(filteredIds.length===0&&consumedBlockIds.length===0){const highest=highestUsedIndex(input.state.messageRefs);const allCovered=effectiveMessageIds.size>0&&[...effectiveMessageIds].every(id=>input.preExistingCoverage.has(id));return{tokens:0,warnings:[...warnings,allCovered?`Range ${input.spec.startRef}..${input.spec.endRef} folded nothing \u2014 every message in it is already covered by active block(s). Nothing failed; do not resend this range. To rewrite or merge those blocks, reference them by block ID instead.`:`Range ${input.spec.startRef}..${input.spec.endRef} folded nothing \u2014 all of its content is protected or filtered (protected tool calls/results, media, or the recent-message zone), which always stays visible. Nothing failed; do not resend this range. Session highest allocated ref is ${highest>0?indexToRef(highest):"none"}.`],noop:true}}let compressedTokens=0;for(const id of filteredIds){const message=input.messages.find(entry=>entry.id===id);compressedTokens+=message?countMessageTokens(message,input.countTokens):0}for(const consumedId of consumedBlockIds){const consumed=blockById(input.state,consumedId);if(consumed){compressedTokens+=input.countTokens(consumed.summary)}}const foldMediaRefs=collectFoldMediaRefs(filteredIds.map(id=>input.messages.find(entry=>entry.id===id)),consumedBlockIds.map(id=>blockById(input.state,id))).map(scrubLoneSurrogates2);const blockId=allocateBlockId(input.state);const interval=resolveCoverageInterval(filteredIds.map(id=>input.messages.find(entry=>entry.id===id)),consumedBlockIds.map(id=>blockById(input.state,id)));const block={blockId,runId:input.runId,tier:outputTier,topic:input.spec.topic,summary:appendMediaRefsSection(input.spec.summary,foldMediaRefs),directMessageIds:filteredIds,effectiveMessageIds:[...effectiveMessageIds],directBlockIds:[...consumedBlockIds],compressedTokens,createdAt:Date.now(),survivedCount:0,generation:"young",active:true,compressCallId:input.spec.compressCallId,startRef:input.spec.startRef,endRef:input.spec.endRef,...interval?{startSeq:interval.start,endSeq:interval.end}:{}};input.state.blocks.push(block);for(const consumedId of consumedBlockIds){const consumed=blockById(input.state,consumedId);if(consumed)consumed.active=false}return{tokens:compressedTokens,warnings}}function resolveCoverageInterval(directMessages,consumedBlocks){const segments=[];for(const message of directMessages){if(!message||typeof message.ledgerSeq!=="number"||!Number.isInteger(message.ledgerSeq)){return void 0}segments.push({start:message.ledgerSeq,end:message.ledgerSeq})}for(const consumed of consumedBlocks){if(!consumed||typeof consumed.startSeq!=="number"||typeof consumed.endSeq!=="number"||consumed.endSeq<consumed.startSeq||consumed.startSeq<0||consumed.endSeq<0){return void 0}segments.push({start:consumed.startSeq,end:consumed.endSeq})}if(segments.length===0)return void 0;segments.sort((a,b2)=>a.start-b2.start||a.end-b2.end);let merged={...segments[0]};for(const segment of segments.slice(1)){if(segment.start<=merged.end+1){if(segment.end>merged.end)merged.end=segment.end}else{return void 0}}return merged}function validateCompressionRange(input){const cfg=input.config.compress;validateSummaryLength(input.spec,cfg,{skipMin:input.minFloorCovered===true})}function summaryLengthError(kind,message){const error=new Error(message);error.name="SummaryLengthError";error.kind=kind;return error}function isSummaryLengthError(error){if(!(error instanceof Error)||error.name!=="SummaryLengthError")return false;const kind=error.kind;return kind==="empty"||kind==="tooShort"||kind==="tooLong"}function lengthRemediation(kinds){const parts=[];if(kinds.has("tooShort")||kinds.has("empty")){parts.push("expand each too-short/empty summary until it reaches its minimum \u2014 write out the key information the range actually contains (do NOT shorten it)")}if(kinds.has("tooLong")){parts.push("shorten or split each too-long summary to fit its cap")}return`Fix it and resend the whole batch: ${parts.join("; and ")}; or drop the offending range(s) and resend only the rest that validate.`}function validateSummaryLength(spec,cfg,opts={}){const summary=spec.summary?.trim()??"";if(summary.length===0){throw summaryLengthError("empty","Summary is empty \u2014 provide a meaningful summary of the compressed range.")}if(!opts.skipMin&&cfg.minSummaryLength>0&&summary.length<cfg.minSummaryLength){throw summaryLengthError("tooShort",`Summary too short (${summary.length} chars, min ${cfg.minSummaryLength}). The summary must capture the compressed range's key information.`)}const effectiveMax=spec.summaryMaxChars??cfg.maxSummaryLength;if(effectiveMax>0&&summary.length>effectiveMax){throw summaryLengthError("tooLong",`Summary too long (${summary.length} chars, max ${effectiveMax}). Strip noise \u2014 keep critical paths, decisions, errors, and code references. Or pass summaryMaxChars to increase the limit \u2014 don't lose critical info just to fit.`)}}function resolveAdaptiveGrowth(modelContextLimit,nudge){if(!modelContextLimit||modelContextLimit<=0)return nudge.growthFloor;return Math.min(nudge.growthCap,Math.max(nudge.growthFloor,Math.round(modelContextLimit*nudge.growthRatio)))}function resolveMinPressureBenefit(modelContextLimit,nudge){return nudge.minPressureBenefitTokens??Math.max(5e3,Math.round(modelContextLimit*.01))}function pendingByTier(state8,recommendation,countTokens,minCompressRange){const out={};const merged=recommendation?.recommendedRanges??[];const effective=minCompressRange>0?merged.filter(r=>(r.chars??r.tokens*4)>=minCompressRange):merged;out[1]={pending:effective.reduce((s3,r)=>s3+r.tokens,0),targetBlocks:[]};const active=activeBlocks(state8).filter(b2=>!b2.retired);const t1=active.filter(b2=>b2.tier===1);const t2=active.filter(b2=>b2.tier===2);out[2]={pending:t1.reduce((s3,b2)=>s3+countTokens(b2.summary),0),targetBlocks:t1};out[3]={pending:t2.reduce((s3,b2)=>s3+countTokens(b2.summary),0),targetBlocks:t2};return out}function decideNudge(input){const{config,state:state8,tokenCount,recommendation,countTokens}=input;const limit=config.modelContextLimit;const usage=limit>0?tokenCount/limit:0;const nudgeGrowthTokens=resolveAdaptiveGrowth(limit,config.nudge);const minPressureBenefit=resolveMinPressureBenefit(limit,config.nudge);const overLimit=usage>=config.nudge.maxContextLimitPct;const emergencyOverride=usage>=config.nudge.emergencyThresholdPct;const pressure=overLimit||emergencyOverride;const estimateHoldStreak=input.tokenCountSource==="estimate"?(state8.nudge.estimateHoldStreak??0)+1:0;state8.nudge.estimateHoldStreak=estimateHoldStreak>0?estimateHoldStreak:void 0;const maxEstimateHoldRounds=Math.max(0,Math.floor(config.nudge.maxEstimateHoldRounds??2));const pressureDeferredNoSample=pressure&&input.tokenCountSource==="estimate"&&config.nudge.requireUsageSampleForPressure!==false&&estimateHoldStreak<=maxEstimateHoldRounds;const baseline=state8.nudge.lastPerMessageNudgeTokens;const hadPendingNudge=state8.nudge.lastNudgeShownTokens>0;const hasPendingNudge=hadPendingNudge;const effectiveThreshold=hasPendingNudge?Math.floor(nudgeGrowthTokens/2):nudgeGrowthTokens;const growthReference=state8.nudge.lastNudgeShownTokens>0?state8.nudge.lastNudgeShownTokens:baseline>0?baseline:tokenCount;const growthFloor=Math.max(config.nudge.minGrowthFloor,config.nudge.minGrowthRatio*nudgeGrowthTokens);const growthSinceReference=tokenCount-growthReference;const rec=recommendation;const tiers=pendingByTier(state8,rec,countTokens,config.compress.minCompressRange);const tier2Threshold=Math.round(nudgeGrowthTokens*(config.nudge.tier2GrowthMultiplier??1.5));const tierThresholds={1:config.nudge.tierGrowthTokens?.t1??nudgeGrowthTokens,2:config.nudge.tierGrowthTokens?.t2??tier2Threshold,3:config.nudge.tierGrowthTokens?.t3??tier2Threshold};let injectedTier=null;let injectedReason="";let bestPending=0;const t1Eff=tiers[1]?.pending??0;const t2Pen=tiers[2]?.pending??0;const t3Pen=tiers[3]?.pending??0;const maxPending=Math.max(0,t1Eff,t2Pen,t3Pen);const t1HarvestStall=config.tiers.enabled&&state8.nudge.t1HarvestStall===true;let stallEscalated=false;const firstSightMassReady=state8.nudge.lastNudgeShownTokens===0&&baseline===0&&usage>=config.nudge.minContextLimitPct&&Math.max(t1Eff,t2Pen,t3Pen)>=nudgeGrowthTokens;const absorbedDebt=state8.nudge.absorbedDebt??0;const absorbCount=state8.nudge.absorbCount??0;const repeatAbsorbs=absorbCount>=2;const payableDebt=repeatAbsorbs?absorbedDebt:0;const backlogDrainReady=repeatAbsorbs&&absorbedDebt>0&&state8.nudge.lastNudgeShownTokens===0&&Math.max(t1Eff,t2Pen,t3Pen)>=2*tierThresholds[1]&&usage>=config.nudge.minContextLimitPct;const growthReady=firstSightMassReady||backlogDrainReady||growthSinceReference+payableDebt>=growthFloor;const t2Count=tiers[2]?.targetBlocks.length??0;const t3Count=tiers[3]?.targetBlocks.length??0;const t2CountReady=t2Count>=config.tiers.tier2Trigger;const t3CountReady=t3Count>=config.tiers.tier3Trigger;if(pressure){const candidates=[];if(!(t1HarvestStall&&Math.max(t2Pen,t3Pen)>=minPressureBenefit)){candidates.push(1)}if(config.tiers.enabled){candidates.push(2,3)}let best=null;for(const t of candidates){const p2=tiers[t]?.pending??0;if(p2>bestPending){bestPending=p2;best=t}}if(best!==null&&bestPending>=minPressureBenefit&&!pressureDeferredNoSample){injectedTier=best;stallEscalated=t1HarvestStall&&best!==1;const label=emergencyOverride?"EMERGENCY":"OVER-LIMIT";injectedReason=best===1?`${label} T1: max effective pending ${bestPending}, usage ${Math.round(usage*100)}%`:`${label} T${best} distill: max pending ${bestPending} (T1 effective ${t1Eff}, T2 ${t2Pen}, T3 ${t3Pen}), usage ${Math.round(usage*100)}%`}}else if(growthReady){if(t1HarvestStall&&t3Pen>=tierThresholds[3]&&t3Pen>t2Pen){const lastShown=state8.nudge.lastShownByTier[3]??0;const cadenceMet=lastShown===0||tokenCount-lastShown>=growthFloor;if(cadenceMet){injectedTier=3;stallEscalated=true;injectedReason=`T3 condense ready: ${tiers[3].targetBlocks.length} tier-2 blocks (${t3Pen} tokens) >= ${tierThresholds[3]}${config.nudge.tierGrowthTokens?.t3===void 0?" (1.5x)":""} and > T2 ${t2Pen}, usage ${Math.round(usage*100)}%`}}if(injectedTier===null&&t1HarvestStall&&t2Pen>=tierThresholds[2]){const lastShown=state8.nudge.lastShownByTier[2]??0;const cadenceMet=lastShown===0||tokenCount-lastShown>=growthFloor;if(cadenceMet){injectedTier=2;stallEscalated=true;injectedReason=`T2 distill ready: ${tiers[2].targetBlocks.length} tier-1 blocks (${t2Pen} tokens) >= ${tierThresholds[2]}${config.nudge.tierGrowthTokens?.t2===void 0?" (1.5x)":""}, usage ${Math.round(usage*100)}%`}}if(injectedTier===null&&t1Eff>=tierThresholds[1]){injectedTier=1;injectedReason=`T1 effective ${t1Eff} >= ${tierThresholds[1]}, growth ${growthSinceReference}, usage ${Math.round(usage*100)}%`}else if(injectedTier===null&&config.tiers.enabled&&(t2CountReady||t2Pen>=tierThresholds[2]&&t2Pen>t1Eff)){const lastShown=state8.nudge.lastShownByTier[2]??0;const cadenceMet=lastShown===0||tokenCount-lastShown>=growthFloor;if(cadenceMet){injectedTier=2;injectedReason=t2CountReady?`T2 distill ready: ${t2Count} tier-1 blocks >= tier2Trigger ${config.tiers.tier2Trigger} (${t2Pen} tokens), usage ${Math.round(usage*100)}%`:`T2 distill ready: ${tiers[2].targetBlocks.length} tier-1 blocks (${t2Pen} tokens) >= ${tierThresholds[2]}${config.nudge.tierGrowthTokens?.t2===void 0?" (1.5x)":""} and > T1 effective ${t1Eff}, usage ${Math.round(usage*100)}%`}}else if(injectedTier===null&&config.tiers.enabled&&(t3CountReady||t3Pen>=tierThresholds[3]&&t3Pen>t2Pen&&t3Pen>t1Eff)){const lastShown=state8.nudge.lastShownByTier[3]??0;const cadenceMet=lastShown===0||tokenCount-lastShown>=growthFloor;if(cadenceMet){injectedTier=3;injectedReason=t3CountReady?`T3 condense ready: ${t3Count} tier-2 blocks >= tier3Trigger ${config.tiers.tier3Trigger} (${t3Pen} tokens), usage ${Math.round(usage*100)}%`:`T3 condense ready: ${tiers[3].targetBlocks.length} tier-2 blocks (${t3Pen} tokens) >= ${tierThresholds[3]}${config.nudge.tierGrowthTokens?.t3===void 0?" (1.5x)":""} and > T2 ${t2Pen} and > T1 effective ${t1Eff}, usage ${Math.round(usage*100)}%`}}}const shouldInject=injectedTier!==null;if(shouldInject&&firstSightMassReady){injectedReason+=" [first-sight mass]"}if(shouldInject&&stallEscalated){injectedReason+=" [T1 harvest stall]"}let reason;if(injectedTier!==null){reason=injectedReason}else if(pressure&&pressureDeferredNoSample){const label=emergencyOverride?"EMERGENCY":"OVER-LIMIT";reason=`${label}: usage ${Math.round(usage*100)}% but the meter reading is estimate-grade (no billing sample landed this cycle, max pending ${maxPending}) \u2014 pressure injection held (estimate round ${estimateHoldStreak} of ${maxEstimateHoldRounds}) until a usage-grade reading decides or the estimate-hold backstop elapses; hard-overflow backstop unaffected`}else if(pressure){const label=emergencyOverride?"EMERGENCY":"OVER-LIMIT";reason=bestPending===0?`${label}: usage ${Math.round(usage*100)}% but no tier has effective compressible content (T1 effective ${t1Eff}, T2 ${t2Pen}, T3 ${t3Pen}) \u2014 nudge suppressed to avoid offering ranges below minCompressRange`:`${label}: usage ${Math.round(usage*100)}% but max pending ${bestPending} < min benefit ${minPressureBenefit} tokens (T1 effective ${t1Eff}, T2 ${t2Pen}, T3 ${t3Pen}) \u2014 suppressed: rewriting below the benefit floor reclaims almost nothing while usage stays high; truncate.threshold remains the safety valve`}else{const tiersList=[1,2,3];const eligible=tiersList.filter(t=>config.tiers.enabled||t===1);const countReady=t=>t===2?t2Count>=config.tiers.tier2Trigger:t===3?t3Count>=config.tiers.tier3Trigger:false;const ready=eligible.filter(t=>(tiers[t]?.pending??0)>=tierThresholds[t]).map(t=>`T${t} ${tiers[t].pending}`);const readyCount=eligible.filter(t=>(tiers[t]?.pending??0)<tierThresholds[t]&&countReady(t)).map(t=>`T${t} ${t===2?t2Count:t3Count} blocks (count)`);const readyAll=[...ready,...readyCount];const readyHint=readyAll.length>0?`, ready: ${readyAll.join(", ")}`:"";const blocked=eligible.filter(t=>((tiers[t]?.pending??0)>=tierThresholds[t]||countReady(t))&&(state8.nudge.lastShownByTier[t]??0)>0&&tokenCount-(state8.nudge.lastShownByTier[t]??0)<growthFloor).map(t=>`T${t} (cadence)`);const blockedHint=blocked.length>0?`, blocked: ${blocked.join(", ")}`:"";const minTierThreshold=Math.min(tierThresholds[1],tierThresholds[2],tierThresholds[3]);const pendingShort=maxPending<minTierThreshold;const growthShort=growthSinceReference<growthFloor;const parts=[];if(pendingShort)parts.push(`max compressible ${maxPending} < threshold ${minTierThreshold}`);if(growthShort)parts.push(absorbedDebt>0&&!repeatAbsorbs?`growth ${growthSinceReference} + absorbed ${absorbedDebt} held (single abort, #5293) < floor ${growthFloor}`:payableDebt>0?`growth ${growthSinceReference} + absorbed ${absorbedDebt} across ${absorbCount} aborts < floor ${growthFloor}`:`growth ${growthSinceReference} < floor ${growthFloor}`);if(parts.length===0)parts.push(`max compressible ${maxPending}, growth ${growthSinceReference}`);reason=`${parts.join("; ")}${readyHint}${blockedHint}`}const ctxBreakdown=computeContextBreakdown(input.messages,tokenCount,growthSinceReference,countTokens);return{shouldInject,reason,compressibleRanges:rec?.recommendedRanges??[],protectedRanges:rec?.contextRanges.protected??[],activeBlockSpans:activeBlockSpans(state8),tierTargetBlocks:injectedTier?tiers[injectedTier].targetBlocks:[],contextUsage:usage,tier:injectedTier,breakdown:{usage,growth:growthSinceReference,growthReference,effectiveThreshold,nudgeGrowthTokens,growthFloor,hasPendingNudge:hasPendingNudge?1:0,overLimit:overLimit?1:0,emergencyOverride:emergencyOverride?1:0,pressureDeferredNoSample:pressureDeferredNoSample?1:0,estimateHoldStreak,minPressureBenefit,pendingT1:tiers[1].pending,pendingT2:tiers[2].pending,pendingT3:tiers[3].pending,maxPending},contextBreakdown:ctxBreakdown}}function computeContextBreakdown(messages,total,growth,countTokens){const count=countTokens??(t=>Math.ceil(t.length/4));let system=0,tool=0,summaries=0,code=0,text2=0;for(const msg of messages){const tokens=countMessageTokens(msg,count);if(msg.text?.startsWith("[Compressed conversation section]")){summaries+=tokens}else if(isToolMessage(msg)){tool+=tokens}else if(msg.role==="system"){system+=tokens}else if(msg.text?.includes("```")){code+=tokens}else{text2+=tokens}}return{system,tool,summaries,code,text:text2,total,growth}}function cloneState(state8){return{blocks:state8.blocks.map(block=>({...block,directMessageIds:[...block.directMessageIds],effectiveMessageIds:[...block.effectiveMessageIds],directBlockIds:[...block.directBlockIds]})),messageRefs:{byRaw:{...state8.messageRefs.byRaw},byRef:{...state8.messageRefs.byRef}},tokenSnapshot:{...state8.tokenSnapshot??{}},tsStamps:state8.tsStamps?{...state8.tsStamps}:void 0,nudge:{...state8.nudge,anchors:{...state8.nudge.anchors}},stats:{...state8.stats},absorbed:(state8.absorbed??[]).map(record3=>({...record3})),rules:(state8.rules??[]).map(rule=>({...rule})),nextRuleId:state8.nextRuleId,terminalStreak:state8.terminalStreak,nextBlockId:state8.nextBlockId,nextRunId:state8.nextRunId,hiddenOrphanRefs:state8.hiddenOrphanRefs?[...state8.hiddenOrphanRefs]:void 0,sweptOrphanCallIds:state8.sweptOrphanCallIds?[...state8.sweptOrphanCallIds]:void 0,pendingOrphanSweepMinRef:state8.pendingOrphanSweepMinRef,deadRefs:state8.deadRefs?[...state8.deadRefs]:void 0,lastPassIds:state8.lastPassIds?[...state8.lastPassIds]:void 0,refLedgerAligned:state8.refLedgerAligned,emergencyTruncateLatch:state8.emergencyTruncateLatch?state8.emergencyTruncateLatch.map(e=>({ref:e.ref,text:e.text})):void 0,renderDeferredRefs:state8.renderDeferredRefs?[...state8.renderDeferredRefs]:void 0,viewLatches:state8.viewLatches?Object.fromEntries(Object.entries(state8.viewLatches).map(([k2,v2])=>[k2,{...v2}])):void 0,viewLatchConfigDigest:state8.viewLatchConfigDigest,...state8.timestampsHighWaterRefSeq!==void 0?{timestampsHighWaterRefSeq:state8.timestampsHighWaterRefSeq}:{},...state8.suppressMintingOnce!==void 0?{suppressMintingOnce:state8.suppressMintingOnce}:{}}}function scoreRelevance(block,terms){const topic=(block.topic??"").toLowerCase();const summary=block.summary.toLowerCase();let score=0;for(const term of terms){const topicHits=countOccurrences(topic,term);if(topicHits>0)score+=Math.min(topicHits*.15,.45);const summaryHits=countOccurrences(summary,term);if(summaryHits>0)score+=Math.min(summaryHits*.04,.2)}return Math.min(score,1)}function countOccurrences(haystack,needle){if(!haystack||!needle)return 0;let count=0;let position=0;while((position=haystack.indexOf(needle,position))!==-1){count++;position+=needle.length}return count}function isValidPackName(name2){return/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name2)&&!name2.includes("..")}function triStateSection(raw,keys){const out={};if(!raw||typeof raw!=="object"||Array.isArray(raw))return out;for(const key2 of keys){const v2=raw[key2];if(typeof v2==="string")out[key2]=v2;else if(v2===null)out[key2]=null}return out}function sanitizePackSurface(raw){if(!raw)return{};const prompts={};const rawPrompts=raw.prompts;if(rawPrompts&&typeof rawPrompts==="object"&&!Array.isArray(rawPrompts)){for(const k2 of PROMPT_RULE_KEYS){const v2=rawPrompts[k2];if(typeof v2==="string")prompts[k2]=v2}}const toolPrompts={};const rawTools=raw.toolPrompts;if(rawTools&&typeof rawTools==="object"&&!Array.isArray(rawTools)){for(const[name2,value]of Object.entries(rawTools)){if(!value||typeof value!=="object"||Array.isArray(value))continue;const ov=value;const out={};if(typeof ov.description==="string")out.description=ov.description;if(ov.paramDescriptions&&typeof ov.paramDescriptions==="object"&&!Array.isArray(ov.paramDescriptions)){const params={};for(const[p2,d]of Object.entries(ov.paramDescriptions)){if(typeof d==="string")params[p2]=d}if(Object.keys(params).length>0)out.paramDescriptions=params}if(Object.keys(out).length>0)toolPrompts[name2]=out}}const surface={prompts,promptSections:triStateSection(raw.promptSections,COMPRESS_SECTION_KEYS),nudgeSections:triStateSection(raw.nudgeSections,NUDGE_SECTION_KEYS),toolPrompts};const adapters=raw.adapters;if(adapters&&typeof adapters==="object"&&!Array.isArray(adapters)){surface.adapters=adapters}return surface}function readPackFile(file){try{const parsed=JSON.parse(readFileSync2(file,"utf8"));return parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}catch{return null}}function createDirPackSource(id,dir){const resolve3=name2=>{if(!isValidPackName(name2))return null;const file=path10.join(dir,`${name2}.json`);const raw=readPackFile(file);if(!raw)return null;return{name:name2,version:typeof raw.version==="string"?raw.version:void 0,description:typeof raw.description==="string"?raw.description:void 0,surface:sanitizePackSurface(raw),source:`file:${file}`}};return{id,resolve:resolve3,list(){let names;try{names=readdirSync3(dir).filter(f2=>f2.endsWith(".json"))}catch{return[]}const out=[];for(const f2 of names){const pack=resolve3(f2.slice(0,-5));if(pack)out.push(pack)}return out}}}function createPackResolver(sources2){return{sources:sources2,resolve(name2){if(!isValidPackName(name2))return null;for(const source of sources2){const pack=source.resolve(name2);if(pack)return pack}return null},listPacks(){const seen=new Set;const out=[];for(const source of sources2){for(const pack of source.list?.()??[]){if(!seen.has(pack.name)){seen.add(pack.name);out.push(pack)}}}return out}}}function resolveActiveBlock(state8,raw){const normalized=typeof raw==="string"?raw.trim():"";const blockId=parseBlockIdArg(normalized);if(!blockId){return{error:`"${normalized}" is not a valid block id (expected e.g. b5)`}}const block=state8.blocks.find(b2=>b2.blockId===blockId);if(!block){return{error:`${blockId} does not exist in this session \u2014 run acp_status for the current block list`}}if(!block.active){return{error:`${blockId} is not active (distilled into a higher tier or deactivated) \u2014 only active blocks can be operated on`}}return{blockId,state:state8}}function retireBlocks(state8,rawIds){const outcome={applied:[],noop:[],failed:[]};for(const raw of rawIds){const target=resolveActiveBlock(state8,raw);if("error"in target){outcome.failed.push({id:String(raw).trim(),reason:target.error});continue}const block=state8.blocks.find(b2=>b2.blockId===target.blockId);if(block.retired){outcome.noop.push(block.blockId)}else{block.retired=true;outcome.applied.push(block.blockId)}}return outcome}function restoreBlocks(state8,rawIds){const outcome={applied:[],noop:[],failed:[]};for(const raw of rawIds){const target=resolveActiveBlock(state8,raw);if("error"in target){outcome.failed.push({id:String(raw).trim(),reason:target.error});continue}const block=state8.blocks.find(b2=>b2.blockId===target.blockId);if(block.retired){block.retired=false;outcome.applied.push(block.blockId)}else{outcome.noop.push(block.blockId)}}return outcome}function rewriteBlockSummary(state8,raw,newSummary){const target=resolveActiveBlock(state8,raw);if("error"in target)return{ok:false,id:String(raw).trim(),reason:target.error};const block=state8.blocks.find(b2=>b2.blockId===target.blockId);const next=typeof newSummary==="string"?newSummary.trim():"";if(!next){return{ok:false,id:block.blockId,reason:"summary must be non-empty text"}}if(next===block.summary.trim()){return{ok:false,id:block.blockId,reason:"new summary is identical to the current one \u2014 nothing to do"}}block.previousSummary=block.summary;block.summary=next;block.rewrittenAt=Date.now();return{ok:true,blockId:block.blockId,prevChars:block.previousSummary.length,newChars:next.length}}function formatTokens2(n){if(!Number.isFinite(n)||n<=0)return"0";return n>=1e3?`${(n/1e3).toFixed(1)}K`:String(n)}function pct(n,total){if(n<=0||total<=0)return 0;return Math.round(n/total*100)}function numericPart2(blockId){const match=/^b(\d+)$/.exec(blockId);return match&&match[1]!==void 0?Number(match[1]):0}function summaryTokensOf(block,countTokens){return countTokens(block.summary)}function effectiveCompressedTokens(block,_state,_countTokens){return block.compressedTokens}function tierLabel(block){return`T${block.tier}`}function tierBreakdown(blocks,countTokens){const tierTokens={};const tierCounts={};for(const block of blocks){tierTokens[block.tier]=(tierTokens[block.tier]??0)+summaryTokensOf(block,countTokens);tierCounts[block.tier]=(tierCounts[block.tier]??0)+1}const tiers=Object.keys(tierTokens).map(Number);if(tiers.length<=1)return null;const parts=[];for(const tier of[1,2,3]){if(tierTokens[tier])parts.push(`T${tier}: ${formatTokens2(tierTokens[tier])} (${tierCounts[tier]} blocks)`)}return parts.join(" | ")}function collectVisible(messages,state8,countTokens){const coveredIds=new Set;for(const block of state8.blocks){if(!block.active)continue;for(const id of block.effectiveMessageIds)coveredIds.add(id)}let summaryTokens=0;for(const block of state8.blocks){if(block.active&&!block.retired)summaryTokens+=summaryTokensOf(block,countTokens)}const visible=[];const summaryNodes=[];const toolCallNames=new Map;for(const message of messages){if(message.contentType==="tool-call"&&message.toolCallId&&message.toolName){toolCallNames.set(message.toolCallId,message.toolName)}}let pendingGap=false;messages.forEach((message,index)=>{const ref=refForRaw(state8.messageRefs,message.id);if(!ref)return;const tokens=countMessageTokens(message,countTokens);if(isRenderedSummaryMessage(message)){if(ref!==BLOCKED_REF&&tokens>0){const blockId=summaryBlockIdOf(message.id);if(blockId!==null){summaryNodes.push({ref,blockId,tokens});pendingGap=true}}return}if(!coveredIds.has(message.id)&&tokens>0){const isTool=isToolMessage(message);const tool=isTool?message.toolName??(message.toolCallId?toolCallNames.get(message.toolCallId):void 0)??"tool":"text";visible.push({ref,tokens,tool,isTool,index,isUser:message.role==="user",gapBefore:pendingGap,toolCallId:message.toolCallId});pendingGap=isLiveCheckpointCarrier(message,state8);return}if(ref!==BLOCKED_REF&&tokens>0)pendingGap=true});return{visible,summaryTokens,summaryNodes}}function buildStatusReport(state8,messages,countTokens,options={}){const scope=options.scope;const view=options.view??"ranges";const toolFilter=options.tool;const sort=options.sort??"size";const limit=options.limit??30;const activeBlocks2=state8.blocks.filter(b2=>b2.active).sort((a,b2)=>numericPart2(a.blockId)-numericPart2(b2.blockId));const residentBlocks=activeBlocks2.filter(b2=>!b2.retired);const retiredBlocks=activeBlocks2.filter(b2=>b2.retired);if(scope==="compressed"){return renderCompressedDrilldown(activeBlocks2,state8,sort,limit,countTokens,options.meta)}const{visible,summaryTokens,summaryNodes}=collectVisible(messages,state8,countTokens);if(scope==="uncompressed"){if(view==="messages"){const cfg=options.config;const orig=options.originalMessages;const blockedInfo=cfg&&orig?{agedIds:collectAgedCompressCallIds(orig,cfg),isCompress:t=>isCompressToolName(t,cfg)}:void 0;return renderMessageDrilldown(visible,toolFilter,sort,limit,blockedInfo)}return renderUncompressedRanges(visible,summaryNodes,sort,limit,state8,countTokens,options.config,options.originalMessages)}return renderOverview(visible,summaryTokens,residentBlocks,retiredBlocks,state8,countTokens,limit,options.meta)}function surfaceLine(meta){if(!meta)return null;const parts=[];if(meta.pack)parts.push(`pack=${meta.pack}${meta.packVersion?` v${meta.packVersion}`:""}`);if(meta.host)parts.push(`host=${meta.host}`);if(parts.length===0)return null;return`ACTIVE SURFACE: ${parts.join(" | ")}`}function renderOverview(visible,summaryTokens,blocks,retiredBlocks,state8,countTokens,limit,meta){const lines=[];const surface=surfaceLine(meta);if(surface){lines.push(surface);lines.push("")}const toolTypeMap=new Map;for(const message of visible){toolTypeMap.set(message.tool,(toolTypeMap.get(message.tool)??0)+message.tokens)}const totalTool=visible.filter(m2=>m2.isTool).reduce((sum,m2)=>sum+m2.tokens,0);const totalText=visible.filter(m2=>!m2.isTool).reduce((sum,m2)=>sum+m2.tokens,0);const total=summaryTokens+totalTool+totalText;lines.push("CONTEXT BREAKDOWN");lines.push(` ${formatTokens2(totalTool)} tool (${pct(totalTool,total)}%) | ${formatTokens2(totalText)} text (${pct(totalText,total)}%) | ${formatTokens2(summaryTokens)} summaries (${pct(summaryTokens,total)}%)`);const topTypes=[...toolTypeMap.entries()].sort((a,b2)=>b2[1]-a[1]).slice(0,3);if(topTypes.length>0){lines.push(` Top tools: ${topTypes.map(([t,n])=>`${t} (${pct(n,total)}%)`).join(", ")}`)}lines.push("");if(blocks.length===0){lines.push("COMPRESSED BLOCKS");lines.push(" No compressed blocks.")}else{const totalSummary=blocks.reduce((s3,b2)=>s3+summaryTokensOf(b2,countTokens),0);const totalEffective=blocks.reduce((s3,b2)=>s3+effectiveCompressedTokens(b2,state8,countTokens),0);lines.push(`COMPRESSED BLOCKS \u2014 ${blocks.length} active (${formatTokens2(totalSummary)} summary, ${formatTokens2(totalEffective)} original)`);const breakdown=tierBreakdown(blocks,countTokens);if(breakdown)lines.push(` Tier usage: ${breakdown}`);lines.push("");const sorted=[...blocks].sort((a,b2)=>effectiveCompressedTokens(b2,state8,countTokens)-effectiveCompressedTokens(a,state8,countTokens)||b2.createdAt-a.createdAt);for(const block of sorted.slice(0,limit)){const topic=block.topic??"(no topic)";const eff=effectiveCompressedTokens(block,state8,countTokens);lines.push(` ${block.blockId} (${tierLabel(block)}) ${formatTokens2(eff)}\u2192${formatTokens2(summaryTokensOf(block,countTokens))} ${block.effectiveMessageIds.length} msgs "${topic}"`)}if(blocks.length>limit){lines.push(` ... and ${blocks.length-limit} more blocks not shown (scope:"compressed", limit:${blocks.length} for full list)`)}}if(retiredBlocks.length>0){const freed=retiredBlocks.reduce((s3,b2)=>s3+summaryTokensOf(b2,countTokens),0);lines.push("");lines.push(`RETIRED BLOCKS \u2014 ${retiredBlocks.length} out of the resident view (${formatTokens2(freed)} summary kept off the wire)`);const sorted=[...retiredBlocks].sort((a,b2)=>numericPart2(a.blockId)-numericPart2(b2.blockId));for(const block of sorted.slice(0,limit)){const topic=block.topic??"(no topic)";lines.push(` ${block.blockId} (${tierLabel(block)}) ${formatTokens2(summaryTokensOf(block,countTokens))} summary ${block.effectiveMessageIds.length} msgs "${topic}"`)}if(retiredBlocks.length>limit){lines.push(` ... and ${retiredBlocks.length-limit} more retired blocks not shown`)}lines.push(` acp_restore({ blockId }) puts a block back into the view; decompress/search_context work on retired blocks as usual.`)}lines.push("");lines.push(`Tip: call again with scope:"uncompressed" for the compressible-ranges listing (view:"messages" drills into individual refs)`);return lines.join("\n")}function renderUncompressedRanges(visible,summaryNodes,sort,limit,state8,countTokens,config,original){const lines=[];const totalTokens=visible.reduce((s3,m2)=>s3+m2.tokens,0);const blockedRows=visible.filter(m2=>m2.ref===BLOCKED_REF);const rangeable=visible.filter(m2=>m2.ref!==BLOCKED_REF);lines.push(`UNCOMPRESSED \u2014 ${formatTokens2(totalTokens)} | ${rangeable.length} visible messages${blockedRows.length>0?` + ${blockedRows.length} unrefed`:""}`);lines.push("");if(visible.length===0&&summaryNodes.length===0){lines.push(" (no uncompressed messages)");return lines.join("\n")}const dominantTool=toolTokens=>{let best="text";let bestN=-1;for(const[tool,n]of toolTokens){if(n>bestN){best=tool;bestN=n}}return best};const merged=[];for(const group of segmentGroups(rangeable)){const first=group[0];const r={startRef:first.ref,endRef:first.ref,startIndex:first.index,count:1,tokens:first.tokens,toolTokens:new Map([[first.tool,first.tokens]])};for(let i=1;i<group.length;i++){const m2=group[i];r.endRef=m2.ref;r.count+=1;r.tokens+=m2.tokens;r.toolTokens.set(m2.tool,(r.toolTokens.get(m2.tool)??0)+m2.tokens)}merged.push(r)}if(sort!=="time")merged.sort((a,b2)=>b2.tokens-a.tokens||a.startIndex-b2.startIndex);let flagFor=null;if(config&&original){const coverage=collectCoverage(state8);const protectedRefs=computeProtectedRefs(original,state8,config,countTokens);const shared=buildProjectionShared(original,state8,config);const splitDescOf=p2=>{const parts=[];if(p2.splitTurnCount>0)parts.push(`${p2.splitTurnCount} turn(s)`);if(p2.splitPairCount>0)parts.push(`${p2.splitPairCount} tool call/result pair(s)`);return parts.join(" and ")||"turn structure"};flagFor=r=>{let proj;try{proj=projectUnit({messages:original,state:state8,config,startRef:r.startRef,endRef:r.endRef,preExistingCoverage:coverage,protectedMessageIds:protectedRefs,shared})}catch{return"\u26A0 not foldable: refs unresolvable"}if(proj.fatal?.kind==="zone")return"\u26A0 not foldable: protected zone only";if(proj.fatal?.kind==="split")return`\u26A0 not foldable: would split ${splitDescOf(proj)}`;if(proj.filteredIds.length===0&&proj.consumedBlockIds.length===0)return"\u26A0 not foldable: nothing new to fold";return null}}lines.push(`Sorted by ${sort==="time"?"time":"size"}`);lines.push("");if(rangeable.length===0){lines.push(" (no raw uncompressed messages)")}else{for(const r of merged.slice(0,limit)){const range=r.count===1?r.startRef:orderedRefPair(r.startRef,r.endRef).join("\u2013");const flag=flagFor?flagFor(r):null;lines.push(` ${range} (${r.count} msgs, ${formatTokens2(r.tokens)}${r.count>1?` (${Math.round(r.tokens/r.count)}/msg)`:""}) ${dominantTool(r.toolTokens)}${flag?` ${flag}`:""}`)}if(merged.length>limit){lines.push(` ... and ${merged.length-limit} more ranges`)}lines.push("");lines.push(` To fold one of the ranges above: compress({ content: "m00150\u2013m00220 optional topic\\n<summary markdown>" })`)}if(summaryNodes.length>0){const sumTokens=summaryNodes.reduce((s3,n)=>s3+n.tokens,0);lines.push("");lines.push(`ALREADY-COMPRESSED SUMMARY NODES \u2014 ${summaryNodes.length} node(s), ${formatTokens2(sumTokens)}`);const shown=summaryNodes.slice(0,limit);lines.push(` ${shown.map(n=>{const block=state8.blocks.find(b2=>b2.blockId===n.blockId&&b2.active);return block?`${n.blockId} (T${block.tier}) ${formatTokens2(n.tokens)}`:`${n.blockId} ${formatTokens2(n.tokens)}`}).join(" \xB7 ")}`);if(summaryNodes.length>limit){lines.push(` ... and ${summaryNodes.length-limit} more nodes (scope:"compressed" lists every block)`)}lines.push(` These are block summaries already in the view \u2014 plain m-ref ranges do not fold them; only tier distillation (block-ID boundaries) does.`);const hint=config?tierActionHint(config,state8).trim():"";if(hint){lines.push(` ${hint}`)}else if(config){lines.push(` Tier distillation is not armed yet \u2014 the nudge announces when block-ID distillation is actionable.`)}else{lines.push(` Fold them via tier distillation: compress({ content: "b1\u2013bN optional topic\\nsummary markdown..." })`)}}if(blockedRows.length>0){const blockedTokens=blockedRows.reduce((s3,m2)=>s3+m2.tokens,0);lines.push("");lines.push(`UNREFED MESSAGES \u2014 ${blockedRows.length} msg(s), ${formatTokens2(blockedTokens)} (protected rows \u2014 no m-ref to cite; cannot be folded by name)`);const isCompressRow=m2=>config?isCompressToolName(m2.tool,config):m2.tool==="compress";const compressRows=blockedRows.filter(isCompressRow);const otherRows=blockedRows.filter(m2=>!isCompressRow(m2));if(compressRows.length>0){const cTokens=compressRows.reduce((s3,m2)=>s3+m2.tokens,0);const callIds=new Set;for(const m2 of compressRows)if(m2.toolCallId)callIds.add(m2.toolCallId);const exchangeCount=callIds.size>0?callIds.size:compressRows.length;let detail=" \u2014 pinned compress receipts";if(config&&original){const agedAll=collectAgedCompressCallIds(original,config);const aged=[...callIds].filter(id=>agedAll.has(id)).length;const newest=exchangeCount-aged;detail=" \u2014 pinned compress receipts: "+(newest>0?`${newest} newest = working memory; `:"")+(aged>0?`the ${aged} older exchange(s) are consumed by any fold that spans their position (cite the refs on either side)`:`all ${exchangeCount} are protected working memory (newest ${COMPRESS_EXCHANGE_KEEP_RECENT} stay pinned)`)}lines.push(` compress: ${exchangeCount} exchange(s), ${formatTokens2(cTokens)}${detail}`)}if(otherRows.length>0){const oTokens=otherRows.reduce((s3,m2)=>s3+m2.tokens,0);lines.push(` other: ${otherRows.length} msg(s), ${formatTokens2(oTokens)} \u2014 hard protection (unrecoverable media / protectedTools)`)}}return lines.join("\n")}function renderMessageDrilldown(visible,toolFilter,sort,limit,blockedInfo){let filtered=visible;if(toolFilter)filtered=filtered.filter(m2=>m2.tool===toolFilter);if(sort==="time")filtered.sort((a,b2)=>a.index-b2.index);else if(sort==="tool")filtered.sort((a,b2)=>a.tool.localeCompare(b2.tool)||b2.tokens-a.tokens);else filtered.sort((a,b2)=>b2.tokens-a.tokens);const totalTokens=filtered.reduce((s3,m2)=>s3+m2.tokens,0);const allTokens=visible.reduce((s3,m2)=>s3+m2.tokens,0);const header2=toolFilter?`UNCOMPRESSED \u2014 ${toolFilter}: ${formatTokens2(totalTokens)} | ${filtered.length} msgs | ${pct(totalTokens,allTokens)}% of visible`:`UNCOMPRESSED \u2014 ${formatTokens2(totalTokens)} | ${filtered.length} msgs`;const lines=[header2,`Sorted by ${sort}`,""];const shown=filtered.slice(0,limit);for(const message of shown){let suffix="";if(message.ref===BLOCKED_REF){if(blockedInfo?.isCompress(message.tool)){suffix=message.toolCallId&&blockedInfo.agedIds.has(message.toolCallId)?" \xB7 aged \u2014 folds when a range spans it":" \xB7 newest \u2014 working memory"}else if(message.tool!=="text"){suffix=" \xB7 protected"}}lines.push(` ${message.ref===BLOCKED_REF?"(unrefed)":message.ref} (${formatTokens2(message.tokens)}) ${message.tool}${suffix}`)}if(filtered.length>shown.length){lines.push("");lines.push(`${shown.length} of ${filtered.length} shown.`)}return lines.join("\n")}function renderCompressedDrilldown(blocks,state8,sort,limit,countTokens,meta){let sorted=[...blocks];if(sort==="time")sorted.sort((a,b2)=>a.createdAt-b2.createdAt);else if(sort==="age")sorted.sort((a,b2)=>b2.survivedCount-a.survivedCount);else sorted.sort((a,b2)=>effectiveCompressedTokens(b2,state8,countTokens)-effectiveCompressedTokens(a,state8,countTokens)||b2.createdAt-a.createdAt);const totalSummary=sorted.reduce((s3,b2)=>s3+summaryTokensOf(b2,countTokens),0);const totalEffective=sorted.reduce((s3,b2)=>s3+effectiveCompressedTokens(b2,state8,countTokens),0);const lines=[];const surface=surfaceLine(meta);if(surface){lines.push(surface);lines.push("")}lines.push(`COMPRESSED \u2014 ${sorted.length} blocks | ${formatTokens2(totalEffective)} original \u2192 ${formatTokens2(totalSummary)} summary`);const breakdown=tierBreakdown(sorted,countTokens);if(breakdown)lines.push(`Tier usage: ${breakdown}`);lines.push("");const shown=sorted.slice(0,limit);for(const block of shown){const nested=block.directBlockIds.length>0?` nested=[${block.directBlockIds.join(",")}]`:"";const topic=block.topic??"(no topic)";const eff=effectiveCompressedTokens(block,state8,countTokens);const retiredMark=block.retired?", retired":"";lines.push(` ${block.blockId} (${tierLabel(block)}${retiredMark}) ${formatTokens2(eff)}\u2192${formatTokens2(summaryTokensOf(block,countTokens))} ${block.effectiveMessageIds.length} msgs age=${block.survivedCount} ${block.generation}${nested}`);lines.push(` "${topic}"`)}if(sorted.length>shown.length){lines.push("");lines.push(`${shown.length} of ${sorted.length} shown.`)}return lines.join("\n")}function decomposeSample(prev,cur,pendingFolds){const missed=Math.max(0,cur.input-cur.cached);const growth=prev?Math.max(0,cur.input-prev.input):0;const newContent=Math.min(missed,growth);const remainder=missed-newContent;let compRepay=0;let foldIndex=null;if(remainder>0&&pendingFolds.length>0){let bestX=Infinity;let owner=-1;for(let i=0;i<pendingFolds.length;i++){const f2=pendingFolds[i];const x=f2.firstFoldStartTokens??f2.viewAfter??0;if(x<bestX){bestX=x;owner=i}}const structuralExcess=Math.max(0,cur.input-bestX-newContent);compRepay=Math.min(remainder,structuralExcess);if(compRepay>0)foldIndex=owner}return{missed,newContent,compRepay,ttlRepay:remainder-compRepay,foldIndex}}function computeFoldEconomics(f2,price){const w2=price?.w??1;const r=price?.r??.1;const q2=price?.q??4;const netTokenDelta=f2.T+f2.sigma-f2.S;const savingPerTurn=f2.S-f2.sigma;const oneTimeCostUnits=(w2-r)*f2.T+q2*f2.sigma-r*f2.S;const perTurnSavingUnits=savingPerTurn*r;const breakevenTurns=perTurnSavingUnits>0?Math.max(0,oneTimeCostUnits)/perTurnSavingUnits:null;const paidBack=breakevenTurns!==null?f2.requestsAfter>=breakevenTurns:null;const cadenceOk=f2.turnsToNextFold!==null&&breakevenTurns!==null?f2.turnsToNextFold>=breakevenTurns:null;return{seq:f2.seq,at:f2.at,S:f2.S,sigma:f2.sigma,Vprime:f2.Vprime??null,hPct:f2.hPct,T:f2.T,requestsAfter:f2.requestsAfter,savedSoFar:Math.max(0,savingPerTurn)*f2.requestsAfter,turnsToNextFold:f2.turnsToNextFold,netTokenDelta,oneTimeCostUnits:round1(oneTimeCostUnits),perTurnSavingUnits:round1(perTurnSavingUnits),breakevenTurns,paidBack,cadenceOk}}function summarizeFoldEconomics(foldEcon){const econ={folds:foldEcon.length,grossSaved:foldEcon.reduce((n,e)=>n+e.savedSoFar,0),repayCost:foldEcon.reduce((n,e)=>n+e.T,0),summaryCost:foldEcon.reduce((n,e)=>n+e.sigma,0),netTokens:0,paidBackCount:0,notPaidBackCount:0,unobservedCount:0};econ.netTokens=econ.grossSaved-econ.repayCost-econ.summaryCost;for(const e of foldEcon){if(e.paidBack===true)econ.paidBackCount++;else if(e.paidBack===false)econ.notPaidBackCount++;else econ.unobservedCount++}return econ}function round1(n){return Math.round(n*10)/10}function fmtTok(n){const v2=Math.round(n);return v2>=1e6?`${(v2/1e6).toFixed(2)}M`:v2>=1e4?`${(v2/1e3).toFixed(1)}K`:String(v2)}function fmtTime(at2){const d=new Date(at2);const p2=x=>String(x).padStart(2,"0");return`${p2(d.getHours())}:${p2(d.getMinutes())}:${p2(d.getSeconds())}`}function hitVerdict(pct2){if(pct2>=HIT_HEALTHY_PCT)return"HEALTHY";if(pct2>=HIT_WATCH_PCT)return"WATCH";return"INVESTIGATE"}function medianHitPct(lines){if(lines.length===0)return null;const xs2=lines.map(l=>l.hitPct).sort((a,b2)=>a-b2);return xs2[Math.floor(xs2.length/2)]??null}function fmtIdleGap(ms2){if(ms2<9e4)return`${Math.max(1,Math.round(ms2/1e3))}s`;if(ms2<90*6e4)return`${Math.round(ms2/6e4)}m`;if(ms2<36*36e5)return`${(ms2/36e5).toFixed(1)}h`;return`${(ms2/864e5).toFixed(1)}d`}function foldVerdict(f2){return f2.paidBack===null?"?":f2.paidBack?"PAID BACK":"NOT PAID BACK"}function formatCacheReportFull(report){const t=report.totals;const out=[];out.push("GRAND LEDGER");out.push(` total input ${fmtTok(t.input)} tok`);out.push(` total cached ${fmtTok(t.cached)} tok (hit ${t.hitPct.toFixed(1)}%)`);out.push(` total output ${fmtTok(t.output)} tok`);out.push(` miss breakdown (input \u2212 cached = ${fmtTok(Math.max(0,t.input-t.cached))} tok):`);out.push(` new content ${fmtTok(t.newContent)} tok (fresh append \u2014 not an invalidation)`);out.push(` compress re-pay ${fmtTok(t.compRepay)} tok (caused by folds)`);out.push(` upstream-ttl-or-client-rewrite (unattributed) ${fmtTok(t.ttlRepay)} tok (stable-prefix misses: upstream TTL expiry / eviction or client-side wire rewrite \u2014 kernel cannot distinguish)`);out.push(` identity check ${t.balanced?"OK":"BROKEN"} \u2014 ${fmtTok(t.input)} = ${fmtTok(t.cached)} + ${fmtTok(t.newContent)} + ${fmtTok(t.compRepay)} + ${fmtTok(t.ttlRepay)} (residual ${t.residual})`);const e=report.economics;if(e.folds>0){const p2=report.profile;out.push("");out.push(`FOLD ECONOMICS (${e.folds} folds @ w=${p2.w} r=${p2.r} q=${p2.q})`);out.push(` gross saved ${fmtTok(e.grossSaved)} tok \xB7 repay cost ${fmtTok(e.repayCost)} tok \xB7 summary cost ${fmtTok(e.summaryCost)} tok \u2192 net ${e.netTokens>=0?"+":""}${fmtTok(e.netTokens)} tok`);out.push(` verdict: ${e.paidBackCount} paid back, ${e.notPaidBackCount} not paid back, ${e.unobservedCount} unobserved`);for(const f2 of report.folds){const nstar=f2.breakevenTurns===null?"n/a":f2.breakevenTurns.toFixed(2);const k2=f2.turnsToNextFold===null?"\u2014":String(f2.turnsToNextFold);const verdict=f2.paidBack===null?"?":f2.paidBack?"PAID BACK":"NOT PAID BACK";const h=f2.hPct===null?"n/a":`${f2.hPct.toFixed(1)}%`;out.push(` #${f2.seq} ${fmtTime(f2.at)} S=${fmtTok(f2.S)} \u03C3=${fmtTok(f2.sigma)} h=${h} T=${fmtTok(f2.T)} \u0394C\u2081=${fmtTok(f2.oneTimeCostUnits)} \u0394s=${fmtTok(f2.perTurnSavingUnits)}/turn n*=${nstar} k=${k2} \u2192 ${verdict}`)}}if(report.lines.length>0){out.push("");if(report.linesOmitted>0)out.push(`LINE ITEMS (last ${report.lines.length} of ${report.lines.length+report.linesOmitted}):`);else out.push("LINE ITEMS:");out.push(" # time input cached hit% new comp ttl fold");for(const l of report.lines){const fold=l.foldSeq!==null?`#${l.foldSeq}`:"";out.push(` ${String(l.seq).padStart(4)} ${fmtTime(l.at)} ${fmtTok(l.input).padStart(7)} ${fmtTok(l.cached).padStart(7)} ${l.hitPct.toFixed(1).padStart(5)}% ${fmtTok(l.newContent).padStart(6)} ${fmtTok(l.compRepay).padStart(6)} ${fmtTok(l.ttlRepay).padStart(6)} ${fold}`)}}return out.join("\n")}function formatCacheReportSummary(report){const t=report.totals;const out=[];out.push("GRAND LEDGER");out.push(` total input ${fmtTok(t.input)} tok`);out.push(` total cached ${fmtTok(t.cached)} tok (hit ${t.hitPct.toFixed(1)}% \u2192 ${hitVerdict(t.hitPct)})`);out.push(` total output ${fmtTok(t.output)} tok`);out.push(` miss breakdown (input \u2212 cached = ${fmtTok(Math.max(0,t.input-t.cached))} tok):`);const avgNew=t.requests>0?t.newContent/t.requests:0;out.push(` new content ${fmtTok(t.newContent)} tok (~${fmtTok(avgNew)}/req fresh append \u2014 not an invalidation)`);out.push(` compress re-pay ${fmtTok(t.compRepay)} tok (${report.economics.folds} folds \u2014 re-billed prefix)`);const spikeIdx=[];report.lines.forEach((l,i)=>{if(l.ttlRepay>=TTL_SPIKE_TOK)spikeIdx.push(i)});const spikes=[...spikeIdx].sort((a,b2)=>(report.lines[b2]?.ttlRepay??0)-(report.lines[a]?.ttlRepay??0)).slice(0,SUMMARY_FOLD_TOPS).sort((a,b2)=>a-b2);const spikeText=spikes.map(i=>{const l=report.lines[i];if(!l)return"";let idle="";const prev=report.lines[i-1];if(prev&&l.at>prev.at)idle=`, idle ${fmtIdleGap(l.at-prev.at)}`;return`#${l.seq} ${fmtTok(l.ttlRepay)}${idle}`}).join(" \xB7 ");out.push(` upstream-ttl-or-client-rewrite (unattributed) ${fmtTok(t.ttlRepay)} tok (stable-prefix misses: upstream TTL expiry / eviction or client-side wire rewrite \u2014 kernel cannot distinguish${spikeText?`; top spikes: ${spikeText}`:""})`);out.push(` identity check ${t.balanced?"OK":"BROKEN"} \u2014 ${fmtTok(t.input)} = ${fmtTok(t.cached)} + ${fmtTok(t.newContent)} + ${fmtTok(t.compRepay)} + ${fmtTok(t.ttlRepay)} (residual ${t.residual})`);const e=report.economics;if(e.folds>0){const p2=report.profile;out.push("");out.push(`FOLD ECONOMICS (${e.folds} folds @ w=${p2.w} r=${p2.r} q=${p2.q})`);out.push(` gross saved ${fmtTok(e.grossSaved)} tok \xB7 repay cost ${fmtTok(e.repayCost)} tok \xB7 summary cost ${fmtTok(e.summaryCost)} tok \u2192 net ${e.netTokens>=0?"+":""}${fmtTok(e.netTokens)} tok`);out.push(` verdict: ${e.paidBackCount} PAID BACK / ${e.notPaidBackCount} NOT PAID BACK / ${e.unobservedCount} unobserved`);if(e.notPaidBackCount>0)out.push(` NOT PAID BACK = post-fold requests so far have not reached n* (early fold or session ended before payback \u2014 one-time cost, not data loss)`);if(report.folds.length<=SUMMARY_FOLD_TOPS*2){for(const f2 of report.folds){const nstar=f2.breakevenTurns===null?"n/a":f2.breakevenTurns.toFixed(2);const k2=f2.turnsToNextFold===null?"\u2014":String(f2.turnsToNextFold);const h=f2.hPct===null?"n/a":`${f2.hPct.toFixed(1)}%`;out.push(` #${f2.seq} ${fmtTime(f2.at)} S=${fmtTok(f2.S)} \u03C3=${fmtTok(f2.sigma)} h=${h} T=${fmtTok(f2.T)} \u0394C\u2081=${fmtTok(f2.oneTimeCostUnits)} \u0394s=${fmtTok(f2.perTurnSavingUnits)}/turn n*=${nstar} k=${k2} \u2192 ${foldVerdict(f2)}`)}}else{const largest=[...report.folds].sort((a,b2)=>b2.S-a.S).slice(0,SUMMARY_FOLD_TOPS);const worst=[...report.folds].sort((a,b2)=>b2.oneTimeCostUnits-a.oneTimeCostUnits).slice(0,SUMMARY_FOLD_TOPS);out.push(` largest folds: ${largest.map(f2=>`#${f2.seq} S=${fmtTok(f2.S)} ${foldVerdict(f2)}`).join(" \xB7 ")}`);out.push(` worst one-time: ${worst.map(f2=>`#${f2.seq} \u0394C\u2081=${fmtTok(f2.oneTimeCostUnits)} (${foldVerdict(f2)}${f2.turnsToNextFold!==null?`, k=${f2.turnsToNextFold}`:""})`).join(" \xB7 ")}`);const shown=new Set([...largest,...worst]);if(report.folds.length>shown.size)out.push(` \u2192 ${report.folds.length-shown.size} more folds omitted (detail:"full" lists every fold)`)}}if(report.lines.length>0){out.push("");const shownIdx=[];report.lines.forEach((l,i)=>{if(l.hitPct<ANOMALY_HIT_PCT||l.missed>=ANOMALY_MISS_TOK)shownIdx.push(i)});const last=report.lines.length-1;if(!shownIdx.includes(last))shownIdx.push(last);const kept=shownIdx.slice(Math.max(0,shownIdx.length-SUMMARY_ANOMALY_CAP));const anomalies=kept.filter(i=>{const l=report.lines[i];if(!l)return false;return l.hitPct<ANOMALY_HIT_PCT||l.missed>=ANOMALY_MISS_TOK}).length;if(anomalies===0){const med=medianHitPct(report.lines);out.push(`LINE ITEMS \u2014 no anomalies (${report.lines.length} requests, median hit ${med!==null?med.toFixed(1):"n/a"}%${report.linesOmitted>0?`, ${report.linesOmitted} older outside window`:""})`)}else{out.push(`LINE ITEMS (anomalies: hit<${ANOMALY_HIT_PCT}% or miss\u2265${fmtTok(ANOMALY_MISS_TOK)}):`);out.push(" # time input cached hit% new comp ttl fold");for(const i of kept){const l=report.lines[i];if(!l)continue;const fold=l.foldSeq!==null?`#${l.foldSeq}`:"";out.push(` ${String(l.seq).padStart(4)} ${fmtTime(l.at)} ${fmtTok(l.input).padStart(7)} ${fmtTok(l.cached).padStart(7)} ${l.hitPct.toFixed(1).padStart(5)}% ${fmtTok(l.newContent).padStart(6)} ${fmtTok(l.compRepay).padStart(6)} ${fmtTok(l.ttlRepay).padStart(6)} ${fold}`)}const omitted=report.lines.length-kept.length;if(omitted>0){const rest=report.lines.filter((_2,i)=>!kept.includes(i));const med=medianHitPct(rest);out.push(` \u2026 ${omitted} lines omitted (median hit ${med!==null?med.toFixed(1):"n/a"}%${report.linesOmitted>0?`, ${report.linesOmitted} older outside window`:""} \u2014 detail:"full" lists all)`)}}}return out.join("\n")}function formatCacheReport(report,sessionLabel,opts){const t=report.totals;const header2=`ACP CACHE REPORT${sessionLabel?` (${sessionLabel})`:""} \u2014 ${t.requests} requests`;if(opts?.detail==="full"){return[header2,"",formatCacheReportFull(report)].join("\n")}return[header2+` [summary \u2014 detail:"full" for every fold & line]`,"",formatCacheReportSummary(report)].join("\n")}function renderMessage2(m2){const parts=[];switch(m2.contentType){case"text":parts.push(m2.text??"");break;case"tool-call":parts.push(`\`${m2.toolName??"?"}(${m2.toolCallId??""})\` args: ${m2.text??""}`);break;case"tool-result":parts.push(`\`${m2.toolName??"?"}(${m2.toolCallId??""})\` \u2192 ${m2.text??""}`);break;case"reasoning":parts.push(`_reasoning_: ${m2.text??""}`);break}const body=parts.join("\n").trim();return body===""?"_(empty)_":body+"\n"}function renderHandoff(input){const{coreMessages,state:state8,full,meta}=input;const lines=[];lines.push("# billion-context session handoff");lines.push("");lines.push(`- title: ${meta.title??"(untitled)"}`);if(meta.label)lines.push(`- label: ${meta.label}`);lines.push(`- session id: ${meta.sessionId}`);for(const bullet of meta.extraBullets??[])lines.push(bullet);if(meta.contextTokens)lines.push(`- last context tokens: ~${meta.contextTokens}`);lines.push(`- compression blocks: ${state8.blocks.length} (active ${state8.blocks.filter(b2=>b2.active).length})`);lines.push("");const folded=input.folded===true;const view=full||folded?coreMessages:prune(coreMessages,state8,{headSummaryAnchors:true});lines.push(full&&!folded?`## Full conversation (${coreMessages.length} messages)`:folded?`## Conversation (persisted folded snapshot, ${coreMessages.length} messages)`:`## Conversation (folded view as the model saw it, ${coreMessages.length} client messages)`);lines.push("");if(view.length===0){lines.push("No conversation messages to export.");lines.push("")}let lastRole="";for(const m2 of view){if(m2.role!==lastRole){lines.push(`### ${m2.role}`);lines.push("");lastRole=m2.role}lines.push(renderMessage2(m2))}lines.push("");if(full&&folded){for(const b2 of input.blocksFull??[]){lines.push(`## Block ${b2.blockId}${b2.topic?` \u2014 ${b2.topic}`:""}`);lines.push("");lines.push(`### Original messages (${b2.count})`);lines.push("");lines.push(b2.fullText.trim());lines.push("")}}return lines.join("\n")}function listRules(state8){return state8.rules??[]}function resolveRuleLimits(config){return{maxRules:config?.rules?.maxRules??DEFAULT_RULE_LIMITS.maxRules,maxRuleChars:config?.rules?.maxRuleChars??DEFAULT_RULE_LIMITS.maxRuleChars}}function highestRuleNumber(state8){let highest=0;for(const rule of state8.rules??[]){const match=RULE_ID_RE.exec(rule.id);if(match)highest=Math.max(highest,Number(match[1]))}return highest}function addRule(state8,text2,limits={}){const maxRules=limits.maxRules??DEFAULT_RULE_LIMITS.maxRules;const maxRuleChars=limits.maxRuleChars??DEFAULT_RULE_LIMITS.maxRuleChars;const trimmed=(text2??"").trim();if(!trimmed){return{ok:false,error:"rule text is empty \u2014 provide the reminder to record."}}if(trimmed.length>maxRuleChars){return{ok:false,error:`${trimmed.length} chars exceeds the ${maxRuleChars}-char limit \u2014 keep rules short and principle-level.`}}const rules=listRules(state8);const duplicate=rules.find(rule2=>rule2.text===trimmed);if(duplicate){return{ok:false,error:`identical rule already exists (${duplicate.id}) \u2014 no change.`}}if(rules.length>=maxRules){return{ok:false,error:`rule limit reached (${maxRules}) \u2014 remove or clear outdated rules first.`}}const next=Math.max(state8.nextRuleId??1,highestRuleNumber(state8)+1);const rule={id:`rule${next}`,text:trimmed};state8.rules=[...rules,rule];state8.nextRuleId=next+1;return{ok:true,rule}}function removeRule(state8,id){const rules=listRules(state8);const target=rules.find(rule=>rule.id===id.trim());if(!target){return{ok:false,error:`no rule with id "${id.trim()}" \u2014 list current rules first (omit the text argument).`}}state8.rules=rules.filter(rule=>rule.id!==target.id);return{ok:true,rule:target}}function clearRules(state8){const count=listRules(state8).length;state8.rules=[];return{ok:true,count}}function formatRulesList(rules){return rules.map((rule,i)=>`${i+1}. [${rule.id}] ${rule.text}`).join("\n")}function stem(word){let w2=word;if(w2.length<=3)return w2;if(w2.endsWith("ies"))w2=w2.slice(0,-3)+"y";else if(w2.endsWith("ses")||w2.endsWith("xes")||w2.endsWith("zes"))w2=w2.slice(0,-2);else if(w2.endsWith("ches")||w2.endsWith("shes"))w2=w2.slice(0,-2);else if(w2.endsWith("s")&&!w2.endsWith("ss"))w2=w2.slice(0,-1);if(w2.endsWith("ing")&&w2.length>5)w2=w2.slice(0,-3);if(w2.endsWith("ed")&&w2.length>4)w2=w2.slice(0,-2);if(w2.endsWith("ation")&&w2.length>6)w2=w2.slice(0,-3);else if(w2.endsWith("tion")&&w2.length>5)w2=w2.slice(0,-4)+"t";else if(w2.endsWith("ion")&&w2.length>4)w2=w2.slice(0,-3);if(w2.endsWith("ment")&&w2.length>6)w2=w2.slice(0,-4);if(w2.endsWith("ness")&&w2.length>6)w2=w2.slice(0,-4);if(w2.endsWith("ly")&&w2.length>4)w2=w2.slice(0,-2);return w2}function cjkRunTokens(segs){const words=segs.filter(w2=>w2.length>=2);if(words.length>0)return words;const run=segs.join("");const out=[];for(let i=0;i<run.length-1;i++)out.push(run.slice(i,i+2));for(const ch of run)out.push(ch);return out}function tokenize(text2,opts={}){const lower=text2.toLowerCase();const tokens=[];const latin=lower.match(LATIN_WORD)??[];for(let w2 of latin){if(w2.length>=2){if(opts.stem)w2=stem(w2);tokens.push(w2)}}if(!CJK.test(lower))return tokens;const runSegs=[];let cur=null;for(const s3 of cjkSegmenter.segment(lower)){const t=s3.segment;if(t.length===0)continue;if(CJK.test(t)){(cur??=[]).push(t)}else if(cur){runSegs.push(cur);cur=null}}if(cur)runSegs.push(cur);for(const segs of runSegs){tokens.push(...cjkRunTokens(segs))}return tokens}function charBigrams(text2){const grams=[];for(let i=0;i<text2.length-1;i++){const pair=text2.slice(i,i+2);if(pair.trim().length===pair.length)grams.push(pair)}return grams}function tfMap(text2,stem2){const m2=new Map;for(const t of tokenize(text2,{stem:stem2}))m2.set(t,(m2.get(t)??0)+1);return m2}function build(text2){const tf=tfMap(text2,true);let len=0;for(const v2 of tf.values())len+=v2;const lower=text2.toLowerCase();return{tf,len,lower,grams:new Set(charBigrams(lower))}}function docFeatures(text2){const hit=cache.get(text2);if(hit){cache.delete(text2);cache.set(text2,hit);return hit}const f2=build(text2);if(text2.length>0&&text2.length<=capChars){while(cachedChars+text2.length>capChars&&cache.size>0){const k2=cache.keys().next().value;cachedChars-=k2.length;cache.delete(k2)}cache.set(text2,f2);cachedChars+=text2.length}return f2}function countOccurrences2(haystack,needle){if(!needle)return 0;return haystack.split(needle).length-1}function registerSearchAlgorithm(algo){registry2.set(algo.name,algo)}function getSearchAlgorithm(name2){return registry2.get(name2)}function blockDocs(state8){return state8.blocks.map(b2=>({kind:"block",ref:b2.blockId,text:`${b2.topic??""} ${b2.summary??""}`,title:b2.topic??b2.blockId,blockId:b2.blockId,tier:b2.tier??1,tokens:b2.compressedTokens}))}function applyRoleWeight(scored,docs,rw){if(docs.length===0)return scored;const docByRef=new Map(docs.map(d=>[d.ref,d]));return scored.map(s3=>{const doc=docByRef.get(s3.ref);if(!doc)return s3;const w2=doc.kind==="message"?doc.role==="user"?rw.user:doc.role==="assistant"?rw.assistant:rw.tool:rw.block;return{ref:s3.ref,score:s3.score*w2}})}function runSearch(docs,query,options){const limit=options.limit??10;const previewLength=options.previewLength??200;const minScore=options.minScore??.01;const algoName=options.algorithm??DEFAULT_ALGORITHM;const rw={...DEFAULT_ROLE_WEIGHTS,...options.roleWeights};const algo=getSearchAlgorithm(algoName);if(!algo)return[];if(docs.length===0)return[];const scoredOrPromise=algo.score(docs,query);const buildResults=weighted=>{const byRef=new Map(docs.map(d=>[d.ref,d]));return weighted.map(s3=>{const doc=byRef.get(s3.ref);if(!doc)return null;return{kind:doc.kind,ref:doc.ref,blockId:doc.blockId,tier:doc.tier??1,score:s3.score,title:doc.title,preview:makePreview(doc.text,query,previewLength),role:doc.role,tokens:doc.tokens}}).filter(r=>r!==null&&r.score>=minScore).sort((a,b2)=>b2.score-a.score).slice(0,limit)};if(scoredOrPromise instanceof Promise){return scoredOrPromise.then(raw=>buildResults(applyRoleWeight(raw,docs,rw)))}return buildResults(applyRoleWeight(scoredOrPromise,docs,rw))}function searchBlocks(docs,query,options={}){const result=runSearch(docs,query,options);if(result instanceof Promise){throw new Error(`searchBlocks: algorithm "${options.algorithm??DEFAULT_ALGORITHM}" is async (e.g. semantic). Use searchBlocksAsync() instead.`)}return result}function makePreview(text2,query,len){if(!text2)return"";const terms=query.toLowerCase().trim().split(/\s+/).filter(t=>t.length>1);if(terms.length===0)return clampPrefix(text2,len);const lower=text2.toLowerCase();let hitIdx=-1;for(const term of terms){const idx=lower.indexOf(term);if(idx>=0){hitIdx=idx;break}}if(hitIdx<0)return clampPrefix(text2,len);const half=Math.max(0,Math.floor(len/2)-10);const start=Math.max(0,hitIdx-half);const end=Math.min(text2.length,start+len);const prefix=start>0?"\u2026":"";const suffix=end<text2.length?"\u2026":"";return prefix+clampWindow(text2,start,end).trim()+suffix}function classifyTurn(messages){if(messages.length===0)return"unknown";const last=messages[messages.length-1];if(!last||last.role!=="user")return"unknown";if(typeof last.text==="string")return last.text.trim()?"new_user_ask":"unknown";const blocks=last.blocks;if(!Array.isArray(blocks)||blocks.length===0)return"unknown";let sawToolResult=false;let sawError=false;for(const b2 of blocks){if(!b2)return"unknown";switch(b2.kind){case"tool_result":sawToolResult=true;if(b2.isError===true)sawError=true;break;case"text":case"image":case"document":return"new_user_ask";default:return"unknown"}}if(sawError)return"error_continuation";if(sawToolResult)return"mechanical_continuation";return"unknown"}function verbosityDirective(level){if(!Number.isInteger(level))return null;return VERBOSITY_LEVELS[level]??null}function renderSteeringBlock(level,sentinel=DEFAULT_STEERING_SENTINEL){const text2=verbosityDirective(level);if(text2===null)return null;return`${sentinel}
|
|
275
|
+
${text2}`}function markBlockRestoredInline(state8,blockId){const existing=state8.blocks.find(b2=>b2.blockId===blockId);if(!existing)return{state:state8,result:null};const blocks=state8.blocks.map(block=>block.blockId===blockId?{...block,restoredInline:true}:block);const span=resolveBlockSpan(existing,state8.messageRefs.byRaw);const result={restored:true,blockId,...span?{restoredStartRef:span.startRef,restoredEndRef:span.endRef}:{}};return{state:{...state8,blocks},result}}function activeAncestorIds(state8,blockId){const out=[];const visited=new Set([blockId]);let frontier=[blockId];while(frontier.length>0){const next=[];for(const block of state8.blocks){if(visited.has(block.blockId))continue;if(!block.directBlockIds.some(id=>frontier.includes(id)))continue;visited.add(block.blockId);if(block.active)out.push(block.blockId);next.push(block.blockId)}frontier=next}return out}function requestedRefoldSpan(state8,spec){const nums=[];for(const ref of[spec.startRef,spec.endRef]){const parsed=parseBoundary(ref);if(!parsed)return null;if(parsed.kind==="message"){nums.push(parsed.numericId);continue}const block=blockById(state8,`b${parsed.numericId}`);if(!block)return null;const span=resolveBlockSpan(block,state8.messageRefs.byRaw);if(!span)return null;const lo2=parseBoundary(span.startRef);const hi2=parseBoundary(span.endRef);if(!lo2||!hi2)return null;nums.push(lo2.numericId,hi2.numericId)}return{lo:Math.min(...nums),hi:Math.max(...nums)}}function evaluateRefold(state8,spec){const span=requestedRefoldSpan(state8,spec);if(!span)return{kind:"blocked",reasons:[]};const reasons=[];const blocks=[];for(const block of state8.blocks){if(!block.active)continue;const resolved=resolveBlockSpan(block,state8.messageRefs.byRaw);if(!resolved){reasons.push(`partially covered ${block.blockId}`);continue}const ownLo=parseBoundary(resolved.startRef)?.numericId;const ownHi=parseBoundary(resolved.endRef)?.numericId;if(ownLo===void 0||ownHi===void 0)continue;if(ownHi<span.lo||ownLo>span.hi)continue;if(!block.restoredInline){reasons.push(`blocked by ${block.blockId} (not restored)`);continue}if(ownLo<span.lo||ownHi>span.hi){reasons.push(`partially covered ${block.blockId}`);continue}const blockers=activeAncestorIds(state8,block.blockId).filter(ancestorId=>!blockById(state8,ancestorId)?.restoredInline);if(blockers.length>0){for(const id of blockers)reasons.push(`blocked by ${id} (not restored)`);continue}blocks.push(block)}const uniqueReasons=[...new Set(reasons)];if(uniqueReasons.length>0)return{kind:"blocked",reasons:uniqueReasons};if(blocks.length>0)return{kind:"refold",blocks};return{kind:"blocked",reasons:[]}}function segmentGroups(items){const groups=[];let cur=null;for(const item of items){if(cur!==null&&(item.isUser&&cur.length>=3||item.gapBefore)){groups.push(cur);cur=null}if(cur===null)cur=[item];else cur.push(item)}if(cur!==null)groups.push(cur);return groups}function estimateTextTokens(text2){return Math.ceil(text2.length/4)}function isSyntheticOrPruned(message,covered){if(message.text?.startsWith(SUMMARY_HEADER))return true;return covered.has(message.id)}function computeProtectedRefs(messages,state8,config,countTokens=estimateTextTokens){const preserveN=config.preserveRecentMessages;const preserveTokens=config.preserveRecentTokens;const covered=coveredMessageIds(state8);const result=new Set;const visible=[];for(const msg of messages){if(isSyntheticOrPruned(msg,covered))continue;if(isNeverPreserveRecent(msg,config.neverPreserveRecentTools,config.preserveRecentTools))continue;const ref=state8.messageRefs.byRaw[msg.id];if(!ref||ref==="BLOCKED")continue;visible.push({ref,tokens:countMessageTokens(msg,countTokens)})}if(preserveN>0){for(const m2 of visible.slice(-preserveN)){result.add(m2.ref)}}if(preserveTokens>0){let tokenAccum=0;for(let i=visible.length-1;i>=0&&tokenAccum<preserveTokens;i--){result.add(visible[i].ref);tokenAccum+=visible[i].tokens}}if(preserveN>0){const anchor=lastUserAnchor(messages,covered,config);if(anchor){const ref=state8.messageRefs.byRaw[anchor.id];if(ref&&ref!=="BLOCKED")result.add(ref)}}{const msgByRef=new Map;for(const m2 of messages){const ref=m2.id?state8.messageRefs.byRaw[m2.id]:void 0;if(ref&&ref!=="BLOCKED")msgByRef.set(ref,m2)}const callRefByToolCallId=new Map;const resultRefByToolCallId=new Map;for(const m2 of messages){if(!m2.id||typeof m2.toolCallId!=="string")continue;if(isSyntheticOrPruned(m2,covered))continue;const ref=state8.messageRefs.byRaw[m2.id];if(!ref||ref==="BLOCKED")continue;if(m2.contentType==="tool-call")callRefByToolCallId.set(m2.toolCallId,ref);else if(m2.contentType==="tool-result")resultRefByToolCallId.set(m2.toolCallId,ref)}for(const ref of[...result]){const m2=msgByRef.get(ref);if(!m2||typeof m2.toolCallId!=="string")continue;if(m2.contentType==="tool-call"){const r=resultRefByToolCallId.get(m2.toolCallId);if(r)result.add(r)}else if(m2.contentType==="tool-result"){const c=callRefByToolCallId.get(m2.toolCallId);if(c)result.add(c)}}}return result}function refNumber(ref){const m2=/^m(\d+)$/i.exec(ref);return m2?Number(m2[1]):null}function hasDeadRefBetween(deadRefNums,lo2,hi2){for(const n of deadRefNums)if(n>lo2&&n<hi2)return true;return false}function markNoMergeAcrossDeadHoles(ranges,deadRefNums){if(deadRefNums.size===0||ranges.length<2)return;const startPos=r=>r.startIndex??refNumber(r.startRef)??0;const order=[...ranges].sort((a,b2)=>startPos(a)-startPos(b2));for(let i=1;i<order.length;i++){const prevEnd=refNumber(order[i-1].endRef);const curStart=refNumber(order[i].startRef);if(prevEnd===null||curStart===null)continue;const lo2=Math.min(prevEnd,curStart);const hi2=Math.max(prevEnd,curStart);if(hi2-lo2>1&&hasDeadRefBetween(deadRefNums,lo2,hi2)){order[i].noMergeBefore=true}}}function buildCompressibleRanges(messages,state8,config,protectedZoneRefs,countTokens=estimateTextTokens,integritySource){let compressibleMsgs=[];const protectedMsgs=[];const covered=coveredMessageIds(state8);const protectedCallIds=collectProtectedToolCallIds(messages,config);const failedCompressCallIds=collectFailedCompressCallIds(messages,config);const latest=collectLatestProtected(messages,config);for(const id of latest.callIds)protectedCallIds.add(id);let skipSinceCompressible=false;let skipSinceProtected=false;let hardGapSinceCompressible=false;let msgIndex=-1;const deadRefNums=new Set((state8.deadRefs??[]).map(ref=>refNumber(ref)).filter(n=>n!==null));let lastCompressibleRefNum=null;for(const msg of messages){msgIndex++;const ref=state8.messageRefs.byRaw[msg.id];if(!ref||ref==="BLOCKED"){hardGapSinceCompressible=true;continue}if(isSyntheticOrPruned(msg,covered)){skipSinceCompressible=true;skipSinceProtected=true;hardGapSinceCompressible=true;continue}if(isLiveCheckpointCarrier(msg,state8)){skipSinceCompressible=true;skipSinceProtected=true;hardGapSinceCompressible=true;continue}if(hasUnrecoverableMediaPayload(msg)){skipSinceCompressible=true;skipSinceProtected=true;hardGapSinceCompressible=true;continue}if(isMessageProtectedWithPairing(msg,config,protectedCallIds,failedCompressCallIds)||isMessageLatestProtected(msg,latest)){protectedMsgs.push({ref,gapBefore:skipSinceProtected,tokens:countMessageTokens(msg,countTokens),tools:msg.toolName?[msg.toolName]:[],index:msgIndex});skipSinceProtected=false;skipSinceCompressible=true;continue}if(protectedZoneRefs?.has(ref)){skipSinceCompressible=true;skipSinceProtected=true;hardGapSinceCompressible=true;continue}const curRefNum=refNumber(ref);if(deadRefNums.size>0&&curRefNum!==null&&lastCompressibleRefNum!==null){const lo2=Math.min(curRefNum,lastCompressibleRefNum);const hi2=Math.max(curRefNum,lastCompressibleRefNum);if(hi2-lo2>1&&hasDeadRefBetween(deadRefNums,lo2,hi2)){skipSinceCompressible=true;hardGapSinceCompressible=true}}compressibleMsgs.push({id:msg.id,ref,gapBefore:skipSinceCompressible,gapHard:hardGapSinceCompressible,tokens:countMessageTokens(msg,countTokens),chars:(msg.text??"").length,isTool:isToolMessage(msg),isUser:msg.role==="user",index:msgIndex});if(curRefNum!==null)lastCompressibleRefNum=curRefNum;skipSinceCompressible=false;skipSinceProtected=true;hardGapSinceCompressible=false}const unfoldedIds=computeIntegrityWithdrawals(integritySource??messages,new Set(compressibleMsgs.map(info=>info.id)),void 0,covered).withdrawn;if(unfoldedIds.size>0){let gapPending=false;let pendingHard=false;const kept=[];for(const info of compressibleMsgs){if(unfoldedIds.has(info.id)){gapPending=true;pendingHard=pendingHard||info.gapHard;continue}kept.push(gapPending?{...info,gapBefore:true,gapHard:pendingHard||info.gapHard}:info);gapPending=false;pendingHard=false}compressibleMsgs=kept}const compressible=[];for(const group of segmentGroups(compressibleMsgs)){const first=group[0];const range={startRef:first.ref,endRef:first.ref,startIndex:first.index,endIndex:first.index,count:1,tokens:first.tokens,chars:first.chars,toolPct:first.isTool?100:0,textPct:first.isTool?0:100,userMsgs:first.isUser?1:0,...first.gapBefore&&!first.gapHard?{bridgeableGapBefore:true}:{}};for(let i=1;i<group.length;i++){const info=group[i];range.endRef=info.ref;range.endIndex=info.index;range.count++;range.tokens+=info.tokens;range.chars=(range.chars??0)+info.chars;if(info.isUser)range.userMsgs=(range.userMsgs??0)+1;if(info.isTool){range.toolPct=Math.round((range.toolPct*(range.count-1)+100)/range.count)}else{range.toolPct=Math.round(range.toolPct*(range.count-1)/range.count)}range.textPct=100-range.toolPct}compressible.push(range)}const protectedRanges=[];let pcur=null;for(const info of protectedMsgs){if(pcur&&info.gapBefore){protectedRanges.push(pcur);pcur=null}if(!pcur){pcur={startRef:info.ref,endRef:info.ref,count:1,tokens:info.tokens,tools:[...info.tools],startIndex:info.index,endIndex:info.index}}else{pcur.endRef=info.ref;pcur.endIndex=info.index;pcur.count++;pcur.tokens+=info.tokens;for(const t of info.tools){if(!pcur.tools.includes(t))pcur.tools.push(t)}}}if(pcur)protectedRanges.push(pcur);markNoMergeAcrossDeadHoles([...compressible,...protectedRanges],deadRefNums);return{compressible:compressible.filter(g2=>g2.tokens>0),protected:protectedRanges}}function mergeBatch(batch){const first=batch[0];const last=batch[batch.length-1];const count=batch.reduce((s3,r)=>s3+r.count,0);const tokens=batch.reduce((s3,r)=>s3+r.tokens,0);const chars=batch.reduce((s3,r)=>s3+rangeChars(r),0);const toolPct=Math.round(batch.reduce((s3,r)=>s3+r.toolPct*r.count,0)/count);const merged={startRef:first.startRef,endRef:last.endRef,count,tokens,chars,toolPct,textPct:100-toolPct,userMsgs:batch.reduce((s3,r)=>s3+(r.userMsgs??0),0)};if(first.startIndex!==void 0&&last.endIndex!==void 0){merged.startIndex=Math.min(...batch.map(r=>r.startIndex??Infinity));merged.endIndex=Math.max(...batch.map(r=>r.endIndex??-Infinity))}if(batch.some(r=>r.dangerous===true)){merged.dangerous=true}if(first.noMergeBefore===true)merged.noMergeBefore=true;if(first.bridgeableGapBefore===true)merged.bridgeableGapBefore=true;return merged}function rangeChars(r){return r.chars??r.tokens*4}function mergeRangesToThreshold(ranges,minChars){if(minChars<=0||ranges.length===0)return ranges;const result=[];let batch=[];let batchChars=0;const closeBatch=()=>{if(batch.length>0){if(batchChars>=minChars)result.push(mergeBatch(batch));batch=[];batchChars=0}};for(const r of ranges){if(r.noMergeBefore)closeBatch();const prev=batch[batch.length-1];if(prev&&prev.endIndex!==void 0&&r.startIndex!==void 0&&r.startIndex>prev.endIndex+1&&!r.bridgeableGapBefore){closeBatch()}batch.push(r);batchChars+=rangeChars(r);if(batchChars>=minChars)closeBatch()}if(batch.length>0&&result.length>0){const prev=result[result.length-1];const contiguous=!batch[0].noMergeBefore&&(prev.endIndex===void 0||batch[0].startIndex===void 0||batch[0].startIndex<=prev.endIndex+1||batch[0].bridgeableGapBefore===true);if(contiguous){result[result.length-1]=mergeBatch([prev,...batch])}else if(batchChars>=minChars){result.push(mergeBatch(batch))}}return result}function screenRecommendedUnits(units,source,state8,config,protectedRefs){if(units.length===0)return units;const coverage=collectCoverage(state8);const shared=buildProjectionShared(source,state8,config);return units.filter(unit=>{let projection;try{projection=projectUnit({messages:source,state:state8,config,startRef:unit.startRef,endRef:unit.endRef,preExistingCoverage:coverage,protectedMessageIds:protectedRefs,shared})}catch(err2){if(!(err2 instanceof BoundaryNotFoundError)){warnScreenDrop(`dropped unit ${unit.startRef}..${unit.endRef} after projection error: ${err2 instanceof Error?err2.message:String(err2)}`)}return false}if(!projection||projection.fatal!==null){if(projection?.fatal){warnScreenDrop(`dropped unit ${unit.startRef}..${unit.endRef}: ${projection.fatal.error.message}`)}return false}if(projection.filteredIds.length===0&&projection.consumedBlockIds.length===0){warnScreenDrop(`dropped unit ${unit.startRef}..${unit.endRef}: nothing foldable in span (filteredIds=0, consumedBlocks=0)`);return false}if(projection.filteredIds.length===0&&projection.consumedBlockIds.length>0&&!projection.isBlockBoundary&&evaluateRefold(state8,unit).kind!=="refold"){warnScreenDrop(`dropped unit ${unit.startRef}..${unit.endRef}: consumes only active block(s), not a refold`);return false}return true})}function warnScreenDrop(detail){screenDropWarnCount+=1;if(screenDropWarnCount>SCREEN_DROP_WARN_BUDGET&&screenDropWarnCount%SCREEN_DROP_WARN_STRIDE!==0){return}console.warn(`[acp-kernel] screenRecommendedUnits ${detail}`)}function runPipeline(nodes,initial,ctx){let io2=initial;for(const node of nodes){if(node.enabled&&!node.enabled(io2,ctx))continue;io2=node.run(io2,ctx)}return io2}function rangeError(spec,message){return`range ${spec.startRef}..${spec.endRef}: ${message}`}function numericBlockId(id){const parsed=/^b(\d+)$/.exec(id);return parsed?Number(parsed[1]):0}function refGateDiagnostics(state8,requestedRanges,unknownCount){const highest=highestUsedIndex(state8.messageRefs);const highestRef=highest>0?indexToRef(highest):"none";return`[diagnostics: session highest allocated ref=${highestRef} (the ref space is sparse \u2014 numbers at or below it are NOT necessarily allocated, so probing numbers will not find a valid one; use only refs acp_status lists), unknown ranges in request=${unknownCount}/${requestedRanges}, session history=${state8.stats.compressionCount} compression(s), ${state8.blocks.length} block(s)]`}function danglingMessageRefs(state8,messages,spec){const visible=new Set(messages.map(m2=>m2.id));const dangling=[];for(const ref of[spec.startRef,spec.endRef]){const parsed=parseBoundary(ref);if(!parsed||parsed.kind!=="message")continue;const rawId=state8.messageRefs.byRef[parsed.raw]??state8.messageRefs.byRef[indexToRef(parsed.numericId)];if(!rawId){const padded=indexToRef(parsed.numericId);if(state8.deadRefs?.includes(parsed.raw)||state8.deadRefs?.includes(padded)){dangling.push(padded)}continue}if(visible.has(rawId))continue;const covered=state8.blocks.some(block=>block.active&&block.effectiveMessageIds.includes(rawId));if(!covered)dangling.push(parsed.raw)}return dangling}function coveringBlockIds(state8,spec){const found=new Set;for(const ref of[spec.startRef,spec.endRef]){const parsed=parseBoundary(ref);if(!parsed)continue;let rawIds=[];if(parsed.kind==="message"){const rawId=state8.messageRefs.byRef[parsed.raw]??state8.messageRefs.byRef[indexToRef(parsed.numericId)];if(rawId)rawIds=[rawId]}else{rawIds=blockById(state8,`b${parsed.numericId}`)?.effectiveMessageIds??[]}if(rawIds.length===0)continue;for(const candidate of activeBlocks(state8)){if(rawIds.some(id=>candidate.effectiveMessageIds.includes(id))){found.add(candidate.blockId)}}}return[...found].sort((x,y)=>numericBlockId(x)-numericBlockId(y))}function tierActionHint(config,state8){if(!config.tiers.enabled)return"";const live=activeBlocks(state8).filter(b2=>!b2.retired);const t2=live.filter(b2=>b2.tier===2);if(t2.length>=config.tiers.tier3Trigger){return` Tier condensation is actionable now: compress({ content: "${t2[0].blockId}\u2013${t2[t2.length-1].blockId} optional topic\\nsummary markdown..." }) merges those tier-2 blocks into one tier-3 block.`}const t1=live.filter(b2=>b2.tier===1);if(t1.length>=config.tiers.tier2Trigger){return` Tier distillation is actionable now: compress({ content: "${t1[0].blockId}\u2013${t1[t1.length-1].blockId} optional topic\\nsummary markdown..." }) merges those tier-1 blocks into one tier-2 block.`}return""}function applyRefolds(input){validateSummaryLength(input.spec,input.config.compress,{skipMin:input.minFloorCovered===true});const targets=new Set(input.blockIds);input.state.blocks=input.state.blocks.map(block=>{if(!targets.has(block.blockId))return block;const carriedRefs=parseMediaRefsSection(block.summary).map(scrubLoneSurrogates2);return{...block,summary:appendMediaRefsSection(input.spec.summary,carriedRefs),topic:input.spec.topic??block.topic,runId:input.runId,restoredInline:false}})}function createCore(ports={}){const countTokens=ports.countTokens??defaultCountTokens;const timestampsOn=ports.timestamps===true;function applyCompression(input){const state8=cloneState(input.state);for(const spec of input.ranges){if(spec.summary)spec.summary=scrubLoneSurrogates2(spec.summary)}let allocatedRunId=null;const runIdOf=()=>allocatedRunId??=allocateRunId(state8);let blocksCreated=0;let tokensCompressed=0;const errors=[];const warnings=[];const notes=[];const protectedMessageIds=input.protectedMessageIds??computeProtectedRefs(input.messages,input.state,input.config,countTokens);let preExistingCoverage=collectCoverage(state8);const classifications=new Map;const classificationErrors=[];const consumedRanges=[];for(const spec of input.ranges){try{const resolved=resolveBoundaries({startRef:spec.startRef,endRef:spec.endRef,messages:input.messages,state:state8});classifications.set(spec,{status:"ok",resolved})}catch(error){if(error instanceof BoundaryNotFoundError){classifications.set(spec,error.kind==="unknown"?{status:"unknown",error}:{status:"consumed",error});if(error.kind==="consumed"){consumedRanges.push(spec)}else{classificationErrors.push(rangeError(spec,error.message))}}else{classifications.set(spec,{status:"invalid",error:error instanceof Error?error:new Error(String(error))});classificationErrors.push(rangeError(spec,error instanceof Error?error.message:String(error)))}}}const visibleIdsForDead=new Set(input.messages.map(m2=>m2.id));let deadRefs=(state8.deadRefs??[]).filter(ref=>{const rawId=state8.messageRefs.byRef[ref];return!(rawId!==void 0&&visibleIdsForDead.has(rawId))});const danglingBySpec=new Map;for(const spec of input.ranges){const resolution=classifications.get(spec);if(resolution===void 0||resolution.status!=="consumed")continue;const dangling=danglingMessageRefs(state8,input.messages,spec);if(dangling.length===0)continue;danglingBySpec.set(spec,dangling);for(const ref of dangling){if(!deadRefs.includes(ref))deadRefs.push(ref)}}if(deadRefs.length>0){state8.deadRefs=[...new Set(deadRefs)].sort((a,b2)=>Number(a.replace(/^m/,""))-Number(b2.replace(/^m/,"")))}else{state8.deadRefs=void 0}let resolvableCount=0;let unknownCount=0;for(const resolution of classifications.values()){if(resolution.status==="ok")resolvableCount++;else if(resolution.status==="unknown")unknownCount++}const refoldDecisions=new Map;const isRefoldCandidate=resolution=>resolution.status==="consumed"||resolution.status==="ok"&&resolution.resolved.boundaryKind!=="block"&&resolution.resolved.messageIds.every(id=>preExistingCoverage.has(id));for(const[spec,resolution]of classifications){if(isRefoldCandidate(resolution)){refoldDecisions.set(spec,evaluateRefold(state8,spec))}}const allRefold=input.ranges.length>0&&unknownCount===0&&[...classifications.entries()].every(([spec,resolution])=>isRefoldCandidate(resolution)&&refoldDecisions.get(spec)?.kind==="refold");const rangeSpans=[];for(const[spec,resolution]of classifications){if(resolution.status!=="ok")continue;rangeSpans.push({spec,start:resolution.resolved.startIndex,end:resolution.resolved.endIndex})}const sortedRanges=[...rangeSpans].sort((a,b2)=>a.start-b2.start);const skipSpecs=new Set;let acceptedMaxIndex=-1;for(const entry of sortedRanges){if(entry.start<=acceptedMaxIndex){skipSpecs.add(entry.spec);warnings.push(`Skipped range (${entry.spec.startRef}..${entry.spec.endRef}) \u2014 overlaps an earlier range in the batch; the earlier range takes precedence. Keep ranges disjoint.`);continue}if(entry.end>acceptedMaxIndex)acceptedMaxIndex=entry.end}if(input.config.compress.minCompressRange>0&&input.ranges.length>0){let totalRangeChars=0;let hasBlockBoundaryRange=false;let countedRanges=0;for(const[spec,resolution]of classifications){if(resolution.status!=="ok"||skipSpecs.has(spec))continue;if(resolution.resolved.boundaryKind==="block"){hasBlockBoundaryRange=true;continue}countedRanges++;for(const id of resolution.resolved.messageIds){const msg=input.messages.find(m2=>m2.id===id);totalRangeChars+=msg?.text?.length??0}}if(!allRefold&&!hasBlockBoundaryRange&&totalRangeChars<input.config.compress.minCompressRange){const diagnostics=refGateDiagnostics(state8,input.ranges.length,unknownCount);const firstConsumed=consumedRanges[0];const covering=firstConsumed?coveringBlockIds(state8,firstConsumed):[];const coverDetail=covering.length>0?`its content is already summarized in active block(s) ${covering.join(", ")}${covering.length===1?` \u2014 use search_context or decompress ${covering[0]} if you need details from it`:""}`:`its refs no longer point to directly compressible content (stale block ref(s) distilled or consumed by higher-tier blocks)`;const refoldReasons=[...new Set(consumedRanges.flatMap(spec=>{const decision=refoldDecisions.get(spec);return decision?.kind==="blocked"?decision.reasons:[]}))];const refoldSuffix=reasons=>reasons.length>0?` Refold blocked: ${reasons.join("; ")}. Restore the affected block(s) inline (decompress with inline:true), then recompressing the same range updates them in place`:"";const refoldDetail=refoldSuffix(refoldReasons);const okBlockedReasons=[...new Set([...classifications.entries()].flatMap(([spec,resolution])=>{if(skipSpecs.has(spec)||resolution.status!=="ok")return[];const decision=refoldDecisions.get(spec);return decision?.kind==="blocked"?decision.reasons:[]}))];const danglingRefs=consumedRanges.flatMap(spec=>danglingBySpec.get(spec)??[]);const unknownEndpoints=new Set;for(const[spec,resolution]of classifications){if(resolution.status!=="unknown")continue;const endpoint=resolution.error.endpoint;unknownEndpoints.add(`${endpoint}Id=${endpoint==="start"?spec.startRef:spec.endRef}`)}let gateMessage=resolvableCount===0&&consumedRanges.length===0&&unknownCount>0?`None of the ${input.ranges.length} requested range(s) resolved \u2014 every ref is unknown to this session${unknownEndpoints.size>0?`, failing endpoints: ${[...unknownEndpoints].join(", ")}`:""}. Refs are per-session snapshots, assigned once when a message is first rendered; no compress reassigns them. An unknown ref is usually a stale artifact from an earlier generation (switching model or upstream mid-conversation starts a fresh session whose refs restart at m00001, and a native-compaction rebase resets them the same way) or a typo \u2014 but a number at or below the highest allocated ref may also simply be an unallocated gap: the ref space is sparse. ${diagnostics} Do not probe for valid numbers. Run acp_status, then call the compress tool again using only the refs it reports.`:consumedRanges.length>0?danglingRefs.length>0?`Requested range(s) cannot be anchored (e.g. ${firstConsumed.startRef}..${firstConsumed.endRef}): refs ${danglingRefs.join(", ")} are known to this session but no longer back any visible or folded message \u2014 the client rewrote or dropped those messages (an edit reissues a new ref; host-native compaction or a bulk history rewrite drops them outright), and no active block covers them. These refs are now recorded as DEAD: no range that includes them can compress now or later, whatever the neighbors. Do not retry this range in any form \u2014 run acp_status and target only the live refs it reports. ${diagnostics}`:`Requested range(s) already compressed (e.g. ${firstConsumed.startRef}..${firstConsumed.endRef}) \u2014 ${coverDetail}${refoldDetail}. Nothing new to compress in that window. ${diagnostics} Continue the task, or run acp_status and target one of the CURRENT compressible ranges it reports.${tierActionHint(input.config,state8)}`:countedRanges>0?`Total compressible content too small (${totalRangeChars} chars across ${countedRanges} range(s), min ${input.config.compress.minCompressRange}). Combine more messages into your range(s) to meet the threshold.${refoldSuffix(okBlockedReasons)}`:null;if(gateMessage===null){return{state:input.state,result:{blocksCreated:0,tokensCompressed:0,errors:[...classificationErrors],warnings:[]}}}const reversalNotes=[];for(const[spec,resolution]of classifications){if(resolution.status==="ok"&&!skipSpecs.has(spec)){const note=resolution.resolved.reversedNote;if(note)reversalNotes.push(note)}}if(reversalNotes.length>0){gateMessage+=` ${reversalNotes.join(" ")}`}const pureResubmit=countedRanges===0&&consumedRanges.length>0&&danglingRefs.length===0&&unknownCount===0;if(pureResubmit){return{state:state8,result:{blocksCreated:0,tokensCompressed:0,errors:[],warnings:[`${gateMessage} Nothing failed and nothing needed redoing \u2014 do not resend these ranges.`],noop:true}}}return{state:state8,result:{blocksCreated:0,tokensCompressed:0,errors:[gateMessage,...classificationErrors],warnings:[]}}}}let batchFloorByTotal=false;{const foldCandidates=[];for(const spec of input.ranges){if(skipSpecs.has(spec))continue;const resolution=classifications.get(spec);if(resolution===void 0)continue;const foldsFresh=resolution.status==="ok";const foldsRefold=resolution.status==="consumed"&&refoldDecisions.get(spec)?.kind==="refold";if(!foldsFresh&&!foldsRefold)continue;foldCandidates.push(spec)}const lengthFailures=[];const failureKinds=new Set;const minLen=input.config.compress.minSummaryLength;if(foldCandidates.length===1){const solo=foldCandidates[0];try{validateSummaryLength(solo,input.config.compress)}catch(error){if(isSummaryLengthError(error))failureKinds.add(error.kind);lengthFailures.push(rangeError(solo,error instanceof Error?error.message:String(error)))}}else{for(const spec of foldCandidates){try{validateSummaryLength(spec,input.config.compress,{skipMin:true})}catch(error){if(isSummaryLengthError(error))failureKinds.add(error.kind);lengthFailures.push(rangeError(spec,error instanceof Error?error.message:String(error)))}}if(minLen>0&&foldCandidates.length>1){const total=foldCandidates.reduce((sum,spec)=>sum+(spec.summary?.trim()??"").length,0);if(total<minLen){failureKinds.add("tooShort");lengthFailures.push(`Batch summary too short (${total} chars across ${foldCandidates.length} ranges, min ${minLen}). The combined summaries must capture the compressed content's key information.`)}}}batchFloorByTotal=foldCandidates.length>1;if(lengthFailures.length>0){return{state:state8,result:{blocksCreated:0,tokensCompressed:0,errors:[`Batch rejected before folding any range \u2014 ${lengthFailures.length} of ${input.ranges.length} requested range(s) failed summary-length validation: ${lengthFailures.join(" | ")}. Nothing was folded, so no prefix was rewritten. ${lengthRemediation(failureKinds)}`,...classificationErrors],warnings:[]}}}}const preLoopState=cloneState(state8);const applyErrors=[];const warningsBase=warnings.length;const preFoldBlockIds=new Set(state8.blocks.map(b2=>b2.blockId));for(const spec of input.ranges){preExistingCoverage=collectCoverage(state8);if(skipSpecs.has(spec))continue;const resolution=classifications.get(spec);if(resolution===void 0)continue;if(resolution.status==="consumed"){const decision=refoldDecisions.get(spec);if(decision?.kind==="refold"){try{applyRefolds({spec,state:state8,runId:runIdOf(),config:input.config,blockIds:decision.blocks.map(block=>block.blockId),minFloorCovered:batchFloorByTotal});blocksCreated+=decision.blocks.length}catch(error){applyErrors.push(rangeError(spec,error instanceof Error?error.message:String(error)))}continue}const reasons=decision?.kind==="blocked"?decision.reasons:[];const dangling=danglingBySpec.get(spec);warnings.push(dangling&&dangling.length>0?`Skipped range (${spec.startRef}..${spec.endRef}) \u2014 its refs ${dangling.join(", ")} are DEAD (the client rewrote or dropped those messages); this range can never compress, do not retry it.`:`Skipped range (${spec.startRef}..${spec.endRef}) \u2014 already compressed${reasons.length>0?`: ${reasons.join("; ")}`:" (messages consumed by existing block(s))"}; nothing to compress.`);continue}if(resolution.status==="unknown"||resolution.status==="invalid"){errors.push(rangeError(spec,resolution.error.message));continue}warnings.push(...resolution.resolved.snappedBoundaries);const note=resolution.resolved.reversedNote;if(note)notes.push(note);try{const outcome=applySingleRange({spec,messages:input.messages,state:state8,runId:runIdOf(),config:input.config,protectedMessageIds,countTokens,preExistingCoverage,minFloorCovered:batchFloorByTotal});blocksCreated+=outcome.noop?0:outcome.refolded?outcome.refolded.length:1;tokensCompressed+=outcome.tokens;warnings.push(...outcome.warnings)}catch(error){applyErrors.push(rangeError(spec,error instanceof Error?error.message:String(error)))}}if(applyErrors.length>0){return{state:preLoopState,result:{blocksCreated:0,tokensCompressed:0,errors:[`Batch rejected before folding any range \u2014 ${applyErrors.length} of ${input.ranges.length} requested range(s) failed during application: ${applyErrors.join(" | ")}. Nothing was folded, so no prefix was rewritten. Fix or drop the offending range(s), then resend the whole batch.`,...classificationErrors],warnings:warnings.slice(0,warningsBase)}}}state8.stats.compressionCount+=blocksCreated;state8.stats.tokensCompressed+=tokensCompressed;if(blocksCreated>0){let foldStartRef;for(const b2 of state8.blocks){if(preFoldBlockIds.has(b2.blockId))continue;for(const id of b2.effectiveMessageIds){const num7=refNum(state8.messageRefs.byRaw[id]);if(num7!==null&&(foldStartRef===void 0||num7<foldStartRef)){foldStartRef=num7}}}if(foldStartRef!==void 0){state8.pendingOrphanSweepMinRef=state8.pendingOrphanSweepMinRef===void 0?foldStartRef:Math.min(state8.pendingOrphanSweepMinRef,foldStartRef)}state8.nudge.lastPerMessageNudgeTokens=0;state8.nudge.lastNudgeShownTokens=0;state8.nudge.lastShownByTier={};state8.nudge.absorbedDebt=0;state8.nudge.absorbCount=0;const distilled=state8.blocks.filter(b2=>!preFoldBlockIds.has(b2.blockId)).some(b2=>(b2.tier??1)>1);const firePending=state8.nudge.lastT1FirePending;if(distilled){state8.nudge.t1HarvestStall=false;state8.nudge.lastT1FirePending=void 0}else if(firePending!==void 0&&firePending>0){state8.nudge.t1HarvestStall=tokensCompressed<STALL_HARVEST_RATIO*firePending;state8.nudge.lastT1FirePending=void 0}state8.terminalStreak=0;state8.emergencyTruncateLatch=void 0;state8.renderDeferredRefs=void 0;state8.viewLatches=void 0}return{state:state8,result:{blocksCreated,tokensCompressed,errors,warnings,...notes.length>0?{notes}:{},...blocksCreated===0&&errors.length===0?{noop:true}:{}}}}function processTurn(input){const configErrors=validateConfig(input.config);if(configErrors.length>0){console.warn(`[acp-kernel] Config validation warnings: ${configErrors.join("; ")}. Thresholds may not fire correctly.`)}const contentStore=input.contentStore??createContentStore();const ctx={config:input.config,tokenCount:input.tokenCount,tokenCountSource:input.tokenCountSource,countTokens,contentStore};const initial={messages:input.messages,state:input.state,effects:{applyView:input.applyView}};const strategy=input.renderTags??"all";const nodes=buildNodes(strategy);const inboundIds=input.messages.map(m2=>m2.id);const result=runPipeline(nodes,initial,ctx);let deadRefs=result.state.deadRefs;if(deadRefs&&deadRefs.length>0){const inboundSet=new Set(inboundIds);const kept=deadRefs.filter(ref=>{const rawId=result.state.messageRefs.byRef[ref];return!(rawId!==void 0&&inboundSet.has(rawId))});deadRefs=kept.length>0?kept:void 0}const state8={...result.state,lastPassIds:inboundIds,deadRefs};const ccrEffect=result.effects.ccr;return{messages:result.messages,state:state8,nudge:result.effects.nudge,terminalEscape:result.effects.terminalEscape,truncationSkipped:result.effects.truncationSkipped,contentStore:ccrEffect?.store??contentStore}}function retrieve(store2,ref,opts){return applyRetrieve({store:store2,ref,...opts})}function decompress(blockId,state8){return blockById(state8,blockId)}function search(query,state8){const terms=query.toLowerCase().split(/\s+/).filter(term=>term.length>0);if(terms.length===0)return[];const scored=activeBlocks(state8).map(block=>({block,score:scoreRelevance(block,terms)})).filter(entry=>entry.score>0).sort((left,right)=>right.score-left.score);return scored.map(entry=>entry.block)}function status(state8,tokenCount,config){const active=activeBlocks(state8);const usage=config.modelContextLimit>0?tokenCount/config.modelContextLimit:0;return{contextUsage:usage,tokenCount,modelContextLimit:config.modelContextLimit,activeBlocks:active.length,totalBlocks:state8.blocks.length,tokensCompressed:state8.stats.tokensCompressed,breakdown:{active:active.length,total:state8.blocks.length,storedMessages:state8.stats.storedCount??0,retrievals:state8.stats.retrievalCount??0}}}function defaultNodes(){return buildNodes("all")}function buildNodes(strategy){const base=[reconcileLiveIdsNode,createStampTimestampsNode(timestampsOn),assignRefsNode,syncBlocksNode,pruneNode,preTransformSnapshotNode,ccrStoreNode,absorbHideNode,crushNode,absorbPromptNode,filterNode,hideCompressCallsNode,viewLatchNode,recommendNode,nudgeNode,emergencyTruncateNode];if(strategy==="none")return base;return[...base,createRenderRefsNode(strategy,{timestamps:timestampsOn})]}return{processTurn,retrieve,applyCompression,defaultNodes,decompress,search,status}}function createStampTimestampsNode(enabled){if(!enabled)return{name:"stamp-timestamps",run(io2){return io2}};return{name:"stamp-timestamps",run(io2){const stamps={...io2.state.tsStamps??{}};const knownIds=io2.state.messageRefs.byRaw;let changed=false;const hwmFresh=io2.state.timestampsHighWaterRefSeq===void 0;const hwm=hwmFresh?highestUsedIndex(io2.state.messageRefs):io2.state.timestampsHighWaterRefSeq;const suppressed=io2.state.suppressMintingOnce===true;const messages=io2.messages.map(m2=>{if(!m2.id||m2.id.startsWith(RETRIEVED_ID_PREFIX))return m2;const stamped=stamps[m2.id];if(stamped!==void 0){if(m2.ts===stamped)return m2;const cur=knownIds[m2.id];const seq=cur===void 0?null:refToIndex(cur);if(seq===null||seq<=hwm)return m2;changed=true;return{...m2,ts:stamped}}const carried=typeof m2.ts==="number"?m2.ts:void 0;const ts2=carried??(!suppressed&&knownIds[m2.id]===void 0?Date.now():void 0);if(ts2===void 0)return m2;stamps[m2.id]=ts2;changed=true;return{...m2,ts:ts2}});if(!changed&&!hwmFresh&&!suppressed)return io2;const nextState={...io2.state,tsStamps:stamps,timestampsHighWaterRefSeq:hwm};if(suppressed)delete nextState.suppressMintingOnce;return{...io2,messages,state:nextState}}}}function applySingleRange(input){const warnings=[];const projection=projectUnit({messages:input.messages,state:input.state,config:input.config,startRef:input.spec.startRef,endRef:input.spec.endRef,preExistingCoverage:input.preExistingCoverage,protectedMessageIds:input.protectedMessageIds,warnings});if(projection.fatal){if(projection.fatal.kind==="zone"){const highest=highestUsedIndex(input.state.messageRefs);return{tokens:0,warnings:[`Range ${input.spec.startRef}..${input.spec.endRef} folded nothing \u2014 it lies entirely inside the protected zone (the last ${input.config.preserveRecentMessages} messages and/or the most recent user message), which always stays visible. Nothing failed; do not resend this range. Session highest allocated ref is ${highest>0?indexToRef(highest):"none"} \u2014 target older ranges only.`],noop:true}}if(projection.fatal.kind==="split"&&projection.fatal.degradable){const highest=highestUsedIndex(input.state.messageRefs);return{tokens:0,warnings:[`Range ${input.spec.startRef}..${input.spec.endRef} folded nothing \u2014 the integrity gate keeps every visible tool call's reasoning run and its results together, and folding this range would split that turn at the protected-zone boundary, so the range was withdrawn in full instead of split. Nothing failed; do not resend this range as-is \u2014 it cannot fold until the whole turn ages out of the protected zone. Session highest allocated ref is ${highest>0?indexToRef(highest):"none"} \u2014 target older ranges only.`],noop:true}}throw projection.fatal.error}const{filteredIds,consumedBlockIds,effectiveMessageIds,outputTier,isBlockBoundary}=projection;const retiredConsumed=consumedBlockIds.filter(id=>blockById(input.state,id)?.retired===true);if(retiredConsumed.length>0){throw new Error(`Range ${input.spec.startRef}..${input.spec.endRef} would consume retired block(s) ${retiredConsumed.join(", ")} \u2014 their summaries are out of the resident view by explicit user decision. Re-target the range excluding them, or call acp_restore({ blockId }) first if they should be foldable again.`)}if(!isBlockBoundary&&filteredIds.length===0&&consumedBlockIds.length>0){const decision=evaluateRefold(input.state,input.spec);if(decision.kind==="refold"){applyRefolds({spec:input.spec,state:input.state,runId:input.runId,config:input.config,blockIds:decision.blocks.map(block2=>block2.blockId),minFloorCovered:input.minFloorCovered});return{tokens:0,warnings,refolded:decision.blocks.map(block2=>block2.blockId)}}const first=consumedBlockIds[0];const last=consumedBlockIds[consumedBlockIds.length-1];return{tokens:0,warnings:[`Range ${input.spec.startRef}..${input.spec.endRef} folded nothing \u2014 every message in it is already covered by active block(s) ${consumedBlockIds.join(", ")}. Nothing failed and nothing needed redoing; do not resend this range. To rewrite or merge those blocks, reference them by block ID (${first}..${last}) instead.`],noop:true}}validateCompressionRange(input);if(filteredIds.length===0&&consumedBlockIds.length===0){const highest=highestUsedIndex(input.state.messageRefs);const allCovered=effectiveMessageIds.size>0&&[...effectiveMessageIds].every(id=>input.preExistingCoverage.has(id));return{tokens:0,warnings:[...warnings,allCovered?`Range ${input.spec.startRef}..${input.spec.endRef} folded nothing \u2014 every message in it is already covered by active block(s). Nothing failed; do not resend this range. To rewrite or merge those blocks, reference them by block ID instead.`:`Range ${input.spec.startRef}..${input.spec.endRef} folded nothing \u2014 all of its content is protected or filtered (protected tool calls/results, media, or the recent-message zone), which always stays visible. Nothing failed; do not resend this range. Session highest allocated ref is ${highest>0?indexToRef(highest):"none"}.`],noop:true}}let compressedTokens=0;for(const id of filteredIds){const message=input.messages.find(entry=>entry.id===id);compressedTokens+=message?countMessageTokens(message,input.countTokens):0}for(const consumedId of consumedBlockIds){const consumed=blockById(input.state,consumedId);if(consumed){compressedTokens+=input.countTokens(consumed.summary)}}const foldMediaRefs=collectFoldMediaRefs(filteredIds.map(id=>input.messages.find(entry=>entry.id===id)),consumedBlockIds.map(id=>blockById(input.state,id))).map(scrubLoneSurrogates2);const blockId=allocateBlockId(input.state);const interval=resolveCoverageInterval(filteredIds.map(id=>input.messages.find(entry=>entry.id===id)),consumedBlockIds.map(id=>blockById(input.state,id)));const block={blockId,runId:input.runId,tier:outputTier,topic:input.spec.topic,summary:appendMediaRefsSection(input.spec.summary,foldMediaRefs),directMessageIds:filteredIds,effectiveMessageIds:[...effectiveMessageIds],directBlockIds:[...consumedBlockIds],compressedTokens,createdAt:Date.now(),survivedCount:0,generation:"young",active:true,compressCallId:input.spec.compressCallId,startRef:input.spec.startRef,endRef:input.spec.endRef,...interval?{startSeq:interval.start,endSeq:interval.end}:{}};input.state.blocks.push(block);for(const consumedId of consumedBlockIds){const consumed=blockById(input.state,consumedId);if(consumed)consumed.active=false}return{tokens:compressedTokens,warnings}}function resolveCoverageInterval(directMessages,consumedBlocks){const segments=[];for(const message of directMessages){if(!message||typeof message.ledgerSeq!=="number"||!Number.isInteger(message.ledgerSeq)){return void 0}segments.push({start:message.ledgerSeq,end:message.ledgerSeq})}for(const consumed of consumedBlocks){if(!consumed||typeof consumed.startSeq!=="number"||typeof consumed.endSeq!=="number"||consumed.endSeq<consumed.startSeq||consumed.startSeq<0||consumed.endSeq<0){return void 0}segments.push({start:consumed.startSeq,end:consumed.endSeq})}if(segments.length===0)return void 0;segments.sort((a,b2)=>a.start-b2.start||a.end-b2.end);let merged={...segments[0]};for(const segment of segments.slice(1)){if(segment.start<=merged.end+1){if(segment.end>merged.end)merged.end=segment.end}else{return void 0}}return merged}function validateCompressionRange(input){const cfg=input.config.compress;validateSummaryLength(input.spec,cfg,{skipMin:input.minFloorCovered===true})}function summaryLengthError(kind,message){const error=new Error(message);error.name="SummaryLengthError";error.kind=kind;return error}function isSummaryLengthError(error){if(!(error instanceof Error)||error.name!=="SummaryLengthError")return false;const kind=error.kind;return kind==="empty"||kind==="tooShort"||kind==="tooLong"}function lengthRemediation(kinds){const parts=[];if(kinds.has("tooShort")||kinds.has("empty")){parts.push("expand each too-short/empty summary until it reaches its minimum \u2014 write out the key information the range actually contains (do NOT shorten it)")}if(kinds.has("tooLong")){parts.push("shorten or split each too-long summary to fit its cap")}return`Fix it and resend the whole batch: ${parts.join("; and ")}; or drop the offending range(s) and resend only the rest that validate.`}function validateSummaryLength(spec,cfg,opts={}){const summary=spec.summary?.trim()??"";if(summary.length===0){throw summaryLengthError("empty","Summary is empty \u2014 provide a meaningful summary of the compressed range.")}if(!opts.skipMin&&cfg.minSummaryLength>0&&summary.length<cfg.minSummaryLength){throw summaryLengthError("tooShort",`Summary too short (${summary.length} chars, min ${cfg.minSummaryLength}). The summary must capture the compressed range's key information.`)}const effectiveMax=spec.summaryMaxChars??cfg.maxSummaryLength;if(effectiveMax>0&&summary.length>effectiveMax){throw summaryLengthError("tooLong",`Summary too long (${summary.length} chars, max ${effectiveMax}). Strip noise \u2014 keep critical paths, decisions, errors, and code references. Or pass summaryMaxChars to increase the limit \u2014 don't lose critical info just to fit.`)}}function resolveAdaptiveGrowth(modelContextLimit,nudge){if(!modelContextLimit||modelContextLimit<=0)return nudge.growthFloor;return Math.min(nudge.growthCap,Math.max(nudge.growthFloor,Math.round(modelContextLimit*nudge.growthRatio)))}function resolveMinPressureBenefit(modelContextLimit,nudge){return nudge.minPressureBenefitTokens??Math.max(5e3,Math.round(modelContextLimit*.01))}function pendingByTier(state8,recommendation,countTokens,minCompressRange){const out={};const merged=recommendation?.recommendedRanges??[];const effective=minCompressRange>0?merged.filter(r=>(r.chars??r.tokens*4)>=minCompressRange):merged;out[1]={pending:effective.reduce((s3,r)=>s3+r.tokens,0),targetBlocks:[]};const active=activeBlocks(state8).filter(b2=>!b2.retired);const t1=active.filter(b2=>b2.tier===1);const t2=active.filter(b2=>b2.tier===2);out[2]={pending:t1.reduce((s3,b2)=>s3+countTokens(b2.summary),0),targetBlocks:t1};out[3]={pending:t2.reduce((s3,b2)=>s3+countTokens(b2.summary),0),targetBlocks:t2};return out}function decideNudge(input){const{config,state:state8,tokenCount,recommendation,countTokens}=input;const limit=config.modelContextLimit;const usage=limit>0?tokenCount/limit:0;const nudgeGrowthTokens=resolveAdaptiveGrowth(limit,config.nudge);const minPressureBenefit=resolveMinPressureBenefit(limit,config.nudge);const overLimit=usage>=config.nudge.maxContextLimitPct;const emergencyOverride=usage>=config.nudge.emergencyThresholdPct;const pressure=overLimit||emergencyOverride;const estimateHoldStreak=input.tokenCountSource==="estimate"?(state8.nudge.estimateHoldStreak??0)+1:0;state8.nudge.estimateHoldStreak=estimateHoldStreak>0?estimateHoldStreak:void 0;const maxEstimateHoldRounds=Math.max(0,Math.floor(config.nudge.maxEstimateHoldRounds??2));const pressureDeferredNoSample=pressure&&input.tokenCountSource==="estimate"&&config.nudge.requireUsageSampleForPressure!==false&&estimateHoldStreak<=maxEstimateHoldRounds;const baseline=state8.nudge.lastPerMessageNudgeTokens;const hadPendingNudge=state8.nudge.lastNudgeShownTokens>0;const hasPendingNudge=hadPendingNudge;const effectiveThreshold=hasPendingNudge?Math.floor(nudgeGrowthTokens/2):nudgeGrowthTokens;const growthReference=state8.nudge.lastNudgeShownTokens>0?state8.nudge.lastNudgeShownTokens:baseline>0?baseline:tokenCount;const growthFloor=Math.max(config.nudge.minGrowthFloor,config.nudge.minGrowthRatio*nudgeGrowthTokens);const growthSinceReference=tokenCount-growthReference;const rec=recommendation;const tiers=pendingByTier(state8,rec,countTokens,config.compress.minCompressRange);const tier2Threshold=Math.round(nudgeGrowthTokens*(config.nudge.tier2GrowthMultiplier??1.5));const tierThresholds={1:config.nudge.tierGrowthTokens?.t1??nudgeGrowthTokens,2:config.nudge.tierGrowthTokens?.t2??tier2Threshold,3:config.nudge.tierGrowthTokens?.t3??tier2Threshold};let injectedTier=null;let injectedReason="";let bestPending=0;const t1Eff=tiers[1]?.pending??0;const t2Pen=tiers[2]?.pending??0;const t3Pen=tiers[3]?.pending??0;const maxPending=Math.max(0,t1Eff,t2Pen,t3Pen);const t1HarvestStall=config.tiers.enabled&&state8.nudge.t1HarvestStall===true;let stallEscalated=false;const firstSightMassReady=state8.nudge.lastNudgeShownTokens===0&&baseline===0&&usage>=config.nudge.minContextLimitPct&&Math.max(t1Eff,t2Pen,t3Pen)>=nudgeGrowthTokens;const absorbedDebt=state8.nudge.absorbedDebt??0;const absorbCount=state8.nudge.absorbCount??0;const repeatAbsorbs=absorbCount>=2;const payableDebt=repeatAbsorbs?absorbedDebt:0;const backlogDrainReady=repeatAbsorbs&&absorbedDebt>0&&state8.nudge.lastNudgeShownTokens===0&&Math.max(t1Eff,t2Pen,t3Pen)>=2*tierThresholds[1]&&usage>=config.nudge.minContextLimitPct;const growthReady=firstSightMassReady||backlogDrainReady||growthSinceReference+payableDebt>=growthFloor;const t2Count=tiers[2]?.targetBlocks.length??0;const t3Count=tiers[3]?.targetBlocks.length??0;const t2CountReady=t2Count>=config.tiers.tier2Trigger;const t3CountReady=t3Count>=config.tiers.tier3Trigger;if(pressure){const candidates=[];if(!(t1HarvestStall&&Math.max(t2Pen,t3Pen)>=minPressureBenefit)){candidates.push(1)}if(config.tiers.enabled){candidates.push(2,3)}let best=null;for(const t of candidates){const p2=tiers[t]?.pending??0;if(p2>bestPending){bestPending=p2;best=t}}if(best!==null&&bestPending>=minPressureBenefit&&!pressureDeferredNoSample){injectedTier=best;stallEscalated=t1HarvestStall&&best!==1;const label=emergencyOverride?"EMERGENCY":"OVER-LIMIT";injectedReason=best===1?`${label} T1: max effective pending ${bestPending}, usage ${Math.round(usage*100)}%`:`${label} T${best} distill: max pending ${bestPending} (T1 effective ${t1Eff}, T2 ${t2Pen}, T3 ${t3Pen}), usage ${Math.round(usage*100)}%`}}else if(growthReady){if(t1HarvestStall&&t3Pen>=tierThresholds[3]&&t3Pen>t2Pen){const lastShown=state8.nudge.lastShownByTier[3]??0;const cadenceMet=lastShown===0||tokenCount-lastShown>=growthFloor;if(cadenceMet){injectedTier=3;stallEscalated=true;injectedReason=`T3 condense ready: ${tiers[3].targetBlocks.length} tier-2 blocks (${t3Pen} tokens) >= ${tierThresholds[3]}${config.nudge.tierGrowthTokens?.t3===void 0?" (1.5x)":""} and > T2 ${t2Pen}, usage ${Math.round(usage*100)}%`}}if(injectedTier===null&&t1HarvestStall&&t2Pen>=tierThresholds[2]){const lastShown=state8.nudge.lastShownByTier[2]??0;const cadenceMet=lastShown===0||tokenCount-lastShown>=growthFloor;if(cadenceMet){injectedTier=2;stallEscalated=true;injectedReason=`T2 distill ready: ${tiers[2].targetBlocks.length} tier-1 blocks (${t2Pen} tokens) >= ${tierThresholds[2]}${config.nudge.tierGrowthTokens?.t2===void 0?" (1.5x)":""}, usage ${Math.round(usage*100)}%`}}if(injectedTier===null&&t1Eff>=tierThresholds[1]){injectedTier=1;injectedReason=`T1 effective ${t1Eff} >= ${tierThresholds[1]}, growth ${growthSinceReference}, usage ${Math.round(usage*100)}%`}else if(injectedTier===null&&config.tiers.enabled&&(t2CountReady||t2Pen>=tierThresholds[2]&&t2Pen>t1Eff)){const lastShown=state8.nudge.lastShownByTier[2]??0;const cadenceMet=lastShown===0||tokenCount-lastShown>=growthFloor;if(cadenceMet){injectedTier=2;injectedReason=t2CountReady?`T2 distill ready: ${t2Count} tier-1 blocks >= tier2Trigger ${config.tiers.tier2Trigger} (${t2Pen} tokens), usage ${Math.round(usage*100)}%`:`T2 distill ready: ${tiers[2].targetBlocks.length} tier-1 blocks (${t2Pen} tokens) >= ${tierThresholds[2]}${config.nudge.tierGrowthTokens?.t2===void 0?" (1.5x)":""} and > T1 effective ${t1Eff}, usage ${Math.round(usage*100)}%`}}else if(injectedTier===null&&config.tiers.enabled&&(t3CountReady||t3Pen>=tierThresholds[3]&&t3Pen>t2Pen&&t3Pen>t1Eff)){const lastShown=state8.nudge.lastShownByTier[3]??0;const cadenceMet=lastShown===0||tokenCount-lastShown>=growthFloor;if(cadenceMet){injectedTier=3;injectedReason=t3CountReady?`T3 condense ready: ${t3Count} tier-2 blocks >= tier3Trigger ${config.tiers.tier3Trigger} (${t3Pen} tokens), usage ${Math.round(usage*100)}%`:`T3 condense ready: ${tiers[3].targetBlocks.length} tier-2 blocks (${t3Pen} tokens) >= ${tierThresholds[3]}${config.nudge.tierGrowthTokens?.t3===void 0?" (1.5x)":""} and > T2 ${t2Pen} and > T1 effective ${t1Eff}, usage ${Math.round(usage*100)}%`}}}const shouldInject=injectedTier!==null;if(shouldInject&&firstSightMassReady){injectedReason+=" [first-sight mass]"}if(shouldInject&&stallEscalated){injectedReason+=" [T1 harvest stall]"}let reason;if(injectedTier!==null){reason=injectedReason}else if(pressure&&pressureDeferredNoSample){const label=emergencyOverride?"EMERGENCY":"OVER-LIMIT";reason=`${label}: usage ${Math.round(usage*100)}% but the meter reading is estimate-grade (no billing sample landed this cycle, max pending ${maxPending}) \u2014 pressure injection held (estimate round ${estimateHoldStreak} of ${maxEstimateHoldRounds}) until a usage-grade reading decides or the estimate-hold backstop elapses; hard-overflow backstop unaffected`}else if(pressure){const label=emergencyOverride?"EMERGENCY":"OVER-LIMIT";reason=bestPending===0?`${label}: usage ${Math.round(usage*100)}% but no tier has effective compressible content (T1 effective ${t1Eff}, T2 ${t2Pen}, T3 ${t3Pen}) \u2014 nudge suppressed to avoid offering ranges below minCompressRange`:`${label}: usage ${Math.round(usage*100)}% but max pending ${bestPending} < min benefit ${minPressureBenefit} tokens (T1 effective ${t1Eff}, T2 ${t2Pen}, T3 ${t3Pen}) \u2014 suppressed: rewriting below the benefit floor reclaims almost nothing while usage stays high; truncate.threshold remains the safety valve`}else{const tiersList=[1,2,3];const eligible=tiersList.filter(t=>config.tiers.enabled||t===1);const countReady=t=>t===2?t2Count>=config.tiers.tier2Trigger:t===3?t3Count>=config.tiers.tier3Trigger:false;const ready=eligible.filter(t=>(tiers[t]?.pending??0)>=tierThresholds[t]).map(t=>`T${t} ${tiers[t].pending}`);const readyCount=eligible.filter(t=>(tiers[t]?.pending??0)<tierThresholds[t]&&countReady(t)).map(t=>`T${t} ${t===2?t2Count:t3Count} blocks (count)`);const readyAll=[...ready,...readyCount];const readyHint=readyAll.length>0?`, ready: ${readyAll.join(", ")}`:"";const blocked=eligible.filter(t=>((tiers[t]?.pending??0)>=tierThresholds[t]||countReady(t))&&(state8.nudge.lastShownByTier[t]??0)>0&&tokenCount-(state8.nudge.lastShownByTier[t]??0)<growthFloor).map(t=>`T${t} (cadence)`);const blockedHint=blocked.length>0?`, blocked: ${blocked.join(", ")}`:"";const minTierThreshold=Math.min(tierThresholds[1],tierThresholds[2],tierThresholds[3]);const pendingShort=maxPending<minTierThreshold;const growthShort=growthSinceReference<growthFloor;const parts=[];if(pendingShort)parts.push(`max compressible ${maxPending} < threshold ${minTierThreshold}`);if(growthShort)parts.push(absorbedDebt>0&&!repeatAbsorbs?`growth ${growthSinceReference} + absorbed ${absorbedDebt} held (single abort, #5293) < floor ${growthFloor}`:payableDebt>0?`growth ${growthSinceReference} + absorbed ${absorbedDebt} across ${absorbCount} aborts < floor ${growthFloor}`:`growth ${growthSinceReference} < floor ${growthFloor}`);if(parts.length===0)parts.push(`max compressible ${maxPending}, growth ${growthSinceReference}`);reason=`${parts.join("; ")}${readyHint}${blockedHint}`}const ctxBreakdown=computeContextBreakdown(input.messages,tokenCount,growthSinceReference,countTokens);return{shouldInject,reason,compressibleRanges:rec?.recommendedRanges??[],protectedRanges:rec?.contextRanges.protected??[],activeBlockSpans:activeBlockSpans(state8),tierTargetBlocks:injectedTier?tiers[injectedTier].targetBlocks:[],contextUsage:usage,tier:injectedTier,breakdown:{usage,growth:growthSinceReference,growthReference,effectiveThreshold,nudgeGrowthTokens,growthFloor,hasPendingNudge:hasPendingNudge?1:0,overLimit:overLimit?1:0,emergencyOverride:emergencyOverride?1:0,pressureDeferredNoSample:pressureDeferredNoSample?1:0,estimateHoldStreak,minPressureBenefit,pendingT1:tiers[1].pending,pendingT2:tiers[2].pending,pendingT3:tiers[3].pending,maxPending},contextBreakdown:ctxBreakdown}}function computeContextBreakdown(messages,total,growth,countTokens){const count=countTokens??(t=>Math.ceil(t.length/4));let system=0,tool=0,summaries=0,code=0,text2=0;for(const msg of messages){const tokens=countMessageTokens(msg,count);if(msg.text?.startsWith("[Compressed conversation section]")){summaries+=tokens}else if(isToolMessage(msg)){tool+=tokens}else if(msg.role==="system"){system+=tokens}else if(msg.text?.includes("```")){code+=tokens}else{text2+=tokens}}return{system,tool,summaries,code,text:text2,total,growth}}function cloneState(state8){return{blocks:state8.blocks.map(block=>({...block,directMessageIds:[...block.directMessageIds],effectiveMessageIds:[...block.effectiveMessageIds],directBlockIds:[...block.directBlockIds]})),messageRefs:{byRaw:{...state8.messageRefs.byRaw},byRef:{...state8.messageRefs.byRef}},tokenSnapshot:{...state8.tokenSnapshot??{}},tsStamps:state8.tsStamps?{...state8.tsStamps}:void 0,nudge:{...state8.nudge,anchors:{...state8.nudge.anchors}},stats:{...state8.stats},absorbed:(state8.absorbed??[]).map(record3=>({...record3})),rules:(state8.rules??[]).map(rule=>({...rule})),nextRuleId:state8.nextRuleId,terminalStreak:state8.terminalStreak,nextBlockId:state8.nextBlockId,nextRunId:state8.nextRunId,hiddenOrphanRefs:state8.hiddenOrphanRefs?[...state8.hiddenOrphanRefs]:void 0,sweptOrphanCallIds:state8.sweptOrphanCallIds?[...state8.sweptOrphanCallIds]:void 0,pendingOrphanSweepMinRef:state8.pendingOrphanSweepMinRef,deadRefs:state8.deadRefs?[...state8.deadRefs]:void 0,lastPassIds:state8.lastPassIds?[...state8.lastPassIds]:void 0,refLedgerAligned:state8.refLedgerAligned,...state8.timestampsHighWaterRefSeq!==void 0?{timestampsHighWaterRefSeq:state8.timestampsHighWaterRefSeq}:{},...state8.suppressMintingOnce!==void 0?{suppressMintingOnce:state8.suppressMintingOnce}:{}}}function scoreRelevance(block,terms){const topic=(block.topic??"").toLowerCase();const summary=block.summary.toLowerCase();let score=0;for(const term of terms){const topicHits=countOccurrences(topic,term);if(topicHits>0)score+=Math.min(topicHits*.15,.45);const summaryHits=countOccurrences(summary,term);if(summaryHits>0)score+=Math.min(summaryHits*.04,.2)}return Math.min(score,1)}function countOccurrences(haystack,needle){if(!haystack||!needle)return 0;let count=0;let position=0;while((position=haystack.indexOf(needle,position))!==-1){count++;position+=needle.length}return count}function isValidPackName(name2){return/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name2)&&!name2.includes("..")}function triStateSection(raw,keys){const out={};if(!raw||typeof raw!=="object"||Array.isArray(raw))return out;for(const key2 of keys){const v2=raw[key2];if(typeof v2==="string")out[key2]=v2;else if(v2===null)out[key2]=null}return out}function sanitizePackSurface(raw){if(!raw)return{};const prompts={};const rawPrompts=raw.prompts;if(rawPrompts&&typeof rawPrompts==="object"&&!Array.isArray(rawPrompts)){for(const k2 of PROMPT_RULE_KEYS){const v2=rawPrompts[k2];if(typeof v2==="string")prompts[k2]=v2}}const toolPrompts={};const rawTools=raw.toolPrompts;if(rawTools&&typeof rawTools==="object"&&!Array.isArray(rawTools)){for(const[name2,value]of Object.entries(rawTools)){if(!value||typeof value!=="object"||Array.isArray(value))continue;const ov=value;const out={};if(typeof ov.description==="string")out.description=ov.description;if(ov.paramDescriptions&&typeof ov.paramDescriptions==="object"&&!Array.isArray(ov.paramDescriptions)){const params={};for(const[p2,d]of Object.entries(ov.paramDescriptions)){if(typeof d==="string")params[p2]=d}if(Object.keys(params).length>0)out.paramDescriptions=params}if(Object.keys(out).length>0)toolPrompts[name2]=out}}const surface={prompts,promptSections:triStateSection(raw.promptSections,COMPRESS_SECTION_KEYS),nudgeSections:triStateSection(raw.nudgeSections,NUDGE_SECTION_KEYS),toolPrompts};const adapters=raw.adapters;if(adapters&&typeof adapters==="object"&&!Array.isArray(adapters)){surface.adapters=adapters}return surface}function readPackFile(file){try{const parsed=JSON.parse(readFileSync2(file,"utf8"));return parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}catch{return null}}function createDirPackSource(id,dir){const resolve3=name2=>{if(!isValidPackName(name2))return null;const file=path10.join(dir,`${name2}.json`);const raw=readPackFile(file);if(!raw)return null;return{name:name2,version:typeof raw.version==="string"?raw.version:void 0,description:typeof raw.description==="string"?raw.description:void 0,surface:sanitizePackSurface(raw),source:`file:${file}`}};return{id,resolve:resolve3,list(){let names;try{names=readdirSync3(dir).filter(f2=>f2.endsWith(".json"))}catch{return[]}const out=[];for(const f2 of names){const pack=resolve3(f2.slice(0,-5));if(pack)out.push(pack)}return out}}}function createPackResolver(sources2){return{sources:sources2,resolve(name2){if(!isValidPackName(name2))return null;for(const source of sources2){const pack=source.resolve(name2);if(pack)return pack}return null},listPacks(){const seen=new Set;const out=[];for(const source of sources2){for(const pack of source.list?.()??[]){if(!seen.has(pack.name)){seen.add(pack.name);out.push(pack)}}}return out}}}function resolveActiveBlock(state8,raw){const normalized=typeof raw==="string"?raw.trim():"";const blockId=parseBlockIdArg(normalized);if(!blockId){return{error:`"${normalized}" is not a valid block id (expected e.g. b5)`}}const block=state8.blocks.find(b2=>b2.blockId===blockId);if(!block){return{error:`${blockId} does not exist in this session \u2014 run acp_status for the current block list`}}if(!block.active){return{error:`${blockId} is not active (distilled into a higher tier or deactivated) \u2014 only active blocks can be operated on`}}return{blockId,state:state8}}function retireBlocks(state8,rawIds){const outcome={applied:[],noop:[],failed:[]};for(const raw of rawIds){const target=resolveActiveBlock(state8,raw);if("error"in target){outcome.failed.push({id:String(raw).trim(),reason:target.error});continue}const block=state8.blocks.find(b2=>b2.blockId===target.blockId);if(block.retired){outcome.noop.push(block.blockId)}else{block.retired=true;outcome.applied.push(block.blockId)}}return outcome}function restoreBlocks(state8,rawIds){const outcome={applied:[],noop:[],failed:[]};for(const raw of rawIds){const target=resolveActiveBlock(state8,raw);if("error"in target){outcome.failed.push({id:String(raw).trim(),reason:target.error});continue}const block=state8.blocks.find(b2=>b2.blockId===target.blockId);if(block.retired){block.retired=false;outcome.applied.push(block.blockId)}else{outcome.noop.push(block.blockId)}}return outcome}function rewriteBlockSummary(state8,raw,newSummary){const target=resolveActiveBlock(state8,raw);if("error"in target)return{ok:false,id:String(raw).trim(),reason:target.error};const block=state8.blocks.find(b2=>b2.blockId===target.blockId);const next=typeof newSummary==="string"?newSummary.trim():"";if(!next){return{ok:false,id:block.blockId,reason:"summary must be non-empty text"}}if(next===block.summary.trim()){return{ok:false,id:block.blockId,reason:"new summary is identical to the current one \u2014 nothing to do"}}block.previousSummary=block.summary;block.summary=next;block.rewrittenAt=Date.now();return{ok:true,blockId:block.blockId,prevChars:block.previousSummary.length,newChars:next.length}}function formatTokens2(n){if(!Number.isFinite(n)||n<=0)return"0";return n>=1e3?`${(n/1e3).toFixed(1)}K`:String(n)}function pct(n,total){if(n<=0||total<=0)return 0;return Math.round(n/total*100)}function numericPart2(blockId){const match=/^b(\d+)$/.exec(blockId);return match&&match[1]!==void 0?Number(match[1]):0}function summaryTokensOf(block,countTokens){return countTokens(block.summary)}function effectiveCompressedTokens(block,_state,_countTokens){return block.compressedTokens}function tierLabel(block){return`T${block.tier}`}function tierBreakdown(blocks,countTokens){const tierTokens={};const tierCounts={};for(const block of blocks){tierTokens[block.tier]=(tierTokens[block.tier]??0)+summaryTokensOf(block,countTokens);tierCounts[block.tier]=(tierCounts[block.tier]??0)+1}const tiers=Object.keys(tierTokens).map(Number);if(tiers.length<=1)return null;const parts=[];for(const tier of[1,2,3]){if(tierTokens[tier])parts.push(`T${tier}: ${formatTokens2(tierTokens[tier])} (${tierCounts[tier]} blocks)`)}return parts.join(" | ")}function collectVisible(messages,state8,countTokens){const coveredIds=new Set;for(const block of state8.blocks){if(!block.active)continue;for(const id of block.effectiveMessageIds)coveredIds.add(id)}let summaryTokens=0;for(const block of state8.blocks){if(block.active&&!block.retired)summaryTokens+=summaryTokensOf(block,countTokens)}const visible=[];const summaryNodes=[];const toolCallNames=new Map;for(const message of messages){if(message.contentType==="tool-call"&&message.toolCallId&&message.toolName){toolCallNames.set(message.toolCallId,message.toolName)}}let pendingGap=false;messages.forEach((message,index)=>{const ref=refForRaw(state8.messageRefs,message.id);if(!ref)return;const tokens=countMessageTokens(message,countTokens);if(isRenderedSummaryMessage(message)){if(ref!==BLOCKED_REF&&tokens>0){const blockId=summaryBlockIdOf(message.id);if(blockId!==null){summaryNodes.push({ref,blockId,tokens});pendingGap=true}}return}if(!coveredIds.has(message.id)&&tokens>0){const isTool=isToolMessage(message);const tool=isTool?message.toolName??(message.toolCallId?toolCallNames.get(message.toolCallId):void 0)??"tool":"text";visible.push({ref,tokens,tool,isTool,index,isUser:message.role==="user",gapBefore:pendingGap,toolCallId:message.toolCallId});pendingGap=isLiveCheckpointCarrier(message,state8);return}if(ref!==BLOCKED_REF&&tokens>0)pendingGap=true});return{visible,summaryTokens,summaryNodes}}function buildStatusReport(state8,messages,countTokens,options={}){const scope=options.scope;const view=options.view??"ranges";const toolFilter=options.tool;const sort=options.sort??"size";const limit=options.limit??30;const activeBlocks2=state8.blocks.filter(b2=>b2.active).sort((a,b2)=>numericPart2(a.blockId)-numericPart2(b2.blockId));const residentBlocks=activeBlocks2.filter(b2=>!b2.retired);const retiredBlocks=activeBlocks2.filter(b2=>b2.retired);if(scope==="compressed"){return renderCompressedDrilldown(activeBlocks2,state8,sort,limit,countTokens,options.meta)}const{visible,summaryTokens,summaryNodes}=collectVisible(messages,state8,countTokens);if(scope==="uncompressed"){if(view==="messages"){const cfg=options.config;const orig=options.originalMessages;const blockedInfo=cfg&&orig?{agedIds:collectAgedCompressCallIds(orig,cfg),isCompress:t=>isCompressToolName(t,cfg)}:void 0;return renderMessageDrilldown(visible,toolFilter,sort,limit,blockedInfo)}return renderUncompressedRanges(visible,summaryNodes,sort,limit,state8,countTokens,options.config,options.originalMessages)}return renderOverview(visible,summaryTokens,residentBlocks,retiredBlocks,state8,countTokens,limit,options.meta)}function surfaceLine(meta){if(!meta)return null;const parts=[];if(meta.pack)parts.push(`pack=${meta.pack}${meta.packVersion?` v${meta.packVersion}`:""}`);if(meta.host)parts.push(`host=${meta.host}`);if(parts.length===0)return null;return`ACTIVE SURFACE: ${parts.join(" | ")}`}function renderOverview(visible,summaryTokens,blocks,retiredBlocks,state8,countTokens,limit,meta){const lines=[];const surface=surfaceLine(meta);if(surface){lines.push(surface);lines.push("")}const toolTypeMap=new Map;for(const message of visible){toolTypeMap.set(message.tool,(toolTypeMap.get(message.tool)??0)+message.tokens)}const totalTool=visible.filter(m2=>m2.isTool).reduce((sum,m2)=>sum+m2.tokens,0);const totalText=visible.filter(m2=>!m2.isTool).reduce((sum,m2)=>sum+m2.tokens,0);const total=summaryTokens+totalTool+totalText;lines.push("CONTEXT BREAKDOWN");lines.push(` ${formatTokens2(totalTool)} tool (${pct(totalTool,total)}%) | ${formatTokens2(totalText)} text (${pct(totalText,total)}%) | ${formatTokens2(summaryTokens)} summaries (${pct(summaryTokens,total)}%)`);const topTypes=[...toolTypeMap.entries()].sort((a,b2)=>b2[1]-a[1]).slice(0,3);if(topTypes.length>0){lines.push(` Top tools: ${topTypes.map(([t,n])=>`${t} (${pct(n,total)}%)`).join(", ")}`)}lines.push("");if(blocks.length===0){lines.push("COMPRESSED BLOCKS");lines.push(" No compressed blocks.")}else{const totalSummary=blocks.reduce((s3,b2)=>s3+summaryTokensOf(b2,countTokens),0);const totalEffective=blocks.reduce((s3,b2)=>s3+effectiveCompressedTokens(b2,state8,countTokens),0);lines.push(`COMPRESSED BLOCKS \u2014 ${blocks.length} active (${formatTokens2(totalSummary)} summary, ${formatTokens2(totalEffective)} original)`);const breakdown=tierBreakdown(blocks,countTokens);if(breakdown)lines.push(` Tier usage: ${breakdown}`);lines.push("");const sorted=[...blocks].sort((a,b2)=>effectiveCompressedTokens(b2,state8,countTokens)-effectiveCompressedTokens(a,state8,countTokens)||b2.createdAt-a.createdAt);for(const block of sorted.slice(0,limit)){const topic=block.topic??"(no topic)";const eff=effectiveCompressedTokens(block,state8,countTokens);lines.push(` ${block.blockId} (${tierLabel(block)}) ${formatTokens2(eff)}\u2192${formatTokens2(summaryTokensOf(block,countTokens))} ${block.effectiveMessageIds.length} msgs "${topic}"`)}if(blocks.length>limit){lines.push(` ... and ${blocks.length-limit} more blocks not shown (scope:"compressed", limit:${blocks.length} for full list)`)}}if(retiredBlocks.length>0){const freed=retiredBlocks.reduce((s3,b2)=>s3+summaryTokensOf(b2,countTokens),0);lines.push("");lines.push(`RETIRED BLOCKS \u2014 ${retiredBlocks.length} out of the resident view (${formatTokens2(freed)} summary kept off the wire)`);const sorted=[...retiredBlocks].sort((a,b2)=>numericPart2(a.blockId)-numericPart2(b2.blockId));for(const block of sorted.slice(0,limit)){const topic=block.topic??"(no topic)";lines.push(` ${block.blockId} (${tierLabel(block)}) ${formatTokens2(summaryTokensOf(block,countTokens))} summary ${block.effectiveMessageIds.length} msgs "${topic}"`)}if(retiredBlocks.length>limit){lines.push(` ... and ${retiredBlocks.length-limit} more retired blocks not shown`)}lines.push(` acp_restore({ blockId }) puts a block back into the view; decompress/search_context work on retired blocks as usual.`)}lines.push("");lines.push(`Tip: call again with scope:"uncompressed" for the compressible-ranges listing (view:"messages" drills into individual refs)`);return lines.join("\n")}function renderUncompressedRanges(visible,summaryNodes,sort,limit,state8,countTokens,config,original){const lines=[];const totalTokens=visible.reduce((s3,m2)=>s3+m2.tokens,0);const blockedRows=visible.filter(m2=>m2.ref===BLOCKED_REF);const rangeable=visible.filter(m2=>m2.ref!==BLOCKED_REF);lines.push(`UNCOMPRESSED \u2014 ${formatTokens2(totalTokens)} | ${rangeable.length} visible messages${blockedRows.length>0?` + ${blockedRows.length} unrefed`:""}`);lines.push("");if(visible.length===0&&summaryNodes.length===0){lines.push(" (no uncompressed messages)");return lines.join("\n")}const dominantTool=toolTokens=>{let best="text";let bestN=-1;for(const[tool,n]of toolTokens){if(n>bestN){best=tool;bestN=n}}return best};const merged=[];for(const group of segmentGroups(rangeable)){const first=group[0];const r={startRef:first.ref,endRef:first.ref,startIndex:first.index,count:1,tokens:first.tokens,toolTokens:new Map([[first.tool,first.tokens]])};for(let i=1;i<group.length;i++){const m2=group[i];r.endRef=m2.ref;r.count+=1;r.tokens+=m2.tokens;r.toolTokens.set(m2.tool,(r.toolTokens.get(m2.tool)??0)+m2.tokens)}merged.push(r)}if(sort!=="time")merged.sort((a,b2)=>b2.tokens-a.tokens||a.startIndex-b2.startIndex);let flagFor=null;if(config&&original){const coverage=collectCoverage(state8);const protectedRefs=computeProtectedRefs(original,state8,config,countTokens);const shared=buildProjectionShared(original,state8,config);const splitDescOf=p2=>{const parts=[];if(p2.splitTurnCount>0)parts.push(`${p2.splitTurnCount} turn(s)`);if(p2.splitPairCount>0)parts.push(`${p2.splitPairCount} tool call/result pair(s)`);return parts.join(" and ")||"turn structure"};flagFor=r=>{let proj;try{proj=projectUnit({messages:original,state:state8,config,startRef:r.startRef,endRef:r.endRef,preExistingCoverage:coverage,protectedMessageIds:protectedRefs,shared})}catch{return"\u26A0 not foldable: refs unresolvable"}if(proj.fatal?.kind==="zone")return"\u26A0 not foldable: protected zone only";if(proj.fatal?.kind==="split")return`\u26A0 not foldable: would split ${splitDescOf(proj)}`;if(proj.filteredIds.length===0&&proj.consumedBlockIds.length===0)return"\u26A0 not foldable: nothing new to fold";return null}}lines.push(`Sorted by ${sort==="time"?"time":"size"}`);lines.push("");if(rangeable.length===0){lines.push(" (no raw uncompressed messages)")}else{for(const r of merged.slice(0,limit)){const range=r.count===1?r.startRef:orderedRefPair(r.startRef,r.endRef).join("\u2013");const flag=flagFor?flagFor(r):null;lines.push(` ${range} (${r.count} msgs, ${formatTokens2(r.tokens)}${r.count>1?` (${Math.round(r.tokens/r.count)}/msg)`:""}) ${dominantTool(r.toolTokens)}${flag?` ${flag}`:""}`)}if(merged.length>limit){lines.push(` ... and ${merged.length-limit} more ranges`)}lines.push("");lines.push(` To fold one of the ranges above: compress({ content: "m00150\u2013m00220 optional topic\\n<summary markdown>" })`)}if(summaryNodes.length>0){const sumTokens=summaryNodes.reduce((s3,n)=>s3+n.tokens,0);lines.push("");lines.push(`ALREADY-COMPRESSED SUMMARY NODES \u2014 ${summaryNodes.length} node(s), ${formatTokens2(sumTokens)}`);const shown=summaryNodes.slice(0,limit);lines.push(` ${shown.map(n=>{const block=state8.blocks.find(b2=>b2.blockId===n.blockId&&b2.active);return block?`${n.blockId} (T${block.tier}) ${formatTokens2(n.tokens)}`:`${n.blockId} ${formatTokens2(n.tokens)}`}).join(" \xB7 ")}`);if(summaryNodes.length>limit){lines.push(` ... and ${summaryNodes.length-limit} more nodes (scope:"compressed" lists every block)`)}lines.push(` These are block summaries already in the view \u2014 plain m-ref ranges do not fold them; only tier distillation (block-ID boundaries) does.`);const hint=config?tierActionHint(config,state8).trim():"";if(hint){lines.push(` ${hint}`)}else if(config){lines.push(` Tier distillation is not armed yet \u2014 the nudge announces when block-ID distillation is actionable.`)}else{lines.push(` Fold them via tier distillation: compress({ content: "b1\u2013bN optional topic\\nsummary markdown..." })`)}}if(blockedRows.length>0){const blockedTokens=blockedRows.reduce((s3,m2)=>s3+m2.tokens,0);lines.push("");lines.push(`UNREFED MESSAGES \u2014 ${blockedRows.length} msg(s), ${formatTokens2(blockedTokens)} (protected rows \u2014 no m-ref to cite; cannot be folded by name)`);const isCompressRow=m2=>config?isCompressToolName(m2.tool,config):m2.tool==="compress";const compressRows=blockedRows.filter(isCompressRow);const otherRows=blockedRows.filter(m2=>!isCompressRow(m2));if(compressRows.length>0){const cTokens=compressRows.reduce((s3,m2)=>s3+m2.tokens,0);const callIds=new Set;for(const m2 of compressRows)if(m2.toolCallId)callIds.add(m2.toolCallId);const exchangeCount=callIds.size>0?callIds.size:compressRows.length;let detail=" \u2014 pinned compress receipts";if(config&&original){const agedAll=collectAgedCompressCallIds(original,config);const aged=[...callIds].filter(id=>agedAll.has(id)).length;const newest=exchangeCount-aged;detail=" \u2014 pinned compress receipts: "+(newest>0?`${newest} newest = working memory; `:"")+(aged>0?`the ${aged} older exchange(s) are consumed by any fold that spans their position (cite the refs on either side)`:`all ${exchangeCount} are protected working memory (newest ${COMPRESS_EXCHANGE_KEEP_RECENT} stay pinned)`)}lines.push(` compress: ${exchangeCount} exchange(s), ${formatTokens2(cTokens)}${detail}`)}if(otherRows.length>0){const oTokens=otherRows.reduce((s3,m2)=>s3+m2.tokens,0);lines.push(` other: ${otherRows.length} msg(s), ${formatTokens2(oTokens)} \u2014 hard protection (unrecoverable media / protectedTools)`)}}return lines.join("\n")}function renderMessageDrilldown(visible,toolFilter,sort,limit,blockedInfo){let filtered=visible;if(toolFilter)filtered=filtered.filter(m2=>m2.tool===toolFilter);if(sort==="time")filtered.sort((a,b2)=>a.index-b2.index);else if(sort==="tool")filtered.sort((a,b2)=>a.tool.localeCompare(b2.tool)||b2.tokens-a.tokens);else filtered.sort((a,b2)=>b2.tokens-a.tokens);const totalTokens=filtered.reduce((s3,m2)=>s3+m2.tokens,0);const allTokens=visible.reduce((s3,m2)=>s3+m2.tokens,0);const header2=toolFilter?`UNCOMPRESSED \u2014 ${toolFilter}: ${formatTokens2(totalTokens)} | ${filtered.length} msgs | ${pct(totalTokens,allTokens)}% of visible`:`UNCOMPRESSED \u2014 ${formatTokens2(totalTokens)} | ${filtered.length} msgs`;const lines=[header2,`Sorted by ${sort}`,""];const shown=filtered.slice(0,limit);for(const message of shown){let suffix="";if(message.ref===BLOCKED_REF){if(blockedInfo?.isCompress(message.tool)){suffix=message.toolCallId&&blockedInfo.agedIds.has(message.toolCallId)?" \xB7 aged \u2014 folds when a range spans it":" \xB7 newest \u2014 working memory"}else if(message.tool!=="text"){suffix=" \xB7 protected"}}lines.push(` ${message.ref===BLOCKED_REF?"(unrefed)":message.ref} (${formatTokens2(message.tokens)}) ${message.tool}${suffix}`)}if(filtered.length>shown.length){lines.push("");lines.push(`${shown.length} of ${filtered.length} shown.`)}return lines.join("\n")}function renderCompressedDrilldown(blocks,state8,sort,limit,countTokens,meta){let sorted=[...blocks];if(sort==="time")sorted.sort((a,b2)=>a.createdAt-b2.createdAt);else if(sort==="age")sorted.sort((a,b2)=>b2.survivedCount-a.survivedCount);else sorted.sort((a,b2)=>effectiveCompressedTokens(b2,state8,countTokens)-effectiveCompressedTokens(a,state8,countTokens)||b2.createdAt-a.createdAt);const totalSummary=sorted.reduce((s3,b2)=>s3+summaryTokensOf(b2,countTokens),0);const totalEffective=sorted.reduce((s3,b2)=>s3+effectiveCompressedTokens(b2,state8,countTokens),0);const lines=[];const surface=surfaceLine(meta);if(surface){lines.push(surface);lines.push("")}lines.push(`COMPRESSED \u2014 ${sorted.length} blocks | ${formatTokens2(totalEffective)} original \u2192 ${formatTokens2(totalSummary)} summary`);const breakdown=tierBreakdown(sorted,countTokens);if(breakdown)lines.push(`Tier usage: ${breakdown}`);lines.push("");const shown=sorted.slice(0,limit);for(const block of shown){const nested=block.directBlockIds.length>0?` nested=[${block.directBlockIds.join(",")}]`:"";const topic=block.topic??"(no topic)";const eff=effectiveCompressedTokens(block,state8,countTokens);const retiredMark=block.retired?", retired":"";lines.push(` ${block.blockId} (${tierLabel(block)}${retiredMark}) ${formatTokens2(eff)}\u2192${formatTokens2(summaryTokensOf(block,countTokens))} ${block.effectiveMessageIds.length} msgs age=${block.survivedCount} ${block.generation}${nested}`);lines.push(` "${topic}"`)}if(sorted.length>shown.length){lines.push("");lines.push(`${shown.length} of ${sorted.length} shown.`)}return lines.join("\n")}function decomposeSample(prev,cur,pendingFolds){const missed=Math.max(0,cur.input-cur.cached);const growth=prev?Math.max(0,cur.input-prev.input):0;const newContent=Math.min(missed,growth);const remainder=missed-newContent;let compRepay=0;let foldIndex=null;if(remainder>0&&pendingFolds.length>0){let bestX=Infinity;let owner=-1;for(let i=0;i<pendingFolds.length;i++){const f2=pendingFolds[i];const x=f2.firstFoldStartTokens??f2.viewAfter??0;if(x<bestX){bestX=x;owner=i}}const structuralExcess=Math.max(0,cur.input-bestX-newContent);compRepay=Math.min(remainder,structuralExcess);if(compRepay>0)foldIndex=owner}return{missed,newContent,compRepay,ttlRepay:remainder-compRepay,foldIndex}}function computeFoldEconomics(f2,price){const w2=price?.w??1;const r=price?.r??.1;const q2=price?.q??4;const netTokenDelta=f2.T+f2.sigma-f2.S;const savingPerTurn=f2.S-f2.sigma;const oneTimeCostUnits=(w2-r)*f2.T+q2*f2.sigma-r*f2.S;const perTurnSavingUnits=savingPerTurn*r;const breakevenTurns=perTurnSavingUnits>0?Math.max(0,oneTimeCostUnits)/perTurnSavingUnits:null;const paidBack=breakevenTurns!==null?f2.requestsAfter>=breakevenTurns:null;const cadenceOk=f2.turnsToNextFold!==null&&breakevenTurns!==null?f2.turnsToNextFold>=breakevenTurns:null;return{seq:f2.seq,at:f2.at,S:f2.S,sigma:f2.sigma,Vprime:f2.Vprime??null,hPct:f2.hPct,T:f2.T,requestsAfter:f2.requestsAfter,savedSoFar:Math.max(0,savingPerTurn)*f2.requestsAfter,turnsToNextFold:f2.turnsToNextFold,netTokenDelta,oneTimeCostUnits:round1(oneTimeCostUnits),perTurnSavingUnits:round1(perTurnSavingUnits),breakevenTurns,paidBack,cadenceOk}}function summarizeFoldEconomics(foldEcon){const econ={folds:foldEcon.length,grossSaved:foldEcon.reduce((n,e)=>n+e.savedSoFar,0),repayCost:foldEcon.reduce((n,e)=>n+e.T,0),summaryCost:foldEcon.reduce((n,e)=>n+e.sigma,0),netTokens:0,paidBackCount:0,notPaidBackCount:0,unobservedCount:0};econ.netTokens=econ.grossSaved-econ.repayCost-econ.summaryCost;for(const e of foldEcon){if(e.paidBack===true)econ.paidBackCount++;else if(e.paidBack===false)econ.notPaidBackCount++;else econ.unobservedCount++}return econ}function round1(n){return Math.round(n*10)/10}function fmtTok(n){const v2=Math.round(n);return v2>=1e6?`${(v2/1e6).toFixed(2)}M`:v2>=1e4?`${(v2/1e3).toFixed(1)}K`:String(v2)}function fmtTime(at2){const d=new Date(at2);const p2=x=>String(x).padStart(2,"0");return`${p2(d.getHours())}:${p2(d.getMinutes())}:${p2(d.getSeconds())}`}function hitVerdict(pct2){if(pct2>=HIT_HEALTHY_PCT)return"HEALTHY";if(pct2>=HIT_WATCH_PCT)return"WATCH";return"INVESTIGATE"}function medianHitPct(lines){if(lines.length===0)return null;const xs2=lines.map(l=>l.hitPct).sort((a,b2)=>a-b2);return xs2[Math.floor(xs2.length/2)]??null}function fmtIdleGap(ms2){if(ms2<9e4)return`${Math.max(1,Math.round(ms2/1e3))}s`;if(ms2<90*6e4)return`${Math.round(ms2/6e4)}m`;if(ms2<36*36e5)return`${(ms2/36e5).toFixed(1)}h`;return`${(ms2/864e5).toFixed(1)}d`}function foldVerdict(f2){return f2.paidBack===null?"?":f2.paidBack?"PAID BACK":"NOT PAID BACK"}function formatCacheReportFull(report){const t=report.totals;const out=[];out.push("GRAND LEDGER");out.push(` total input ${fmtTok(t.input)} tok`);out.push(` total cached ${fmtTok(t.cached)} tok (hit ${t.hitPct.toFixed(1)}%)`);out.push(` total output ${fmtTok(t.output)} tok`);out.push(` miss breakdown (input \u2212 cached = ${fmtTok(Math.max(0,t.input-t.cached))} tok):`);out.push(` new content ${fmtTok(t.newContent)} tok (fresh append \u2014 not an invalidation)`);out.push(` compress re-pay ${fmtTok(t.compRepay)} tok (caused by folds)`);out.push(` upstream-ttl-or-client-rewrite (unattributed) ${fmtTok(t.ttlRepay)} tok (stable-prefix misses: upstream TTL expiry / eviction or client-side wire rewrite \u2014 kernel cannot distinguish)`);out.push(` identity check ${t.balanced?"OK":"BROKEN"} \u2014 ${fmtTok(t.input)} = ${fmtTok(t.cached)} + ${fmtTok(t.newContent)} + ${fmtTok(t.compRepay)} + ${fmtTok(t.ttlRepay)} (residual ${t.residual})`);const e=report.economics;if(e.folds>0){const p2=report.profile;out.push("");out.push(`FOLD ECONOMICS (${e.folds} folds @ w=${p2.w} r=${p2.r} q=${p2.q})`);out.push(` gross saved ${fmtTok(e.grossSaved)} tok \xB7 repay cost ${fmtTok(e.repayCost)} tok \xB7 summary cost ${fmtTok(e.summaryCost)} tok \u2192 net ${e.netTokens>=0?"+":""}${fmtTok(e.netTokens)} tok`);out.push(` verdict: ${e.paidBackCount} paid back, ${e.notPaidBackCount} not paid back, ${e.unobservedCount} unobserved`);for(const f2 of report.folds){const nstar=f2.breakevenTurns===null?"n/a":f2.breakevenTurns.toFixed(2);const k2=f2.turnsToNextFold===null?"\u2014":String(f2.turnsToNextFold);const verdict=f2.paidBack===null?"?":f2.paidBack?"PAID BACK":"NOT PAID BACK";const h=f2.hPct===null?"n/a":`${f2.hPct.toFixed(1)}%`;out.push(` #${f2.seq} ${fmtTime(f2.at)} S=${fmtTok(f2.S)} \u03C3=${fmtTok(f2.sigma)} h=${h} T=${fmtTok(f2.T)} \u0394C\u2081=${fmtTok(f2.oneTimeCostUnits)} \u0394s=${fmtTok(f2.perTurnSavingUnits)}/turn n*=${nstar} k=${k2} \u2192 ${verdict}`)}}if(report.lines.length>0){out.push("");if(report.linesOmitted>0)out.push(`LINE ITEMS (last ${report.lines.length} of ${report.lines.length+report.linesOmitted}):`);else out.push("LINE ITEMS:");out.push(" # time input cached hit% new comp ttl fold");for(const l of report.lines){const fold=l.foldSeq!==null?`#${l.foldSeq}`:"";out.push(` ${String(l.seq).padStart(4)} ${fmtTime(l.at)} ${fmtTok(l.input).padStart(7)} ${fmtTok(l.cached).padStart(7)} ${l.hitPct.toFixed(1).padStart(5)}% ${fmtTok(l.newContent).padStart(6)} ${fmtTok(l.compRepay).padStart(6)} ${fmtTok(l.ttlRepay).padStart(6)} ${fold}`)}}return out.join("\n")}function formatCacheReportSummary(report){const t=report.totals;const out=[];out.push("GRAND LEDGER");out.push(` total input ${fmtTok(t.input)} tok`);out.push(` total cached ${fmtTok(t.cached)} tok (hit ${t.hitPct.toFixed(1)}% \u2192 ${hitVerdict(t.hitPct)})`);out.push(` total output ${fmtTok(t.output)} tok`);out.push(` miss breakdown (input \u2212 cached = ${fmtTok(Math.max(0,t.input-t.cached))} tok):`);const avgNew=t.requests>0?t.newContent/t.requests:0;out.push(` new content ${fmtTok(t.newContent)} tok (~${fmtTok(avgNew)}/req fresh append \u2014 not an invalidation)`);out.push(` compress re-pay ${fmtTok(t.compRepay)} tok (${report.economics.folds} folds \u2014 re-billed prefix)`);const spikeIdx=[];report.lines.forEach((l,i)=>{if(l.ttlRepay>=TTL_SPIKE_TOK)spikeIdx.push(i)});const spikes=[...spikeIdx].sort((a,b2)=>(report.lines[b2]?.ttlRepay??0)-(report.lines[a]?.ttlRepay??0)).slice(0,SUMMARY_FOLD_TOPS).sort((a,b2)=>a-b2);const spikeText=spikes.map(i=>{const l=report.lines[i];if(!l)return"";let idle="";const prev=report.lines[i-1];if(prev&&l.at>prev.at)idle=`, idle ${fmtIdleGap(l.at-prev.at)}`;return`#${l.seq} ${fmtTok(l.ttlRepay)}${idle}`}).join(" \xB7 ");out.push(` upstream-ttl-or-client-rewrite (unattributed) ${fmtTok(t.ttlRepay)} tok (stable-prefix misses: upstream TTL expiry / eviction or client-side wire rewrite \u2014 kernel cannot distinguish${spikeText?`; top spikes: ${spikeText}`:""})`);out.push(` identity check ${t.balanced?"OK":"BROKEN"} \u2014 ${fmtTok(t.input)} = ${fmtTok(t.cached)} + ${fmtTok(t.newContent)} + ${fmtTok(t.compRepay)} + ${fmtTok(t.ttlRepay)} (residual ${t.residual})`);const e=report.economics;if(e.folds>0){const p2=report.profile;out.push("");out.push(`FOLD ECONOMICS (${e.folds} folds @ w=${p2.w} r=${p2.r} q=${p2.q})`);out.push(` gross saved ${fmtTok(e.grossSaved)} tok \xB7 repay cost ${fmtTok(e.repayCost)} tok \xB7 summary cost ${fmtTok(e.summaryCost)} tok \u2192 net ${e.netTokens>=0?"+":""}${fmtTok(e.netTokens)} tok`);out.push(` verdict: ${e.paidBackCount} PAID BACK / ${e.notPaidBackCount} NOT PAID BACK / ${e.unobservedCount} unobserved`);if(e.notPaidBackCount>0)out.push(` NOT PAID BACK = post-fold requests so far have not reached n* (early fold or session ended before payback \u2014 one-time cost, not data loss)`);if(report.folds.length<=SUMMARY_FOLD_TOPS*2){for(const f2 of report.folds){const nstar=f2.breakevenTurns===null?"n/a":f2.breakevenTurns.toFixed(2);const k2=f2.turnsToNextFold===null?"\u2014":String(f2.turnsToNextFold);const h=f2.hPct===null?"n/a":`${f2.hPct.toFixed(1)}%`;out.push(` #${f2.seq} ${fmtTime(f2.at)} S=${fmtTok(f2.S)} \u03C3=${fmtTok(f2.sigma)} h=${h} T=${fmtTok(f2.T)} \u0394C\u2081=${fmtTok(f2.oneTimeCostUnits)} \u0394s=${fmtTok(f2.perTurnSavingUnits)}/turn n*=${nstar} k=${k2} \u2192 ${foldVerdict(f2)}`)}}else{const largest=[...report.folds].sort((a,b2)=>b2.S-a.S).slice(0,SUMMARY_FOLD_TOPS);const worst=[...report.folds].sort((a,b2)=>b2.oneTimeCostUnits-a.oneTimeCostUnits).slice(0,SUMMARY_FOLD_TOPS);out.push(` largest folds: ${largest.map(f2=>`#${f2.seq} S=${fmtTok(f2.S)} ${foldVerdict(f2)}`).join(" \xB7 ")}`);out.push(` worst one-time: ${worst.map(f2=>`#${f2.seq} \u0394C\u2081=${fmtTok(f2.oneTimeCostUnits)} (${foldVerdict(f2)}${f2.turnsToNextFold!==null?`, k=${f2.turnsToNextFold}`:""})`).join(" \xB7 ")}`);const shown=new Set([...largest,...worst]);if(report.folds.length>shown.size)out.push(` \u2192 ${report.folds.length-shown.size} more folds omitted (detail:"full" lists every fold)`)}}if(report.lines.length>0){out.push("");const shownIdx=[];report.lines.forEach((l,i)=>{if(l.hitPct<ANOMALY_HIT_PCT||l.missed>=ANOMALY_MISS_TOK)shownIdx.push(i)});const last=report.lines.length-1;if(!shownIdx.includes(last))shownIdx.push(last);const kept=shownIdx.slice(Math.max(0,shownIdx.length-SUMMARY_ANOMALY_CAP));const anomalies=kept.filter(i=>{const l=report.lines[i];if(!l)return false;return l.hitPct<ANOMALY_HIT_PCT||l.missed>=ANOMALY_MISS_TOK}).length;if(anomalies===0){const med=medianHitPct(report.lines);out.push(`LINE ITEMS \u2014 no anomalies (${report.lines.length} requests, median hit ${med!==null?med.toFixed(1):"n/a"}%${report.linesOmitted>0?`, ${report.linesOmitted} older outside window`:""})`)}else{out.push(`LINE ITEMS (anomalies: hit<${ANOMALY_HIT_PCT}% or miss\u2265${fmtTok(ANOMALY_MISS_TOK)}):`);out.push(" # time input cached hit% new comp ttl fold");for(const i of kept){const l=report.lines[i];if(!l)continue;const fold=l.foldSeq!==null?`#${l.foldSeq}`:"";out.push(` ${String(l.seq).padStart(4)} ${fmtTime(l.at)} ${fmtTok(l.input).padStart(7)} ${fmtTok(l.cached).padStart(7)} ${l.hitPct.toFixed(1).padStart(5)}% ${fmtTok(l.newContent).padStart(6)} ${fmtTok(l.compRepay).padStart(6)} ${fmtTok(l.ttlRepay).padStart(6)} ${fold}`)}const omitted=report.lines.length-kept.length;if(omitted>0){const rest=report.lines.filter((_2,i)=>!kept.includes(i));const med=medianHitPct(rest);out.push(` \u2026 ${omitted} lines omitted (median hit ${med!==null?med.toFixed(1):"n/a"}%${report.linesOmitted>0?`, ${report.linesOmitted} older outside window`:""} \u2014 detail:"full" lists all)`)}}}return out.join("\n")}function formatCacheReport(report,sessionLabel,opts){const t=report.totals;const header2=`ACP CACHE REPORT${sessionLabel?` (${sessionLabel})`:""} \u2014 ${t.requests} requests`;if(opts?.detail==="full"){return[header2,"",formatCacheReportFull(report)].join("\n")}return[header2+` [summary \u2014 detail:"full" for every fold & line]`,"",formatCacheReportSummary(report)].join("\n")}function renderMessage2(m2){const parts=[];switch(m2.contentType){case"text":parts.push(m2.text??"");break;case"tool-call":parts.push(`\`${m2.toolName??"?"}(${m2.toolCallId??""})\` args: ${m2.text??""}`);break;case"tool-result":parts.push(`\`${m2.toolName??"?"}(${m2.toolCallId??""})\` \u2192 ${m2.text??""}`);break;case"reasoning":parts.push(`_reasoning_: ${m2.text??""}`);break}const body=parts.join("\n").trim();return body===""?"_(empty)_":body+"\n"}function renderHandoff(input){const{coreMessages,state:state8,full,meta}=input;const lines=[];lines.push("# billion-context session handoff");lines.push("");lines.push(`- title: ${meta.title??"(untitled)"}`);if(meta.label)lines.push(`- label: ${meta.label}`);lines.push(`- session id: ${meta.sessionId}`);for(const bullet of meta.extraBullets??[])lines.push(bullet);if(meta.contextTokens)lines.push(`- last context tokens: ~${meta.contextTokens}`);lines.push(`- compression blocks: ${state8.blocks.length} (active ${state8.blocks.filter(b2=>b2.active).length})`);lines.push("");const folded=input.folded===true;const view=full||folded?coreMessages:prune(coreMessages,state8,{headSummaryAnchors:true});lines.push(full&&!folded?`## Full conversation (${coreMessages.length} messages)`:folded?`## Conversation (persisted folded snapshot, ${coreMessages.length} messages)`:`## Conversation (folded view as the model saw it, ${coreMessages.length} client messages)`);lines.push("");if(view.length===0){lines.push("No conversation messages to export.");lines.push("")}let lastRole="";for(const m2 of view){if(m2.role!==lastRole){lines.push(`### ${m2.role}`);lines.push("");lastRole=m2.role}lines.push(renderMessage2(m2))}lines.push("");if(full&&folded){for(const b2 of input.blocksFull??[]){lines.push(`## Block ${b2.blockId}${b2.topic?` \u2014 ${b2.topic}`:""}`);lines.push("");lines.push(`### Original messages (${b2.count})`);lines.push("");lines.push(b2.fullText.trim());lines.push("")}}return lines.join("\n")}function listRules(state8){return state8.rules??[]}function resolveRuleLimits(config){return{maxRules:config?.rules?.maxRules??DEFAULT_RULE_LIMITS.maxRules,maxRuleChars:config?.rules?.maxRuleChars??DEFAULT_RULE_LIMITS.maxRuleChars}}function highestRuleNumber(state8){let highest=0;for(const rule of state8.rules??[]){const match=RULE_ID_RE.exec(rule.id);if(match)highest=Math.max(highest,Number(match[1]))}return highest}function addRule(state8,text2,limits={}){const maxRules=limits.maxRules??DEFAULT_RULE_LIMITS.maxRules;const maxRuleChars=limits.maxRuleChars??DEFAULT_RULE_LIMITS.maxRuleChars;const trimmed=(text2??"").trim();if(!trimmed){return{ok:false,error:"rule text is empty \u2014 provide the reminder to record."}}if(trimmed.length>maxRuleChars){return{ok:false,error:`${trimmed.length} chars exceeds the ${maxRuleChars}-char limit \u2014 keep rules short and principle-level.`}}const rules=listRules(state8);const duplicate=rules.find(rule2=>rule2.text===trimmed);if(duplicate){return{ok:false,error:`identical rule already exists (${duplicate.id}) \u2014 no change.`}}if(rules.length>=maxRules){return{ok:false,error:`rule limit reached (${maxRules}) \u2014 remove or clear outdated rules first.`}}const next=Math.max(state8.nextRuleId??1,highestRuleNumber(state8)+1);const rule={id:`rule${next}`,text:trimmed};state8.rules=[...rules,rule];state8.nextRuleId=next+1;return{ok:true,rule}}function removeRule(state8,id){const rules=listRules(state8);const target=rules.find(rule=>rule.id===id.trim());if(!target){return{ok:false,error:`no rule with id "${id.trim()}" \u2014 list current rules first (omit the text argument).`}}state8.rules=rules.filter(rule=>rule.id!==target.id);return{ok:true,rule:target}}function clearRules(state8){const count=listRules(state8).length;state8.rules=[];return{ok:true,count}}function formatRulesList(rules){return rules.map((rule,i)=>`${i+1}. [${rule.id}] ${rule.text}`).join("\n")}function stem(word){let w2=word;if(w2.length<=3)return w2;if(w2.endsWith("ies"))w2=w2.slice(0,-3)+"y";else if(w2.endsWith("ses")||w2.endsWith("xes")||w2.endsWith("zes"))w2=w2.slice(0,-2);else if(w2.endsWith("ches")||w2.endsWith("shes"))w2=w2.slice(0,-2);else if(w2.endsWith("s")&&!w2.endsWith("ss"))w2=w2.slice(0,-1);if(w2.endsWith("ing")&&w2.length>5)w2=w2.slice(0,-3);if(w2.endsWith("ed")&&w2.length>4)w2=w2.slice(0,-2);if(w2.endsWith("ation")&&w2.length>6)w2=w2.slice(0,-3);else if(w2.endsWith("tion")&&w2.length>5)w2=w2.slice(0,-4)+"t";else if(w2.endsWith("ion")&&w2.length>4)w2=w2.slice(0,-3);if(w2.endsWith("ment")&&w2.length>6)w2=w2.slice(0,-4);if(w2.endsWith("ness")&&w2.length>6)w2=w2.slice(0,-4);if(w2.endsWith("ly")&&w2.length>4)w2=w2.slice(0,-2);return w2}function cjkRunTokens(segs){const words=segs.filter(w2=>w2.length>=2);if(words.length>0)return words;const run=segs.join("");const out=[];for(let i=0;i<run.length-1;i++)out.push(run.slice(i,i+2));for(const ch of run)out.push(ch);return out}function tokenize(text2,opts={}){const lower=text2.toLowerCase();const tokens=[];const latin=lower.match(LATIN_WORD)??[];for(let w2 of latin){if(w2.length>=2){if(opts.stem)w2=stem(w2);tokens.push(w2)}}if(!CJK.test(lower))return tokens;const runSegs=[];let cur=null;for(const s3 of cjkSegmenter.segment(lower)){const t=s3.segment;if(t.length===0)continue;if(CJK.test(t)){(cur??=[]).push(t)}else if(cur){runSegs.push(cur);cur=null}}if(cur)runSegs.push(cur);for(const segs of runSegs){tokens.push(...cjkRunTokens(segs))}return tokens}function charBigrams(text2){const grams=[];for(let i=0;i<text2.length-1;i++){const pair=text2.slice(i,i+2);if(pair.trim().length===pair.length)grams.push(pair)}return grams}function tfMap(text2,stem2){const m2=new Map;for(const t of tokenize(text2,{stem:stem2}))m2.set(t,(m2.get(t)??0)+1);return m2}function build(text2){const tf=tfMap(text2,true);let len=0;for(const v2 of tf.values())len+=v2;const lower=text2.toLowerCase();return{tf,len,lower,grams:new Set(charBigrams(lower))}}function docFeatures(text2){const hit=cache.get(text2);if(hit){cache.delete(text2);cache.set(text2,hit);return hit}const f2=build(text2);if(text2.length>0&&text2.length<=capChars){while(cachedChars+text2.length>capChars&&cache.size>0){const k2=cache.keys().next().value;cachedChars-=k2.length;cache.delete(k2)}cache.set(text2,f2);cachedChars+=text2.length}return f2}function countOccurrences2(haystack,needle){if(!needle)return 0;return haystack.split(needle).length-1}function registerSearchAlgorithm(algo){registry2.set(algo.name,algo)}function getSearchAlgorithm(name2){return registry2.get(name2)}function blockDocs(state8){return state8.blocks.map(b2=>({kind:"block",ref:b2.blockId,text:`${b2.topic??""} ${b2.summary??""}`,title:b2.topic??b2.blockId,blockId:b2.blockId,tier:b2.tier??1,tokens:b2.compressedTokens}))}function applyRoleWeight(scored,docs,rw){if(docs.length===0)return scored;const docByRef=new Map(docs.map(d=>[d.ref,d]));return scored.map(s3=>{const doc=docByRef.get(s3.ref);if(!doc)return s3;const w2=doc.kind==="message"?doc.role==="user"?rw.user:doc.role==="assistant"?rw.assistant:rw.tool:rw.block;return{ref:s3.ref,score:s3.score*w2}})}function runSearch(docs,query,options){const limit=options.limit??10;const previewLength=options.previewLength??200;const minScore=options.minScore??.01;const algoName=options.algorithm??DEFAULT_ALGORITHM;const rw={...DEFAULT_ROLE_WEIGHTS,...options.roleWeights};const algo=getSearchAlgorithm(algoName);if(!algo)return[];if(docs.length===0)return[];const scoredOrPromise=algo.score(docs,query);const buildResults=weighted=>{const byRef=new Map(docs.map(d=>[d.ref,d]));return weighted.map(s3=>{const doc=byRef.get(s3.ref);if(!doc)return null;return{kind:doc.kind,ref:doc.ref,blockId:doc.blockId,tier:doc.tier??1,score:s3.score,title:doc.title,preview:makePreview(doc.text,query,previewLength),role:doc.role,tokens:doc.tokens}}).filter(r=>r!==null&&r.score>=minScore).sort((a,b2)=>b2.score-a.score).slice(0,limit)};if(scoredOrPromise instanceof Promise){return scoredOrPromise.then(raw=>buildResults(applyRoleWeight(raw,docs,rw)))}return buildResults(applyRoleWeight(scoredOrPromise,docs,rw))}function searchBlocks(docs,query,options={}){const result=runSearch(docs,query,options);if(result instanceof Promise){throw new Error(`searchBlocks: algorithm "${options.algorithm??DEFAULT_ALGORITHM}" is async (e.g. semantic). Use searchBlocksAsync() instead.`)}return result}function makePreview(text2,query,len){if(!text2)return"";const terms=query.toLowerCase().trim().split(/\s+/).filter(t=>t.length>1);if(terms.length===0)return clampPrefix(text2,len);const lower=text2.toLowerCase();let hitIdx=-1;for(const term of terms){const idx=lower.indexOf(term);if(idx>=0){hitIdx=idx;break}}if(hitIdx<0)return clampPrefix(text2,len);const half=Math.max(0,Math.floor(len/2)-10);const start=Math.max(0,hitIdx-half);const end=Math.min(text2.length,start+len);const prefix=start>0?"\u2026":"";const suffix=end<text2.length?"\u2026":"";return prefix+clampWindow(text2,start,end).trim()+suffix}function classifyTurn(messages){if(messages.length===0)return"unknown";const last=messages[messages.length-1];if(!last||last.role!=="user")return"unknown";if(typeof last.text==="string")return last.text.trim()?"new_user_ask":"unknown";const blocks=last.blocks;if(!Array.isArray(blocks)||blocks.length===0)return"unknown";let sawToolResult=false;let sawError=false;for(const b2 of blocks){if(!b2)return"unknown";switch(b2.kind){case"tool_result":sawToolResult=true;if(b2.isError===true)sawError=true;break;case"text":case"image":case"document":return"new_user_ask";default:return"unknown"}}if(sawError)return"error_continuation";if(sawToolResult)return"mechanical_continuation";return"unknown"}function verbosityDirective(level){if(!Number.isInteger(level))return null;return VERBOSITY_LEVELS[level]??null}function renderSteeringBlock(level,sentinel=DEFAULT_STEERING_SENTINEL){const text2=verbosityDirective(level);if(text2===null)return null;return`${sentinel}
|
|
276
276
|
${text2}
|
|
277
277
|
</${sentinel.slice(1)}`}function clampEffortToFloor(current,floor="low"){if(typeof current!=="string")return null;const ci2=EFFORT_LADDER.indexOf(current);if(ci2===-1)return null;const fi2=EFFORT_LADDER.indexOf(floor);return ci2>fi2?floor:null}function resolveVerbosityLevel(v2){if(typeof v2==="number"&&Number.isInteger(v2)&&v2>=MIN_VERBOSITY_LEVEL&&v2<=MAX_VERBOSITY_LEVEL){return{level:v2}}const level=DEFAULT_OUTPUT_STEERING_CONFIG.verbosityLevel;if(v2===void 0)return{level};return{level,warning:`[config] outputSteering.verbosityLevel must be an integer ${MIN_VERBOSITY_LEVEL}-${MAX_VERBOSITY_LEVEL}; got ${JSON.stringify(v2)} \u2014 falling back to ${level}`}}function resolveOutputSteeringConfig(v2){if(!v2||typeof v2!=="object"||Array.isArray(v2)){return{config:DEFAULT_OUTPUT_STEERING_CONFIG,warnings:[]}}const obj=v2;const lvl=resolveVerbosityLevel(obj.verbosityLevel);return{config:{enabled:obj.enabled===true,verbosityLevel:lvl.level,effortRouting:obj.effortRouting!==false},warnings:lvl.warning?[lvl.warning]:[]}}function decideOutputSteering(messages,config=DEFAULT_OUTPUT_STEERING_CONFIG){const turnKind=classifyTurn(messages);return{turnKind,verbosityLevel:config.enabled?config.verbosityLevel:0,lowerEffort:config.enabled&&config.effortRouting&&turnKind==="mechanical_continuation"}}var CONTENT_HASH_ROOT,COMPRESS_TOOL_NAME,DECOMPRESS_TOOL_NAME,SEARCH_CONTEXT_TOOL_NAME,ACP_STATUS_TOOL_NAME,ACP_CACHE_TOOL_NAME,ACP_RETIRE_TOOL_NAME,ACP_RESTORE_TOOL_NAME,ACP_REWRITE_TOOL_NAME,ABSORB_TOOL_NAME,ACP_TEXT_OPEN,ACP_TEXT_CLOSE,ACP_STATUS_OPEN,ACP_STATUS_CLOSE,ACP_SEARCH_OPEN,ACP_SEARCH_CLOSE,ACP_DECOMPRESS_OPEN,ACP_DECOMPRESS_CLOSE,COMPRESS_PARAMETERS,COMPRESS_TOOL,COMPRESS_TOOL_OPENAI,FUNCTION_ACP_TAGS_DEFAULT,FUNCTION_ACP_TAGS_TIMESTAMPED,TEXT_ACP_TAGS_DEFAULT,FUNCTION_PROMPT_SECTIONS,TEXT_PROMPT_SECTIONS,HYBRID_PROMPT_SECTIONS,DECOMPRESS_TOOL_OPENAI,SEARCH_CONTEXT_TOOL_OPENAI,ACP_STATUS_PARAMETERS,ACP_STATUS_TOOL_OPENAI,ACP_CACHE_TOOL_DESCRIPTION,ACP_CACHE_TOOL_OPENAI,BLOCK_IDS_PARAMETERS,ACP_RETIRE_DESCRIPTION,ACP_RESTORE_DESCRIPTION,ACP_REWRITE_DESCRIPTION,ACP_REWRITE_PARAMETERS,ACP_RETIRE_TOOL_OPENAI,ACP_RESTORE_TOOL_OPENAI,ACP_REWRITE_TOOL_OPENAI,ACP_TOOLS_OPENAI,DECOMPRESS_TOOL,SEARCH_CONTEXT_TOOL,ACP_STATUS_TOOL,ACP_CACHE_TOOL,ACP_RETIRE_TOOL,ACP_RESTORE_TOOL,ACP_REWRITE_TOOL,ACP_TOOLS_ANTHROPIC,COMPRESS_TOOL_RESPONSES,DECOMPRESS_TOOL_RESPONSES,SEARCH_CONTEXT_TOOL_RESPONSES,ACP_STATUS_TOOL_RESPONSES,ACP_CACHE_TOOL_RESPONSES,ACP_RETIRE_TOOL_RESPONSES,ACP_RESTORE_TOOL_RESPONSES,ACP_REWRITE_TOOL_RESPONSES,ACP_TOOLS_RESPONSES,ACP_READONLY_TOOLS_RESPONSES,ACP_TOOL_NAMES,BLOCK_OP_TOOL_NAMES,ACP_MUTATING_TOOLS,ABSORB_TOOL_DESCRIPTION,ABSORB_PARAMETERS,ABSORB_TOOL,ABSORB_TOOL_OPENAI,COMPRESS_TOOL_GOOGLE,DECOMPRESS_TOOL_GOOGLE,SEARCH_CONTEXT_TOOL_GOOGLE,ACP_STATUS_TOOL_GOOGLE,ACP_CACHE_TOOL_GOOGLE,ACP_RETIRE_TOOL_GOOGLE,ACP_RESTORE_TOOL_GOOGLE,ACP_REWRITE_TOOL_GOOGLE,ACP_TOOLS_GOOGLE,ABSORB_TOOL_GOOGLE,RETRIEVE_TOOL_NAME,RETRIEVE_TOOL_NAME2,RETRIEVE_INLINE_TOKENS_DEFAULT,DEFAULT_CCR_CONFIG,STORED_PLACEHOLDER_MARKER,RETRIEVED_ID_PREFIX,KIND_LABELS,COMMAND_FIELDS,LEADING_TAG_RE,CANONICAL_REF,PLACEHOLDER_LINE1_RE,PLACEHOLDER_LINE2_RE,RETRIEVED_DATA_NOTICE,RETRIEVED_FILE_NOTICE,RETRIEVED_CLOSE_TAG_RE,ccrStoreNode,MESSAGE_REF_PATTERN,BLOCK_REF_PATTERN,BoundaryNotFoundError,TRUNCATION_MARKER,DEFAULTS,REF_PAIR_IN_LINE,SINGLE_REF_IN_LINE,UNRECOGNIZED_REF_SEP_RE,LINE_ENTRY_REFS_RE,WHITESPACE_RE,SUMMARY_STUB_CHARS,ABSORB_PROMPT_MARKER,DEFAULT_ABSORB_CONFIG,NO_PROTECTED_CALLS,DEFAULT_CRUSH_CONFIG,MAX_INPUT_CHARS,MAX_DEPTH,MAX_FOLDS,RUN_MIN,HOIST_MIN,CODE_KEEP_RATIO,CRUSH_KEY,LOG_MIN_LINES,LOG_MAX_TOTAL_LINES,LOG_MAX_ERRORS,LOG_ERROR_CONTEXT,LOG_MAX_WARNINGS,LOG_MAX_STACK_TRACES,LOG_STACK_MAX_LINES,LOG_TRACE_HEAD_FRAMES,LOG_TRACE_APP_FRAMES,LOG_CLASSIFIED_GATE,LOG_SUMMARY_GATE,LEVEL_PATTERNS,RUNTIME_FRAME_PREFIXES,RUNTIME_FRAME_MARKERS,LOG_FORMAT_TABLE,jsonFoldPlugin,codeTrimPlugin,logSelectPlugin,builtInPlugins,crushRegistry,preTransformSnapshotNode,viewLatchNode,registry,M_REF,LT,GT,TAG_OPEN,TAG_CLOSE,renderRefsNode,SCREEN_DROP_WARN_BUDGET,SCREEN_DROP_WARN_STRIDE,screenDropWarnCount,MAX_TRUNCATE_LATCH,STALL_HARVEST_RATIO,reconcileLiveIdsNode,assignRefsNode,syncBlocksNode,pruneNode,absorbHideNode,absorbPromptNode,crushNode,filterNode,hideCompressCallsNode,recommendNode,nudgeNode,emergencyTruncateNode,PROMPT_RULE_KEYS,COMPRESS_SECTION_KEYS,NUDGE_SECTION_KEYS,defaultPack,LEAN_TOOL_PROMPTS,LEAN_HOW_TO_COMPRESS,TIMELINE_RULE_LINE,LEAN_TIMELINE_ANCHOR,leanWithTimeline,LEAN_HOW_TO_COMPRESS_TIMESTAMPED,LEAN_PROMPT_SECTIONS,leanPack,BUILTIN_REGISTRY,builtinSource,FOLD_CLAIM_WARM_HIT_PCT,FOLD_CLAIM_COLD_ROUNDS,HIT_HEALTHY_PCT,HIT_WATCH_PCT,ANOMALY_HIT_PCT,ANOMALY_MISS_TOK,TTL_SPIKE_TOK,SUMMARY_FOLD_TOPS,SUMMARY_ANOMALY_CAP,RULE_TOOL_NAME,DEFAULT_RULE_LIMITS,RULES_USAGE_PROMPT,RULE_ID_RE,CJK,LATIN_WORD,cjkSegmenter,DEFAULT_CAP_CHARS,capChars,cache,cachedChars,substringAlgorithm,bm25Algorithm,fuzzyAlgorithm,W_BM25,W_FUZZY,hybridAlgorithm,registry2,DEFAULT_ROLE_WEIGHTS,DEFAULT_ALGORITHM,MIN_VERBOSITY_LEVEL,MAX_VERBOSITY_LEVEL,DEFAULT_VERBOSITY_LEVEL,VERBOSITY_LEVELS,DEFAULT_STEERING_SENTINEL,EFFORT_LADDER,DEFAULT_OUTPUT_STEERING_CONFIG;var init_dist=__esm({"kernel/dist/index.js"(){"use strict";init_chunk_H5KBAFEH();init_chunk_AMMGW3CR();init_chunk_6ECDTFU5();CONTENT_HASH_ROOT=/^h_([0-9a-f]{16})(?:_\d+)?(?:#.*)?$/;COMPRESS_TOOL_NAME="compress";DECOMPRESS_TOOL_NAME="decompress";SEARCH_CONTEXT_TOOL_NAME="search_context";ACP_STATUS_TOOL_NAME="acp_status";ACP_CACHE_TOOL_NAME="acp_cache";ACP_RETIRE_TOOL_NAME="acp_retire";ACP_RESTORE_TOOL_NAME="acp_restore";ACP_REWRITE_TOOL_NAME="acp_rewrite";ABSORB_TOOL_NAME="absorb";ACP_TEXT_OPEN="<acp_compress>";ACP_TEXT_CLOSE="</acp_compress>";ACP_STATUS_OPEN="<acp_status>";ACP_STATUS_CLOSE="</acp_status>";ACP_SEARCH_OPEN="<acp_search>";ACP_SEARCH_CLOSE="</acp_search>";ACP_DECOMPRESS_OPEN="<acp_decompress>";ACP_DECOMPRESS_CLOSE="</acp_decompress>";COMPRESS_PARAMETERS={type:"object",properties:{content:{type:"string",description:"ONE plain string holding ALL ranges to compress \u2014 each block starts with its 'm00150\u2013m00220 optional topic' header line followed by that block's summary markdown. Batch multiple ranges into ONE call \u2014 do not split into one call per range."}}};COMPRESS_TOOL={name:COMPRESS_TOOL_NAME,description:"Replace consumed conversation ranges with self-contained summaries you write, identified by their refs. content = ONE plain string holding ALL ranges \u2014 each block starts with its 'm00150\u2013m00220 optional topic' header line followed by that block's summary. Batch multiple ranges into ONE call \u2014 do not split into one call per range. Use when content is genuinely consumed.",input_schema:COMPRESS_PARAMETERS};COMPRESS_TOOL_OPENAI={type:"function",function:{name:COMPRESS_TOOL_NAME,description:COMPRESS_TOOL.description,parameters:COMPRESS_PARAMETERS}};FUNCTION_ACP_TAGS_DEFAULT=`ACP TAGS
|
|
278
278
|
|