billion-context 0.1.210 → 0.1.211
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/omp.js +1 -1
- package/dist/agent/opencode-native.js +11 -11
- package/dist/agent/opencode.js +1 -1
- package/dist/agent/pi-native.js +11 -11
- package/dist/agent/pi.js +1 -1
- package/dist/build-info.json +1 -1
- package/dist/claude-mcp-entry.js +1 -1
- package/dist/claude-native-bootstrap.js +1 -1
- package/dist/index.js +11 -11
- package/dist/kimi/bootstrap-hook.js +1 -1
- package/dist/kimi/native-mcp.js +1 -1
- package/dist/zcode/bootstrap-hook.js +1 -1
- package/dist/zcode/mcp-entry.js +1 -1
- package/package.json +1 -1
- package/website/blog/posts/2026-11-01_frequent-compression.md +13 -0
- package/website/blog/posts/2026-11-01_frequent-compression.zh.md +12 -0
|
@@ -134,7 +134,7 @@ Read the exported file with the file-read tool (page through it with offset/limi
|
|
|
134
134
|
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)}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,state7){const records=state7.absorbed??[];if(records.length===0)return messages;const hidden=new Set;for(const record4 of records){if(record4.callMessageId)hidden.add(record4.callMessageId);if(record4.resultMessageId)hidden.add(record4.resultMessageId)}return messages.filter(msg=>!hidden.has(msg.id))}function appendAbsorbPrompts(messages,state7,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 record4 of state7.absorbed??[]){if(record4.resultMessageId)absorbedIds.add(record4.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(state7.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 record4={toolCallId:target.toolCallId,callMessageId:call?.id??"",resultMessageId:target.id,...input.absorbCallId?{absorbCallId:input.absorbCallId}:{},summary,tokensReclaimed:tokens,createdAt:Date.now()};const state7={...input.state,absorbed:[...input.state.absorbed??[],record4],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:state7,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,stats,cache22){if(depth>MAX_DEPTH||stats.folds>=MAX_FOLDS)return v2;if(Array.isArray(v2))return compactArray(v2,depth,stats,cache22);if(isPlainObject(v2)){let changed=false;const out={};for(const[k2,val]of Object.entries(v2)){const nv=compactValue(val,depth+1,stats,cache22);out[k2]=nv;if(nv!==val)changed=true}return changed?out:v2}return v2}function compactArray(arr,depth,stats,cache22){const n=arr.length;if(n<RUN_MIN&&n<HOIST_MIN)return arr.map(e=>compactValue(e,depth+1,stats,cache22));if(stats.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}}stats.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 stats={folds:0};const out=compactValue(parsed,0,stats,cache22);if(stats.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 state7="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(state7==="triple"){const close=findTripleClose(line,quote);if(close===-1){if(isDocstring)pending++;else emitted.push(line);continue}state7="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}state7="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();state7="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(state7==="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 state7="code";let tmpl={mode:"tpl",quote:"",depth:0};let blankRun=0;for(const line of lines){if(state7==="block"){const close=line.indexOf("*/");if(close===-1){pending++;continue}state7="code";if(line.slice(close+2).trim().length===0)pending++;else{flush();emitted.push(line)}blankRun=0;continue}if(state7==="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)state7="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++;state7="block";continue}if(scan.kind==="block-open-mid"){flush();state7="block";emitted.push(line);blankRun=0;continue}if(scan.kind==="template-open"){flush();state7="template";tmpl=scan.tmpl??{mode:"tpl",quote:"",depth:0};emitted.push(line);blankRun=0;continue}flush();emitted.push(line);blankRun=0}if(state7!=="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[name,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=name}}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(state7){const spans=[];for(const block of state7.blocks){if(!block.active)continue;const span=resolveBlockSpan(block,state7.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,state7,countTokens=text2=>Math.ceil(text2.length/4),strategy="all",timestamps=false){const map=state7.messageRefs;const snapshot={...state7.tokenSnapshot??{}};const deferred=state7.renderDeferredRefs?new Set(state7.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){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));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 adjustBoundariesForToolPairs(startIndex,endIndex,messages,maxScan=20){const callIdsInRange=new Set;for(let i=startIndex;i<=endIndex;i++){const msg=messages[i];if(!msg||!msg.toolCallId)continue;if(msg.toolName==="compress")continue;callIdsInRange.add(msg.toolCallId)}if(callIdsInRange.size===0){return{startIndex,endIndex}}let newEndIndex=endIndex;for(let i=endIndex+1;i<messages.length&&i<=endIndex+maxScan;i++){const msg=messages[i];if(!msg)break;if(msg.toolCallId&&callIdsInRange.has(msg.toolCallId)){newEndIndex=i}else if(newEndIndex>endIndex){break}}let newStartIndex=startIndex;for(let i=startIndex-1;i>=0&&i>=startIndex-maxScan;i--){const msg=messages[i];if(!msg)break;if(msg.toolCallId&&callIdsInRange.has(msg.toolCallId)){newStartIndex=i}else if(newStartIndex<startIndex){break}}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 adjustedIds=applyPairBoundaryAdjustments(resolved,input.messages);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 consumedBlockIds=resolved.nestedBlockIds.filter(id=>{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 (remote URL / file references with no stored bytes) from compression range \u2014 folding would destroy them permanently (billion-context#1188/#2609). Inline images fold normally 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;return finish2({fatal:{kind:"zone",error: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: ${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);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",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 sample=[...consumedCoverage].slice(0,5).join(", ");return finish2({fatal:{kind:"split",error:new Error(`Merging ${consumedBlockIds.join(", ")} cannot satisfy turn integrity without unfolding already-folded message(s) owned by those blocks (${sample}) \u2014 doing so would drop their existing coverage. Align the range to whole turns (do not cut through a reasoning/tool-call/result group) or merge fewer blocks.`)}})}withdrawnIds=unfolded;for(const id of unfolded)effectiveMessageIds.delete(id);const beforeWithdraw=filteredIds.length;filteredIds=filteredIds.filter(id=>!unfolded.has(id));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,state7,config){const liveCarrierIds=new Set;for(const message of messages){if(isLiveCheckpointCarrier(message,state7))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)}}return{byId:buildIndexByMessageId(messages),liveCarrierIds,failedCompressCallIds,latestProtected,agedCompressCallIds,baseProtectedCallIds,pairByCallId:buildPairMap(messages),anchorMessage:lastUserAnchor(messages,coveredMessageIds(state7),config),integrityPre:buildIntegrityPre(messages)}}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(state7){const coverage=new Set;for(const block of activeBlocks(state7)){for(const id of block.effectiveMessageIds)coverage.add(id)}return coverage}function applyPairBoundaryAdjustments(resolved,messages){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);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 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(state7,nestedBlockIds,isBlockBoundary){if(!isBlockBoundary)return 1;if(nestedBlockIds.length===0)return 1;let minTier=3;for(const id of nestedBlockIds){const block=blockById(state7,id);if(block&&block.tier<minTier)minTier=block.tier}return minTier}function deactivateBlock(state7,blockIds,options={}){const targets=new Set(blockIds);const updated=state7.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{...state7,blocks:final}}function collectBlockContent(state7,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 child=state7.blocks.find(b2=>b2.blockId===childId);if(!child?.active)continue;nestedChildren.push(child);for(const id of child.effectiveMessageIds)nestedCovered.add(id)}const parts=[];for(const child of nestedChildren){const label=child.topic?`${child.blockId}: ${child.topic}`:child.blockId;parts.push(`${SUMMARY_HEADER} \u2014 ${label}
|
|
135
135
|
${child.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}]
|
|
136
136
|
${text2}`}return`[${message.role}]
|
|
137
|
-
${text2}`}function markBlockRestoredInline(state7,blockId){const existing=state7.blocks.find(b2=>b2.blockId===blockId);if(!existing)return{state:state7,result:null};const blocks=state7.blocks.map(block=>block.blockId===blockId?{...block,restoredInline:true}:block);const span=resolveBlockSpan(existing,state7.messageRefs.byRaw);const result={restored:true,blockId,...span?{restoredStartRef:span.startRef,restoredEndRef:span.endRef}:{}};return{state:{...state7,blocks},result}}function activeAncestorIds(state7,blockId){const out=[];const visited=new Set([blockId]);let frontier=[blockId];while(frontier.length>0){const next=[];for(const block of state7.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(state7,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(state7,`b${parsed.numericId}`);if(!block)return null;const span=resolveBlockSpan(block,state7.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(state7,spec){const span=requestedRefoldSpan(state7,spec);if(!span)return{kind:"blocked",reasons:[]};const reasons=[];const blocks=[];for(const block of state7.blocks){if(!block.active)continue;const resolved=resolveBlockSpan(block,state7.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(state7,block.blockId).filter(ancestorId=>!blockById(state7,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,state7,config,countTokens=estimateTextTokens){const preserveN=config.preserveRecentMessages;const preserveTokens=config.preserveRecentTokens;const covered=coveredMessageIds(state7);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=state7.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=state7.messageRefs.byRaw[anchor.id];if(ref&&ref!=="BLOCKED")result.add(ref)}}{const msgByRef=new Map;for(const m2 of messages){const ref=m2.id?state7.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=state7.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,state7,config,protectedZoneRefs,countTokens=estimateTextTokens,integritySource){let compressibleMsgs=[];const protectedMsgs=[];const covered=coveredMessageIds(state7);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 msgIndex=-1;const deadRefNums=new Set((state7.deadRefs??[]).map(ref=>refNumber(ref)).filter(n=>n!==null));let lastCompressibleRefNum=null;for(const msg of messages){msgIndex++;const ref=state7.messageRefs.byRaw[msg.id];if(!ref||ref==="BLOCKED")continue;if(isSyntheticOrPruned(msg,covered)){skipSinceCompressible=true;skipSinceProtected=true;continue}if(isLiveCheckpointCarrier(msg,state7)){skipSinceCompressible=true;skipSinceProtected=true;continue}if(hasUnrecoverableMediaPayload(msg)){skipSinceCompressible=true;skipSinceProtected=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;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}}compressibleMsgs.push({id:msg.id,ref,gapBefore:skipSinceCompressible,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}const unfoldedIds=computeIntegrityWithdrawals(integritySource??messages,new Set(compressibleMsgs.map(info=>info.id))).withdrawn;if(unfoldedIds.size>0){let gapPending=false;const kept=[];for(const info of compressibleMsgs){if(unfoldedIds.has(info.id)){gapPending=true;continue}kept.push(gapPending?{...info,gapBefore:true}:info);gapPending=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};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;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){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);if(contiguous){result[result.length-1]=mergeBatch([prev,...batch])}else if(batchChars>=minChars){result.push(mergeBatch(batch))}}return result}function screenRecommendedUnits(units,source,state7,config,protectedRefs){if(units.length===0)return units;const coverage=collectCoverage(state7);const shared=buildProjectionShared(source,state7,config);return units.filter(unit=>{let projection;try{projection=projectUnit({messages:source,state:state7,config,startRef:unit.startRef,endRef:unit.endRef,preExistingCoverage:coverage,protectedMessageIds:protectedRefs,shared})}catch(err2){if(!(err2 instanceof BoundaryNotFoundError)){console.warn(`[acp-kernel] screenRecommendedUnits dropped unit ${unit.startRef}..${unit.endRef} after projection error: ${err2 instanceof Error?err2.message:String(err2)}`)}return false}if(!projection||projection.fatal!==null)return false;if(projection.filteredIds.length===0&&projection.consumedBlockIds.length===0){return false}if(projection.filteredIds.length===0&&projection.consumedBlockIds.length>0&&!projection.isBlockBoundary&&evaluateRefold(state7,unit).kind!=="refold"){return false}return true})}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 formatK2(n){return n>=1e3?`${(n/1e3).toFixed(1)}K`:`${n}`}function refGateDiagnostics(state7,requestedRanges,unknownCount){const highest=highestUsedIndex(state7.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=${state7.stats.compressionCount} compression(s), ${state7.blocks.length} block(s)]`}function danglingMessageRefs(state7,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=state7.messageRefs.byRef[parsed.raw]??state7.messageRefs.byRef[indexToRef(parsed.numericId)];if(!rawId){const padded=indexToRef(parsed.numericId);if(state7.deadRefs?.includes(parsed.raw)||state7.deadRefs?.includes(padded)){dangling.push(padded)}continue}if(visible.has(rawId))continue;const covered=state7.blocks.some(block=>block.active&&block.effectiveMessageIds.includes(rawId));if(!covered)dangling.push(parsed.raw)}return dangling}function coveringBlockIds(state7,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=state7.messageRefs.byRef[parsed.raw]??state7.messageRefs.byRef[indexToRef(parsed.numericId)];if(rawId)rawIds=[rawId]}else{rawIds=blockById(state7,`b${parsed.numericId}`)?.effectiveMessageIds??[]}if(rawIds.length===0)continue;for(const candidate of activeBlocks(state7)){if(rawIds.some(id=>candidate.effectiveMessageIds.includes(id))){found.add(candidate.blockId)}}}return[...found].sort((x,y)=>numericBlockId(x)-numericBlockId(y))}function tierActionHint(config,state7){if(!config.tiers.enabled)return"";const t2=activeBlocks(state7).filter(b2=>b2.tier===2);if(t2.length>=config.tiers.tier3Trigger){return` Tier condensation is actionable now: compress({ content: [{ startId: "${t2[0].blockId}", endId: "${t2[t2.length-1].blockId}", summary: "...", topic: "..." }] }) merges those tier-2 blocks into one tier-3 block.`}const t1=activeBlocks(state7).filter(b2=>b2.tier===1);if(t1.length>=config.tiers.tier2Trigger){return` Tier distillation is actionable now: compress({ content: [{ startId: "${t1[0].blockId}", endId: "${t1[t1.length-1].blockId}", summary: "...", topic: "..." }] }) merges those tier-1 blocks into one tier-2 block.`}return""}function applyRefolds(input){validateSummaryLength(input.spec,input.config.compress);const targets=new Set(input.blockIds);input.state.blocks=input.state.blocks.map(block=>targets.has(block.blockId)?{...block,summary:input.spec.summary,topic:input.spec.topic??block.topic,runId:input.runId,restoredInline:false}:block)}function createCore(ports={}){const countTokens=ports.countTokens??defaultCountTokens;const timestampsOn=ports.timestamps===true;function applyCompression(input){const state7=cloneState(input.state);for(const spec of input.ranges){if(spec.summary)spec.summary=scrubLoneSurrogates(spec.summary)}let allocatedRunId=null;const runIdOf=()=>allocatedRunId??=allocateRunId(state7);let blocksCreated=0;let tokensCompressed=0;const errors=[];const warnings=[];const notes=[];const protectedMessageIds=input.protectedMessageIds??computeProtectedRefs(input.messages,input.state,input.config,countTokens);const preExistingCoverage=collectCoverage(state7);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:state7});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=(state7.deadRefs??[]).filter(ref=>{const rawId=state7.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(state7,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){state7.deadRefs=[...new Set(deadRefs)].sort((a,b2)=>Number(a.replace(/^m/,""))-Number(b2.replace(/^m/,"")))}else{state7.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(state7,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(state7,input.ranges.length,unknownCount);const firstConsumed=consumedRanges[0];const covering=firstConsumed?coveringBlockIds(state7,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,state7)}`: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:state7,result:{blocksCreated:0,tokensCompressed:0,errors:[],warnings:[`${gateMessage} Nothing failed and nothing needed redoing \u2014 do not resend these ranges.`],noop:true}}}return{state:state7,result:{blocksCreated:0,tokensCompressed:0,errors:[gateMessage,...classificationErrors],warnings:[]}}}}{const lengthFailures=[];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;try{validateSummaryLength(spec,input.config.compress)}catch(error){lengthFailures.push(rangeError(spec,error instanceof Error?error.message:String(error)))}}if(lengthFailures.length>0){return{state:state7,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. Fix it one way or the other and resend: shorten or split each offending range's summary to fit its cap, then resend the whole batch; or drop the offending range(s) and resend only the rest that validate.`,...classificationErrors],warnings:[]}}}}const preLoopState=cloneState(state7);const applyErrors=[];const warningsBase=warnings.length;const preFoldBlockIds=new Set(state7.blocks.map(b2=>b2.blockId));for(const spec of input.ranges){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:state7,runId:runIdOf(),config:input.config,blockIds:decision.blocks.map(block=>block.blockId)});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:state7,runId:runIdOf(),config:input.config,protectedMessageIds,countTokens,preExistingCoverage});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)}}}state7.stats.compressionCount+=blocksCreated;state7.stats.tokensCompressed+=tokensCompressed;if(blocksCreated>0){let foldStartRef;for(const b2 of state7.blocks){if(preFoldBlockIds.has(b2.blockId))continue;for(const id of b2.effectiveMessageIds){const num7=refNum(state7.messageRefs.byRaw[id]);if(num7!==null&&(foldStartRef===void 0||num7<foldStartRef)){foldStartRef=num7}}}if(foldStartRef!==void 0){state7.pendingOrphanSweepMinRef=state7.pendingOrphanSweepMinRef===void 0?foldStartRef:Math.min(state7.pendingOrphanSweepMinRef,foldStartRef)}state7.nudge.lastPerMessageNudgeTokens=0;state7.nudge.lastNudgeShownTokens=0;state7.nudge.lastShownByTier={};state7.terminalStreak=0;state7.emergencyTruncateLatch=void 0;state7.renderDeferredRefs=void 0;state7.viewLatches=void 0}return{state:state7,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,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 state7={...result.state,lastPassIds:inboundIds,deadRefs};const ccrEffect=result.effects.ccr;let statusLine;const nudge=result.effects.nudge;const bannerShown=(result.state.nudge?.lastNudgeShownTokens??0)>0||Object.keys(result.state.nudge?.lastShownByTier??{}).length>0;if(nudge&&!nudge.shouldInject&&(nudge.tier!==null||bannerShown)&&(nudge.compressibleRanges?.length??0)>0){const highest=highestUsedIndex(state7.messageRefs);const offered=nudge.compressibleRanges.slice(0,3).map(r=>`${r.startRef}\u2013${r.endRef} (${formatK2(r.tokens)})`).join(", ");const extra=nudge.compressibleRanges.length>3?`, +${nudge.compressibleRanges.length-3} more`:"";statusLine=`[ACP status: highest allocated ref ${highest>0?indexToRef(highest):"none"} \u2014 refs above it are not minted yet, never guess them; compressible now: ${offered}${extra}; the newest messages stay protected. Use these refs directly; acp_status only if you need the full list.]`}return{messages:result.messages,state:state7,nudge:result.effects.nudge,statusLine,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,state7){return blockById(state7,blockId)}function search(query,state7){const terms=query.toLowerCase().split(/\s+/).filter(term=>term.length>0);if(terms.length===0)return[];const scored=activeBlocks(state7).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(state7,tokenCount,config){const active=activeBlocks(state7);const usage=config.modelContextLimit>0?tokenCount/config.modelContextLimit:0;return{contextUsage:usage,tokenCount,modelContextLimit:config.modelContextLimit,activeBlocks:active.length,totalBlocks:state7.blocks.length,tokensCompressed:state7.stats.tokensCompressed,breakdown:{active:active.length,total:state7.blocks.length,storedMessages:state7.stats.storedCount??0,retrievals:state7.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 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;changed=true;return{...m2,ts:stamped}}const carried=typeof m2.ts==="number"?m2.ts:void 0;const ts2=carried??(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)return io2;return{...io2,messages,state:{...io2.state,tsStamps:stamps}}}}}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}}throw projection.fatal.error}const{filteredIds,consumedBlockIds,effectiveMessageIds,outputTier,isBlockBoundary}=projection;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)});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);return{tokens:0,warnings:[`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 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:input.spec.summary,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)}function validateSummaryLength(spec,cfg){const summary=spec.summary?.trim()??"";if(summary.length===0){throw new Error("Summary is empty \u2014 provide a meaningful summary of the compressed range.")}if(cfg.minSummaryLength>0&&summary.length<cfg.minSummaryLength){throw new Error(`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 new Error(`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(state7,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(state7);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:state7,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 baseline=state7.nudge.lastPerMessageNudgeTokens;const hadPendingNudge=state7.nudge.lastNudgeShownTokens>0;const hasPendingNudge=hadPendingNudge;const effectiveThreshold=hasPendingNudge?Math.floor(nudgeGrowthTokens/2):nudgeGrowthTokens;const growthReference=state7.nudge.lastNudgeShownTokens>0?state7.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(state7,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 firstSightMassReady=state7.nudge.lastNudgeShownTokens===0&&baseline===0&&usage>=config.nudge.minContextLimitPct&&Math.max(t1Eff,t2Pen,t3Pen)>=nudgeGrowthTokens;const growthReady=firstSightMassReady||growthSinceReference>=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=[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){injectedTier=best;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(t1Eff>=tierThresholds[1]){injectedTier=1;injectedReason=`T1 effective ${t1Eff} >= ${tierThresholds[1]}, growth ${growthSinceReference}, usage ${Math.round(usage*100)}%`}else if(config.tiers.enabled&&(t2CountReady||t2Pen>=tierThresholds[2]&&t2Pen>t1Eff)){const lastShown=state7.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(config.tiers.enabled&&(t3CountReady||t3Pen>=tierThresholds[3]&&t3Pen>t2Pen&&t3Pen>t1Eff)){const lastShown=state7.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]"}let reason;if(injectedTier!==null){reason=injectedReason}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))&&(state7.nudge.lastShownByTier[t]??0)>0&&tokenCount-(state7.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(`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(state7),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,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(state7){return{blocks:state7.blocks.map(block=>({...block,directMessageIds:[...block.directMessageIds],effectiveMessageIds:[...block.effectiveMessageIds],directBlockIds:[...block.directBlockIds]})),messageRefs:{byRaw:{...state7.messageRefs.byRaw},byRef:{...state7.messageRefs.byRef}},tokenSnapshot:{...state7.tokenSnapshot??{}},tsStamps:state7.tsStamps?{...state7.tsStamps}:void 0,nudge:{...state7.nudge,anchors:{...state7.nudge.anchors}},stats:{...state7.stats},absorbed:(state7.absorbed??[]).map(record4=>({...record4})),rules:(state7.rules??[]).map(rule=>({...rule})),nextRuleId:state7.nextRuleId,terminalStreak:state7.terminalStreak,nextBlockId:state7.nextBlockId,nextRunId:state7.nextRunId,hiddenOrphanRefs:state7.hiddenOrphanRefs?[...state7.hiddenOrphanRefs]:void 0,sweptOrphanCallIds:state7.sweptOrphanCallIds?[...state7.sweptOrphanCallIds]:void 0,pendingOrphanSweepMinRef:state7.pendingOrphanSweepMinRef,deadRefs:state7.deadRefs?[...state7.deadRefs]:void 0,lastPassIds:state7.lastPassIds?[...state7.lastPassIds]:void 0,refLedgerAligned:state7.refLedgerAligned}}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(name){return/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)&&!name.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[name,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[name]=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(readFileSync(file,"utf8"));return parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}catch{return null}}function createDirPackSource(id,dir){const resolve2=name=>{if(!isValidPackName(name))return null;const file=path.join(dir,`${name}.json`);const raw=readPackFile(file);if(!raw)return null;return{name,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:resolve2,list(){let names;try{names=readdirSync(dir).filter(f2=>f2.endsWith(".json"))}catch{return[]}const out=[];for(const f2 of names){const pack=resolve2(f2.slice(0,-5));if(pack)out.push(pack)}return out}}}function createPackResolver(sources){return{sources,resolve(name){if(!isValidPackName(name))return null;for(const source of sources){const pack=source.resolve(name);if(pack)return pack}return null},listPacks(){const seen=new Set;const out=[];for(const source of sources){for(const pack of source.list?.()??[]){if(!seen.has(pack.name)){seen.add(pack.name);out.push(pack)}}}return out}}}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,state7,countTokens){const coveredIds=new Set;for(const block of state7.blocks){if(!block.active)continue;for(const id of block.effectiveMessageIds)coveredIds.add(id)}let summaryTokens=0;for(const block of state7.blocks){if(block.active)summaryTokens+=summaryTokensOf(block,countTokens)}const visible=[];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(state7.messageRefs,message.id);if(!ref)return;const tokens=countMessageTokens(message,countTokens);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});pendingGap=isLiveCheckpointCarrier(message,state7);return}if(ref!==BLOCKED_REF&&tokens>0)pendingGap=true});return{visible,summaryTokens}}function buildStatusReport(state7,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=state7.blocks.filter(b2=>b2.active).sort((a,b2)=>numericPart2(a.blockId)-numericPart2(b2.blockId));if(scope==="compressed"){return renderCompressedDrilldown(activeBlocks2,state7,sort,limit,countTokens,options.meta)}const{visible,summaryTokens}=collectVisible(messages,state7,countTokens);if(scope==="uncompressed"){if(view==="messages"){return renderMessageDrilldown(visible,toolFilter,sort,limit)}return renderUncompressedRanges(visible,sort,limit,state7,countTokens,options.config,options.originalMessages)}return renderOverview(visible,summaryTokens,activeBlocks2,state7,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,state7,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 topTool=[...toolTypeMap.entries()].sort((a,b2)=>b2[1]-a[1])[0]?.[0];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,state7,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,state7,countTokens)-effectiveCompressedTokens(a,state7,countTokens)||b2.createdAt-a.createdAt);for(const block of sorted.slice(0,limit)){const topic=block.topic??"(no topic)";const eff=effectiveCompressedTokens(block,state7,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)`)}}lines.push("");lines.push(`Tip: buildStatusReport({scope:"uncompressed", view:"messages", tool:"${topTool??"bash"}"}) for per-message listing`);return lines.join("\n")}function renderUncompressedRanges(visible,sort,limit,state7,countTokens,config,original){const lines=[];const totalTokens=visible.reduce((s3,m2)=>s3+m2.tokens,0);lines.push(`UNCOMPRESSED \u2014 ${formatTokens2(totalTokens)} | ${visible.length} visible messages`);lines.push("");if(visible.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(visible)){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(state7);const protectedRefs=computeProtectedRefs(original,state7,config,countTokens);const shared=buildProjectionShared(original,state7,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:state7,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("");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`)}return lines.join("\n")}function renderMessageDrilldown(visible,toolFilter,sort,limit){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 header=toolFilter?`UNCOMPRESSED \u2014 ${toolFilter}: ${formatTokens2(totalTokens)} | ${filtered.length} msgs | ${pct(totalTokens,allTokens)}% of visible`:`UNCOMPRESSED \u2014 ${formatTokens2(totalTokens)} | ${filtered.length} msgs`;const lines=[header,`Sorted by ${sort}`,""];const shown=filtered.slice(0,limit);for(const message of shown){lines.push(` ${message.ref} (${formatTokens2(message.tokens)}) ${message.tool}`)}if(filtered.length>shown.length){lines.push("");lines.push(`${shown.length} of ${filtered.length} shown.`)}return lines.join("\n")}function renderCompressedDrilldown(blocks,state7,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,state7,countTokens)-effectiveCompressedTokens(a,state7,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,state7,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,state7,countTokens);lines.push(` ${block.blockId} (${tierLabel(block)}) ${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 header=`ACP CACHE REPORT${sessionLabel?` (${sessionLabel})`:""} \u2014 ${t.requests} requests`;if(opts?.detail==="full"){return[header,"",formatCacheReportFull(report)].join("\n")}return[header+` [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:state7,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: ${state7.blocks.length} (active ${state7.blocks.filter(b2=>b2.active).length})`);lines.push("");const folded=input.folded===true;const view=full||folded?coreMessages:prune(coreMessages,state7,{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(state7){return state7.rules??[]}function resolveRuleLimits(config){return{maxRules:config?.rules?.maxRules??DEFAULT_RULE_LIMITS.maxRules,maxRuleChars:config?.rules?.maxRuleChars??DEFAULT_RULE_LIMITS.maxRuleChars}}function highestRuleNumber(state7){let highest=0;for(const rule of state7.rules??[]){const match=RULE_ID_RE.exec(rule.id);if(match)highest=Math.max(highest,Number(match[1]))}return highest}function addRule(state7,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(state7);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(state7.nextRuleId??1,highestRuleNumber(state7)+1);const rule={id:`rule${next}`,text:trimmed};state7.rules=[...rules,rule];state7.nextRuleId=next+1;return{ok:true,rule}}function removeRule(state7,id){const rules=listRules(state7);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).`}}state7.rules=rules.filter(rule=>rule.id!==target.id);return{ok:true,rule:target}}function clearRules(state7){const count=listRules(state7).length;state7.rules=[];return{ok:true,count}}function formatRulesList(rules){return rules.map((rule,i)=>`${i+1}. [${rule.id}] ${rule.text}`).join("\n")}function parseCompressArgs(input,opts){const callId=opts?.callId;const diag={ok:false,kind:"ok",invalidItems:0};if(input===null||input===void 0){diag.kind="empty-input";return finish([],diag)}if(typeof input==="string"){return parseStringInput(input,callId,diag)}if(typeof input!=="object"||Array.isArray(input)){diag.kind="not-object";return finish([],diag)}return parseObjectValue(input,callId,diag)}function parseStringInput(raw,callId,diag){diag.rawPrefix=clampPrefix(raw,800);diag.length=raw.length;const cleaned=stripFence(raw.trim());const first=parseStringCore(cleaned,callId,diag);if(first.ranges.length===0||first.diagnostics.invalidItems>0){const normalized=normalizeSingleQuotes(cleaned);if(normalized!==void 0){const retryDiag={ok:false,kind:"ok",invalidItems:0};retryDiag.rawPrefix=diag.rawPrefix;retryDiag.length=diag.length;const retry=parseStringCore(normalized,callId,retryDiag);if(retry.ranges.length>first.ranges.length){retryDiag.quoteSalvage=true;return retry}}}return first}function parseStringCore(cleaned,callId,diag){if(cleaned===""){diag.kind="empty-input";return finish([],diag)}let value=tryParseLenient(cleaned);if(typeof value==="string"){const inner=tryParseLenient(stripFence(value));if(inner!==void 0)value=inner}if(value!==null&&typeof value==="object"&&!Array.isArray(value)){return parseObjectValue(value,callId,diag)}if(value!==void 0){diag.kind="not-object";return finish([],diag)}const entries2=salvageContentEntries(cleaned);return finishSalvage(entries2,callId,diag,looksTruncated(cleaned))}function parseObjectValue(value,callId,diag){diag.keys=Object.keys(value);const content=value["content"];if(content===void 0){const single=validateEntry(value,callId);if("range"in single){diag.kind="ok";return finish([single.range],diag)}diag.kind="missing-content";return finish([],diag)}let entries2;let salvaged=false;if(Array.isArray(content)){entries2=content}else if(typeof content==="string"){const parsed=parseContentArray(content);if(parsed===null||parsed.entries.length===0&&content.trim().length>0){const bare=stripJsonWrapperResidue(content);const entries22=splitLineEntries(bare);const{ranges:ranges2,invalid:invalid2,reasons:reasons2}=validateEntries(entries22,callId);if(ranges2.length>0){diag.invalidItems=invalid2;if(reasons2.length>0)diag.invalidReasons=reasons2;diag.kind="ok";return finish(ranges2,diag)}if(entries22.length===0||entries22.every(isHeaderlessLineEntry)){const flat=flatSingleRangeFromContent(value,content,callId);if(flat!==void 0){diag.flatSummarySalvage=true;diag.kind="ok";return finish([flat],diag)}}diag.invalidItems=invalid2;if(reasons2.length>0)diag.invalidReasons=reasons2;diag.kind=entries22.some(e=>!isHeaderlessLineEntry(e))?"no-valid-ranges":"content-not-array";return finish([],diag)}entries2=parsed.entries;salvaged=parsed.salvaged;if(parsed.quoteRepaired)diag.quoteSalvage=true}else if(content!==null&&typeof content==="object"){const obj=content;const nested=obj["ranges"];entries2=Array.isArray(nested)?nested:[obj];diag.contentSalvage=true}else{diag.kind="content-not-array";return finish([],diag)}const{ranges,invalid,reasons}=validateEntries(entries2,callId);const topTopic=stringOr(value["topic"]);const topMaxChars=value["summaryMaxChars"];const hasTopMaxChars=typeof topMaxChars==="number"&&Number.isFinite(topMaxChars);if(topTopic!==void 0||hasTopMaxChars){for(const r of ranges){if(r.topic===void 0&&topTopic!==void 0)r.topic=topTopic;if(r.summaryMaxChars===void 0&&hasTopMaxChars)r.summaryMaxChars=topMaxChars}}diag.invalidItems=invalid;if(reasons.length>0)diag.invalidReasons=reasons;diag.kind=salvaged?"truncated":ranges.length>0?"ok":"no-valid-ranges";return finish(ranges,diag)}function isHeaderlessLineEntry(e){if(typeof e!=="string")return false;const nl=e.indexOf("\n");const head=(nl===-1?e:e.slice(0,nl)).trim();return!REF_PAIR_IN_LINE.test(head)&&!SINGLE_REF_IN_LINE.test(head)}function flatSingleRangeFromContent(value,content,callId){const start=stringOr(value["startRef"])??stringOr(value["startId"])??stringOr(value["messageId"]);const end=stringOr(value["endRef"])??stringOr(value["endId"])??stringOr(value["messageId"]);if(start===void 0||end===void 0)return void 0;let summary=stringOr(value["summary"]);let topic=stringOr(value["topic"]);if(summary===void 0){const inner=tryParseLenient(stripFence(content.trim()));if(inner!==null&&typeof inner==="object"&&!Array.isArray(inner)){const o=inner;summary=stringOr(o["summary"]);if(topic===void 0)topic=stringOr(o["topic"])}if(summary===void 0){const text2=content.trim();if(text2.length>0)summary=text2}}if(summary===void 0)return void 0;const entry={startRef:start,endRef:end,summary};if(topic!==void 0)entry["topic"]=topic;const outcome=validateEntry(entry,callId);return"range"in outcome?outcome.range:void 0}function parseContentArray(s3){const cleaned=stripFence(s3.trim());const direct=parseContentArrayCore(cleaned);if(direct!==null&&direct.entries.length>0)return direct;const normalized=normalizeSingleQuotes(cleaned);if(normalized!==void 0){const retry=parseContentArrayCore(normalized);if(retry!==null&&retry.entries.length>0)return{...retry,quoteRepaired:true}}return direct}function parseContentArrayCore(s3){let value=s3===""?void 0:tryParseLenient(s3);if(typeof value==="string"){value=tryParseLenient(stripFence(value))}if(Array.isArray(value)){return{entries:value,salvaged:false}}if(value===void 0){const entries2=salvageContentEntries('{"content": '+s3);return{entries:entries2,salvaged:entries2.length>0}}return null}function finish(ranges,diag){diag.ok=ranges.length>0;return{ranges,diagnostics:diag}}function finishSalvage(entries2,callId,diag,truncatedShape){const{ranges,invalid,reasons}=validateEntries(entries2,callId);diag.invalidItems=invalid;if(reasons.length>0)diag.invalidReasons=reasons;diag.kind=entries2.length>0||truncatedShape?"truncated":"malformed-json";return finish(ranges,diag)}function coalesceLineEntries(entries2){const out=[];let headerOnlyIdx=-1;for(const e of entries2){if(typeof e==="string"){const nl=e.indexOf("\n");const head=(nl===-1?e:e.slice(0,nl)).trim();const hasRef=REF_PAIR_IN_LINE.test(head)||SINGLE_REF_IN_LINE.test(head);if(!hasRef&&headerOnlyIdx>=0){out[headerOnlyIdx]=`${out[headerOnlyIdx]}
|
|
137
|
+
${text2}`}function markBlockRestoredInline(state7,blockId){const existing=state7.blocks.find(b2=>b2.blockId===blockId);if(!existing)return{state:state7,result:null};const blocks=state7.blocks.map(block=>block.blockId===blockId?{...block,restoredInline:true}:block);const span=resolveBlockSpan(existing,state7.messageRefs.byRaw);const result={restored:true,blockId,...span?{restoredStartRef:span.startRef,restoredEndRef:span.endRef}:{}};return{state:{...state7,blocks},result}}function activeAncestorIds(state7,blockId){const out=[];const visited=new Set([blockId]);let frontier=[blockId];while(frontier.length>0){const next=[];for(const block of state7.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(state7,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(state7,`b${parsed.numericId}`);if(!block)return null;const span=resolveBlockSpan(block,state7.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(state7,spec){const span=requestedRefoldSpan(state7,spec);if(!span)return{kind:"blocked",reasons:[]};const reasons=[];const blocks=[];for(const block of state7.blocks){if(!block.active)continue;const resolved=resolveBlockSpan(block,state7.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(state7,block.blockId).filter(ancestorId=>!blockById(state7,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,state7,config,countTokens=estimateTextTokens){const preserveN=config.preserveRecentMessages;const preserveTokens=config.preserveRecentTokens;const covered=coveredMessageIds(state7);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=state7.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=state7.messageRefs.byRaw[anchor.id];if(ref&&ref!=="BLOCKED")result.add(ref)}}{const msgByRef=new Map;for(const m2 of messages){const ref=m2.id?state7.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=state7.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,state7,config,protectedZoneRefs,countTokens=estimateTextTokens,integritySource){let compressibleMsgs=[];const protectedMsgs=[];const covered=coveredMessageIds(state7);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 msgIndex=-1;const deadRefNums=new Set((state7.deadRefs??[]).map(ref=>refNumber(ref)).filter(n=>n!==null));let lastCompressibleRefNum=null;for(const msg of messages){msgIndex++;const ref=state7.messageRefs.byRaw[msg.id];if(!ref||ref==="BLOCKED")continue;if(isSyntheticOrPruned(msg,covered)){skipSinceCompressible=true;skipSinceProtected=true;continue}if(isLiveCheckpointCarrier(msg,state7)){skipSinceCompressible=true;skipSinceProtected=true;continue}if(hasUnrecoverableMediaPayload(msg)){skipSinceCompressible=true;skipSinceProtected=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;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}}compressibleMsgs.push({id:msg.id,ref,gapBefore:skipSinceCompressible,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}const unfoldedIds=computeIntegrityWithdrawals(integritySource??messages,new Set(compressibleMsgs.map(info=>info.id))).withdrawn;if(unfoldedIds.size>0){let gapPending=false;const kept=[];for(const info of compressibleMsgs){if(unfoldedIds.has(info.id)){gapPending=true;continue}kept.push(gapPending?{...info,gapBefore:true}:info);gapPending=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};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;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){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);if(contiguous){result[result.length-1]=mergeBatch([prev,...batch])}else if(batchChars>=minChars){result.push(mergeBatch(batch))}}return result}function screenRecommendedUnits(units,source,state7,config,protectedRefs){if(units.length===0)return units;const coverage=collectCoverage(state7);const shared=buildProjectionShared(source,state7,config);return units.filter(unit=>{let projection;try{projection=projectUnit({messages:source,state:state7,config,startRef:unit.startRef,endRef:unit.endRef,preExistingCoverage:coverage,protectedMessageIds:protectedRefs,shared})}catch(err2){if(!(err2 instanceof BoundaryNotFoundError)){console.warn(`[acp-kernel] screenRecommendedUnits dropped unit ${unit.startRef}..${unit.endRef} after projection error: ${err2 instanceof Error?err2.message:String(err2)}`)}return false}if(!projection||projection.fatal!==null)return false;if(projection.filteredIds.length===0&&projection.consumedBlockIds.length===0){return false}if(projection.filteredIds.length===0&&projection.consumedBlockIds.length>0&&!projection.isBlockBoundary&&evaluateRefold(state7,unit).kind!=="refold"){return false}return true})}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 formatK2(n){return n>=1e3?`${(n/1e3).toFixed(1)}K`:`${n}`}function refGateDiagnostics(state7,requestedRanges,unknownCount){const highest=highestUsedIndex(state7.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=${state7.stats.compressionCount} compression(s), ${state7.blocks.length} block(s)]`}function danglingMessageRefs(state7,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=state7.messageRefs.byRef[parsed.raw]??state7.messageRefs.byRef[indexToRef(parsed.numericId)];if(!rawId){const padded=indexToRef(parsed.numericId);if(state7.deadRefs?.includes(parsed.raw)||state7.deadRefs?.includes(padded)){dangling.push(padded)}continue}if(visible.has(rawId))continue;const covered=state7.blocks.some(block=>block.active&&block.effectiveMessageIds.includes(rawId));if(!covered)dangling.push(parsed.raw)}return dangling}function coveringBlockIds(state7,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=state7.messageRefs.byRef[parsed.raw]??state7.messageRefs.byRef[indexToRef(parsed.numericId)];if(rawId)rawIds=[rawId]}else{rawIds=blockById(state7,`b${parsed.numericId}`)?.effectiveMessageIds??[]}if(rawIds.length===0)continue;for(const candidate of activeBlocks(state7)){if(rawIds.some(id=>candidate.effectiveMessageIds.includes(id))){found.add(candidate.blockId)}}}return[...found].sort((x,y)=>numericBlockId(x)-numericBlockId(y))}function tierActionHint(config,state7){if(!config.tiers.enabled)return"";const t2=activeBlocks(state7).filter(b2=>b2.tier===2);if(t2.length>=config.tiers.tier3Trigger){return` Tier condensation is actionable now: compress({ content: [{ startId: "${t2[0].blockId}", endId: "${t2[t2.length-1].blockId}", summary: "...", topic: "..." }] }) merges those tier-2 blocks into one tier-3 block.`}const t1=activeBlocks(state7).filter(b2=>b2.tier===1);if(t1.length>=config.tiers.tier2Trigger){return` Tier distillation is actionable now: compress({ content: [{ startId: "${t1[0].blockId}", endId: "${t1[t1.length-1].blockId}", summary: "...", topic: "..." }] }) merges those tier-1 blocks into one tier-2 block.`}return""}function applyRefolds(input){validateSummaryLength(input.spec,input.config.compress);const targets=new Set(input.blockIds);input.state.blocks=input.state.blocks.map(block=>targets.has(block.blockId)?{...block,summary:input.spec.summary,topic:input.spec.topic??block.topic,runId:input.runId,restoredInline:false}:block)}function createCore(ports={}){const countTokens=ports.countTokens??defaultCountTokens;const timestampsOn=ports.timestamps===true;function applyCompression(input){const state7=cloneState(input.state);for(const spec of input.ranges){if(spec.summary)spec.summary=scrubLoneSurrogates(spec.summary)}let allocatedRunId=null;const runIdOf=()=>allocatedRunId??=allocateRunId(state7);let blocksCreated=0;let tokensCompressed=0;const errors=[];const warnings=[];const notes=[];const protectedMessageIds=input.protectedMessageIds??computeProtectedRefs(input.messages,input.state,input.config,countTokens);const preExistingCoverage=collectCoverage(state7);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:state7});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=(state7.deadRefs??[]).filter(ref=>{const rawId=state7.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(state7,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){state7.deadRefs=[...new Set(deadRefs)].sort((a,b2)=>Number(a.replace(/^m/,""))-Number(b2.replace(/^m/,"")))}else{state7.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(state7,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(state7,input.ranges.length,unknownCount);const firstConsumed=consumedRanges[0];const covering=firstConsumed?coveringBlockIds(state7,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,state7)}`: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:state7,result:{blocksCreated:0,tokensCompressed:0,errors:[],warnings:[`${gateMessage} Nothing failed and nothing needed redoing \u2014 do not resend these ranges.`],noop:true}}}return{state:state7,result:{blocksCreated:0,tokensCompressed:0,errors:[gateMessage,...classificationErrors],warnings:[]}}}}{const lengthFailures=[];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;try{validateSummaryLength(spec,input.config.compress)}catch(error){lengthFailures.push(rangeError(spec,error instanceof Error?error.message:String(error)))}}if(lengthFailures.length>0){return{state:state7,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. Fix it one way or the other and resend: shorten or split each offending range's summary to fit its cap, then resend the whole batch; or drop the offending range(s) and resend only the rest that validate.`,...classificationErrors],warnings:[]}}}}const preLoopState=cloneState(state7);const applyErrors=[];const warningsBase=warnings.length;const preFoldBlockIds=new Set(state7.blocks.map(b2=>b2.blockId));for(const spec of input.ranges){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:state7,runId:runIdOf(),config:input.config,blockIds:decision.blocks.map(block=>block.blockId)});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:state7,runId:runIdOf(),config:input.config,protectedMessageIds,countTokens,preExistingCoverage});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)}}}state7.stats.compressionCount+=blocksCreated;state7.stats.tokensCompressed+=tokensCompressed;if(blocksCreated>0){let foldStartRef;for(const b2 of state7.blocks){if(preFoldBlockIds.has(b2.blockId))continue;for(const id of b2.effectiveMessageIds){const num7=refNum(state7.messageRefs.byRaw[id]);if(num7!==null&&(foldStartRef===void 0||num7<foldStartRef)){foldStartRef=num7}}}if(foldStartRef!==void 0){state7.pendingOrphanSweepMinRef=state7.pendingOrphanSweepMinRef===void 0?foldStartRef:Math.min(state7.pendingOrphanSweepMinRef,foldStartRef)}state7.nudge.lastPerMessageNudgeTokens=0;state7.nudge.lastNudgeShownTokens=0;state7.nudge.lastShownByTier={};state7.nudge.absorbedDebt=0;state7.nudge.absorbCount=0;state7.terminalStreak=0;state7.emergencyTruncateLatch=void 0;state7.renderDeferredRefs=void 0;state7.viewLatches=void 0}return{state:state7,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,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 state7={...result.state,lastPassIds:inboundIds,deadRefs};const ccrEffect=result.effects.ccr;let statusLine;const nudge=result.effects.nudge;const bannerShown=(result.state.nudge?.lastNudgeShownTokens??0)>0||Object.keys(result.state.nudge?.lastShownByTier??{}).length>0;if(nudge&&!nudge.shouldInject&&(nudge.tier!==null||bannerShown)&&(nudge.compressibleRanges?.length??0)>0){const highest=highestUsedIndex(state7.messageRefs);const offered=nudge.compressibleRanges.slice(0,3).map(r=>`${r.startRef}\u2013${r.endRef} (${formatK2(r.tokens)})`).join(", ");const extra=nudge.compressibleRanges.length>3?`, +${nudge.compressibleRanges.length-3} more`:"";statusLine=`[ACP status: highest allocated ref ${highest>0?indexToRef(highest):"none"} \u2014 refs above it are not minted yet, never guess them; compressible now: ${offered}${extra}; the newest messages stay protected. Use these refs directly; acp_status only if you need the full list.]`}return{messages:result.messages,state:state7,nudge:result.effects.nudge,statusLine,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,state7){return blockById(state7,blockId)}function search(query,state7){const terms=query.toLowerCase().split(/\s+/).filter(term=>term.length>0);if(terms.length===0)return[];const scored=activeBlocks(state7).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(state7,tokenCount,config){const active=activeBlocks(state7);const usage=config.modelContextLimit>0?tokenCount/config.modelContextLimit:0;return{contextUsage:usage,tokenCount,modelContextLimit:config.modelContextLimit,activeBlocks:active.length,totalBlocks:state7.blocks.length,tokensCompressed:state7.stats.tokensCompressed,breakdown:{active:active.length,total:state7.blocks.length,storedMessages:state7.stats.storedCount??0,retrievals:state7.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 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;changed=true;return{...m2,ts:stamped}}const carried=typeof m2.ts==="number"?m2.ts:void 0;const ts2=carried??(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)return io2;return{...io2,messages,state:{...io2.state,tsStamps:stamps}}}}}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}}throw projection.fatal.error}const{filteredIds,consumedBlockIds,effectiveMessageIds,outputTier,isBlockBoundary}=projection;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)});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);return{tokens:0,warnings:[`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 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:input.spec.summary,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)}function validateSummaryLength(spec,cfg){const summary=spec.summary?.trim()??"";if(summary.length===0){throw new Error("Summary is empty \u2014 provide a meaningful summary of the compressed range.")}if(cfg.minSummaryLength>0&&summary.length<cfg.minSummaryLength){throw new Error(`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 new Error(`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(state7,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(state7);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:state7,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 baseline=state7.nudge.lastPerMessageNudgeTokens;const hadPendingNudge=state7.nudge.lastNudgeShownTokens>0;const hasPendingNudge=hadPendingNudge;const effectiveThreshold=hasPendingNudge?Math.floor(nudgeGrowthTokens/2):nudgeGrowthTokens;const growthReference=state7.nudge.lastNudgeShownTokens>0?state7.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(state7,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 firstSightMassReady=state7.nudge.lastNudgeShownTokens===0&&baseline===0&&usage>=config.nudge.minContextLimitPct&&Math.max(t1Eff,t2Pen,t3Pen)>=nudgeGrowthTokens;const absorbedDebt=state7.nudge.absorbedDebt??0;const absorbCount=state7.nudge.absorbCount??0;const repeatAbsorbs=absorbCount>=2;const payableDebt=repeatAbsorbs?absorbedDebt:0;const backlogDrainReady=repeatAbsorbs&&absorbedDebt>0&&state7.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=[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){injectedTier=best;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(t1Eff>=tierThresholds[1]){injectedTier=1;injectedReason=`T1 effective ${t1Eff} >= ${tierThresholds[1]}, growth ${growthSinceReference}, usage ${Math.round(usage*100)}%`}else if(config.tiers.enabled&&(t2CountReady||t2Pen>=tierThresholds[2]&&t2Pen>t1Eff)){const lastShown=state7.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(config.tiers.enabled&&(t3CountReady||t3Pen>=tierThresholds[3]&&t3Pen>t2Pen&&t3Pen>t1Eff)){const lastShown=state7.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]"}let reason;if(injectedTier!==null){reason=injectedReason}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))&&(state7.nudge.lastShownByTier[t]??0)>0&&tokenCount-(state7.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(state7),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,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(state7){return{blocks:state7.blocks.map(block=>({...block,directMessageIds:[...block.directMessageIds],effectiveMessageIds:[...block.effectiveMessageIds],directBlockIds:[...block.directBlockIds]})),messageRefs:{byRaw:{...state7.messageRefs.byRaw},byRef:{...state7.messageRefs.byRef}},tokenSnapshot:{...state7.tokenSnapshot??{}},tsStamps:state7.tsStamps?{...state7.tsStamps}:void 0,nudge:{...state7.nudge,anchors:{...state7.nudge.anchors}},stats:{...state7.stats},absorbed:(state7.absorbed??[]).map(record4=>({...record4})),rules:(state7.rules??[]).map(rule=>({...rule})),nextRuleId:state7.nextRuleId,terminalStreak:state7.terminalStreak,nextBlockId:state7.nextBlockId,nextRunId:state7.nextRunId,hiddenOrphanRefs:state7.hiddenOrphanRefs?[...state7.hiddenOrphanRefs]:void 0,sweptOrphanCallIds:state7.sweptOrphanCallIds?[...state7.sweptOrphanCallIds]:void 0,pendingOrphanSweepMinRef:state7.pendingOrphanSweepMinRef,deadRefs:state7.deadRefs?[...state7.deadRefs]:void 0,lastPassIds:state7.lastPassIds?[...state7.lastPassIds]:void 0,refLedgerAligned:state7.refLedgerAligned}}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(name){return/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)&&!name.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[name,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[name]=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(readFileSync(file,"utf8"));return parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}catch{return null}}function createDirPackSource(id,dir){const resolve2=name=>{if(!isValidPackName(name))return null;const file=path.join(dir,`${name}.json`);const raw=readPackFile(file);if(!raw)return null;return{name,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:resolve2,list(){let names;try{names=readdirSync(dir).filter(f2=>f2.endsWith(".json"))}catch{return[]}const out=[];for(const f2 of names){const pack=resolve2(f2.slice(0,-5));if(pack)out.push(pack)}return out}}}function createPackResolver(sources){return{sources,resolve(name){if(!isValidPackName(name))return null;for(const source of sources){const pack=source.resolve(name);if(pack)return pack}return null},listPacks(){const seen=new Set;const out=[];for(const source of sources){for(const pack of source.list?.()??[]){if(!seen.has(pack.name)){seen.add(pack.name);out.push(pack)}}}return out}}}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,state7,countTokens){const coveredIds=new Set;for(const block of state7.blocks){if(!block.active)continue;for(const id of block.effectiveMessageIds)coveredIds.add(id)}let summaryTokens=0;for(const block of state7.blocks){if(block.active)summaryTokens+=summaryTokensOf(block,countTokens)}const visible=[];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(state7.messageRefs,message.id);if(!ref)return;const tokens=countMessageTokens(message,countTokens);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});pendingGap=isLiveCheckpointCarrier(message,state7);return}if(ref!==BLOCKED_REF&&tokens>0)pendingGap=true});return{visible,summaryTokens}}function buildStatusReport(state7,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=state7.blocks.filter(b2=>b2.active).sort((a,b2)=>numericPart2(a.blockId)-numericPart2(b2.blockId));if(scope==="compressed"){return renderCompressedDrilldown(activeBlocks2,state7,sort,limit,countTokens,options.meta)}const{visible,summaryTokens}=collectVisible(messages,state7,countTokens);if(scope==="uncompressed"){if(view==="messages"){return renderMessageDrilldown(visible,toolFilter,sort,limit)}return renderUncompressedRanges(visible,sort,limit,state7,countTokens,options.config,options.originalMessages)}return renderOverview(visible,summaryTokens,activeBlocks2,state7,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,state7,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 topTool=[...toolTypeMap.entries()].sort((a,b2)=>b2[1]-a[1])[0]?.[0];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,state7,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,state7,countTokens)-effectiveCompressedTokens(a,state7,countTokens)||b2.createdAt-a.createdAt);for(const block of sorted.slice(0,limit)){const topic=block.topic??"(no topic)";const eff=effectiveCompressedTokens(block,state7,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)`)}}lines.push("");lines.push(`Tip: buildStatusReport({scope:"uncompressed", view:"messages", tool:"${topTool??"bash"}"}) for per-message listing`);return lines.join("\n")}function renderUncompressedRanges(visible,sort,limit,state7,countTokens,config,original){const lines=[];const totalTokens=visible.reduce((s3,m2)=>s3+m2.tokens,0);lines.push(`UNCOMPRESSED \u2014 ${formatTokens2(totalTokens)} | ${visible.length} visible messages`);lines.push("");if(visible.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(visible)){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(state7);const protectedRefs=computeProtectedRefs(original,state7,config,countTokens);const shared=buildProjectionShared(original,state7,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:state7,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("");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`)}return lines.join("\n")}function renderMessageDrilldown(visible,toolFilter,sort,limit){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 header=toolFilter?`UNCOMPRESSED \u2014 ${toolFilter}: ${formatTokens2(totalTokens)} | ${filtered.length} msgs | ${pct(totalTokens,allTokens)}% of visible`:`UNCOMPRESSED \u2014 ${formatTokens2(totalTokens)} | ${filtered.length} msgs`;const lines=[header,`Sorted by ${sort}`,""];const shown=filtered.slice(0,limit);for(const message of shown){lines.push(` ${message.ref} (${formatTokens2(message.tokens)}) ${message.tool}`)}if(filtered.length>shown.length){lines.push("");lines.push(`${shown.length} of ${filtered.length} shown.`)}return lines.join("\n")}function renderCompressedDrilldown(blocks,state7,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,state7,countTokens)-effectiveCompressedTokens(a,state7,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,state7,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,state7,countTokens);lines.push(` ${block.blockId} (${tierLabel(block)}) ${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 header=`ACP CACHE REPORT${sessionLabel?` (${sessionLabel})`:""} \u2014 ${t.requests} requests`;if(opts?.detail==="full"){return[header,"",formatCacheReportFull(report)].join("\n")}return[header+` [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:state7,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: ${state7.blocks.length} (active ${state7.blocks.filter(b2=>b2.active).length})`);lines.push("");const folded=input.folded===true;const view=full||folded?coreMessages:prune(coreMessages,state7,{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(state7){return state7.rules??[]}function resolveRuleLimits(config){return{maxRules:config?.rules?.maxRules??DEFAULT_RULE_LIMITS.maxRules,maxRuleChars:config?.rules?.maxRuleChars??DEFAULT_RULE_LIMITS.maxRuleChars}}function highestRuleNumber(state7){let highest=0;for(const rule of state7.rules??[]){const match=RULE_ID_RE.exec(rule.id);if(match)highest=Math.max(highest,Number(match[1]))}return highest}function addRule(state7,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(state7);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(state7.nextRuleId??1,highestRuleNumber(state7)+1);const rule={id:`rule${next}`,text:trimmed};state7.rules=[...rules,rule];state7.nextRuleId=next+1;return{ok:true,rule}}function removeRule(state7,id){const rules=listRules(state7);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).`}}state7.rules=rules.filter(rule=>rule.id!==target.id);return{ok:true,rule:target}}function clearRules(state7){const count=listRules(state7).length;state7.rules=[];return{ok:true,count}}function formatRulesList(rules){return rules.map((rule,i)=>`${i+1}. [${rule.id}] ${rule.text}`).join("\n")}function parseCompressArgs(input,opts){const callId=opts?.callId;const diag={ok:false,kind:"ok",invalidItems:0};if(input===null||input===void 0){diag.kind="empty-input";return finish([],diag)}if(typeof input==="string"){return parseStringInput(input,callId,diag)}if(typeof input!=="object"||Array.isArray(input)){diag.kind="not-object";return finish([],diag)}return parseObjectValue(input,callId,diag)}function parseStringInput(raw,callId,diag){diag.rawPrefix=clampPrefix(raw,800);diag.length=raw.length;const cleaned=stripFence(raw.trim());const first=parseStringCore(cleaned,callId,diag);if(first.ranges.length===0||first.diagnostics.invalidItems>0){const normalized=normalizeSingleQuotes(cleaned);if(normalized!==void 0){const retryDiag={ok:false,kind:"ok",invalidItems:0};retryDiag.rawPrefix=diag.rawPrefix;retryDiag.length=diag.length;const retry=parseStringCore(normalized,callId,retryDiag);if(retry.ranges.length>first.ranges.length){retryDiag.quoteSalvage=true;return retry}}}return first}function parseStringCore(cleaned,callId,diag){if(cleaned===""){diag.kind="empty-input";return finish([],diag)}let value=tryParseLenient(cleaned);if(typeof value==="string"){const inner=tryParseLenient(stripFence(value));if(inner!==void 0)value=inner}if(value!==null&&typeof value==="object"&&!Array.isArray(value)){return parseObjectValue(value,callId,diag)}if(value!==void 0){diag.kind="not-object";return finish([],diag)}const entries2=salvageContentEntries(cleaned);return finishSalvage(entries2,callId,diag,looksTruncated(cleaned))}function parseObjectValue(value,callId,diag){diag.keys=Object.keys(value);const content=value["content"];if(content===void 0){const single=validateEntry(value,callId);if("range"in single){diag.kind="ok";return finish([single.range],diag)}diag.kind="missing-content";return finish([],diag)}let entries2;let salvaged=false;if(Array.isArray(content)){entries2=content}else if(typeof content==="string"){const parsed=parseContentArray(content);if(parsed===null||parsed.entries.length===0&&content.trim().length>0){const bare=stripJsonWrapperResidue(content);const entries22=splitLineEntries(bare);const{ranges:ranges2,invalid:invalid2,reasons:reasons2}=validateEntries(entries22,callId);if(ranges2.length>0){diag.invalidItems=invalid2;if(reasons2.length>0)diag.invalidReasons=reasons2;diag.kind="ok";return finish(ranges2,diag)}if(entries22.length===0||entries22.every(isHeaderlessLineEntry)){const flat=flatSingleRangeFromContent(value,content,callId);if(flat!==void 0){diag.flatSummarySalvage=true;diag.kind="ok";return finish([flat],diag)}}diag.invalidItems=invalid2;if(reasons2.length>0)diag.invalidReasons=reasons2;diag.kind=entries22.some(e=>!isHeaderlessLineEntry(e))?"no-valid-ranges":"content-not-array";return finish([],diag)}entries2=parsed.entries;salvaged=parsed.salvaged;if(parsed.quoteRepaired)diag.quoteSalvage=true}else if(content!==null&&typeof content==="object"){const obj=content;const nested=obj["ranges"];entries2=Array.isArray(nested)?nested:[obj];diag.contentSalvage=true}else{diag.kind="content-not-array";return finish([],diag)}const{ranges,invalid,reasons}=validateEntries(entries2,callId);const topTopic=stringOr(value["topic"]);const topMaxChars=value["summaryMaxChars"];const hasTopMaxChars=typeof topMaxChars==="number"&&Number.isFinite(topMaxChars);if(topTopic!==void 0||hasTopMaxChars){for(const r of ranges){if(r.topic===void 0&&topTopic!==void 0)r.topic=topTopic;if(r.summaryMaxChars===void 0&&hasTopMaxChars)r.summaryMaxChars=topMaxChars}}diag.invalidItems=invalid;if(reasons.length>0)diag.invalidReasons=reasons;diag.kind=salvaged?"truncated":ranges.length>0?"ok":"no-valid-ranges";return finish(ranges,diag)}function isHeaderlessLineEntry(e){if(typeof e!=="string")return false;const nl=e.indexOf("\n");const head=(nl===-1?e:e.slice(0,nl)).trim();return!REF_PAIR_IN_LINE.test(head)&&!SINGLE_REF_IN_LINE.test(head)}function flatSingleRangeFromContent(value,content,callId){const start=stringOr(value["startRef"])??stringOr(value["startId"])??stringOr(value["messageId"]);const end=stringOr(value["endRef"])??stringOr(value["endId"])??stringOr(value["messageId"]);if(start===void 0||end===void 0)return void 0;let summary=stringOr(value["summary"]);let topic=stringOr(value["topic"]);if(summary===void 0){const inner=tryParseLenient(stripFence(content.trim()));if(inner!==null&&typeof inner==="object"&&!Array.isArray(inner)){const o=inner;summary=stringOr(o["summary"]);if(topic===void 0)topic=stringOr(o["topic"])}if(summary===void 0){const text2=content.trim();if(text2.length>0)summary=text2}}if(summary===void 0)return void 0;const entry={startRef:start,endRef:end,summary};if(topic!==void 0)entry["topic"]=topic;const outcome=validateEntry(entry,callId);return"range"in outcome?outcome.range:void 0}function parseContentArray(s3){const cleaned=stripFence(s3.trim());const direct=parseContentArrayCore(cleaned);if(direct!==null&&direct.entries.length>0)return direct;const normalized=normalizeSingleQuotes(cleaned);if(normalized!==void 0){const retry=parseContentArrayCore(normalized);if(retry!==null&&retry.entries.length>0)return{...retry,quoteRepaired:true}}return direct}function parseContentArrayCore(s3){let value=s3===""?void 0:tryParseLenient(s3);if(typeof value==="string"){value=tryParseLenient(stripFence(value))}if(Array.isArray(value)){return{entries:value,salvaged:false}}if(value===void 0){const entries2=salvageContentEntries('{"content": '+s3);return{entries:entries2,salvaged:entries2.length>0}}return null}function finish(ranges,diag){diag.ok=ranges.length>0;return{ranges,diagnostics:diag}}function finishSalvage(entries2,callId,diag,truncatedShape){const{ranges,invalid,reasons}=validateEntries(entries2,callId);diag.invalidItems=invalid;if(reasons.length>0)diag.invalidReasons=reasons;diag.kind=entries2.length>0||truncatedShape?"truncated":"malformed-json";return finish(ranges,diag)}function coalesceLineEntries(entries2){const out=[];let headerOnlyIdx=-1;for(const e of entries2){if(typeof e==="string"){const nl=e.indexOf("\n");const head=(nl===-1?e:e.slice(0,nl)).trim();const hasRef=REF_PAIR_IN_LINE.test(head)||SINGLE_REF_IN_LINE.test(head);if(!hasRef&&headerOnlyIdx>=0){out[headerOnlyIdx]=`${out[headerOnlyIdx]}
|
|
138
138
|
${e}`;continue}out.push(e);headerOnlyIdx=hasRef&&nl===-1?out.length-1:-1}else{out.push(e);headerOnlyIdx=-1}}return out}function validateEntries(entries2,callId){const ranges=[];const reasons=[];let invalid=0;const items=coalesceLineEntries(entries2);for(let i=0;i<items.length;i++){const outcome=validateEntry(items[i],callId);if("range"in outcome)ranges.push(outcome.range);else{invalid++;reasons.push(`entry ${i}: ${outcome.reason}`)}}return{ranges,invalid,reasons}}function normalizeLineRef(raw){const lower=raw.toLowerCase();const digits=lower.slice(1);return lower[0]==="b"?`b${digits}`:`m${digits.padStart(5,"0")}`}function parseLineEntry(entry,callId){const nl=entry.indexOf("\n");const head=(nl===-1?entry:entry.slice(0,nl)).trim();const summary=(nl===-1?"":entry.slice(nl+1)).trim();const pair=REF_PAIR_IN_LINE.exec(head);let startRef;let endRef;let afterRefs;if(pair!==null){startRef=normalizeLineRef(pair[1]);endRef=normalizeLineRef(pair[2]);afterRefs=pair.index+pair[0].length}else{const single=SINGLE_REF_IN_LINE.exec(head);if(single===null)return{reason:"line entry: no mNNNNN/bN refs in header"};const rest=head.slice(single.index+single[0].length);if(UNRECOGNIZED_REF_SEP_RE.test(rest))return{reason:"line entry: refs separator not recognized \u2014 refusing to narrow a ref pair to its first ref (use -, \u2013, \u2014, \u2026, ~, .., or to)"};startRef=normalizeLineRef(single[1]);endRef=startRef;afterRefs=single.index+single[0].length}if(summary.length===0)return{reason:"line entry: missing summary after the refs header line (every entry needs refs THEN its summary text on the same or the next line; a note about an already-folded range does not belong in the batch \u2014 drop it; to rewrite an existing block use a bN..bM block-id header entry)"};const explicitTopic=head.slice(afterRefs).trim();const range={startRef,endRef,summary,topic:explicitTopic.length>0?explicitTopic:deriveTopicFromSummary(summary)};if(callId!==void 0)range.compressCallId=callId;return{range}}function deriveTopicFromSummary(summary){const heading=/^#{1,6}\s+(.+)$/m.exec(summary);const source=heading!==null?heading[1]:summary.split("\n").find(l=>l.trim().length>0)??"";const text2=source.trim().replace(/^[\u2022\-*]\s+/,"");if(text2.length===0)return void 0;return text2.length>60?clampPrefix(text2,60).trimEnd():text2}function skipWhitespace(s3,i){while(i<s3.length&&WHITESPACE_RE.test(s3[i]))i++;return i}function isQuote(ch){return ch==='"'||ch==="'"}function refsHeaderAt(s3,i){LINE_ENTRY_REFS_RE.lastIndex=i;return LINE_ENTRY_REFS_RE.test(s3)}function startsLineEntry(s3,i){if(!isQuote(s3[i]))return refsHeaderAt(s3,i);const afterQuote=skipWhitespace(s3,i+1);if(s3[afterQuote]!==",")return refsHeaderAt(s3,afterQuote);const afterComma=skipWhitespace(s3,afterQuote+1);if(!isQuote(s3[afterComma]))return refsHeaderAt(s3,afterComma);return refsHeaderAt(s3,skipWhitespace(s3,afterComma+1))}function splitLineEntries(content){const chunks=[];let chunkStart=0;let nl=content.indexOf("\n");while(nl!==-1){const runEnd=skipWhitespace(content,nl+1);if(startsLineEntry(content,runEnd)){for(let p2=nl;p2<runEnd;p2++){if(content[p2]!=="\n")continue;chunks.push(content.slice(chunkStart,p2));chunkStart=p2+1}}nl=content.indexOf("\n",runEnd)}chunks.push(content.slice(chunkStart));const parts=chunks.map(p2=>p2.trim().replace(/^(?:["']\s*,?\s*)+/,"").replace(/["']\s*$/,"")).filter(p2=>p2.length>0);return parts.length>0?parts:[content.trim()]}function stripJsonWrapperResidue(s3){let t=s3.trim();if(t.startsWith("["))t=t.replace(/^\[+\s*/,"");t=t.replace(/^"/,"");if(t.endsWith("]")){let end=t.length;while(end>0&&t[end-1]==="]")end--;t=t.slice(0,end).trimEnd()}t=t.replace(/"$/,"");return t.trim()}function validateEntry(entry,callId){if(typeof entry==="string")return parseLineEntry(entry,callId);if(entry===null||typeof entry!=="object"||Array.isArray(entry))return{reason:"not an object"};const e=entry;const start=stringOr(e["startRef"])??stringOr(e["startId"])??stringOr(e["messageId"]);const end=stringOr(e["endRef"])??stringOr(e["endId"])??stringOr(e["messageId"]);if(start===void 0||end===void 0){return{reason:"missing range bounds (need startRef/startId and endRef/endId)"}}const summary=stringOr(e["summary"]);if(summary===void 0)return{reason:"missing summary"};const range={startRef:start,endRef:end,summary};const topic=stringOr(e["topic"]);if(topic!==void 0)range.topic=topic;const maxChars=e["summaryMaxChars"];if(typeof maxChars==="number"&&Number.isFinite(maxChars))range.summaryMaxChars=maxChars;if(callId!==void 0)range.compressCallId=callId;return{range}}function stringOr(value){return typeof value==="string"&&value.length>0?value:void 0}function tryParseLenient(s3){if(s3==="")return void 0;try{return JSON.parse(s3)}catch{}const noTrailingCommas=stripTrailingCommas(s3);if(noTrailingCommas!==s3){try{return JSON.parse(noTrailingCommas)}catch{}}const fixed=escapeRawNewlinesInStrings(noTrailingCommas);if(fixed!==noTrailingCommas){try{return JSON.parse(fixed)}catch{}}const ctrlFixed=repairAtParserPositions(noTrailingCommas);if(ctrlFixed!==noTrailingCommas){try{return JSON.parse(ctrlFixed)}catch{}}return void 0}function normalizeSingleQuotes(raw){if(!raw.includes("'")||!raw.includes("{")&&!raw.includes("["))return void 0;let out="";let changed=false;let inDouble=false;let inSingle=false;for(let i=0;i<raw.length;i++){const ch=raw.charAt(i);if(inDouble){out+=ch;if(ch==="\\"&&i+1<raw.length){out+=raw.charAt(i+1);i++}else if(ch==='"'){inDouble=false}continue}if(inSingle){if(ch==="\\"&&i+1<raw.length){const next=raw.charAt(i+1);out+=next==="'"?"'":"\\"+next;i++;continue}if(ch==="'"){out+='"';inSingle=false;changed=true;continue}if(ch==='"'){out+='\\"';continue}if(ch==="\n"){out+="\\n";continue}if(ch==="\r"){out+="\\r";continue}if(ch===" "){out+="\\t";continue}out+=ch;continue}if(ch==='"'){inDouble=true;out+=ch;continue}if(ch==="'"){inSingle=true;out+='"';changed=true;continue}out+=ch}return changed?out:void 0}function stripFence(s3){if(!s3.startsWith("```"))return s3;const firstNewline=s3.indexOf("\n");if(firstNewline===-1)return s3;const bodyStart=firstNewline+1;const end=s3.lastIndexOf("```");return end>bodyStart?s3.slice(bodyStart,end).trim():s3.slice(bodyStart).trim()}function stripTrailingCommas(s3){let out="";let inString=false;let escaped=false;for(let i=0;i<s3.length;i++){const ch=s3.charAt(i);if(inString){out+=ch;if(escaped)escaped=false;else if(ch==="\\")escaped=true;else if(ch==='"')inString=false;continue}if(ch==='"'){inString=true;out+=ch;continue}if(ch===","){let j2=i+1;while(j2<s3.length&&(s3.charAt(j2)===" "||s3.charAt(j2)===" "||s3.charAt(j2)==="\n"||s3.charAt(j2)==="\r"))j2++;if(j2<s3.length&&(s3.charAt(j2)==="}"||s3.charAt(j2)==="]"))continue}out+=ch}return out}function escapeRawNewlinesInStrings(s3){let out="";let inString=false;let escaped=false;for(let i=0;i<s3.length;i++){const ch=s3.charAt(i);if(!inString){if(ch==='"')inString=true;out+=ch;continue}if(escaped){out+=ch;escaped=false;continue}if(ch==="\\"){out+=ch;escaped=true;continue}if(ch==="\n"){out+="\\n";continue}if(ch==="\r"){out+="\\r";continue}if(ch===" "){out+="\\t";continue}if(ch==='"')inString=false;out+=ch}return out}function repairAtParserPositions(s3){let cur=s3;for(let i=0;i<500;i++){let err2;try{JSON.parse(cur);return cur}catch(e){err2=e}const msg=err2 instanceof Error?err2.message:String(err2);const posMatch=/position (\d+)/.exec(msg);if(posMatch===null)return cur;const pos=Number(posMatch[1]);if(!Number.isInteger(pos)||pos<0||pos>=cur.length)return cur;if(/control character/i.test(msg)){const ch=cur.charAt(pos);let esc;if(ch==="\n")esc="\\n";else if(ch==="\r")esc="\\r";else if(ch===" ")esc="\\t";else if(ch.charCodeAt(0)<32)esc="\\u"+ch.charCodeAt(0).toString(16).padStart(4,"0");if(esc===void 0)return cur;cur=cur.slice(0,pos)+esc+cur.slice(pos+1)}else if(/Bad escaped character/i.test(msg)){const b2=cur.charAt(pos-1)==="\\"?pos-1:cur.charAt(pos)==="\\"?pos:-1;if(b2<0)return cur;cur=cur.slice(0,b2)+"\\\\"+cur.slice(b2+1)}else{return cur}}return cur}function looksTruncated(s3){let depth=0;let inString=false;let escaped=false;for(let i=0;i<s3.length;i++){const ch=s3.charAt(i);if(inString){if(escaped)escaped=false;else if(ch==="\\")escaped=true;else if(ch==='"')inString=false;continue}if(ch==='"'){inString=true;continue}if(ch==="{"||ch==="[")depth++;else if(ch==="}"||ch==="]")depth--}return depth>0||inString}function salvageContentEntries(raw){const match=/"content"\s*:\s*\[/.exec(raw);if(match===null)return[];const arrayStart=match.index+match[0].length-1;const entries2=[];let depth=0;let inString=false;let escaped=false;let entryStart=-1;for(let i=arrayStart+1;i<raw.length;i++){const ch=raw.charAt(i);if(inString){if(escaped)escaped=false;else if(ch==="\\")escaped=true;else if(ch==='"')inString=false;continue}if(ch==='"'){inString=true;continue}if(ch==="{"||ch==="["){if(depth===0&&ch==="{"&&entryStart===-1)entryStart=i;depth++;continue}if(ch==="}"||ch==="]"){depth--;if(depth<0)break;if(depth===0&&entryStart!==-1){const entrySlice=raw.slice(entryStart,i+1);entryStart=-1;const parsed=tryParseLenient(entrySlice);if(parsed!==void 0)entries2.push(parsed)}}}return entries2}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(name){return registry2.get(name)}function blockDocs(state7){return state7.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}
|
|
139
139
|
${text2}
|
|
140
140
|
</${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,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_TOOL_OPENAI,ACP_CACHE_TOOL_DESCRIPTION,ACP_CACHE_TOOL_OPENAI,ACP_TOOLS_OPENAI,DECOMPRESS_TOOL,SEARCH_CONTEXT_TOOL,ACP_STATUS_TOOL,ACP_CACHE_TOOL,ACP_TOOLS_ANTHROPIC,COMPRESS_TOOL_RESPONSES,DECOMPRESS_TOOL_RESPONSES,SEARCH_CONTEXT_TOOL_RESPONSES,ACP_STATUS_TOOL_RESPONSES,ACP_CACHE_TOOL_RESPONSES,ACP_TOOLS_RESPONSES,ACP_READONLY_TOOLS_RESPONSES,ACP_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_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,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,MAX_TRUNCATE_LATCH,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,REF_PAIR_IN_LINE,SINGLE_REF_IN_LINE,UNRECOGNIZED_REF_SEP_RE,LINE_ENTRY_REFS_RE,WHITESPACE_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_CSGXYMD3();init_chunk_4SDIPO2M();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";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 (a valid JSON string: internal quotes \\" and newlines \\n; a JSON-encoded array as that string is also accepted). 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 (a valid JSON string \u2014 internal quotes \\", newlines \\n; a JSON-encoded array as that string is also accepted for gateways that stringify arrays). 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
|
|
@@ -888,17 +888,17 @@ CREATE TABLE IF NOT EXISTS bili_meta (
|
|
|
888
888
|
ORDER BY b.ord LIMIT 1) AS firstSummary,
|
|
889
889
|
(SELECT COALESCE(SUM(CAST(JSON_EXTRACT(b.payload_json, '$.compressedTokens') AS DOUBLE)), 0)
|
|
890
890
|
FROM blocks b WHERE b.session_id = s.session_id AND b.active = 1) AS activeCompressed
|
|
891
|
-
FROM sessions s`);return rows.map(r=>({sessionId:str(r.sessionId),title:r.title!==null&&r.title!==void 0?str(r.title):void 0,hostTitle:r.hostTitle!==null&&r.hostTitle!==void 0?str(r.hostTitle):void 0,label:r.label!==null&&r.label!==void 0?str(r.label):void 0,protocol:r.protocol!==null&&r.protocol!==void 0?str(r.protocol):void 0,origin:r.origin!==null&&r.origin!==void 0?str(r.origin):void 0,updatedAt:num(r.updatedAt),statsJson:str(r.statsJson),metadataJson:str(r.metadataJson),blocks:num(r.blocks),firstTopic:nullableStr(r.firstTopic),firstSummary:nullableStr(r.firstSummary),activeCompressedTokens:num(r.activeCompressed),status:str(r.status??"active")}))}async verifyProjections(sessionId){const fail=(where,msg)=>({ok:false,error:`${sessionId}: ${where}: ${msg}`});let checks=0;const s3=await this.getSessionRow(sessionId);if(!s3)return fail("sessions","row missing");const meta=JSON.parse(s3.metaJson);checks++;if((s3.protocol??null)!==(meta.protocol??null))return fail("sessions.protocol",`${s3.protocol} vs ${String(meta.protocol)}`);if((s3.label??null)!==(meta.label??null))return fail("sessions.label",`${s3.label} vs ${String(meta.label)}`);if((s3.title??null)!==(meta.title??null))return fail("sessions.title",`${s3.title} vs ${String(meta.title)}`);if((s3.hostTitle??null)!==(meta.hostTitle??null))return fail("sessions.hostTitle",`${s3.hostTitle} vs ${String(meta.hostTitle)}`);const kstate=JSON.parse(s3.kstateJson);checks++;if(kstate.nextBlockId!==void 0||kstate.nextRunId!==void 0){return fail("sessions.kstate_json","must not carry nextBlockId/nextRunId (columns own them)")}const messages=await this.getMessages(sessionId,{includeRetired:true});const refByRaw=new Map((await this.getRefs(sessionId)).map(r=>[r.rawId,r.ref]));for(const m2 of messages){checks++;if(m2.ref!==(refByRaw.get(m2.msgId)??null)){return fail(`messages[${m2.seq}].ref`,`${String(m2.ref)} vs refs ledger ${String(refByRaw.get(m2.msgId))}`)}}for(const m2 of messages){checks++;const parsed=JSON.parse(m2.content);if(parsed.id!==m2.msgId)return fail(`messages[${m2.seq}].msg_id`,`${m2.msgId} vs ${String(parsed.id)}`);if(parsed.role!==m2.role)return fail(`messages[${m2.seq}].role`,`${m2.role} vs ${String(parsed.role)}`);if((parsed.contentType??"message")!==m2.kind){return fail(`messages[${m2.seq}].kind`,`${m2.kind} vs ${String(parsed.contentType)}`)}}const blocks=await this.getBlocks(sessionId);for(const b2 of blocks){checks++;const payload=JSON.parse(b2.payloadJson);if(payload.blockId!==b2.blockId)return fail(`blocks[${b2.blockId}].blockId`,"id mismatch");if(payload.tier!==b2.tier)return fail(`blocks[${b2.blockId}].tier`,`${b2.tier} vs ${String(payload.tier)}`);if((payload.active??true)!==b2.active){return fail(`blocks[${b2.blockId}].active`,`${b2.active} vs ${String(payload.active)}`)}}return{ok:true,checks}}async counts(){const out={};for(const t of["sessions","messages","refs","blocks","dead_refs","ccr_entries","content","checkpoints"]){const[rows]=await this.pool.query(`SELECT COUNT(*) AS n FROM ${t}`);out[t]=num(rows[0].n)}return out}async contentDedupReport(){const[rows]=await this.pool.query("SELECT COUNT(*) AS n, COALESCE(SUM(byte_len),0) AS b, COALESCE(SUM(refcount),0) AS r FROM content");return{rows:num(rows[0].n),bytesTotal:num(rows[0].b),refcounted:num(rows[0].r)}}}}});async function openBackend(name,indexPath,engine){if(name==="sqlite")return SqliteBackend.open(indexPath,engine);if(name==="mysql"){if(typeof indexPath!=="string"||indexPath.trim().length===0){throw new Error(`[storage] backend "mysql" needs a DSN \u2014 set BILI_MYSQL_DSN or storage.mysql.dsn (mysql://user:pass@host:3306/db); runs on "sqlite" until then (#3388/#3931)`)}let driver;try{driver=await import("mysql2/promise")}catch(err2){throw new Error(`[storage] mysql backend selected but the mysql2 driver cannot be loaded (${err2 instanceof Error?err2.message:String(err2)}) \u2014 installs without a node_modules tree cannot run the mysql backend; set storage.backend="sqlite" or install with dependencies (#4008)`)}const{MysqlBackend:MysqlBackend2}=await Promise.resolve().then(()=>(init_mysql(),mysql_exports));return new MysqlBackend2(indexPath,driver)}throw new Error(`[storage] unknown backend "${name}" \u2014 valid names: ${REGISTERED_BACKENDS.join(", ")}`)}function selectedBackendRaw(env,file){const envRaw=env?.BILI_STORAGE_BACKEND;const fromEnv=typeof envRaw==="string"?envRaw.trim().toLowerCase():"";if(fromEnv.length>0)return fromEnv;return typeof file==="string"?file.trim().toLowerCase():""}function resolveBackendName(env,file){const raw=selectedBackendRaw(env,file);if(raw.length>0)return REGISTERED_BACKENDS.includes(raw)?raw:"sqlite";return"sqlite"}function backendSelectionNotice(name){if(!name||name==="sqlite")return void 0;if(REGISTERED_BACKENDS.includes(name)){if(name==="mysql"){return`[storage] storage.backend="mysql" rides the StorageBackend contract (#3388/#3931) \u2014 saves ingest through the async shadow queue; replicas/ext/GC/export/fork speak the async twins; SYNC reads ride the JSON envelope (sync facades miss by design); writerOff stays sqlite-only`}return`[storage] storage.backend="${name}" is registered but not implemented \u2014 the unified store stays on "sqlite"`}return`[storage] storage.backend="${name}" is not a registered backend (valid: ${REGISTERED_BACKENDS.join(", ")}) \u2014 using "sqlite"`}var SqliteBackend,REGISTERED_BACKENDS;var init_backend=__esm({"src/storage/backend.ts"(){"use strict";init_store();SqliteBackend=class _SqliteBackend{store;constructor(store2){this.store=store2}static open(indexPath,engine){return new _SqliteBackend(UnifiedStore.open(indexPath,engine))}ingestSession(input,delta,opts){return Promise.resolve(this.store.ingestSession(input,delta,opts))}sessionCounters(sessionId){return Promise.resolve(this.store.sessionCounters(sessionId))}sessionUpdatedAt(sessionId){return Promise.resolve(this.store.sessionUpdatedAt(sessionId))}deleteSession(sessionId){return Promise.resolve(this.store.deleteSession(sessionId))}listSessionIds(){return Promise.resolve(this.store.listSessionIds())}lookupConversation(namespace,conversationId){return Promise.resolve(this.store.lookupConversation(namespace,conversationId))}listConversationBindings(namespace){return Promise.resolve(this.store.listConversationBindings(namespace))}getSessionRow(sessionId){return Promise.resolve(this.store.getSessionRow(sessionId))}liveRowCount(sessionId){return Promise.resolve(this.store.liveRowCount(sessionId))}lastLiveSeq(sessionId){return Promise.resolve(this.store.lastLiveSeq(sessionId))}seqByRaw(sessionId){return Promise.resolve(this.store.seqByRaw(sessionId))}cloneSessionRows(parentId,childId,throughSeq,initial){return Promise.resolve(this.store.cloneSessionRows(parentId,childId,throughSeq,initial))}getMessages(sessionId,opts){return Promise.resolve(this.store.getMessages(sessionId,opts))}getBlocks(sessionId,opts){return Promise.resolve(this.store.getBlocks(sessionId,opts))}sessionViewRows(sessionId){return Promise.resolve(this.store.sessionViewRows(sessionId))}getDeadRefs(sessionId){return Promise.resolve(this.store.getDeadRefs(sessionId))}getRefs(sessionId){return Promise.resolve(this.store.getRefs(sessionId))}readSnapshot(read){return this.store.readSnapshotAsync(store2=>read({getSessionRow:async id=>store2.getSessionRow(id),getMessages:async(id,opts)=>store2.getMessages(id,opts),getBlocks:async(id,opts)=>store2.getBlocks(id,opts),getDeadRefs:async id=>store2.getDeadRefs(id),getRefs:async id=>store2.getRefs(id)}))}getCcr(sessionId){return Promise.resolve(this.store.getCcr(sessionId))}getCcrEntries(sessionId){return Promise.resolve(this.store.getCcrEntries(sessionId))}ingestWatermark(sessionId){return Promise.resolve(this.store.ingestWatermark(sessionId))}tailSeqs(sessionId){return Promise.resolve(this.store.tailSeqs(sessionId))}clearIngestWatermark(sessionId){return Promise.resolve(this.store.clearIngestWatermark(sessionId))}resetAllIngestWatermarks(){return Promise.resolve(this.store.resetAllIngestWatermarks())}probeIngestBoundary(sessionId,seq){return Promise.resolve(this.store.probeIngestBoundary(sessionId,seq))}reapBlocks(sessionId,reapedIds,orphanContents2){return Promise.resolve(this.store.reapBlocks(sessionId,reapedIds,orphanContents2))}archiveSession(sessionId,opts){return Promise.resolve(this.store.archiveSession(sessionId,opts))}restoreArchived(sessionId,opts){return Promise.resolve(this.store.restoreArchived(sessionId,opts))}gc(opts){return Promise.resolve(this.store.gc(opts))}contentRefCountOfBody(needle){return Promise.resolve(this.store.contentRefCountOfBody(needle))}mediaRefCount(bytes){return Promise.resolve(this.store.mediaRefCount(bytes))}insertCheckpoint(cp2){return Promise.resolve(this.store.insertCheckpoint(cp2))}listCheckpoints(sessionId){return Promise.resolve(this.store.listCheckpoints(sessionId))}getCheckpoint(cpId){return Promise.resolve(this.store.getCheckpoint(cpId))}checkpointState(cpId){return Promise.resolve(this.store.checkpointState(cpId))}deleteCheckpoint(cpId){return Promise.resolve(this.store.deleteCheckpoint(cpId))}setSessionExt(sessionId,key2,value){return Promise.resolve(this.store.setSessionExt(sessionId,key2,value))}getSessionExt(sessionId,key2){return Promise.resolve(this.store.getSessionExt(sessionId,key2))}listSessionExt(sessionId){return Promise.resolve(this.store.listSessionExt(sessionId))}deleteSessionExt(sessionId,key2){return Promise.resolve(this.store.deleteSessionExt(sessionId,key2))}setKv(namespace,key2,value){return Promise.resolve(this.store.setKv(namespace,key2,value))}getKv(namespace,key2){return Promise.resolve(this.store.getKv(namespace,key2))}listKv(namespace,keyPrefix){return Promise.resolve(this.store.listKv(namespace,keyPrefix))}deleteKv(namespace,key2){return Promise.resolve(this.store.deleteKv(namespace,key2))}sessionSummaries(){return Promise.resolve(this.store.sessionSummaries())}webSummaryRows(){return Promise.resolve(this.store.webSummaryRows())}verifyProjections(sessionId){return Promise.resolve(this.store.verifyProjections(sessionId))}counts(){return Promise.resolve(this.store.counts())}contentDedupReport(){return Promise.resolve(this.store.contentDedupReport())}close(){return Promise.resolve(this.store.close())}};REGISTERED_BACKENDS=["sqlite","mysql"]}});import{createHash as createHash10}from"crypto";function canonicalize(value){return canonicalizeWithContext(value,void 0)}function canonicalizeWithContext(value,key2){if(Array.isArray(value))return value.map(v2=>canonicalizeWithContext(v2,void 0));if(value instanceof Map)return{__map__:[...value.entries()].map(([k2,v2])=>[k2,canonicalizeWithContext(v2,void 0)])};if(value instanceof Set)return{__set__:[...value.values()].map(v2=>canonicalizeWithContext(v2,void 0))};if(value&&typeof value==="object"){const out={};const record4=value;for(const k2 of Object.keys(record4).sort()){const v2=record4[k2];if(Object.hasOwn(DIGEST_SKIPPED_KEYS,k2))continue;out[k2]=canonicalizeWithContext(v2,k2)}return out}return canonicalScalar(value,key2)}function canonicalScalar(value,key2){if(key2==="biliVersion"&&typeof value==="string")return"__VER__";if(typeof value==="number"&&Number.isFinite(value)&&value>16e11)return"__TS__";if(typeof value==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value))return"__UUID__";return value}function isArrayIndexKey(k2){return/^(0|[1-9]\d*)$/.test(k2)&&Number(k2)<=4294967294}function sha256(s3){return createHash10("sha256").update(s3,"utf8").digest("hex")}function canonicalDigest(value){if(value===void 0||typeof value==="function"||typeof value==="symbol")return sha256(JSON.stringify(value));const hash=createHash10("sha256");const chunkSize=64*1024;let pending="";function write(text2){pending+=text2;if(pending.length>=chunkSize){hash.update(pending,"utf8");pending=""}}function writeString(text2){write('"');for(let start=0;start<text2.length;){let end=Math.min(start+chunkSize,text2.length);const last=text2.charCodeAt(end-1);if(end<text2.length&&last>=55296&&last<=56319)end--;write(JSON.stringify(text2.slice(start,end)).slice(1,-1));start=end}write('"')}function visit2(current,key2){if(Array.isArray(current)){write("[");for(let i=0;i<current.length;i++){if(i)write(",");visit2(current[i])}write("]")}else if(current instanceof Map){write('{"__map__":[');let separator="";for(const[k2,v2]of current){write(separator+"[");write(JSON.stringify(k2)??"null");write(",");visit2(v2);write("]");separator=","}write("]}")}else if(current instanceof Set){write('{"__set__":[');let separator="";for(const v2 of current){write(separator);visit2(v2);separator=","}write("]}")}else if(current&&typeof current==="object"){write("{");let separator="";const keys=Object.keys(current);const orderedKeys=keys.filter(isArrayIndexKey).sort((a,b2)=>Number(a)-Number(b2)).concat(keys.filter(k2=>!isArrayIndexKey(k2)).sort());for(const k2 of orderedKeys){if(Object.hasOwn(DIGEST_SKIPPED_KEYS,k2)||k2==="__proto__")continue;const v2=current[k2];if(v2===void 0||typeof v2==="function"||typeof v2==="symbol")continue;write(separator);writeString(k2);write(":");visit2(v2,k2);separator=","}write("}")}else{const normalized=canonicalScalar(current,key2);if(typeof normalized==="string")writeString(normalized);else write(JSON.stringify(normalized)??"null")}}visit2(value);hash.update(pending,"utf8");return hash.digest("hex")}var DIGEST_SKIPPED_KEYS;var init_canonical=__esm({"src/storage/canonical.ts"(){"use strict";DIGEST_SKIPPED_KEYS={storageMode:true,tailGaps:true}}});import path24 from"path";function hadIntegrityQuickCheckFailure(){return integrityQuickCheckFailed}function sqliteOpenFailureHint(err2){if(process.platform!=="win32")return"";if(/unable to open database file/i.test(err2)){return` (win32: the OS refused to open the file \u2014 check the Node runtime's integrity label FIRST (icacls "<path-to-node.exe>"; a Low label is refused by Windows integrity control even with correct ACLs, #5154), then antivirus/Defender locking the sessions dir, OneDrive placeholder files under the profile dir, or a path over 260 chars; if the label is clean, exclude %USERPROFILE%\\.local\\share\\billion-context\\ from antivirus real-time scanning; deleting the file will not clear a lock)`}if(/attempt to write a readonly database/i.test(err2)){return" (win32: 'attempt to write a readonly database' on an EXISTING index.db = the file opened read-only and the first write was refused by the OS \u2014 most often Windows integrity control (a process running at Low integrity cannot write Medium-labeled files, and a DSH-spawned node.exe can itself carry a Low label, e.g. after a stray 'icacls /setintegritylevel Low' \u2014 #5154), less often antivirus/Defender or another bili/dsh process holding the files; check the PROCESS side first \u2014 run icacls on your node.exe and if it reports a Low label restore it with 'icacls <path-to-node.exe> /setintegritylevel Medium' \u2014 do NOT relabel the sessions dir Low to match (that cements the mislabel and drags every file down with it); do NOT delete the file \u2014 in unified-full mode it may hold the only copy of recent session state)"}return""}function orphanContents(legacy){if(legacy.blockContents.size===0)return false;const known=new Set;for(const block of legacy.state.blocks)known.add(block.blockId);for(const id of legacy.blockContents.keys()){if(!known.has(id))return true}return false}function warnTailGaps(id,view){if((view.tailGaps??0)>0){log("warn",`[storage] ${view.tailGaps} tail pointer(s) for ${id} reference missing rows \u2014 view is shorter than the recorded tail (#4390)`)}}function shadowDigest(view){return canonicalDigest(view)}function missingSlot(){return{id:"-",role:"-",length:0,sha8:"-"}}function messageSignature(value){const json=JSON.stringify(canonicalize(value))??"null";const digest=sha256(json);const message=value;return{digest,slot:!message||typeof message!=="object"?missingSlot():{id:typeof message.id==="string"?message.id:"-",role:typeof message.role==="string"?message.role:"-",length:json.length,sha8:digest.slice(0,8)}}}function describeViewDivergence(expectView,gotView){const e=expectView??{};const g2=gotView??{};const ser=v2=>v2===void 0?null:JSON.stringify(canonicalize(v2));const keys=[];for(const k2 of[...new Set([...Object.keys(e),...Object.keys(g2)])].sort()){if(k2==="tailGaps")continue;if(ser(e[k2])!==ser(g2[k2]))keys.push(k2)}const diagnostics={keys};if(keys.includes("lastMessages")&&Array.isArray(e["lastMessages"])&&Array.isArray(g2["lastMessages"])){const et2=e["lastMessages"];const gt2=g2["lastMessages"];let index=-1;for(let i=0;i<Math.min(et2.length,gt2.length);i++){if(ser(et2[i])!==ser(gt2[i])){index=i;break}}if(index===-1&&et2.length!==gt2.length)index=Math.min(et2.length,gt2.length);if(index!==-1){const fp2=m2=>{if(!m2||typeof m2!=="object")return{id:"-",role:"-",length:0,sha8:"-"};const s3=m2;const s22=ser(m2)??"";return{id:typeof s3.id==="string"?s3.id:"-",role:typeof s3.role==="string"?s3.role:"-",length:s22.length,sha8:sha256(s22).slice(0,8)}};diagnostics.tailSlot={index,expect:fp2(index<et2.length?et2[index]:null),got:fp2(index<gt2.length?gt2[index]:null)}}}return diagnostics}function formatDriftDiagnostics(d){const parts=[`diverged: ${d.keys.length>0?d.keys.join(","):"<unknown>"}`];if(d.tailSlot){const{index,expect:ex,got:go2}=d.tailSlot;parts.push(`tail slot ${index}: expect ${ex.id}/${ex.role} len=${ex.length} sha=${ex.sha8}, got ${go2.id}/${go2.role} len=${go2.length} sha=${go2.sha8}`)}return" ["+parts.join("; ")+"]"}var integrityQuickCheckFailed,VERIFY_BATCH_SIZE,VIEW_READ_BATCH_SIZE,VERIFY_EVERY_INGESTS,DRIFT_ESCALATE_STREAK,UnifiedShadow,BatchedViewVerification;var init_shadow=__esm({"src/storage/shadow.ts"(){"use strict";init_logger();init_ingest();init_knobs();init_store();init_backend();init_canonical();init_runtime_status();init_knobs();integrityQuickCheckFailed=false;VERIFY_BATCH_SIZE=32;VIEW_READ_BATCH_SIZE=32;VERIFY_EVERY_INGESTS=20;DRIFT_ESCALATE_STREAK=3;UnifiedShadow=class _UnifiedShadow{mode;stats={ingests:0,deltaIngests:0,verifySamples:0,verifyOk:0,verifyDrift:0,imports:0,disabled:false,lastError:null,orphanSkips:0};driftedSessions=new Set;driftStreaks=new Map;frozenEnvelopeIds=new Set;sync;backend=null;queueTail=Promise.resolve();legacyLoad;dbPath;consecutiveFailures=0;ingestCounts=new Map;constructor(mode,store2,legacyLoad,backend,dbPath){this.mode=mode;this.sync=store2;if(store2===null)this.backend=backend??null;this.legacyLoad=legacyLoad;this.dbPath=dbPath??null}noteIngestFailure(err2){const prev=this.stats.lastError??"";const errStr=String(err2);this.consecutiveFailures+=1;this.stats.lastError=errStr;if(errStr!==prev){log("warn",`[storage] unified sidecar ${this.dbPath??"backend"} failed to ingest (${this.consecutiveFailures} in a row; ${errStr})${sqliteOpenFailureHint(errStr)} \u2014 the index write will be RETRIED on every subsequent save until it succeeds again (no self-disable; the JSON envelope keeps serving meanwhile)`)}}get isAsyncBackend(){return this.sync===null}get engineInfo(){return this.sync?{name:this.sync.engine,source:this.sync.engineSource}:{name:"mysql",source:"network"}}static maybeOpen(dir,env=process.env,legacyLoad,fileUnified,fileWalLimit,fileBackend){const mode=resolveStorageMode(env,fileUnified);if(mode==="legacy")return null;const walLimit=resolveStorageWalJournalSizeLimit(env,fileWalLimit);const selected=selectedBackendRaw(env,fileBackend);if(selected&&selected!=="sqlite"){const notice=backendSelectionNotice(selected);if(notice)log("warn",notice)}let store2;try{try{store2=UnifiedStore.open(`${dir}/index.db`,void 0,{walJournalSizeLimitBytes:walLimit})}catch(err2){if(!(err2 instanceof StorageIntegrityError))throw err2;log("error",`[storage] index.db FAILED its integrity quick_check (${err2.detail}) \u2014 starting WITHOUT the index (no file moved, no copy, no automatic rebuild; 2026-10-30 owner policy): back up ${path24.join(dir,"index.db")}{,-wal,-shm}, then MOVE those files aside by hand and start again \u2014 the fresh index re-imports the JSON envelopes (#4175/#4626/#4816)`);recordSidecarOpenFailure(`integrity quick_check failed: ${err2.detail}`);integrityQuickCheckFailed=true;return null}store2.resetAllIngestWatermarks()}catch(err2){const errStr=String(err2);const hint=sqliteOpenFailureHint(errStr);const tail=/no SQLite engine available/i.test(errStr)?"":hint!==""?`; ${hint}`:"; check file/OS state (CANTOPEN/readonly) or move index.db{,-wal,-shm} aside after backing up to force a fresh rebuild";log("error",`[storage] unified sidecar failed to open ${dir}/index.db (${errStr}) \u2014 REFUSING TO START (owner policy 2026-10-30: NO degradation in any case \u2014 fix the environment or set BILI_STORAGE_UNIFIED=legacy explicitly to serve JSON-only${tail})`);recordSidecarOpenFailure(errStr);throw err2}const shadow=new _UnifiedShadow(mode,store2,legacyLoad??(()=>null),void 0,path24.join(dir,"index.db"));recordSidecarInstance(shadow);const engineTag=` [engine: ${store2.engine}/${store2.engineSource}]`;const walTag=` [wal-cap: ${walLimit}]`;log("info",mode==="full"?`[storage] unified FULL mode ENABLED (storage.unified=full or BILI_STORAGE_UNIFIED=full): index.db is the load path (unified-first, legacy fallback); legacy files keep being written \u2014 unset the knob to roll back${engineTag}${walTag}`:`[storage] unified shadow mode ENABLED (storage.unified=shadow or BILI_STORAGE_UNIFIED): every session write is double-ingested into index.db and digest-reconciled${engineTag}${walTag}`);return shadow}static async openAsync(dir,env=process.env,legacyLoad,fileUnified,fileWalLimit,fileBackend,fileMysqlDsn){const backendName=resolveBackendName(env,fileBackend);if(backendName!=="mysql")return _UnifiedShadow.maybeOpen(dir,env,legacyLoad,fileUnified,fileWalLimit,fileBackend);const mode=resolveStorageMode(env,fileUnified);if(mode==="legacy")return null;const dsn=(env.BILI_MYSQL_DSN??fileMysqlDsn??"").trim();if(!dsn){const msg="[storage] storage.backend=mysql selected but no DSN is configured (BILI_MYSQL_DSN or storage.mysql.dsn) \u2014 REFUSING TO START; configure the DSN or unset storage.backend (see the CONFIGURATION storage section)";log("error",msg);recordSidecarOpenFailure("mysql backend selected without a DSN");throw new Error(msg)}try{const backend=await openBackend("mysql",dsn);await backend.init?.();const shadow=new _UnifiedShadow(mode,null,legacyLoad??(()=>null),backend);recordSidecarInstance(shadow);log("info",`[storage] unified ${mode==="full"?"FULL":"shadow"} mode on the MYSQL backend (dsn host ${dsn.replace(/:[^:@/]*@/,":***@")}) \u2014 async shadow facade; JSON envelopes keep being written (writerOff is sqlite-only)`);return shadow}catch(err2){const errStr=String(err2);log("error",`[storage] mysql backend failed to open (${errStr}) \u2014 REFUSING TO START (no degradation in any case, 2026-10-30 owner policy); fix the connection or unset storage.backend`);recordSidecarOpenFailure(errStr);throw err2}}static fromBackend(mode,backend,legacyLoad){return new _UnifiedShadow(mode,null,legacyLoad??(()=>null),backend)}get readsUnified(){return this.mode==="full"}record(record4,rawTail,liveCcr){if(this.sync===null){this.enqueueAsyncRecord(record4,rawTail,liveCcr);return}try{const loaded=this.legacyLoad(record4);if(!loaded)return;let legacy=loaded;let hasRawTail=false;if(rawTail&&rawTail.lastMessages.length>0){hasRawTail=true;legacy={...legacy,lastMessages:rawTail.lastMessages,lastMessagesFolded:rawTail.lastMessagesFolded===true}}if(liveCcr)legacy={...legacy,contentStore:liveCcr};if(!this.ingestDelta(legacy,hasRawTail)){const plan2=planIngest(legacy);this.sync.ingestSession(plan2,void 0,{completeLog:hasRawTail})}this.stats.ingests++;const count=(this.ingestCounts.get(legacy.id)??0)+1;this.ingestCounts.set(legacy.id,count);if((count-1)%VERIFY_EVERY_INGESTS===0){this.stats.verifySamples++;const sessionRow=this.sync.getSessionRow(legacy.id);if(!sessionRow)throw new Error(`session row missing after ingest: ${legacy.id}`);const verifier=new BatchedViewVerification(legacy,sessionRow,this.sync.getRefs(legacy.id),this.sync.getDeadRefs(legacy.id));for(let offset=0;;offset+=VERIFY_BATCH_SIZE){const rows=this.sync.getBlocks(legacy.id,{limit:VERIFY_BATCH_SIZE,offset});verifier.addBlocks(rows);if(rows.length<VERIFY_BATCH_SIZE)break}for(let i=0;i<verifier.messageSeqs.length;i+=VERIFY_BATCH_SIZE){verifier.addMessages(this.sync.getMessages(legacy.id,{seqs:verifier.messageSeqs.slice(i,i+VERIFY_BATCH_SIZE)}))}const verified=verifier.finish();warnTailGaps(legacy.id,verified);if(!verified.matches){this.stats.verifyDrift++;const repeat=this.driftedSessions.has(legacy.id);this.driftedSessions.add(legacy.id);const streak=(this.driftStreaks.get(legacy.id)??0)+1;this.driftStreaks.set(legacy.id,streak);if(streak===DRIFT_ESCALATE_STREAK){this.frozenEnvelopeIds.add(legacy.id);let sides="";try{const envBlocks=legacy.state.blocks.filter(b2=>b2.active).length;const idxBlocks=verified.activeBlocks;sides=` [envelope ${envBlocks} active block(s) vs index ${idxBlocks}]`}catch{}log("warn",`[storage] DIGEST DRIFT ESCALATED for ${legacy.id}: ${streak} consecutive sampled drifts \u2014 the views have stopped converging${sides}. Both legs are built in THIS process, so a persistent gap is a digest-shape mismatch first (field only one leg builds, ordering \u2014 #4392) and only then a writer: known producers are a second bili instance sharing one sessions dir (#394 anti-pattern; second-instance detection: #4177), or ONE host re-writing history slots below the ingest watermark on every save (the delta fast path skips them by design, so the sampled backstop cannot converge against a repeating trigger \u2014 #4614). Freezing THIS process's JSON envelope writes for the session until a clean sample re-admits it \u2014 the unified store keeps receiving every save (#4323)`)}this.stats.lastError=`digest drift for ${legacy.id}: unified replay != legacy load view`;this.sync.clearIngestWatermark(legacy.id);let diagnosis="";try{diagnosis=formatDriftDiagnostics(verified.diagnostics)}catch{}log("error",`[storage] unified shadow DIGEST DRIFT for ${legacy.id}: unified replay != legacy load view${repeat?" (repeat: consecutive sampled drift \u2014 the views are not converging)":""}${diagnosis} \u2014 dropped the ingest watermark, the next save re-ingests the full tail`)}else{this.stats.verifyOk++;this.driftedSessions.delete(legacy.id);this.driftStreaks.delete(legacy.id);if(this.frozenEnvelopeIds.delete(legacy.id)){log("info",`[storage] drift resolved for ${legacy.id}: clean sample re-admits the session \u2014 envelope writes resume (#4323)`)}}}this.consecutiveFailures=0}catch(err2){this.noteIngestFailure(err2)}}ingestDelta(legacy,hasRawTail){if(this.sync===null)return false;try{const mark=this.sync.ingestWatermark(legacy.id);if(!mark)return false;const boundary=this.sync.probeIngestBoundary(legacy.id,mark.seq);if(!boundary)return false;let head;if(mark.tailSeqs.length>1){const headMsgId=this.sync.headRowMsgId(legacy.id,mark.tailSeqs[0]);if(headMsgId===null)return false;head={msgId:headMsgId}}const plan2=planIngestDelta(legacy,mark.seq,mark.tailSeqs,{msgId:boundary.msgId,contentHash:boundary.contentHash},hasRawTail,head);if(!plan2)return false;const applied=this.sync.ingestSession(plan2,{trustedSeq:mark.seq,boundaryMsgId:boundary.msgId,boundaryHash:boundary.contentHash,trustedTailSeqs:mark.tailSeqs});if(applied)this.stats.deltaIngests++;return applied}catch{return false}}viewFor(id){const store2=this.sync;if(store2===null)return null;try{const unified=store2.readSnapshot(()=>{const sessionRow=store2.getSessionRow(id);if(!sessionRow)return null;const builder=new LegacyViewBuilder(sessionRow,store2.getRefs(id),store2.getDeadRefs(id));for(let offset=0;;offset+=VIEW_READ_BATCH_SIZE){const blocks=store2.getBlocks(id,{limit:VIEW_READ_BATCH_SIZE,offset});builder.addBlocks(blocks);if(blocks.length<VIEW_READ_BATCH_SIZE)break}for(let offset=0;offset<builder.messageSeqs.length;offset+=VIEW_READ_BATCH_SIZE){builder.addMessages(store2.getMessages(id,{seqs:builder.messageSeqs.slice(offset,offset+VIEW_READ_BATCH_SIZE)}))}return builder.finish()});if(!unified)return null;warnTailGaps(id,unified);return unified}catch(err2){log("warn",`[storage] unified load failed for ${id} (${String(err2)}) \u2014 falling back to the legacy file`);return null}}readResidentFieldsFor(id,fields){const store2=this.sync;if(store2===null)return null;try{return store2.readSnapshot(()=>{const header=store2.getLoadHeader(id);if(!header)return null;const result={header};if(fields.metadata){const json=store2.getMetadataJson(id);if(json===null)return null;result.metadata=JSON.parse(json)}if(fields.blockContents){const contents=new Map;for(let offset=0;;offset+=VIEW_READ_BATCH_SIZE){const page=store2.getBlockContents(id,{limit:VIEW_READ_BATCH_SIZE,offset});const blocks=Array.isArray(page)?page:[];appendBlockContents(contents,blocks);if(blocks.length<VIEW_READ_BATCH_SIZE)break}mergeOrphanBlockContents(contents,store2.getOrphansJson(id));result.blockContents=contents}return result})}catch(err2){log("warn",`[storage] resident field load failed for ${id} (${String(err2)}) \u2014 falling back to the legacy file`);return null}}envelopeFrozen(id){return this.sync!==null&&this.frozenEnvelopeIds.has(id)}activeBlockCount(id){if(this.sync===null)return null;try{return this.sync.getBlocks(id).filter(b2=>b2.active).length}catch{return null}}importRecord(record4){if(this.sync===null)return null;try{const legacy=this.legacyLoad(record4);if(!legacy)return null;this.sync.ingestSession(planIngest(legacy));this.stats.imports++;log("info",`[storage] unified import on first open: ${legacy.id}`);return legacy}catch(err2){log("warn",`[storage] unified import failed for a legacy record (${String(err2)}) \u2014 serving the legacy view`);return null}}remove(id){if(this.sync===null)return;this.ingestCounts.delete(id);this.driftStreaks.delete(id);this.frozenEnvelopeIds.delete(id);try{this.sync.deleteSession(id)}catch(err2){log("warn",`[storage] unified remove failed for ${id} (${String(err2)})`)}}createCheckpoint(cp2){if(this.sync===null)throw new Error("[storage] sync checkpoint API unavailable on a network backend \u2014 use the async twin");this.sync.insertCheckpoint(cp2)}listCheckpoints(sessionId){if(this.sync===null)return[];return this.sync.listCheckpoints(sessionId)}getCheckpoint(cpId){if(this.sync===null)return void 0;return this.sync.getCheckpoint(cpId)}checkpointState(cpId){if(this.sync===null)throw new Error("[storage] sync checkpoint API unavailable on a network backend \u2014 use the async twin");return this.sync.checkpointState(cpId)}deleteCheckpoint(cpId){if(this.sync===null)return false;return this.sync.deleteCheckpoint(cpId)}sessionUpdatedAt(sessionId){if(this.sync===null)return null;return this.sync.sessionUpdatedAt(sessionId)}sessionTipSeq(sessionId){if(this.sync===null)return 0;return(this.sync.lastLiveSeq(sessionId)??-1)+1}messagesForIds(sessionId,msgIds,includeNeighbors){if(!this.sync)return[];return this.sync.messagesForIds(sessionId,msgIds,includeNeighbors)}listSessionIds(){if(this.sync===null)return[];return this.sync.listSessionIds()}lookupConversation(namespace,conversationId){if(this.sync===null)return null;return this.sync.lookupConversation(namespace,conversationId)}sessionCounters(sessionId){if(this.sync===null)return null;return this.sync.sessionCounters(sessionId)}listConversationBindings(namespace){if(this.sync===null)return[];return this.sync.listConversationBindings(namespace)}backupInto(dstPath){if(this.sync===null)throw new Error("backup is a sqlite-store operation (VACUUM INTO)");return this.sync.backupInto(dstPath)}gc(opts){if(this.sync===null)return{archived:0,contentRowsDeleted:0};return this.sync.gc(opts)}restoreArchived(sessionId,opts){if(this.sync===null)return{ok:false,reason:"async backend \u2014 use restoreArchivedAsync"};return this.sync.restoreArchived(sessionId,opts)}archiveSession(sessionId,opts){if(this.sync===null)return{ok:false,reason:"async backend \u2014 single-session archive unavailable"};return this.sync.archiveSession(sessionId,opts)}allMessageIds(sessionId){if(this.sync===null)return[];return this.sync.allMessageIds(sessionId)}getBlocks(sessionId){if(this.sync===null)return[];return this.sync.getBlocks(sessionId)}archiveBlock(sessionId,blockId,opts){if(this.sync===null)return{ok:false,reason:"async backend \u2014 single-block archive unavailable"};return this.sync.archiveBlock(sessionId,blockId,opts)}restoreBlock(sessionId,blockId,opts){if(this.sync===null)return{ok:false,reason:"async backend \u2014 single-block restore unavailable"};return this.sync.restoreBlock(sessionId,blockId,opts)}sessionStorageStats(sessionId){if(this.sync===null)return null;return this.sync.sessionStorageStats(sessionId)}vacuum(mode){if(this.sync===null)throw new Error("[storage] sync vacuum unavailable on a network backend");return this.sync.vacuum(mode)}gcPlan(archiveAfterDays,now){if(this.sync===null)return null;return this.sync.gcPlan(archiveAfterDays,now)}activeForeignWriter(){if(this.sync===null)return null;return this.sync.activeForeignWriter()}rawMessages(sessionId,fromSeqExclusive){if(this.sync===null)return[];return this.sync.getMessages(sessionId,fromSeqExclusive!==void 0?{fromSeqExclusive}:void 0).map(m2=>({seq:m2.seq,content:m2.content,ts:m2.ts??null}))}tailSeqs(sessionId){if(this.sync===null)return null;return this.sync.tailSeqs(sessionId)}messageIdRows(sessionId){if(this.sync===null)return[];return this.sync.messageIdRows(sessionId)}uncoveredRows(sessionId,intervals){if(this.sync===null)return[];return this.sync.uncoveredRows(sessionId,intervals)}tailViewRows(sessionId){if(this.sync===null)return[];return this.sync.getMessages(sessionId)}messageContentByRefNums(sessionId,refNums){if(this.sync===null||refNums.length===0)return[];return this.sync.messageContentByRefNums(sessionId,refNums)}sessionSummaries(){if(this.sync===null)return[];return this.sync.sessionSummaries()}getCcr(sessionId){if(this.sync===null)return null;return this.sync.getCcr(sessionId)}getSessionMetadata(sessionId){if(this.sync===null)return null;try{return this.sync.getSessionMetadata(sessionId)}catch{return null}}getBlockContents(sessionId){if(this.sync===null)return null;try{return this.sync.getBlockContents(sessionId)}catch{return null}}seqByRaw(sessionId){if(this.sync===null)return null;return this.sync.seqByRaw(sessionId)}liveRowCount(sessionId){if(this.sync!==null)return this.sync.liveRowCount(sessionId);return-1}lastLiveSeq(sessionId){if(this.sync===null)return null;return this.sync.lastLiveSeq(sessionId)}cloneSessionRows(parentId,childId,throughSeq){if(this.sync!==null)return this.sync.cloneSessionRows(parentId,childId,throughSeq);return false}webSummaryRows(){if(this.sync===null)return[];return this.sync.webSummaryRows()}setSessionExt(sessionId,key2,value){if(this.sync===null)return;this.sync.setSessionExt(sessionId,key2,value)}getSessionExt(sessionId,key2){if(this.sync===null)return null;return this.sync.getSessionExt(sessionId,key2)}listSessionExt(sessionId){if(this.sync===null)return[];return this.sync.listSessionExt(sessionId)}deleteSessionExt(sessionId,key2){if(this.sync===null)return 0;return this.sync.deleteSessionExt(sessionId,key2)}setKv(namespace,key2,value){if(this.sync===null)return;this.sync.setKv(namespace,key2,value)}getKv(namespace,key2){if(this.sync===null)return null;return this.sync.getKv(namespace,key2)}listKv(namespace,keyPrefix){if(this.sync===null)return[];return this.sync.listKv(namespace,keyPrefix)}deleteKv(namespace,key2){if(this.sync===null)return 0;return this.sync.deleteKv(namespace,key2)}enqueue(work){const backend=this.backend;if(!backend)return Promise.reject(new Error("[storage] async shadow work without a backend"));const next=this.queueTail.then(work,work);this.queueTail=next.then(()=>void 0,()=>void 0);return next}enqueueAsyncRecord(record4,rawTail,liveCcr){void this.enqueue(async()=>{try{const backend=this.backend;const loaded0=this.legacyLoad(record4);if(!loaded0)return;let legacy=loaded0;let hasRawTail=false;if(rawTail&&rawTail.lastMessages.length>0){hasRawTail=true;legacy={...legacy,lastMessages:rawTail.lastMessages,lastMessagesFolded:rawTail.lastMessagesFolded===true}}if(liveCcr)legacy={...legacy,contentStore:liveCcr};let applied=false;try{const mark=await backend.ingestWatermark(legacy.id);if(mark){const boundary=await backend.probeIngestBoundary(legacy.id,mark.seq);if(boundary){const plan2=planIngestDelta(legacy,mark.seq,mark.tailSeqs,{msgId:boundary.msgId,contentHash:boundary.contentHash},hasRawTail);if(plan2){applied=await backend.ingestSession(plan2,{trustedSeq:mark.seq,boundaryMsgId:boundary.msgId,boundaryHash:boundary.contentHash,trustedTailSeqs:mark.tailSeqs});if(applied)this.stats.deltaIngests++}}}}catch{applied=false}if(!applied)await backend.ingestSession(planIngest(legacy),void 0,{completeLog:hasRawTail});this.stats.ingests++;const count=(this.ingestCounts.get(legacy.id)??0)+1;this.ingestCounts.set(legacy.id,count);if((count-1)%VERIFY_EVERY_INGESTS===0){this.stats.verifySamples++;const sessionRow=await backend.getSessionRow(legacy.id);if(!sessionRow)throw new Error(`session row missing after ingest: ${legacy.id}`);const verifier=new BatchedViewVerification(legacy,sessionRow,await backend.getRefs(legacy.id),await backend.getDeadRefs(legacy.id));for(let offset=0;;offset+=VERIFY_BATCH_SIZE){const rows=await backend.getBlocks(legacy.id,{limit:VERIFY_BATCH_SIZE,offset});verifier.addBlocks(rows);if(rows.length<VERIFY_BATCH_SIZE)break}for(let i=0;i<verifier.messageSeqs.length;i+=VERIFY_BATCH_SIZE){verifier.addMessages(await backend.getMessages(legacy.id,{seqs:verifier.messageSeqs.slice(i,i+VERIFY_BATCH_SIZE)}))}const verified=verifier.finish();warnTailGaps(legacy.id,verified);if(!verified.matches){this.stats.verifyDrift++;this.driftedSessions.add(legacy.id);this.stats.lastError=`digest drift for ${legacy.id}: unified replay != legacy load view`;await backend.clearIngestWatermark(legacy.id);log("error",`[storage] unified shadow DIGEST DRIFT for ${legacy.id}: unified replay != legacy load view \u2014 dropped the ingest watermark, the next save re-ingests the full tail`)}else{this.stats.verifyOk++;this.driftedSessions.delete(legacy.id)}}this.consecutiveFailures=0}catch(err2){this.noteIngestFailure(err2)}})}viaAsync(miss,syncValue,via){return this.sync===null?via():Promise.resolve(syncValue())}viewForAsync(id){return this.viaAsync(null,()=>this.viewFor(id),async()=>{try{const backend=this.backend;const loaded=await backend.readSnapshot(async reader=>{const sessionRow=await reader.getSessionRow(id);if(!sessionRow)return null;const builder=new LegacyViewBuilder(sessionRow,await reader.getRefs(id),await reader.getDeadRefs(id));for(let offset=0;;offset+=VIEW_READ_BATCH_SIZE){const blocks=await reader.getBlocks(id,{limit:VIEW_READ_BATCH_SIZE,offset});builder.addBlocks(blocks);if(blocks.length<VIEW_READ_BATCH_SIZE)break}for(let offset=0;offset<builder.messageSeqs.length;offset+=VIEW_READ_BATCH_SIZE){builder.addMessages(await reader.getMessages(id,{seqs:builder.messageSeqs.slice(offset,offset+VIEW_READ_BATCH_SIZE)}))}return builder.finish()});if(!loaded)return null;warnTailGaps(id,loaded);return loaded}catch(err2){log("warn",`[storage] unified load failed for ${id} (${String(err2)}) \u2014 falling back to the legacy file`);return null}})}importRecordAsync(record4){return this.viaAsync(null,()=>this.importRecord(record4),async()=>{try{const legacy=this.legacyLoad(record4);if(!legacy)return null;await this.enqueue(()=>this.backend.ingestSession(planIngest(legacy)));this.stats.imports++;log("info",`[storage] unified import on first open: ${legacy.id}`);return legacy}catch(err2){log("warn",`[storage] unified import failed for a legacy record (${String(err2)}) \u2014 serving the legacy view`);return null}})}removeAsync(id){return this.viaAsync(void 0,()=>this.remove(id),()=>this.enqueue(()=>this.backend.deleteSession(id)).then(()=>void 0))}listSessionIdsAsync(){return this.viaAsync([],()=>this.listSessionIds(),()=>this.backend.listSessionIds())}sessionSummariesAsync(){return this.viaAsync([],()=>this.sessionSummaries(),()=>this.backend.sessionSummaries())}webSummaryRowsAsync(){return this.viaAsync([],()=>this.webSummaryRows(),()=>this.backend.webSummaryRows())}lookupConversationAsync(namespace,conversationId){return this.viaAsync(null,()=>this.lookupConversation(namespace,conversationId),()=>this.backend.lookupConversation(namespace,conversationId))}listConversationBindingsAsync(namespace){return this.viaAsync([],()=>this.listConversationBindings(namespace),()=>this.backend.listConversationBindings(namespace))}sessionCountersAsync(sessionId){return this.viaAsync(null,()=>this.sessionCounters(sessionId),()=>this.backend.sessionCounters(sessionId))}sessionUpdatedAtAsync(sessionId){return this.viaAsync(null,()=>this.sessionUpdatedAt(sessionId),()=>this.backend.sessionUpdatedAt(sessionId))}sessionTipSeqAsync(sessionId){return this.viaAsync(0,()=>this.sessionTipSeq(sessionId),async()=>{const max=await this.backend.lastLiveSeq(sessionId);return(max??-1)+1})}insertCheckpointAsync(cp2){return this.viaAsync(void 0,()=>this.createCheckpoint(cp2),()=>this.enqueue(()=>this.backend.insertCheckpoint(cp2)).then(()=>void 0))}listCheckpointsAsync(sessionId){return this.viaAsync([],()=>this.listCheckpoints(sessionId),()=>this.backend.listCheckpoints(sessionId))}getCheckpointAsync(cpId){return this.viaAsync(void 0,()=>this.getCheckpoint(cpId),()=>this.backend.getCheckpoint(cpId))}checkpointStateAsync(cpId){return this.viaAsync({stateJson:"",byteLen:0},()=>this.checkpointState(cpId),()=>this.backend.checkpointState(cpId))}deleteCheckpointAsync(cpId){return this.viaAsync(false,()=>this.deleteCheckpoint(cpId),()=>this.backend.deleteCheckpoint(cpId))}gcAsync(opts){return this.viaAsync({archived:0,contentRowsDeleted:0},()=>this.gc(opts),()=>this.enqueue(()=>this.backend.gc(opts)))}restoreArchivedAsync(sessionId,opts){return this.viaAsync({ok:false,reason:"async backend"},()=>this.restoreArchived(sessionId,opts),()=>this.enqueue(()=>this.backend.restoreArchived(sessionId,opts)))}rawMessagesAsync(sessionId){return this.viaAsync([],()=>this.rawMessages(sessionId),async()=>(await this.backend.getMessages(sessionId)).map(m2=>({seq:m2.seq,content:m2.content,ts:m2.ts??null})))}tailSeqsAsync(sessionId){return this.viaAsync(null,()=>this.tailSeqs(sessionId),()=>this.backend.tailSeqs(sessionId))}tailViewRowsAsync(sessionId){return this.viaAsync([],()=>this.tailViewRows(sessionId),()=>this.backend.getMessages(sessionId))}lastLiveSeqAsync(sessionId){return this.viaAsync(null,()=>this.lastLiveSeq(sessionId),async()=>{try{return await this.backend.lastLiveSeq(sessionId)}catch(err2){log("warn",`[storage] lastLiveSeq failed for ${sessionId} (${String(err2)}) \u2014 kernel-only fork bound`);return null}})}cloneSessionRowsAsync(parentId,childId,throughSeq){return this.viaAsync(false,()=>this.cloneSessionRows(parentId,childId,throughSeq),async()=>{try{return await this.enqueue(()=>this.backend.cloneSessionRows(parentId,childId,throughSeq))}catch(err2){log("warn",`[storage] fork row clone ${parentId} -> ${childId} failed (${String(err2)}) \u2014 kernel-only fork`);return false}})}createForkAsync(parentId,child){const initial=planIngest(child);if(this.sync!==null){const throughSeq=this.sync.lastLiveSeq(parentId);return Promise.resolve(this.sync.cloneSessionRows(parentId,child.id,throughSeq??-1,initial))}return this.enqueue(async()=>{const throughSeq=await this.backend.lastLiveSeq(parentId);return this.backend.cloneSessionRows(parentId,child.id,throughSeq??-1,initial)})}getCcrAsync(sessionId){return this.viaAsync(null,()=>this.getCcr(sessionId),()=>this.backend.getCcr(sessionId))}setSessionExtAsync(sessionId,key2,value){return this.viaAsync(void 0,()=>this.setSessionExt(sessionId,key2,value),()=>this.enqueue(()=>this.backend.setSessionExt(sessionId,key2,value)).then(()=>void 0))}getSessionExtAsync(sessionId,key2){return this.viaAsync(null,()=>this.getSessionExt(sessionId,key2),()=>this.backend.getSessionExt(sessionId,key2))}listSessionExtAsync(sessionId){return this.viaAsync([],()=>this.listSessionExt(sessionId),()=>this.backend.listSessionExt(sessionId))}deleteSessionExtAsync(sessionId,key2){return this.viaAsync(0,()=>this.deleteSessionExt(sessionId,key2),()=>this.backend.deleteSessionExt(sessionId,key2))}setKvAsync(namespace,key2,value){return this.viaAsync(void 0,()=>this.setKv(namespace,key2,value),()=>this.enqueue(()=>this.backend.setKv(namespace,key2,value)).then(()=>void 0))}getKvAsync(namespace,key2){return this.viaAsync(null,()=>this.getKv(namespace,key2),()=>this.backend.getKv(namespace,key2))}listKvAsync(namespace,keyPrefix){return this.viaAsync([],()=>this.listKv(namespace,keyPrefix),()=>this.backend.listKv(namespace,keyPrefix))}deleteKvAsync(namespace,key2){return this.viaAsync(0,()=>this.deleteKv(namespace,key2),()=>this.backend.deleteKv(namespace,key2))}async closeAsync(){if(this.sync!==null){this.close();return}try{await this.queueTail}catch{}await this.backend?.close()}close(){if(this.sync===null)return;try{this.sync.close()}catch(err2){log("warn",`[storage] sidecar sqlite close failed \u2014 handle may stay locked: ${String(err2)}`)}}};BatchedViewVerification=class{constructor(legacy,session,refs,deadRefs){this.legacy=legacy;const header=loadLegacyView({session,refs,deadRefs,messages:[],blocks:[]});this.orphans=header.blockContents;this.remainingContents=new Map(completeBlockContents(legacy.blockContents,legacy.state.blocks));this.tail=JSON.parse(session.tailJson);this.messageSeqs=[...new Set([...this.tail.tailSeqs??[],...this.tail.pluginSnapshotSeqs??[]])];const withoutBulk=view=>({...view,state:{...view.state,blocks:[]},blockContents:new Map,lastMessages:view.lastMessages===void 0?void 0:[],pluginSnapshot:view.pluginSnapshot===void 0?void 0:[]});const expect=withoutBulk(legacy);const got=withoutBulk(header);if(shadowDigest(expect)!==shadowDigest(got)){this.drift=true;try{for(const key2 of describeViewDivergence(expect,got).keys)this.keys.add(key2)}catch{}}}legacy;messageSeqs;tail;remainingContents;orphans;messages=new Map;keys=new Set;drift=false;blockCount=0;activeBlocks=0;tailGaps=0;tailSlot;addBlocks(rows){for(const row of rows){const payload=JSON.parse(row.payloadJson);if(payload?.active===true)this.activeBlocks++;if(this.blockCount>=this.legacy.state.blocks.length||shadowDigest(payload)!==shadowDigest(this.legacy.state.blocks[this.blockCount]))this.changed("state");this.blockCount++;this.compareContents(row.blockId,{one:row.one===null?null:JSON.parse(row.one),full:JSON.parse(row.summary)});this.orphans.delete(row.blockId)}}addMessages(rows){for(const row of rows)this.messages.set(row.seq,messageSignature(JSON.parse(row.content)))}changed(key2){this.drift=true;this.keys.add(key2)}compareContents(id,view){if(!this.remainingContents.has(id)||shadowDigest(this.remainingContents.get(id))!==shadowDigest(view))this.changed("blockContents");this.remainingContents.delete(id)}compareMessages(key2,seqs){const expected=this.legacy[key2];let index=0;for(const seq of seqs??[]){const got=this.messages.get(seq);if(!got){this.tailGaps++;continue}const want=expected&&index<expected.length?messageSignature(expected[index]):void 0;if(!want||want.digest!==got.digest){this.changed(key2);if(key2==="lastMessages"&&expected&&!this.tailSlot){this.tailSlot={index,expect:want?.slot??missingSlot(),got:got.slot}}}index++}if(seqs&&expected&&index<expected.length){this.changed(key2);if(key2==="lastMessages"&&!this.tailSlot)this.tailSlot={index,expect:messageSignature(expected[index]).slot,got:missingSlot()}}}finish(){if(this.blockCount!==this.legacy.state.blocks.length)this.changed("state");for(const[id,view]of this.orphans)this.compareContents(id,view);if(this.remainingContents.size>0)this.changed("blockContents");this.compareMessages("lastMessages",this.tail.tailSeqs);this.compareMessages("pluginSnapshot",this.tail.pluginSnapshotSeqs);const diagnostics={keys:[...this.keys].sort()};if(this.tailSlot)diagnostics.tailSlot=this.tailSlot;return{matches:!this.drift,activeBlocks:this.activeBlocks,tailGaps:this.tailGaps,diagnostics}}}}});function isNoEngineError(errStr){return/no SQLite engine available/i.test(errStr)}function freshState(){return{requested:null,encryptionBlocked:false,persistDisabled:false,sidecar:null,sidecarOpenError:null,bootstrap:null,integrity:null,secondProcess:null,splitBrain:null,splitBrainAcks:new Map,backup:null}}function recordEngineBootstrap(outcome){state.bootstrap=outcome}function recordSidecarOpenFailure(error){state.sidecar=null;state.sidecarOpenError=error}function recordSidecarInstance(shadow){state.sidecar=shadow;state.sidecarOpenError=null}function recordRequestedMode(mode,encryptionBlocked,persistDisabled=false){state.requested=mode;state.encryptionBlocked=encryptionBlocked;state.persistDisabled=persistDisabled}function recordIntegrityOutcome(dbPath,ok,durationMs,detail){state.integrity={ok,checkedAt:Date.now(),durationMs,...detail===void 0?{}:{detail:`${dbPath}: ${detail}`}}}function recordSecondProcessOwner(pid,info){state.secondProcess={pid,at:Date.now(),benign:false,...info??{}}}function ackSplitBrainContest(sessionId){const cur=state.splitBrain;if(cur===null||cur.sessionId!==sessionId)return false;state.splitBrainAcks.set(`${cur.sessionId}|${cur.peer.instanceId}`,cur.peer.servedAt);while(state.splitBrainAcks.size>MAX_SPLIT_BRAIN_ACKS){const oldest=state.splitBrainAcks.keys().next().value;if(oldest===void 0)break;state.splitBrainAcks.delete(oldest)}state.splitBrain=null;return true}function recordBackupOutcome(lastPath,lastBytes){state.backup={lastPath,lastAt:Date.now(),lastBytes}}function pidAlive(pid){try{process.kill(pid,0);return true}catch(err2){return err2.code==="EPERM"}}function shortenError(err2){const oneLine=err2.replace(/\s+/g," ").trim();if(oneLine.length<=160)return oneLine;return`${safePrefix(oneLine,78)}\u2026${safeSuffix(oneLine,78)}`}function degradeReason(){if(state.bootstrap?.status==="unsupported-node"){return`no self-downloaded SQLite engine supports this Node.js (${state.bootstrap.detail??"unknown"})${nodeSqliteUpgradeHint()}`}if(state.sidecarOpenError){const e=shortenError(state.sidecarOpenError);if(isNoEngineError(e)){return`no SQLite engine available (node:sqlite missing, better-sqlite3 not installed)${nodeSqliteUpgradeHint()}`}if(/StorageIntegrityError|integrity quick_check failed/i.test(state.sidecarOpenError)){return`index database failed its integrity check and was left UNTOUCHED (${e}) \u2014 bili is starting WITHOUT the index (envelope-served); fix: back up index.db{,-wal,-shm}, move those files aside by hand, start again`}return`index database failed to open (${e})${sqliteOpenFailureHint(state.sidecarOpenError)}`}const b2=state.bootstrap;if(b2){switch(b2.status){case"cooldown":return`SQLite self-download blocked (${b2.detail??"unknown"}), retrying after cooldown`;case"unsupported-platform":return`unsupported platform for SQLite self-download (${b2.detail??"?"})`;case"disabled":return"SQLite self-download disabled by configuration";case"failed":return`SQLite self-download failed (${b2.detail??"unknown"})`;default:break}}return`no SQLite engine available (node:sqlite missing, better-sqlite3 not installed)${nodeSqliteUpgradeHint()}`}function cooldownState(){const now=Date.now();if(cooldownCache&&now-cooldownCache.at<COOLDOWN_CACHE_MS){return{marker:cooldownCache.marker,remainingMs:cooldownCache.marker?Math.max(0,cooldownCache.marker.atMs+COOLDOWN_MS-now):null}}const marker=readBootstrapFailureMarker();cooldownCache={at:now,marker};return{marker,remainingMs:marker?Math.max(0,marker.atMs+COOLDOWN_MS-now):null}}function getStorageRuntimeStatus(){const requested=state.requested??resolveStorageMode(process.env,fileStorageUnified());const intentionalOptOut=state.encryptionBlocked||state.persistDisabled;const sidecar=state.sidecar;const effective=requested!=="legacy"&&!intentionalOptOut&&sidecar?requested:"legacy";const degraded=requested!=="legacy"&&!intentionalOptOut&&sidecar===null;const cd=cooldownState();const sp=state.secondProcess;if(sp!==null&&!pidAlive(sp.pid)){state.secondProcess=null;log("info",`[storage] second-process pid ${sp.pid} has exited \u2014 stale warning cleared`)}const sb=state.splitBrain;if(sb!==null&&splitBrainEvidenceCheck!==null&&splitBrainEvidenceCheck(sb)===false){state.splitBrain=null;log("info",`[split-brain] session ${sb.sessionId} notice cleared \u2014 peer ${sb.peer.instanceId} (pid ${sb.peer.pid}) no longer contests it`)}return{requested,effective,degraded,intentionalOptOut,reason:degraded?degradeReason():null,engine:sidecar?sidecar.engineInfo:state.sidecarOpenError!==null&&!isNoEngineError(state.sidecarOpenError)?resolvedSqliteEngineInfo():null,bootstrap:state.bootstrap?.status??null,bootstrapFailure:cd.marker,cooldownRemainingMs:cd.remainingMs,sidecarDisabled:false,sidecarLastError:sidecar?.stats.lastError??null,indexDbOpenError:state.sidecarOpenError,verifyDrift:sidecar?.stats.verifyDrift??0,driftedSessions:sidecar?.driftedSessions.size??0,integrity:state.integrity,secondProcess:state.secondProcess,splitBrain:state.splitBrain,backup:state.backup,frozenEnvelopeSessions:sidecar?.frozenEnvelopeIds.size??0}}function splitBrainWire(cur){if(cur===null)return null;const strip=x=>({instanceId:x.instanceId,pid:x.pid,origin:x.origin,version:x.version,lane:x.lane});return{sessionId:cur.sessionId,title:cur.title,self:strip(cur.self),peer:strip(cur.peer),at:cur.at}}function storageStatusWire(){const st2=getStorageRuntimeStatus();return{requested:st2.requested,effective:st2.effective,degraded:st2.degraded,intentionalOptOut:st2.intentionalOptOut,reason:st2.reason,engine:st2.engine,bootstrap:st2.bootstrap,bootstrapFailure:st2.bootstrapFailure,cooldownRemainingMs:st2.cooldownRemainingMs,sidecarDisabled:st2.sidecarDisabled,verifyDrift:st2.verifyDrift,driftedSessions:st2.driftedSessions,integrity:st2.integrity,secondProcess:st2.secondProcess,splitBrain:splitBrainWire(st2.splitBrain),backup:st2.backup,frozenEnvelopeSessions:st2.frozenEnvelopeSessions}}function storageDiagnosticsLines(ctx){const st2=getStorageRuntimeStatus();const env=process.env;const fileUnified=fileStorageUnified();const fileJsonWriter=fileStorageJsonWriter();const fileAutoDownload=fileStorageAutoDownload();const fileWalLimit=fileStorageWalJournalSizeLimit();const lines=["--- storage ---",`requested mode: ${st2.requested}`,`effective mode: ${st2.effective}${st2.intentionalOptOut?" (BILI_ENCRYPTION_KEY opt-out \u2014 intentional)":""}`,...st2.degraded&&st2.reason?[`degrade reason: ${st2.reason}`]:[],`engine: ${st2.engine?`${st2.engine.name}/${st2.engine.source}${state.sidecarOpenError!==null&&!isNoEngineError(state.sidecarOpenError)?" (resolved, but index.db open failed \u2014 see degrade reason)":""}`:"none"}`,`engine bootstrap: ${st2.bootstrap??"not run"}`,...st2.bootstrapFailure?[`bootstrap failure marker: at=${new Date(st2.bootstrapFailure.atMs).toISOString()} reason="${st2.bootstrapFailure.reason}"${st2.cooldownRemainingMs?` (cooldown ~${Math.round(st2.cooldownRemainingMs/6e4)}m remaining, until ${new Date(st2.bootstrapFailure.atMs+COOLDOWN_MS).toISOString()})`:""}`,`force immediate retry: delete ${bootstrapFailureMarkerPath()} and restart`]:[],`BILI_STORAGE_UNIFIED: ${env.BILI_STORAGE_UNIFIED??"(unset)"}`,`storage.unified (config file): ${fileUnified??"(unset)"}`,`BILI_STORAGE_JSON_WRITER: ${env.BILI_STORAGE_JSON_WRITER??"(unset)"}`,`storage.jsonWriter (config file): ${fileJsonWriter??"(unset)"}`,`BILI_SQLITE_AUTO_DOWNLOAD: ${env.BILI_SQLITE_AUTO_DOWNLOAD??"(unset)"}`,`storage.sqliteAutoDownload (config file): ${fileAutoDownload??"(unset)"}`,`BILI_STORAGE_WAL_JOURNAL_SIZE_LIMIT_BYTES: ${env.BILI_STORAGE_WAL_JOURNAL_SIZE_LIMIT_BYTES??"(unset)"}`,`storage.walJournalSizeLimitBytes (config file): ${fileWalLimit??"(unset)"}`,`BILI_ENCRYPTION_KEY set: ${env.BILI_ENCRYPTION_KEY!==void 0&&env.BILI_ENCRYPTION_KEY!==""?"yes":"no"}`,`sessions on disk: ${ctx.sessions}`];if(ctx.storageLogLines.length>0){lines.push("last [storage] log lines:");lines.push(...ctx.storageLogLines.map(l=>` ${l}`))}return lines}var state,MAX_SPLIT_BRAIN_ACKS,splitBrainEvidenceCheck,COOLDOWN_CACHE_MS,cooldownCache;var init_runtime_status=__esm({"src/storage/runtime-status.ts"(){"use strict";init_engine_bootstrap();init_knobs();init_logger();init_text_safe();init_driver();init_shadow();state=freshState();MAX_SPLIT_BRAIN_ACKS=64;splitBrainEvidenceCheck=null;COOLDOWN_CACHE_MS=3e4;cooldownCache=null}});var require_constants6=__commonJS({"node_modules/ws/lib/constants.js"(exports,module){"use strict";var BINARY_TYPES=["nodebuffer","arraybuffer","fragments"];var hasBlob=typeof Blob!=="undefined";if(hasBlob)BINARY_TYPES.push("blob");module.exports={BINARY_TYPES,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}});var require_buffer_util=__commonJS({"node_modules/ws/lib/buffer-util.js"(exports,module){"use strict";var{EMPTY_BUFFER}=require_constants6();var FastBuffer=Buffer[Symbol.species];function concat(list,totalLength){if(list.length===0)return EMPTY_BUFFER;if(list.length===1)return list[0];const target=Buffer.allocUnsafe(totalLength);let offset=0;for(let i=0;i<list.length;i++){const buf=list[i];target.set(buf,offset);offset+=buf.length}if(offset<totalLength){return new FastBuffer(target.buffer,target.byteOffset,offset)}return target}function _mask(source,mask,output,offset,length){for(let i=0;i<length;i++){output[offset+i]=source[i]^mask[i&3]}}function _unmask(buffer,mask){for(let i=0;i<buffer.length;i++){buffer[i]^=mask[i&3]}}function toArrayBuffer(buf){if(buf.length===buf.buffer.byteLength){return buf.buffer}return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.length)}function toBuffer(data){toBuffer.readOnly=true;if(Buffer.isBuffer(data))return data;let buf;if(data instanceof ArrayBuffer){buf=new FastBuffer(data)}else if(ArrayBuffer.isView(data)){buf=new FastBuffer(data.buffer,data.byteOffset,data.byteLength)}else{buf=Buffer.from(data);toBuffer.readOnly=false}return buf}module.exports={concat,mask:_mask,toArrayBuffer,toBuffer,unmask:_unmask};if(!process.env.WS_NO_BUFFER_UTIL){try{const bufferUtil=__require("bufferutil");module.exports.mask=function(source,mask,output,offset,length){if(length<48)_mask(source,mask,output,offset,length);else bufferUtil.mask(source,mask,output,offset,length)};module.exports.unmask=function(buffer,mask){if(buffer.length<32)_unmask(buffer,mask);else bufferUtil.unmask(buffer,mask)}}catch(e){}}}});var require_limiter=__commonJS({"node_modules/ws/lib/limiter.js"(exports,module){"use strict";var kDone=Symbol("kDone");var kRun=Symbol("kRun");var Limiter=class{constructor(concurrency){this[kDone]=()=>{this.pending--;this[kRun]()};this.concurrency=concurrency||Infinity;this.jobs=[];this.pending=0}add(job){this.jobs.push(job);this[kRun]()}[kRun](){if(this.pending===this.concurrency)return;if(this.jobs.length){const job=this.jobs.shift();this.pending++;job(this[kDone])}}};module.exports=Limiter}});var require_permessage_deflate2=__commonJS({"node_modules/ws/lib/permessage-deflate.js"(exports,module){"use strict";var zlib2=__require("zlib");var bufferUtil=require_buffer_util();var Limiter=require_limiter();var{kStatusCode}=require_constants6();var FastBuffer=Buffer[Symbol.species];var TRAILER=Buffer.from([0,0,255,255]);var kPerMessageDeflate=Symbol("permessage-deflate");var kTotalLength=Symbol("total-length");var kCallback=Symbol("callback");var kBuffers=Symbol("buffers");var kError=Symbol("error");var zlibLimiter;var PerMessageDeflate2=class{constructor(options){this._options=options||{};this._threshold=this._options.threshold!==void 0?this._options.threshold:1024;this._maxPayload=this._options.maxPayload|0;this._isServer=!!this._options.isServer;this._deflate=null;this._inflate=null;this.params=null;if(!zlibLimiter){const concurrency=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){const params={};if(this._options.serverNoContextTakeover){params.server_no_context_takeover=true}if(this._options.clientNoContextTakeover){params.client_no_context_takeover=true}if(this._options.serverMaxWindowBits){params.server_max_window_bits=this._options.serverMaxWindowBits}if(this._options.clientMaxWindowBits){params.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits==null){params.client_max_window_bits=true}return params}accept(configurations){configurations=this.normalizeParams(configurations);this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations);return this.params}cleanup(){if(this._inflate){this._inflate.close();this._inflate=null}if(this._deflate){const callback=this._deflate[kCallback];this._deflate.close();this._deflate=null;if(callback){callback(new Error("The deflate stream was closed while data was being processed"))}}}acceptAsServer(offers){const opts=this._options;const accepted=offers.find(params=>{if(opts.serverNoContextTakeover===false&¶ms.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===false||typeof opts.serverMaxWindowBits==="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits==="number"&&(typeof params.client_max_window_bits==="number"?opts.clientMaxWindowBits>params.client_max_window_bits:!params.client_max_window_bits)){return false}return true});if(!accepted){throw new Error("None of the extension offers can be accepted")}if(opts.serverNoContextTakeover){accepted.server_no_context_takeover=true}if(opts.clientNoContextTakeover){accepted.client_no_context_takeover=true}if(typeof opts.serverMaxWindowBits==="number"){accepted.server_max_window_bits=opts.serverMaxWindowBits}if(typeof opts.clientMaxWindowBits==="number"){accepted.client_max_window_bits=opts.clientMaxWindowBits}else if(accepted.client_max_window_bits===true||opts.clientMaxWindowBits===false){delete accepted.client_max_window_bits}return accepted}acceptAsClient(response){const params=response[0];if(this._options.clientNoContextTakeover===false&¶ms.client_no_context_takeover){throw new Error('Unexpected parameter "client_no_context_takeover"')}if(!params.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number"){params.client_max_window_bits=this._options.clientMaxWindowBits}}else if(this._options.clientMaxWindowBits===false||typeof this._options.clientMaxWindowBits==="number"&¶ms.client_max_window_bits>this._options.clientMaxWindowBits){throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}return params}normalizeParams(configurations){configurations.forEach(params=>{Object.keys(params).forEach(key2=>{let value=params[key2];if(value.length>1){throw new Error(`Parameter "${key2}" must have only a single value`)}value=value[0];if(key2==="client_max_window_bits"){if(value!==true){const num7=+value;if(!Number.isInteger(num7)||num7<8||num7>15){throw new TypeError(`Invalid value for parameter "${key2}": ${value}`)}value=num7}else if(!this._isServer){throw new TypeError(`Invalid value for parameter "${key2}": ${value}`)}}else if(key2==="server_max_window_bits"){const num7=+value;if(!Number.isInteger(num7)||num7<8||num7>15){throw new TypeError(`Invalid value for parameter "${key2}": ${value}`)}value=num7}else if(key2==="client_no_context_takeover"||key2==="server_no_context_takeover"){if(value!==true){throw new TypeError(`Invalid value for parameter "${key2}": ${value}`)}}else{throw new Error(`Unknown parameter "${key2}"`)}params[key2]=value})});return configurations}decompress(data,fin,callback){zlibLimiter.add(done=>{this._decompress(data,fin,(err2,result)=>{done();callback(err2,result)})})}compress(data,fin,callback){zlibLimiter.add(done=>{this._compress(data,fin,(err2,result)=>{done();callback(err2,result)})})}_decompress(data,fin,callback){const endpoint=this._isServer?"client":"server";if(!this._inflate){const key2=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key2]!=="number"?zlib2.Z_DEFAULT_WINDOWBITS:this.params[key2];this._inflate=zlib2.createInflateRaw({...this._options.zlibInflateOptions,windowBits});this._inflate[kPerMessageDeflate]=this;this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];this._inflate.on("error",inflateOnError);this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback;this._inflate.write(data);if(fin)this._inflate.write(TRAILER);this._inflate.flush(()=>{const err2=this._inflate[kError];if(err2){this._inflate.close();this._inflate=null;callback(err2);return}const data2=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);if(this._inflate._readableState.endEmitted){this._inflate.close();this._inflate=null}else{this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._inflate.reset()}}callback(null,data2)})}_compress(data,fin,callback){const endpoint=this._isServer?"server":"client";if(!this._deflate){const key2=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key2]!=="number"?zlib2.Z_DEFAULT_WINDOWBITS:this.params[key2];this._deflate=zlib2.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits});this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback;this._deflate.write(data);this._deflate.flush(zlib2.Z_SYNC_FLUSH,()=>{if(!this._deflate){return}let data2=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);if(fin){data2=new FastBuffer(data2.buffer,data2.byteOffset,data2.length-4)}this._deflate[kCallback]=null;this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._deflate.reset()}callback(null,data2)})}};module.exports=PerMessageDeflate2;function deflateOnData(chunk){this[kBuffers].push(chunk);this[kTotalLength]+=chunk.length}function inflateOnData(chunk){this[kTotalLength]+=chunk.length;if(this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded");this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";this[kError][kStatusCode]=1009;this.removeListener("data",inflateOnData);this.reset()}function inflateOnError(err2){this[kPerMessageDeflate]._inflate=null;if(this[kError]){this[kCallback](this[kError]);return}err2[kStatusCode]=1007;this[kCallback](err2)}}});var require_validation=__commonJS({"node_modules/ws/lib/validation.js"(exports,module){"use strict";var{isUtf8}=__require("buffer");var{hasBlob}=require_constants6();var tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(code){return code>=1e3&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3e3&&code<=4999}function _isValidUTF8(buf){const len=buf.length;let i=0;while(i<len){if((buf[i]&128)===0){i++}else if((buf[i]&224)===192){if(i+1===len||(buf[i+1]&192)!==128||(buf[i]&254)===192){return false}i+=2}else if((buf[i]&240)===224){if(i+2>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||buf[i]===224&&(buf[i+1]&224)===128||buf[i]===237&&(buf[i+1]&224)===160){return false}i+=3}else if((buf[i]&248)===240){if(i+3>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||(buf[i+3]&192)!==128||buf[i]===240&&(buf[i+1]&240)===128||buf[i]===244&&buf[i+1]>143||buf[i]>244){return false}i+=4}else{return false}}return true}function isBlob(value){return hasBlob&&typeof value==="object"&&typeof value.arrayBuffer==="function"&&typeof value.type==="string"&&typeof value.stream==="function"&&(value[Symbol.toStringTag]==="Blob"||value[Symbol.toStringTag]==="File")}module.exports={isBlob,isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8){module.exports.isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)}}else if(!process.env.WS_NO_UTF_8_VALIDATE){try{const isValidUTF8=__require("utf-8-validate");module.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch(e){}}}});var require_receiver2=__commonJS({"node_modules/ws/lib/receiver.js"(exports,module){"use strict";var{Writable}=__require("stream");var PerMessageDeflate2=require_permessage_deflate2();var{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants6();var{concat,toArrayBuffer,unmask}=require_buffer_util();var{isValidStatusCode,isValidUTF8}=require_validation();var FastBuffer=Buffer[Symbol.species];var GET_INFO=0;var GET_PAYLOAD_LENGTH_16=1;var GET_PAYLOAD_LENGTH_64=2;var GET_MASK=3;var GET_DATA=4;var INFLATING=5;var DEFER_EVENT=6;var Receiver2=class extends Writable{constructor(options={}){super();this._allowSynchronousEvents=options.allowSynchronousEvents!==void 0?options.allowSynchronousEvents:true;this._binaryType=options.binaryType||BINARY_TYPES[0];this._extensions=options.extensions||{};this._isServer=!!options.isServer;this._maxBufferedChunks=options.maxBufferedChunks|0;this._maxFragments=options.maxFragments|0;this._maxPayload=options.maxPayload|0;this._skipUTF8Validation=!!options.skipUTF8Validation;this[kWebSocket]=void 0;this._bufferedBytes=0;this._buffers=[];this._compressed=false;this._payloadLength=0;this._mask=void 0;this._fragmented=0;this._masked=false;this._fin=false;this._opcode=0;this._totalPayloadLength=0;this._messageLength=0;this._numFragments=0;this._fragments=[];this._errored=false;this._loop=false;this._state=GET_INFO}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){cb(this.createError(RangeError,"Too many buffered chunks",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=chunk.length;this._buffers.push(chunk);this.startLoop(cb)}consume(n){this._bufferedBytes-=n;if(n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){const buf=this._buffers[0];this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n);return new FastBuffer(buf.buffer,buf.byteOffset,n)}const dst=Buffer.allocUnsafe(n);do{const buf=this._buffers[0];const offset=dst.length-n;if(n>=buf.length){dst.set(this._buffers.shift(),offset)}else{dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset);this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n)}n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=true;do{switch(this._state){case GET_INFO:this.getInfo(cb);break;case GET_PAYLOAD_LENGTH_16:this.getPayloadLength16(cb);break;case GET_PAYLOAD_LENGTH_64:this.getPayloadLength64(cb);break;case GET_MASK:this.getMask();break;case GET_DATA:this.getData(cb);break;case INFLATING:case DEFER_EVENT:this._loop=false;return}}while(this._loop);if(!this._errored)cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=false;return}const buf=this.consume(2);if((buf[0]&48)!==0){const error=this.createError(RangeError,"RSV2 and RSV3 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error);return}const compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate2.extensionName]){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}this._fin=(buf[0]&128)===128;this._opcode=buf[0]&15;this._payloadLength=buf[1]&127;if(this._opcode===0){if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(!this._fragmented){const error=this.createError(RangeError,"invalid opcode 0",true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const error=this.createError(RangeError,"FIN must be set",true,1002,"WS_ERR_EXPECTED_FIN");cb(error);return}if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){const error=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error);return}}else{const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;this._masked=(buf[1]&128)===128;if(this._isServer){if(!this._masked){const error=this.createError(RangeError,"MASK must be set",true,1002,"WS_ERR_EXPECTED_MASK");cb(error);return}}else if(this._masked){const error=this.createError(RangeError,"MASK must be clear",true,1002,"WS_ERR_UNEXPECTED_MASK");cb(error);return}if(this._payloadLength===126)this._state=GET_PAYLOAD_LENGTH_16;else if(this._payloadLength===127)this._state=GET_PAYLOAD_LENGTH_64;else this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=false;return}this._payloadLength=this.consume(2).readUInt16BE(0);this.haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=false;return}const buf=this.consume(8);const num7=buf.readUInt32BE(0);if(num7>Math.pow(2,53-32)-1){const error=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",false,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error);return}this._payloadLength=num7*Math.pow(2,32)+buf.readUInt32BE(4);this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8){this._totalPayloadLength+=this._payloadLength;if(this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}}if(this._masked)this._state=GET_MASK;else this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=false;return}this._mask=this.consume(4);this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=false;return}data=this.consume(this._payloadLength);if(this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0){unmask(data,this._mask)}}if(this._opcode>7){this.controlMessage(data,cb);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){const error=this.createError(RangeError,"Too many message fragments",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error);return}if(this._compressed){this._state=INFLATING;this.decompress(data,cb);return}if(data.length){this._messageLength=this._totalPayloadLength;this._fragments.push(data)}this.dataMessage(cb)}decompress(data,cb){const perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];perMessageDeflate.decompress(data,this._fin,(err2,buf)=>{if(err2)return cb(err2);if(buf.length){this._messageLength+=buf.length;if(this._messageLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}this._fragments.push(buf)}this.dataMessage(cb);if(this._state===GET_INFO)this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=GET_INFO;return}const messageLength=this._messageLength;const fragments=this._fragments;this._totalPayloadLength=0;this._messageLength=0;this._fragmented=0;this._numFragments=0;this._fragments=[];if(this._opcode===2){let data;if(this._binaryType==="nodebuffer"){data=concat(fragments,messageLength)}else if(this._binaryType==="arraybuffer"){data=toArrayBuffer(concat(fragments,messageLength))}else if(this._binaryType==="blob"){data=new Blob(fragments)}else{data=fragments}if(this._allowSynchronousEvents){this.emit("message",data,true);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",data,true);this._state=GET_INFO;this.startLoop(cb)})}}else{const buf=concat(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}if(this._state===INFLATING||this._allowSynchronousEvents){this.emit("message",buf,false);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",buf,false);this._state=GET_INFO;this.startLoop(cb)})}}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0){this._loop=false;this.emit("conclude",1005,EMPTY_BUFFER);this.end()}else{const code=data.readUInt16BE(0);if(!isValidStatusCode(code)){const error=this.createError(RangeError,`invalid status code ${code}`,true,1002,"WS_ERR_INVALID_CLOSE_CODE");cb(error);return}const buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._loop=false;this.emit("conclude",code,buf);this.end()}this._state=GET_INFO;return}if(this._allowSynchronousEvents){this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO;this.startLoop(cb)})}}createError(ErrorCtor,message,prefix,statusCode,errorCode){this._loop=false;this._errored=true;const err2=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message}`:message);Error.captureStackTrace(err2,this.createError);err2.code=errorCode;err2[kStatusCode]=statusCode;return err2}};module.exports=Receiver2}});var require_sender2=__commonJS({"node_modules/ws/lib/sender.js"(exports,module){"use strict";var{Duplex}=__require("stream");var{randomFillSync}=__require("crypto");var{types:{isUint8Array}}=__require("util");var PerMessageDeflate2=require_permessage_deflate2();var{EMPTY_BUFFER,kWebSocket,NOOP}=require_constants6();var{isBlob,isValidStatusCode}=require_validation();var{mask:applyMask,toBuffer}=require_buffer_util();var kByteLength=Symbol("kByteLength");var maskBuffer=Buffer.alloc(4);var RANDOM_POOL_SIZE=8*1024;var randomPool;var randomPoolPointer=RANDOM_POOL_SIZE;var DEFAULT=0;var DEFLATING=1;var GET_BLOB_DATA=2;var Sender2=class _Sender{constructor(socket,extensions,generateMask){this._extensions=extensions||{};if(generateMask){this._generateMask=generateMask;this._maskBuffer=Buffer.alloc(4)}this._socket=socket;this._firstFragment=true;this._compress=false;this._bufferedBytes=0;this._queue=[];this._state=DEFAULT;this.onerror=NOOP;this[kWebSocket]=void 0}static frame(data,options){let mask;let merge=false;let offset=2;let skipMasking=false;if(options.mask){mask=options.maskBuffer||maskBuffer;if(options.generateMask){options.generateMask(mask)}else{if(randomPoolPointer===RANDOM_POOL_SIZE){if(randomPool===void 0){randomPool=Buffer.alloc(RANDOM_POOL_SIZE)}randomFillSync(randomPool,0,RANDOM_POOL_SIZE);randomPoolPointer=0}mask[0]=randomPool[randomPoolPointer++];mask[1]=randomPool[randomPoolPointer++];mask[2]=randomPool[randomPoolPointer++];mask[3]=randomPool[randomPoolPointer++]}skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0;offset=6}let dataLength;if(typeof data==="string"){if((!options.mask||skipMasking)&&options[kByteLength]!==void 0){dataLength=options[kByteLength]}else{data=Buffer.from(data);dataLength=data.length}}else{dataLength=data.length;merge=options.mask&&options.readOnly&&!skipMasking}let payloadLength=dataLength;if(dataLength>=65536){offset+=8;payloadLength=127}else if(dataLength>125){offset+=2;payloadLength=126}const target=Buffer.allocUnsafe(merge?dataLength+offset:offset);target[0]=options.fin?options.opcode|128:options.opcode;if(options.rsv1)target[0]|=64;target[1]=payloadLength;if(payloadLength===126){target.writeUInt16BE(dataLength,2)}else if(payloadLength===127){target[2]=target[3]=0;target.writeUIntBE(dataLength,4,6)}if(!options.mask)return[target,data];target[1]|=128;target[offset-4]=mask[0];target[offset-3]=mask[1];target[offset-2]=mask[2];target[offset-1]=mask[3];if(skipMasking)return[target,data];if(merge){applyMask(data,mask,target,offset,dataLength);return[target]}applyMask(data,mask,data,0,dataLength);return[target,data]}close(code,data,mask,cb){let buf;if(code===void 0){buf=EMPTY_BUFFER}else if(typeof code!=="number"||!isValidStatusCode(code)){throw new TypeError("First argument must be a valid error code number")}else if(data===void 0||!data.length){buf=Buffer.allocUnsafe(2);buf.writeUInt16BE(code,0)}else{const length=Buffer.byteLength(data);if(length>123){throw new RangeError("The message must not be greater than 123 bytes")}buf=Buffer.allocUnsafe(2+length);buf.writeUInt16BE(code,0);if(typeof data==="string"){buf.write(data,2)}else if(isUint8Array(data)){buf.set(data,2)}else{throw new TypeError("Second argument must be a string or a Uint8Array")}}const options={[kByteLength]:buf.length,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:false,rsv1:false};if(this._state!==DEFAULT){this.enqueue([this.dispatch,buf,false,options,cb])}else{this.sendFrame(_Sender.frame(buf,options),cb)}}ping(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(_Sender.frame(data,options),cb)}}pong(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(_Sender.frame(data,options),cb)}}send(data,options,cb){const perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];let opcode=options.binary?2:1;let rsv1=options.compress;let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(this._firstFragment){this._firstFragment=false;if(rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"]){rsv1=byteLength>=perMessageDeflate._threshold}this._compress=rsv1}else{rsv1=false;opcode=0}if(options.fin)this._firstFragment=true;const opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,this._compress,opts,cb])}else{this.getBlobData(data,this._compress,opts,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,this._compress,opts,cb])}else{this.dispatch(data,this._compress,opts,cb)}}getBlobData(blob,compress,options,cb){this._bufferedBytes+=options[kByteLength];this._state=GET_BLOB_DATA;blob.arrayBuffer().then(arrayBuffer=>{if(this._socket.destroyed){const err2=new Error("The socket was closed while the blob was being read");process.nextTick(callCallbacks,this,err2,cb);return}this._bufferedBytes-=options[kByteLength];const data=toBuffer(arrayBuffer);if(!compress){this._state=DEFAULT;this.sendFrame(_Sender.frame(data,options),cb);this.dequeue()}else{this.dispatch(data,compress,options,cb)}}).catch(err2=>{process.nextTick(onError,this,err2,cb)})}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(_Sender.frame(data,options),cb);return}const perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];this._bufferedBytes+=options[kByteLength];this._state=DEFLATING;perMessageDeflate.compress(data,options.fin,(_2,buf)=>{if(this._socket.destroyed){const err2=new Error("The socket was closed while data was being compressed");callCallbacks(this,err2,cb);return}this._bufferedBytes-=options[kByteLength];this._state=DEFAULT;options.readOnly=false;this.sendFrame(_Sender.frame(buf,options),cb);this.dequeue()})}dequeue(){while(this._state===DEFAULT&&this._queue.length){const params=this._queue.shift();this._bufferedBytes-=params[3][kByteLength];Reflect.apply(params[0],this,params.slice(1))}}enqueue(params){this._bufferedBytes+=params[3][kByteLength];this._queue.push(params)}sendFrame(list,cb){if(list.length===2){this._socket.cork();this._socket.write(list[0]);this._socket.write(list[1],cb);this._socket.uncork()}else{this._socket.write(list[0],cb)}}};module.exports=Sender2;function callCallbacks(sender,err2,cb){if(typeof cb==="function")cb(err2);for(let i=0;i<sender._queue.length;i++){const params=sender._queue[i];const callback=params[params.length-1];if(typeof callback==="function")callback(err2)}}function onError(sender,err2,cb){callCallbacks(sender,err2,cb);sender.onerror(err2)}}});var require_event_target=__commonJS({"node_modules/ws/lib/event-target.js"(exports,module){"use strict";var{kForOnEventAttribute,kListener}=require_constants6();var kCode=Symbol("kCode");var kData=Symbol("kData");var kError=Symbol("kError");var kMessage=Symbol("kMessage");var kReason=Symbol("kReason");var kTarget=Symbol("kTarget");var kType=Symbol("kType");var kWasClean=Symbol("kWasClean");var Event2=class{constructor(type){this[kTarget]=null;this[kType]=type}get target(){return this[kTarget]}get type(){return this[kType]}};Object.defineProperty(Event2.prototype,"target",{enumerable:true});Object.defineProperty(Event2.prototype,"type",{enumerable:true});var CloseEvent=class extends Event2{constructor(type,options={}){super(type);this[kCode]=options.code===void 0?0:options.code;this[kReason]=options.reason===void 0?"":options.reason;this[kWasClean]=options.wasClean===void 0?false:options.wasClean}get code(){return this[kCode]}get reason(){return this[kReason]}get wasClean(){return this[kWasClean]}};Object.defineProperty(CloseEvent.prototype,"code",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:true});var ErrorEvent=class extends Event2{constructor(type,options={}){super(type);this[kError]=options.error===void 0?null:options.error;this[kMessage]=options.message===void 0?"":options.message}get error(){return this[kError]}get message(){return this[kMessage]}};Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:true});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:true});var MessageEvent=class extends Event2{constructor(type,options={}){super(type);this[kData]=options.data===void 0?null:options.data}get data(){return this[kData]}};Object.defineProperty(MessageEvent.prototype,"data",{enumerable:true});var EventTarget2={addEventListener(type,handler,options={}){for(const listener of this.listeners(type)){if(!options[kForOnEventAttribute]&&listener[kListener]===handler&&!listener[kForOnEventAttribute]){return}}let wrapper;if(type==="message"){wrapper=function onMessage(data,isBinary){const event=new MessageEvent("message",{data:isBinary?data:data.toString()});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="close"){wrapper=function onClose(code,message){const event=new CloseEvent("close",{code,reason:message.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="error"){wrapper=function onError(error){const event=new ErrorEvent("error",{error,message:error.message});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="open"){wrapper=function onOpen(){const event=new Event2("open");event[kTarget]=this;callListener(handler,this,event)}}else{return}wrapper[kForOnEventAttribute]=!!options[kForOnEventAttribute];wrapper[kListener]=handler;if(options.once){this.once(type,wrapper)}else{this.on(type,wrapper)}},removeEventListener(type,handler){for(const listener of this.listeners(type)){if(listener[kListener]===handler&&!listener[kForOnEventAttribute]){this.removeListener(type,listener);break}}}};module.exports={CloseEvent,ErrorEvent,Event:Event2,EventTarget:EventTarget2,MessageEvent};function callListener(listener,thisArg,event){if(typeof listener==="object"&&listener.handleEvent){listener.handleEvent.call(listener,event)}else{listener.call(thisArg,event)}}}});var require_extension=__commonJS({"node_modules/ws/lib/extension.js"(exports,module){"use strict";var{tokenChars}=require_validation();function push(dest,name,elem){if(dest[name]===void 0)dest[name]=[elem];else dest[name].push(elem)}function parse4(header){const offers=Object.create(null);let params=Object.create(null);let mustUnescape=false;let isEscaping=false;let inQuotes=false;let extensionName;let paramName;let start=-1;let code=-1;let end=-1;let i=0;for(;i<header.length;i++){code=header.charCodeAt(i);if(extensionName===void 0){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const name=header.slice(start,end);if(code===44){push(offers,name,params);params=Object.create(null)}else{extensionName=name}start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(paramName===void 0){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(code===32||code===9){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;push(params,header.slice(start,end),true);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=void 0}start=end=-1}else if(code===61&&start!==-1&&end===-1){paramName=header.slice(start,i);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else{if(isEscaping){if(tokenChars[code]!==1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(start===-1)start=i;else if(!mustUnescape)mustUnescape=true;isEscaping=false}else if(inQuotes){if(tokenChars[code]===1){if(start===-1)start=i}else if(code===34&&start!==-1){inQuotes=false;end=i}else if(code===92){isEscaping=true}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(code===34&&header.charCodeAt(i-1)===61){inQuotes=true}else if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(start!==-1&&(code===32||code===9)){if(end===-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;let value=header.slice(start,end);if(mustUnescape){value=value.replace(/\\/g,"");mustUnescape=false}push(params,paramName,value);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=void 0}paramName=void 0;start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}}if(start===-1||inQuotes||code===32||code===9){throw new SyntaxError("Unexpected end of input")}if(end===-1)end=i;const token=header.slice(start,end);if(extensionName===void 0){push(offers,token,params)}else{if(paramName===void 0){push(params,token,true)}else if(mustUnescape){push(params,paramName,token.replace(/\\/g,""))}else{push(params,paramName,token)}push(offers,extensionName,params)}return offers}function format2(extensions){return Object.keys(extensions).map(extension2=>{let configurations=extensions[extension2];if(!Array.isArray(configurations))configurations=[configurations];return configurations.map(params=>{return[extension2].concat(Object.keys(params).map(k2=>{let values=params[k2];if(!Array.isArray(values))values=[values];return values.map(v2=>v2===true?k2:`${k2}=${v2}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}module.exports={format:format2,parse:parse4}}});var require_websocket2=__commonJS({"node_modules/ws/lib/websocket.js"(exports,module){"use strict";var EventEmitter2=__require("events");var https=__require("https");var http6=__require("http");var net5=__require("net");var tls6=__require("tls");var{randomBytes:randomBytes5,createHash:createHash35}=__require("crypto");var{Duplex,Readable:Readable3}=__require("stream");var{URL:URL2}=__require("url");var PerMessageDeflate2=require_permessage_deflate2();var Receiver2=require_receiver2();var Sender2=require_sender2();var{isBlob}=require_validation();var{BINARY_TYPES,CLOSE_TIMEOUT,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants6();var{EventTarget:{addEventListener,removeEventListener}}=require_event_target();var{format:format2,parse:parse4}=require_extension();var{toBuffer}=require_buffer_util();var kAborted=Symbol("kAborted");var protocolVersions=[8,13];var readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"];var subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var WebSocket3=class _WebSocket extends EventEmitter2{constructor(address,protocols,options){super();this._binaryType=BINARY_TYPES[0];this._closeCode=1006;this._closeFrameReceived=false;this._closeFrameSent=false;this._closeMessage=EMPTY_BUFFER;this._closeTimer=null;this._errorEmitted=false;this._extensions={};this._paused=false;this._protocol="";this._readyState=_WebSocket.CONNECTING;this._receiver=null;this._sender=null;this._socket=null;if(address!==null){this._bufferedAmount=0;this._isServer=false;this._redirects=0;if(protocols===void 0){if(!options||options.protocols===void 0){protocols=[]}else if(Array.isArray(options.protocols)){protocols=options.protocols}else{protocols=[options.protocols]}}else if(!Array.isArray(protocols)){if(typeof protocols==="object"&&protocols!==null){options=protocols;if(options.protocols===void 0){protocols=[]}else if(Array.isArray(options.protocols)){protocols=options.protocols}else{protocols=[options.protocols]}}else{protocols=[protocols]}}initAsClient(this,address,protocols,options)}else{this._autoPong=options.autoPong;this._closeTimeout=options.closeTimeout;this._isServer=true}}get binaryType(){return this._binaryType}set binaryType(type){if(!BINARY_TYPES.includes(type))return;this._binaryType=type;if(this._receiver)this._receiver._binaryType=type}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){const receiver=new Receiver2({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:options.maxBufferedChunks,maxFragments:options.maxFragments,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation});const sender=new Sender2(socket,this._extensions,options.generateMask);this._receiver=receiver;this._sender=sender;this._socket=socket;receiver[kWebSocket]=this;sender[kWebSocket]=this;socket[kWebSocket]=this;receiver.on("conclude",receiverOnConclude);receiver.on("drain",receiverOnDrain);receiver.on("error",receiverOnError);receiver.on("message",receiverOnMessage);receiver.on("ping",receiverOnPing);receiver.on("pong",receiverOnPong);sender.onerror=senderOnError;if(socket.setTimeout)socket.setTimeout(0);if(socket.setNoDelay)socket.setNoDelay();if(head.length>0)socket.unshift(head);socket.on("close",socketOnClose);socket.on("data",socketOnData);socket.on("end",socketOnEnd);socket.on("error",socketOnError);this._readyState=_WebSocket.OPEN;this.emit("open")}emitClose(){if(!this._socket){this._readyState=_WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[PerMessageDeflate2.extensionName]){this._extensions[PerMessageDeflate2.extensionName].cleanup()}this._receiver.removeAllListeners();this._readyState=_WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState===_WebSocket.CLOSED)return;if(this.readyState===_WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this.readyState===_WebSocket.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)){this._socket.end()}return}this._sender.close(code,data,!this._isServer,err2=>{if(err2)return;this._closeFrameSent=true;if(this._closeFrameReceived||this._receiver._writableState.errorEmitted){this._socket.end()}});this._readyState=_WebSocket.CLOSING;setCloseTimer(this)}pause(){if(this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED){return}this._paused=true;this._socket.pause()}ping(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=void 0}else if(typeof mask==="function"){cb=mask;mask=void 0}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=void 0}else if(typeof mask==="function"){cb=mask;mask=void 0}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){if(this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED){return}this._paused=false;if(!this._receiver._writableState.needDrain)this._socket.resume()}send(data,options,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof options==="function"){cb=options;options={}}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}const opts={binary:typeof data!=="string",mask:!this._isServer,compress:true,fin:true,...options};if(!this._extensions[PerMessageDeflate2.extensionName]){opts.compress=false}this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState===_WebSocket.CLOSED)return;if(this.readyState===_WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this._socket){this._readyState=_WebSocket.CLOSING;this._socket.destroy()}}};Object.defineProperty(WebSocket3,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket3.prototype,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket3,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket3.prototype,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket3,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket3.prototype,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket3,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket3.prototype,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(property=>{Object.defineProperty(WebSocket3.prototype,property,{enumerable:true})});["open","error","close","message"].forEach(method=>{Object.defineProperty(WebSocket3.prototype,`on${method}`,{enumerable:true,get(){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute])return listener[kListener]}return null},set(handler){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}}if(typeof handler!=="function")return;this.addEventListener(method,handler,{[kForOnEventAttribute]:true})}})});WebSocket3.prototype.addEventListener=addEventListener;WebSocket3.prototype.removeEventListener=removeEventListener;module.exports=WebSocket3;function initAsClient(websocket,address,protocols,options){const opts={allowSynchronousEvents:true,autoPong:true,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:true,followRedirects:false,maxRedirects:10,...options,socketPath:void 0,hostname:void 0,protocol:void 0,protocols:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};websocket._autoPong=opts.autoPong;websocket._closeTimeout=opts.closeTimeout;if(!protocolVersions.includes(opts.protocolVersion)){throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`)}let parsedUrl;if(address instanceof URL2){parsedUrl=address}else{try{parsedUrl=new URL2(address)}catch{throw new SyntaxError(`Invalid URL: ${address}`)}}if(parsedUrl.protocol==="http:"){parsedUrl.protocol="ws:"}else if(parsedUrl.protocol==="https:"){parsedUrl.protocol="wss:"}websocket._url=parsedUrl.href;const isSecure=parsedUrl.protocol==="wss:";const isIpcUrl=parsedUrl.protocol==="ws+unix:";let invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl){invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`}else if(isIpcUrl&&!parsedUrl.pathname){invalidUrlMessage="The URL's pathname is empty"}else if(parsedUrl.hash){invalidUrlMessage="The URL contains a fragment identifier"}if(invalidUrlMessage){const err2=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0){throw err2}else{emitErrorAndClose(websocket,err2);return}}const defaultPort2=isSecure?443:80;const key2=randomBytes5(16).toString("base64");const request=isSecure?https.request:http6.request;const protocolSet=new Set;let perMessageDeflate;opts.createConnection=opts.createConnection||(isSecure?tlsConnect:netConnect);opts.defaultPort=opts.defaultPort||defaultPort2;opts.port=parsedUrl.port||defaultPort2;opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname;opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key2,Connection:"Upgrade",Upgrade:"websocket"};opts.path=parsedUrl.pathname+parsedUrl.search;opts.timeout=opts.handshakeTimeout;if(opts.perMessageDeflate){perMessageDeflate=new PerMessageDeflate2({...opts.perMessageDeflate,isServer:false,maxPayload:opts.maxPayload});opts.headers["Sec-WebSocket-Extensions"]=format2({[PerMessageDeflate2.extensionName]:perMessageDeflate.offer()})}if(protocols.length){for(const protocol of protocols){if(typeof protocol!=="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol)){throw new SyntaxError("An invalid or duplicated subprotocol was specified")}protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin){if(opts.protocolVersion<13){opts.headers["Sec-WebSocket-Origin"]=opts.origin}else{opts.headers.Origin=opts.origin}}if(parsedUrl.username||parsedUrl.password){opts.auth=`${parsedUrl.username}:${parsedUrl.password}`}if(isIpcUrl){const parts=opts.path.split(":");opts.socketPath=parts[0];opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl;websocket._originalSecure=isSecure;websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;const headers=options&&options.headers;options={...options,headers:{}};if(headers){for(const[key3,value]of Object.entries(headers)){options.headers[key3.toLowerCase()]=value}}}else if(websocket.listenerCount("redirect")===0){const isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:false:websocket._originalIpc?false:parsedUrl.host===websocket._originalHostOrSocketPath;if(!isSameHost||websocket._originalSecure&&!isSecure){delete opts.headers.authorization;delete opts.headers.cookie;if(!isSameHost)delete opts.headers.host;opts.auth=void 0}}if(opts.auth&&!options.headers.authorization){options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")}req=websocket._req=request(opts);if(websocket._redirects){websocket.emit("redirect",websocket.url,req)}}else{req=websocket._req=request(opts)}if(opts.timeout){req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")})}req.on("error",err2=>{if(req===null||req[kAborted])return;req=websocket._req=null;emitErrorAndClose(websocket,err2)});req.on("response",res=>{const location=res.headers.location;const statusCode=res.statusCode;if(location&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location,address)}catch(e){const err2=new SyntaxError(`Invalid URL: ${location}`);emitErrorAndClose(websocket,err2);return}initAsClient(websocket,addr,protocols,options)}else if(!websocket.emit("unexpected-response",req,res)){abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}});req.on("upgrade",(res,socket,head)=>{websocket.emit("upgrade",res);if(websocket.readyState!==WebSocket3.CONNECTING)return;req=websocket._req=null;const upgrade=res.headers.upgrade;if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}const digest=createHash35("sha1").update(key2+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}const serverProt=res.headers["sec-websocket-protocol"];let protError;if(serverProt!==void 0){if(!protocolSet.size){protError="Server sent a subprotocol but none was requested"}else if(!protocolSet.has(serverProt)){protError="Server sent an invalid subprotocol"}}else if(protocolSet.size){protError="Server sent no subprotocol"}if(protError){abortHandshake(websocket,socket,protError);return}if(serverProt)websocket._protocol=serverProt;const secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==void 0){if(!perMessageDeflate){const message="Server sent a Sec-WebSocket-Extensions header but no extension was requested";abortHandshake(websocket,socket,message);return}let extensions;try{extensions=parse4(secWebSocketExtensions)}catch(err2){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}const extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate2.extensionName){const message="Server indicated an extension that was not requested";abortHandshake(websocket,socket,message);return}try{perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName])}catch(err2){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}websocket._extensions[PerMessageDeflate2.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxBufferedChunks:opts.maxBufferedChunks,maxFragments:opts.maxFragments,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})});if(opts.finishRequest){opts.finishRequest(req,websocket)}else{req.end()}}function emitErrorAndClose(websocket,err2){websocket._readyState=WebSocket3.CLOSING;websocket._errorEmitted=true;websocket.emit("error",err2);websocket.emitClose()}function netConnect(options){options.path=options.socketPath;return net5.connect(options)}function tlsConnect(options){options.path=void 0;if(!options.servername&&options.servername!==""){options.servername=net5.isIP(options.host)?"":options.host}return tls6.connect(options)}function abortHandshake(websocket,stream2,message){websocket._readyState=WebSocket3.CLOSING;const err2=new Error(message);Error.captureStackTrace(err2,abortHandshake);if(stream2.setHeader){stream2[kAborted]=true;stream2.abort();if(stream2.socket&&!stream2.socket.destroyed){stream2.socket.destroy()}process.nextTick(emitErrorAndClose,websocket,err2)}else{stream2.destroy(err2);stream2.once("error",websocket.emit.bind(websocket,"error"));stream2.once("close",websocket.emitClose.bind(websocket))}}function sendAfterClose(websocket,data,cb){if(data){const length=isBlob(data)?data.size:toBuffer(data).length;if(websocket._socket)websocket._sender._bufferedBytes+=length;else websocket._bufferedAmount+=length}if(cb){const err2=new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);process.nextTick(cb,err2)}}function receiverOnConclude(code,reason){const websocket=this[kWebSocket];websocket._closeFrameReceived=true;websocket._closeMessage=reason;websocket._closeCode=code;if(websocket._socket[kWebSocket]===void 0)return;websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);if(code===1005)websocket.close();else websocket.close(code,reason)}function receiverOnDrain(){const websocket=this[kWebSocket];if(!websocket.isPaused)websocket._socket.resume()}function receiverOnError(err2){const websocket=this[kWebSocket];if(websocket._socket[kWebSocket]!==void 0){websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);websocket.close(err2[kStatusCode])}if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err2)}}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){const websocket=this[kWebSocket];if(websocket._autoPong)websocket.pong(data,!this._isServer,NOOP);websocket.emit("ping",data)}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream2){stream2.resume()}function senderOnError(err2){const websocket=this[kWebSocket];if(websocket.readyState===WebSocket3.CLOSED)return;if(websocket.readyState===WebSocket3.OPEN){websocket._readyState=WebSocket3.CLOSING;setCloseTimer(websocket)}this._socket.end();if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err2)}}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),websocket._closeTimeout)}function socketOnClose(){const websocket=this[kWebSocket];this.removeListener("close",socketOnClose);this.removeListener("data",socketOnData);this.removeListener("end",socketOnEnd);websocket._readyState=WebSocket3.CLOSING;if(!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){const chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}websocket._receiver.end();this[kWebSocket]=void 0;clearTimeout(websocket._closeTimer);if(websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted){websocket.emitClose()}else{websocket._receiver.on("error",receiverOnFinish);websocket._receiver.on("finish",receiverOnFinish)}}function socketOnData(chunk){if(!this[kWebSocket]._receiver.write(chunk)){this.pause()}}function socketOnEnd(){const websocket=this[kWebSocket];websocket._readyState=WebSocket3.CLOSING;websocket._receiver.end();this.end()}function socketOnError(){const websocket=this[kWebSocket];this.removeListener("error",socketOnError);this.on("error",NOOP);if(websocket){websocket._readyState=WebSocket3.CLOSING;this.destroy()}}}});var require_stream=__commonJS({"node_modules/ws/lib/stream.js"(exports,module){"use strict";var WebSocket3=require_websocket2();var{Duplex}=__require("stream");function emitClose(stream2){stream2.emit("close")}function duplexOnEnd(){if(!this.destroyed&&this._writableState.finished){this.destroy()}}function duplexOnError(err2){this.removeListener("error",duplexOnError);this.destroy();if(this.listenerCount("error")===0){this.emit("error",err2)}}function createWebSocketStream2(ws2,options){let terminateOnDestroy=true;const duplex=new Duplex({...options,autoDestroy:false,emitClose:false,objectMode:false,writableObjectMode:false});ws2.on("message",function message(msg,isBinary){const data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;if(!duplex.push(data))ws2.pause()});ws2.once("error",function error(err2){if(duplex.destroyed)return;terminateOnDestroy=false;duplex.destroy(err2)});ws2.once("close",function close(){if(duplex.destroyed)return;duplex.push(null)});duplex._destroy=function(err2,callback){if(ws2.readyState===ws2.CLOSED){callback(err2);process.nextTick(emitClose,duplex);return}let called=false;ws2.once("error",function error(err3){called=true;callback(err3)});ws2.once("close",function close(){if(!called)callback(err2);process.nextTick(emitClose,duplex)});if(terminateOnDestroy)ws2.terminate()};duplex._final=function(callback){if(ws2.readyState===ws2.CONNECTING){ws2.once("open",function open(){duplex._final(callback)});return}if(ws2._socket===null)return;if(ws2._socket._writableState.finished){callback();if(duplex._readableState.endEmitted)duplex.destroy()}else{ws2._socket.once("finish",function finish2(){callback()});ws2.close()}};duplex._read=function(){if(ws2.isPaused)ws2.resume()};duplex._write=function(chunk,encoding,callback){if(ws2.readyState===ws2.CONNECTING){ws2.once("open",function open(){duplex._write(chunk,encoding,callback)});return}ws2.send(chunk,callback)};duplex.on("end",duplexOnEnd);duplex.on("error",duplexOnError);return duplex}module.exports=createWebSocketStream2}});var require_subprotocol=__commonJS({"node_modules/ws/lib/subprotocol.js"(exports,module){"use strict";var{tokenChars}=require_validation();function parse4(header){const protocols=new Set;let start=-1;let end=-1;let i=0;for(i;i<header.length;i++){const code=header.charCodeAt(i);if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const protocol2=header.slice(start,end);if(protocols.has(protocol2)){throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`)}protocols.add(protocol2);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}if(start===-1||end!==-1){throw new SyntaxError("Unexpected end of input")}const protocol=header.slice(start,i);if(protocols.has(protocol)){throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`)}protocols.add(protocol);return protocols}module.exports={parse:parse4}}});var require_websocket_server=__commonJS({"node_modules/ws/lib/websocket-server.js"(exports,module){"use strict";var EventEmitter2=__require("events");var http6=__require("http");var{Duplex}=__require("stream");var{createHash:createHash35}=__require("crypto");var extension2=require_extension();var PerMessageDeflate2=require_permessage_deflate2();var subprotocol2=require_subprotocol();var WebSocket3=require_websocket2();var{CLOSE_TIMEOUT,GUID,kWebSocket}=require_constants6();var keyRegex=/^[+/0-9A-Za-z]{22}==$/;var RUNNING=0;var CLOSING=1;var CLOSED=2;var WebSocketServer2=class extends EventEmitter2{constructor(options,callback){super();options={allowSynchronousEvents:true,autoPong:true,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:false,handleProtocols:null,clientTracking:true,closeTimeout:CLOSE_TIMEOUT,verifyClient:null,noServer:false,backlog:null,server:null,host:null,path:null,port:null,WebSocket:WebSocket3,...options};if(options.port==null&&!options.server&&!options.noServer||options.port!=null&&(options.server||options.noServer)||options.server&&options.noServer){throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified')}if(options.port!=null){this._server=http6.createServer((req,res)=>{const body=http6.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"});res.end(body)});this._server.listen(options.port,options.host,options.backlog,callback)}else if(options.server){this._server=options.server}if(this._server){const emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}if(options.perMessageDeflate===true)options.perMessageDeflate={};if(options.clientTracking){this.clients=new Set;this._shouldEmitClose=false}this.options=options;this._state=RUNNING}address(){if(this.options.noServer){throw new Error('The server is operating in "noServer" mode')}if(!this._server)return null;return this._server.address()}close(cb){if(this._state===CLOSED){if(cb){this.once("close",()=>{cb(new Error("The server is not running"))})}process.nextTick(emitClose,this);return}if(cb)this.once("close",cb);if(this._state===CLOSING)return;this._state=CLOSING;if(this.options.noServer||this.options.server){if(this._server){this._removeListeners();this._removeListeners=this._server=null}if(this.clients){if(!this.clients.size){process.nextTick(emitClose,this)}else{this._shouldEmitClose=true}}else{process.nextTick(emitClose,this)}}else{const server2=this._server;this._removeListeners();this._removeListeners=this._server=null;server2.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){const index=req.url.indexOf("?");const pathname=index!==-1?req.url.slice(0,index):req.url;if(pathname!==this.options.path)return false}return true}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);const key2=req.headers["sec-websocket-key"];const upgrade=req.headers.upgrade;const version=+req.headers["sec-websocket-version"];if(req.method!=="GET"){const message="Invalid HTTP method";abortHandshakeOrEmitwsClientError(this,req,socket,405,message);return}if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){const message="Invalid Upgrade header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(key2===void 0||!keyRegex.test(key2)){const message="Missing or invalid Sec-WebSocket-Key header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(version!==13&&version!==8){const message="Missing or invalid Sec-WebSocket-Version header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message,{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}const secWebSocketProtocol=req.headers["sec-websocket-protocol"];let protocols=new Set;if(secWebSocketProtocol!==void 0){try{protocols=subprotocol2.parse(secWebSocketProtocol)}catch(err2){const message="Invalid Sec-WebSocket-Protocol header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}const secWebSocketExtensions=req.headers["sec-websocket-extensions"];const extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==void 0){const perMessageDeflate=new PerMessageDeflate2({...this.options.perMessageDeflate,isServer:true,maxPayload:this.options.maxPayload});try{const offers=extension2.parse(secWebSocketExtensions);if(offers[PerMessageDeflate2.extensionName]){perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);extensions[PerMessageDeflate2.extensionName]=perMessageDeflate}}catch(err2){const message="Invalid or unacceptable Sec-WebSocket-Extensions header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}if(this.options.verifyClient){const info={origin:req.headers[`${version===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified){return abortHandshake(socket,code||401,message,headers)}this.completeUpgrade(extensions,key2,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key2,protocols,req,socket,head,cb)}completeUpgrade(extensions,key2,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket]){throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration")}if(this._state>RUNNING)return abortHandshake(socket,503);const digest=createHash35("sha1").update(key2+GUID).digest("base64");const headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${digest}`];const ws2=new this.options.WebSocket(null,void 0,this.options);if(protocols.size){const protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;if(protocol){headers.push(`Sec-WebSocket-Protocol: ${protocol}`);ws2._protocol=protocol}}if(extensions[PerMessageDeflate2.extensionName]){const params=extensions[PerMessageDeflate2.extensionName].params;const value=extension2.format({[PerMessageDeflate2.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`);ws2._extensions=extensions}this.emit("headers",headers,req);socket.write(headers.concat("\r\n").join("\r\n"));socket.removeListener("error",socketOnError);ws2.setSocket(socket,head,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation});if(this.clients){this.clients.add(ws2);ws2.on("close",()=>{this.clients.delete(ws2);if(this._shouldEmitClose&&!this.clients.size){process.nextTick(emitClose,this)}})}cb(ws2,req)}};module.exports=WebSocketServer2;function addListeners(server2,map){for(const event of Object.keys(map))server2.on(event,map[event]);return function removeListeners(){for(const event of Object.keys(map)){server2.removeListener(event,map[event])}}}function emitClose(server2){server2._state=CLOSED;server2.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(socket,code,message,headers){message=message||http6.STATUS_CODES[code];headers={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(message),...headers};socket.once("finish",socket.destroy);socket.end(`HTTP/1.1 ${code} ${http6.STATUS_CODES[code]}\r
|
|
891
|
+
FROM sessions s`);return rows.map(r=>({sessionId:str(r.sessionId),title:r.title!==null&&r.title!==void 0?str(r.title):void 0,hostTitle:r.hostTitle!==null&&r.hostTitle!==void 0?str(r.hostTitle):void 0,label:r.label!==null&&r.label!==void 0?str(r.label):void 0,protocol:r.protocol!==null&&r.protocol!==void 0?str(r.protocol):void 0,origin:r.origin!==null&&r.origin!==void 0?str(r.origin):void 0,updatedAt:num(r.updatedAt),statsJson:str(r.statsJson),metadataJson:str(r.metadataJson),blocks:num(r.blocks),firstTopic:nullableStr(r.firstTopic),firstSummary:nullableStr(r.firstSummary),activeCompressedTokens:num(r.activeCompressed),status:str(r.status??"active")}))}async verifyProjections(sessionId){const fail=(where,msg)=>({ok:false,error:`${sessionId}: ${where}: ${msg}`});let checks=0;const s3=await this.getSessionRow(sessionId);if(!s3)return fail("sessions","row missing");const meta=JSON.parse(s3.metaJson);checks++;if((s3.protocol??null)!==(meta.protocol??null))return fail("sessions.protocol",`${s3.protocol} vs ${String(meta.protocol)}`);if((s3.label??null)!==(meta.label??null))return fail("sessions.label",`${s3.label} vs ${String(meta.label)}`);if((s3.title??null)!==(meta.title??null))return fail("sessions.title",`${s3.title} vs ${String(meta.title)}`);if((s3.hostTitle??null)!==(meta.hostTitle??null))return fail("sessions.hostTitle",`${s3.hostTitle} vs ${String(meta.hostTitle)}`);const kstate=JSON.parse(s3.kstateJson);checks++;if(kstate.nextBlockId!==void 0||kstate.nextRunId!==void 0){return fail("sessions.kstate_json","must not carry nextBlockId/nextRunId (columns own them)")}const messages=await this.getMessages(sessionId,{includeRetired:true});const refByRaw=new Map((await this.getRefs(sessionId)).map(r=>[r.rawId,r.ref]));for(const m2 of messages){checks++;if(m2.ref!==(refByRaw.get(m2.msgId)??null)){return fail(`messages[${m2.seq}].ref`,`${String(m2.ref)} vs refs ledger ${String(refByRaw.get(m2.msgId))}`)}}for(const m2 of messages){checks++;const parsed=JSON.parse(m2.content);if(parsed.id!==m2.msgId)return fail(`messages[${m2.seq}].msg_id`,`${m2.msgId} vs ${String(parsed.id)}`);if(parsed.role!==m2.role)return fail(`messages[${m2.seq}].role`,`${m2.role} vs ${String(parsed.role)}`);if((parsed.contentType??"message")!==m2.kind){return fail(`messages[${m2.seq}].kind`,`${m2.kind} vs ${String(parsed.contentType)}`)}}const blocks=await this.getBlocks(sessionId);for(const b2 of blocks){checks++;const payload=JSON.parse(b2.payloadJson);if(payload.blockId!==b2.blockId)return fail(`blocks[${b2.blockId}].blockId`,"id mismatch");if(payload.tier!==b2.tier)return fail(`blocks[${b2.blockId}].tier`,`${b2.tier} vs ${String(payload.tier)}`);if((payload.active??true)!==b2.active){return fail(`blocks[${b2.blockId}].active`,`${b2.active} vs ${String(payload.active)}`)}}return{ok:true,checks}}async counts(){const out={};for(const t of["sessions","messages","refs","blocks","dead_refs","ccr_entries","content","checkpoints"]){const[rows]=await this.pool.query(`SELECT COUNT(*) AS n FROM ${t}`);out[t]=num(rows[0].n)}return out}async contentDedupReport(){const[rows]=await this.pool.query("SELECT COUNT(*) AS n, COALESCE(SUM(byte_len),0) AS b, COALESCE(SUM(refcount),0) AS r FROM content");return{rows:num(rows[0].n),bytesTotal:num(rows[0].b),refcounted:num(rows[0].r)}}}}});async function openBackend(name,indexPath,engine){if(name==="sqlite")return SqliteBackend.open(indexPath,engine);if(name==="mysql"){if(typeof indexPath!=="string"||indexPath.trim().length===0){throw new Error(`[storage] backend "mysql" needs a DSN \u2014 set BILI_MYSQL_DSN or storage.mysql.dsn (mysql://user:pass@host:3306/db); runs on "sqlite" until then (#3388/#3931)`)}let driver;try{driver=await import("mysql2/promise")}catch(err2){throw new Error(`[storage] mysql backend selected but the mysql2 driver cannot be loaded (${err2 instanceof Error?err2.message:String(err2)}) \u2014 installs without a node_modules tree cannot run the mysql backend; set storage.backend="sqlite" or install with dependencies (#4008)`)}const{MysqlBackend:MysqlBackend2}=await Promise.resolve().then(()=>(init_mysql(),mysql_exports));return new MysqlBackend2(indexPath,driver)}throw new Error(`[storage] unknown backend "${name}" \u2014 valid names: ${REGISTERED_BACKENDS.join(", ")}`)}function selectedBackendRaw(env,file){const envRaw=env?.BILI_STORAGE_BACKEND;const fromEnv=typeof envRaw==="string"?envRaw.trim().toLowerCase():"";if(fromEnv.length>0)return fromEnv;return typeof file==="string"?file.trim().toLowerCase():""}function resolveBackendName(env,file){const raw=selectedBackendRaw(env,file);if(raw.length>0)return REGISTERED_BACKENDS.includes(raw)?raw:"sqlite";return"sqlite"}function backendSelectionNotice(name){if(!name||name==="sqlite")return void 0;if(REGISTERED_BACKENDS.includes(name)){if(name==="mysql"){return`[storage] storage.backend="mysql" rides the StorageBackend contract (#3388/#3931) \u2014 saves ingest through the async shadow queue; replicas/ext/GC/export/fork speak the async twins; SYNC reads ride the JSON envelope (sync facades miss by design); writerOff stays sqlite-only`}return`[storage] storage.backend="${name}" is registered but not implemented \u2014 the unified store stays on "sqlite"`}return`[storage] storage.backend="${name}" is not a registered backend (valid: ${REGISTERED_BACKENDS.join(", ")}) \u2014 using "sqlite"`}var SqliteBackend,REGISTERED_BACKENDS;var init_backend=__esm({"src/storage/backend.ts"(){"use strict";init_store();SqliteBackend=class _SqliteBackend{store;constructor(store2){this.store=store2}static open(indexPath,engine){return new _SqliteBackend(UnifiedStore.open(indexPath,engine))}ingestSession(input,delta,opts){return Promise.resolve(this.store.ingestSession(input,delta,opts))}sessionCounters(sessionId){return Promise.resolve(this.store.sessionCounters(sessionId))}sessionUpdatedAt(sessionId){return Promise.resolve(this.store.sessionUpdatedAt(sessionId))}deleteSession(sessionId){return Promise.resolve(this.store.deleteSession(sessionId))}listSessionIds(){return Promise.resolve(this.store.listSessionIds())}lookupConversation(namespace,conversationId){return Promise.resolve(this.store.lookupConversation(namespace,conversationId))}listConversationBindings(namespace){return Promise.resolve(this.store.listConversationBindings(namespace))}getSessionRow(sessionId){return Promise.resolve(this.store.getSessionRow(sessionId))}liveRowCount(sessionId){return Promise.resolve(this.store.liveRowCount(sessionId))}lastLiveSeq(sessionId){return Promise.resolve(this.store.lastLiveSeq(sessionId))}seqByRaw(sessionId){return Promise.resolve(this.store.seqByRaw(sessionId))}cloneSessionRows(parentId,childId,throughSeq,initial){return Promise.resolve(this.store.cloneSessionRows(parentId,childId,throughSeq,initial))}getMessages(sessionId,opts){return Promise.resolve(this.store.getMessages(sessionId,opts))}getBlocks(sessionId,opts){return Promise.resolve(this.store.getBlocks(sessionId,opts))}sessionViewRows(sessionId){return Promise.resolve(this.store.sessionViewRows(sessionId))}getDeadRefs(sessionId){return Promise.resolve(this.store.getDeadRefs(sessionId))}getRefs(sessionId){return Promise.resolve(this.store.getRefs(sessionId))}readSnapshot(read){return this.store.readSnapshotAsync(store2=>read({getSessionRow:async id=>store2.getSessionRow(id),getMessages:async(id,opts)=>store2.getMessages(id,opts),getBlocks:async(id,opts)=>store2.getBlocks(id,opts),getDeadRefs:async id=>store2.getDeadRefs(id),getRefs:async id=>store2.getRefs(id)}))}getCcr(sessionId){return Promise.resolve(this.store.getCcr(sessionId))}getCcrEntries(sessionId){return Promise.resolve(this.store.getCcrEntries(sessionId))}ingestWatermark(sessionId){return Promise.resolve(this.store.ingestWatermark(sessionId))}tailSeqs(sessionId){return Promise.resolve(this.store.tailSeqs(sessionId))}clearIngestWatermark(sessionId){return Promise.resolve(this.store.clearIngestWatermark(sessionId))}resetAllIngestWatermarks(){return Promise.resolve(this.store.resetAllIngestWatermarks())}probeIngestBoundary(sessionId,seq){return Promise.resolve(this.store.probeIngestBoundary(sessionId,seq))}reapBlocks(sessionId,reapedIds,orphanContents2){return Promise.resolve(this.store.reapBlocks(sessionId,reapedIds,orphanContents2))}archiveSession(sessionId,opts){return Promise.resolve(this.store.archiveSession(sessionId,opts))}restoreArchived(sessionId,opts){return Promise.resolve(this.store.restoreArchived(sessionId,opts))}gc(opts){return Promise.resolve(this.store.gc(opts))}contentRefCountOfBody(needle){return Promise.resolve(this.store.contentRefCountOfBody(needle))}mediaRefCount(bytes){return Promise.resolve(this.store.mediaRefCount(bytes))}insertCheckpoint(cp2){return Promise.resolve(this.store.insertCheckpoint(cp2))}listCheckpoints(sessionId){return Promise.resolve(this.store.listCheckpoints(sessionId))}getCheckpoint(cpId){return Promise.resolve(this.store.getCheckpoint(cpId))}checkpointState(cpId){return Promise.resolve(this.store.checkpointState(cpId))}deleteCheckpoint(cpId){return Promise.resolve(this.store.deleteCheckpoint(cpId))}setSessionExt(sessionId,key2,value){return Promise.resolve(this.store.setSessionExt(sessionId,key2,value))}getSessionExt(sessionId,key2){return Promise.resolve(this.store.getSessionExt(sessionId,key2))}listSessionExt(sessionId){return Promise.resolve(this.store.listSessionExt(sessionId))}deleteSessionExt(sessionId,key2){return Promise.resolve(this.store.deleteSessionExt(sessionId,key2))}setKv(namespace,key2,value){return Promise.resolve(this.store.setKv(namespace,key2,value))}getKv(namespace,key2){return Promise.resolve(this.store.getKv(namespace,key2))}listKv(namespace,keyPrefix){return Promise.resolve(this.store.listKv(namespace,keyPrefix))}deleteKv(namespace,key2){return Promise.resolve(this.store.deleteKv(namespace,key2))}sessionSummaries(){return Promise.resolve(this.store.sessionSummaries())}webSummaryRows(){return Promise.resolve(this.store.webSummaryRows())}verifyProjections(sessionId){return Promise.resolve(this.store.verifyProjections(sessionId))}counts(){return Promise.resolve(this.store.counts())}contentDedupReport(){return Promise.resolve(this.store.contentDedupReport())}close(){return Promise.resolve(this.store.close())}};REGISTERED_BACKENDS=["sqlite","mysql"]}});import{createHash as createHash10}from"crypto";function canonicalize(value){return canonicalizeWithContext(value,void 0)}function canonicalizeWithContext(value,key2){if(Array.isArray(value))return value.map(v2=>canonicalizeWithContext(v2,void 0));if(value instanceof Map)return{__map__:[...value.entries()].map(([k2,v2])=>[k2,canonicalizeWithContext(v2,void 0)])};if(value instanceof Set)return{__set__:[...value.values()].map(v2=>canonicalizeWithContext(v2,void 0))};if(value&&typeof value==="object"){const out={};const record4=value;for(const k2 of Object.keys(record4).sort()){const v2=record4[k2];if(Object.hasOwn(DIGEST_SKIPPED_KEYS,k2))continue;out[k2]=canonicalizeWithContext(v2,k2)}return out}return canonicalScalar(value,key2)}function canonicalScalar(value,key2){if(key2==="biliVersion"&&typeof value==="string")return"__VER__";if(typeof value==="number"&&Number.isFinite(value)&&value>16e11)return"__TS__";if(typeof value==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value))return"__UUID__";return value}function isArrayIndexKey(k2){return/^(0|[1-9]\d*)$/.test(k2)&&Number(k2)<=4294967294}function sha256(s3){return createHash10("sha256").update(s3,"utf8").digest("hex")}function canonicalDigest(value){if(value===void 0||typeof value==="function"||typeof value==="symbol")return sha256(JSON.stringify(value));const hash=createHash10("sha256");const chunkSize=64*1024;let pending="";function write(text2){pending+=text2;if(pending.length>=chunkSize){hash.update(pending,"utf8");pending=""}}function writeString(text2){write('"');for(let start=0;start<text2.length;){let end=Math.min(start+chunkSize,text2.length);const last=text2.charCodeAt(end-1);if(end<text2.length&&last>=55296&&last<=56319)end--;write(JSON.stringify(text2.slice(start,end)).slice(1,-1));start=end}write('"')}function visit2(current,key2){if(Array.isArray(current)){write("[");for(let i=0;i<current.length;i++){if(i)write(",");visit2(current[i])}write("]")}else if(current instanceof Map){write('{"__map__":[');let separator="";for(const[k2,v2]of current){write(separator+"[");write(JSON.stringify(k2)??"null");write(",");visit2(v2);write("]");separator=","}write("]}")}else if(current instanceof Set){write('{"__set__":[');let separator="";for(const v2 of current){write(separator);visit2(v2);separator=","}write("]}")}else if(current&&typeof current==="object"){write("{");let separator="";const keys=Object.keys(current);const orderedKeys=keys.filter(isArrayIndexKey).sort((a,b2)=>Number(a)-Number(b2)).concat(keys.filter(k2=>!isArrayIndexKey(k2)).sort());for(const k2 of orderedKeys){if(Object.hasOwn(DIGEST_SKIPPED_KEYS,k2)||k2==="__proto__")continue;const v2=current[k2];if(v2===void 0||typeof v2==="function"||typeof v2==="symbol")continue;write(separator);writeString(k2);write(":");visit2(v2,k2);separator=","}write("}")}else{const normalized=canonicalScalar(current,key2);if(typeof normalized==="string")writeString(normalized);else write(JSON.stringify(normalized)??"null")}}visit2(value);hash.update(pending,"utf8");return hash.digest("hex")}var DIGEST_SKIPPED_KEYS;var init_canonical=__esm({"src/storage/canonical.ts"(){"use strict";DIGEST_SKIPPED_KEYS={storageMode:true,tailGaps:true}}});import path24 from"path";function hadIntegrityQuickCheckFailure(){return integrityQuickCheckFailed}function sqliteOpenFailureHint(err2){if(process.platform!=="win32")return"";if(/unable to open database file/i.test(err2)){return` (win32: the OS refused to open the file \u2014 check the Node runtime's integrity label FIRST (icacls "<path-to-node.exe>"; a Low label is refused by Windows integrity control even with correct ACLs, #5154), then antivirus/Defender locking the sessions dir, OneDrive placeholder files under the profile dir, or a path over 260 chars; if the label is clean, exclude %USERPROFILE%\\.local\\share\\billion-context\\ from antivirus real-time scanning; deleting the file will not clear a lock)`}if(/attempt to write a readonly database/i.test(err2)){return" (win32: 'attempt to write a readonly database' on an EXISTING index.db = the file opened read-only and the first write was refused by the OS \u2014 most often Windows integrity control (a process running at Low integrity cannot write Medium-labeled files, and a DSH-spawned node.exe can itself carry a Low label, e.g. after a stray 'icacls /setintegritylevel Low' \u2014 #5154), less often antivirus/Defender or another bili/dsh process holding the files; check the PROCESS side first \u2014 run icacls on your node.exe and if it reports a Low label restore it with 'icacls <path-to-node.exe> /setintegritylevel Medium' \u2014 do NOT relabel the sessions dir Low to match (that cements the mislabel and drags every file down with it); do NOT delete the file \u2014 in unified-full mode it may hold the only copy of recent session state)"}return""}function orphanContents(legacy){if(legacy.blockContents.size===0)return false;const known=new Set;for(const block of legacy.state.blocks)known.add(block.blockId);for(const id of legacy.blockContents.keys()){if(!known.has(id))return true}return false}function warnTailGaps(id,view){if((view.tailGaps??0)>0){log("warn",`[storage] ${view.tailGaps} tail pointer(s) for ${id} reference missing rows \u2014 view is shorter than the recorded tail (#4390)`)}}function shadowDigest(view){return canonicalDigest(view)}function missingSlot(){return{id:"-",role:"-",length:0,sha8:"-"}}function messageSignature(value){const json=JSON.stringify(canonicalize(value))??"null";const digest=sha256(json);const message=value;return{digest,slot:!message||typeof message!=="object"?missingSlot():{id:typeof message.id==="string"?message.id:"-",role:typeof message.role==="string"?message.role:"-",length:json.length,sha8:digest.slice(0,8)}}}function describeViewDivergence(expectView,gotView){const e=expectView??{};const g2=gotView??{};const ser=v2=>v2===void 0?null:JSON.stringify(canonicalize(v2));const keys=[];for(const k2 of[...new Set([...Object.keys(e),...Object.keys(g2)])].sort()){if(k2==="tailGaps")continue;if(ser(e[k2])!==ser(g2[k2]))keys.push(k2)}const diagnostics={keys};if(keys.includes("state")){const es2=e["state"];const gs2=g2["state"];if(es2!==null&&typeof es2==="object"&&!Array.isArray(es2)&&gs2!==null&&typeof gs2==="object"&&!Array.isArray(gs2)){const eo2=es2;const go2=gs2;const subKeys=[];for(const k2 of[...new Set([...Object.keys(eo2),...Object.keys(go2)])].sort()){if(ser(eo2[k2])!==ser(go2[k2]))subKeys.push(k2)}if(subKeys.length>0)diagnostics.stateKeys=subKeys}}if(keys.includes("lastMessages")&&Array.isArray(e["lastMessages"])&&Array.isArray(g2["lastMessages"])){const et2=e["lastMessages"];const gt2=g2["lastMessages"];let index=-1;for(let i=0;i<Math.min(et2.length,gt2.length);i++){if(ser(et2[i])!==ser(gt2[i])){index=i;break}}if(index===-1&&et2.length!==gt2.length)index=Math.min(et2.length,gt2.length);if(index!==-1){const fp2=m2=>{if(!m2||typeof m2!=="object")return{id:"-",role:"-",length:0,sha8:"-"};const s3=m2;const s22=ser(m2)??"";return{id:typeof s3.id==="string"?s3.id:"-",role:typeof s3.role==="string"?s3.role:"-",length:s22.length,sha8:sha256(s22).slice(0,8)}};diagnostics.tailSlot={index,expect:fp2(index<et2.length?et2[index]:null),got:fp2(index<gt2.length?gt2[index]:null)}}}return diagnostics}function formatDriftDiagnostics(d){const parts=[`diverged: ${d.keys.length>0?d.keys.join(","):"<unknown>"}`];if(d.stateKeys)parts.push(`state: ${d.stateKeys.join(",")}`);if(d.tailSlot){const{index,expect:ex,got:go2}=d.tailSlot;parts.push(`tail slot ${index}: expect ${ex.id}/${ex.role} len=${ex.length} sha=${ex.sha8}, got ${go2.id}/${go2.role} len=${go2.length} sha=${go2.sha8}`)}return" ["+parts.join("; ")+"]"}var integrityQuickCheckFailed,VERIFY_BATCH_SIZE,VIEW_READ_BATCH_SIZE,VERIFY_EVERY_INGESTS,DRIFT_ESCALATE_STREAK,UnifiedShadow,BatchedViewVerification;var init_shadow=__esm({"src/storage/shadow.ts"(){"use strict";init_logger();init_ingest();init_knobs();init_store();init_backend();init_canonical();init_runtime_status();init_knobs();integrityQuickCheckFailed=false;VERIFY_BATCH_SIZE=32;VIEW_READ_BATCH_SIZE=32;VERIFY_EVERY_INGESTS=20;DRIFT_ESCALATE_STREAK=3;UnifiedShadow=class _UnifiedShadow{mode;stats={ingests:0,deltaIngests:0,verifySamples:0,verifyOk:0,verifyDrift:0,imports:0,disabled:false,lastError:null,orphanSkips:0};driftedSessions=new Set;driftStreaks=new Map;frozenEnvelopeIds=new Set;frozenEnvelopeSince=new Map;sync;backend=null;queueTail=Promise.resolve();legacyLoad;dbPath;consecutiveFailures=0;ingestCounts=new Map;constructor(mode,store2,legacyLoad,backend,dbPath){this.mode=mode;this.sync=store2;if(store2===null)this.backend=backend??null;this.legacyLoad=legacyLoad;this.dbPath=dbPath??null}noteIngestFailure(err2){const prev=this.stats.lastError??"";const errStr=String(err2);this.consecutiveFailures+=1;this.stats.lastError=errStr;if(errStr!==prev){log("warn",`[storage] unified sidecar ${this.dbPath??"backend"} failed to ingest (${this.consecutiveFailures} in a row; ${errStr})${sqliteOpenFailureHint(errStr)} \u2014 the index write will be RETRIED on every subsequent save until it succeeds again (no self-disable; the JSON envelope keeps serving meanwhile)`)}}get isAsyncBackend(){return this.sync===null}get engineInfo(){return this.sync?{name:this.sync.engine,source:this.sync.engineSource}:{name:"mysql",source:"network"}}static maybeOpen(dir,env=process.env,legacyLoad,fileUnified,fileWalLimit,fileBackend){const mode=resolveStorageMode(env,fileUnified);if(mode==="legacy")return null;const walLimit=resolveStorageWalJournalSizeLimit(env,fileWalLimit);const selected=selectedBackendRaw(env,fileBackend);if(selected&&selected!=="sqlite"){const notice=backendSelectionNotice(selected);if(notice)log("warn",notice)}let store2;try{try{store2=UnifiedStore.open(`${dir}/index.db`,void 0,{walJournalSizeLimitBytes:walLimit})}catch(err2){if(!(err2 instanceof StorageIntegrityError))throw err2;log("error",`[storage] index.db FAILED its integrity quick_check (${err2.detail}) \u2014 starting WITHOUT the index (no file moved, no copy, no automatic rebuild; 2026-10-30 owner policy): back up ${path24.join(dir,"index.db")}{,-wal,-shm}, then MOVE those files aside by hand and start again \u2014 the fresh index re-imports the JSON envelopes (#4175/#4626/#4816)`);recordSidecarOpenFailure(`integrity quick_check failed: ${err2.detail}`);integrityQuickCheckFailed=true;return null}store2.resetAllIngestWatermarks()}catch(err2){const errStr=String(err2);const hint=sqliteOpenFailureHint(errStr);const tail=/no SQLite engine available/i.test(errStr)?"":hint!==""?`; ${hint}`:"; check file/OS state (CANTOPEN/readonly) or move index.db{,-wal,-shm} aside after backing up to force a fresh rebuild";log("error",`[storage] unified sidecar failed to open ${dir}/index.db (${errStr}) \u2014 REFUSING TO START (owner policy 2026-10-30: NO degradation in any case \u2014 fix the environment or set BILI_STORAGE_UNIFIED=legacy explicitly to serve JSON-only${tail})`);recordSidecarOpenFailure(errStr);throw err2}const shadow=new _UnifiedShadow(mode,store2,legacyLoad??(()=>null),void 0,path24.join(dir,"index.db"));recordSidecarInstance(shadow);const engineTag=` [engine: ${store2.engine}/${store2.engineSource}]`;const walTag=` [wal-cap: ${walLimit}]`;log("info",mode==="full"?`[storage] unified FULL mode ENABLED (storage.unified=full or BILI_STORAGE_UNIFIED=full): index.db is the load path (unified-first, legacy fallback); legacy files keep being written \u2014 unset the knob to roll back${engineTag}${walTag}`:`[storage] unified shadow mode ENABLED (storage.unified=shadow or BILI_STORAGE_UNIFIED): every session write is double-ingested into index.db and digest-reconciled${engineTag}${walTag}`);return shadow}static async openAsync(dir,env=process.env,legacyLoad,fileUnified,fileWalLimit,fileBackend,fileMysqlDsn){const backendName=resolveBackendName(env,fileBackend);if(backendName!=="mysql")return _UnifiedShadow.maybeOpen(dir,env,legacyLoad,fileUnified,fileWalLimit,fileBackend);const mode=resolveStorageMode(env,fileUnified);if(mode==="legacy")return null;const dsn=(env.BILI_MYSQL_DSN??fileMysqlDsn??"").trim();if(!dsn){const msg="[storage] storage.backend=mysql selected but no DSN is configured (BILI_MYSQL_DSN or storage.mysql.dsn) \u2014 REFUSING TO START; configure the DSN or unset storage.backend (see the CONFIGURATION storage section)";log("error",msg);recordSidecarOpenFailure("mysql backend selected without a DSN");throw new Error(msg)}try{const backend=await openBackend("mysql",dsn);await backend.init?.();const shadow=new _UnifiedShadow(mode,null,legacyLoad??(()=>null),backend);recordSidecarInstance(shadow);log("info",`[storage] unified ${mode==="full"?"FULL":"shadow"} mode on the MYSQL backend (dsn host ${dsn.replace(/:[^:@/]*@/,":***@")}) \u2014 async shadow facade; JSON envelopes keep being written (writerOff is sqlite-only)`);return shadow}catch(err2){const errStr=String(err2);log("error",`[storage] mysql backend failed to open (${errStr}) \u2014 REFUSING TO START (no degradation in any case, 2026-10-30 owner policy); fix the connection or unset storage.backend`);recordSidecarOpenFailure(errStr);throw err2}}static fromBackend(mode,backend,legacyLoad){return new _UnifiedShadow(mode,null,legacyLoad??(()=>null),backend)}get readsUnified(){return this.mode==="full"}record(record4,rawTail,liveCcr){if(this.sync===null){this.enqueueAsyncRecord(record4,rawTail,liveCcr);return}try{const loaded=this.legacyLoad(record4);if(!loaded)return;let legacy=loaded;let hasRawTail=false;if(rawTail&&rawTail.lastMessages.length>0){hasRawTail=true;legacy={...legacy,lastMessages:rawTail.lastMessages,lastMessagesFolded:rawTail.lastMessagesFolded===true}}if(liveCcr)legacy={...legacy,contentStore:liveCcr};if(!this.ingestDelta(legacy,hasRawTail)){const plan2=planIngest(legacy);const completeLog=hasRawTail||this.driftedSessions.has(legacy.id);this.sync.ingestSession(plan2,void 0,{completeLog})}this.stats.ingests++;const count=(this.ingestCounts.get(legacy.id)??0)+1;this.ingestCounts.set(legacy.id,count);if((count-1)%VERIFY_EVERY_INGESTS===0){this.stats.verifySamples++;const sessionRow=this.sync.getSessionRow(legacy.id);if(!sessionRow)throw new Error(`session row missing after ingest: ${legacy.id}`);const verifier=new BatchedViewVerification(legacy,sessionRow,this.sync.getRefs(legacy.id),this.sync.getDeadRefs(legacy.id));for(let offset=0;;offset+=VERIFY_BATCH_SIZE){const rows=this.sync.getBlocks(legacy.id,{limit:VERIFY_BATCH_SIZE,offset});verifier.addBlocks(rows);if(rows.length<VERIFY_BATCH_SIZE)break}for(let i=0;i<verifier.messageSeqs.length;i+=VERIFY_BATCH_SIZE){verifier.addMessages(this.sync.getMessages(legacy.id,{seqs:verifier.messageSeqs.slice(i,i+VERIFY_BATCH_SIZE)}))}const verified=verifier.finish();warnTailGaps(legacy.id,verified);if(!verified.matches){this.stats.verifyDrift++;const repeat=this.driftedSessions.has(legacy.id);this.driftedSessions.add(legacy.id);const streak=(this.driftStreaks.get(legacy.id)??0)+1;this.driftStreaks.set(legacy.id,streak);let diagnosis="";try{diagnosis=formatDriftDiagnostics(verified.diagnostics)}catch{}if(streak===DRIFT_ESCALATE_STREAK){this.frozenEnvelopeIds.add(legacy.id);this.frozenEnvelopeSince.set(legacy.id,Date.now());let sides="";try{const envBlocks=legacy.state.blocks.filter(b2=>b2.active).length;const idxBlocks=verified.activeBlocks;sides=` [envelope ${envBlocks} active block(s) vs index ${idxBlocks}]`}catch{}log("warn",`[storage] DIGEST DRIFT ESCALATED for ${legacy.id}: ${streak} consecutive sampled drifts \u2014 the views have stopped converging${sides}${diagnosis}. Both legs are built in THIS process, so a persistent gap is a digest-shape mismatch first (field only one leg builds, ordering \u2014 #4392) and only then a writer: known producers are a second bili instance sharing one sessions dir (#394 anti-pattern; second-instance detection: #4177), or ONE host re-writing history slots below the ingest watermark on every save (the delta fast path skips them by design, so the sampled backstop cannot converge against a repeating trigger \u2014 #4614). Freezing THIS process's JSON envelope writes for the session until a clean sample re-admits it \u2014 the unified store keeps receiving every save (#4323)`)}this.stats.lastError=`digest drift for ${legacy.id}: unified replay != legacy load view`;this.sync.clearIngestWatermark(legacy.id);log("error",`[storage] unified shadow DIGEST DRIFT for ${legacy.id}: unified replay != legacy load view${repeat?" (repeat: consecutive sampled drift \u2014 the views are not converging)":""}${diagnosis} \u2014 dropped the ingest watermark, the next save re-ingests the full tail`)}else{this.stats.verifyOk++;this.driftedSessions.delete(legacy.id);this.driftStreaks.delete(legacy.id);if(this.frozenEnvelopeIds.delete(legacy.id)){this.frozenEnvelopeSince.delete(legacy.id);log("info",`[storage] drift resolved for ${legacy.id}: clean sample re-admits the session \u2014 envelope writes resume (#4323)`)}}}this.consecutiveFailures=0}catch(err2){this.noteIngestFailure(err2)}}ingestDelta(legacy,hasRawTail){if(this.sync===null)return false;try{const mark=this.sync.ingestWatermark(legacy.id);if(!mark)return false;const boundary=this.sync.probeIngestBoundary(legacy.id,mark.seq);if(!boundary)return false;let head;if(mark.tailSeqs.length>1){const headMsgId=this.sync.headRowMsgId(legacy.id,mark.tailSeqs[0]);if(headMsgId===null)return false;head={msgId:headMsgId}}const plan2=planIngestDelta(legacy,mark.seq,mark.tailSeqs,{msgId:boundary.msgId,contentHash:boundary.contentHash},hasRawTail,head);if(!plan2)return false;const applied=this.sync.ingestSession(plan2,{trustedSeq:mark.seq,boundaryMsgId:boundary.msgId,boundaryHash:boundary.contentHash,trustedTailSeqs:mark.tailSeqs});if(applied)this.stats.deltaIngests++;return applied}catch{return false}}viewFor(id){const store2=this.sync;if(store2===null)return null;try{const unified=store2.readSnapshot(()=>{const sessionRow=store2.getSessionRow(id);if(!sessionRow)return null;const builder=new LegacyViewBuilder(sessionRow,store2.getRefs(id),store2.getDeadRefs(id));for(let offset=0;;offset+=VIEW_READ_BATCH_SIZE){const blocks=store2.getBlocks(id,{limit:VIEW_READ_BATCH_SIZE,offset});builder.addBlocks(blocks);if(blocks.length<VIEW_READ_BATCH_SIZE)break}for(let offset=0;offset<builder.messageSeqs.length;offset+=VIEW_READ_BATCH_SIZE){builder.addMessages(store2.getMessages(id,{seqs:builder.messageSeqs.slice(offset,offset+VIEW_READ_BATCH_SIZE)}))}return builder.finish()});if(!unified)return null;warnTailGaps(id,unified);return unified}catch(err2){log("warn",`[storage] unified load failed for ${id} (${String(err2)}) \u2014 falling back to the legacy file`);return null}}readResidentFieldsFor(id,fields){const store2=this.sync;if(store2===null)return null;try{return store2.readSnapshot(()=>{const header=store2.getLoadHeader(id);if(!header)return null;const result={header};if(fields.metadata){const json=store2.getMetadataJson(id);if(json===null)return null;result.metadata=JSON.parse(json)}if(fields.blockContents){const contents=new Map;for(let offset=0;;offset+=VIEW_READ_BATCH_SIZE){const page=store2.getBlockContents(id,{limit:VIEW_READ_BATCH_SIZE,offset});const blocks=Array.isArray(page)?page:[];appendBlockContents(contents,blocks);if(blocks.length<VIEW_READ_BATCH_SIZE)break}mergeOrphanBlockContents(contents,store2.getOrphansJson(id));result.blockContents=contents}return result})}catch(err2){log("warn",`[storage] resident field load failed for ${id} (${String(err2)}) \u2014 falling back to the legacy file`);return null}}envelopeFrozen(id){return this.sync!==null&&this.frozenEnvelopeIds.has(id)}envelopeFrozenInfo(id){if(!this.envelopeFrozen(id))return null;return{sinceMs:this.frozenEnvelopeSince.get(id)??Date.now()}}frozenEnvelopeDetails(){const out=[];for(const id of this.frozenEnvelopeIds)out.push({id,sinceMs:this.frozenEnvelopeSince.get(id)??Date.now()});out.sort((a,b2)=>a.id.localeCompare(b2.id));return out}activeBlockCount(id){if(this.sync===null)return null;try{return this.sync.getBlocks(id).filter(b2=>b2.active).length}catch{return null}}importRecord(record4){if(this.sync===null)return null;try{const legacy=this.legacyLoad(record4);if(!legacy)return null;this.sync.ingestSession(planIngest(legacy));this.stats.imports++;log("info",`[storage] unified import on first open: ${legacy.id}`);return legacy}catch(err2){log("warn",`[storage] unified import failed for a legacy record (${String(err2)}) \u2014 serving the legacy view`);return null}}remove(id){if(this.sync===null)return;this.ingestCounts.delete(id);this.driftStreaks.delete(id);this.frozenEnvelopeIds.delete(id);this.frozenEnvelopeSince.delete(id);try{this.sync.deleteSession(id)}catch(err2){log("warn",`[storage] unified remove failed for ${id} (${String(err2)})`)}}createCheckpoint(cp2){if(this.sync===null)throw new Error("[storage] sync checkpoint API unavailable on a network backend \u2014 use the async twin");this.sync.insertCheckpoint(cp2)}listCheckpoints(sessionId){if(this.sync===null)return[];return this.sync.listCheckpoints(sessionId)}getCheckpoint(cpId){if(this.sync===null)return void 0;return this.sync.getCheckpoint(cpId)}checkpointState(cpId){if(this.sync===null)throw new Error("[storage] sync checkpoint API unavailable on a network backend \u2014 use the async twin");return this.sync.checkpointState(cpId)}deleteCheckpoint(cpId){if(this.sync===null)return false;return this.sync.deleteCheckpoint(cpId)}sessionUpdatedAt(sessionId){if(this.sync===null)return null;return this.sync.sessionUpdatedAt(sessionId)}sessionTipSeq(sessionId){if(this.sync===null)return 0;return(this.sync.lastLiveSeq(sessionId)??-1)+1}messagesForIds(sessionId,msgIds,includeNeighbors){if(!this.sync)return[];return this.sync.messagesForIds(sessionId,msgIds,includeNeighbors)}listSessionIds(){if(this.sync===null)return[];return this.sync.listSessionIds()}lookupConversation(namespace,conversationId){if(this.sync===null)return null;return this.sync.lookupConversation(namespace,conversationId)}sessionCounters(sessionId){if(this.sync===null)return null;return this.sync.sessionCounters(sessionId)}listConversationBindings(namespace){if(this.sync===null)return[];return this.sync.listConversationBindings(namespace)}backupInto(dstPath){if(this.sync===null)throw new Error("backup is a sqlite-store operation (VACUUM INTO)");return this.sync.backupInto(dstPath)}gc(opts){if(this.sync===null)return{archived:0,contentRowsDeleted:0};return this.sync.gc(opts)}restoreArchived(sessionId,opts){if(this.sync===null)return{ok:false,reason:"async backend \u2014 use restoreArchivedAsync"};return this.sync.restoreArchived(sessionId,opts)}archiveSession(sessionId,opts){if(this.sync===null)return{ok:false,reason:"async backend \u2014 single-session archive unavailable"};return this.sync.archiveSession(sessionId,opts)}allMessageIds(sessionId){if(this.sync===null)return[];return this.sync.allMessageIds(sessionId)}getBlocks(sessionId){if(this.sync===null)return[];return this.sync.getBlocks(sessionId)}archiveBlock(sessionId,blockId,opts){if(this.sync===null)return{ok:false,reason:"async backend \u2014 single-block archive unavailable"};return this.sync.archiveBlock(sessionId,blockId,opts)}restoreBlock(sessionId,blockId,opts){if(this.sync===null)return{ok:false,reason:"async backend \u2014 single-block restore unavailable"};return this.sync.restoreBlock(sessionId,blockId,opts)}sessionStorageStats(sessionId){if(this.sync===null)return null;return this.sync.sessionStorageStats(sessionId)}vacuum(mode){if(this.sync===null)throw new Error("[storage] sync vacuum unavailable on a network backend");return this.sync.vacuum(mode)}gcPlan(archiveAfterDays,now){if(this.sync===null)return null;return this.sync.gcPlan(archiveAfterDays,now)}activeForeignWriter(){if(this.sync===null)return null;return this.sync.activeForeignWriter()}rawMessages(sessionId,fromSeqExclusive){if(this.sync===null)return[];return this.sync.getMessages(sessionId,fromSeqExclusive!==void 0?{fromSeqExclusive}:void 0).map(m2=>({seq:m2.seq,content:m2.content,ts:m2.ts??null}))}tailSeqs(sessionId){if(this.sync===null)return null;return this.sync.tailSeqs(sessionId)}messageIdRows(sessionId){if(this.sync===null)return[];return this.sync.messageIdRows(sessionId)}uncoveredRows(sessionId,intervals){if(this.sync===null)return[];return this.sync.uncoveredRows(sessionId,intervals)}tailViewRows(sessionId){if(this.sync===null)return[];return this.sync.getMessages(sessionId)}messageContentByRefNums(sessionId,refNums){if(this.sync===null||refNums.length===0)return[];return this.sync.messageContentByRefNums(sessionId,refNums)}sessionSummaries(){if(this.sync===null)return[];return this.sync.sessionSummaries()}getCcr(sessionId){if(this.sync===null)return null;return this.sync.getCcr(sessionId)}getSessionMetadata(sessionId){if(this.sync===null)return null;try{return this.sync.getSessionMetadata(sessionId)}catch{return null}}getBlockContents(sessionId){if(this.sync===null)return null;try{return this.sync.getBlockContents(sessionId)}catch{return null}}seqByRaw(sessionId){if(this.sync===null)return null;return this.sync.seqByRaw(sessionId)}liveRowCount(sessionId){if(this.sync!==null)return this.sync.liveRowCount(sessionId);return-1}lastLiveSeq(sessionId){if(this.sync===null)return null;return this.sync.lastLiveSeq(sessionId)}cloneSessionRows(parentId,childId,throughSeq){if(this.sync!==null)return this.sync.cloneSessionRows(parentId,childId,throughSeq);return false}webSummaryRows(){if(this.sync===null)return[];return this.sync.webSummaryRows()}setSessionExt(sessionId,key2,value){if(this.sync===null)return;this.sync.setSessionExt(sessionId,key2,value)}getSessionExt(sessionId,key2){if(this.sync===null)return null;return this.sync.getSessionExt(sessionId,key2)}listSessionExt(sessionId){if(this.sync===null)return[];return this.sync.listSessionExt(sessionId)}deleteSessionExt(sessionId,key2){if(this.sync===null)return 0;return this.sync.deleteSessionExt(sessionId,key2)}setKv(namespace,key2,value){if(this.sync===null)return;this.sync.setKv(namespace,key2,value)}getKv(namespace,key2){if(this.sync===null)return null;return this.sync.getKv(namespace,key2)}listKv(namespace,keyPrefix){if(this.sync===null)return[];return this.sync.listKv(namespace,keyPrefix)}deleteKv(namespace,key2){if(this.sync===null)return 0;return this.sync.deleteKv(namespace,key2)}enqueue(work){const backend=this.backend;if(!backend)return Promise.reject(new Error("[storage] async shadow work without a backend"));const next=this.queueTail.then(work,work);this.queueTail=next.then(()=>void 0,()=>void 0);return next}enqueueAsyncRecord(record4,rawTail,liveCcr){void this.enqueue(async()=>{try{const backend=this.backend;const loaded0=this.legacyLoad(record4);if(!loaded0)return;let legacy=loaded0;let hasRawTail=false;if(rawTail&&rawTail.lastMessages.length>0){hasRawTail=true;legacy={...legacy,lastMessages:rawTail.lastMessages,lastMessagesFolded:rawTail.lastMessagesFolded===true}}if(liveCcr)legacy={...legacy,contentStore:liveCcr};let applied=false;try{const mark=await backend.ingestWatermark(legacy.id);if(mark){const boundary=await backend.probeIngestBoundary(legacy.id,mark.seq);if(boundary){const plan2=planIngestDelta(legacy,mark.seq,mark.tailSeqs,{msgId:boundary.msgId,contentHash:boundary.contentHash},hasRawTail);if(plan2){applied=await backend.ingestSession(plan2,{trustedSeq:mark.seq,boundaryMsgId:boundary.msgId,boundaryHash:boundary.contentHash,trustedTailSeqs:mark.tailSeqs});if(applied)this.stats.deltaIngests++}}}}catch{applied=false}const completeLog=hasRawTail||this.driftedSessions.has(legacy.id);if(!applied)await backend.ingestSession(planIngest(legacy),void 0,{completeLog});this.stats.ingests++;const count=(this.ingestCounts.get(legacy.id)??0)+1;this.ingestCounts.set(legacy.id,count);if((count-1)%VERIFY_EVERY_INGESTS===0){this.stats.verifySamples++;const sessionRow=await backend.getSessionRow(legacy.id);if(!sessionRow)throw new Error(`session row missing after ingest: ${legacy.id}`);const verifier=new BatchedViewVerification(legacy,sessionRow,await backend.getRefs(legacy.id),await backend.getDeadRefs(legacy.id));for(let offset=0;;offset+=VERIFY_BATCH_SIZE){const rows=await backend.getBlocks(legacy.id,{limit:VERIFY_BATCH_SIZE,offset});verifier.addBlocks(rows);if(rows.length<VERIFY_BATCH_SIZE)break}for(let i=0;i<verifier.messageSeqs.length;i+=VERIFY_BATCH_SIZE){verifier.addMessages(await backend.getMessages(legacy.id,{seqs:verifier.messageSeqs.slice(i,i+VERIFY_BATCH_SIZE)}))}const verified=verifier.finish();warnTailGaps(legacy.id,verified);if(!verified.matches){this.stats.verifyDrift++;this.driftedSessions.add(legacy.id);this.stats.lastError=`digest drift for ${legacy.id}: unified replay != legacy load view`;await backend.clearIngestWatermark(legacy.id);log("error",`[storage] unified shadow DIGEST DRIFT for ${legacy.id}: unified replay != legacy load view \u2014 dropped the ingest watermark, the next save re-ingests the full tail`)}else{this.stats.verifyOk++;this.driftedSessions.delete(legacy.id)}}this.consecutiveFailures=0}catch(err2){this.noteIngestFailure(err2)}})}viaAsync(miss,syncValue,via){return this.sync===null?via():Promise.resolve(syncValue())}viewForAsync(id){return this.viaAsync(null,()=>this.viewFor(id),async()=>{try{const backend=this.backend;const loaded=await backend.readSnapshot(async reader=>{const sessionRow=await reader.getSessionRow(id);if(!sessionRow)return null;const builder=new LegacyViewBuilder(sessionRow,await reader.getRefs(id),await reader.getDeadRefs(id));for(let offset=0;;offset+=VIEW_READ_BATCH_SIZE){const blocks=await reader.getBlocks(id,{limit:VIEW_READ_BATCH_SIZE,offset});builder.addBlocks(blocks);if(blocks.length<VIEW_READ_BATCH_SIZE)break}for(let offset=0;offset<builder.messageSeqs.length;offset+=VIEW_READ_BATCH_SIZE){builder.addMessages(await reader.getMessages(id,{seqs:builder.messageSeqs.slice(offset,offset+VIEW_READ_BATCH_SIZE)}))}return builder.finish()});if(!loaded)return null;warnTailGaps(id,loaded);return loaded}catch(err2){log("warn",`[storage] unified load failed for ${id} (${String(err2)}) \u2014 falling back to the legacy file`);return null}})}importRecordAsync(record4){return this.viaAsync(null,()=>this.importRecord(record4),async()=>{try{const legacy=this.legacyLoad(record4);if(!legacy)return null;await this.enqueue(()=>this.backend.ingestSession(planIngest(legacy)));this.stats.imports++;log("info",`[storage] unified import on first open: ${legacy.id}`);return legacy}catch(err2){log("warn",`[storage] unified import failed for a legacy record (${String(err2)}) \u2014 serving the legacy view`);return null}})}removeAsync(id){return this.viaAsync(void 0,()=>this.remove(id),()=>this.enqueue(()=>this.backend.deleteSession(id)).then(()=>void 0))}listSessionIdsAsync(){return this.viaAsync([],()=>this.listSessionIds(),()=>this.backend.listSessionIds())}sessionSummariesAsync(){return this.viaAsync([],()=>this.sessionSummaries(),()=>this.backend.sessionSummaries())}webSummaryRowsAsync(){return this.viaAsync([],()=>this.webSummaryRows(),()=>this.backend.webSummaryRows())}lookupConversationAsync(namespace,conversationId){return this.viaAsync(null,()=>this.lookupConversation(namespace,conversationId),()=>this.backend.lookupConversation(namespace,conversationId))}listConversationBindingsAsync(namespace){return this.viaAsync([],()=>this.listConversationBindings(namespace),()=>this.backend.listConversationBindings(namespace))}sessionCountersAsync(sessionId){return this.viaAsync(null,()=>this.sessionCounters(sessionId),()=>this.backend.sessionCounters(sessionId))}sessionUpdatedAtAsync(sessionId){return this.viaAsync(null,()=>this.sessionUpdatedAt(sessionId),()=>this.backend.sessionUpdatedAt(sessionId))}sessionTipSeqAsync(sessionId){return this.viaAsync(0,()=>this.sessionTipSeq(sessionId),async()=>{const max=await this.backend.lastLiveSeq(sessionId);return(max??-1)+1})}insertCheckpointAsync(cp2){return this.viaAsync(void 0,()=>this.createCheckpoint(cp2),()=>this.enqueue(()=>this.backend.insertCheckpoint(cp2)).then(()=>void 0))}listCheckpointsAsync(sessionId){return this.viaAsync([],()=>this.listCheckpoints(sessionId),()=>this.backend.listCheckpoints(sessionId))}getCheckpointAsync(cpId){return this.viaAsync(void 0,()=>this.getCheckpoint(cpId),()=>this.backend.getCheckpoint(cpId))}checkpointStateAsync(cpId){return this.viaAsync({stateJson:"",byteLen:0},()=>this.checkpointState(cpId),()=>this.backend.checkpointState(cpId))}deleteCheckpointAsync(cpId){return this.viaAsync(false,()=>this.deleteCheckpoint(cpId),()=>this.backend.deleteCheckpoint(cpId))}gcAsync(opts){return this.viaAsync({archived:0,contentRowsDeleted:0},()=>this.gc(opts),()=>this.enqueue(()=>this.backend.gc(opts)))}restoreArchivedAsync(sessionId,opts){return this.viaAsync({ok:false,reason:"async backend"},()=>this.restoreArchived(sessionId,opts),()=>this.enqueue(()=>this.backend.restoreArchived(sessionId,opts)))}rawMessagesAsync(sessionId){return this.viaAsync([],()=>this.rawMessages(sessionId),async()=>(await this.backend.getMessages(sessionId)).map(m2=>({seq:m2.seq,content:m2.content,ts:m2.ts??null})))}tailSeqsAsync(sessionId){return this.viaAsync(null,()=>this.tailSeqs(sessionId),()=>this.backend.tailSeqs(sessionId))}tailViewRowsAsync(sessionId){return this.viaAsync([],()=>this.tailViewRows(sessionId),()=>this.backend.getMessages(sessionId))}lastLiveSeqAsync(sessionId){return this.viaAsync(null,()=>this.lastLiveSeq(sessionId),async()=>{try{return await this.backend.lastLiveSeq(sessionId)}catch(err2){log("warn",`[storage] lastLiveSeq failed for ${sessionId} (${String(err2)}) \u2014 kernel-only fork bound`);return null}})}cloneSessionRowsAsync(parentId,childId,throughSeq){return this.viaAsync(false,()=>this.cloneSessionRows(parentId,childId,throughSeq),async()=>{try{return await this.enqueue(()=>this.backend.cloneSessionRows(parentId,childId,throughSeq))}catch(err2){log("warn",`[storage] fork row clone ${parentId} -> ${childId} failed (${String(err2)}) \u2014 kernel-only fork`);return false}})}createForkAsync(parentId,child){const initial=planIngest(child);if(this.sync!==null){const throughSeq=this.sync.lastLiveSeq(parentId);return Promise.resolve(this.sync.cloneSessionRows(parentId,child.id,throughSeq??-1,initial))}return this.enqueue(async()=>{const throughSeq=await this.backend.lastLiveSeq(parentId);return this.backend.cloneSessionRows(parentId,child.id,throughSeq??-1,initial)})}getCcrAsync(sessionId){return this.viaAsync(null,()=>this.getCcr(sessionId),()=>this.backend.getCcr(sessionId))}setSessionExtAsync(sessionId,key2,value){return this.viaAsync(void 0,()=>this.setSessionExt(sessionId,key2,value),()=>this.enqueue(()=>this.backend.setSessionExt(sessionId,key2,value)).then(()=>void 0))}getSessionExtAsync(sessionId,key2){return this.viaAsync(null,()=>this.getSessionExt(sessionId,key2),()=>this.backend.getSessionExt(sessionId,key2))}listSessionExtAsync(sessionId){return this.viaAsync([],()=>this.listSessionExt(sessionId),()=>this.backend.listSessionExt(sessionId))}deleteSessionExtAsync(sessionId,key2){return this.viaAsync(0,()=>this.deleteSessionExt(sessionId,key2),()=>this.backend.deleteSessionExt(sessionId,key2))}setKvAsync(namespace,key2,value){return this.viaAsync(void 0,()=>this.setKv(namespace,key2,value),()=>this.enqueue(()=>this.backend.setKv(namespace,key2,value)).then(()=>void 0))}getKvAsync(namespace,key2){return this.viaAsync(null,()=>this.getKv(namespace,key2),()=>this.backend.getKv(namespace,key2))}listKvAsync(namespace,keyPrefix){return this.viaAsync([],()=>this.listKv(namespace,keyPrefix),()=>this.backend.listKv(namespace,keyPrefix))}deleteKvAsync(namespace,key2){return this.viaAsync(0,()=>this.deleteKv(namespace,key2),()=>this.backend.deleteKv(namespace,key2))}async closeAsync(){if(this.sync!==null){this.close();return}try{await this.queueTail}catch{}await this.backend?.close()}close(){if(this.sync===null)return;try{this.sync.close()}catch(err2){log("warn",`[storage] sidecar sqlite close failed \u2014 handle may stay locked: ${String(err2)}`)}}};BatchedViewVerification=class{constructor(legacy,session,refs,deadRefs){this.legacy=legacy;const header=loadLegacyView({session,refs,deadRefs,messages:[],blocks:[]});this.orphans=header.blockContents;this.remainingContents=new Map(completeBlockContents(legacy.blockContents,legacy.state.blocks));this.tail=JSON.parse(session.tailJson);this.messageSeqs=[...new Set([...this.tail.tailSeqs??[],...this.tail.pluginSnapshotSeqs??[]])];const withoutBulk=view=>({...view,state:{...view.state,blocks:[]},blockContents:new Map,lastMessages:view.lastMessages===void 0?void 0:[],pluginSnapshot:view.pluginSnapshot===void 0?void 0:[]});const expect=withoutBulk(legacy);const got=withoutBulk(header);if(shadowDigest(expect)!==shadowDigest(got)){this.drift=true;try{const diag=describeViewDivergence(expect,got);this.headerDiag=diag;for(const key2 of diag.keys)this.keys.add(key2)}catch{}}}legacy;messageSeqs;tail;remainingContents;orphans;messages=new Map;keys=new Set;headerDiag=null;drift=false;blockCount=0;activeBlocks=0;tailGaps=0;tailSlot;addBlocks(rows){for(const row of rows){const payload=JSON.parse(row.payloadJson);if(payload?.active===true)this.activeBlocks++;if(this.blockCount>=this.legacy.state.blocks.length||shadowDigest(payload)!==shadowDigest(this.legacy.state.blocks[this.blockCount]))this.changed("state");this.blockCount++;this.compareContents(row.blockId,{one:row.one===null?null:JSON.parse(row.one),full:JSON.parse(row.summary)});this.orphans.delete(row.blockId)}}addMessages(rows){for(const row of rows)this.messages.set(row.seq,messageSignature(JSON.parse(row.content)))}changed(key2){this.drift=true;this.keys.add(key2)}compareContents(id,view){if(!this.remainingContents.has(id)||shadowDigest(this.remainingContents.get(id))!==shadowDigest(view))this.changed("blockContents");this.remainingContents.delete(id)}compareMessages(key2,seqs){const expected=this.legacy[key2];let index=0;for(const seq of seqs??[]){const got=this.messages.get(seq);if(!got){this.tailGaps++;continue}const want=expected&&index<expected.length?messageSignature(expected[index]):void 0;if(!want||want.digest!==got.digest){this.changed(key2);if(key2==="lastMessages"&&expected&&!this.tailSlot){this.tailSlot={index,expect:want?.slot??missingSlot(),got:got.slot}}}index++}if(seqs&&expected&&index<expected.length){this.changed(key2);if(key2==="lastMessages"&&!this.tailSlot)this.tailSlot={index,expect:messageSignature(expected[index]).slot,got:missingSlot()}}}finish(){if(this.blockCount!==this.legacy.state.blocks.length)this.changed("state");for(const[id,view]of this.orphans)this.compareContents(id,view);if(this.remainingContents.size>0)this.changed("blockContents");this.compareMessages("lastMessages",this.tail.tailSeqs);this.compareMessages("pluginSnapshot",this.tail.pluginSnapshotSeqs);const diagnostics={keys:[...this.keys].sort()};if(this.headerDiag?.stateKeys)diagnostics.stateKeys=this.headerDiag.stateKeys;if(this.tailSlot)diagnostics.tailSlot=this.tailSlot;return{matches:!this.drift,activeBlocks:this.activeBlocks,tailGaps:this.tailGaps,diagnostics}}}}});function isNoEngineError(errStr){return/no SQLite engine available/i.test(errStr)}function freshState(){return{requested:null,encryptionBlocked:false,persistDisabled:false,sidecar:null,sidecarOpenError:null,bootstrap:null,integrity:null,secondProcess:null,splitBrain:null,splitBrainAcks:new Map,backup:null}}function recordEngineBootstrap(outcome){state.bootstrap=outcome}function recordSidecarOpenFailure(error){state.sidecar=null;state.sidecarOpenError=error}function recordSidecarInstance(shadow){state.sidecar=shadow;state.sidecarOpenError=null}function recordRequestedMode(mode,encryptionBlocked,persistDisabled=false){state.requested=mode;state.encryptionBlocked=encryptionBlocked;state.persistDisabled=persistDisabled}function recordIntegrityOutcome(dbPath,ok,durationMs,detail){state.integrity={ok,checkedAt:Date.now(),durationMs,...detail===void 0?{}:{detail:`${dbPath}: ${detail}`}}}function recordSecondProcessOwner(pid,info){state.secondProcess={pid,at:Date.now(),benign:false,...info??{}}}function ackSplitBrainContest(sessionId){const cur=state.splitBrain;if(cur===null||cur.sessionId!==sessionId)return false;state.splitBrainAcks.set(`${cur.sessionId}|${cur.peer.instanceId}`,cur.peer.servedAt);while(state.splitBrainAcks.size>MAX_SPLIT_BRAIN_ACKS){const oldest=state.splitBrainAcks.keys().next().value;if(oldest===void 0)break;state.splitBrainAcks.delete(oldest)}state.splitBrain=null;return true}function recordBackupOutcome(lastPath,lastBytes){state.backup={lastPath,lastAt:Date.now(),lastBytes}}function pidAlive(pid){try{process.kill(pid,0);return true}catch(err2){return err2.code==="EPERM"}}function shortenError(err2){const oneLine=err2.replace(/\s+/g," ").trim();if(oneLine.length<=160)return oneLine;return`${safePrefix(oneLine,78)}\u2026${safeSuffix(oneLine,78)}`}function degradeReason(){if(state.bootstrap?.status==="unsupported-node"){return`no self-downloaded SQLite engine supports this Node.js (${state.bootstrap.detail??"unknown"})${nodeSqliteUpgradeHint()}`}if(state.sidecarOpenError){const e=shortenError(state.sidecarOpenError);if(isNoEngineError(e)){return`no SQLite engine available (node:sqlite missing, better-sqlite3 not installed)${nodeSqliteUpgradeHint()}`}if(/StorageIntegrityError|integrity quick_check failed/i.test(state.sidecarOpenError)){return`index database failed its integrity check and was left UNTOUCHED (${e}) \u2014 bili is starting WITHOUT the index (envelope-served); fix: back up index.db{,-wal,-shm}, move those files aside by hand, start again`}return`index database failed to open (${e})${sqliteOpenFailureHint(state.sidecarOpenError)}`}const b2=state.bootstrap;if(b2){switch(b2.status){case"cooldown":return`SQLite self-download blocked (${b2.detail??"unknown"}), retrying after cooldown`;case"unsupported-platform":return`unsupported platform for SQLite self-download (${b2.detail??"?"})`;case"disabled":return"SQLite self-download disabled by configuration";case"failed":return`SQLite self-download failed (${b2.detail??"unknown"})`;default:break}}return`no SQLite engine available (node:sqlite missing, better-sqlite3 not installed)${nodeSqliteUpgradeHint()}`}function cooldownState(){const now=Date.now();if(cooldownCache&&now-cooldownCache.at<COOLDOWN_CACHE_MS){return{marker:cooldownCache.marker,remainingMs:cooldownCache.marker?Math.max(0,cooldownCache.marker.atMs+COOLDOWN_MS-now):null}}const marker=readBootstrapFailureMarker();cooldownCache={at:now,marker};return{marker,remainingMs:marker?Math.max(0,marker.atMs+COOLDOWN_MS-now):null}}function getStorageRuntimeStatus(){const requested=state.requested??resolveStorageMode(process.env,fileStorageUnified());const intentionalOptOut=state.encryptionBlocked||state.persistDisabled;const sidecar=state.sidecar;const effective=requested!=="legacy"&&!intentionalOptOut&&sidecar?requested:"legacy";const degraded=requested!=="legacy"&&!intentionalOptOut&&sidecar===null;const cd=cooldownState();const sp=state.secondProcess;if(sp!==null&&!pidAlive(sp.pid)){state.secondProcess=null;log("info",`[storage] second-process pid ${sp.pid} has exited \u2014 stale warning cleared`)}const sb=state.splitBrain;if(sb!==null&&splitBrainEvidenceCheck!==null&&splitBrainEvidenceCheck(sb)===false){state.splitBrain=null;log("info",`[split-brain] session ${sb.sessionId} notice cleared \u2014 peer ${sb.peer.instanceId} (pid ${sb.peer.pid}) no longer contests it`)}return{requested,effective,degraded,intentionalOptOut,reason:degraded?degradeReason():null,engine:sidecar?sidecar.engineInfo:state.sidecarOpenError!==null&&!isNoEngineError(state.sidecarOpenError)?resolvedSqliteEngineInfo():null,bootstrap:state.bootstrap?.status??null,bootstrapFailure:cd.marker,cooldownRemainingMs:cd.remainingMs,sidecarDisabled:false,sidecarLastError:sidecar?.stats.lastError??null,indexDbOpenError:state.sidecarOpenError,verifyDrift:sidecar?.stats.verifyDrift??0,driftedSessions:sidecar?.driftedSessions.size??0,integrity:state.integrity,secondProcess:state.secondProcess,splitBrain:state.splitBrain,backup:state.backup,frozenEnvelopeSessions:sidecar?.frozenEnvelopeIds.size??0,frozenEnvelopeDetails:sidecar?.frozenEnvelopeDetails()??[]}}function splitBrainWire(cur){if(cur===null)return null;const strip=x=>({instanceId:x.instanceId,pid:x.pid,origin:x.origin,version:x.version,lane:x.lane});return{sessionId:cur.sessionId,title:cur.title,self:strip(cur.self),peer:strip(cur.peer),at:cur.at}}function storageStatusWire(){const st2=getStorageRuntimeStatus();return{requested:st2.requested,effective:st2.effective,degraded:st2.degraded,intentionalOptOut:st2.intentionalOptOut,reason:st2.reason,engine:st2.engine,bootstrap:st2.bootstrap,bootstrapFailure:st2.bootstrapFailure,cooldownRemainingMs:st2.cooldownRemainingMs,sidecarDisabled:st2.sidecarDisabled,verifyDrift:st2.verifyDrift,driftedSessions:st2.driftedSessions,integrity:st2.integrity,secondProcess:st2.secondProcess,splitBrain:splitBrainWire(st2.splitBrain),backup:st2.backup,frozenEnvelopeSessions:st2.frozenEnvelopeSessions,frozenEnvelopeDetails:st2.frozenEnvelopeDetails}}function storageDiagnosticsLines(ctx){const st2=getStorageRuntimeStatus();const env=process.env;const fileUnified=fileStorageUnified();const fileJsonWriter=fileStorageJsonWriter();const fileAutoDownload=fileStorageAutoDownload();const fileWalLimit=fileStorageWalJournalSizeLimit();const lines=["--- storage ---",`requested mode: ${st2.requested}`,`effective mode: ${st2.effective}${st2.intentionalOptOut?" (BILI_ENCRYPTION_KEY opt-out \u2014 intentional)":""}`,...st2.degraded&&st2.reason?[`degrade reason: ${st2.reason}`]:[],`engine: ${st2.engine?`${st2.engine.name}/${st2.engine.source}${state.sidecarOpenError!==null&&!isNoEngineError(state.sidecarOpenError)?" (resolved, but index.db open failed \u2014 see degrade reason)":""}`:"none"}`,`engine bootstrap: ${st2.bootstrap??"not run"}`,...st2.bootstrapFailure?[`bootstrap failure marker: at=${new Date(st2.bootstrapFailure.atMs).toISOString()} reason="${st2.bootstrapFailure.reason}"${st2.cooldownRemainingMs?` (cooldown ~${Math.round(st2.cooldownRemainingMs/6e4)}m remaining, until ${new Date(st2.bootstrapFailure.atMs+COOLDOWN_MS).toISOString()})`:""}`,`force immediate retry: delete ${bootstrapFailureMarkerPath()} and restart`]:[],`BILI_STORAGE_UNIFIED: ${env.BILI_STORAGE_UNIFIED??"(unset)"}`,`storage.unified (config file): ${fileUnified??"(unset)"}`,`BILI_STORAGE_JSON_WRITER: ${env.BILI_STORAGE_JSON_WRITER??"(unset)"}`,`storage.jsonWriter (config file): ${fileJsonWriter??"(unset)"}`,`BILI_SQLITE_AUTO_DOWNLOAD: ${env.BILI_SQLITE_AUTO_DOWNLOAD??"(unset)"}`,`storage.sqliteAutoDownload (config file): ${fileAutoDownload??"(unset)"}`,`BILI_STORAGE_WAL_JOURNAL_SIZE_LIMIT_BYTES: ${env.BILI_STORAGE_WAL_JOURNAL_SIZE_LIMIT_BYTES??"(unset)"}`,`storage.walJournalSizeLimitBytes (config file): ${fileWalLimit??"(unset)"}`,`BILI_ENCRYPTION_KEY set: ${env.BILI_ENCRYPTION_KEY!==void 0&&env.BILI_ENCRYPTION_KEY!==""?"yes":"no"}`,`sessions on disk: ${ctx.sessions}`,...st2.frozenEnvelopeDetails.map(f2=>`frozen envelope writes: ${f2.id} (since ${new Date(f2.sinceMs).toISOString()})`)];if(ctx.storageLogLines.length>0){lines.push("last [storage] log lines:");lines.push(...ctx.storageLogLines.map(l=>` ${l}`))}return lines}var state,MAX_SPLIT_BRAIN_ACKS,splitBrainEvidenceCheck,COOLDOWN_CACHE_MS,cooldownCache;var init_runtime_status=__esm({"src/storage/runtime-status.ts"(){"use strict";init_engine_bootstrap();init_knobs();init_logger();init_text_safe();init_driver();init_shadow();state=freshState();MAX_SPLIT_BRAIN_ACKS=64;splitBrainEvidenceCheck=null;COOLDOWN_CACHE_MS=3e4;cooldownCache=null}});var require_constants6=__commonJS({"node_modules/ws/lib/constants.js"(exports,module){"use strict";var BINARY_TYPES=["nodebuffer","arraybuffer","fragments"];var hasBlob=typeof Blob!=="undefined";if(hasBlob)BINARY_TYPES.push("blob");module.exports={BINARY_TYPES,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}});var require_buffer_util=__commonJS({"node_modules/ws/lib/buffer-util.js"(exports,module){"use strict";var{EMPTY_BUFFER}=require_constants6();var FastBuffer=Buffer[Symbol.species];function concat(list,totalLength){if(list.length===0)return EMPTY_BUFFER;if(list.length===1)return list[0];const target=Buffer.allocUnsafe(totalLength);let offset=0;for(let i=0;i<list.length;i++){const buf=list[i];target.set(buf,offset);offset+=buf.length}if(offset<totalLength){return new FastBuffer(target.buffer,target.byteOffset,offset)}return target}function _mask(source,mask,output,offset,length){for(let i=0;i<length;i++){output[offset+i]=source[i]^mask[i&3]}}function _unmask(buffer,mask){for(let i=0;i<buffer.length;i++){buffer[i]^=mask[i&3]}}function toArrayBuffer(buf){if(buf.length===buf.buffer.byteLength){return buf.buffer}return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.length)}function toBuffer(data){toBuffer.readOnly=true;if(Buffer.isBuffer(data))return data;let buf;if(data instanceof ArrayBuffer){buf=new FastBuffer(data)}else if(ArrayBuffer.isView(data)){buf=new FastBuffer(data.buffer,data.byteOffset,data.byteLength)}else{buf=Buffer.from(data);toBuffer.readOnly=false}return buf}module.exports={concat,mask:_mask,toArrayBuffer,toBuffer,unmask:_unmask};if(!process.env.WS_NO_BUFFER_UTIL){try{const bufferUtil=__require("bufferutil");module.exports.mask=function(source,mask,output,offset,length){if(length<48)_mask(source,mask,output,offset,length);else bufferUtil.mask(source,mask,output,offset,length)};module.exports.unmask=function(buffer,mask){if(buffer.length<32)_unmask(buffer,mask);else bufferUtil.unmask(buffer,mask)}}catch(e){}}}});var require_limiter=__commonJS({"node_modules/ws/lib/limiter.js"(exports,module){"use strict";var kDone=Symbol("kDone");var kRun=Symbol("kRun");var Limiter=class{constructor(concurrency){this[kDone]=()=>{this.pending--;this[kRun]()};this.concurrency=concurrency||Infinity;this.jobs=[];this.pending=0}add(job){this.jobs.push(job);this[kRun]()}[kRun](){if(this.pending===this.concurrency)return;if(this.jobs.length){const job=this.jobs.shift();this.pending++;job(this[kDone])}}};module.exports=Limiter}});var require_permessage_deflate2=__commonJS({"node_modules/ws/lib/permessage-deflate.js"(exports,module){"use strict";var zlib2=__require("zlib");var bufferUtil=require_buffer_util();var Limiter=require_limiter();var{kStatusCode}=require_constants6();var FastBuffer=Buffer[Symbol.species];var TRAILER=Buffer.from([0,0,255,255]);var kPerMessageDeflate=Symbol("permessage-deflate");var kTotalLength=Symbol("total-length");var kCallback=Symbol("callback");var kBuffers=Symbol("buffers");var kError=Symbol("error");var zlibLimiter;var PerMessageDeflate2=class{constructor(options){this._options=options||{};this._threshold=this._options.threshold!==void 0?this._options.threshold:1024;this._maxPayload=this._options.maxPayload|0;this._isServer=!!this._options.isServer;this._deflate=null;this._inflate=null;this.params=null;if(!zlibLimiter){const concurrency=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){const params={};if(this._options.serverNoContextTakeover){params.server_no_context_takeover=true}if(this._options.clientNoContextTakeover){params.client_no_context_takeover=true}if(this._options.serverMaxWindowBits){params.server_max_window_bits=this._options.serverMaxWindowBits}if(this._options.clientMaxWindowBits){params.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits==null){params.client_max_window_bits=true}return params}accept(configurations){configurations=this.normalizeParams(configurations);this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations);return this.params}cleanup(){if(this._inflate){this._inflate.close();this._inflate=null}if(this._deflate){const callback=this._deflate[kCallback];this._deflate.close();this._deflate=null;if(callback){callback(new Error("The deflate stream was closed while data was being processed"))}}}acceptAsServer(offers){const opts=this._options;const accepted=offers.find(params=>{if(opts.serverNoContextTakeover===false&¶ms.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===false||typeof opts.serverMaxWindowBits==="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits==="number"&&(typeof params.client_max_window_bits==="number"?opts.clientMaxWindowBits>params.client_max_window_bits:!params.client_max_window_bits)){return false}return true});if(!accepted){throw new Error("None of the extension offers can be accepted")}if(opts.serverNoContextTakeover){accepted.server_no_context_takeover=true}if(opts.clientNoContextTakeover){accepted.client_no_context_takeover=true}if(typeof opts.serverMaxWindowBits==="number"){accepted.server_max_window_bits=opts.serverMaxWindowBits}if(typeof opts.clientMaxWindowBits==="number"){accepted.client_max_window_bits=opts.clientMaxWindowBits}else if(accepted.client_max_window_bits===true||opts.clientMaxWindowBits===false){delete accepted.client_max_window_bits}return accepted}acceptAsClient(response){const params=response[0];if(this._options.clientNoContextTakeover===false&¶ms.client_no_context_takeover){throw new Error('Unexpected parameter "client_no_context_takeover"')}if(!params.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number"){params.client_max_window_bits=this._options.clientMaxWindowBits}}else if(this._options.clientMaxWindowBits===false||typeof this._options.clientMaxWindowBits==="number"&¶ms.client_max_window_bits>this._options.clientMaxWindowBits){throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}return params}normalizeParams(configurations){configurations.forEach(params=>{Object.keys(params).forEach(key2=>{let value=params[key2];if(value.length>1){throw new Error(`Parameter "${key2}" must have only a single value`)}value=value[0];if(key2==="client_max_window_bits"){if(value!==true){const num7=+value;if(!Number.isInteger(num7)||num7<8||num7>15){throw new TypeError(`Invalid value for parameter "${key2}": ${value}`)}value=num7}else if(!this._isServer){throw new TypeError(`Invalid value for parameter "${key2}": ${value}`)}}else if(key2==="server_max_window_bits"){const num7=+value;if(!Number.isInteger(num7)||num7<8||num7>15){throw new TypeError(`Invalid value for parameter "${key2}": ${value}`)}value=num7}else if(key2==="client_no_context_takeover"||key2==="server_no_context_takeover"){if(value!==true){throw new TypeError(`Invalid value for parameter "${key2}": ${value}`)}}else{throw new Error(`Unknown parameter "${key2}"`)}params[key2]=value})});return configurations}decompress(data,fin,callback){zlibLimiter.add(done=>{this._decompress(data,fin,(err2,result)=>{done();callback(err2,result)})})}compress(data,fin,callback){zlibLimiter.add(done=>{this._compress(data,fin,(err2,result)=>{done();callback(err2,result)})})}_decompress(data,fin,callback){const endpoint=this._isServer?"client":"server";if(!this._inflate){const key2=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key2]!=="number"?zlib2.Z_DEFAULT_WINDOWBITS:this.params[key2];this._inflate=zlib2.createInflateRaw({...this._options.zlibInflateOptions,windowBits});this._inflate[kPerMessageDeflate]=this;this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];this._inflate.on("error",inflateOnError);this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback;this._inflate.write(data);if(fin)this._inflate.write(TRAILER);this._inflate.flush(()=>{const err2=this._inflate[kError];if(err2){this._inflate.close();this._inflate=null;callback(err2);return}const data2=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);if(this._inflate._readableState.endEmitted){this._inflate.close();this._inflate=null}else{this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._inflate.reset()}}callback(null,data2)})}_compress(data,fin,callback){const endpoint=this._isServer?"server":"client";if(!this._deflate){const key2=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key2]!=="number"?zlib2.Z_DEFAULT_WINDOWBITS:this.params[key2];this._deflate=zlib2.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits});this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback;this._deflate.write(data);this._deflate.flush(zlib2.Z_SYNC_FLUSH,()=>{if(!this._deflate){return}let data2=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);if(fin){data2=new FastBuffer(data2.buffer,data2.byteOffset,data2.length-4)}this._deflate[kCallback]=null;this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._deflate.reset()}callback(null,data2)})}};module.exports=PerMessageDeflate2;function deflateOnData(chunk){this[kBuffers].push(chunk);this[kTotalLength]+=chunk.length}function inflateOnData(chunk){this[kTotalLength]+=chunk.length;if(this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded");this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";this[kError][kStatusCode]=1009;this.removeListener("data",inflateOnData);this.reset()}function inflateOnError(err2){this[kPerMessageDeflate]._inflate=null;if(this[kError]){this[kCallback](this[kError]);return}err2[kStatusCode]=1007;this[kCallback](err2)}}});var require_validation=__commonJS({"node_modules/ws/lib/validation.js"(exports,module){"use strict";var{isUtf8}=__require("buffer");var{hasBlob}=require_constants6();var tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(code){return code>=1e3&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3e3&&code<=4999}function _isValidUTF8(buf){const len=buf.length;let i=0;while(i<len){if((buf[i]&128)===0){i++}else if((buf[i]&224)===192){if(i+1===len||(buf[i+1]&192)!==128||(buf[i]&254)===192){return false}i+=2}else if((buf[i]&240)===224){if(i+2>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||buf[i]===224&&(buf[i+1]&224)===128||buf[i]===237&&(buf[i+1]&224)===160){return false}i+=3}else if((buf[i]&248)===240){if(i+3>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||(buf[i+3]&192)!==128||buf[i]===240&&(buf[i+1]&240)===128||buf[i]===244&&buf[i+1]>143||buf[i]>244){return false}i+=4}else{return false}}return true}function isBlob(value){return hasBlob&&typeof value==="object"&&typeof value.arrayBuffer==="function"&&typeof value.type==="string"&&typeof value.stream==="function"&&(value[Symbol.toStringTag]==="Blob"||value[Symbol.toStringTag]==="File")}module.exports={isBlob,isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8){module.exports.isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)}}else if(!process.env.WS_NO_UTF_8_VALIDATE){try{const isValidUTF8=__require("utf-8-validate");module.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch(e){}}}});var require_receiver2=__commonJS({"node_modules/ws/lib/receiver.js"(exports,module){"use strict";var{Writable}=__require("stream");var PerMessageDeflate2=require_permessage_deflate2();var{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants6();var{concat,toArrayBuffer,unmask}=require_buffer_util();var{isValidStatusCode,isValidUTF8}=require_validation();var FastBuffer=Buffer[Symbol.species];var GET_INFO=0;var GET_PAYLOAD_LENGTH_16=1;var GET_PAYLOAD_LENGTH_64=2;var GET_MASK=3;var GET_DATA=4;var INFLATING=5;var DEFER_EVENT=6;var Receiver2=class extends Writable{constructor(options={}){super();this._allowSynchronousEvents=options.allowSynchronousEvents!==void 0?options.allowSynchronousEvents:true;this._binaryType=options.binaryType||BINARY_TYPES[0];this._extensions=options.extensions||{};this._isServer=!!options.isServer;this._maxBufferedChunks=options.maxBufferedChunks|0;this._maxFragments=options.maxFragments|0;this._maxPayload=options.maxPayload|0;this._skipUTF8Validation=!!options.skipUTF8Validation;this[kWebSocket]=void 0;this._bufferedBytes=0;this._buffers=[];this._compressed=false;this._payloadLength=0;this._mask=void 0;this._fragmented=0;this._masked=false;this._fin=false;this._opcode=0;this._totalPayloadLength=0;this._messageLength=0;this._numFragments=0;this._fragments=[];this._errored=false;this._loop=false;this._state=GET_INFO}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){cb(this.createError(RangeError,"Too many buffered chunks",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=chunk.length;this._buffers.push(chunk);this.startLoop(cb)}consume(n){this._bufferedBytes-=n;if(n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){const buf=this._buffers[0];this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n);return new FastBuffer(buf.buffer,buf.byteOffset,n)}const dst=Buffer.allocUnsafe(n);do{const buf=this._buffers[0];const offset=dst.length-n;if(n>=buf.length){dst.set(this._buffers.shift(),offset)}else{dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset);this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n)}n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=true;do{switch(this._state){case GET_INFO:this.getInfo(cb);break;case GET_PAYLOAD_LENGTH_16:this.getPayloadLength16(cb);break;case GET_PAYLOAD_LENGTH_64:this.getPayloadLength64(cb);break;case GET_MASK:this.getMask();break;case GET_DATA:this.getData(cb);break;case INFLATING:case DEFER_EVENT:this._loop=false;return}}while(this._loop);if(!this._errored)cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=false;return}const buf=this.consume(2);if((buf[0]&48)!==0){const error=this.createError(RangeError,"RSV2 and RSV3 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error);return}const compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate2.extensionName]){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}this._fin=(buf[0]&128)===128;this._opcode=buf[0]&15;this._payloadLength=buf[1]&127;if(this._opcode===0){if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(!this._fragmented){const error=this.createError(RangeError,"invalid opcode 0",true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const error=this.createError(RangeError,"FIN must be set",true,1002,"WS_ERR_EXPECTED_FIN");cb(error);return}if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){const error=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error);return}}else{const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;this._masked=(buf[1]&128)===128;if(this._isServer){if(!this._masked){const error=this.createError(RangeError,"MASK must be set",true,1002,"WS_ERR_EXPECTED_MASK");cb(error);return}}else if(this._masked){const error=this.createError(RangeError,"MASK must be clear",true,1002,"WS_ERR_UNEXPECTED_MASK");cb(error);return}if(this._payloadLength===126)this._state=GET_PAYLOAD_LENGTH_16;else if(this._payloadLength===127)this._state=GET_PAYLOAD_LENGTH_64;else this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=false;return}this._payloadLength=this.consume(2).readUInt16BE(0);this.haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=false;return}const buf=this.consume(8);const num7=buf.readUInt32BE(0);if(num7>Math.pow(2,53-32)-1){const error=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",false,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error);return}this._payloadLength=num7*Math.pow(2,32)+buf.readUInt32BE(4);this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8){this._totalPayloadLength+=this._payloadLength;if(this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}}if(this._masked)this._state=GET_MASK;else this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=false;return}this._mask=this.consume(4);this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=false;return}data=this.consume(this._payloadLength);if(this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0){unmask(data,this._mask)}}if(this._opcode>7){this.controlMessage(data,cb);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){const error=this.createError(RangeError,"Too many message fragments",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error);return}if(this._compressed){this._state=INFLATING;this.decompress(data,cb);return}if(data.length){this._messageLength=this._totalPayloadLength;this._fragments.push(data)}this.dataMessage(cb)}decompress(data,cb){const perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];perMessageDeflate.decompress(data,this._fin,(err2,buf)=>{if(err2)return cb(err2);if(buf.length){this._messageLength+=buf.length;if(this._messageLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}this._fragments.push(buf)}this.dataMessage(cb);if(this._state===GET_INFO)this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=GET_INFO;return}const messageLength=this._messageLength;const fragments=this._fragments;this._totalPayloadLength=0;this._messageLength=0;this._fragmented=0;this._numFragments=0;this._fragments=[];if(this._opcode===2){let data;if(this._binaryType==="nodebuffer"){data=concat(fragments,messageLength)}else if(this._binaryType==="arraybuffer"){data=toArrayBuffer(concat(fragments,messageLength))}else if(this._binaryType==="blob"){data=new Blob(fragments)}else{data=fragments}if(this._allowSynchronousEvents){this.emit("message",data,true);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",data,true);this._state=GET_INFO;this.startLoop(cb)})}}else{const buf=concat(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}if(this._state===INFLATING||this._allowSynchronousEvents){this.emit("message",buf,false);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",buf,false);this._state=GET_INFO;this.startLoop(cb)})}}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0){this._loop=false;this.emit("conclude",1005,EMPTY_BUFFER);this.end()}else{const code=data.readUInt16BE(0);if(!isValidStatusCode(code)){const error=this.createError(RangeError,`invalid status code ${code}`,true,1002,"WS_ERR_INVALID_CLOSE_CODE");cb(error);return}const buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._loop=false;this.emit("conclude",code,buf);this.end()}this._state=GET_INFO;return}if(this._allowSynchronousEvents){this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO;this.startLoop(cb)})}}createError(ErrorCtor,message,prefix,statusCode,errorCode){this._loop=false;this._errored=true;const err2=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message}`:message);Error.captureStackTrace(err2,this.createError);err2.code=errorCode;err2[kStatusCode]=statusCode;return err2}};module.exports=Receiver2}});var require_sender2=__commonJS({"node_modules/ws/lib/sender.js"(exports,module){"use strict";var{Duplex}=__require("stream");var{randomFillSync}=__require("crypto");var{types:{isUint8Array}}=__require("util");var PerMessageDeflate2=require_permessage_deflate2();var{EMPTY_BUFFER,kWebSocket,NOOP}=require_constants6();var{isBlob,isValidStatusCode}=require_validation();var{mask:applyMask,toBuffer}=require_buffer_util();var kByteLength=Symbol("kByteLength");var maskBuffer=Buffer.alloc(4);var RANDOM_POOL_SIZE=8*1024;var randomPool;var randomPoolPointer=RANDOM_POOL_SIZE;var DEFAULT=0;var DEFLATING=1;var GET_BLOB_DATA=2;var Sender2=class _Sender{constructor(socket,extensions,generateMask){this._extensions=extensions||{};if(generateMask){this._generateMask=generateMask;this._maskBuffer=Buffer.alloc(4)}this._socket=socket;this._firstFragment=true;this._compress=false;this._bufferedBytes=0;this._queue=[];this._state=DEFAULT;this.onerror=NOOP;this[kWebSocket]=void 0}static frame(data,options){let mask;let merge=false;let offset=2;let skipMasking=false;if(options.mask){mask=options.maskBuffer||maskBuffer;if(options.generateMask){options.generateMask(mask)}else{if(randomPoolPointer===RANDOM_POOL_SIZE){if(randomPool===void 0){randomPool=Buffer.alloc(RANDOM_POOL_SIZE)}randomFillSync(randomPool,0,RANDOM_POOL_SIZE);randomPoolPointer=0}mask[0]=randomPool[randomPoolPointer++];mask[1]=randomPool[randomPoolPointer++];mask[2]=randomPool[randomPoolPointer++];mask[3]=randomPool[randomPoolPointer++]}skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0;offset=6}let dataLength;if(typeof data==="string"){if((!options.mask||skipMasking)&&options[kByteLength]!==void 0){dataLength=options[kByteLength]}else{data=Buffer.from(data);dataLength=data.length}}else{dataLength=data.length;merge=options.mask&&options.readOnly&&!skipMasking}let payloadLength=dataLength;if(dataLength>=65536){offset+=8;payloadLength=127}else if(dataLength>125){offset+=2;payloadLength=126}const target=Buffer.allocUnsafe(merge?dataLength+offset:offset);target[0]=options.fin?options.opcode|128:options.opcode;if(options.rsv1)target[0]|=64;target[1]=payloadLength;if(payloadLength===126){target.writeUInt16BE(dataLength,2)}else if(payloadLength===127){target[2]=target[3]=0;target.writeUIntBE(dataLength,4,6)}if(!options.mask)return[target,data];target[1]|=128;target[offset-4]=mask[0];target[offset-3]=mask[1];target[offset-2]=mask[2];target[offset-1]=mask[3];if(skipMasking)return[target,data];if(merge){applyMask(data,mask,target,offset,dataLength);return[target]}applyMask(data,mask,data,0,dataLength);return[target,data]}close(code,data,mask,cb){let buf;if(code===void 0){buf=EMPTY_BUFFER}else if(typeof code!=="number"||!isValidStatusCode(code)){throw new TypeError("First argument must be a valid error code number")}else if(data===void 0||!data.length){buf=Buffer.allocUnsafe(2);buf.writeUInt16BE(code,0)}else{const length=Buffer.byteLength(data);if(length>123){throw new RangeError("The message must not be greater than 123 bytes")}buf=Buffer.allocUnsafe(2+length);buf.writeUInt16BE(code,0);if(typeof data==="string"){buf.write(data,2)}else if(isUint8Array(data)){buf.set(data,2)}else{throw new TypeError("Second argument must be a string or a Uint8Array")}}const options={[kByteLength]:buf.length,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:false,rsv1:false};if(this._state!==DEFAULT){this.enqueue([this.dispatch,buf,false,options,cb])}else{this.sendFrame(_Sender.frame(buf,options),cb)}}ping(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(_Sender.frame(data,options),cb)}}pong(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(_Sender.frame(data,options),cb)}}send(data,options,cb){const perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];let opcode=options.binary?2:1;let rsv1=options.compress;let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(this._firstFragment){this._firstFragment=false;if(rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"]){rsv1=byteLength>=perMessageDeflate._threshold}this._compress=rsv1}else{rsv1=false;opcode=0}if(options.fin)this._firstFragment=true;const opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,this._compress,opts,cb])}else{this.getBlobData(data,this._compress,opts,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,this._compress,opts,cb])}else{this.dispatch(data,this._compress,opts,cb)}}getBlobData(blob,compress,options,cb){this._bufferedBytes+=options[kByteLength];this._state=GET_BLOB_DATA;blob.arrayBuffer().then(arrayBuffer=>{if(this._socket.destroyed){const err2=new Error("The socket was closed while the blob was being read");process.nextTick(callCallbacks,this,err2,cb);return}this._bufferedBytes-=options[kByteLength];const data=toBuffer(arrayBuffer);if(!compress){this._state=DEFAULT;this.sendFrame(_Sender.frame(data,options),cb);this.dequeue()}else{this.dispatch(data,compress,options,cb)}}).catch(err2=>{process.nextTick(onError,this,err2,cb)})}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(_Sender.frame(data,options),cb);return}const perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];this._bufferedBytes+=options[kByteLength];this._state=DEFLATING;perMessageDeflate.compress(data,options.fin,(_2,buf)=>{if(this._socket.destroyed){const err2=new Error("The socket was closed while data was being compressed");callCallbacks(this,err2,cb);return}this._bufferedBytes-=options[kByteLength];this._state=DEFAULT;options.readOnly=false;this.sendFrame(_Sender.frame(buf,options),cb);this.dequeue()})}dequeue(){while(this._state===DEFAULT&&this._queue.length){const params=this._queue.shift();this._bufferedBytes-=params[3][kByteLength];Reflect.apply(params[0],this,params.slice(1))}}enqueue(params){this._bufferedBytes+=params[3][kByteLength];this._queue.push(params)}sendFrame(list,cb){if(list.length===2){this._socket.cork();this._socket.write(list[0]);this._socket.write(list[1],cb);this._socket.uncork()}else{this._socket.write(list[0],cb)}}};module.exports=Sender2;function callCallbacks(sender,err2,cb){if(typeof cb==="function")cb(err2);for(let i=0;i<sender._queue.length;i++){const params=sender._queue[i];const callback=params[params.length-1];if(typeof callback==="function")callback(err2)}}function onError(sender,err2,cb){callCallbacks(sender,err2,cb);sender.onerror(err2)}}});var require_event_target=__commonJS({"node_modules/ws/lib/event-target.js"(exports,module){"use strict";var{kForOnEventAttribute,kListener}=require_constants6();var kCode=Symbol("kCode");var kData=Symbol("kData");var kError=Symbol("kError");var kMessage=Symbol("kMessage");var kReason=Symbol("kReason");var kTarget=Symbol("kTarget");var kType=Symbol("kType");var kWasClean=Symbol("kWasClean");var Event2=class{constructor(type){this[kTarget]=null;this[kType]=type}get target(){return this[kTarget]}get type(){return this[kType]}};Object.defineProperty(Event2.prototype,"target",{enumerable:true});Object.defineProperty(Event2.prototype,"type",{enumerable:true});var CloseEvent=class extends Event2{constructor(type,options={}){super(type);this[kCode]=options.code===void 0?0:options.code;this[kReason]=options.reason===void 0?"":options.reason;this[kWasClean]=options.wasClean===void 0?false:options.wasClean}get code(){return this[kCode]}get reason(){return this[kReason]}get wasClean(){return this[kWasClean]}};Object.defineProperty(CloseEvent.prototype,"code",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:true});var ErrorEvent=class extends Event2{constructor(type,options={}){super(type);this[kError]=options.error===void 0?null:options.error;this[kMessage]=options.message===void 0?"":options.message}get error(){return this[kError]}get message(){return this[kMessage]}};Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:true});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:true});var MessageEvent=class extends Event2{constructor(type,options={}){super(type);this[kData]=options.data===void 0?null:options.data}get data(){return this[kData]}};Object.defineProperty(MessageEvent.prototype,"data",{enumerable:true});var EventTarget2={addEventListener(type,handler,options={}){for(const listener of this.listeners(type)){if(!options[kForOnEventAttribute]&&listener[kListener]===handler&&!listener[kForOnEventAttribute]){return}}let wrapper;if(type==="message"){wrapper=function onMessage(data,isBinary){const event=new MessageEvent("message",{data:isBinary?data:data.toString()});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="close"){wrapper=function onClose(code,message){const event=new CloseEvent("close",{code,reason:message.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="error"){wrapper=function onError(error){const event=new ErrorEvent("error",{error,message:error.message});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="open"){wrapper=function onOpen(){const event=new Event2("open");event[kTarget]=this;callListener(handler,this,event)}}else{return}wrapper[kForOnEventAttribute]=!!options[kForOnEventAttribute];wrapper[kListener]=handler;if(options.once){this.once(type,wrapper)}else{this.on(type,wrapper)}},removeEventListener(type,handler){for(const listener of this.listeners(type)){if(listener[kListener]===handler&&!listener[kForOnEventAttribute]){this.removeListener(type,listener);break}}}};module.exports={CloseEvent,ErrorEvent,Event:Event2,EventTarget:EventTarget2,MessageEvent};function callListener(listener,thisArg,event){if(typeof listener==="object"&&listener.handleEvent){listener.handleEvent.call(listener,event)}else{listener.call(thisArg,event)}}}});var require_extension=__commonJS({"node_modules/ws/lib/extension.js"(exports,module){"use strict";var{tokenChars}=require_validation();function push(dest,name,elem){if(dest[name]===void 0)dest[name]=[elem];else dest[name].push(elem)}function parse4(header){const offers=Object.create(null);let params=Object.create(null);let mustUnescape=false;let isEscaping=false;let inQuotes=false;let extensionName;let paramName;let start=-1;let code=-1;let end=-1;let i=0;for(;i<header.length;i++){code=header.charCodeAt(i);if(extensionName===void 0){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const name=header.slice(start,end);if(code===44){push(offers,name,params);params=Object.create(null)}else{extensionName=name}start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(paramName===void 0){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(code===32||code===9){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;push(params,header.slice(start,end),true);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=void 0}start=end=-1}else if(code===61&&start!==-1&&end===-1){paramName=header.slice(start,i);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else{if(isEscaping){if(tokenChars[code]!==1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(start===-1)start=i;else if(!mustUnescape)mustUnescape=true;isEscaping=false}else if(inQuotes){if(tokenChars[code]===1){if(start===-1)start=i}else if(code===34&&start!==-1){inQuotes=false;end=i}else if(code===92){isEscaping=true}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(code===34&&header.charCodeAt(i-1)===61){inQuotes=true}else if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(start!==-1&&(code===32||code===9)){if(end===-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;let value=header.slice(start,end);if(mustUnescape){value=value.replace(/\\/g,"");mustUnescape=false}push(params,paramName,value);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=void 0}paramName=void 0;start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}}if(start===-1||inQuotes||code===32||code===9){throw new SyntaxError("Unexpected end of input")}if(end===-1)end=i;const token=header.slice(start,end);if(extensionName===void 0){push(offers,token,params)}else{if(paramName===void 0){push(params,token,true)}else if(mustUnescape){push(params,paramName,token.replace(/\\/g,""))}else{push(params,paramName,token)}push(offers,extensionName,params)}return offers}function format2(extensions){return Object.keys(extensions).map(extension2=>{let configurations=extensions[extension2];if(!Array.isArray(configurations))configurations=[configurations];return configurations.map(params=>{return[extension2].concat(Object.keys(params).map(k2=>{let values=params[k2];if(!Array.isArray(values))values=[values];return values.map(v2=>v2===true?k2:`${k2}=${v2}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}module.exports={format:format2,parse:parse4}}});var require_websocket2=__commonJS({"node_modules/ws/lib/websocket.js"(exports,module){"use strict";var EventEmitter2=__require("events");var https=__require("https");var http6=__require("http");var net5=__require("net");var tls6=__require("tls");var{randomBytes:randomBytes5,createHash:createHash35}=__require("crypto");var{Duplex,Readable:Readable3}=__require("stream");var{URL:URL2}=__require("url");var PerMessageDeflate2=require_permessage_deflate2();var Receiver2=require_receiver2();var Sender2=require_sender2();var{isBlob}=require_validation();var{BINARY_TYPES,CLOSE_TIMEOUT,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants6();var{EventTarget:{addEventListener,removeEventListener}}=require_event_target();var{format:format2,parse:parse4}=require_extension();var{toBuffer}=require_buffer_util();var kAborted=Symbol("kAborted");var protocolVersions=[8,13];var readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"];var subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var WebSocket3=class _WebSocket extends EventEmitter2{constructor(address,protocols,options){super();this._binaryType=BINARY_TYPES[0];this._closeCode=1006;this._closeFrameReceived=false;this._closeFrameSent=false;this._closeMessage=EMPTY_BUFFER;this._closeTimer=null;this._errorEmitted=false;this._extensions={};this._paused=false;this._protocol="";this._readyState=_WebSocket.CONNECTING;this._receiver=null;this._sender=null;this._socket=null;if(address!==null){this._bufferedAmount=0;this._isServer=false;this._redirects=0;if(protocols===void 0){if(!options||options.protocols===void 0){protocols=[]}else if(Array.isArray(options.protocols)){protocols=options.protocols}else{protocols=[options.protocols]}}else if(!Array.isArray(protocols)){if(typeof protocols==="object"&&protocols!==null){options=protocols;if(options.protocols===void 0){protocols=[]}else if(Array.isArray(options.protocols)){protocols=options.protocols}else{protocols=[options.protocols]}}else{protocols=[protocols]}}initAsClient(this,address,protocols,options)}else{this._autoPong=options.autoPong;this._closeTimeout=options.closeTimeout;this._isServer=true}}get binaryType(){return this._binaryType}set binaryType(type){if(!BINARY_TYPES.includes(type))return;this._binaryType=type;if(this._receiver)this._receiver._binaryType=type}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){const receiver=new Receiver2({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:options.maxBufferedChunks,maxFragments:options.maxFragments,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation});const sender=new Sender2(socket,this._extensions,options.generateMask);this._receiver=receiver;this._sender=sender;this._socket=socket;receiver[kWebSocket]=this;sender[kWebSocket]=this;socket[kWebSocket]=this;receiver.on("conclude",receiverOnConclude);receiver.on("drain",receiverOnDrain);receiver.on("error",receiverOnError);receiver.on("message",receiverOnMessage);receiver.on("ping",receiverOnPing);receiver.on("pong",receiverOnPong);sender.onerror=senderOnError;if(socket.setTimeout)socket.setTimeout(0);if(socket.setNoDelay)socket.setNoDelay();if(head.length>0)socket.unshift(head);socket.on("close",socketOnClose);socket.on("data",socketOnData);socket.on("end",socketOnEnd);socket.on("error",socketOnError);this._readyState=_WebSocket.OPEN;this.emit("open")}emitClose(){if(!this._socket){this._readyState=_WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[PerMessageDeflate2.extensionName]){this._extensions[PerMessageDeflate2.extensionName].cleanup()}this._receiver.removeAllListeners();this._readyState=_WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState===_WebSocket.CLOSED)return;if(this.readyState===_WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this.readyState===_WebSocket.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)){this._socket.end()}return}this._sender.close(code,data,!this._isServer,err2=>{if(err2)return;this._closeFrameSent=true;if(this._closeFrameReceived||this._receiver._writableState.errorEmitted){this._socket.end()}});this._readyState=_WebSocket.CLOSING;setCloseTimer(this)}pause(){if(this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED){return}this._paused=true;this._socket.pause()}ping(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=void 0}else if(typeof mask==="function"){cb=mask;mask=void 0}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=void 0}else if(typeof mask==="function"){cb=mask;mask=void 0}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){if(this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED){return}this._paused=false;if(!this._receiver._writableState.needDrain)this._socket.resume()}send(data,options,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof options==="function"){cb=options;options={}}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}const opts={binary:typeof data!=="string",mask:!this._isServer,compress:true,fin:true,...options};if(!this._extensions[PerMessageDeflate2.extensionName]){opts.compress=false}this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState===_WebSocket.CLOSED)return;if(this.readyState===_WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this._socket){this._readyState=_WebSocket.CLOSING;this._socket.destroy()}}};Object.defineProperty(WebSocket3,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket3.prototype,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket3,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket3.prototype,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket3,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket3.prototype,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket3,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket3.prototype,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(property=>{Object.defineProperty(WebSocket3.prototype,property,{enumerable:true})});["open","error","close","message"].forEach(method=>{Object.defineProperty(WebSocket3.prototype,`on${method}`,{enumerable:true,get(){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute])return listener[kListener]}return null},set(handler){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}}if(typeof handler!=="function")return;this.addEventListener(method,handler,{[kForOnEventAttribute]:true})}})});WebSocket3.prototype.addEventListener=addEventListener;WebSocket3.prototype.removeEventListener=removeEventListener;module.exports=WebSocket3;function initAsClient(websocket,address,protocols,options){const opts={allowSynchronousEvents:true,autoPong:true,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:true,followRedirects:false,maxRedirects:10,...options,socketPath:void 0,hostname:void 0,protocol:void 0,protocols:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};websocket._autoPong=opts.autoPong;websocket._closeTimeout=opts.closeTimeout;if(!protocolVersions.includes(opts.protocolVersion)){throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`)}let parsedUrl;if(address instanceof URL2){parsedUrl=address}else{try{parsedUrl=new URL2(address)}catch{throw new SyntaxError(`Invalid URL: ${address}`)}}if(parsedUrl.protocol==="http:"){parsedUrl.protocol="ws:"}else if(parsedUrl.protocol==="https:"){parsedUrl.protocol="wss:"}websocket._url=parsedUrl.href;const isSecure=parsedUrl.protocol==="wss:";const isIpcUrl=parsedUrl.protocol==="ws+unix:";let invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl){invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`}else if(isIpcUrl&&!parsedUrl.pathname){invalidUrlMessage="The URL's pathname is empty"}else if(parsedUrl.hash){invalidUrlMessage="The URL contains a fragment identifier"}if(invalidUrlMessage){const err2=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0){throw err2}else{emitErrorAndClose(websocket,err2);return}}const defaultPort2=isSecure?443:80;const key2=randomBytes5(16).toString("base64");const request=isSecure?https.request:http6.request;const protocolSet=new Set;let perMessageDeflate;opts.createConnection=opts.createConnection||(isSecure?tlsConnect:netConnect);opts.defaultPort=opts.defaultPort||defaultPort2;opts.port=parsedUrl.port||defaultPort2;opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname;opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key2,Connection:"Upgrade",Upgrade:"websocket"};opts.path=parsedUrl.pathname+parsedUrl.search;opts.timeout=opts.handshakeTimeout;if(opts.perMessageDeflate){perMessageDeflate=new PerMessageDeflate2({...opts.perMessageDeflate,isServer:false,maxPayload:opts.maxPayload});opts.headers["Sec-WebSocket-Extensions"]=format2({[PerMessageDeflate2.extensionName]:perMessageDeflate.offer()})}if(protocols.length){for(const protocol of protocols){if(typeof protocol!=="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol)){throw new SyntaxError("An invalid or duplicated subprotocol was specified")}protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin){if(opts.protocolVersion<13){opts.headers["Sec-WebSocket-Origin"]=opts.origin}else{opts.headers.Origin=opts.origin}}if(parsedUrl.username||parsedUrl.password){opts.auth=`${parsedUrl.username}:${parsedUrl.password}`}if(isIpcUrl){const parts=opts.path.split(":");opts.socketPath=parts[0];opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl;websocket._originalSecure=isSecure;websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;const headers=options&&options.headers;options={...options,headers:{}};if(headers){for(const[key3,value]of Object.entries(headers)){options.headers[key3.toLowerCase()]=value}}}else if(websocket.listenerCount("redirect")===0){const isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:false:websocket._originalIpc?false:parsedUrl.host===websocket._originalHostOrSocketPath;if(!isSameHost||websocket._originalSecure&&!isSecure){delete opts.headers.authorization;delete opts.headers.cookie;if(!isSameHost)delete opts.headers.host;opts.auth=void 0}}if(opts.auth&&!options.headers.authorization){options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")}req=websocket._req=request(opts);if(websocket._redirects){websocket.emit("redirect",websocket.url,req)}}else{req=websocket._req=request(opts)}if(opts.timeout){req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")})}req.on("error",err2=>{if(req===null||req[kAborted])return;req=websocket._req=null;emitErrorAndClose(websocket,err2)});req.on("response",res=>{const location=res.headers.location;const statusCode=res.statusCode;if(location&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location,address)}catch(e){const err2=new SyntaxError(`Invalid URL: ${location}`);emitErrorAndClose(websocket,err2);return}initAsClient(websocket,addr,protocols,options)}else if(!websocket.emit("unexpected-response",req,res)){abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}});req.on("upgrade",(res,socket,head)=>{websocket.emit("upgrade",res);if(websocket.readyState!==WebSocket3.CONNECTING)return;req=websocket._req=null;const upgrade=res.headers.upgrade;if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}const digest=createHash35("sha1").update(key2+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}const serverProt=res.headers["sec-websocket-protocol"];let protError;if(serverProt!==void 0){if(!protocolSet.size){protError="Server sent a subprotocol but none was requested"}else if(!protocolSet.has(serverProt)){protError="Server sent an invalid subprotocol"}}else if(protocolSet.size){protError="Server sent no subprotocol"}if(protError){abortHandshake(websocket,socket,protError);return}if(serverProt)websocket._protocol=serverProt;const secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==void 0){if(!perMessageDeflate){const message="Server sent a Sec-WebSocket-Extensions header but no extension was requested";abortHandshake(websocket,socket,message);return}let extensions;try{extensions=parse4(secWebSocketExtensions)}catch(err2){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}const extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate2.extensionName){const message="Server indicated an extension that was not requested";abortHandshake(websocket,socket,message);return}try{perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName])}catch(err2){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}websocket._extensions[PerMessageDeflate2.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxBufferedChunks:opts.maxBufferedChunks,maxFragments:opts.maxFragments,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})});if(opts.finishRequest){opts.finishRequest(req,websocket)}else{req.end()}}function emitErrorAndClose(websocket,err2){websocket._readyState=WebSocket3.CLOSING;websocket._errorEmitted=true;websocket.emit("error",err2);websocket.emitClose()}function netConnect(options){options.path=options.socketPath;return net5.connect(options)}function tlsConnect(options){options.path=void 0;if(!options.servername&&options.servername!==""){options.servername=net5.isIP(options.host)?"":options.host}return tls6.connect(options)}function abortHandshake(websocket,stream2,message){websocket._readyState=WebSocket3.CLOSING;const err2=new Error(message);Error.captureStackTrace(err2,abortHandshake);if(stream2.setHeader){stream2[kAborted]=true;stream2.abort();if(stream2.socket&&!stream2.socket.destroyed){stream2.socket.destroy()}process.nextTick(emitErrorAndClose,websocket,err2)}else{stream2.destroy(err2);stream2.once("error",websocket.emit.bind(websocket,"error"));stream2.once("close",websocket.emitClose.bind(websocket))}}function sendAfterClose(websocket,data,cb){if(data){const length=isBlob(data)?data.size:toBuffer(data).length;if(websocket._socket)websocket._sender._bufferedBytes+=length;else websocket._bufferedAmount+=length}if(cb){const err2=new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);process.nextTick(cb,err2)}}function receiverOnConclude(code,reason){const websocket=this[kWebSocket];websocket._closeFrameReceived=true;websocket._closeMessage=reason;websocket._closeCode=code;if(websocket._socket[kWebSocket]===void 0)return;websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);if(code===1005)websocket.close();else websocket.close(code,reason)}function receiverOnDrain(){const websocket=this[kWebSocket];if(!websocket.isPaused)websocket._socket.resume()}function receiverOnError(err2){const websocket=this[kWebSocket];if(websocket._socket[kWebSocket]!==void 0){websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);websocket.close(err2[kStatusCode])}if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err2)}}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){const websocket=this[kWebSocket];if(websocket._autoPong)websocket.pong(data,!this._isServer,NOOP);websocket.emit("ping",data)}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream2){stream2.resume()}function senderOnError(err2){const websocket=this[kWebSocket];if(websocket.readyState===WebSocket3.CLOSED)return;if(websocket.readyState===WebSocket3.OPEN){websocket._readyState=WebSocket3.CLOSING;setCloseTimer(websocket)}this._socket.end();if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err2)}}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),websocket._closeTimeout)}function socketOnClose(){const websocket=this[kWebSocket];this.removeListener("close",socketOnClose);this.removeListener("data",socketOnData);this.removeListener("end",socketOnEnd);websocket._readyState=WebSocket3.CLOSING;if(!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){const chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}websocket._receiver.end();this[kWebSocket]=void 0;clearTimeout(websocket._closeTimer);if(websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted){websocket.emitClose()}else{websocket._receiver.on("error",receiverOnFinish);websocket._receiver.on("finish",receiverOnFinish)}}function socketOnData(chunk){if(!this[kWebSocket]._receiver.write(chunk)){this.pause()}}function socketOnEnd(){const websocket=this[kWebSocket];websocket._readyState=WebSocket3.CLOSING;websocket._receiver.end();this.end()}function socketOnError(){const websocket=this[kWebSocket];this.removeListener("error",socketOnError);this.on("error",NOOP);if(websocket){websocket._readyState=WebSocket3.CLOSING;this.destroy()}}}});var require_stream=__commonJS({"node_modules/ws/lib/stream.js"(exports,module){"use strict";var WebSocket3=require_websocket2();var{Duplex}=__require("stream");function emitClose(stream2){stream2.emit("close")}function duplexOnEnd(){if(!this.destroyed&&this._writableState.finished){this.destroy()}}function duplexOnError(err2){this.removeListener("error",duplexOnError);this.destroy();if(this.listenerCount("error")===0){this.emit("error",err2)}}function createWebSocketStream2(ws2,options){let terminateOnDestroy=true;const duplex=new Duplex({...options,autoDestroy:false,emitClose:false,objectMode:false,writableObjectMode:false});ws2.on("message",function message(msg,isBinary){const data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;if(!duplex.push(data))ws2.pause()});ws2.once("error",function error(err2){if(duplex.destroyed)return;terminateOnDestroy=false;duplex.destroy(err2)});ws2.once("close",function close(){if(duplex.destroyed)return;duplex.push(null)});duplex._destroy=function(err2,callback){if(ws2.readyState===ws2.CLOSED){callback(err2);process.nextTick(emitClose,duplex);return}let called=false;ws2.once("error",function error(err3){called=true;callback(err3)});ws2.once("close",function close(){if(!called)callback(err2);process.nextTick(emitClose,duplex)});if(terminateOnDestroy)ws2.terminate()};duplex._final=function(callback){if(ws2.readyState===ws2.CONNECTING){ws2.once("open",function open(){duplex._final(callback)});return}if(ws2._socket===null)return;if(ws2._socket._writableState.finished){callback();if(duplex._readableState.endEmitted)duplex.destroy()}else{ws2._socket.once("finish",function finish2(){callback()});ws2.close()}};duplex._read=function(){if(ws2.isPaused)ws2.resume()};duplex._write=function(chunk,encoding,callback){if(ws2.readyState===ws2.CONNECTING){ws2.once("open",function open(){duplex._write(chunk,encoding,callback)});return}ws2.send(chunk,callback)};duplex.on("end",duplexOnEnd);duplex.on("error",duplexOnError);return duplex}module.exports=createWebSocketStream2}});var require_subprotocol=__commonJS({"node_modules/ws/lib/subprotocol.js"(exports,module){"use strict";var{tokenChars}=require_validation();function parse4(header){const protocols=new Set;let start=-1;let end=-1;let i=0;for(i;i<header.length;i++){const code=header.charCodeAt(i);if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const protocol2=header.slice(start,end);if(protocols.has(protocol2)){throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`)}protocols.add(protocol2);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}if(start===-1||end!==-1){throw new SyntaxError("Unexpected end of input")}const protocol=header.slice(start,i);if(protocols.has(protocol)){throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`)}protocols.add(protocol);return protocols}module.exports={parse:parse4}}});var require_websocket_server=__commonJS({"node_modules/ws/lib/websocket-server.js"(exports,module){"use strict";var EventEmitter2=__require("events");var http6=__require("http");var{Duplex}=__require("stream");var{createHash:createHash35}=__require("crypto");var extension2=require_extension();var PerMessageDeflate2=require_permessage_deflate2();var subprotocol2=require_subprotocol();var WebSocket3=require_websocket2();var{CLOSE_TIMEOUT,GUID,kWebSocket}=require_constants6();var keyRegex=/^[+/0-9A-Za-z]{22}==$/;var RUNNING=0;var CLOSING=1;var CLOSED=2;var WebSocketServer2=class extends EventEmitter2{constructor(options,callback){super();options={allowSynchronousEvents:true,autoPong:true,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:false,handleProtocols:null,clientTracking:true,closeTimeout:CLOSE_TIMEOUT,verifyClient:null,noServer:false,backlog:null,server:null,host:null,path:null,port:null,WebSocket:WebSocket3,...options};if(options.port==null&&!options.server&&!options.noServer||options.port!=null&&(options.server||options.noServer)||options.server&&options.noServer){throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified')}if(options.port!=null){this._server=http6.createServer((req,res)=>{const body=http6.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"});res.end(body)});this._server.listen(options.port,options.host,options.backlog,callback)}else if(options.server){this._server=options.server}if(this._server){const emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}if(options.perMessageDeflate===true)options.perMessageDeflate={};if(options.clientTracking){this.clients=new Set;this._shouldEmitClose=false}this.options=options;this._state=RUNNING}address(){if(this.options.noServer){throw new Error('The server is operating in "noServer" mode')}if(!this._server)return null;return this._server.address()}close(cb){if(this._state===CLOSED){if(cb){this.once("close",()=>{cb(new Error("The server is not running"))})}process.nextTick(emitClose,this);return}if(cb)this.once("close",cb);if(this._state===CLOSING)return;this._state=CLOSING;if(this.options.noServer||this.options.server){if(this._server){this._removeListeners();this._removeListeners=this._server=null}if(this.clients){if(!this.clients.size){process.nextTick(emitClose,this)}else{this._shouldEmitClose=true}}else{process.nextTick(emitClose,this)}}else{const server2=this._server;this._removeListeners();this._removeListeners=this._server=null;server2.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){const index=req.url.indexOf("?");const pathname=index!==-1?req.url.slice(0,index):req.url;if(pathname!==this.options.path)return false}return true}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);const key2=req.headers["sec-websocket-key"];const upgrade=req.headers.upgrade;const version=+req.headers["sec-websocket-version"];if(req.method!=="GET"){const message="Invalid HTTP method";abortHandshakeOrEmitwsClientError(this,req,socket,405,message);return}if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){const message="Invalid Upgrade header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(key2===void 0||!keyRegex.test(key2)){const message="Missing or invalid Sec-WebSocket-Key header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(version!==13&&version!==8){const message="Missing or invalid Sec-WebSocket-Version header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message,{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}const secWebSocketProtocol=req.headers["sec-websocket-protocol"];let protocols=new Set;if(secWebSocketProtocol!==void 0){try{protocols=subprotocol2.parse(secWebSocketProtocol)}catch(err2){const message="Invalid Sec-WebSocket-Protocol header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}const secWebSocketExtensions=req.headers["sec-websocket-extensions"];const extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==void 0){const perMessageDeflate=new PerMessageDeflate2({...this.options.perMessageDeflate,isServer:true,maxPayload:this.options.maxPayload});try{const offers=extension2.parse(secWebSocketExtensions);if(offers[PerMessageDeflate2.extensionName]){perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);extensions[PerMessageDeflate2.extensionName]=perMessageDeflate}}catch(err2){const message="Invalid or unacceptable Sec-WebSocket-Extensions header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}if(this.options.verifyClient){const info={origin:req.headers[`${version===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified){return abortHandshake(socket,code||401,message,headers)}this.completeUpgrade(extensions,key2,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key2,protocols,req,socket,head,cb)}completeUpgrade(extensions,key2,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket]){throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration")}if(this._state>RUNNING)return abortHandshake(socket,503);const digest=createHash35("sha1").update(key2+GUID).digest("base64");const headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${digest}`];const ws2=new this.options.WebSocket(null,void 0,this.options);if(protocols.size){const protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;if(protocol){headers.push(`Sec-WebSocket-Protocol: ${protocol}`);ws2._protocol=protocol}}if(extensions[PerMessageDeflate2.extensionName]){const params=extensions[PerMessageDeflate2.extensionName].params;const value=extension2.format({[PerMessageDeflate2.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`);ws2._extensions=extensions}this.emit("headers",headers,req);socket.write(headers.concat("\r\n").join("\r\n"));socket.removeListener("error",socketOnError);ws2.setSocket(socket,head,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation});if(this.clients){this.clients.add(ws2);ws2.on("close",()=>{this.clients.delete(ws2);if(this._shouldEmitClose&&!this.clients.size){process.nextTick(emitClose,this)}})}cb(ws2,req)}};module.exports=WebSocketServer2;function addListeners(server2,map){for(const event of Object.keys(map))server2.on(event,map[event]);return function removeListeners(){for(const event of Object.keys(map)){server2.removeListener(event,map[event])}}}function emitClose(server2){server2._state=CLOSED;server2.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(socket,code,message,headers){message=message||http6.STATUS_CODES[code];headers={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(message),...headers};socket.once("finish",socket.destroy);socket.end(`HTTP/1.1 ${code} ${http6.STATUS_CODES[code]}\r
|
|
892
892
|
`+Object.keys(headers).map(h=>`${h}: ${headers[h]}`).join("\r\n")+"\r\n\r\n"+message)}function abortHandshakeOrEmitwsClientError(server2,req,socket,code,message,headers){if(server2.listenerCount("wsClientError")){const err2=new Error(message);Error.captureStackTrace(err2,abortHandshakeOrEmitwsClientError);server2.emit("wsClientError",err2,socket,req)}else{abortHandshake(socket,code,message,headers)}}}});var require_constants7=__commonJS({"node_modules/semver/internal/constants.js"(exports,module){"use strict";var SEMVER_SPEC_VERSION="2.0.0";var MAX_LENGTH=256;var MAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER||9007199254740991;var MAX_SAFE_COMPONENT_LENGTH=16;var MAX_SAFE_BUILD_LENGTH=MAX_LENGTH-6;var RELEASE_TYPES=["major","premajor","minor","preminor","patch","prepatch","prerelease"];module.exports={MAX_LENGTH,MAX_SAFE_COMPONENT_LENGTH,MAX_SAFE_BUILD_LENGTH,MAX_SAFE_INTEGER,RELEASE_TYPES,SEMVER_SPEC_VERSION,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}});var require_debug=__commonJS({"node_modules/semver/internal/debug.js"(exports,module){"use strict";var debug=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...args)=>console.error("SEMVER",...args):()=>{};module.exports=debug}});var require_re=__commonJS({"node_modules/semver/internal/re.js"(exports,module){"use strict";var{MAX_SAFE_COMPONENT_LENGTH,MAX_SAFE_BUILD_LENGTH,MAX_LENGTH}=require_constants7();var debug=require_debug();exports=module.exports={};var re2=exports.re=[];var safeRe=exports.safeRe=[];var src=exports.src=[];var safeSrc=exports.safeSrc=[];var t=exports.t={};var R2=0;var LETTERDASHNUMBER="[a-zA-Z0-9-]";var safeRegexReplacements=[["\\s",1],["\\d",MAX_LENGTH],[LETTERDASHNUMBER,MAX_SAFE_BUILD_LENGTH]];var makeSafeRegex=value=>{for(const[token,max]of safeRegexReplacements){value=value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`)}return value};var createToken=(name,value,isGlobal)=>{const safe=makeSafeRegex(value);const index=R2++;debug(name,index,value);t[name]=index;src[index]=value;safeSrc[index]=safe;re2[index]=new RegExp(value,isGlobal?"g":void 0);safeRe[index]=new RegExp(safe,isGlobal?"g":void 0)};createToken("NUMERICIDENTIFIER","0|[1-9]\\d*");createToken("NUMERICIDENTIFIERLOOSE","\\d+");createToken("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);createToken("MAINVERSION",`(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`);createToken("MAINVERSIONLOOSE",`(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`);createToken("PRERELEASEIDENTIFIER",`(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`);createToken("PRERELEASEIDENTIFIERLOOSE",`(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`);createToken("PRERELEASE",`(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);createToken("PRERELEASELOOSE",`(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);createToken("BUILDIDENTIFIER",`${LETTERDASHNUMBER}+`);createToken("BUILD",`(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);createToken("FULLPLAIN",`v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);createToken("FULL",`^${src[t.FULLPLAIN]}$`);createToken("LOOSEPLAIN",`[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);createToken("LOOSE",`^${src[t.LOOSEPLAIN]}$`);createToken("GTLT","((?:<|>)?=?)");createToken("XRANGEIDENTIFIERLOOSE",`${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);createToken("XRANGEIDENTIFIER",`${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);createToken("XRANGEPLAIN",`[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`);createToken("XRANGEPLAINLOOSE",`[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`);createToken("XRANGE",`^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);createToken("XRANGELOOSE",`^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);createToken("COERCEPLAIN",`${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);createToken("COERCE",`${src[t.COERCEPLAIN]}(?:$|[^\\d])`);createToken("COERCEFULL",src[t.COERCEPLAIN]+`(?:${src[t.PRERELEASE]})?(?:${src[t.BUILD]})?(?:$|[^\\d])`);createToken("COERCERTL",src[t.COERCE],true);createToken("COERCERTLFULL",src[t.COERCEFULL],true);createToken("LONETILDE","(?:~>?)");createToken("TILDETRIM",`(\\s*)${src[t.LONETILDE]}\\s+`,true);exports.tildeTrimReplace="$1~";createToken("TILDE",`^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);createToken("TILDELOOSE",`^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);createToken("LONECARET","(?:\\^)");createToken("CARETTRIM",`(\\s*)${src[t.LONECARET]}\\s+`,true);exports.caretTrimReplace="$1^";createToken("CARET",`^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);createToken("CARETLOOSE",`^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);createToken("COMPARATORLOOSE",`^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);createToken("COMPARATOR",`^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);createToken("COMPARATORTRIM",`(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`,true);exports.comparatorTrimReplace="$1$2$3";createToken("HYPHENRANGE",`^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`);createToken("HYPHENRANGELOOSE",`^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`);createToken("STAR","(<|>)?=?\\s*\\*");createToken("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");createToken("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}});var require_parse_options=__commonJS({"node_modules/semver/internal/parse-options.js"(exports,module){"use strict";var looseOption=Object.freeze({loose:true});var emptyOpts=Object.freeze({});var parseOptions=options=>{if(!options){return emptyOpts}if(typeof options!=="object"){return looseOption}return options};module.exports=parseOptions}});var require_identifiers=__commonJS({"node_modules/semver/internal/identifiers.js"(exports,module){"use strict";var numeric=/^[0-9]+$/;var compareIdentifiers=(a,b2)=>{if(typeof a==="number"&&typeof b2==="number"){return a===b2?0:a<b2?-1:1}const anum=numeric.test(a);const bnum=numeric.test(b2);if(anum&&bnum){a=+a;b2=+b2}return a===b2?0:anum&&!bnum?-1:bnum&&!anum?1:a<b2?-1:1};var rcompareIdentifiers=(a,b2)=>compareIdentifiers(b2,a);module.exports={compareIdentifiers,rcompareIdentifiers}}});var require_semver=__commonJS({"node_modules/semver/classes/semver.js"(exports,module){"use strict";var debug=require_debug();var{MAX_LENGTH,MAX_SAFE_INTEGER}=require_constants7();var{safeRe:re2,t}=require_re();var parseOptions=require_parse_options();var{compareIdentifiers}=require_identifiers();var isPrereleaseIdentifier=(prerelease,identifier)=>{const identifiers=identifier.split(".");if(identifiers.length>prerelease.length){return false}for(let i=0;i<identifiers.length;i++){if(compareIdentifiers(prerelease[i],identifiers[i])!==0){return false}}return true};var SemVer=class _SemVer{constructor(version,options){options=parseOptions(options);if(version instanceof _SemVer){if(version.loose===!!options.loose&&version.includePrerelease===!!options.includePrerelease){return version}else{version=version.version}}else if(typeof version!=="string"){throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`)}if(version.length>MAX_LENGTH){throw new TypeError(`version is longer than ${MAX_LENGTH} characters`)}debug("SemVer",version,options);this.options=options;this.loose=!!options.loose;this.includePrerelease=!!options.includePrerelease;const m2=version.trim().match(options.loose?re2[t.LOOSE]:re2[t.FULL]);if(!m2){throw new TypeError(`Invalid Version: ${version}`)}this.raw=version;this.major=+m2[1];this.minor=+m2[2];this.patch=+m2[3];if(this.major>MAX_SAFE_INTEGER||this.major<0){throw new TypeError("Invalid major version")}if(this.minor>MAX_SAFE_INTEGER||this.minor<0){throw new TypeError("Invalid minor version")}if(this.patch>MAX_SAFE_INTEGER||this.patch<0){throw new TypeError("Invalid patch version")}if(!m2[4]){this.prerelease=[]}else{this.prerelease=m2[4].split(".").map(id=>{if(/^[0-9]+$/.test(id)){const num7=+id;if(num7>=0&&num7<MAX_SAFE_INTEGER){return num7}}return id})}this.build=m2[5]?m2[5].split("."):[];this.format()}format(){this.version=`${this.major}.${this.minor}.${this.patch}`;if(this.prerelease.length){this.version+=`-${this.prerelease.join(".")}`}return this.version}toString(){return this.version}compare(other){debug("SemVer.compare",this.version,this.options,other);if(!(other instanceof _SemVer)){if(typeof other==="string"&&other===this.version){return 0}other=new _SemVer(other,this.options)}if(other.version===this.version){return 0}return this.compareMain(other)||this.comparePre(other)}compareMain(other){if(!(other instanceof _SemVer)){other=new _SemVer(other,this.options)}if(this.major<other.major){return-1}if(this.major>other.major){return 1}if(this.minor<other.minor){return-1}if(this.minor>other.minor){return 1}if(this.patch<other.patch){return-1}if(this.patch>other.patch){return 1}return 0}comparePre(other){if(!(other instanceof _SemVer)){other=new _SemVer(other,this.options)}if(this.prerelease.length&&!other.prerelease.length){return-1}else if(!this.prerelease.length&&other.prerelease.length){return 1}else if(!this.prerelease.length&&!other.prerelease.length){return 0}let i=0;do{const a=this.prerelease[i];const b2=other.prerelease[i];debug("prerelease compare",i,a,b2);if(a===void 0&&b2===void 0){return 0}else if(b2===void 0){return 1}else if(a===void 0){return-1}else if(a===b2){continue}else{return compareIdentifiers(a,b2)}}while(++i)}compareBuild(other){if(!(other instanceof _SemVer)){other=new _SemVer(other,this.options)}let i=0;do{const a=this.build[i];const b2=other.build[i];debug("build compare",i,a,b2);if(a===void 0&&b2===void 0){return 0}else if(b2===void 0){return 1}else if(a===void 0){return-1}else if(a===b2){continue}else{return compareIdentifiers(a,b2)}}while(++i)}inc(release,identifier,identifierBase){if(release.startsWith("pre")){if(!identifier&&identifierBase===false){throw new Error("invalid increment argument: identifier is empty")}if(identifier){const match=`-${identifier}`.match(this.options.loose?re2[t.PRERELEASELOOSE]:re2[t.PRERELEASE]);if(!match||match[1]!==identifier){throw new Error(`invalid identifier: ${identifier}`)}}}switch(release){case"premajor":this.prerelease.length=0;this.patch=0;this.minor=0;this.major++;this.inc("pre",identifier,identifierBase);break;case"preminor":this.prerelease.length=0;this.patch=0;this.minor++;this.inc("pre",identifier,identifierBase);break;case"prepatch":this.prerelease.length=0;this.inc("patch",identifier,identifierBase);this.inc("pre",identifier,identifierBase);break;case"prerelease":if(this.prerelease.length===0){this.inc("patch",identifier,identifierBase)}this.inc("pre",identifier,identifierBase);break;case"release":if(this.prerelease.length===0){throw new Error(`version ${this.raw} is not a prerelease`)}this.prerelease.length=0;break;case"major":if(this.minor!==0||this.patch!==0||this.prerelease.length===0){this.major++}this.minor=0;this.patch=0;this.prerelease=[];break;case"minor":if(this.patch!==0||this.prerelease.length===0){this.minor++}this.patch=0;this.prerelease=[];break;case"patch":if(this.prerelease.length===0){this.patch++}this.prerelease=[];break;case"pre":{const base=Number(identifierBase)?1:0;if(this.prerelease.length===0){this.prerelease=[base]}else{let i=this.prerelease.length;while(--i>=0){if(typeof this.prerelease[i]==="number"){this.prerelease[i]++;i=-2}}if(i===-1){if(identifier===this.prerelease.join(".")&&identifierBase===false){throw new Error("invalid increment argument: identifier already exists")}this.prerelease.push(base)}}if(identifier){let prerelease=[identifier,base];if(identifierBase===false){prerelease=[identifier]}if(isPrereleaseIdentifier(this.prerelease,identifier)){const prereleaseBase=this.prerelease[identifier.split(".").length];if(isNaN(prereleaseBase)){this.prerelease=prerelease}}else{this.prerelease=prerelease}}break}default:throw new Error(`invalid increment argument: ${release}`)}this.raw=this.format();if(this.build.length){this.raw+=`+${this.build.join(".")}`}return this}};module.exports=SemVer}});var require_parse2=__commonJS({"node_modules/semver/functions/parse.js"(exports,module){"use strict";var SemVer=require_semver();var parse4=(version,options,throwErrors=false)=>{if(version instanceof SemVer){return version}try{return new SemVer(version,options)}catch(er2){if(!throwErrors){return null}throw er2}};module.exports=parse4}});var require_valid=__commonJS({"node_modules/semver/functions/valid.js"(exports,module){"use strict";var parse4=require_parse2();var valid=(version,options)=>{const v2=parse4(version,options);return v2?v2.version:null};module.exports=valid}});var require_clean=__commonJS({"node_modules/semver/functions/clean.js"(exports,module){"use strict";var parse4=require_parse2();var clean=(version,options)=>{const s3=parse4(version.trim().replace(/^[=v]+/,""),options);return s3?s3.version:null};module.exports=clean}});var require_inc=__commonJS({"node_modules/semver/functions/inc.js"(exports,module){"use strict";var SemVer=require_semver();var inc=(version,release,options,identifier,identifierBase)=>{if(typeof options==="string"){identifierBase=identifier;identifier=options;options=void 0}try{return new SemVer(version instanceof SemVer?version.version:version,options).inc(release,identifier,identifierBase).version}catch(er2){return null}};module.exports=inc}});var require_diff=__commonJS({"node_modules/semver/functions/diff.js"(exports,module){"use strict";var parse4=require_parse2();var diff=(version1,version2)=>{const v1=parse4(version1,null,true);const v2=parse4(version2,null,true);const comparison=v1.compare(v2);if(comparison===0){return null}const v1Higher=comparison>0;const highVersion=v1Higher?v1:v2;const lowVersion=v1Higher?v2:v1;const highHasPre=!!highVersion.prerelease.length;const lowHasPre=!!lowVersion.prerelease.length;if(lowHasPre&&!highHasPre){if(!lowVersion.patch&&!lowVersion.minor){return"major"}if(lowVersion.compareMain(highVersion)===0){if(lowVersion.minor&&!lowVersion.patch){return"minor"}return"patch"}}const prefix=highHasPre?"pre":"";if(v1.major!==v2.major){return prefix+"major"}if(v1.minor!==v2.minor){return prefix+"minor"}if(v1.patch!==v2.patch){return prefix+"patch"}return"prerelease"};module.exports=diff}});var require_major=__commonJS({"node_modules/semver/functions/major.js"(exports,module){"use strict";var SemVer=require_semver();var major=(a,loose)=>new SemVer(a,loose).major;module.exports=major}});var require_minor=__commonJS({"node_modules/semver/functions/minor.js"(exports,module){"use strict";var SemVer=require_semver();var minor=(a,loose)=>new SemVer(a,loose).minor;module.exports=minor}});var require_patch=__commonJS({"node_modules/semver/functions/patch.js"(exports,module){"use strict";var SemVer=require_semver();var patch=(a,loose)=>new SemVer(a,loose).patch;module.exports=patch}});var require_prerelease=__commonJS({"node_modules/semver/functions/prerelease.js"(exports,module){"use strict";var parse4=require_parse2();var prerelease=(version,options)=>{const parsed=parse4(version,options);return parsed&&parsed.prerelease.length?parsed.prerelease:null};module.exports=prerelease}});var require_compare=__commonJS({"node_modules/semver/functions/compare.js"(exports,module){"use strict";var SemVer=require_semver();var compare=(a,b2,loose)=>new SemVer(a,loose).compare(new SemVer(b2,loose));module.exports=compare}});var require_rcompare=__commonJS({"node_modules/semver/functions/rcompare.js"(exports,module){"use strict";var compare=require_compare();var rcompare=(a,b2,loose)=>compare(b2,a,loose);module.exports=rcompare}});var require_compare_loose=__commonJS({"node_modules/semver/functions/compare-loose.js"(exports,module){"use strict";var compare=require_compare();var compareLoose=(a,b2)=>compare(a,b2,true);module.exports=compareLoose}});var require_compare_build=__commonJS({"node_modules/semver/functions/compare-build.js"(exports,module){"use strict";var SemVer=require_semver();var compareBuild=(a,b2,loose)=>{const versionA=new SemVer(a,loose);const versionB=new SemVer(b2,loose);return versionA.compare(versionB)||versionA.compareBuild(versionB)};module.exports=compareBuild}});var require_sort=__commonJS({"node_modules/semver/functions/sort.js"(exports,module){"use strict";var compareBuild=require_compare_build();var sort=(list,loose)=>list.sort((a,b2)=>compareBuild(a,b2,loose));module.exports=sort}});var require_rsort=__commonJS({"node_modules/semver/functions/rsort.js"(exports,module){"use strict";var compareBuild=require_compare_build();var rsort=(list,loose)=>list.sort((a,b2)=>compareBuild(b2,a,loose));module.exports=rsort}});var require_gt=__commonJS({"node_modules/semver/functions/gt.js"(exports,module){"use strict";var compare=require_compare();var gt2=(a,b2,loose)=>compare(a,b2,loose)>0;module.exports=gt2}});var require_lt=__commonJS({"node_modules/semver/functions/lt.js"(exports,module){"use strict";var compare=require_compare();var lt2=(a,b2,loose)=>compare(a,b2,loose)<0;module.exports=lt2}});var require_eq=__commonJS({"node_modules/semver/functions/eq.js"(exports,module){"use strict";var compare=require_compare();var eq=(a,b2,loose)=>compare(a,b2,loose)===0;module.exports=eq}});var require_neq=__commonJS({"node_modules/semver/functions/neq.js"(exports,module){"use strict";var compare=require_compare();var neq=(a,b2,loose)=>compare(a,b2,loose)!==0;module.exports=neq}});var require_gte=__commonJS({"node_modules/semver/functions/gte.js"(exports,module){"use strict";var compare=require_compare();var gte=(a,b2,loose)=>compare(a,b2,loose)>=0;module.exports=gte}});var require_lte=__commonJS({"node_modules/semver/functions/lte.js"(exports,module){"use strict";var compare=require_compare();var lte=(a,b2,loose)=>compare(a,b2,loose)<=0;module.exports=lte}});var require_cmp=__commonJS({"node_modules/semver/functions/cmp.js"(exports,module){"use strict";var eq=require_eq();var neq=require_neq();var gt2=require_gt();var gte=require_gte();var lt2=require_lt();var lte=require_lte();var cmp=(a,op,b2,loose)=>{switch(op){case"===":if(typeof a==="object"){a=a.version}if(typeof b2==="object"){b2=b2.version}return a===b2;case"!==":if(typeof a==="object"){a=a.version}if(typeof b2==="object"){b2=b2.version}return a!==b2;case"":case"=":case"==":return eq(a,b2,loose);case"!=":return neq(a,b2,loose);case">":return gt2(a,b2,loose);case">=":return gte(a,b2,loose);case"<":return lt2(a,b2,loose);case"<=":return lte(a,b2,loose);default:throw new TypeError(`Invalid operator: ${op}`)}};module.exports=cmp}});var require_coerce=__commonJS({"node_modules/semver/functions/coerce.js"(exports,module){"use strict";var SemVer=require_semver();var parse4=require_parse2();var{safeRe:re2,t}=require_re();var coerce=(version,options)=>{if(version instanceof SemVer){return version}if(typeof version==="number"){version=String(version)}if(typeof version!=="string"){return null}options=options||{};let match=null;if(!options.rtl){match=version.match(options.includePrerelease?re2[t.COERCEFULL]:re2[t.COERCE])}else{const coerceRtlRegex=options.includePrerelease?re2[t.COERCERTLFULL]:re2[t.COERCERTL];let next;while((next=coerceRtlRegex.exec(version))&&(!match||match.index+match[0].length!==version.length)){if(!match||next.index+next[0].length!==match.index+match[0].length){match=next}coerceRtlRegex.lastIndex=next.index+next[1].length+next[2].length}coerceRtlRegex.lastIndex=-1}if(match===null){return null}const major=match[2];const minor=match[3]||"0";const patch=match[4]||"0";const prerelease=options.includePrerelease&&match[5]?`-${match[5]}`:"";const build2=options.includePrerelease&&match[6]?`+${match[6]}`:"";return parse4(`${major}.${minor}.${patch}${prerelease}${build2}`,options)};module.exports=coerce}});var require_truncate=__commonJS({"node_modules/semver/functions/truncate.js"(exports,module){"use strict";var parse4=require_parse2();var constants2=require_constants7();var SemVer=require_semver();var truncate=(version,truncation,options)=>{if(!constants2.RELEASE_TYPES.includes(truncation)){return null}const clonedVersion=cloneInputVersion(version,options);return clonedVersion&&doTruncation(clonedVersion,truncation)};var cloneInputVersion=(version,options)=>{const versionStringToParse=version instanceof SemVer?version.version:version;return parse4(versionStringToParse,options)};var doTruncation=(version,truncation)=>{if(isPrerelease(truncation)){return version.version}version.prerelease=[];switch(truncation){case"major":version.minor=0;version.patch=0;break;case"minor":version.patch=0;break}return version.format()};var isPrerelease=type=>{return type.startsWith("pre")};module.exports=truncate}});var require_lrucache=__commonJS({"node_modules/semver/internal/lrucache.js"(exports,module){"use strict";var LRUCache=class{constructor(){this.max=1e3;this.map=new Map}get(key2){const value=this.map.get(key2);if(value===void 0){return void 0}else{this.map.delete(key2);this.map.set(key2,value);return value}}delete(key2){return this.map.delete(key2)}set(key2,value){const deleted=this.delete(key2);if(!deleted&&value!==void 0){if(this.map.size>=this.max){const firstKey=this.map.keys().next().value;this.delete(firstKey)}this.map.set(key2,value)}return this}};module.exports=LRUCache}});var require_range=__commonJS({"node_modules/semver/classes/range.js"(exports,module){"use strict";var SPACE_CHARACTERS=/\s+/g;var Range=class _Range{constructor(range,options){options=parseOptions(options);if(range instanceof _Range){if(range.loose===!!options.loose&&range.includePrerelease===!!options.includePrerelease){return range}else{return new _Range(range.raw,options)}}if(range instanceof Comparator){this.raw=range.value;this.set=[[range]];this.formatted=void 0;return this}this.options=options;this.loose=!!options.loose;this.includePrerelease=!!options.includePrerelease;this.raw=range.trim().replace(SPACE_CHARACTERS," ");this.set=this.raw.split("||").map(r=>this.parseRange(r.trim())).filter(c=>c.length);if(!this.set.length){throw new TypeError(`Invalid SemVer Range: ${this.raw}`)}if(this.set.length>1){const first=this.set[0];this.set=this.set.filter(c=>!isNullSet(c[0]));if(this.set.length===0){this.set=[first]}else if(this.set.length>1){for(const c of this.set){if(c.length===1&&isAny(c[0])){this.set=[c];break}}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let i=0;i<this.set.length;i++){if(i>0){this.formatted+="||"}const comps=this.set[i];for(let k2=0;k2<comps.length;k2++){if(k2>0){this.formatted+=" "}this.formatted+=comps[k2].toString().trim()}}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(range){range=range.replace(BUILDSTRIPRE,"");const memoOpts=(this.options.includePrerelease&&FLAG_INCLUDE_PRERELEASE)|(this.options.loose&&FLAG_LOOSE);const memoKey=memoOpts+":"+range;const cached=cache6.get(memoKey);if(cached){return cached}const loose=this.options.loose;const hr2=loose?re2[t.HYPHENRANGELOOSE]:re2[t.HYPHENRANGE];range=range.replace(hr2,hyphenReplace(this.options.includePrerelease));debug("hyphen replace",range);range=range.replace(re2[t.COMPARATORTRIM],comparatorTrimReplace);debug("comparator trim",range);range=range.replace(re2[t.TILDETRIM],tildeTrimReplace);debug("tilde trim",range);range=range.replace(re2[t.CARETTRIM],caretTrimReplace);debug("caret trim",range);let rangeList=range.split(" ").map(comp=>parseComparator(comp,this.options)).join(" ").split(/\s+/).map(comp=>replaceGTE0(comp,this.options));if(loose){rangeList=rangeList.filter(comp=>{debug("loose invalid filter",comp,this.options);return!!comp.match(re2[t.COMPARATORLOOSE])})}debug("range list",rangeList);const rangeMap=new Map;const comparators=rangeList.map(comp=>new Comparator(comp,this.options));for(const comp of comparators){if(isNullSet(comp)){return[comp]}rangeMap.set(comp.value,comp)}if(rangeMap.size>1&&rangeMap.has("")){rangeMap.delete("")}const result=[...rangeMap.values()];cache6.set(memoKey,result);return result}intersects(range,options){if(!(range instanceof _Range)){throw new TypeError("a Range is required")}return this.set.some(thisComparators=>{return isSatisfiable(thisComparators,options)&&range.set.some(rangeComparators=>{return isSatisfiable(rangeComparators,options)&&thisComparators.every(thisComparator=>{return rangeComparators.every(rangeComparator=>{return thisComparator.intersects(rangeComparator,options)})})})})}test(version){if(!version){return false}if(typeof version==="string"){try{version=new SemVer(version,this.options)}catch(er2){return false}}for(let i=0;i<this.set.length;i++){if(testSet(this.set[i],version,this.options)){return true}}return false}};module.exports=Range;var LRU=require_lrucache();var cache6=new LRU;var parseOptions=require_parse_options();var Comparator=require_comparator();var debug=require_debug();var SemVer=require_semver();var{safeRe:re2,src,t,comparatorTrimReplace,tildeTrimReplace,caretTrimReplace}=require_re();var{FLAG_INCLUDE_PRERELEASE,FLAG_LOOSE}=require_constants7();var BUILDSTRIPRE=new RegExp(src[t.BUILD],"g");var isNullSet=c=>c.value==="<0.0.0-0";var isAny=c=>c.value==="";var isSatisfiable=(comparators,options)=>{let result=true;const remainingComparators=comparators.slice();let testComparator=remainingComparators.pop();while(result&&remainingComparators.length){result=remainingComparators.every(otherComparator=>{return testComparator.intersects(otherComparator,options)});testComparator=remainingComparators.pop()}return result};var parseComparator=(comp,options)=>{comp=comp.replace(re2[t.BUILD],"");debug("comp",comp,options);comp=replaceCarets(comp,options);debug("caret",comp);comp=replaceTildes(comp,options);debug("tildes",comp);comp=replaceXRanges(comp,options);debug("xrange",comp);comp=replaceStars(comp,options);debug("stars",comp);return comp};var isX=id=>!id||id.toLowerCase()==="x"||id==="*";var invalidXRangeOrder=(M2,m2,p2)=>isX(M2)&&!isX(m2)||isX(m2)&&p2&&!isX(p2);var replaceTildes=(comp,options)=>{return comp.trim().split(/\s+/).map(c=>replaceTilde(c,options)).join(" ")};var replaceTilde=(comp,options)=>{const r=options.loose?re2[t.TILDELOOSE]:re2[t.TILDE];const z2=options.includePrerelease?"-0":"";return comp.replace(r,(_2,M2,m2,p2,pr2)=>{debug("tilde",comp,_2,M2,m2,p2,pr2);let ret;if(isX(M2)){ret=""}else if(isX(m2)){ret=`>=${M2}.0.0${z2} <${+M2+1}.0.0-0`}else if(isX(p2)){ret=`>=${M2}.${m2}.0${z2} <${M2}.${+m2+1}.0-0`}else if(pr2){debug("replaceTilde pr",pr2);ret=`>=${M2}.${m2}.${p2}-${pr2} <${M2}.${+m2+1}.0-0`}else{ret=`>=${M2}.${m2}.${p2} <${M2}.${+m2+1}.0-0`}debug("tilde return",ret);return ret})};var replaceCarets=(comp,options)=>{return comp.trim().split(/\s+/).map(c=>replaceCaret(c,options)).join(" ")};var replaceCaret=(comp,options)=>{debug("caret",comp,options);const r=options.loose?re2[t.CARETLOOSE]:re2[t.CARET];const z2=options.includePrerelease?"-0":"";return comp.replace(r,(_2,M2,m2,p2,pr2)=>{debug("caret",comp,_2,M2,m2,p2,pr2);let ret;if(isX(M2)){ret=""}else if(isX(m2)){ret=`>=${M2}.0.0${z2} <${+M2+1}.0.0-0`}else if(isX(p2)){if(M2==="0"){ret=`>=${M2}.${m2}.0${z2} <${M2}.${+m2+1}.0-0`}else{ret=`>=${M2}.${m2}.0${z2} <${+M2+1}.0.0-0`}}else if(pr2){debug("replaceCaret pr",pr2);if(M2==="0"){if(m2==="0"){ret=`>=${M2}.${m2}.${p2}-${pr2} <${M2}.${m2}.${+p2+1}-0`}else{ret=`>=${M2}.${m2}.${p2}-${pr2} <${M2}.${+m2+1}.0-0`}}else{ret=`>=${M2}.${m2}.${p2}-${pr2} <${+M2+1}.0.0-0`}}else{debug("no pr");if(M2==="0"){if(m2==="0"){ret=`>=${M2}.${m2}.${p2} <${M2}.${m2}.${+p2+1}-0`}else{ret=`>=${M2}.${m2}.${p2} <${M2}.${+m2+1}.0-0`}}else{ret=`>=${M2}.${m2}.${p2} <${+M2+1}.0.0-0`}}debug("caret return",ret);return ret})};var replaceXRanges=(comp,options)=>{debug("replaceXRanges",comp,options);return comp.split(/\s+/).map(c=>replaceXRange(c,options)).join(" ")};var replaceXRange=(comp,options)=>{comp=comp.trim();const r=options.loose?re2[t.XRANGELOOSE]:re2[t.XRANGE];return comp.replace(r,(ret,gtlt,M2,m2,p2,pr2)=>{debug("xRange",comp,ret,gtlt,M2,m2,p2,pr2);if(invalidXRangeOrder(M2,m2,p2)){return comp}const xM=isX(M2);const xm=xM||isX(m2);const xp=xm||isX(p2);const anyX=xp;if(gtlt==="="&&anyX){gtlt=""}pr2=options.includePrerelease?"-0":"";if(xM){if(gtlt===">"||gtlt==="<"){ret="<0.0.0-0"}else{ret="*"}}else if(gtlt&&anyX){if(xm){m2=0}p2=0;if(gtlt===">"){gtlt=">=";if(xm){M2=+M2+1;m2=0;p2=0}else{m2=+m2+1;p2=0}}else if(gtlt==="<="){gtlt="<";if(xm){M2=+M2+1}else{m2=+m2+1}}if(gtlt==="<"){pr2="-0"}ret=`${gtlt+M2}.${m2}.${p2}${pr2}`}else if(xm){ret=`>=${M2}.0.0${pr2} <${+M2+1}.0.0-0`}else if(xp){ret=`>=${M2}.${m2}.0${pr2} <${M2}.${+m2+1}.0-0`}debug("xRange return",ret);return ret})};var replaceStars=(comp,options)=>{debug("replaceStars",comp,options);return comp.trim().replace(re2[t.STAR],"")};var replaceGTE0=(comp,options)=>{debug("replaceGTE0",comp,options);return comp.trim().replace(re2[options.includePrerelease?t.GTE0PRE:t.GTE0],"")};var hyphenReplace=incPr=>($0,from,fM,fm,fp2,fpr,fb,to2,tM,tm,tp,tpr)=>{if(isX(fM)){from=""}else if(isX(fm)){from=`>=${fM}.0.0${incPr?"-0":""}`}else if(isX(fp2)){from=`>=${fM}.${fm}.0${incPr?"-0":""}`}else if(fpr){from=`>=${from}`}else{from=`>=${from}${incPr?"-0":""}`}if(isX(tM)){to2=""}else if(isX(tm)){to2=`<${+tM+1}.0.0-0`}else if(isX(tp)){to2=`<${tM}.${+tm+1}.0-0`}else if(tpr){to2=`<=${tM}.${tm}.${tp}-${tpr}`}else if(incPr){to2=`<${tM}.${tm}.${+tp+1}-0`}else{to2=`<=${to2}`}return`${from} ${to2}`.trim()};var testSet=(set,version,options)=>{for(let i=0;i<set.length;i++){if(!set[i].test(version)){return false}}if(version.prerelease.length&&!options.includePrerelease){for(let i=0;i<set.length;i++){debug(set[i].semver);if(set[i].semver===Comparator.ANY){continue}if(set[i].semver.prerelease.length>0){const allowed=set[i].semver;if(allowed.major===version.major&&allowed.minor===version.minor&&allowed.patch===version.patch){return true}}}return false}return true}}});var require_comparator=__commonJS({"node_modules/semver/classes/comparator.js"(exports,module){"use strict";var ANY=Symbol("SemVer ANY");var Comparator=class _Comparator{static get ANY(){return ANY}constructor(comp,options){options=parseOptions(options);if(comp instanceof _Comparator){if(comp.loose===!!options.loose){return comp}else{comp=comp.value}}comp=comp.trim().split(/\s+/).join(" ");debug("comparator",comp,options);this.options=options;this.loose=!!options.loose;this.parse(comp);if(this.semver===ANY){this.value=""}else{this.value=this.operator+this.semver.version}debug("comp",this)}parse(comp){const r=this.options.loose?re2[t.COMPARATORLOOSE]:re2[t.COMPARATOR];const m2=comp.match(r);if(!m2){throw new TypeError(`Invalid comparator: ${comp}`)}this.operator=m2[1]!==void 0?m2[1]:"";if(this.operator==="="){this.operator=""}if(!m2[2]){this.semver=ANY}else{this.semver=new SemVer(m2[2],this.options.loose)}}toString(){return this.value}test(version){debug("Comparator.test",version,this.options.loose);if(this.semver===ANY||version===ANY){return true}if(typeof version==="string"){try{version=new SemVer(version,this.options)}catch(er2){return false}}return cmp(version,this.operator,this.semver,this.options)}intersects(comp,options){if(!(comp instanceof _Comparator)){throw new TypeError("a Comparator is required")}if(this.operator===""){if(this.value===""){return true}return new Range(comp.value,options).test(this.value)}else if(comp.operator===""){if(comp.value===""){return true}return new Range(this.value,options).test(comp.semver)}options=parseOptions(options);if(options.includePrerelease&&(this.value==="<0.0.0-0"||comp.value==="<0.0.0-0")){return false}if(!options.includePrerelease&&(this.value.startsWith("<0.0.0")||comp.value.startsWith("<0.0.0"))){return false}if(this.operator.startsWith(">")&&comp.operator.startsWith(">")){return true}if(this.operator.startsWith("<")&&comp.operator.startsWith("<")){return true}if(this.semver.version===comp.semver.version&&this.operator.includes("=")&&comp.operator.includes("=")){return true}if(cmp(this.semver,"<",comp.semver,options)&&this.operator.startsWith(">")&&comp.operator.startsWith("<")){return true}if(cmp(this.semver,">",comp.semver,options)&&this.operator.startsWith("<")&&comp.operator.startsWith(">")){return true}return false}};module.exports=Comparator;var parseOptions=require_parse_options();var{safeRe:re2,t}=require_re();var cmp=require_cmp();var debug=require_debug();var SemVer=require_semver();var Range=require_range()}});var require_satisfies=__commonJS({"node_modules/semver/functions/satisfies.js"(exports,module){"use strict";var Range=require_range();var satisfies=(version,range,options)=>{try{range=new Range(range,options)}catch(er2){return false}return range.test(version)};module.exports=satisfies}});var require_to_comparators=__commonJS({"node_modules/semver/ranges/to-comparators.js"(exports,module){"use strict";var Range=require_range();var toComparators=(range,options)=>new Range(range,options).set.map(comp=>comp.map(c=>c.value).join(" ").trim().split(" "));module.exports=toComparators}});var require_max_satisfying=__commonJS({"node_modules/semver/ranges/max-satisfying.js"(exports,module){"use strict";var SemVer=require_semver();var Range=require_range();var maxSatisfying=(versions,range,options)=>{let max=null;let maxSV=null;let rangeObj=null;try{rangeObj=new Range(range,options)}catch(er2){return null}versions.forEach(v2=>{if(rangeObj.test(v2)){if(!max||maxSV.compare(v2)===-1){max=v2;maxSV=new SemVer(max,options)}}});return max};module.exports=maxSatisfying}});var require_min_satisfying=__commonJS({"node_modules/semver/ranges/min-satisfying.js"(exports,module){"use strict";var SemVer=require_semver();var Range=require_range();var minSatisfying=(versions,range,options)=>{let min=null;let minSV=null;let rangeObj=null;try{rangeObj=new Range(range,options)}catch(er2){return null}versions.forEach(v2=>{if(rangeObj.test(v2)){if(!min||minSV.compare(v2)===1){min=v2;minSV=new SemVer(min,options)}}});return min};module.exports=minSatisfying}});var require_min_version=__commonJS({"node_modules/semver/ranges/min-version.js"(exports,module){"use strict";var SemVer=require_semver();var Range=require_range();var gt2=require_gt();var minVersion=(range,loose)=>{range=new Range(range,loose);let minver=new SemVer("0.0.0");if(range.test(minver)){return minver}minver=new SemVer("0.0.0-0");if(range.test(minver)){return minver}minver=null;for(let i=0;i<range.set.length;++i){const comparators=range.set[i];let setMin=null;comparators.forEach(comparator=>{const compver=new SemVer(comparator.semver.version);switch(comparator.operator){case">":if(compver.prerelease.length===0){compver.patch++}else{compver.prerelease.push(0)}compver.raw=compver.format();case"":case">=":if(!setMin||gt2(compver,setMin)){setMin=compver}break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${comparator.operator}`)}});if(setMin&&(!minver||gt2(minver,setMin))){minver=setMin}}if(minver&&range.test(minver)){return minver}return null};module.exports=minVersion}});var require_valid2=__commonJS({"node_modules/semver/ranges/valid.js"(exports,module){"use strict";var Range=require_range();var validRange=(range,options)=>{try{return new Range(range,options).range||"*"}catch(er2){return null}};module.exports=validRange}});var require_outside=__commonJS({"node_modules/semver/ranges/outside.js"(exports,module){"use strict";var SemVer=require_semver();var Comparator=require_comparator();var{ANY}=Comparator;var Range=require_range();var satisfies=require_satisfies();var gt2=require_gt();var lt2=require_lt();var lte=require_lte();var gte=require_gte();var outside=(version,range,hilo,options)=>{version=new SemVer(version,options);range=new Range(range,options);let gtfn,ltefn,ltfn,comp,ecomp;switch(hilo){case">":gtfn=gt2;ltefn=lte;ltfn=lt2;comp=">";ecomp=">=";break;case"<":gtfn=lt2;ltefn=gte;ltfn=gt2;comp="<";ecomp="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(satisfies(version,range,options)){return false}for(let i=0;i<range.set.length;++i){const comparators=range.set[i];let high=null;let low=null;comparators.forEach(comparator=>{if(comparator.semver===ANY){comparator=new Comparator(">=0.0.0")}high=high||comparator;low=low||comparator;if(gtfn(comparator.semver,high.semver,options)){high=comparator}else if(ltfn(comparator.semver,low.semver,options)){low=comparator}});if(high.operator===comp||high.operator===ecomp){return false}if((!low.operator||low.operator===comp)&<efn(version,low.semver)){return false}else if(low.operator===ecomp&<fn(version,low.semver)){return false}}return true};module.exports=outside}});var require_gtr=__commonJS({"node_modules/semver/ranges/gtr.js"(exports,module){"use strict";var outside=require_outside();var gtr=(version,range,options)=>outside(version,range,">",options);module.exports=gtr}});var require_ltr=__commonJS({"node_modules/semver/ranges/ltr.js"(exports,module){"use strict";var outside=require_outside();var ltr=(version,range,options)=>outside(version,range,"<",options);module.exports=ltr}});var require_intersects=__commonJS({"node_modules/semver/ranges/intersects.js"(exports,module){"use strict";var Range=require_range();var intersects=(r1,r2,options)=>{r1=new Range(r1,options);r2=new Range(r2,options);return r1.intersects(r2,options)};module.exports=intersects}});var require_simplify=__commonJS({"node_modules/semver/ranges/simplify.js"(exports,module){"use strict";var satisfies=require_satisfies();var compare=require_compare();module.exports=(versions,range,options)=>{const set=[];let first=null;let prev=null;const v2=versions.sort((a,b2)=>compare(a,b2,options));for(const version of v2){const included2=satisfies(version,range,options);if(included2){prev=version;if(!first){first=version}}else{if(prev){set.push([first,prev])}prev=null;first=null}}if(first){set.push([first,null])}const ranges=[];for(const[min,max]of set){if(min===max){ranges.push(min)}else if(!max&&min===v2[0]){ranges.push("*")}else if(!max){ranges.push(`>=${min}`)}else if(min===v2[0]){ranges.push(`<=${max}`)}else{ranges.push(`${min} - ${max}`)}}const simplified=ranges.join(" || ");const original=typeof range.raw==="string"?range.raw:String(range);return simplified.length<original.length?simplified:range}}});var require_subset=__commonJS({"node_modules/semver/ranges/subset.js"(exports,module){"use strict";var Range=require_range();var Comparator=require_comparator();var{ANY}=Comparator;var satisfies=require_satisfies();var compare=require_compare();var subset=(sub,dom,options={})=>{if(sub===dom){return true}sub=new Range(sub,options);dom=new Range(dom,options);let sawNonNull=false;OUTER:for(const simpleSub of sub.set){for(const simpleDom of dom.set){const isSub=simpleSubset(simpleSub,simpleDom,options);sawNonNull=sawNonNull||isSub!==null;if(isSub){continue OUTER}}if(sawNonNull){return false}}return true};var minimumVersionWithPreRelease=[new Comparator(">=0.0.0-0")];var minimumVersion=[new Comparator(">=0.0.0")];var simpleSubset=(sub,dom,options)=>{if(sub===dom){return true}if(sub.length===1&&sub[0].semver===ANY){if(dom.length===1&&dom[0].semver===ANY){return true}else if(options.includePrerelease){sub=minimumVersionWithPreRelease}else{sub=minimumVersion}}if(dom.length===1&&dom[0].semver===ANY){if(options.includePrerelease){return true}else{dom=minimumVersion}}const eqSet=new Set;let gt2,lt2;for(const c of sub){if(c.operator===">"||c.operator===">="){gt2=higherGT(gt2,c,options)}else if(c.operator==="<"||c.operator==="<="){lt2=lowerLT(lt2,c,options)}else{eqSet.add(c.semver)}}if(eqSet.size>1){return null}let gtltComp;if(gt2&<2){gtltComp=compare(gt2.semver,lt2.semver,options);if(gtltComp>0){return null}else if(gtltComp===0&&(gt2.operator!==">="||lt2.operator!=="<=")){return null}}for(const eq of eqSet){if(gt2&&!satisfies(eq,String(gt2),options)){return null}if(lt2&&!satisfies(eq,String(lt2),options)){return null}for(const c of dom){if(!satisfies(eq,String(c),options)){return false}}return true}let higher,lower;let hasDomLT,hasDomGT;let needDomLTPre=lt2&&!options.includePrerelease&<2.semver.prerelease.length?lt2.semver:false;let needDomGTPre=gt2&&!options.includePrerelease&>2.semver.prerelease.length?gt2.semver:false;if(needDomLTPre&&needDomLTPre.prerelease.length===1&<2.operator==="<"&&needDomLTPre.prerelease[0]===0){needDomLTPre=false}for(const c of dom){hasDomGT=hasDomGT||c.operator===">"||c.operator===">=";hasDomLT=hasDomLT||c.operator==="<"||c.operator==="<=";if(gt2){if(needDomGTPre){if(c.semver.prerelease&&c.semver.prerelease.length&&c.semver.major===needDomGTPre.major&&c.semver.minor===needDomGTPre.minor&&c.semver.patch===needDomGTPre.patch){needDomGTPre=false}}if(c.operator===">"||c.operator===">="){higher=higherGT(gt2,c,options);if(higher===c&&higher!==gt2){return false}}else if(gt2.operator===">="&&!c.test(gt2.semver)){return false}}if(lt2){if(needDomLTPre){if(c.semver.prerelease&&c.semver.prerelease.length&&c.semver.major===needDomLTPre.major&&c.semver.minor===needDomLTPre.minor&&c.semver.patch===needDomLTPre.patch){needDomLTPre=false}}if(c.operator==="<"||c.operator==="<="){lower=lowerLT(lt2,c,options);if(lower===c&&lower!==lt2){return false}}else if(lt2.operator==="<="&&!c.test(lt2.semver)){return false}}if(!c.operator&&(lt2||gt2)&>ltComp!==0){return false}}if(gt2&&hasDomLT&&!lt2&>ltComp!==0){return false}if(lt2&&hasDomGT&&!gt2&>ltComp!==0){return false}if(needDomGTPre||needDomLTPre){return false}return true};var higherGT=(a,b2,options)=>{if(!a){return b2}const comp=compare(a.semver,b2.semver,options);return comp>0?a:comp<0?b2:b2.operator===">"&&a.operator===">="?b2:a};var lowerLT=(a,b2,options)=>{if(!a){return b2}const comp=compare(a.semver,b2.semver,options);return comp<0?a:comp>0?b2:b2.operator==="<"&&a.operator==="<="?b2:a};module.exports=subset}});var require_semver2=__commonJS({"node_modules/semver/index.js"(exports,module){"use strict";var internalRe=require_re();var constants2=require_constants7();var SemVer=require_semver();var identifiers=require_identifiers();var parse4=require_parse2();var valid=require_valid();var clean=require_clean();var inc=require_inc();var diff=require_diff();var major=require_major();var minor=require_minor();var patch=require_patch();var prerelease=require_prerelease();var compare=require_compare();var rcompare=require_rcompare();var compareLoose=require_compare_loose();var compareBuild=require_compare_build();var sort=require_sort();var rsort=require_rsort();var gt2=require_gt();var lt2=require_lt();var eq=require_eq();var neq=require_neq();var gte=require_gte();var lte=require_lte();var cmp=require_cmp();var coerce=require_coerce();var truncate=require_truncate();var Comparator=require_comparator();var Range=require_range();var satisfies=require_satisfies();var toComparators=require_to_comparators();var maxSatisfying=require_max_satisfying();var minSatisfying=require_min_satisfying();var minVersion=require_min_version();var validRange=require_valid2();var outside=require_outside();var gtr=require_gtr();var ltr=require_ltr();var intersects=require_intersects();var simplifyRange=require_simplify();var subset=require_subset();module.exports={parse:parse4,valid,clean,inc,diff,major,minor,patch,prerelease,compare,rcompare,compareLoose,compareBuild,sort,rsort,gt:gt2,lt:lt2,eq,neq,gte,lte,cmp,coerce,truncate,Comparator,Range,satisfies,toComparators,maxSatisfying,minSatisfying,minVersion,validRange,outside,gtr,ltr,intersects,simplifyRange,subset,SemVer,re:internalRe.re,src:internalRe.src,tokens:internalRe.t,SEMVER_SPEC_VERSION:constants2.SEMVER_SPEC_VERSION,RELEASE_TYPES:constants2.RELEASE_TYPES,compareIdentifiers:identifiers.compareIdentifiers,rcompareIdentifiers:identifiers.rcompareIdentifiers}}});init_dist();init_logger();init_fetch_util();init_dist();init_external_summary_settings();init_config();var EXTERNAL_SUMMARY_NOTE="\n\n[External summary mode: the conversation model selects consumed ranges; the configured independent summary service generates the authoritative summary. Use object-form content: [{startId, endId, topic?}]. summary is optional and, if supplied, only a non-authoritative hint, not the committed summary. Selected source text and read-only context are sent to the configured service using its separate credentials. All candidates failing leaves originals unchanged. This mode overrides instructions above requiring you to write the final summary.]";function externalSummaryEnabled(config){return config?.externalSummary?.enabled===true}function conversationPromptSections(sections,external){return external?{...sections,howToCompress:null}:sections}function messageTimestampSections(sections,kind="function"){if(!resolveMessageTimestamps(loadConfigFile().compress))return sections;const out={...sections};if(kind==="function"&&out.acpTags===void 0)out.acpTags=FUNCTION_ACP_TAGS_TIMESTAMPED;if(out.howToCompress===LEAN_HOW_TO_COMPRESS)out.howToCompress=LEAN_HOW_TO_COMPRESS_TIMESTAMPED;return out}function externalSummaryMaxToolDurationMs(config){const ext=config?.externalSummary;const total=ext?.budget?.totalTimeoutMs;return ext?.enabled===true&&typeof total==="number"&&Number.isFinite(total)&&total>0?total:void 0}function autoFoldActive(config){const ext=config?.externalSummary;return ext?.enabled===true&&ext.autoFold===true}var AUTO_FOLD_BACKOFF_MS=10*6e4;function autoFoldBackoffActive(session){const until=session?.metadata?.autoFoldBackoffUntil;return typeof until==="number"&&until>Date.now()}function armAutoFoldBackoff(session){if(!session)return;(session.metadata??(session.metadata={})).autoFoldBackoffUntil=Date.now()+AUTO_FOLD_BACKOFF_MS}function autoFoldFloor(session){const value=session?.metadata?.autoFoldFloorTokens;return typeof value==="number"&&Number.isFinite(value)&&value>0?value:void 0}function externalQueueDroppedAll(dispatch){return dispatch!==void 0&&dispatch.calls>0&&dispatch.attempts===0}function autoFoldEngaged(config,session){return autoFoldActive(config)&&!autoFoldBackoffActive(session)}function growthFoldingArmed(config,overflowTarget,measuredFloor){const resolved=config;const ext=resolved?.externalSummary;if(ext?.enabled!==true||ext.autoFold!==true)return false;const overflow=overflowTarget??resolved?.modelContextLimit??0;if(!(overflow>0))return false;const configured=ext.autoFoldTargetTokens??Math.round(overflow/2);const target=Math.max(AUTO_FOLD_TARGET_MIN,Math.min(configured,overflow),measuredFloor??0);return target<overflow}function adaptSchema(value){if(Array.isArray(value))return value.map(adaptSchema);if(!value||typeof value!=="object")return value;const result={};for(const[key2,child]of Object.entries(value)){result[key2]=key2==="required"&&Array.isArray(child)?child.filter(name=>name!=="summary"):adaptSchema(child)}const properties=result.properties;if(properties?.summary)properties.summary={type:"string",description:"Optional non-authoritative hint; the independent service generates the committed summary."};return result}function withExternalSummaryTools(tools,enabled){if(!enabled)return[...tools];return tools.map(tool=>{const copy=structuredClone(tool);const declaration=copy.function??copy;if(declaration.name!=="compress")return tool;declaration.description="Compress selected consumed ranges using the configured independent summary service."+EXTERNAL_SUMMARY_NOTE;if(declaration.parameters)declaration.parameters=adaptSchema(declaration.parameters);if(copy.input_schema)copy.input_schema=adaptSchema(copy.input_schema);return copy})}init_dist();init_dist();var MARKER_INTEGRITY_NOTE="\n\n[ACP marker integrity: lines shaped like '\u{1F4E6} [ACP] Compressed \u2026' or '\u274C [ACP] \u2026 FAILED' are CONFIRMATION MARKERS emitted by the bili proxy itself, right after it executes a compress/decompress/search_context/acp_status call. They are not something you write. NEVER emit such a line as your own text \u2014 writing one fakes a state change that did not happen, and the proxy strips it. To compress, call the compress tool. To verify a compression landed, call acp_status and confirm the block count increased \u2014 a confirmation line you wrote yourself proves nothing.";var MARKER_SILENCE_CLAUSE=" Execute these calls silently: no announcement or preamble before the call, and no completion summary, status line, or marker-style line after it \u2014 when the tool returns, continue the task directly as if the call had not happened.]";function isNudgeEchoText(text2){const t=text2.trim();if(t.length===0)return false;return t.endsWith(MARKER_INTEGRITY_NOTE)||t.endsWith(MARKER_SILENCE_CLAUSE)}var NON_ACP_TAGS_SECTIONS={function:["tools","summariesInContext"],hybrid:["textProtocol","functionTools"]};function effectiveLeadSection(override,fallback){return override===null?null:override??fallback}function buildAcpTagsOnlyPrompt(family,prompts,sections){const p2=prompts??defaultPrompts;const overrides={...sections??{}};for(const key2 of NON_ACP_TAGS_SECTIONS[family])overrides[key2]=null;const lead=[];for(const eff of[effectiveLeadSection(overrides.philosophy,p2.compressPhilosophy),effectiveLeadSection(overrides.howToCompress,p2.howToCompressRules)])if(eff!==null)lead.push(eff);const prefix=lead.length>0?`${lead.join("\n\n")}
|
|
893
893
|
|
|
894
894
|
`:"";const full=family==="hybrid"?buildCompressHybridSystemPrompt(p2,overrides):buildCompressSystemPrompt(p2,overrides);if(!full.startsWith(prefix))return"";return full.slice(prefix.length)}var BILI_SEARCH_CONTEXT_TOOL={name:SEARCH_CONTEXT_TOOL.name,description:SEARCH_CONTEXT_TOOL.description,input_schema:SEARCH_CONTEXT_TOOL.input_schema};var BILI_SEARCH_CONTEXT_TOOL_OPENAI={type:"function",function:{name:SEARCH_CONTEXT_TOOL_OPENAI.function.name,description:SEARCH_CONTEXT_TOOL_OPENAI.function.description,parameters:SEARCH_CONTEXT_TOOL_OPENAI.function.parameters}};var BILI_SEARCH_CONTEXT_TOOL_RESPONSES={type:"function",name:SEARCH_CONTEXT_TOOL_RESPONSES.name,description:SEARCH_CONTEXT_TOOL_RESPONSES.description,parameters:SEARCH_CONTEXT_TOOL_RESPONSES.parameters};var BILI_SEARCH_CONTEXT_TOOL_GOOGLE={name:SEARCH_CONTEXT_TOOL_GOOGLE.name,description:SEARCH_CONTEXT_TOOL_GOOGLE.description,parameters:SEARCH_CONTEXT_TOOL_GOOGLE.parameters};var DECOMPRESS_RANGE_PARAM_START={type:"string",description:"Optional mNNNNN message ref, inclusive lower bound of a sub-range of this block. With endId, restores only that span instead of the whole block (requires CCR: compress.ccr.enabled). Omit both to restore the whole block; empty values count as omitted."};var DECOMPRESS_RANGE_PARAM_END={type:"string",description:"Optional mNNNNN message ref, inclusive upper bound. Used together with startId; omit both to restore the whole block."};function withRangeParams(schema){return{...schema,properties:{...schema.properties,startId:DECOMPRESS_RANGE_PARAM_START,endId:DECOMPRESS_RANGE_PARAM_END}}}var DECOMPRESS_IMAGE_PARAM={type:"string",description:'Optional mNNNNN message ref whose IMAGE payload you want restored (an image that was stripped or folded away). Pass "list" to enumerate every image currently restorable. Restored images are written to host-readable files and their paths returned \u2014 open them with the read tool. Independent of blockId/range and of CCR.'};var DECOMPRESS_IMAGE_NOTE=` Pass imageRef (an mNNNNN ref) to restore a stripped/folded image's original pixels to a file you open with the read tool; imageRef:"list" shows what is restorable.`;function withImageRestoreParam(schema){return{...schema,properties:{...schema.properties,imageRef:DECOMPRESS_IMAGE_PARAM}}}var BILI_DECOMPRESS_TOOL={name:DECOMPRESS_TOOL.name,description:DECOMPRESS_TOOL.description+DECOMPRESS_IMAGE_NOTE,input_schema:withImageRestoreParam(withRangeParams(DECOMPRESS_TOOL.input_schema))};var BILI_DECOMPRESS_TOOL_OPENAI={type:"function",function:{name:DECOMPRESS_TOOL_OPENAI.function.name,description:DECOMPRESS_TOOL_OPENAI.function.description+DECOMPRESS_IMAGE_NOTE,parameters:withImageRestoreParam(withRangeParams(DECOMPRESS_TOOL_OPENAI.function.parameters))}};var BILI_DECOMPRESS_TOOL_RESPONSES={type:"function",name:DECOMPRESS_TOOL_RESPONSES.name,description:DECOMPRESS_TOOL_RESPONSES.description+DECOMPRESS_IMAGE_NOTE,parameters:withImageRestoreParam(withRangeParams(DECOMPRESS_TOOL_RESPONSES.parameters))};var BILI_DECOMPRESS_TOOL_GOOGLE={name:DECOMPRESS_TOOL_GOOGLE.name,description:DECOMPRESS_TOOL_GOOGLE.description+DECOMPRESS_IMAGE_NOTE,parameters:withImageRestoreParam(withRangeParams(DECOMPRESS_TOOL_GOOGLE.parameters))};var BILI_ACP_TOOLS_ANTHROPIC=ACP_TOOLS_ANTHROPIC.map(t=>t.name===SEARCH_CONTEXT_TOOL_NAME?BILI_SEARCH_CONTEXT_TOOL:t.name===DECOMPRESS_TOOL_NAME?BILI_DECOMPRESS_TOOL:t);var BILI_ACP_TOOLS_OPENAI=ACP_TOOLS_OPENAI.map(t=>t.function.name===SEARCH_CONTEXT_TOOL_NAME?BILI_SEARCH_CONTEXT_TOOL_OPENAI:t.function.name===DECOMPRESS_TOOL_NAME?BILI_DECOMPRESS_TOOL_OPENAI:t);var BILI_ACP_TOOLS_RESPONSES=ACP_TOOLS_RESPONSES.map(t=>t.name===SEARCH_CONTEXT_TOOL_NAME?BILI_SEARCH_CONTEXT_TOOL_RESPONSES:t.name===DECOMPRESS_TOOL_NAME?BILI_DECOMPRESS_TOOL_RESPONSES:t);var BILI_ACP_TOOLS_GOOGLE=ACP_TOOLS_GOOGLE.map(t=>t.name===SEARCH_CONTEXT_TOOL_NAME?BILI_SEARCH_CONTEXT_TOOL_GOOGLE:t.name===DECOMPRESS_TOOL_NAME?BILI_DECOMPRESS_TOOL_GOOGLE:t);var BILI_DECOMPRESS_IMG_ANTHROPIC={name:DECOMPRESS_TOOL.name,description:DECOMPRESS_TOOL.description+DECOMPRESS_IMAGE_NOTE,input_schema:withImageRestoreParam(DECOMPRESS_TOOL.input_schema)};var BILI_DECOMPRESS_IMG_OPENAI={type:"function",function:{name:DECOMPRESS_TOOL_OPENAI.function.name,description:DECOMPRESS_TOOL_OPENAI.function.description+DECOMPRESS_IMAGE_NOTE,parameters:withImageRestoreParam(DECOMPRESS_TOOL_OPENAI.function.parameters)}};var BILI_DECOMPRESS_IMG_RESPONSES={type:"function",name:DECOMPRESS_TOOL_RESPONSES.name,description:DECOMPRESS_TOOL_RESPONSES.description+DECOMPRESS_IMAGE_NOTE,parameters:withImageRestoreParam(DECOMPRESS_TOOL_RESPONSES.parameters)};var BILI_DECOMPRESS_IMG_GOOGLE={name:DECOMPRESS_TOOL_GOOGLE.name,description:DECOMPRESS_TOOL_GOOGLE.description+DECOMPRESS_IMAGE_NOTE,parameters:withImageRestoreParam(DECOMPRESS_TOOL_GOOGLE.parameters)};var BILI_ACP_TOOLS_ANTHROPIC_NO_RANGE=ACP_TOOLS_ANTHROPIC.map(t=>t.name===SEARCH_CONTEXT_TOOL_NAME?BILI_SEARCH_CONTEXT_TOOL:t.name===DECOMPRESS_TOOL_NAME?BILI_DECOMPRESS_IMG_ANTHROPIC:t);var BILI_ACP_TOOLS_OPENAI_NO_RANGE=ACP_TOOLS_OPENAI.map(t=>t.function.name===SEARCH_CONTEXT_TOOL_NAME?BILI_SEARCH_CONTEXT_TOOL_OPENAI:t.function.name===DECOMPRESS_TOOL_NAME?BILI_DECOMPRESS_IMG_OPENAI:t);var BILI_ACP_TOOLS_RESPONSES_NO_RANGE=ACP_TOOLS_RESPONSES.map(t=>t.name===SEARCH_CONTEXT_TOOL_NAME?BILI_SEARCH_CONTEXT_TOOL_RESPONSES:t.name===DECOMPRESS_TOOL_NAME?BILI_DECOMPRESS_IMG_RESPONSES:t);var BILI_ACP_TOOLS_GOOGLE_NO_RANGE=ACP_TOOLS_GOOGLE.map(t=>t.name===SEARCH_CONTEXT_TOOL_NAME?BILI_SEARCH_CONTEXT_TOOL_GOOGLE:t.name===DECOMPRESS_TOOL_NAME?BILI_DECOMPRESS_IMG_GOOGLE:t);var BILI_ACP_READONLY_TOOLS_RESPONSES_NO_RANGE=ACP_READONLY_TOOLS_RESPONSES.map(t=>t.name===SEARCH_CONTEXT_TOOL_NAME?BILI_SEARCH_CONTEXT_TOOL_RESPONSES:t.name===DECOMPRESS_TOOL_NAME?BILI_DECOMPRESS_IMG_RESPONSES:t);var BILI_ACP_READONLY_TOOLS_RESPONSES=ACP_READONLY_TOOLS_RESPONSES.map(t=>t.name===SEARCH_CONTEXT_TOOL_NAME?BILI_SEARCH_CONTEXT_TOOL_RESPONSES:t.name===DECOMPRESS_TOOL_NAME?BILI_DECOMPRESS_TOOL_RESPONSES:t);var RUN_CODE_TOOL_NAME="run_code";var CODE_MODE_OMNIBUS_TOOL_NAMES=new Set([RUN_CODE_TOOL_NAME,"code_run"]);var PTC_BINDING_NOTE=" Calling convention: if this environment only allows `run_code` to be called directly (code-mode/PTC harness), call this tool from inside a run_code program via the harness's generated SDK; otherwise call it directly as a tool.";var PTC_EXEMPT_NOTE=" If a harness rule says only `run_code` may be called directly, this tool is the exception: it has no run_code SDK binding, so call it DIRECTLY as a normal tool call \u2014 the proxy executes it server-side.";var PROJECT_URL_NOTE=" Context management is provided by billion-context \u2014 report billion-context problems at github.com/ranxianglei/billion-context/issues.";function acpNoteFor(name,mode){if(name===void 0||!ACP_TOOL_NAMES.has(name))return void 0;let note=mode==="binding"?PTC_BINDING_NOTE:mode==="exempt"?PTC_EXEMPT_NOTE:"";if(name===COMPRESS_TOOL_NAME)note+=PROJECT_URL_NOTE;return note.length>0?note:void 0}function withAcpNotes(tools,mode,skip){return tools.map(t=>{const note=skip?.has(String(t?.name))?void 0:acpNoteFor(t?.name,mode);return note&&typeof t.description==="string"?{...t,description:t.description+note}:t})}function withAcpNotesOpenAI(tools,mode,skip){return tools.map(t=>{const note=skip?.has(String(t?.function?.name))?void 0:acpNoteFor(t?.function?.name,mode);return note&&typeof t.function.description==="string"?{...t,function:{...t.function,description:t.function.description+note}}:t})}function packOwnsDescription(toolPrompts){const owned=new Set;if(!toolPrompts)return owned;for(const[name,tp]of Object.entries(toolPrompts))if(tp?.description!==void 0)owned.add(name);return owned}var PROJECT_ATTRIBUTION_LINE="Context management for this conversation is provided by billion-context (github.com/ranxianglei/billion-context). Report billion-context problems to that project's issue tracker.";function withProjectAttribution(prompt){return prompt+"\n\n"+PROJECT_ATTRIBUTION_LINE}function mcpBiliToolName(name){return"mcp__bili__"+name}var MCP_DIALECT_NOTE="On this host the context-management tools are exposed under MCP-prefixed names: call `mcp__bili__compress` (not `compress`) \u2014 likewise `mcp__bili__decompress`, `mcp__bili__search_context`, `mcp__bili__acp_status`.";function withMcpDialectNote(prompt,on){return on?`${prompt}
|
|
895
895
|
|
|
896
896
|
${MCP_DIALECT_NOTE}`:prompt}function ptcNoteMode(names){for(const n of names)if(typeof n==="string"&&CODE_MODE_OMNIBUS_TOOL_NAMES.has(n))return"exempt";return"none"}var ABSORB_TOOL_RESPONSES={type:"function",name:ABSORB_TOOL_OPENAI.function.name,description:ABSORB_TOOL_OPENAI.function.description,parameters:ABSORB_TOOL_OPENAI.function.parameters};function absorbToolsFor(name){return{anthropic:{name,description:ABSORB_TOOL.description,input_schema:ABSORB_TOOL.input_schema},openai:{type:"function",function:{name,description:ABSORB_TOOL_OPENAI.function.description,parameters:ABSORB_TOOL_OPENAI.function.parameters}},responses:{type:"function",name,description:ABSORB_TOOL_OPENAI.function.description,parameters:ABSORB_TOOL_OPENAI.function.parameters},google:{name,description:ABSORB_TOOL_GOOGLE.description,parameters:ABSORB_TOOL_GOOGLE.parameters}}}var RULE_TOOL_DESCRIPTION='Record a short, principle-level reminder so it survives context compression \u2014 the call and its result are protected and stay in context. Record when: the user calls out or repeatedly emphasizes a lesson; the user asks you to remember or follow a behavior; you personally hit a major pitfall worth remembering long-term. Keep each rule to one short line. Omit the rule argument to list recorded rules. To remove a recorded rule pass delete with its id (e.g. "rule3"); to remove every recorded rule pass clear: true. delete and clear are mutually exclusive with each other and with rule \u2014 use one operation per call.';var RULE_PARAM_SCHEMA={type:"object",properties:{rule:{type:"string",description:"Short principle-level reminder to record. Omit to list recorded rules."},delete:{type:"string",description:'Id of a recorded rule to remove (e.g. "rule3"). Mutually exclusive with rule and clear.'},clear:{type:"boolean",description:"Remove every recorded rule at once. Mutually exclusive with rule and delete."}}};var RULE_TOOL={name:RULE_TOOL_NAME,description:RULE_TOOL_DESCRIPTION,input_schema:RULE_PARAM_SCHEMA};var RULE_TOOL_OPENAI={type:"function",function:{name:RULE_TOOL_NAME,description:RULE_TOOL_DESCRIPTION,parameters:RULE_PARAM_SCHEMA}};var RULE_TOOL_RESPONSES={type:"function",name:RULE_TOOL_NAME,description:RULE_TOOL_DESCRIPTION,parameters:RULE_PARAM_SCHEMA};var RULE_TOOL_GOOGLE={name:RULE_TOOL_NAME,description:RULE_TOOL_DESCRIPTION,parameters:RULE_PARAM_SCHEMA};var READ_ORIGINAL_IMAGE_TOOL_NAME="acp_read_original_image";var READ_ORIGINAL_IMAGE_TOOL_DESCRIPTION="Read the ORIGINAL full-resolution image of a message whose picture was downscaled before reaching you. Beside each shrunken image there is a [bili] note quoting its mNNNNN ref and both sizes \u2014 pass that ref here. The original bytes are returned as an image attached to this result. The original can be much larger than the downscaled copy, so call this only when you actually need full-resolution detail (small text, colors, pixel alignment); the downscaled version is enough for most work.";var READ_ORIGINAL_IMAGE_PARAM_SCHEMA={type:"object",properties:{ref:{type:"string",description:"The mNNNNN message ref quoted in the [bili] downsample note beside the shrunken image."}},required:["ref"]};var READ_ORIGINAL_IMAGE_TOOL={name:READ_ORIGINAL_IMAGE_TOOL_NAME,description:READ_ORIGINAL_IMAGE_TOOL_DESCRIPTION,input_schema:READ_ORIGINAL_IMAGE_PARAM_SCHEMA};var READ_ORIGINAL_IMAGE_TOOL_OPENAI={type:"function",function:{name:READ_ORIGINAL_IMAGE_TOOL_NAME,description:READ_ORIGINAL_IMAGE_TOOL_DESCRIPTION,parameters:READ_ORIGINAL_IMAGE_PARAM_SCHEMA}};var READ_ORIGINAL_IMAGE_TOOL_RESPONSES={type:"function",name:READ_ORIGINAL_IMAGE_TOOL_NAME,description:READ_ORIGINAL_IMAGE_TOOL_DESCRIPTION,parameters:READ_ORIGINAL_IMAGE_PARAM_SCHEMA};var READ_ORIGINAL_IMAGE_TOOL_GOOGLE={name:READ_ORIGINAL_IMAGE_TOOL_NAME,description:READ_ORIGINAL_IMAGE_TOOL_DESCRIPTION,parameters:READ_ORIGINAL_IMAGE_PARAM_SCHEMA};var RETRIEVE_TOOL_DESCRIPTION='Retrieve the full original text of a stored message by its id. Large tool results are replaced on the wire with a placeholder shaped like "\u{1F4E6} [acp-stored #m00423 \xB7 shell output \xB7 4,213 tok] `npm run build`\n \u2192 acp_retrieve("m00423") returns the full text". Call this with that ref to read the complete original back into context. Leaving the placeholder costs nothing; retrieving costs one call \u2014 fetch only when the detail matters to the current step.';var RETRIEVE_PARAM_SCHEMA={type:"object",properties:{ref:{type:"string",description:"The stored message id to retrieve (an mNNNNN ref from an [acp-stored] placeholder)."}},required:["ref"]};function retrieveToolsFor(name){return{anthropic:{name,description:RETRIEVE_TOOL_DESCRIPTION,input_schema:RETRIEVE_PARAM_SCHEMA},openai:{type:"function",function:{name,description:RETRIEVE_TOOL_DESCRIPTION,parameters:RETRIEVE_PARAM_SCHEMA}},responses:{type:"function",name,description:RETRIEVE_TOOL_DESCRIPTION,parameters:RETRIEVE_PARAM_SCHEMA},google:{name,description:RETRIEVE_TOOL_DESCRIPTION,parameters:RETRIEVE_PARAM_SCHEMA}}}function isPlainObject2(v2){return typeof v2==="object"&&v2!==null&&!Array.isArray(v2)}function looksLikeRangeEntry(o){const hasStart=typeof o["startId"]==="string"||typeof o["startRef"]==="string"||typeof o["messageId"]==="string";const hasEnd=typeof o["endId"]==="string"||typeof o["endRef"]==="string"||typeof o["messageId"]==="string";return hasStart&&hasEnd&&typeof o["summary"]==="string"}function decodeCompressObject(raw){let s3=raw.trim();if(s3.startsWith("```")){const nl=s3.indexOf("\n");if(nl===-1)return void 0;const body=s3.slice(nl+1);const end=body.lastIndexOf("```");s3=(end>0?body.slice(0,end):body).trim()}let v2;try{v2=JSON.parse(s3)}catch{return void 0}if(typeof v2==="string"){try{v2=JSON.parse(v2)}catch{return void 0}}return isPlainObject2(v2)?v2:void 0}function normalizeCompressInput(input){if(Array.isArray(input))return{content:input};if(isPlainObject2(input)){const c=input["content"];if(isPlainObject2(c))return{...input,content:[c]};return input}if(typeof input==="string"){const obj=decodeCompressObject(input);if(!obj)return input;const c=obj["content"];if(isPlainObject2(c))return{...obj,content:[c]};if(looksLikeRangeEntry(obj))return{content:[obj]};return input}return input}function decodeDoubleEscapedContent(input){if(!isPlainObject2(input))return void 0;const c=input["content"];if(typeof c!=="string")return void 0;if(c.includes("\n"))return void 0;if(!c.includes("\\n"))return void 0;const decoded=c.replace(/\\r\\n/g,"\r\n").replace(/\\n/g,"\n");if(decoded===c)return void 0;return{...input,content:decoded}}function parseCompressInput(input,callId,options={}){const normalized=normalizeCompressInput(input);let parsed=parseCompressArgs(normalized,{callId});const note=message=>{if(!options.quiet)log("warn",message)};if(!parsed.diagnostics.ok&&parsed.diagnostics.kind!=="ok"){const decoded=decodeDoubleEscapedContent(normalized);if(decoded!==void 0){const retry=parseCompressArgs(decoded,{callId});if(retry.ranges.length>parsed.ranges.length){note(`[acp-compress-input] double-escape salvage: recovered ${retry.ranges.length} range(s) after decoding literal backslash-n separators once (kind was ${parsed.diagnostics.kind}) (#3780)`);parsed=retry}}}if(parsed.diagnostics.quoteSalvage===true){note(`[acp-compress-input] quote-salvage: recovered ${parsed.ranges.length} range(s) after single->double quote normalization (kind=${parsed.diagnostics.kind})`)}if(parsed.diagnostics.flatSummarySalvage===true){note(`[acp-compress-input] flat-summary salvage: recovered ${parsed.ranges.length} range(s); summary text arrived in content alongside top-level refs`)}if(!parsed.diagnostics.ok&&parsed.diagnostics.kind!=="ok"){note(`[acp-compress-input] rejected: kind=${parsed.diagnostics.kind} invalidItems=${parsed.diagnostics.invalidItems}${parsed.diagnostics.keys?` keys=[${parsed.diagnostics.keys.join(",")}]`:""}${parsed.diagnostics.length!==void 0?` len=${parsed.diagnostics.length}`:""}${parsed.diagnostics.invalidReasons&&parsed.diagnostics.invalidReasons.length>0?` reasons=[${parsed.diagnostics.invalidReasons.join(" | ")}]`:""}`)}else if(parsed.diagnostics.invalidItems>0||parsed.diagnostics.kind==="truncated"){note(`[acp-compress-input] partial: ${parsed.ranges.length} range(s) applied, ${parsed.diagnostics.invalidItems} rejected (kind=${parsed.diagnostics.kind}) reasons=[${(parsed.diagnostics.invalidReasons??[]).join(" | ")}]`)}return{ranges:parsed.ranges,diagnostics:parsed.diagnostics}}function extractResponsesTextTriggers(text2){const calls=[];let clean=text2;let hadTrigger=false;const triggers=[{name:"compress",open:ACP_TEXT_OPEN,close:ACP_TEXT_CLOSE,requirePayload:true},{name:"acp_status",open:ACP_STATUS_OPEN,close:ACP_STATUS_CLOSE,requirePayload:false},{name:"search_context",open:ACP_SEARCH_OPEN,close:ACP_SEARCH_CLOSE,requirePayload:true},{name:"decompress",open:ACP_DECOMPRESS_OPEN,close:ACP_DECOMPRESS_CLOSE,requirePayload:true}];for(const t of triggers){let start=clean.indexOf(t.open);while(start>=0){const end=clean.indexOf(t.close,start+t.open.length);if(end<0)break;hadTrigger=true;const payload=clean.slice(start+t.open.length,end).trim();if(payload.length>0||!t.requirePayload){const stamp2=`${Date.now()}-${calls.length}`;calls.push({name:t.name,callId:`call_text_${stamp2}`,arguments:payload.length>0?payload:"{}"})}clean=clean.slice(0,start)+clean.slice(end+t.close.length);start=clean.indexOf(t.open)}}return{clean:hadTrigger?clean:text2,calls}}var STAGED_COMPRESS_GUIDANCE="\n\n[Smooth-transition guidance: when you compress, prefer a SMALLER, TAIL-biased range \u2014 compress the most recent large content and keep the stable prefix (the earliest messages) intact. A large single rewrite changes the request shape sharply and can trip provider risk-control; smaller tail-biased folds keep the prefix cache alive and the transition gentle.]";function withStagedCompressGuidance(text2){if(maxShrinkPerCompress2()===void 0)return text2;return text2+STAGED_COMPRESS_GUIDANCE}var FIRST_SIGHT_DRAIN_NOTE="\n\n[First-sight digestion: the compressible ranges above are a pre-existing backlog this session arrived with, not growth from your current task. Drain the backlog in ONE batched compress call \u2014 cover EVERY ready range, splitting oversized spans into multiple smaller ranges at logical boundaries (each summary within its cap), and submit them all together in the same call (content: [{startId,endId,summary}, {\u2026}]). Do NOT fold piecemeal across turns: every small front fold re-bills the whole remaining tail to the prefix cache, while one batched call lands once. Keep draining while the nudge repeats \u2014 it stops when the backlog is gone. Where this conflicts with a single-span directive above, this takes precedence: the cited span is the starting point of the batch, not its limit.]";var FIRST_SIGHT_DRAIN_NOTE_EXTERNAL="\n\n[First-sight digestion: the compressible ranges above are a pre-existing backlog this session arrived with, not growth from your current task. The independent summary service writes the summaries \u2014 you only select the ranges (plus optional topic hints), so your own response-length budget is not a limit here. Drain the backlog in ONE batched compress call \u2014 cover EVERY ready range, splitting oversized spans into multiple smaller ranges at logical boundaries, and submit them all together in the same call (content: [{startId,endId,summary}, {\u2026}]). Do NOT fold piecemeal across turns: every small front fold re-bills the whole remaining tail to the prefix cache, while one batched call lands once. Keep draining while the nudge repeats \u2014 it stops when the backlog is gone. Where this conflicts with a single-span directive above, this takes precedence: the cited span is the starting point of the batch, not its limit.]";function firstSightDrainActive(reason){return reason!==void 0&&reason.includes("[first-sight mass]")}function withFirstSightDrain(text2,reason,external){if(!firstSightDrainActive(reason))return withStagedCompressGuidance(text2);return text2+(external?FIRST_SIGHT_DRAIN_NOTE_EXTERNAL:FIRST_SIGHT_DRAIN_NOTE)}function withMarkerIntegrityNote(text2,visibilityMarkers=true){return text2+MARKER_INTEGRITY_NOTE+(visibilityMarkers?MARKER_SILENCE_CLAUSE:"")}var SUMMARY_BUDGET_NOTE="\n\n[Per-summary length budget: every compress summary has a hard character cap, and a single oversized summary fails the WHOLE compress call \u2014 nothing gets folded. Dense content (many subagent results, long tool outputs) tempts you into writing one giant summary for a big range; don't. When a range is large or dense, SPLIT it into several smaller ranges at logical boundaries and give EACH its own concise, scannable summary, then batch all the ranges in one compress call (content: [{startId,endId,summary}, {\u2026}]). Prefer several tight blocks over one bloated block: each stays under the cap, and smaller blocks are cheaper to re-send and independently searchable/decompressible.]";function withSummaryBudgetNote(text2,external){return text2+(external?EXTERNAL_SUMMARY_NOTE:SUMMARY_BUDGET_NOTE)}import{createHash as createHash16,randomUUID as randomUUID6}from"crypto";import fs15 from"fs";import net3 from"net";import os9 from"os";import path28 from"path";import{createRequire as createRequire4}from"module";import{Worker as Worker3}from"worker_threads";import{pathToFileURL as pathToFileURL2}from"url";import{execFileSync as execFileSync5,spawn as spawn2,spawnSync as spawnSync3}from"child_process";import tls4 from"tls";var import_node_forge=__toESM(require_lib(),1);init_paths();init_logger();import crypto from"crypto";import{execFileSync as execFileSync3}from"child_process";import fs from"fs";import os2 from"os";import path7 from"path";import tls3 from"tls";var ROOT_CERT_FILE="root-ca.pem";var COMBINED_MAX_AGE_MS=24*60*60*1e3;var PLATFORM_CA_CANDIDATES=process.platform==="darwin"?["/etc/ssl/cert.pem","/private/etc/ssl/cert.pem"]:process.platform==="win32"?[]:["/etc/ssl/certs/ca-certificates.crt","/etc/pki/tls/certs/ca-bundle.crt","/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem","/etc/ssl/ca-bundle.pem","/etc/ssl/cert.pem"];function rootCaPath(){return path7.join(caDir(),ROOT_CERT_FILE)}init_upstream_proxy();init_client_config();init_vertex();import fs3 from"fs";import os4 from"os";import path9 from"path";init_util();init_log_mask();init_knobs();init_mitm_domains();var MITM_UPSTREAM_KEY="__biliMitmUpstream";var blindTunnelCounts=new Map;function getBlindTunnelStats(){const hosts2={};let total=0;for(const[h,n]of blindTunnelCounts){hosts2[h]=n;total+=n}return{total,hosts:hosts2}}function readMitmUpstream(socket){if(!socket)return void 0;return socket[MITM_UPSTREAM_KEY]}init_private_host();init_upstream_fail();init_instance();var TWIN_ADOPT_EXIT_CODE=3;import net2 from"net";var CONNECT_PROBE_TIMEOUT_MS=2e3;function originHostPort(origin){try{const u2=new URL(origin);if(u2.protocol!=="http:"&&u2.protocol!=="https:")return void 0;const host=u2.hostname.replace(/^\[|\]$/g,"");if(host==="")return void 0;const port=u2.port!==""?Number(u2.port):u2.protocol==="https:"?443:80;return Number.isInteger(port)&&port>0?{host,port}:void 0}catch{return void 0}}function attemptConnect(host,port,timeoutMs){return new Promise(resolve2=>{let settled=false;const settle=outcome=>{if(settled)return;settled=true;socket.destroy();resolve2(outcome)};const socket=net2.connect({host,port});socket.setTimeout(timeoutMs);socket.once("connect",()=>settle({ok:true}));socket.once("timeout",()=>settle({ok:false,detail:`connect timeout after ${timeoutMs}ms`}));socket.once("error",err2=>settle({ok:false,detail:typeof err2.code==="string"&&err2.code.length>0?err2.code:String(err2.message??err2)}))})}async function tcpConnectable(origin,timeoutMs=CONNECT_PROBE_TIMEOUT_MS){const hp=originHostPort(origin);if(hp===void 0)return false;const outcome=await attemptConnect(hp.host,hp.port,timeoutMs);return outcome.ok}function errCodeOf(err2){const e=err2;const code=e?.cause?.code??e?.code;return typeof code==="string"&&code.length>0?code:void 0}function isTimeoutErr(err2){const e=err2;const names=[e?.name,e?.cause?.name];const codes=[e?.code,e?.cause?.code];return names.includes("TimeoutError")||names.includes("AbortError")||codes.includes("ABORT_ERR")||codes.includes("UND_ERR_HEADERS_TIMEOUT")}async function probeLiveness(origin,budgetMs){const hp=originHostPort(origin);if(hp===void 0)return{state:"dead",detail:"unparseable origin"};const conn=await attemptConnect(hp.host,hp.port,CONNECT_PROBE_TIMEOUT_MS);if(!conn.ok)return{state:"dead",detail:conn.detail??"connect failed"};try{const res=await fetch(`${origin}/__bili/health`,{signal:AbortSignal.timeout(budgetMs)});if(!res.ok)return{state:"dead",detail:`HTTP ${res.status}`};try{const data=await res.json();if(data.ok!==true)return{state:"dead",detail:"health payload reports not-ok"}}catch{return{state:"dead",detail:"non-JSON health payload (foreign listener?)"}}return{state:"alive"}}catch(err2){if(isTimeoutErr(err2))return{state:"busy",detail:`no health answer within ${budgetMs}ms after TCP connect`};return{state:"dead",detail:errCodeOf(err2)??String(err2?.message??err2).slice(0,120)}}}init_main();init_client_config();init_vertex();init_config();init_instance();init_dsh_channel();init_pi_channel();init_update();import fs12 from"fs";import path20 from"path";import os8 from"os";import crypto4 from"crypto";import{execFileSync as execFileSync4,spawnSync as spawnSync2}from"child_process";import{fileURLToPath as fileURLToPath4}from"url";import fs9 from"fs";import path17 from"path";init_client_config();init_instance();init_native_bootstrap();init_shared();init_client_config();import fs10 from"fs";import path18 from"path";import crypto3 from"crypto";import fs11 from"fs";import path19 from"path";init_instance();init_native_bootstrap();init_shared();init_config();init_native_bootstrap();init_log_mask();init_logger();init_paths();init_version();import{appendFileSync,mkdirSync as mkdirSync3}from"fs";import path21 from"path";function logHostEvent(level,origin,msg){try{const file=defaultLogFile();mkdirSync3(path21.dirname(file),{recursive:true});const safe=maskUrlsForDiagnostics(maskIpsInText(redactSecretsInText(msg)));appendFileSync(file,`${logTimestamp()} [${level}] [v=${VERSION}] ${origin?`${origin} `:""}${safe}
|
|
897
|
-
`)}catch{}}init_logger();init_version();import http from"http";var PERMISSION_DENIED_SIGNATURE=/\b(?:EPERM|EACCES|EROFS|EBUSY)\b|operation not permitted|permission denied|read-only file system|readonly database/i;var BILI_DATA_PATH_SIGNATURE=/billion-context|combined-ca\.pem|index\.db|\.local[\\/](?:share|state)[\\/]/i;function classifyStartupFailure(sample){if(!PERMISSION_DENIED_SIGNATURE.test(sample)||!BILI_DATA_PATH_SIGNATURE.test(sample))return"";return"possible cause: the proxy could not write its own data files (EPERM/EACCES/read-only on the bili data dir) \u2014 most often antivirus (e.g. Windows Defender Controlled Folder Access) blocking the node runtime, a read-only flag or ACL on the directory, or another process holding the files; add the bili data dir and the node runtime to AV exclusions (see #367) or fix the directory permissions, then retry"}var MAX_HOLD_MS=10*6e4;init_update();init_win_cmd();init_client_config();init_config();init_registry();init_config();init_logger();var BILI_HOP_HEADER="x-bili-hop";function parseLauncherModelWindows(raw){if(!raw)return{};try{const parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return{};const out={};for(const[id,v2]of Object.entries(parsed)){if(typeof v2==="number"&&Number.isFinite(v2)&&v2>0)out[id]=Math.floor(v2)}return out}catch{return{}}}var LAUNCHER_MODEL_WINDOWS=parseLauncherModelWindows(process.env.BILI_LAUNCHER_MODEL_WINDOWS);function parseLauncherModelMaxOutputs(raw){if(!raw)return{};try{const parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return{};const out={};for(const[id,v2]of Object.entries(parsed)){if(typeof v2==="number"&&Number.isFinite(v2)&&v2>0)out[id]=Math.floor(v2)}return out}catch{return{}}}var LAUNCHER_MODEL_MAX_OUTPUTS=parseLauncherModelMaxOutputs(process.env.BILI_LAUNCHER_MODEL_MAX_OUTPUTS);function launcherMaxOutput(model){return LAUNCHER_MODEL_MAX_OUTPUTS[model]}function launcherContextWindow(model){return LAUNCHER_MODEL_WINDOWS[model]}var windowSourceLogged=new Set;var MAX_ANTHROPIC_BETA_WINDOW=1e7;function anthropicBetaContextWindow(headers){const raw=headers["anthropic-beta"];if(raw===void 0)return void 0;const list=Array.isArray(raw)?raw.join(","):raw;let best;for(const part of list.split(",")){const m2=/^context-(\d+)m\b/.exec(part.trim().toLowerCase());if(!m2)continue;const n=Number.parseInt(m2[1],10);if(!Number.isFinite(n)||n<=0)continue;const w2=Math.min(n*1e6,MAX_ANTHROPIC_BETA_WINDOW);if(best===void 0||w2>best)best=w2}return best}function expandedContextSuffixWindow(model){if(!model)return void 0;const m2=/\[(\d+)m\]$/i.exec(model.trim());if(!m2)return void 0;const n=Number.parseInt(m2[1],10);if(!Number.isFinite(n)||n<=0)return void 0;return Math.min(n*1e6,MAX_ANTHROPIC_BETA_WINDOW)}var registryWindowCappedLogged=new Set;function capRegistryWindowByStandard(model,registryWindow,hasTierEvidence){if(registryWindow===void 0||hasTierEvidence)return registryWindow;const std=tierGatedStandardWindow(model);if(std===void 0||registryWindow<=std)return registryWindow;if(!registryWindowCappedLogged.has(model)){registryWindowCappedLogged.add(model);log("info",`[window] registry advertises ${registryWindow} for ${model} but the request carries no tier evidence (context-Nm beta header / [Nm] suffix) \u2014 capping at the built-in standard ${std} (#1321)`)}return std}init_vertex();init_client_config();init_dist();init_logger();import{createHash as createHash15}from"crypto";import{createHash as createHash14,randomUUID as randomUUID4}from"crypto";import{closeSync,existsSync as existsSync7,fsyncSync,mkdirSync as mkdirSync7,openSync,readdirSync as readdirSync2,readFileSync as readFileSync9,renameSync as renameSync2,rmSync,statSync as statSync6,writeFileSync as writeFileSync6}from"fs";import{readdir as readdir2,readFile as readFile4,rm as rm2}from"fs/promises";import*as path25 from"path";import{createHash as createHash7}from"crypto";import fs13 from"fs";import fsp from"fs/promises";import path22 from"path";var StateStore=class{enabled;dir;version;debounceMs;log;legacyFn;relPathFn;validateFn;foreignFileFn;codec;retryAttempts;retryBaseMs;retryMaxMs;timers=new Map;pending=new Map;writeChains=new Map;discovered=new Map;commitSeq=new Map;failCounts=new Map;tmpSeq=0;constructor(opts){this.dir=opts.dir;this.version=opts.version;this.debounceMs=opts.debounceMs??500;this.enabled=opts.enabled??true;this.log=opts.log??((_level,_msg)=>{});this.relPathFn=opts.relPath;this.legacyFn=opts.legacy;this.validateFn=opts.validate??defaultValidate;this.foreignFileFn=opts.foreignFile;this.codec=opts.codec;this.retryAttempts=Math.max(1,opts.retryAttempts??6);this.retryBaseMs=Math.max(1,opts.retryBaseMs??50);this.retryMaxMs=Math.max(this.retryBaseMs,opts.retryMaxMs??1600)}scheduleSave(id,build2){if(!this.enabled)return;this.pending.set(id,build2);const existing=this.timers.get(id);if(existing)return;const timer3=setTimeout(()=>{this.timers.delete(id);const builder=this.pending.get(id);this.pending.delete(id);if(!builder)return;void this.writeNow(id,builder).catch(()=>{})},this.debounceMs);timer3.unref?.();this.timers.set(id,timer3)}async writeNow(id,build2){if(!this.enabled)return;const prev=this.writeChains.get(id)??Promise.resolve();const next=prev.catch(()=>{}).then(()=>this.writeInner(id,build2));this.writeChains.set(id,next);next.finally(()=>{if(this.writeChains.get(id)===next)this.writeChains.delete(id)}).catch(()=>{});return next}flushSync(id,build2){if(!this.enabled)return true;const timer3=this.timers.get(id);if(timer3){clearTimeout(timer3);this.timers.delete(id);this.pending.delete(id)}let payload;try{payload=build2()}catch(e){this.log("error",`[persist] builder failed for ${id}: ${errText(e)}`);return false}const file=this.resolvePath(id,payload);const data=this.serialize(id,payload);let lastErr;for(let attempt=0;attempt<this.retryAttempts;attempt++){const tmp=this.tempPath(file);try{fs13.mkdirSync(path22.dirname(file),{recursive:true});this.atomicWriteDurable(tmp,data);fs13.renameSync(tmp,file);lastErr=void 0;break}catch(e){lastErr=e;try{fs13.unlinkSync(tmp)}catch{}if(!isTransientFsError(e)||attempt===this.retryAttempts-1)break;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,this.backoffMs(attempt))}}if(!lastErr){this.discovered.set(id,file);this.clearFailure(id);this.bumpCommit(id);this.removeSpillSync(file);return true}const spill=this.spillPathFor(file);let spillPath=null;for(let attempt=0;attempt<this.retryAttempts&&spillPath===null;attempt++){try{fs13.mkdirSync(path22.dirname(spill),{recursive:true});this.atomicWriteDurable(spill,data);spillPath=spill}catch(e){if(!isTransientFsError(e)||attempt===this.retryAttempts-1)break;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,this.backoffMs(attempt))}}if(spillPath)this.discovered.set(id,spillPath);if(spillPath)this.bumpCommit(id);this.recordFailure(id,lastErr,spillPath);return spillPath!==null}loadSync(id,hint){if(!this.enabled)return null;const candidates=[this.discovered.get(id),hint?path22.join(this.dir,hint):void 0,path22.join(this.dir,flatFileNameFor(id))];for(const file of candidates){if(!file)continue;const envelope=this.readEnvelope(file);if(envelope&&envelope.id===id)return envelope}return null}async loadAll(){const out=new Map;if(!this.enabled)return out;const files=await this.walkJsonFiles(this.dir);for(const file of files){if(this.foreignFileFn?.(file))continue;const envelope=this.readEnvelope(file);if(!envelope)continue;const base=path22.basename(file);const relBase=path22.basename(this.relPathOf(envelope.id,envelope.payload));const flatBase=flatFileNameFor(envelope.id);let owner=null;if(base===relBase||base===flatBase){owner=envelope.id}else if(base.endsWith(".fb.json")){const canonicalBase=`${base.slice(0,-".fb.json".length)}.json`;if(canonicalBase===relBase||canonicalBase===flatBase){owner=envelope.id}}if(owner===null){this.log("warn",`[persist] skipping ${rel(file,this.dir)}: filename does not match record id`);continue}const existing=out.get(owner);if(!existing||envelope.savedAt>=existing.savedAt){out.set(owner,envelope);this.discovered.set(owner,file)}}return out}hasPending(id){return this.timers.has(id)}pendingIds(){return[...this.timers.keys()]}async flushAll(){const ids=this.pendingIds();for(const timer3 of this.timers.values())clearTimeout(timer3);this.timers.clear();const builders=new Map;for(const id of ids){const build2=this.pending.get(id);if(build2)builders.set(id,build2);this.pending.delete(id)}await Promise.all([...builders.entries()].map(([id,build2])=>this.writeNow(id,build2).catch(e=>{this.log("error",`[persist] shutdown flush failed for ${id}: ${errText(e)}`)})));await Promise.allSettled([...this.writeChains.values()])}cancelAll(){for(const timer3 of this.timers.values())clearTimeout(timer3);this.timers.clear();this.pending.clear()}async writeInner(id,build2){const baseSeq=this.commitSeq.get(id)??0;let payload;try{payload=build2()}catch(e){this.log("error",`[persist] builder failed for ${id}: ${errText(e)}`);throw e}const file=this.resolvePath(id,payload);const data=this.serialize(id,payload);let lastErr;for(let attempt=0;attempt<this.retryAttempts;attempt++){const tmp=this.tempPath(file);try{await fsp.mkdir(path22.dirname(file),{recursive:true});await fsp.writeFile(tmp,data);this.fsyncFile(tmp);if((this.commitSeq.get(id)??0)!==baseSeq){await fsp.unlink(tmp).catch(()=>{});return}try{fs13.renameSync(tmp,file)}catch(e){lastErr=e;await fsp.unlink(tmp).catch(()=>{});if(!isTransientFsError(e)||attempt===this.retryAttempts-1)break;const{promise,resolve:resolve2}=Promise.withResolvers();setTimeout(resolve2,this.backoffMs(attempt));await promise;continue}this.discovered.set(id,file);this.clearFailure(id);this.commitSeq.set(id,baseSeq+1);await this.removeSpill(file);return}catch(e){lastErr=e;await fsp.unlink(tmp).catch(()=>{});if(!isTransientFsError(e)||attempt===this.retryAttempts-1)break;const{promise,resolve:resolve2}=Promise.withResolvers();setTimeout(resolve2,this.backoffMs(attempt));await promise}}if((this.commitSeq.get(id)??0)!==baseSeq)return;const spill=this.spillPathFor(file);let spillPath=null;for(let attempt=0;attempt<this.retryAttempts&&spillPath===null;attempt++){try{await fsp.mkdir(path22.dirname(spill),{recursive:true});if((this.commitSeq.get(id)??0)!==baseSeq)return;this.atomicWriteDurable(spill,data);spillPath=spill}catch(e){if(!isTransientFsError(e)||attempt===this.retryAttempts-1)break;const{promise,resolve:resolve2}=Promise.withResolvers();setTimeout(resolve2,this.backoffMs(attempt));await promise}}if(spillPath){this.discovered.set(id,spillPath);this.commitSeq.set(id,baseSeq+1)}this.recordFailure(id,lastErr,spillPath);throw lastErr}envelope(id,payload){return{version:this.version,savedAt:Date.now(),id,payload}}serialize(id,payload){const json=JSON.stringify(this.envelope(id,payload));return this.codec?this.codec.encode(json):json}resolvePath(id,payload){return path22.join(this.dir,this.relPathOf(id,payload))}relPathOf(id,payload){const custom=this.relPathFn?.(id,payload);if(!custom)return flatFileNameFor(id);const rel2=path22.normalize(custom);if(path22.isAbsolute(rel2)||rel2.split(/[\\/]+/).includes("..")){this.log("warn",`[persist] relPath for ${id} escapes dir; using flat name`);return flatFileNameFor(id)}return rel2}tempPath(dest){const seq=this.tmpSeq++;return path22.join(path22.dirname(dest),`.tmp-${path22.basename(dest,".json")}-${process.pid}-${seq}`)}atomicWriteDurable(file,data){const fd=fs13.openSync(file,"w");try{fs13.writeFileSync(fd,data);fs13.fsyncSync(fd)}finally{fs13.closeSync(fd)}}fsyncFile(file){const fd=fs13.openSync(file,"r+");try{fs13.fsyncSync(fd)}finally{fs13.closeSync(fd)}}backoffMs(attempt){return Math.min(this.retryBaseMs*2**attempt,this.retryMaxMs)}spillPathFor(file){const base=path22.basename(file);const dot=base.lastIndexOf(".");const stem2=dot>0?base.slice(0,dot):base;const ext=dot>0?base.slice(dot):".json";return path22.join(path22.dirname(file),`${stem2}.fb${ext}`)}async removeSpill(file){await fsp.unlink(this.spillPathFor(file)).catch(()=>{})}bumpCommit(id){this.commitSeq.set(id,(this.commitSeq.get(id)??0)+1)}removeSpillSync(file){try{fs13.unlinkSync(this.spillPathFor(file))}catch{}}recordFailure(id,err2,spillPath){const count=(this.failCounts.get(id)??0)+1;this.failCounts.set(id,count);const alertAt=count===1||count>=2&&(count&count-1)===0;if(!alertAt)return;const where=spillPath?`; data spilled to ${rel(spillPath,this.dir)}`:"; SPILLOVER ALSO FAILED \u2014 data at risk";this.log(count===1?"error":"warn",`[persist] write failed for ${id} (total ${count}x): ${errText(err2)}${where}`)}clearFailure(id){this.failCounts.delete(id)}readEnvelope(file){let parsed;try{const buf=fs13.readFileSync(file);const text2=this.codec?this.codec.decode(buf):buf.toString("utf8");parsed=JSON.parse(text2)}catch(e){if(e.code!=="ENOENT"){this.log("warn",`[persist] skipping corrupt file ${rel(file,this.dir)}: ${errText(e)}`)}return null}if(isEnvelopeLike(parsed)){if(!this.validateFn(parsed)){this.log("warn",`[persist] skipping invalid record ${rel(file,this.dir)}`);return null}return parsed}const adopted=this.adoptLegacy(parsed);if(adopted)return adopted;this.log("warn",`[persist] skipping invalid record ${rel(file,this.dir)}`);return null}adoptLegacy(parsed){const adoption=this.legacyFn?this.legacyFn(parsed):null;if(!adoption||typeof adoption.id!=="string"||adoption.id.length===0||adoption.payload==null){return null}const source=parsed;const envelope={version:adoption.version??source.version??this.version,savedAt:adoption.savedAt??source.savedAt??0,id:adoption.id,payload:adoption.payload};if(!this.validateFn(envelope))return null;return envelope}async walkJsonFiles(root){const out=[];const queue=[root];while(queue.length>0){const dir=queue.pop();let dirents;try{dirents=await fsp.readdir(dir,{withFileTypes:true})}catch{continue}for(const d of dirents){if(d.name.startsWith(".tmp-"))continue;const full=path22.join(dir,d.name);if(d.isDirectory())queue.push(full);else if(d.isFile()&&d.name.endsWith(".json"))out.push(full)}}return out}};function defaultValidate(envelope){return typeof envelope.id==="string"&&envelope.id.length>0&&envelope.payload!=null}function isEnvelopeLike(value){if(!value||typeof value!=="object")return false;const v2=value;return typeof v2.id==="string"&&"payload"in v2}function flatFileNameFor(id){return createHash7("sha256").update(id,"utf8").digest("hex").slice(0,24)+".json"}function isTransientFsError(e){const code=e.code;return code==="EPERM"||code==="EBUSY"||code==="EACCES"||code==="ENOENT"||code==="ENOTDIR"}function errText(e){return e instanceof Error?e.message:String(e)}function rel(p2,base){const r=path22.relative(base,p2);return r&&!r.startsWith("..")?r:p2}init_paths();init_knobs();init_logger();init_runtime_status();init_version();import{createCipheriv,createDecipheriv,randomBytes as randomBytes2}from"crypto";import*as zlib from"zlib";var ab=ArrayBuffer;var u8=Uint8Array;var u16=Uint16Array;var i16=Int16Array;var i32=Int32Array;var slc=function(v2,s3,e){if(u8.prototype.slice)return u8.prototype.slice.call(v2,s3,e);if(s3==null||s3<0)s3=0;if(e==null||e>v2.length)e=v2.length;var n=new u8(e-s3);n.set(v2.subarray(s3,e));return n};var fill=function(v2,n,s3,e){if(u8.prototype.fill)return u8.prototype.fill.call(v2,n,s3,e);if(s3==null||s3<0)s3=0;if(e==null||e>v2.length)e=v2.length;for(;s3<e;++s3)v2[s3]=n;return v2};var cpw=function(v2,t,s3,e){if(u8.prototype.copyWithin)return u8.prototype.copyWithin.call(v2,t,s3,e);if(s3==null||s3<0)s3=0;if(e==null||e>v2.length)e=v2.length;while(s3<e){v2[t++]=v2[s3++]}};var ec=["invalid zstd data","window size too large (>2046MB)","invalid block type","FSE accuracy too high","match distance too far back","unexpected EOF"];var err=function(ind,msg,nt2){var e=new Error(msg||ec[ind]);e.code=ind;if(Error.captureStackTrace)Error.captureStackTrace(e,err);if(!nt2)throw e;return e};var rb=function(d,b2,n){var i=0,o=0;for(;i<n;++i)o|=d[b2++]<<(i<<3);return o};var b4=function(d,b2){return(d[b2]|d[b2+1]<<8|d[b2+2]<<16|d[b2+3]<<24)>>>0};var rzfh=function(dat,w2){var n3=dat[0]|dat[1]<<8|dat[2]<<16;if(n3==3126568&&dat[3]==253){var flg=dat[4];var ss2=flg>>5&1,cc=flg>>2&1,df=flg&3,fcf=flg>>6;if(flg&8)err(0);var bt2=6-ss2;var db=df==3?4:df;var di2=rb(dat,bt2,db);bt2+=db;var fsb=fcf?1<<fcf:ss2;var fss=rb(dat,bt2,fsb)+(fcf==1&&256);var ws2=fss;if(!ss2){var wb=1<<10+(dat[5]>>3);ws2=wb+(wb>>3)*(dat[5]&7)}if(ws2>2145386496)err(1);var buf=new u8((w2==1?fss||ws2:w2?0:ws2)+12);buf[0]=1,buf[4]=4,buf[8]=8;return{b:bt2+fsb,y:0,l:0,d:di2,w:w2&&w2!=1?w2:buf.subarray(12),e:ws2,o:new i32(buf.buffer,0,3),u:fss,c:cc,m:Math.min(131072,ws2)}}else if((n3>>4|dat[3]<<20)==25481893){return b4(dat,4)+8}err(0)};var msb=function(val){var bits=0;for(;1<<bits<=val;++bits);return bits-1};var rfse=function(dat,bt2,mal){var tpos=(bt2<<3)+4;var al=(dat[bt2]&15)+5;if(al>mal)err(3);var sz=1<<al;var probs=sz,sym=-1,re2=-1,i=-1,ht2=sz;var buf=new ab(512+(sz<<2));var freq=new i16(buf,0,256);var dstate=new u16(buf,0,256);var nstate=new u16(buf,512,sz);var bb1=512+(sz<<1);var syms=new u8(buf,bb1,sz);var nbits=new u8(buf,bb1+sz);while(sym<255&&probs>0){var bits=msb(probs+1);var cbt=tpos>>3;var msk=(1<<bits+1)-1;var val=(dat[cbt]|dat[cbt+1]<<8|dat[cbt+2]<<16)>>(tpos&7)&msk;var msk1fb=(1<<bits)-1;var msv=msk-probs-1;var sval=val&msk1fb;if(sval<msv)tpos+=bits,val=sval;else{tpos+=bits+1;if(val>msk1fb)val-=msv}freq[++sym]=--val;if(val==-1){probs+=val;syms[--ht2]=sym}else probs-=val;if(!val){do{var rbt=tpos>>3;re2=(dat[rbt]|dat[rbt+1]<<8)>>(tpos&7)&3;tpos+=2;sym+=re2}while(re2==3)}}if(sym>255||probs)err(0);var sympos=0;var sstep=(sz>>1)+(sz>>3)+3;var smask=sz-1;for(var s3=0;s3<=sym;++s3){var sf=freq[s3];if(sf<1){dstate[s3]=-sf;continue}for(i=0;i<sf;++i){syms[sympos]=s3;do{sympos=sympos+sstep&smask}while(sympos>=ht2)}}if(sympos)err(0);for(i=0;i<sz;++i){var ns2=dstate[syms[i]]++;var nb=nbits[i]=al-msb(ns2);nstate[i]=(ns2<<nb)-sz}return[tpos+7>>3,{b:al,s:syms,n:nbits,t:nstate}]};var rhu=function(dat,bt2){var i=0,wc=-1;var buf=new u8(292),hb=dat[bt2];var hw=buf.subarray(0,256);var rc=buf.subarray(256,268);var ri2=new u16(buf.buffer,268);if(hb<128){var _a=rfse(dat,bt2+1,6),ebt=_a[0],fdt=_a[1];bt2+=hb;var epos=ebt<<3;var lb=dat[bt2];if(!lb)err(0);var st1=0,st2=0,btr1=fdt.b,btr2=btr1;var fpos=(++bt2<<3)-8+msb(lb);for(;;){fpos-=btr1;if(fpos<epos)break;var cbt=fpos>>3;st1+=(dat[cbt]|dat[cbt+1]<<8)>>(fpos&7)&(1<<btr1)-1;hw[++wc]=fdt.s[st1];fpos-=btr2;if(fpos<epos)break;cbt=fpos>>3;st2+=(dat[cbt]|dat[cbt+1]<<8)>>(fpos&7)&(1<<btr2)-1;hw[++wc]=fdt.s[st2];btr1=fdt.n[st1];st1=fdt.t[st1];btr2=fdt.n[st2];st2=fdt.t[st2]}if(++wc>255)err(0)}else{wc=hb-127;for(;i<wc;i+=2){var byte=dat[++bt2];hw[i]=byte>>4;hw[i+1]=byte&15}++bt2}var wes=0;for(i=0;i<wc;++i){var wt2=hw[i];if(wt2>11)err(0);wes+=wt2&&1<<wt2-1}var mb=msb(wes)+1;var ts2=1<<mb;var rem=ts2-wes;if(rem&rem-1)err(0);hw[wc++]=msb(rem)+1;for(i=0;i<wc;++i){var wt2=hw[i];++rc[hw[i]=wt2&&mb+1-wt2]}var hbuf=new u8(ts2<<1);var syms=hbuf.subarray(0,ts2),nb=hbuf.subarray(ts2);ri2[mb]=0;for(i=mb;i>0;--i){var pv=ri2[i];fill(nb,i,pv,ri2[i-1]=pv+rc[i]*(1<<mb-i))}if(ri2[0]!=ts2)err(0);for(i=0;i<wc;++i){var bits=hw[i];if(bits){var code=ri2[bits];fill(syms,i,code,ri2[bits]=code+(1<<mb-bits))}}return[bt2,{n:nb,b:mb,s:syms}]};var dllt=rfse(new u8([81,16,99,140,49,198,24,99,12,33,196,24,99,102,102,134,70,146,4]),0,6)[1];var dmlt=rfse(new u8([33,20,196,24,99,140,33,132,16,66,8,33,132,16,66,8,33,68,68,68,68,68,68,68,68,36,9]),0,6)[1];var doct=rfse(new u8([32,132,16,66,102,70,68,68,68,68,36,73,2]),0,5)[1];var b2bl=function(b2,s3){var len=b2.length,bl=new i32(len);for(var i=0;i<len;++i){bl[i]=s3;s3+=1<<b2[i]}return bl};var llb=new u8(new i32([0,0,0,0,16843009,50528770,134678020,202050057,269422093]).buffer,0,36);var llbl=b2bl(llb,0);var mlb=new u8(new i32([0,0,0,0,0,0,0,0,16843009,50528770,117769220,185207048,252579084,16]).buffer,0,53);var mlbl=b2bl(mlb,3);var dhu=function(dat,out,hu){var len=dat.length,ss2=out.length,lb=dat[len-1],msk=(1<<hu.b)-1,eb=-hu.b;if(!lb)err(0);var st2=0,btr=hu.b,pos=(len<<3)-8+msb(lb)-btr,i=-1;for(;pos>eb&&i<ss2;){var cbt=pos>>3;var val=(dat[cbt]|dat[cbt+1]<<8|dat[cbt+2]<<16)>>(pos&7);st2=(st2<<btr|val)&msk;out[++i]=hu.s[st2];pos-=btr=hu.n[st2]}if(pos!=eb||i+1!=ss2)err(0)};var dhu4=function(dat,out,hu){var bt2=6;var ss2=out.length,sz1=ss2+3>>2,sz2=sz1<<1,sz3=sz1+sz2;dhu(dat.subarray(bt2,bt2+=dat[0]|dat[1]<<8),out.subarray(0,sz1),hu);dhu(dat.subarray(bt2,bt2+=dat[2]|dat[3]<<8),out.subarray(sz1,sz2),hu);dhu(dat.subarray(bt2,bt2+=dat[4]|dat[5]<<8),out.subarray(sz2,sz3),hu);dhu(dat.subarray(bt2),out.subarray(sz3),hu)};var rzb=function(dat,st2,out){var _a;var bt2=st2.b;var b0=dat[bt2],btype=b0>>1&3;st2.l=b0&1;var sz=b0>>3|dat[bt2+1]<<5|dat[bt2+2]<<13;var ebt=(bt2+=3)+sz;if(btype==1){if(bt2>=dat.length)return;st2.b=bt2+1;if(out){fill(out,dat[bt2],st2.y,st2.y+=sz);return out}return fill(new u8(sz),dat[bt2])}if(ebt>dat.length)return;if(btype==0){st2.b=ebt;if(out){out.set(dat.subarray(bt2,ebt),st2.y);st2.y+=sz;return out}return slc(dat,bt2,ebt)}if(btype==2){var b3=dat[bt2],lbt=b3&3,sf=b3>>2&3;var lss=b3>>4,lcs=0,s4=0;if(lbt<2){if(sf&1)lss|=dat[++bt2]<<4|(sf&2&&dat[++bt2]<<12);else lss=b3>>3}else{s4=sf;if(sf<2)lss|=(dat[++bt2]&63)<<4,lcs=dat[bt2]>>6|dat[++bt2]<<2;else if(sf==2)lss|=dat[++bt2]<<4|(dat[++bt2]&3)<<12,lcs=dat[bt2]>>2|dat[++bt2]<<6;else lss|=dat[++bt2]<<4|(dat[++bt2]&63)<<12,lcs=dat[bt2]>>6|dat[++bt2]<<2|dat[++bt2]<<10}++bt2;var buf=out?out.subarray(st2.y,st2.y+st2.m):new u8(st2.m);var spl=buf.length-lss;if(lbt==0)buf.set(dat.subarray(bt2,bt2+=lss),spl);else if(lbt==1)fill(buf,dat[bt2++],spl);else{var hu=st2.h;if(lbt==2){var hud=rhu(dat,bt2);lcs+=bt2-(bt2=hud[0]);st2.h=hu=hud[1]}else if(!hu)err(0);(s4?dhu4:dhu)(dat.subarray(bt2,bt2+=lcs),buf.subarray(spl),hu)}var ns2=dat[bt2++];if(ns2){if(ns2==255)ns2=(dat[bt2++]|dat[bt2++]<<8)+32512;else if(ns2>127)ns2=ns2-128<<8|dat[bt2++];var scm=dat[bt2++];if(scm&3)err(0);var dts=[dmlt,doct,dllt];for(var i=2;i>-1;--i){var md=scm>>(i<<1)+2&3;if(md==1){var rbuf=new u8([0,0,dat[bt2++]]);dts[i]={s:rbuf.subarray(2,3),n:rbuf.subarray(0,1),t:new u16(rbuf.buffer,0,1),b:0}}else if(md==2){_a=rfse(dat,bt2,9-(i&1)),bt2=_a[0],dts[i]=_a[1]}else if(md==3){if(!st2.t)err(0);dts[i]=st2.t[i]}}var _b=st2.t=dts,mlt=_b[0],oct=_b[1],llt=_b[2];var lb=dat[ebt-1];if(!lb)err(0);var spos=(ebt<<3)-8+msb(lb)-llt.b,cbt=spos>>3,oubt=0;var lst=(dat[cbt]|dat[cbt+1]<<8)>>(spos&7)&(1<<llt.b)-1;cbt=(spos-=oct.b)>>3;var ost=(dat[cbt]|dat[cbt+1]<<8)>>(spos&7)&(1<<oct.b)-1;cbt=(spos-=mlt.b)>>3;var mst=(dat[cbt]|dat[cbt+1]<<8)>>(spos&7)&(1<<mlt.b)-1;for(++ns2;--ns2;){var llc=llt.s[lst];var lbtr=llt.n[lst];var mlc=mlt.s[mst];var mbtr=mlt.n[mst];var ofc=oct.s[ost];var obtr=oct.n[ost];cbt=(spos-=ofc)>>3;var ofp=1<<ofc;var off=ofp+((dat[cbt]|dat[cbt+1]<<8|dat[cbt+2]<<16|dat[cbt+3]<<24)>>>(spos&7)&ofp-1);cbt=(spos-=mlb[mlc])>>3;var ml=mlbl[mlc]+((dat[cbt]|dat[cbt+1]<<8|dat[cbt+2]<<16)>>(spos&7)&(1<<mlb[mlc])-1);cbt=(spos-=llb[llc])>>3;var ll=llbl[llc]+((dat[cbt]|dat[cbt+1]<<8|dat[cbt+2]<<16)>>(spos&7)&(1<<llb[llc])-1);cbt=(spos-=lbtr)>>3;lst=llt.t[lst]+((dat[cbt]|dat[cbt+1]<<8)>>(spos&7)&(1<<lbtr)-1);cbt=(spos-=mbtr)>>3;mst=mlt.t[mst]+((dat[cbt]|dat[cbt+1]<<8)>>(spos&7)&(1<<mbtr)-1);cbt=(spos-=obtr)>>3;ost=oct.t[ost]+((dat[cbt]|dat[cbt+1]<<8)>>(spos&7)&(1<<obtr)-1);if(off>3){st2.o[2]=st2.o[1];st2.o[1]=st2.o[0];st2.o[0]=off-=3}else{var idx=off-(ll!=0);if(idx){off=idx==3?st2.o[0]-1:st2.o[idx];if(idx>1)st2.o[2]=st2.o[1];st2.o[1]=st2.o[0];st2.o[0]=off}else off=st2.o[0]}for(var i=0;i<ll;++i){buf[oubt+i]=buf[spl+i]}oubt+=ll,spl+=ll;var stin=oubt-off;if(stin<0){var len=-stin;var bs2=st2.e+stin;if(len>ml)len=ml;for(var i=0;i<len;++i){buf[oubt+i]=st2.w[bs2+i]}oubt+=len,ml-=len,stin=0}for(var i=0;i<ml;++i){buf[oubt+i]=buf[stin+i]}oubt+=ml}if(oubt!=spl){while(spl<buf.length){buf[oubt++]=buf[spl++]}}else oubt=buf.length;if(out)st2.y+=oubt;else buf=slc(buf,0,oubt)}else if(out){st2.y+=lss;if(spl){for(var i=0;i<lss;++i){buf[i]=buf[spl+i]}}}else if(spl)buf=slc(buf,spl);st2.b=ebt;return buf}err(2)};var cct=function(bufs,ol){if(bufs.length==1)return bufs[0];var buf=new u8(ol);for(var i=0,b2=0;i<bufs.length;++i){var chk=bufs[i];buf.set(chk,b2);b2+=chk.length}return buf};var Decompress=(function(){function Decompress2(ondata){this.ondata=ondata;this.c=[];this.l=0;this.z=0}Decompress2.prototype.push=function(chunk,final){if(typeof this.s=="number"){var sub=Math.min(chunk.length,this.s);chunk=chunk.subarray(sub);this.s-=sub}var sl=chunk.length;var ncs=sl+this.l;if(!this.s){if(final){if(!ncs){this.ondata(new u8(0),true);return}if(ncs<5)err(5)}else if(ncs<18){this.c.push(chunk);this.l=ncs;return}if(this.l){this.c.push(chunk);chunk=cct(this.c,ncs);this.c=[];this.l=0}if(typeof(this.s=rzfh(chunk))=="number")return this.push(chunk,final)}if(typeof this.s!="number"){if(ncs<(this.z||3)){if(final)err(5);this.c.push(chunk);this.l=ncs;return}if(this.l){this.c.push(chunk);chunk=cct(this.c,ncs);this.c=[];this.l=0}if(!this.z&&ncs<(this.z=chunk[this.s.b]&2?4:3+(chunk[this.s.b]>>3|chunk[this.s.b+1]<<5|chunk[this.s.b+2]<<13))){if(final)err(5);this.c.push(chunk);this.l=ncs;return}else this.z=0;for(;;){var blk=rzb(chunk,this.s);if(!blk){if(final)err(5);var adc=chunk.subarray(this.s.b);this.s.b=0;this.c.push(adc),this.l+=adc.length;return}else{this.ondata(blk,false);cpw(this.s.w,0,blk.length);this.s.w.set(blk,this.s.w.length-blk.length)}if(this.s.l){var rest=chunk.subarray(this.s.b);this.s=this.s.c*4;this.push(rest,final);return}}}else if(final)err(5)};return Decompress2})();var ENCRYPT_MAGIC=Buffer.from("BILIENC1","utf8");var ZSTD_MAGIC=Buffer.from("BILIZSTD1","utf8");var FORMAT_VERSION=1;var MODE_RAW=0;var MODE_ZSTD=1;var NONCE_LEN=12;var TAG_LEN=16;var ENCRYPT_HEADER_LEN=ENCRYPT_MAGIC.length+2+NONCE_LEN;var MIN_ENCRYPTED_LEN=ENCRYPT_HEADER_LEN+TAG_LEN;var PLAIN_HEADER_LEN=ZSTD_MAGIC.length+2;function parseEncryptionKey(value){const v2=value.trim();let buf=null;if(/^[0-9a-fA-F]+$/.test(v2)&&v2.length%2===0){buf=Buffer.from(v2,"hex")}else if(/^[A-Za-z0-9+/]+={0,2}$/.test(v2)){buf=Buffer.from(v2,"base64")}if(!buf||buf.length!==32){const got=buf?`${buf.length} bytes`:"an undecodable value";throw new Error(`[encrypt] BILI_ENCRYPTION_KEY must be exactly 32 bytes encoded as hex (64 chars) or base64 \u2014 got ${got}`)}return buf}var zstdOverride=null;function zstdAvailable(){if(zstdOverride===false)return false;return typeof zlib.zstdCompressSync==="function"&&typeof zlib.zstdDecompressSync==="function"}function inflateZstd(body){if(zstdAvailable())return zlib.zstdDecompressSync(body);const chunks=[];new Decompress(chunk=>chunks.push(Buffer.from(chunk))).push(body,true);return Buffer.concat(chunks)}function createStorageCodec(opts={}){const key2=opts.key??null;const compress=opts.compress??false;if(!key2&&!compress)return void 0;return{encode(data){const plain=Buffer.from(data,"utf8");const useZstd=compress&&zstdAvailable();let body=plain;let mode=MODE_RAW;if(useZstd){const z2=zlib.zstdCompressSync(plain);if(z2.length<plain.length){body=z2;mode=MODE_ZSTD}}if(!key2&&mode===MODE_RAW)return plain;const header=Buffer.from([FORMAT_VERSION,mode]);if(!key2){return Buffer.concat([ZSTD_MAGIC,header,body])}const nonce=randomBytes2(NONCE_LEN);const cipher=createCipheriv("aes-256-gcm",key2,nonce);const ct2=Buffer.concat([cipher.update(body),cipher.final()]);return Buffer.concat([ENCRYPT_MAGIC,header,nonce,ct2,cipher.getAuthTag()])},decode(buf){if(buf.length>=ENCRYPT_MAGIC.length&&buf.subarray(0,ENCRYPT_MAGIC.length).equals(ENCRYPT_MAGIC)){return decryptEnvelope(buf,key2)}if(buf.length>=ZSTD_MAGIC.length&&buf.subarray(0,ZSTD_MAGIC.length).equals(ZSTD_MAGIC)){return decompressEnvelope(buf)}return buf.toString("utf8")}}}function decryptEnvelope(buf,key2){if(!key2){throw new Error("[storage] session file is BILIENC1-encrypted but no BILI_ENCRYPTION_KEY is set \u2014 cannot read it")}if(buf.length<MIN_ENCRYPTED_LEN||buf[ENCRYPT_MAGIC.length]!==FORMAT_VERSION){throw new Error(`[encrypt] unsupported session file format version ${buf[ENCRYPT_MAGIC.length]}`)}const mode=buf[ENCRYPT_MAGIC.length+1];const nonce=buf.subarray(ENCRYPT_HEADER_LEN-NONCE_LEN,ENCRYPT_HEADER_LEN);const tag=buf.subarray(buf.length-TAG_LEN);const ct2=buf.subarray(ENCRYPT_HEADER_LEN,buf.length-TAG_LEN);const decipher=createDecipheriv("aes-256-gcm",key2,nonce);decipher.setAuthTag(tag);const body=Buffer.concat([decipher.update(ct2),decipher.final()]);const plain=mode===MODE_ZSTD?inflateZstd(body):body;return plain.toString("utf8")}function decompressEnvelope(buf){if(buf.length<PLAIN_HEADER_LEN||buf[ZSTD_MAGIC.length]!==FORMAT_VERSION){throw new Error(`[storage] unsupported session file format version ${buf[ZSTD_MAGIC.length]}`)}const mode=buf[ZSTD_MAGIC.length+1];const body=buf.subarray(PLAIN_HEADER_LEN);const plain=mode===MODE_ZSTD?inflateZstd(body):body;return plain.toString("utf8")}init_logger();var LOCK_CODES=/\b(EPERM|EBUSY|EACCES)\b/;var WRITE_FAIL_RE=/^\[persist\] write failed for (.+?) \(total (\d+)x\): (.+)$/;var PersistEpermAlert=class{dir;threshold;repeatMs;platform;now;onAlert;hasAlerted=false;alertedAt=0;constructor(opts){this.dir=opts.dir;this.threshold=opts.threshold??5;this.repeatMs=opts.repeatMs??0;this.platform=opts.platform??process.platform;this.now=opts.now??Date.now;this.onAlert=opts.onAlert??((d,c)=>log("warn",buildAlertMessage(d,c)))}observe(level,msg){if(this.platform!=="win32")return false;if(level!=="error"&&level!=="warn")return false;const m2=WRITE_FAIL_RE.exec(msg);if(!m2)return false;const count=Number(m2[2]);if(count<this.threshold)return false;if(!LOCK_CODES.test(m2[3]))return false;if(!this.shouldAlert())return false;this.hasAlerted=true;this.alertedAt=this.now();this.onAlert(this.dir,count);return true}shouldAlert(){if(!this.hasAlerted)return true;if(this.repeatMs<=0)return false;return this.now()-this.alertedAt>=this.repeatMs}};function buildAlertMessage(dir,count){return[`[persist] session dir ${dir} failed ${count} consecutive writes (EPERM \u2014 rename is locked).`,"Likely cause: Windows Defender / antivirus / indexer / a sync tool is locking the directory.",`Fix: add ${dir} to Windows Defender exclusions (Settings \u2192 Virus & threat protection \u2192 Manage settings \u2192 Exclusions \u2192 Add an exclusion),`,"and make sure no OneDrive / sync tool is syncing this path."].join("\n")}init_dist();init_billing();init_state_hydration();init_dist();init_shadow();init_backend();init_ingest();init_store();init_dist();init_logger();init_paths();import{randomUUID as randomUUID2}from"crypto";import{mkdirSync as mkdirSync6,writeFileSync as writeFileSync5}from"fs";import{dirname as dirname3,join as join5}from"path";init_knobs();init_proxy_tool_result();var EFFECTIVE_CCR_KEY="effectiveCcr";function storeEffectiveCcr(session,ccr){session.metadata[EFFECTIVE_CCR_KEY]=ccr??null;if(!ccr){const carrierRefs=carrierOf(session).map(p2=>p2.ref);const ledgerRefs=readLedger(session).map(e=>e.ref);const allRefs=[...new Set([...carrierRefs,...ledgerRefs])];if(allRefs.length>0)dropRetrievals(session,allRefs,"CCR disarmed before delivery")}}function effectiveCcr(session){const meta=session?.metadata[EFFECTIVE_CCR_KEY];if(meta&&typeof meta==="object"&&typeof meta.enabled==="boolean"){return meta}return void 0}function ccrEnabled(session){return effectiveCcr(session)?.enabled===true}var EFFECTIVE_IMAGE_RESCALE_KEY="effectiveImageRescale";function storeEffectiveImageRescale(session,armed2){if(armed2===true)session.metadata[EFFECTIVE_IMAGE_RESCALE_KEY]=true;else delete session.metadata[EFFECTIVE_IMAGE_RESCALE_KEY]}function imageRescaleToolArmed(session){return session?.metadata[EFFECTIVE_IMAGE_RESCALE_KEY]===true}function retrieveToolName(session){return effectiveCcr(session)?.toolName??RETRIEVE_TOOL_NAME}function ccrLoopConfig(session,config){if(!ccrEnabled(session))return{...config,ccr:void 0};const eff=effectiveCcr(session);if(!eff)return config;return{...config,ccr:{...DEFAULT_CCR_CONFIG,...eff}}}var PLUGIN_CCR_WIRES=new Set(["anthropic","openai"]);function ccrPluginWireOk(protocol){return PLUGIN_CCR_WIRES.has(protocol)}function contentStoreOf(session){if(!session.contentStore){session.contentStore=getStore().unifiedCcrFor(session.id)??getStore().loadContentStore(session)??createContentStore()}return session.contentStore}function adoptContentStore(session,store2){const prev=session.contentStore;let prevRefs=null;if(prev){try{prevRefs=new Set(Object.keys(prev.byRef))}catch(err2){log("warn",`[ccr] lazy content store for ${session.id} could not be re-materialized during adopt (${String(err2 instanceof Error?err2.message:err2)}) \u2014 proceeding with the incoming store as the full set`)}}const added=!prev||prevRefs===null?Object.entries(store2.byRef):Object.entries(store2.byRef).filter(([ref])=>!prevRefs.has(ref));session.contentStore=store2;if(added.length===0)return;let saved=0;for(const[ref,entry]of added){const placeholder=buildStoredPlaceholder({ref,kind:entry.kind,tokens:entry.tokens,head:entry.head,retrieveToolName:retrieveToolName(session)});saved+=Math.max(0,entry.chars-Buffer.byteLength(placeholder,"utf8"))}session.stats.storedBytes=contentStoreStats(store2).totalChars;session.stats.storeBytesSaved=(session.stats.storeBytesSaved??0)+saved;session.contentStoreDirty=true}function cloneStoreForRefs(store2,refs){const wanted=new Set(refs);const byRef={};const byHash={};for(const[ref,entry]of Object.entries(store2.byRef)){if(!wanted.has(ref))continue;byRef[ref]={...entry};const text2=store2.byHash[entry.hash];if(text2!==void 0&&!(entry.hash in byHash))byHash[entry.hash]=text2}return Object.keys(byRef).length>0?{version:1,byHash,byRef}:null}function executeRetrieve(args,session){session.stats.retrieveCalls=(session.stats.retrieveCalls??0)+1;const rawRef=args.ref;const ref=typeof rawRef==="string"?rawRef.trim():"";if(!ref){session.stats.retrieveMisses=(session.stats.retrieveMisses??0)+1;return toolFail(`[${retrieveToolName(session)} FAILED: ref (an mNNNNN id) is required]`)}const result=applyRetrieve({store:contentStoreOf(session),ref,exportDir:retrievalExportDir()});if(!result.ok){session.stats.retrieveMisses=(session.stats.retrieveMisses??0)+1;log("info",`[ccr] retrieve ${ref}: miss (${result.reason})`);return toolFail(result.toolResultText)}session.stats.retrieveHits=(session.stats.retrieveHits??0)+1;session.state=noteRetrieval(session.state);recordRetrieveHit(session,ref);if(result.export!==void 0&&!writeRetrievalExport(result.export)){return toolFail(`[${retrieveToolName(session)} FAILED: could not write ${result.export.path} \u2014 head preview follows]
|
|
897
|
+
`)}catch{}}init_logger();init_version();import http from"http";var PERMISSION_DENIED_SIGNATURE=/\b(?:EPERM|EACCES|EROFS|EBUSY)\b|operation not permitted|permission denied|read-only file system|readonly database/i;var BILI_DATA_PATH_SIGNATURE=/billion-context|combined-ca\.pem|index\.db|\.local[\\/](?:share|state)[\\/]/i;function classifyStartupFailure(sample){if(!PERMISSION_DENIED_SIGNATURE.test(sample)||!BILI_DATA_PATH_SIGNATURE.test(sample))return"";return"possible cause: the proxy could not write its own data files (EPERM/EACCES/read-only on the bili data dir) \u2014 most often antivirus (e.g. Windows Defender Controlled Folder Access) blocking the node runtime, a read-only flag or ACL on the directory, or another process holding the files; add the bili data dir and the node runtime to AV exclusions (see #367) or fix the directory permissions, then retry"}var MAX_HOLD_MS=10*6e4;init_update();init_win_cmd();init_client_config();init_config();init_registry();init_config();init_logger();var BILI_HOP_HEADER="x-bili-hop";function parseLauncherModelWindows(raw){if(!raw)return{};try{const parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return{};const out={};for(const[id,v2]of Object.entries(parsed)){if(typeof v2==="number"&&Number.isFinite(v2)&&v2>0)out[id]=Math.floor(v2)}return out}catch{return{}}}var LAUNCHER_MODEL_WINDOWS=parseLauncherModelWindows(process.env.BILI_LAUNCHER_MODEL_WINDOWS);function parseLauncherModelMaxOutputs(raw){if(!raw)return{};try{const parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return{};const out={};for(const[id,v2]of Object.entries(parsed)){if(typeof v2==="number"&&Number.isFinite(v2)&&v2>0)out[id]=Math.floor(v2)}return out}catch{return{}}}var LAUNCHER_MODEL_MAX_OUTPUTS=parseLauncherModelMaxOutputs(process.env.BILI_LAUNCHER_MODEL_MAX_OUTPUTS);function launcherMaxOutput(model){return LAUNCHER_MODEL_MAX_OUTPUTS[model]}function launcherContextWindow(model){return LAUNCHER_MODEL_WINDOWS[model]}var windowSourceLogged=new Set;var MAX_ANTHROPIC_BETA_WINDOW=1e7;function anthropicBetaContextWindow(headers){const raw=headers["anthropic-beta"];if(raw===void 0)return void 0;const list=Array.isArray(raw)?raw.join(","):raw;let best;for(const part of list.split(",")){const m2=/^context-(\d+)m\b/.exec(part.trim().toLowerCase());if(!m2)continue;const n=Number.parseInt(m2[1],10);if(!Number.isFinite(n)||n<=0)continue;const w2=Math.min(n*1e6,MAX_ANTHROPIC_BETA_WINDOW);if(best===void 0||w2>best)best=w2}return best}function expandedContextSuffixWindow(model){if(!model)return void 0;const m2=/\[(\d+)m\]$/i.exec(model.trim());if(!m2)return void 0;const n=Number.parseInt(m2[1],10);if(!Number.isFinite(n)||n<=0)return void 0;return Math.min(n*1e6,MAX_ANTHROPIC_BETA_WINDOW)}var registryWindowCappedLogged=new Set;function capRegistryWindowByStandard(model,registryWindow,hasTierEvidence){if(registryWindow===void 0||hasTierEvidence)return registryWindow;const std=tierGatedStandardWindow(model);if(std===void 0||registryWindow<=std)return registryWindow;if(!registryWindowCappedLogged.has(model)){registryWindowCappedLogged.add(model);log("info",`[window] registry advertises ${registryWindow} for ${model} but the request carries no tier evidence (context-Nm beta header / [Nm] suffix) \u2014 capping at the built-in standard ${std} (#1321)`)}return std}init_vertex();init_client_config();init_dist();init_logger();import{createHash as createHash15}from"crypto";import{createHash as createHash14,randomUUID as randomUUID4}from"crypto";import{closeSync,existsSync as existsSync7,fsyncSync,mkdirSync as mkdirSync7,openSync,readdirSync as readdirSync2,readFileSync as readFileSync9,renameSync as renameSync2,rmSync,statSync as statSync6,writeFileSync as writeFileSync6}from"fs";import{readdir as readdir2,readFile as readFile4,rm as rm2}from"fs/promises";import*as path25 from"path";import{createHash as createHash7}from"crypto";import fs13 from"fs";import fsp from"fs/promises";import path22 from"path";var StateStore=class{enabled;dir;version;debounceMs;log;legacyFn;relPathFn;validateFn;foreignFileFn;codec;retryAttempts;retryBaseMs;retryMaxMs;timers=new Map;pending=new Map;writeChains=new Map;discovered=new Map;commitSeq=new Map;failCounts=new Map;tmpSeq=0;constructor(opts){this.dir=opts.dir;this.version=opts.version;this.debounceMs=opts.debounceMs??500;this.enabled=opts.enabled??true;this.log=opts.log??((_level,_msg)=>{});this.relPathFn=opts.relPath;this.legacyFn=opts.legacy;this.validateFn=opts.validate??defaultValidate;this.foreignFileFn=opts.foreignFile;this.codec=opts.codec;this.retryAttempts=Math.max(1,opts.retryAttempts??6);this.retryBaseMs=Math.max(1,opts.retryBaseMs??50);this.retryMaxMs=Math.max(this.retryBaseMs,opts.retryMaxMs??1600)}scheduleSave(id,build2){if(!this.enabled)return;this.pending.set(id,build2);const existing=this.timers.get(id);if(existing)return;const timer3=setTimeout(()=>{this.timers.delete(id);const builder=this.pending.get(id);this.pending.delete(id);if(!builder)return;void this.writeNow(id,builder).catch(()=>{})},this.debounceMs);timer3.unref?.();this.timers.set(id,timer3)}async writeNow(id,build2){if(!this.enabled)return;const prev=this.writeChains.get(id)??Promise.resolve();const next=prev.catch(()=>{}).then(()=>this.writeInner(id,build2));this.writeChains.set(id,next);next.finally(()=>{if(this.writeChains.get(id)===next)this.writeChains.delete(id)}).catch(()=>{});return next}flushSync(id,build2){if(!this.enabled)return true;const timer3=this.timers.get(id);if(timer3){clearTimeout(timer3);this.timers.delete(id);this.pending.delete(id)}let payload;try{payload=build2()}catch(e){this.log("error",`[persist] builder failed for ${id}: ${errText(e)}`);return false}const file=this.resolvePath(id,payload);const data=this.serialize(id,payload);let lastErr;for(let attempt=0;attempt<this.retryAttempts;attempt++){const tmp=this.tempPath(file);try{fs13.mkdirSync(path22.dirname(file),{recursive:true});this.atomicWriteDurable(tmp,data);fs13.renameSync(tmp,file);lastErr=void 0;break}catch(e){lastErr=e;try{fs13.unlinkSync(tmp)}catch{}if(!isTransientFsError(e)||attempt===this.retryAttempts-1)break;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,this.backoffMs(attempt))}}if(!lastErr){this.discovered.set(id,file);this.clearFailure(id);this.bumpCommit(id);this.removeSpillSync(file);return true}const spill=this.spillPathFor(file);let spillPath=null;for(let attempt=0;attempt<this.retryAttempts&&spillPath===null;attempt++){try{fs13.mkdirSync(path22.dirname(spill),{recursive:true});this.atomicWriteDurable(spill,data);spillPath=spill}catch(e){if(!isTransientFsError(e)||attempt===this.retryAttempts-1)break;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,this.backoffMs(attempt))}}if(spillPath)this.discovered.set(id,spillPath);if(spillPath)this.bumpCommit(id);this.recordFailure(id,lastErr,spillPath);return spillPath!==null}loadSync(id,hint){if(!this.enabled)return null;const candidates=[this.discovered.get(id),hint?path22.join(this.dir,hint):void 0,path22.join(this.dir,flatFileNameFor(id))];for(const file of candidates){if(!file)continue;const envelope=this.readEnvelope(file);if(envelope&&envelope.id===id)return envelope}return null}async loadAll(){const out=new Map;if(!this.enabled)return out;const files=await this.walkJsonFiles(this.dir);for(const file of files){if(this.foreignFileFn?.(file))continue;const envelope=this.readEnvelope(file);if(!envelope)continue;const base=path22.basename(file);const relBase=path22.basename(this.relPathOf(envelope.id,envelope.payload));const flatBase=flatFileNameFor(envelope.id);let owner=null;if(base===relBase||base===flatBase){owner=envelope.id}else if(base.endsWith(".fb.json")){const canonicalBase=`${base.slice(0,-".fb.json".length)}.json`;if(canonicalBase===relBase||canonicalBase===flatBase){owner=envelope.id}}if(owner===null){this.log("warn",`[persist] skipping ${rel(file,this.dir)}: filename does not match record id`);continue}const existing=out.get(owner);if(!existing||envelope.savedAt>=existing.savedAt){out.set(owner,envelope);this.discovered.set(owner,file)}}return out}hasPending(id){return this.timers.has(id)}pendingIds(){return[...this.timers.keys()]}async flushAll(){const ids=this.pendingIds();for(const timer3 of this.timers.values())clearTimeout(timer3);this.timers.clear();const builders=new Map;for(const id of ids){const build2=this.pending.get(id);if(build2)builders.set(id,build2);this.pending.delete(id)}await Promise.all([...builders.entries()].map(([id,build2])=>this.writeNow(id,build2).catch(e=>{this.log("error",`[persist] shutdown flush failed for ${id}: ${errText(e)}`)})));await Promise.allSettled([...this.writeChains.values()])}cancelAll(){for(const timer3 of this.timers.values())clearTimeout(timer3);this.timers.clear();this.pending.clear()}async writeInner(id,build2){const baseSeq=this.commitSeq.get(id)??0;let payload;try{payload=build2()}catch(e){this.log("error",`[persist] builder failed for ${id}: ${errText(e)}`);throw e}const file=this.resolvePath(id,payload);const data=this.serialize(id,payload);let lastErr;for(let attempt=0;attempt<this.retryAttempts;attempt++){const tmp=this.tempPath(file);try{await fsp.mkdir(path22.dirname(file),{recursive:true});await fsp.writeFile(tmp,data);this.fsyncFile(tmp);if((this.commitSeq.get(id)??0)!==baseSeq){await fsp.unlink(tmp).catch(()=>{});return}try{fs13.renameSync(tmp,file)}catch(e){lastErr=e;await fsp.unlink(tmp).catch(()=>{});if(!isTransientFsError(e)||attempt===this.retryAttempts-1)break;const{promise,resolve:resolve2}=Promise.withResolvers();setTimeout(resolve2,this.backoffMs(attempt));await promise;continue}this.discovered.set(id,file);this.clearFailure(id);this.commitSeq.set(id,baseSeq+1);await this.removeSpill(file);return}catch(e){lastErr=e;await fsp.unlink(tmp).catch(()=>{});if(!isTransientFsError(e)||attempt===this.retryAttempts-1)break;const{promise,resolve:resolve2}=Promise.withResolvers();setTimeout(resolve2,this.backoffMs(attempt));await promise}}if((this.commitSeq.get(id)??0)!==baseSeq)return;const spill=this.spillPathFor(file);let spillPath=null;for(let attempt=0;attempt<this.retryAttempts&&spillPath===null;attempt++){try{await fsp.mkdir(path22.dirname(spill),{recursive:true});if((this.commitSeq.get(id)??0)!==baseSeq)return;this.atomicWriteDurable(spill,data);spillPath=spill}catch(e){if(!isTransientFsError(e)||attempt===this.retryAttempts-1)break;const{promise,resolve:resolve2}=Promise.withResolvers();setTimeout(resolve2,this.backoffMs(attempt));await promise}}if(spillPath){this.discovered.set(id,spillPath);this.commitSeq.set(id,baseSeq+1)}this.recordFailure(id,lastErr,spillPath);throw lastErr}envelope(id,payload){return{version:this.version,savedAt:Date.now(),id,payload}}serialize(id,payload){const json=JSON.stringify(this.envelope(id,payload));return this.codec?this.codec.encode(json):json}resolvePath(id,payload){return path22.join(this.dir,this.relPathOf(id,payload))}relPathOf(id,payload){const custom=this.relPathFn?.(id,payload);if(!custom)return flatFileNameFor(id);const rel2=path22.normalize(custom);if(path22.isAbsolute(rel2)||rel2.split(/[\\/]+/).includes("..")){this.log("warn",`[persist] relPath for ${id} escapes dir; using flat name`);return flatFileNameFor(id)}return rel2}tempPath(dest){const seq=this.tmpSeq++;return path22.join(path22.dirname(dest),`.tmp-${path22.basename(dest,".json")}-${process.pid}-${seq}`)}atomicWriteDurable(file,data){const fd=fs13.openSync(file,"w");try{fs13.writeFileSync(fd,data);fs13.fsyncSync(fd)}finally{fs13.closeSync(fd)}}fsyncFile(file){const fd=fs13.openSync(file,"r+");try{fs13.fsyncSync(fd)}finally{fs13.closeSync(fd)}}backoffMs(attempt){return Math.min(this.retryBaseMs*2**attempt,this.retryMaxMs)}spillPathFor(file){const base=path22.basename(file);const dot=base.lastIndexOf(".");const stem2=dot>0?base.slice(0,dot):base;const ext=dot>0?base.slice(dot):".json";return path22.join(path22.dirname(file),`${stem2}.fb${ext}`)}async removeSpill(file){await fsp.unlink(this.spillPathFor(file)).catch(()=>{})}bumpCommit(id){this.commitSeq.set(id,(this.commitSeq.get(id)??0)+1)}removeSpillSync(file){try{fs13.unlinkSync(this.spillPathFor(file))}catch{}}recordFailure(id,err2,spillPath){const count=(this.failCounts.get(id)??0)+1;this.failCounts.set(id,count);const alertAt=count===1||count>=2&&(count&count-1)===0;if(!alertAt)return;const where=spillPath?`; data spilled to ${rel(spillPath,this.dir)}`:"; SPILLOVER ALSO FAILED \u2014 data at risk";this.log(count===1?"error":"warn",`[persist] write failed for ${id} (total ${count}x): ${errText(err2)}${where}`)}clearFailure(id){this.failCounts.delete(id)}readEnvelope(file){let parsed;try{const buf=fs13.readFileSync(file);const text2=this.codec?this.codec.decode(buf):buf.toString("utf8");parsed=JSON.parse(text2)}catch(e){if(e.code!=="ENOENT"){this.log("warn",`[persist] skipping corrupt file ${rel(file,this.dir)}: ${errText(e)}`)}return null}if(isEnvelopeLike(parsed)){if(!this.validateFn(parsed)){this.log("warn",`[persist] skipping invalid record ${rel(file,this.dir)}`);return null}return parsed}const adopted=this.adoptLegacy(parsed);if(adopted)return adopted;this.log("warn",`[persist] skipping invalid record ${rel(file,this.dir)}`);return null}adoptLegacy(parsed){const adoption=this.legacyFn?this.legacyFn(parsed):null;if(!adoption||typeof adoption.id!=="string"||adoption.id.length===0||adoption.payload==null){return null}const source=parsed;const envelope={version:adoption.version??source.version??this.version,savedAt:adoption.savedAt??source.savedAt??0,id:adoption.id,payload:adoption.payload};if(!this.validateFn(envelope))return null;return envelope}async walkJsonFiles(root){const out=[];const queue=[root];while(queue.length>0){const dir=queue.pop();let dirents;try{dirents=await fsp.readdir(dir,{withFileTypes:true})}catch{continue}for(const d of dirents){if(d.name.startsWith(".tmp-"))continue;const full=path22.join(dir,d.name);if(d.isDirectory())queue.push(full);else if(d.isFile()&&d.name.endsWith(".json"))out.push(full)}}return out}};function defaultValidate(envelope){return typeof envelope.id==="string"&&envelope.id.length>0&&envelope.payload!=null}function isEnvelopeLike(value){if(!value||typeof value!=="object")return false;const v2=value;return typeof v2.id==="string"&&"payload"in v2}function flatFileNameFor(id){return createHash7("sha256").update(id,"utf8").digest("hex").slice(0,24)+".json"}function isTransientFsError(e){const code=e.code;return code==="EPERM"||code==="EBUSY"||code==="EACCES"||code==="ENOENT"||code==="ENOTDIR"}function errText(e){return e instanceof Error?e.message:String(e)}function rel(p2,base){const r=path22.relative(base,p2);return r&&!r.startsWith("..")?r:p2}init_paths();init_knobs();init_logger();init_runtime_status();init_version();import{createCipheriv,createDecipheriv,randomBytes as randomBytes2}from"crypto";import*as zlib from"zlib";var ab=ArrayBuffer;var u8=Uint8Array;var u16=Uint16Array;var i16=Int16Array;var i32=Int32Array;var slc=function(v2,s3,e){if(u8.prototype.slice)return u8.prototype.slice.call(v2,s3,e);if(s3==null||s3<0)s3=0;if(e==null||e>v2.length)e=v2.length;var n=new u8(e-s3);n.set(v2.subarray(s3,e));return n};var fill=function(v2,n,s3,e){if(u8.prototype.fill)return u8.prototype.fill.call(v2,n,s3,e);if(s3==null||s3<0)s3=0;if(e==null||e>v2.length)e=v2.length;for(;s3<e;++s3)v2[s3]=n;return v2};var cpw=function(v2,t,s3,e){if(u8.prototype.copyWithin)return u8.prototype.copyWithin.call(v2,t,s3,e);if(s3==null||s3<0)s3=0;if(e==null||e>v2.length)e=v2.length;while(s3<e){v2[t++]=v2[s3++]}};var ec=["invalid zstd data","window size too large (>2046MB)","invalid block type","FSE accuracy too high","match distance too far back","unexpected EOF"];var err=function(ind,msg,nt2){var e=new Error(msg||ec[ind]);e.code=ind;if(Error.captureStackTrace)Error.captureStackTrace(e,err);if(!nt2)throw e;return e};var rb=function(d,b2,n){var i=0,o=0;for(;i<n;++i)o|=d[b2++]<<(i<<3);return o};var b4=function(d,b2){return(d[b2]|d[b2+1]<<8|d[b2+2]<<16|d[b2+3]<<24)>>>0};var rzfh=function(dat,w2){var n3=dat[0]|dat[1]<<8|dat[2]<<16;if(n3==3126568&&dat[3]==253){var flg=dat[4];var ss2=flg>>5&1,cc=flg>>2&1,df=flg&3,fcf=flg>>6;if(flg&8)err(0);var bt2=6-ss2;var db=df==3?4:df;var di2=rb(dat,bt2,db);bt2+=db;var fsb=fcf?1<<fcf:ss2;var fss=rb(dat,bt2,fsb)+(fcf==1&&256);var ws2=fss;if(!ss2){var wb=1<<10+(dat[5]>>3);ws2=wb+(wb>>3)*(dat[5]&7)}if(ws2>2145386496)err(1);var buf=new u8((w2==1?fss||ws2:w2?0:ws2)+12);buf[0]=1,buf[4]=4,buf[8]=8;return{b:bt2+fsb,y:0,l:0,d:di2,w:w2&&w2!=1?w2:buf.subarray(12),e:ws2,o:new i32(buf.buffer,0,3),u:fss,c:cc,m:Math.min(131072,ws2)}}else if((n3>>4|dat[3]<<20)==25481893){return b4(dat,4)+8}err(0)};var msb=function(val){var bits=0;for(;1<<bits<=val;++bits);return bits-1};var rfse=function(dat,bt2,mal){var tpos=(bt2<<3)+4;var al=(dat[bt2]&15)+5;if(al>mal)err(3);var sz=1<<al;var probs=sz,sym=-1,re2=-1,i=-1,ht2=sz;var buf=new ab(512+(sz<<2));var freq=new i16(buf,0,256);var dstate=new u16(buf,0,256);var nstate=new u16(buf,512,sz);var bb1=512+(sz<<1);var syms=new u8(buf,bb1,sz);var nbits=new u8(buf,bb1+sz);while(sym<255&&probs>0){var bits=msb(probs+1);var cbt=tpos>>3;var msk=(1<<bits+1)-1;var val=(dat[cbt]|dat[cbt+1]<<8|dat[cbt+2]<<16)>>(tpos&7)&msk;var msk1fb=(1<<bits)-1;var msv=msk-probs-1;var sval=val&msk1fb;if(sval<msv)tpos+=bits,val=sval;else{tpos+=bits+1;if(val>msk1fb)val-=msv}freq[++sym]=--val;if(val==-1){probs+=val;syms[--ht2]=sym}else probs-=val;if(!val){do{var rbt=tpos>>3;re2=(dat[rbt]|dat[rbt+1]<<8)>>(tpos&7)&3;tpos+=2;sym+=re2}while(re2==3)}}if(sym>255||probs)err(0);var sympos=0;var sstep=(sz>>1)+(sz>>3)+3;var smask=sz-1;for(var s3=0;s3<=sym;++s3){var sf=freq[s3];if(sf<1){dstate[s3]=-sf;continue}for(i=0;i<sf;++i){syms[sympos]=s3;do{sympos=sympos+sstep&smask}while(sympos>=ht2)}}if(sympos)err(0);for(i=0;i<sz;++i){var ns2=dstate[syms[i]]++;var nb=nbits[i]=al-msb(ns2);nstate[i]=(ns2<<nb)-sz}return[tpos+7>>3,{b:al,s:syms,n:nbits,t:nstate}]};var rhu=function(dat,bt2){var i=0,wc=-1;var buf=new u8(292),hb=dat[bt2];var hw=buf.subarray(0,256);var rc=buf.subarray(256,268);var ri2=new u16(buf.buffer,268);if(hb<128){var _a=rfse(dat,bt2+1,6),ebt=_a[0],fdt=_a[1];bt2+=hb;var epos=ebt<<3;var lb=dat[bt2];if(!lb)err(0);var st1=0,st2=0,btr1=fdt.b,btr2=btr1;var fpos=(++bt2<<3)-8+msb(lb);for(;;){fpos-=btr1;if(fpos<epos)break;var cbt=fpos>>3;st1+=(dat[cbt]|dat[cbt+1]<<8)>>(fpos&7)&(1<<btr1)-1;hw[++wc]=fdt.s[st1];fpos-=btr2;if(fpos<epos)break;cbt=fpos>>3;st2+=(dat[cbt]|dat[cbt+1]<<8)>>(fpos&7)&(1<<btr2)-1;hw[++wc]=fdt.s[st2];btr1=fdt.n[st1];st1=fdt.t[st1];btr2=fdt.n[st2];st2=fdt.t[st2]}if(++wc>255)err(0)}else{wc=hb-127;for(;i<wc;i+=2){var byte=dat[++bt2];hw[i]=byte>>4;hw[i+1]=byte&15}++bt2}var wes=0;for(i=0;i<wc;++i){var wt2=hw[i];if(wt2>11)err(0);wes+=wt2&&1<<wt2-1}var mb=msb(wes)+1;var ts2=1<<mb;var rem=ts2-wes;if(rem&rem-1)err(0);hw[wc++]=msb(rem)+1;for(i=0;i<wc;++i){var wt2=hw[i];++rc[hw[i]=wt2&&mb+1-wt2]}var hbuf=new u8(ts2<<1);var syms=hbuf.subarray(0,ts2),nb=hbuf.subarray(ts2);ri2[mb]=0;for(i=mb;i>0;--i){var pv=ri2[i];fill(nb,i,pv,ri2[i-1]=pv+rc[i]*(1<<mb-i))}if(ri2[0]!=ts2)err(0);for(i=0;i<wc;++i){var bits=hw[i];if(bits){var code=ri2[bits];fill(syms,i,code,ri2[bits]=code+(1<<mb-bits))}}return[bt2,{n:nb,b:mb,s:syms}]};var dllt=rfse(new u8([81,16,99,140,49,198,24,99,12,33,196,24,99,102,102,134,70,146,4]),0,6)[1];var dmlt=rfse(new u8([33,20,196,24,99,140,33,132,16,66,8,33,132,16,66,8,33,68,68,68,68,68,68,68,68,36,9]),0,6)[1];var doct=rfse(new u8([32,132,16,66,102,70,68,68,68,68,36,73,2]),0,5)[1];var b2bl=function(b2,s3){var len=b2.length,bl=new i32(len);for(var i=0;i<len;++i){bl[i]=s3;s3+=1<<b2[i]}return bl};var llb=new u8(new i32([0,0,0,0,16843009,50528770,134678020,202050057,269422093]).buffer,0,36);var llbl=b2bl(llb,0);var mlb=new u8(new i32([0,0,0,0,0,0,0,0,16843009,50528770,117769220,185207048,252579084,16]).buffer,0,53);var mlbl=b2bl(mlb,3);var dhu=function(dat,out,hu){var len=dat.length,ss2=out.length,lb=dat[len-1],msk=(1<<hu.b)-1,eb=-hu.b;if(!lb)err(0);var st2=0,btr=hu.b,pos=(len<<3)-8+msb(lb)-btr,i=-1;for(;pos>eb&&i<ss2;){var cbt=pos>>3;var val=(dat[cbt]|dat[cbt+1]<<8|dat[cbt+2]<<16)>>(pos&7);st2=(st2<<btr|val)&msk;out[++i]=hu.s[st2];pos-=btr=hu.n[st2]}if(pos!=eb||i+1!=ss2)err(0)};var dhu4=function(dat,out,hu){var bt2=6;var ss2=out.length,sz1=ss2+3>>2,sz2=sz1<<1,sz3=sz1+sz2;dhu(dat.subarray(bt2,bt2+=dat[0]|dat[1]<<8),out.subarray(0,sz1),hu);dhu(dat.subarray(bt2,bt2+=dat[2]|dat[3]<<8),out.subarray(sz1,sz2),hu);dhu(dat.subarray(bt2,bt2+=dat[4]|dat[5]<<8),out.subarray(sz2,sz3),hu);dhu(dat.subarray(bt2),out.subarray(sz3),hu)};var rzb=function(dat,st2,out){var _a;var bt2=st2.b;var b0=dat[bt2],btype=b0>>1&3;st2.l=b0&1;var sz=b0>>3|dat[bt2+1]<<5|dat[bt2+2]<<13;var ebt=(bt2+=3)+sz;if(btype==1){if(bt2>=dat.length)return;st2.b=bt2+1;if(out){fill(out,dat[bt2],st2.y,st2.y+=sz);return out}return fill(new u8(sz),dat[bt2])}if(ebt>dat.length)return;if(btype==0){st2.b=ebt;if(out){out.set(dat.subarray(bt2,ebt),st2.y);st2.y+=sz;return out}return slc(dat,bt2,ebt)}if(btype==2){var b3=dat[bt2],lbt=b3&3,sf=b3>>2&3;var lss=b3>>4,lcs=0,s4=0;if(lbt<2){if(sf&1)lss|=dat[++bt2]<<4|(sf&2&&dat[++bt2]<<12);else lss=b3>>3}else{s4=sf;if(sf<2)lss|=(dat[++bt2]&63)<<4,lcs=dat[bt2]>>6|dat[++bt2]<<2;else if(sf==2)lss|=dat[++bt2]<<4|(dat[++bt2]&3)<<12,lcs=dat[bt2]>>2|dat[++bt2]<<6;else lss|=dat[++bt2]<<4|(dat[++bt2]&63)<<12,lcs=dat[bt2]>>6|dat[++bt2]<<2|dat[++bt2]<<10}++bt2;var buf=out?out.subarray(st2.y,st2.y+st2.m):new u8(st2.m);var spl=buf.length-lss;if(lbt==0)buf.set(dat.subarray(bt2,bt2+=lss),spl);else if(lbt==1)fill(buf,dat[bt2++],spl);else{var hu=st2.h;if(lbt==2){var hud=rhu(dat,bt2);lcs+=bt2-(bt2=hud[0]);st2.h=hu=hud[1]}else if(!hu)err(0);(s4?dhu4:dhu)(dat.subarray(bt2,bt2+=lcs),buf.subarray(spl),hu)}var ns2=dat[bt2++];if(ns2){if(ns2==255)ns2=(dat[bt2++]|dat[bt2++]<<8)+32512;else if(ns2>127)ns2=ns2-128<<8|dat[bt2++];var scm=dat[bt2++];if(scm&3)err(0);var dts=[dmlt,doct,dllt];for(var i=2;i>-1;--i){var md=scm>>(i<<1)+2&3;if(md==1){var rbuf=new u8([0,0,dat[bt2++]]);dts[i]={s:rbuf.subarray(2,3),n:rbuf.subarray(0,1),t:new u16(rbuf.buffer,0,1),b:0}}else if(md==2){_a=rfse(dat,bt2,9-(i&1)),bt2=_a[0],dts[i]=_a[1]}else if(md==3){if(!st2.t)err(0);dts[i]=st2.t[i]}}var _b=st2.t=dts,mlt=_b[0],oct=_b[1],llt=_b[2];var lb=dat[ebt-1];if(!lb)err(0);var spos=(ebt<<3)-8+msb(lb)-llt.b,cbt=spos>>3,oubt=0;var lst=(dat[cbt]|dat[cbt+1]<<8)>>(spos&7)&(1<<llt.b)-1;cbt=(spos-=oct.b)>>3;var ost=(dat[cbt]|dat[cbt+1]<<8)>>(spos&7)&(1<<oct.b)-1;cbt=(spos-=mlt.b)>>3;var mst=(dat[cbt]|dat[cbt+1]<<8)>>(spos&7)&(1<<mlt.b)-1;for(++ns2;--ns2;){var llc=llt.s[lst];var lbtr=llt.n[lst];var mlc=mlt.s[mst];var mbtr=mlt.n[mst];var ofc=oct.s[ost];var obtr=oct.n[ost];cbt=(spos-=ofc)>>3;var ofp=1<<ofc;var off=ofp+((dat[cbt]|dat[cbt+1]<<8|dat[cbt+2]<<16|dat[cbt+3]<<24)>>>(spos&7)&ofp-1);cbt=(spos-=mlb[mlc])>>3;var ml=mlbl[mlc]+((dat[cbt]|dat[cbt+1]<<8|dat[cbt+2]<<16)>>(spos&7)&(1<<mlb[mlc])-1);cbt=(spos-=llb[llc])>>3;var ll=llbl[llc]+((dat[cbt]|dat[cbt+1]<<8|dat[cbt+2]<<16)>>(spos&7)&(1<<llb[llc])-1);cbt=(spos-=lbtr)>>3;lst=llt.t[lst]+((dat[cbt]|dat[cbt+1]<<8)>>(spos&7)&(1<<lbtr)-1);cbt=(spos-=mbtr)>>3;mst=mlt.t[mst]+((dat[cbt]|dat[cbt+1]<<8)>>(spos&7)&(1<<mbtr)-1);cbt=(spos-=obtr)>>3;ost=oct.t[ost]+((dat[cbt]|dat[cbt+1]<<8)>>(spos&7)&(1<<obtr)-1);if(off>3){st2.o[2]=st2.o[1];st2.o[1]=st2.o[0];st2.o[0]=off-=3}else{var idx=off-(ll!=0);if(idx){off=idx==3?st2.o[0]-1:st2.o[idx];if(idx>1)st2.o[2]=st2.o[1];st2.o[1]=st2.o[0];st2.o[0]=off}else off=st2.o[0]}for(var i=0;i<ll;++i){buf[oubt+i]=buf[spl+i]}oubt+=ll,spl+=ll;var stin=oubt-off;if(stin<0){var len=-stin;var bs2=st2.e+stin;if(len>ml)len=ml;for(var i=0;i<len;++i){buf[oubt+i]=st2.w[bs2+i]}oubt+=len,ml-=len,stin=0}for(var i=0;i<ml;++i){buf[oubt+i]=buf[stin+i]}oubt+=ml}if(oubt!=spl){while(spl<buf.length){buf[oubt++]=buf[spl++]}}else oubt=buf.length;if(out)st2.y+=oubt;else buf=slc(buf,0,oubt)}else if(out){st2.y+=lss;if(spl){for(var i=0;i<lss;++i){buf[i]=buf[spl+i]}}}else if(spl)buf=slc(buf,spl);st2.b=ebt;return buf}err(2)};var cct=function(bufs,ol){if(bufs.length==1)return bufs[0];var buf=new u8(ol);for(var i=0,b2=0;i<bufs.length;++i){var chk=bufs[i];buf.set(chk,b2);b2+=chk.length}return buf};var Decompress=(function(){function Decompress2(ondata){this.ondata=ondata;this.c=[];this.l=0;this.z=0}Decompress2.prototype.push=function(chunk,final){if(typeof this.s=="number"){var sub=Math.min(chunk.length,this.s);chunk=chunk.subarray(sub);this.s-=sub}var sl=chunk.length;var ncs=sl+this.l;if(!this.s){if(final){if(!ncs){this.ondata(new u8(0),true);return}if(ncs<5)err(5)}else if(ncs<18){this.c.push(chunk);this.l=ncs;return}if(this.l){this.c.push(chunk);chunk=cct(this.c,ncs);this.c=[];this.l=0}if(typeof(this.s=rzfh(chunk))=="number")return this.push(chunk,final)}if(typeof this.s!="number"){if(ncs<(this.z||3)){if(final)err(5);this.c.push(chunk);this.l=ncs;return}if(this.l){this.c.push(chunk);chunk=cct(this.c,ncs);this.c=[];this.l=0}if(!this.z&&ncs<(this.z=chunk[this.s.b]&2?4:3+(chunk[this.s.b]>>3|chunk[this.s.b+1]<<5|chunk[this.s.b+2]<<13))){if(final)err(5);this.c.push(chunk);this.l=ncs;return}else this.z=0;for(;;){var blk=rzb(chunk,this.s);if(!blk){if(final)err(5);var adc=chunk.subarray(this.s.b);this.s.b=0;this.c.push(adc),this.l+=adc.length;return}else{this.ondata(blk,false);cpw(this.s.w,0,blk.length);this.s.w.set(blk,this.s.w.length-blk.length)}if(this.s.l){var rest=chunk.subarray(this.s.b);this.s=this.s.c*4;this.push(rest,final);return}}}else if(final)err(5)};return Decompress2})();var ENCRYPT_MAGIC=Buffer.from("BILIENC1","utf8");var ZSTD_MAGIC=Buffer.from("BILIZSTD1","utf8");var FORMAT_VERSION=1;var MODE_RAW=0;var MODE_ZSTD=1;var NONCE_LEN=12;var TAG_LEN=16;var ENCRYPT_HEADER_LEN=ENCRYPT_MAGIC.length+2+NONCE_LEN;var MIN_ENCRYPTED_LEN=ENCRYPT_HEADER_LEN+TAG_LEN;var PLAIN_HEADER_LEN=ZSTD_MAGIC.length+2;function parseEncryptionKey(value){const v2=value.trim();let buf=null;if(/^[0-9a-fA-F]+$/.test(v2)&&v2.length%2===0){buf=Buffer.from(v2,"hex")}else if(/^[A-Za-z0-9+/]+={0,2}$/.test(v2)){buf=Buffer.from(v2,"base64")}if(!buf||buf.length!==32){const got=buf?`${buf.length} bytes`:"an undecodable value";throw new Error(`[encrypt] BILI_ENCRYPTION_KEY must be exactly 32 bytes encoded as hex (64 chars) or base64 \u2014 got ${got}`)}return buf}var zstdOverride=null;function zstdAvailable(){if(zstdOverride===false)return false;return typeof zlib.zstdCompressSync==="function"&&typeof zlib.zstdDecompressSync==="function"}function inflateZstd(body){if(zstdAvailable())return zlib.zstdDecompressSync(body);const chunks=[];new Decompress(chunk=>chunks.push(Buffer.from(chunk))).push(body,true);return Buffer.concat(chunks)}function createStorageCodec(opts={}){const key2=opts.key??null;const compress=opts.compress??false;if(!key2&&!compress)return void 0;return{encode(data){const plain=Buffer.from(data,"utf8");const useZstd=compress&&zstdAvailable();let body=plain;let mode=MODE_RAW;if(useZstd){const z2=zlib.zstdCompressSync(plain);if(z2.length<plain.length){body=z2;mode=MODE_ZSTD}}if(!key2&&mode===MODE_RAW)return plain;const header=Buffer.from([FORMAT_VERSION,mode]);if(!key2){return Buffer.concat([ZSTD_MAGIC,header,body])}const nonce=randomBytes2(NONCE_LEN);const cipher=createCipheriv("aes-256-gcm",key2,nonce);const ct2=Buffer.concat([cipher.update(body),cipher.final()]);return Buffer.concat([ENCRYPT_MAGIC,header,nonce,ct2,cipher.getAuthTag()])},decode(buf){if(buf.length>=ENCRYPT_MAGIC.length&&buf.subarray(0,ENCRYPT_MAGIC.length).equals(ENCRYPT_MAGIC)){return decryptEnvelope(buf,key2)}if(buf.length>=ZSTD_MAGIC.length&&buf.subarray(0,ZSTD_MAGIC.length).equals(ZSTD_MAGIC)){return decompressEnvelope(buf)}return buf.toString("utf8")}}}function decryptEnvelope(buf,key2){if(!key2){throw new Error("[storage] session file is BILIENC1-encrypted but no BILI_ENCRYPTION_KEY is set \u2014 cannot read it")}if(buf.length<MIN_ENCRYPTED_LEN||buf[ENCRYPT_MAGIC.length]!==FORMAT_VERSION){throw new Error(`[encrypt] unsupported session file format version ${buf[ENCRYPT_MAGIC.length]}`)}const mode=buf[ENCRYPT_MAGIC.length+1];const nonce=buf.subarray(ENCRYPT_HEADER_LEN-NONCE_LEN,ENCRYPT_HEADER_LEN);const tag=buf.subarray(buf.length-TAG_LEN);const ct2=buf.subarray(ENCRYPT_HEADER_LEN,buf.length-TAG_LEN);const decipher=createDecipheriv("aes-256-gcm",key2,nonce);decipher.setAuthTag(tag);const body=Buffer.concat([decipher.update(ct2),decipher.final()]);const plain=mode===MODE_ZSTD?inflateZstd(body):body;return plain.toString("utf8")}function decompressEnvelope(buf){if(buf.length<PLAIN_HEADER_LEN||buf[ZSTD_MAGIC.length]!==FORMAT_VERSION){throw new Error(`[storage] unsupported session file format version ${buf[ZSTD_MAGIC.length]}`)}const mode=buf[ZSTD_MAGIC.length+1];const body=buf.subarray(PLAIN_HEADER_LEN);const plain=mode===MODE_ZSTD?inflateZstd(body):body;return plain.toString("utf8")}init_logger();var LOCK_CODES=/\b(EPERM|EBUSY|EACCES)\b/;var WRITE_FAIL_RE=/^\[persist\] write failed for (.+?) \(total (\d+)x\): (.+)$/;var PersistEpermAlert=class{dir;threshold;repeatMs;platform;now;onAlert;hasAlerted=false;alertedAt=0;constructor(opts){this.dir=opts.dir;this.threshold=opts.threshold??5;this.repeatMs=opts.repeatMs??0;this.platform=opts.platform??process.platform;this.now=opts.now??Date.now;this.onAlert=opts.onAlert??((d,c)=>log("warn",buildAlertMessage(d,c)))}observe(level,msg){if(this.platform!=="win32")return false;if(level!=="error"&&level!=="warn")return false;const m2=WRITE_FAIL_RE.exec(msg);if(!m2)return false;const count=Number(m2[2]);if(count<this.threshold)return false;if(!LOCK_CODES.test(m2[3]))return false;if(!this.shouldAlert())return false;this.hasAlerted=true;this.alertedAt=this.now();this.onAlert(this.dir,count);return true}shouldAlert(){if(!this.hasAlerted)return true;if(this.repeatMs<=0)return false;return this.now()-this.alertedAt>=this.repeatMs}};function buildAlertMessage(dir,count){return[`[persist] session dir ${dir} failed ${count} consecutive writes (EPERM \u2014 rename is locked).`,"Likely cause: Windows Defender / antivirus / indexer / a sync tool is locking the directory.",`Fix: add ${dir} to Windows Defender exclusions (Settings \u2192 Virus & threat protection \u2192 Manage settings \u2192 Exclusions \u2192 Add an exclusion),`,"and make sure no OneDrive / sync tool is syncing this path."].join("\n")}init_dist();init_billing();init_state_hydration();init_dist();init_shadow();init_logger();var HOT_ATTACH_WINDOW_MS=10*6e4;var ATTACH_SILENCE_MS=5*6e4;var attachSilenceMs=ATTACH_SILENCE_MS;var armed=new Map;function disarm(id){const entry=armed.get(id);if(!entry)return;clearTimeout(entry.timer);armed.delete(id)}function noteColdLoad(id,source,savedAt){if(savedAt===void 0)return;if(Date.now()-savedAt>HOT_ATTACH_WINDOW_MS){disarm(id);return}disarm(id);const entry={id,source,savedAt,timer:setTimeout(()=>fire(entry),attachSilenceMs),fired:false};entry.timer.unref?.();armed.set(id,entry)}function noteRequest(id){disarm(id)}function fire(entry){if(entry.fired)return;entry.fired=true;armed.delete(entry.id);log("error",`[attach] ${entry.id}: cold-loaded from ${entry.source} while still hot (savedAt ${new Date(entry.savedAt).toISOString()}) but NO model request was observed within ${attachSilenceMs/6e4} min \u2014 the host's traffic may be bypassing this proxy entirely (fetch chain detached, #1158/#1662) or the host died; compression is NOT running for this session (#5408)`)}init_backend();init_ingest();init_store();init_dist();init_logger();init_paths();import{randomUUID as randomUUID2}from"crypto";import{mkdirSync as mkdirSync6,writeFileSync as writeFileSync5}from"fs";import{dirname as dirname3,join as join5}from"path";init_knobs();init_proxy_tool_result();var EFFECTIVE_CCR_KEY="effectiveCcr";function storeEffectiveCcr(session,ccr){session.metadata[EFFECTIVE_CCR_KEY]=ccr??null;if(!ccr){const carrierRefs=carrierOf(session).map(p2=>p2.ref);const ledgerRefs=readLedger(session).map(e=>e.ref);const allRefs=[...new Set([...carrierRefs,...ledgerRefs])];if(allRefs.length>0)dropRetrievals(session,allRefs,"CCR disarmed before delivery")}}function effectiveCcr(session){const meta=session?.metadata[EFFECTIVE_CCR_KEY];if(meta&&typeof meta==="object"&&typeof meta.enabled==="boolean"){return meta}return void 0}function ccrEnabled(session){return effectiveCcr(session)?.enabled===true}var EFFECTIVE_IMAGE_RESCALE_KEY="effectiveImageRescale";function storeEffectiveImageRescale(session,armed3){if(armed3===true)session.metadata[EFFECTIVE_IMAGE_RESCALE_KEY]=true;else delete session.metadata[EFFECTIVE_IMAGE_RESCALE_KEY]}function imageRescaleToolArmed(session){return session?.metadata[EFFECTIVE_IMAGE_RESCALE_KEY]===true}function retrieveToolName(session){return effectiveCcr(session)?.toolName??RETRIEVE_TOOL_NAME}function ccrLoopConfig(session,config){if(!ccrEnabled(session))return{...config,ccr:void 0};const eff=effectiveCcr(session);if(!eff)return config;return{...config,ccr:{...DEFAULT_CCR_CONFIG,...eff}}}var PLUGIN_CCR_WIRES=new Set(["anthropic","openai"]);function ccrPluginWireOk(protocol){return PLUGIN_CCR_WIRES.has(protocol)}function contentStoreOf(session){if(!session.contentStore){session.contentStore=getStore().unifiedCcrFor(session.id)??getStore().loadContentStore(session)??createContentStore()}return session.contentStore}function adoptContentStore(session,store2){const prev=session.contentStore;let prevRefs=null;if(prev){try{prevRefs=new Set(Object.keys(prev.byRef))}catch(err2){log("warn",`[ccr] lazy content store for ${session.id} could not be re-materialized during adopt (${String(err2 instanceof Error?err2.message:err2)}) \u2014 proceeding with the incoming store as the full set`)}}const added=!prev||prevRefs===null?Object.entries(store2.byRef):Object.entries(store2.byRef).filter(([ref])=>!prevRefs.has(ref));session.contentStore=store2;if(added.length===0)return;let saved=0;for(const[ref,entry]of added){const placeholder=buildStoredPlaceholder({ref,kind:entry.kind,tokens:entry.tokens,head:entry.head,retrieveToolName:retrieveToolName(session)});saved+=Math.max(0,entry.chars-Buffer.byteLength(placeholder,"utf8"))}session.stats.storedBytes=contentStoreStats(store2).totalChars;session.stats.storeBytesSaved=(session.stats.storeBytesSaved??0)+saved;session.contentStoreDirty=true}function cloneStoreForRefs(store2,refs){const wanted=new Set(refs);const byRef={};const byHash={};for(const[ref,entry]of Object.entries(store2.byRef)){if(!wanted.has(ref))continue;byRef[ref]={...entry};const text2=store2.byHash[entry.hash];if(text2!==void 0&&!(entry.hash in byHash))byHash[entry.hash]=text2}return Object.keys(byRef).length>0?{version:1,byHash,byRef}:null}function executeRetrieve(args,session){session.stats.retrieveCalls=(session.stats.retrieveCalls??0)+1;const rawRef=args.ref;const ref=typeof rawRef==="string"?rawRef.trim():"";if(!ref){session.stats.retrieveMisses=(session.stats.retrieveMisses??0)+1;return toolFail(`[${retrieveToolName(session)} FAILED: ref (an mNNNNN id) is required]`)}const result=applyRetrieve({store:contentStoreOf(session),ref,exportDir:retrievalExportDir()});if(!result.ok){session.stats.retrieveMisses=(session.stats.retrieveMisses??0)+1;log("info",`[ccr] retrieve ${ref}: miss (${result.reason})`);return toolFail(result.toolResultText)}session.stats.retrieveHits=(session.stats.retrieveHits??0)+1;session.state=noteRetrieval(session.state);recordRetrieveHit(session,ref);if(result.export!==void 0&&!writeRetrievalExport(result.export)){return toolFail(`[${retrieveToolName(session)} FAILED: could not write ${result.export.path} \u2014 head preview follows]
|
|
898
898
|
${result.entry.head}`)}session.stats.retrieveDelivered=(session.stats.retrieveDelivered??0)+1;log("info",`[ccr] retrieve ${ref} (${result.entry.tokens} tok, ${result.entry.chars} chars${result.export?`, exported ${result.export.path}`:""})`);return toolOk(result.toolResultText)}function retrievalExportDir(){return join5(stateDir(),"retrieve")}function writeRetrievalExport(exported){try{mkdirSync6(dirname3(exported.path),{recursive:true});writeFileSync5(exported.path,exported.text,{encoding:"utf8",mode:384});return true}catch(e){log("warn",`[ccr] retrieve export write failed (${exported.path}): ${String(e)}`);return false}}var MAX_DROP_NOTES=64;function readLedger(session){const v2=session.metadata.ccrUndelivered;return Array.isArray(v2)?v2:[]}function carrierOf(session){return session.pendingRetrievals??[]}function retrievalTtlMs(){return ccrRetrievalTtlMs()}function bufferDropNote(session,refs,reason){const existing=session.metadata.ccrDropNotes;const arr=Array.isArray(existing)?existing:[];arr.push({id:randomUUID2(),refs,reason,createdAt:Date.now()});while(arr.length>MAX_DROP_NOTES){const evicted=arr.shift();log("warn",`[ccr] corrective note buffer full (${MAX_DROP_NOTES}) \u2014 evicting oldest (${evicted?.refs.join(", ")??"?"}: ${evicted?.reason??"?"})`)}session.metadata.ccrDropNotes=arr}function snapshotPendingRetrievals(session){return carrierOf(session).slice()}function commitRetrievals(session,refs){const requested=[...new Set(refs)];if(requested.length===0)return;const reqSet=new Set(requested);const carrier=carrierOf(session);const ledger=readLedger(session);const inCarrier=carrier.filter(p2=>reqSet.has(p2.ref));const inLedger=ledger.filter(e=>reqSet.has(e.ref));if(inCarrier.length===0&&inLedger.length===0)return;session.pendingRetrievals=carrier.filter(p2=>!reqSet.has(p2.ref));session.metadata.ccrUndelivered=ledger.filter(e=>!reqSet.has(e.ref));const ccr=new Set([...inCarrier.filter(p2=>p2.ccr).map(p2=>p2.ref),...inLedger.map(e=>e.ref)]);if(ccr.size>0)session.stats.retrieveDelivered=(session.stats.retrieveDelivered??0)+ccr.size}function dropRetrievals(session,refs,reason){const requested=[...new Set(refs)];if(requested.length===0)return;const reqSet=new Set(requested);const carrier=carrierOf(session);const ledger=readLedger(session);const inCarrier=carrier.filter(p2=>reqSet.has(p2.ref));const inLedger=ledger.filter(e=>reqSet.has(e.ref));if(inCarrier.length===0&&inLedger.length===0)return;session.pendingRetrievals=carrier.filter(p2=>!reqSet.has(p2.ref));session.metadata.ccrUndelivered=ledger.filter(e=>!reqSet.has(e.ref));const ccrRefs=[...new Set([...inCarrier.filter(p2=>p2.ccr).map(p2=>p2.ref),...inLedger.map(e=>e.ref)])];if(ccrRefs.length===0)return;const tok=inCarrier.filter(p2=>p2.ccr).reduce((s3,p2)=>s3+p2.tokens,0);session.stats.retrieveDropped=(session.stats.retrieveDropped??0)+ccrRefs.length;log("warn",`[ccr] ${ccrRefs.length} retrieval(s) not delivered (${reason}): ${ccrRefs.join(", ")}${tok?` (${tok} tok)`:""}`);bufferDropNote(session,ccrRefs,reason)}function pruneExpiredRetrievals(session,now=Date.now()){const ttl=retrievalTtlMs();if(ttl<=0)return;const expired=carrierOf(session).filter(p2=>p2.ccr&&now-p2.queuedAt>ttl).map(p2=>p2.ref);if(expired.length>0)dropRetrievals(session,expired,`still queued after ${ttl}ms without a delivery request`)}function reconcileReloadedRetrievals(session){if(!session.ccrReconcilePending)return;session.ccrReconcilePending=false;const carried=new Set(carrierOf(session).map(p2=>p2.ref));const lost=readLedger(session).filter(e=>!carried.has(e.ref)).map(e=>e.ref);if(lost.length>0)dropRetrievals(session,lost,"proxy restarted before delivery")}function snapshotRetrievalNotes(session){const v2=session.metadata.ccrDropNotes;if(!Array.isArray(v2)||v2.length===0)return[];return v2.map(n=>({...n,id:typeof n.id==="string"?n.id:""}))}function renderRetrievalNotes(notes){if(notes.length===0)return null;const lines=notes.map(n=>`${n.refs.join(", ")}: ${n.reason}`).join("; ");return`[billion-context] Earlier acp_retrieve result(s) were NOT delivered, so their acks are stale and you do NOT have that content: ${lines}. Re-issue acp_retrieve for any ref above to fetch it.`}function commitRetrievalNotes(session,ids){const requested=[...new Set(ids)];if(requested.length===0)return;const v2=session.metadata.ccrDropNotes;if(!Array.isArray(v2)||v2.length===0)return;const reqSet=new Set(requested);const remaining=v2.filter(n=>!reqSet.has(typeof n.id==="string"?n.id:""));if(remaining.length===v2.length)return;if(remaining.length===0)delete session.metadata.ccrDropNotes;else session.metadata.ccrDropNotes=remaining;log("info",`[ccr] ${v2.length-remaining.length} corrective note(s) confirmed delivered`)}function drainPendingRetrievals(session){pruneExpiredRetrievals(session);const items=carrierOf(session).slice();if(items.length===0)return[];session.pendingRetrievals=[];commitRetrievals(session,items.map(i=>i.ref));return items.map(i=>i.injection)}var RETRIEVE_COUNT_CAP=512;function recordRetrieveHit(session,ref){const counts=session.retrieveCountsByRef??new Map;counts.set(ref,(counts.get(ref)??0)+1);while(counts.size>RETRIEVE_COUNT_CAP){const oldest=counts.keys().next().value;if(oldest===void 0)break;counts.delete(oldest)}session.retrieveCountsByRef=counts}init_dist();init_logger();import{createHash as createHash13,randomUUID as randomUUID3}from"crypto";import{AsyncLocalStorage as AsyncLocalStorage3}from"async_hooks";init_dist();import{createHash as createHash12}from"crypto";var FORMS=[{open:"<think>\n",close:"\n</think>"},{open:"<thinking>\n",close:"\n</thinking>"},{open:"```thinking\n",close:"\n```"}];import{createHash as createHash11}from"crypto";var MAX_FEATURES=256;var SKETCH_MEMO_CAP=8192;var sketchMemo=new Map;function fnv1a32(text2,basis){let h=basis>>>0;for(let i=0;i<text2.length;i++){h^=text2.charCodeAt(i);h=Math.imul(h,16777619)>>>0}return h>>>0}function simhashHex(canonical2){const tokens=canonical2.match(/[\p{L}\p{N}_]+/gu)??[];const features=[];if(tokens.length<2){for(const t of tokens)features.push(t)}else{for(let i=0;i+1<tokens.length;i++)features.push(`${tokens[i]}${tokens[i+1]}`)}if(features.length===0){features.push(canonical2)}const stride=Math.max(1,Math.ceil(features.length/MAX_FEATURES));const v2=new Int8Array(64);for(let f2=0;f2<features.length;f2+=stride){const h1=fnv1a32(features[f2],2166136261);const h2=fnv1a32(features[f2],2166136261^2654435769);for(let b2=0;b2<64;b2++){const bit=b2<32?h1>>>b2&1:h2>>>b2-32&1;v2[b2]+=bit===1?1:-1}}let lo2=0;let hi2=0;for(let b2=0;b2<32;b2++){if(v2[b2]>0)lo2|=1<<b2;if(v2[b2+32]>0)hi2|=1<<b2}return(hi2>>>0).toString(16).padStart(8,"0")+(lo2>>>0).toString(16).padStart(8,"0")}function hammingHex(a,b2){if(a.length!==16||b2.length!==16)return-1;return popcount(hexToU32(a.slice(0,8))^hexToU32(b2.slice(0,8)))+popcount(hexToU32(a.slice(8))^hexToU32(b2.slice(8)))}function hexToU32(hex){const n=Number.parseInt(hex,16);return Number.isFinite(n)?n>>>0:0}function popcount(x){x=x-(x>>>1&1431655765);x=(x&858993459)+(x>>>2&858993459);x=x+(x>>>4)&252645135;return Math.imul(x,16843009)>>>24}var simhashComputeCount=0;function sketchForCanonical(canonical2,itemHash){const key2=itemHash??createHash11("sha256").update(canonical2).digest("hex");const hit=sketchMemo.get(key2);if(hit!==void 0){sketchMemo.delete(key2);sketchMemo.set(key2,hit);return hit}const sketch=simhashHex(canonical2);simhashComputeCount++;if(sketchMemo.size>=SKETCH_MEMO_CAP){const oldest=sketchMemo.keys().next().value;if(oldest!==void 0)sketchMemo.delete(oldest)}sketchMemo.set(key2,sketch);return sketch}function dshSkillCatalogPath(msg){return msg.role!=="assistant"&&msg.contentType==="text"&&typeof msg.text==="string"&&msg.text.includes("<available_skills>")?"durable/skill-catalog":void 0}function dshWorkspaceInstructionsPath(msg){return msg.role!=="assistant"&&msg.contentType==="text"&&typeof msg.text==="string"&&msg.text.includes("Instructions from:")?"durable/agents-md":void 0}function dshMcpCatalogPath(msg){return msg.role!=="assistant"&&msg.contentType==="text"&&typeof msg.text==="string"&&msg.text.includes("<mcp_catalog>")?"durable/mcp-catalog":void 0}function dshRuntimeContextPath(msg){return msg.role!=="assistant"&&msg.contentType==="text"&&typeof msg.text==="string"&&msg.text.includes("Current runtime context")?"durable/runtime-context":void 0}var TIME_CONTEXT_MARKER="Time sampled while preparing turn";function dshTimeContextPath(msg){return msg.role!=="assistant"&&msg.contentType==="text"&&typeof msg.text==="string"&&startsWithAsciiCI(msg.text.trim(),TIME_CONTEXT_MARKER)?"oneshot/time-context":void 0}function dshPastedImagePath(msg){return msg.role!=="assistant"&&msg.contentType==="text"&&typeof msg.text==="string"&&msg.text.includes("<type>image</type>")?"oneshot/ptc-image":void 0}function dshToolJobNoticePath(msg){return msg.role!=="assistant"&&msg.contentType==="text"&&typeof msg.text==="string"&&startsWithAsciiCI(msg.text.trim(),"background job")?"oneshot/tool-job-notice":void 0}function startsWithAsciiCI(hay,needle){if(hay.length<needle.length)return false;for(let i=0;i<needle.length;i++){const h=hay.charCodeAt(i);const n=needle.charCodeAt(i);if(h===n)continue;const hl=h>=65&&h<=90?h+32:h;if(hl!==(n>=65&&n<=90?n+32:n))return false}return true}function dshDurableToolPath(msg){return dshSkillCatalogPath(msg)??dshWorkspaceInstructionsPath(msg)??dshRuntimeContextPath(msg)??dshMcpCatalogPath(msg)??dshTimeContextPath(msg)}var durableMessageToolPaths={dsh:dshDurableToolPath};function classifiesDurable(patterns){return(patterns??[]).some(p2=>p2.toLowerCase().split("/")[0]==="durable")}function withDurableProtection(config,classifier){const classified=classifiesDurable(config.protectedTools)||classifiesDurable(config.protectedLatestTools);if(classified){return{...config,messagePathOf:classifier}}return{...config,protectedLatestTools:[...config.protectedLatestTools??[],"durable/*"],messagePathOf:classifier}}var oneShotCarrierPaths={dsh:msg=>dshSkillCatalogPath(msg)??dshWorkspaceInstructionsPath(msg)??dshRuntimeContextPath(msg)??dshMcpCatalogPath(msg)??dshTimeContextPath(msg)??dshPastedImagePath(msg)??dshToolJobNoticePath(msg)};var dshCarrierRawMarkers=["<available_skills>","Instructions from:","Current runtime context","<mcp_catalog>","Time sampled while preparing turn","<type>image</type>","background job"];init_logger();var METADATA_ANCHORS="foldAnchors";var METADATA_ORDER="foldAnchorOrder";var METADATA_POSITIONS="foldPositions";var METADATA_SYSTEM_FP="systemFp";var METADATA_CANONICAL_SYS_FP="canonicalSysFp";var METADATA_LAST_RESPONSES_MODE="lastResponsesMode";var MAX_ANCHORS=16384;var MAX_ORDER=32768;var METADATA_DRIFT_STREAK="foldDriftStreak";var METADATA_DRIFT_SINCE="foldDriftSince";var METADATA_MARKER_CHURN_NOTED="foldMarkerChurnNoted";var METADATA_DRIFT_ESCALATED="foldDriftEscalated";var METADATA_EPOCH_CONFIRM="foldEpochConfirmPending";var METADATA_SHAPE_NOTED="foldShapeChurnNoted";var METADATA_TRUNC_NOTED="foldTruncationNoted";var METADATA_TAIL_TRUNC_NOTED="foldTailTruncationNoted";var METADATA_EPISODE_ORDER="foldEpisodeOrder";function epochConfirmPending(session){return session.metadata?.[METADATA_EPOCH_CONFIRM]===true}var FOLD_DRIFT_ESCALATE_PASSES=3;var SHAPE_MASS_MIN=4;var FOLD_DRIFT_ESCALATE_MIN_UNMATCHED=10;var MIN_RESYNC_RUN=3;var MAX_RESYNC_GAPS=8;var GAP_SIMHASH_MAX_HAMMING=8;var METADATA_FOLD_COVERAGE="foldCoverageByBlock";var SIDE_REQUEST_MAX_MSGS=10;var USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)";var METADATA_EXPECTED_REBASE="foldExpectedRebase";var METADATA_EXPECTED_REBASE_NOTED="foldExpectedRebaseNoted";var METADATA_OFFLOAD_PENDING="foldOffloadPending";var MAX_REBASE_LOOKUP_PER_PASS=256;var MAX_REBASE_MEMO=8192;function pruneRebaseMemo(memo){const keys=Object.keys(memo);if(keys.length<=MAX_REBASE_MEMO)return memo;const out={};for(const k2 of keys.slice(-MAX_REBASE_MEMO))out[k2]=memo[k2];return out}function storedMessageCarriesImage(m2){if(typeof m2!=="object"||m2===null)return false;const mm=m2;const ab2=mm.rawAnthropicBlock;if(typeof ab2==="object"&&ab2!==null&&ab2.type==="image")return true;if(typeof mm.imageBase64==="string"&&mm.imageBase64.length>0)return true;const t=mm.text;if(typeof t==="string"&&(t==="[image]"||t.includes("data:image/")))return true;for(const field of["rawOpenaiContentParts","rawResponsesItem"]){const v2=mm[field];if(v2!==void 0&&v2!==null&&JSON.stringify(v2).includes('"image'))return true}return false}function resetFoldDriftState(session){const md=session.metadata;if(!md)return;delete md[METADATA_DRIFT_STREAK];delete md[METADATA_DRIFT_SINCE];delete md[METADATA_DRIFT_ESCALATED];delete md[METADATA_EPOCH_CONFIRM];delete md[METADATA_SHAPE_NOTED];delete md[METADATA_TRUNC_NOTED];delete md[METADATA_TAIL_TRUNC_NOTED];delete md[METADATA_EPISODE_ORDER];delete md[METADATA_EXPECTED_REBASE_NOTED]}var seenInvalidEnv=new Set;function resolveFoldReconcileMode(env,configured){const raw=env.BILI_FOLD_RECONCILE;if(raw!==void 0&&raw!==""){if(raw==="off"||raw==="warn"||raw==="repair")return raw;if(!seenInvalidEnv.has(raw)){seenInvalidEnv.add(raw);console.warn(`[fold-reconcile] ignoring invalid BILI_FOLD_RECONCILE="${raw}" (expected off|warn|repair)`)}}if(configured==="off"||configured==="warn"||configured==="repair")return configured;return"repair"}function normalizeMessageText(text2){if(text2===void 0||text2==="")return"";return text2.normalize("NFC").replace(/\r\n?/g,"\n").replace(/[^\S\n]+/g," ").replace(/ *\n */g,"\n").replace(/\n{2,}/g,"\n").trim()}var normalizedIdentityWork=0;function normalizedIdentity(message){normalizedIdentityWork++;const h=createHash12("sha256");h.update(`${message.role}\0${message.contentType}\0${message.toolName??""}\0${message.toolCallId??""}\0${normalizeMessageText(message.text)}`);return h.digest("hex").slice(0,16)}function normalizedIdentityNoToolCallId(message){normalizedIdentityWork++;const h=createHash12("sha256");h.update(`${message.role}\0${message.contentType}\0${message.toolName??""}\0${normalizeMessageText(message.text)}`);return h.digest("hex").slice(0,16)}function identityWithText(message,text2){normalizedIdentityWork++;const h=createHash12("sha256");h.update(`${message.role}\0${message.contentType}\0${message.toolName??""}\0${message.toolCallId??""}\0${normalizeMessageText(text2)}`);return h.digest("hex").slice(0,16)}function turnKeyOf(reasoning,text2){normalizedIdentityWork++;const joined=reasoning!==void 0&&reasoning!==""&&text2!==void 0&&text2!==""?`${reasoning}
|
|
899
899
|
${text2}`:(reasoning??"")+(text2??"");const h=createHash12("sha256");h.update(`turn\0${normalizeMessageText(joined)}`);return h.digest("hex").slice(0,16)}function turnKeyOfSeamless(reasoning,text2){normalizedIdentityWork++;const joined=(reasoning??"")+(text2??"");const h=createHash12("sha256");h.update(`turn\0${normalizeMessageText(joined)}`);return h.digest("hex").slice(0,16)}function extractThinkingMerge(text2){if(text2===void 0||text2==="")return null;let rest=text2;const parts=[];for(;;){let matched=false;for(const form of FORMS){if(!rest.startsWith(form.open))continue;const end=rest.indexOf(form.close,form.open.length);if(end<0)continue;const inner=rest.slice(form.open.length,end);if(inner.length===0)continue;parts.push(inner);rest=rest.slice(end+form.close.length);if(rest.startsWith("\n"))rest=rest.slice(1);matched=true;break}if(!matched)break}if(parts.length===0)return null;return{reasoning:parts.join("\n"),text:rest}}function turnContexts(msgs){const ctx=new Map;for(let i=0;i<msgs.length;i++){const m2=msgs[i];if(m2.id===void 0||m2.role!=="assistant"||m2.toolCallId!==void 0&&m2.toolCallId!=="")continue;if(m2.contentType==="reasoning"){const next=msgs[i+1];if(next!==void 0&&next.id!==void 0&&next.role==="assistant"&&next.contentType==="text"&&(next.toolCallId===void 0||next.toolCallId==="")){const key2=turnKeyOf(m2.text,next.text);const seamless=turnKeyOfSeamless(m2.text,next.text);ctx.set(m2.id,seamless!==key2?{p:key2,p2:seamless,x:next.id}:{p:key2,x:next.id});ctx.set(next.id,seamless!==key2?{p:key2,p2:seamless,x:m2.id}:{p:key2,x:m2.id})}else{ctx.set(m2.id,{p:turnKeyOf(m2.text,void 0)})}}else if(m2.contentType==="text"){const prev=msgs[i-1];if(prev===void 0||prev.id===void 0||prev.role!=="assistant"||prev.contentType!=="reasoning"||prev.toolCallId!==void 0&&prev.toolCallId!==""){const ex=extractThinkingMerge(m2.text);if(ex!==null){const key2=turnKeyOf(ex.reasoning,ex.text);const seamless=turnKeyOfSeamless(ex.reasoning,ex.text);ctx.set(m2.id,seamless!==key2?{p:key2,p2:seamless}:{p:key2})}else{ctx.set(m2.id,{p:turnKeyOf(void 0,m2.text)})}}}}return ctx}function canonicalJson(value){if(typeof value==="string")return JSON.stringify(value);if(typeof value==="number"||typeof value==="boolean"||value===null)return String(value);if(Array.isArray(value))return`[${value.map(v2=>canonicalJson(v2)).join(",")}]`;if(typeof value==="object"){const keys=Object.keys(value).sort();const parts=[];for(const k2 of keys){parts.push(`${JSON.stringify(k2)}:${canonicalJson(value[k2])}`)}return`{${parts.join(",")}}`}return JSON.stringify(String(value))}function canonicalTextOf(text2){const t=text2.trimStart();if(!t.startsWith("{")&&!t.startsWith("["))return normalizeMessageText(text2);try{return canonicalJson(JSON.parse(t))}catch{return normalizeMessageText(text2)}}function wordBagDigest(text2){let acc=1;for(const m2 of text2.toLowerCase().matchAll(new RegExp("\\p{L}+|\\p{N}+","gu"))){acc=(acc+wordHash(m2[0]))%9007199254740991}return acc}function wordHash(w2){let h=2166136261;for(let i=0;i<w2.length;i++){h^=w2.charCodeAt(i);h=Math.imul(h,16777619)>>>0}return h}var positionalFingerprintWork=0;function positionalFingerprint(message){positionalFingerprintWork++;const h=createHash12("sha256");if(message.contentType==="reasoning"){h.update(`${message.role}\0reasoning-id-carrier\0`);return h.digest("hex").slice(0,16)}h.update(`${message.role}\0${message.toolName??""}\0${canonicalTextOf(message.text??"")}`);return h.digest("hex").slice(0,16)}function anchorFrom(message,ctx){const t=message.toolCallId!==void 0&&message.toolCallId!==""?message.toolCallId:void 0;const anchor={n:normalizedIdentity(message),r:message.role,c:message.contentType,b:message.text?.length??0};if(t!==void 0){anchor.t=t;anchor.m=normalizedIdentityNoToolCallId(message)}if(message.text!==void 0&&message.text!==""&&message.contentType!=="reasoning"){anchor.sh=simhashHex(canonicalTextOf(message.text));anchor.wh=wordBagDigest(canonicalTextOf(message.text))}if(ctx?.p!==void 0)anchor.p=ctx.p;if(ctx?.p2!==void 0)anchor.p2=ctx.p2;if(ctx?.x!==void 0)anchor.x=ctx.x;return anchor}function liteToolAnchorFrom(message){return{r:message.role,c:message.contentType,t:message.toolCallId,b:message.text?.length??0}}function coveredIdsOf(blocks){return coveredRealHistoryIds(blocks)}function recoveryCandidateIds(blocks){const ids=new Set;for(const block of blocks){if(block.active||block.expanded===true)continue;for(const id of block.effectiveMessageIds??[]){if(!isResponsesTurnSeparatorId(id))ids.add(id)}}return ids}function planReconciliation(oldOrder,anchors,msgs,covered,positions,expectedAbsent){const plan2={claims:new Map,byPos:0,byTool:0,byTwin:0,bySim:0,byOrder:0,byNorm:0,byTurn:0,byImage:0,unmatched:[],idRewriteSuspects:0,newOrder:[],nextCanon:void 0,resyncs:0,byShape:0,absentEverywhere:[],nearDupResidual:[]};const canonById=new Map;if(positions!==void 0){const pids=positions.ids;const pcanon=positions.canon;for(let i=0;i<pids.length&&i<pcanon.length;i++)canonById.set(pids[i],pcanon[i])}let stored;if(positions!==void 0&&positions.ids.length===oldOrder.length&&positions.canon.length===oldOrder.length){if(positions.ids.every((id,i)=>id===oldOrder[i])){stored=positions.canon}else{plan2.pass0Desync=true}}const canon2=[];const newOrder=[];const byId2=new Map;for(const m2 of msgs){if(m2.id===void 0)continue;const i=newOrder.length;newOrder.push(m2.id);byId2.set(m2.id,m2);const priorCanon=canonById.get(m2.id);canon2.push(priorCanon!==void 0?priorCanon:positionalFingerprint(m2))}plan2.newOrder=newOrder;plan2.nextCanon=canon2;const missing=[];const missingSet=new Set;for(const id of covered){if(!byId2.has(id)&&!expectedAbsent?.has(id)){missing.push(id);missingSet.add(id)}}if(missing.length===0)return plan2;let prefix=0;while(prefix<oldOrder.length&&prefix<newOrder.length&&oldOrder[prefix]===newOrder[prefix])prefix++;let suffix=0;while(suffix<oldOrder.length-prefix&&suffix<newOrder.length-prefix&&oldOrder[oldOrder.length-1-suffix]===newOrder[newOrder.length-1-suffix])suffix++;const candidates=[];for(let i=prefix;i<newOrder.length-suffix;i++){const id=newOrder[i];if(covered.has(id))continue;const message=byId2.get(id);if(message===void 0)continue;candidates.push({id,message,pos:i})}const claimedCandidates=new Set;const missingMiddle=[];for(let i=prefix;i<oldOrder.length-suffix;i++){const id=oldOrder[i];if(missingSet.has(id))missingMiddle.push(id)}const gapPairs=[];const claimedIdx=[];const recordGap=(oldIdx,oldId,newId)=>{if(oldId!==newId&&missingSet.has(oldId)&&!covered.has(newId)&&!claimedCandidates.has(newId)){gapPairs.push({oldIdx,oldId,newId})}};if(stored!==void 0){const head=Math.min(oldOrder.length,newOrder.length)-suffix;let gaps=0;let i=prefix;while(i<head){if(canon2[i]!==stored[i]){recordGap(i,oldOrder[i],newOrder[i]);let r=-1;for(let k2=i+1;k2+MIN_RESYNC_RUN<=head;k2++){if(canon2[k2]===stored[k2]&&canon2[k2+1]===stored[k2+1]&&canon2[k2+2]===stored[k2+2]){r=k2;break}}if(r===-1||++gaps>MAX_RESYNC_GAPS)break;plan2.resyncs++;i=r;continue}const oldId=oldOrder[i];const newId=newOrder[i];if(oldId===newId||!missingSet.has(oldId)||covered.has(newId)||claimedCandidates.has(newId)){i++;continue}plan2.claims.set(oldId,[newId]);claimedCandidates.add(newId);plan2.byPos++;claimedIdx.push(i);i++}const tail=Math.min(oldOrder.length,newOrder.length)-prefix;gaps=0;let j2=1;while(j2<=tail){const iOld=oldOrder.length-j2;const iNew=newOrder.length-j2;if(stored[iOld]!==canon2[iNew]){recordGap(iOld,oldOrder[iOld],newOrder[iNew]);let r=-1;for(let k2=j2+1;k2+MIN_RESYNC_RUN-1<=tail;k2++){let ok=true;for(let u2=0;u2<MIN_RESYNC_RUN;u2++){if(stored[oldOrder.length-(k2+u2)]!==canon2[newOrder.length-(k2+u2)]){ok=false;break}}if(ok){r=k2;break}}if(r===-1||++gaps>MAX_RESYNC_GAPS)break;plan2.resyncs++;j2=r;continue}const oldId=oldOrder[iOld];const newId=newOrder[iNew];if(oldId===newId||!missingSet.has(oldId)||covered.has(newId)||claimedCandidates.has(newId)||plan2.claims.has(oldId)){j2++;continue}plan2.claims.set(oldId,[newId]);claimedCandidates.add(newId);plan2.byPos++;claimedIdx.push(iOld);j2++}}if(missingMiddle.length>0&&candidates.length>0){const byToolCallId=new Map;for(const cand of candidates){const t=cand.message.toolCallId;if(t===void 0||t==="")continue;const bucket=byToolCallId.get(t);if(bucket===void 0)byToolCallId.set(t,[cand]);else bucket.push(cand)}for(const oldId of missingMiddle){const anchor=anchors[oldId];if(anchor===void 0||anchor.t===void 0||anchor.r===void 0)continue;const bucket=byToolCallId.get(anchor.t);if(bucket===void 0)continue;const usable=bucket.filter(c=>!claimedCandidates.has(c.id)&&c.message.role===anchor.r);if(usable.length!==1)continue;plan2.claims.set(oldId,[usable[0].id]);claimedCandidates.add(usable[0].id);plan2.byTool++}}if(missingMiddle.length>0&&candidates.length>0){const twinBuckets=new Map;for(const cand of candidates){if(claimedCandidates.has(cand.id))continue;const t=cand.message.toolCallId;if(t===void 0||t==="")continue;const nt2=normalizedIdentityNoToolCallId(cand.message);const b2=twinBuckets.get(nt2);if(b2===void 0)twinBuckets.set(nt2,{k:0,ids:[cand.id],messages:[cand.message]});else{b2.ids.push(cand.id);b2.messages.push(cand.message)}}if(twinBuckets.size>0){for(const oldId of missingMiddle){if(plan2.claims.has(oldId))continue;const anchor=anchors[oldId];if(anchor===void 0||anchor.t===void 0||anchor.m===void 0)continue;const b2=twinBuckets.get(anchor.m);if(b2===void 0||b2.k>=b2.ids.length)continue;const message=b2.messages[b2.k];const len=message.text?.length??0;if(Math.abs(len-anchor.b)>Math.max(256,anchor.b>>2))continue;plan2.claims.set(oldId,[b2.ids[b2.k]]);claimedCandidates.add(b2.ids[b2.k]);b2.k++;plan2.byTwin++}}}const normGroups=new Map;for(const cand of candidates){if(claimedCandidates.has(cand.id))continue;const norm=cand.norm??(cand.norm=normalizedIdentity(cand.message));const g2=normGroups.get(norm);if(g2===void 0)normGroups.set(norm,{ids:[cand.id],anchors:[]});else g2.ids.push(cand.id)}for(const oldId of missingMiddle){if(plan2.claims.has(oldId))continue;const anchor=anchors[oldId];if(anchor===void 0||anchor.n===void 0)continue;const g2=normGroups.get(anchor.n);if(g2===void 0)continue;if(g2.anchors.length>=g2.ids.length)continue;const newId=g2.ids[g2.anchors.length];const message=byId2.get(newId);if(message===void 0)continue;const len=message.text?.length??0;if(Math.abs(len-anchor.b)>Math.max(256,anchor.b>>2))continue;g2.anchors.push(anchor);plan2.claims.set(oldId,[newId]);claimedCandidates.add(newId);plan2.byNorm++}if(missingMiddle.length>0&&candidates.length>0){const byPos=new Map;for(const cand of candidates)byPos.set(cand.pos,cand);const singleTurnKeys=new Map;const pairTurnKeys=new Map;const isBareAssistantCore=m2=>m2.role==="assistant"&&(m2.toolCallId===void 0||m2.toolCallId==="");for(const cand of candidates){if(claimedCandidates.has(cand.id))continue;if(!isBareAssistantCore(cand.message))continue;if(cand.message.contentType==="text"){const keys=new Set([turnKeyOf(void 0,cand.message.text)]);const ex=extractThinkingMerge(cand.message.text);if(ex!==null){keys.add(turnKeyOf(ex.reasoning,ex.text));keys.add(turnKeyOfSeamless(ex.reasoning,ex.text))}for(const key2 of keys){const bucket=singleTurnKeys.get(key2);if(bucket===void 0)singleTurnKeys.set(key2,[cand.id]);else bucket.push(cand.id)}}else if(cand.message.contentType==="reasoning"){const next=byPos.get(cand.pos+1);if(next!==void 0&&!claimedCandidates.has(next.id)&&isBareAssistantCore(next.message)&&next.message.contentType==="text"){const pair=[cand.id,next.id];for(const key2 of new Set([turnKeyOf(cand.message.text,next.message.text),turnKeyOfSeamless(cand.message.text,next.message.text)])){const bucket=pairTurnKeys.get(key2);if(bucket===void 0)pairTurnKeys.set(key2,[pair]);else bucket.push(pair)}}else{const key2=turnKeyOf(cand.message.text,void 0);const bucket=singleTurnKeys.get(key2);if(bucket===void 0)singleTurnKeys.set(key2,[cand.id]);else bucket.push(cand.id)}}}if(singleTurnKeys.size>0||pairTurnKeys.size>0){const candById=new Map(candidates.map(c=>[c.id,c]));for(const oldId of missingMiddle){if(plan2.claims.has(oldId))continue;const anchor=anchors[oldId];if(anchor===void 0||anchor.p===void 0)continue;const probeKeys=new Set([anchor.p,anchor.p2].filter(k2=>k2!==void 0));const singles=[];const pairs=[];for(const key2 of probeKeys){for(const id of singleTurnKeys.get(key2)??[]){const c=candById.get(id);if(c!==void 0&&!claimedCandidates.has(id)&&!singles.includes(id)&&(c.message.text?.length??0)+64>=anchor.b)singles.push(id)}for(const p2 of pairTurnKeys.get(key2)??[]){if(pairs.some(([a,b2])=>a===p2[0]&&b2===p2[1]))continue;if(claimedCandidates.has(p2[0])||claimedCandidates.has(p2[1]))continue;const ca=candById.get(p2[0]);const cb=candById.get(p2[1]);if(ca===void 0||cb===void 0)continue;const joined=(ca.message.text?.length??0)+(cb.message.text?.length??0)+1;if(Math.abs(joined-anchor.b)<=Math.max(256,anchor.b>>2))pairs.push(p2)}}if(singles.length+pairs.length!==1)continue;const claimSibling=targets=>{if(anchor.x===void 0||!missingSet.has(anchor.x)||plan2.claims.has(anchor.x))return;plan2.claims.set(anchor.x,targets)};if(singles.length===1){plan2.claims.set(oldId,[singles[0]]);claimedCandidates.add(singles[0]);claimSibling([singles[0]])}else{const[a,b2]=pairs[0];plan2.claims.set(oldId,[a,b2]);claimedCandidates.add(a);claimedCandidates.add(b2);claimSibling([a,b2])}plan2.byTurn++}}}if(missingMiddle.length>0&&candidates.length>0){const stripVariants=new Map;const appendVariants=new Map;for(const cand of candidates){if(claimedCandidates.has(cand.id))continue;const m2=cand.message;if(m2.role!=="user"||m2.contentType!=="text"||m2.toolCallId!==void 0&&m2.toolCallId!=="")continue;const raw=m2.text??"";const suffix2=`
|
|
900
900
|
${USER_IMAGE_PLACEHOLDER}`;if(raw.endsWith(suffix2)){const key2=identityWithText(m2,raw.slice(0,raw.length-suffix2.length));const bucket=stripVariants.get(key2);if(bucket===void 0)stripVariants.set(key2,[cand.id]);else bucket.push(cand.id)}const appendKey=identityWithText(m2,raw+suffix2);const bucket2=appendVariants.get(appendKey);if(bucket2===void 0)appendVariants.set(appendKey,[cand.id]);else bucket2.push(cand.id)}const candById=new Map(candidates.map(c=>[c.id,c]));if(stripVariants.size>0||appendVariants.size>0){for(const oldId of missingMiddle){if(plan2.claims.has(oldId))continue;const anchor=anchors[oldId];if(anchor===void 0||anchor.t!==void 0||anchor.n===void 0)continue;const normKey=anchor.n;const take=map=>{const bucket=map.get(normKey);if(bucket===void 0)return void 0;const usable=bucket.filter(id=>{const c=candById.get(id);return c!==void 0&&!claimedCandidates.has(id)&&(c.message.text?.length??0)+USER_IMAGE_PLACEHOLDER.length+64>=anchor.b});return usable.length===1?usable[0]:void 0};const target=take(stripVariants)??take(appendVariants);if(target===void 0)continue;plan2.claims.set(oldId,[target]);claimedCandidates.add(target);plan2.byImage++}const familyClaim=map=>{const byNorm=new Map;for(const oldId of missingMiddle){if(plan2.claims.has(oldId))continue;const anchor=anchors[oldId];if(anchor===void 0||anchor.t!==void 0||anchor.n===void 0)continue;const bucket=byNorm.get(anchor.n);if(bucket===void 0)byNorm.set(anchor.n,[oldId]);else bucket.push(oldId)}for(const[key2,bucket]of map){const usable=bucket.filter(id=>!claimedCandidates.has(id));const oldIds=byNorm.get(key2)??[];if(oldIds.length===0||oldIds.length!==usable.length)continue;for(let k2=0;k2<usable.length;k2++){const anchor=anchors[oldIds[k2]];const c=candById.get(usable[k2]);if(c===void 0||(c.message.text?.length??0)+USER_IMAGE_PLACEHOLDER.length+64<anchor.b)continue;plan2.claims.set(oldIds[k2],[usable[k2]]);claimedCandidates.add(usable[k2]);plan2.byImage++}}};familyClaim(stripVariants);familyClaim(appendVariants)}}if(gapPairs.length>0){const fenced=plan2.byPos>0||plan2.resyncs>0;const minClaimed=claimedIdx.length>0?Math.min(...claimedIdx):-1;const maxClaimed=claimedIdx.length>0?Math.max(...claimedIdx):-1;for(const gap of gapPairs){if(plan2.claims.has(gap.oldId)||claimedCandidates.has(gap.newId))continue;const anchor=anchors[gap.oldId];const message=byId2.get(gap.newId);if(anchor===void 0||message===void 0)continue;if(anchor.r!==void 0&&anchor.r!==message.role)continue;const len=message.text?.length??0;if(Math.abs(len-anchor.b)>Math.max(256,anchor.b>>2))continue;if(anchor.sh!==void 0){const sketch=simhashHex(canonicalTextOf(message.text??""));if(hammingHex(anchor.sh,sketch)>=0&&hammingHex(anchor.sh,sketch)<=GAP_SIMHASH_MAX_HAMMING){if(anchor.wh===void 0||anchor.wh===wordBagDigest(canonicalTextOf(message.text??""))){plan2.claims.set(gap.oldId,[gap.newId]);claimedCandidates.add(gap.newId);plan2.bySim++;continue}}}if(fenced&&gap.oldIdx>minClaimed&&gap.oldIdx<maxClaimed){const loose=Math.abs(len-anchor.b)>Math.max(1024,anchor.b);if(loose)continue;if(anchor.t!==void 0&&(message.toolCallId===void 0||message.toolCallId===""))continue;plan2.claims.set(gap.oldId,[gap.newId]);claimedCandidates.add(gap.newId);plan2.byOrder++}}}for(const id of missing){if(!plan2.claims.has(id))plan2.unmatched.push(id)}const residualMiddle=missingMiddle.filter(id=>!plan2.claims.has(id));if(residualMiddle.length>=SHAPE_MASS_MIN){const looseProse=(anchor,m2)=>{if(anchor.wh===void 0||anchor.sh===void 0)return false;if(anchor.r!==void 0&&anchor.r!==m2.role)return false;const len=m2.text?.length??0;if(Math.abs(len-anchor.b)>Math.max(256,anchor.b>>2))return false;const wh=wordBagDigest(canonicalTextOf(m2.text??""));if(wh!==anchor.wh)return false;const dist=hammingHex(anchor.sh,simhashHex(canonicalTextOf(m2.text??"")));return dist>=0&&dist<=GAP_SIMHASH_MAX_HAMMING};for(const oldId of residualMiddle){const anchor=anchors[oldId];if(anchor===void 0||anchor.sh===void 0||anchor.wh===void 0)continue;const cand=candidates.find(c=>!claimedCandidates.has(c.id)&&looseProse(anchor,c.message));if(cand===void 0)continue;plan2.claims.set(oldId,[cand.id]);claimedCandidates.add(cand.id);plan2.byShape++}const textless=residualMiddle.filter(id=>{const anchor=anchors[id];return anchor!==void 0&&anchor.sh===void 0&&anchor.wh===void 0});if(textless.length>0){const posInOld=new Map;oldOrder.forEach((id,i)=>posInOld.set(id,i));const newIndexOf=new Map;plan2.newOrder.forEach((id,i)=>newIndexOf.set(id,i));const candById=new Map;for(const c of candidates)candById.set(c.id,c);const placed=textless.map(id=>({id,at:posInOld.get(id)})).filter(x=>x.at!==void 0).sort((a,b2)=>a.at-b2.at);const runs=[];for(const item of placed){const last=runs[runs.length-1];if(last!==void 0&&item.at===last[last.length-1].at+1)last.push(item);else runs.push([item])}const wireIndexOf2=id=>{const direct=newIndexOf.get(id);if(direct!==void 0)return direct;const claimed=plan2.claims.get(id);if(claimed!==void 0){for(const nid of claimed){const at2=newIndexOf.get(nid);if(at2!==void 0)return at2}}return-1};for(const run of runs){const lo2=run[0].at;const hi2=run[run.length-1].at;let left=-1;for(let j2=lo2-1;j2>=0;j2--){const at2=wireIndexOf2(oldOrder[j2]);if(at2>=0){left=at2;break}}let right=-1;for(let j2=hi2+1;j2<oldOrder.length;j2++){const at2=wireIndexOf2(oldOrder[j2]);if(at2>=0){right=at2;break}}if(left<0||right<0)continue;if(left>=right)continue;const familyCands=[];for(let at2=left+1;at2<right;at2++){const id=plan2.newOrder[at2];const c=candById.get(id);if(c===void 0||claimedCandidates.has(id)||covered.has(id))continue;familyCands.push(c)}if(familyCands.length!==run.length)continue;for(let k2=0;k2<run.length;k2++){plan2.claims.set(run[k2].id,[familyCands[k2].id]);claimedCandidates.add(familyCands[k2].id);plan2.byShape++}}}}{const residualClasses=new Set(["text","tool-call","tool-result","image","reasoning","code"]);const classCarrying=plan2.unmatched.filter(id=>{const anchor=anchors[id];return anchor!==void 0&&anchor.c!==void 0&&anchor.c!=="reasoning"});for(const id of classCarrying){const anchor=anchors[id];const loose=candidates.some(c=>!claimedCandidates.has(c.id)&&(anchor.r===void 0||anchor.r===c.message.role)&&(anchor.wh!==void 0&&anchor.sh!==void 0&&wordBagDigest(canonicalTextOf(c.message.text??""))===anchor.wh&&(()=>{const d=hammingHex(anchor.sh,simhashHex(canonicalTextOf(c.message.text??"")));return d>=0&&d<=GAP_SIMHASH_MAX_HAMMING})()));if(loose)plan2.nearDupResidual.push(id);else plan2.absentEverywhere.push(id)}}if(plan2.unmatched.length>0){const noToolWitnesses=new Map;for(const cand of candidates){if(claimedCandidates.has(cand.id))continue;const t=cand.message.toolCallId;if(t===void 0||t==="")continue;const nt2=normalizedIdentityNoToolCallId(cand.message);const bucket=noToolWitnesses.get(nt2);if(bucket===void 0)noToolWitnesses.set(nt2,[t]);else bucket.push(t)}for(const id of plan2.unmatched){const anchor=anchors[id];if(anchor===void 0||anchor.m===void 0||anchor.t===void 0)continue;const witnesses=noToolWitnesses.get(anchor.m);if(witnesses===void 0)continue;if(witnesses.some(w2=>w2!==anchor.t))plan2.idRewriteSuspects++}}let churnTokens=0;for(const c of candidates)churnTokens+=defaultCountTokens(c.message.text??"");let claimedChurnTokens=0;for(const cid of claimedCandidates){const m2=byId2.get(cid);if(m2!==void 0)claimedChurnTokens+=defaultCountTokens(m2.text??"")}plan2.churnTokens=churnTokens;plan2.claimedChurnTokens=claimedChurnTokens;return plan2}function rewriteBlocks(blocks,claims){if(claims.size===0)return false;let touched=false;for(const block of blocks){const lists=[block.effectiveMessageIds,block.directMessageIds];for(const list of lists){if(list===void 0)continue;for(let i=0;i<list.length;i++){const replacement=claims.get(list[i]);if(replacement===void 0||replacement.length===0)continue;const keep=replacement.filter(t=>!list.includes(t));if(keep.length===0){list.splice(i,1);i--;touched=true;continue}list.splice(i,1,...keep);i+=keep.length-1;touched=true}}}return touched}function reconcileFoldCoverage(session,msgs,opts={}){const mode=opts.mode??resolveFoldReconcileMode(process.env);if(mode==="off"){resetFoldDriftState(session);return{kind:"off",missing:0,claims:0,byPos:0,byTool:0,byTwin:0,bySim:0,byOrder:0,byNorm:0,byTurn:0,byImage:0,byShape:0,reaped:0,unmatched:0,expectedRetired:0}}const blocks=session.state?.blocks??[];const covered=coveredIdsOf(blocks);for(const id of recoveryCandidateIds(blocks))covered.add(id);if(covered.size===0){resetFoldDriftState(session);return{kind:"noop",missing:0,claims:0,byPos:0,byTool:0,byTwin:0,bySim:0,byOrder:0,byNorm:0,byTurn:0,byImage:0,byShape:0,reaped:0,unmatched:0,expectedRetired:0}}if(msgs.length<SIDE_REQUEST_MAX_MSGS||opts.inboundMessageCount!==void 0&&opts.inboundMessageCount<SIDE_REQUEST_MAX_MSGS){return{kind:"noop",missing:0,claims:0,byPos:0,byTool:0,byTwin:0,bySim:0,byOrder:0,byNorm:0,byTurn:0,byImage:0,byShape:0,reaped:0,unmatched:0,expectedRetired:0}}if(!session.metadata)return{kind:"noop",missing:0,claims:0,byPos:0,byTool:0,byTwin:0,bySim:0,byOrder:0,byNorm:0,byTurn:0,byImage:0,byShape:0,reaped:0,unmatched:0,expectedRetired:0};let anchors=session.metadata[METADATA_ANCHORS]??{};const oldOrder=session.metadata[METADATA_ORDER]??[];const storedRaw=session.metadata[METADATA_POSITIONS];let positions;if(Array.isArray(storedRaw)){positions=storedRaw.length===oldOrder.length?{ids:oldOrder,canon:storedRaw}:void 0}else if(storedRaw!==void 0&&Array.isArray(storedRaw.ids)&&Array.isArray(storedRaw.canon)){positions={ids:storedRaw.ids,canon:storedRaw.canon}}const byId2=new Map;for(const m2 of msgs)if(m2.id!==void 0)byId2.set(m2.id,m2);if(opts.storedMessages!==void 0&&opts.storedMessages.length>0){const sById=new Map;for(const m2 of opts.storedMessages)if(m2.id!==void 0)sById.set(m2.id,m2);const sCtx=turnContexts(opts.storedMessages);let changed=false;const upgraded={};for(const[id,a]of Object.entries(anchors)){if(a.p===void 0&&a.r==="assistant"&&a.t===void 0&&!byId2.has(id)){const sm=sById.get(id);if(sm!==void 0){upgraded[id]=anchorFrom(sm,sCtx.get(id));changed=true;continue}}upgraded[id]=a}if(changed)anchors=upgraded}const expected=session.metadata[METADATA_EXPECTED_REBASE]??{};const classifyCarrier=typeof session.metadata.pluginAgent==="string"?oneShotCarrierPaths[session.metadata.pluginAgent]:void 0;if(classifyCarrier!==void 0){for(const m2 of msgs){const id=m2.id;if(id===void 0||anchors[id]!==void 0||expected[id]!==void 0)continue;const path53=classifyCarrier(m2);if(path53!==void 0)expected[id]=path53}}let expectedSize=Object.keys(expected).length;const plan2=planReconciliation(oldOrder,anchors,msgs,covered,positions,new Set(Object.keys(expected)));if(plan2.pass0Desync){log("warn",`[fold-reconcile] Pass 0 disabled: stored positional copy desynced from order backbone (session=${session.id}, copyIds=${positions?.ids.length??-1}, backbone=${oldOrder.length})`)}if(process.env.FOLD_RECONCILE_DEBUG==="1"){const active=blocks.filter(b2=>b2.active).length;const sample=msgs.slice(0,6).map(m2=>`${m2.role}/${m2.contentType??"-"}/${m2.id??"?"}`);process.stderr.write(`[fold-reconcile-dbg] blocks=${blocks.length} active=${active} covered=${covered.size} oldOrder=${oldOrder.length} positions=${positions?.canon.length??-1} missing=${plan2.unmatched.length+plan2.claims.size} claims=${plan2.claims.size} expected=${expectedSize} byPos=${plan2.byPos} resyncs=${plan2.resyncs} byTool=${plan2.byTool} byTwin=${plan2.byTwin} bySim=${plan2.bySim} byOrder=${plan2.byOrder} byNorm=${plan2.byNorm} byTurn=${plan2.byTurn} byImage=${plan2.byImage} unmatched=${plan2.unmatched.length} | msgs[0..5]=${sample.join(" | ")}
|
|
901
|
-
`)}let offloadPending=session.metadata[METADATA_OFFLOAD_PENDING]??{};if(plan2.unmatched.length>0&&opts.storedRowLookup!==void 0){const needed=[];for(const id of plan2.unmatched){if(expected[id]!==void 0||offloadPending[id]!==void 0)continue;needed.push(id);if(needed.length>=MAX_REBASE_LOOKUP_PER_PASS)break}if(needed.length>0){const rows=opts.storedRowLookup(needed);if(rows!==null){const best=new Map;for(const row of rows){const cur=best.get(row.msgId);if(cur===void 0||row.seq>cur.seq)best.set(row.msgId,{seq:row.seq,content:row.content})}for(const id of needed){const hit=best.get(id);if(hit===void 0)continue;const content=hit.content;const hasImageMarker=content.includes('"rawAnthropicBlock"')&&content.includes('"type":"image"')||content.includes('"imageBase64":"')||content.includes('"text":"[image]"')||content.includes("data:image/");const hasCarrierMarker=classifyCarrier!==void 0&&dshCarrierRawMarkers.some(mk=>content.includes(mk));if(hasCarrierMarker){let parsed;try{parsed=JSON.parse(content)}catch{continue}if(typeof parsed==="object"&&parsed!==null){const path53=classifyCarrier(parsed);if(path53!==void 0){expected[id]=path53;continue}}}if(hasImageMarker)offloadPending[id]=1}}}}const pendingIds=Object.keys(offloadPending);if(pendingIds.length>0){const claimedTargets=new Set;for(const targets of plan2.claims.values())for(const t of targets)claimedTargets.add(t);const posInOld=new Map;oldOrder.forEach((id,i)=>posInOld.set(id,i));for(const id of pendingIds){if(byId2.has(id)){delete offloadPending[id];continue}const oi2=posInOld.get(id);if(oi2===void 0){delete offloadPending[id];continue}const nid=plan2.newOrder[oi2];if(nid===void 0||nid===id||covered.has(nid)||claimedTargets.has(nid))continue;const nm=byId2.get(nid);if(nm===void 0||nm.toolCallId!==void 0&&nm.toolCallId!=="")continue;const anchor=anchors[id];if(anchor!==void 0&&anchor.r!==void 0&&nm.role!==anchor.r)continue;if(storedMessageCarriesImage(nm))continue;expected[id]="image-offload";delete offloadPending[id]}}const prunedPending=pruneRebaseMemo(offloadPending);if(Object.keys(prunedPending).length>0)session.metadata[METADATA_OFFLOAD_PENDING]=prunedPending;else delete session.metadata[METADATA_OFFLOAD_PENDING];if(Object.keys(expected).length>0)session.metadata[METADATA_EXPECTED_REBASE]=expected;else delete session.metadata[METADATA_EXPECTED_REBASE];expectedSize=Object.keys(expected).length;let turnCtx;const ctxOf=id=>{if(turnCtx===void 0)turnCtx=turnContexts(msgs);return turnCtx.get(id)};const turnCtxFor=message=>message!==void 0&&message.id!==void 0&&message.role==="assistant"&&(message.toolCallId===void 0||message.toolCallId==="")?ctxOf(message.id):void 0;const nextAnchors={};let anchorCount=0;for(const id of covered){const claimed=plan2.claims.get(id);if(claimed!==void 0){for(const nid of new Set(claimed)){if(nextAnchors[nid]!==void 0)continue;const message2=byId2.get(nid);if(message2===void 0)continue;if(anchorCount<MAX_ANCHORS){nextAnchors[nid]=anchorFrom(message2,turnCtxFor(message2));anchorCount++}else if(message2.toolCallId!==void 0&&message2.toolCallId!==""){nextAnchors[nid]=liteToolAnchorFrom(message2)}}continue}const prior=anchors[id];if(prior!==void 0){if(anchorCount>=MAX_ANCHORS){nextAnchors[id]=prior;continue}if(prior.t!==void 0&&prior.m===void 0){const message2=byId2.get(id);nextAnchors[id]=message2!==void 0?anchorFrom(message2):prior}else if(prior.p===void 0&&prior.r==="assistant"&&prior.t===void 0){const message2=byId2.get(id);nextAnchors[id]=message2!==void 0?anchorFrom(message2,ctxOf(id)):prior}else if(prior.c===void 0){const message2=byId2.get(id);nextAnchors[id]=message2!==void 0?anchorFrom(message2,turnCtxFor(message2)):prior}else{nextAnchors[id]=prior}anchorCount++;continue}const message=byId2.get(id);if(message!==void 0){if(anchorCount<MAX_ANCHORS){nextAnchors[id]=anchorFrom(message,turnCtxFor(message));anchorCount++}else if(message.toolCallId!==void 0&&message.toolCallId!==""){nextAnchors[id]=liteToolAnchorFrom(message)}}}const nextOrder=plan2.newOrder.slice(-MAX_ORDER);if(plan2.nextCanon!==void 0){session.metadata[METADATA_POSITIONS]={ids:nextOrder,canon:plan2.nextCanon.slice(-MAX_ORDER)}}const absentSet=new Set(plan2.absentEverywhere);let witness=session.metadata[METADATA_EPISODE_ORDER];const episodeActive=(session.metadata[METADATA_DRIFT_STREAK]??0)>0;if(witness===void 0&&episodeActive&&oldOrder.length>0){witness=oldOrder.slice(-MAX_ORDER);session.metadata[METADATA_EPISODE_ORDER]=witness}const continuityBaseline=witness??oldOrder;let wireContinuity=false;let tailTruncated=false;if(continuityBaseline.length>0){const witness2=continuityBaseline;const inboundSet=new Set(plan2.newOrder);const witnessSet=new Set(witness2);const commonWitness=witness2.filter(id=>inboundSet.has(id));const commonInbound=plan2.newOrder.filter(id=>witnessSet.has(id));wireContinuity=commonWitness.length>0&&witness2.slice(witness2.length-commonWitness.length).every(id=>inboundSet.has(id))&&plan2.newOrder.slice(0,commonInbound.length).every(id=>witnessSet.has(id));const commonPrefix=commonInbound;tailTruncated=commonPrefix.length>0&&commonPrefix.length<witness2.length&&witness2.slice(0,commonPrefix.length).every(id=>inboundSet.has(id))&&plan2.newOrder.slice(0,commonPrefix.length).every(id=>witnessSet.has(id))}const markerChurnExplained=(opts.markerStripped??0)>0;const realUnmatched=plan2.unmatched.filter(id=>expected[id]===void 0);const accountedHere=plan2.unmatched.length-realUnmatched.length;const expectedNote=accountedHere>0?`; ${accountedHere} more covered id(s) accounted as expected host behavior (#5142)`:"";const reasoningOnlyDrop=plan2.claims.size===0&&realUnmatched.length>0&&realUnmatched.every(id=>anchors[id]?.c==="reasoning");const nonReasoningUnmatched=realUnmatched.filter(id=>{const cls=anchors[id]?.c;return cls!==void 0&&cls!=="reasoning"}).length;const classCarryingResidual=realUnmatched.filter(id=>{const cls=anchors[id]?.c;return cls!==void 0&&cls!=="reasoning"});const shapeExplained=plan2.byShape>0||classCarryingResidual.length>0&&plan2.nearDupResidual.length>=.6*classCarryingResidual.length;const truncationExplained=classCarryingResidual.length>0&&plan2.nearDupResidual.length===0&&classCarryingResidual.every(id=>absentSet.has(id))&&wireContinuity;const tailTruncationExplained=classCarryingResidual.length>0&&plan2.nearDupResidual.length===0&&classCarryingResidual.every(id=>absentSet.has(id))&&tailTruncated;const totalDrift=plan2.claims.size===0&&realUnmatched.length>0&&!reasoningOnlyDrop&&!markerChurnExplained&&!shapeExplained&&!truncationExplained&&!tailTruncationExplained;const epochProtected=session.metadata[METADATA_EPOCH_CONFIRM]===true||totalDrift&&nonReasoningUnmatched>=FOLD_DRIFT_ESCALATE_MIN_UNMATCHED;const prevCov=session.metadata[METADATA_FOLD_COVERAGE]??{};const nextCov={};let covCount=0;for(const block of blocks){const bid=block.blockId;if(bid===void 0||bid==="")continue;const ids=(block.effectiveMessageIds??[]).filter(id=>!isResponsesTurnSeparatorId(id)&&expected[id]===void 0);if(ids.length===0)continue;let p2=0,r=0;for(const id of ids){if(byId2.has(id))p2++;else if(plan2.claims.has(id))r++}const rec={p:p2,r,t:ids.length};if(prevCov[bid]?.e===1||p2+r>0)rec.e=1;const hardIds=ids.filter(id=>anchors[id]?.c!=="reasoning");const gone=hardIds.length>0&&2*(p2+r)<hardIds.length;const absentHard=hardIds.filter(id=>!byId2.has(id)&&!plan2.claims.has(id));const structurallyAbsent=absentHard.length>0&&absentHard.every(id=>absentSet.has(id))&&(wireContinuity||tailTruncated);if(gone&&!structurallyAbsent){if(rec.e===1)rec.z=(prevCov[bid]?.z??0)+1}else{rec.z=0}if(covCount>=MAX_ANCHORS)continue;nextCov[bid]=rec;covCount++}let reapedCount=0;if(mode==="repair"&&session.metadata.pluginAgent===void 0&&!epochProtected){const ripe=new Set;for(const block of blocks){const bid=block.blockId;if(bid!==void 0&&(nextCov[bid]?.z??0)>=FOLD_DRIFT_ESCALATE_PASSES)ripe.add(bid)}if(ripe.size>0){const liveRawIds=new Set(msgs.map(m2=>m2.id));const reaped=reapDestroyedSubstrate(session,ripe,liveRawIds,opts.log??(()=>{}));reapedCount=reaped.length;if(reapedCount>0){const deadIds=new Set;for(const block of blocks){if(block.blockId===void 0||!ripe.has(block.blockId))continue;delete nextCov[block.blockId];for(const id of block.effectiveMessageIds??[])deadIds.add(id);for(const id of block.directMessageIds??[])deadIds.add(id)}for(const id of deadIds)delete nextAnchors[id];for(let i=nextOrder.length-1;i>=0;i--){if(deadIds.has(nextOrder[i]))nextOrder.splice(i,1)}const storedPositions=session.metadata[METADATA_POSITIONS];const positionIds=storedPositions?.ids;if(Array.isArray(positionIds)&&positionIds!==nextOrder){for(let i=positionIds.length-1;i>=0;i--){if(deadIds.has(positionIds[i]))positionIds.splice(i,1)}}recordConflict(session,"orphan-reap",`reaped ${reapedCount} zombie fold block(s) [${reaped.join(", ")}]: covered substrate majority-absent for ${FOLD_DRIFT_ESCALATE_PASSES} consecutive passes (#2695)`)}}}session.metadata[METADATA_FOLD_COVERAGE]=nextCov;if(plan2.claims.size>0&&mode==="repair"){rewriteBlocks(blocks,plan2.claims);const prior=new Set(session.state?.lastPassIds??[]);for(const targets of plan2.claims.values()){for(const newId of targets)prior.add(newId)}session.state.lastPassIds=[...prior]}session.metadata[METADATA_ANCHORS]=nextAnchors;session.metadata[METADATA_ORDER]=nextOrder;const tag=opts.sessionId===void 0?"":`[${opts.sessionId}] `;const unfoldedDrift=mode==="repair"?Math.max(0,(plan2.churnTokens??0)-(plan2.claimedChurnTokens??0)):plan2.churnTokens??0;const driftTok=unfoldedDrift>0?` (~${unfoldedDrift} tok unfolded in churn region)`:"";const prevStreak=session.metadata[METADATA_DRIFT_STREAK]??0;if(!totalDrift){if(prevStreak!==0)resetFoldDriftState(session);if(shapeExplained&&session.metadata[METADATA_SHAPE_NOTED]!==true){session.metadata[METADATA_SHAPE_NOTED]=true;opts.log?.("info",`${tag}[fold-reconcile] ${classCarryingResidual.length} covered id(s) churned shape (protocol switch / offload) with word evidence intact \u2014 re-anchored ${plan2.byShape}, ${plan2.nearDupResidual.length} near-duplicate residual kept under watch (#3641); fold state retained`)}if(tailTruncationExplained&&session.metadata[METADATA_TAIL_TRUNC_NOTED]!==true&&session.metadata[METADATA_TRUNC_NOTED]!==true){session.metadata[METADATA_TAIL_TRUNC_NOTED]=true;opts.log?.("info",`${tag}[fold-reconcile] ${classCarryingResidual.length} covered id(s) no longer on the wire with no replacement evidence and the resent history is a prefix of the pre-rewind wire \u2014 host rewind/undo removed the newest turns (incl. a folded span); fold snapshot retained, nothing reaped (#3724)`)}else if(truncationExplained&&session.metadata[METADATA_TRUNC_NOTED]!==true&&session.metadata[METADATA_TAIL_TRUNC_NOTED]!==true){session.metadata[METADATA_TRUNC_NOTED]=true;opts.log?.("info",`${tag}[fold-reconcile] ${classCarryingResidual.length} covered id(s) no longer on the wire with no replacement evidence and remaining substrate present \u2014 host-side truncation/dropped history, fold snapshot retained (#2695/#3641)`)}if(expectedSize>0&&session.metadata[METADATA_EXPECTED_REBASE_NOTED]!==true){let expectedSuppressed=0;for(const id of covered)if(!byId2.has(id)&&expected[id]!==void 0)expectedSuppressed++;if(expectedSuppressed>0){session.metadata[METADATA_EXPECTED_REBASE_NOTED]=true;let carriers=0,offloads=0;for(const reason of Object.values(expected)){if(reason==="image-offload")offloads++;else carriers++}opts.log?.("info",`${tag}[fold-reconcile] ${expectedSize} covered id(s) retired by expected host behavior (${carriers} one-shot carrier(s), ${offloads} image offload rewrite(s)) \u2014 excluded from drift accounting, near-zero steady state restored (#5142)`)}}}else{const streak=prevStreak+1;if(prevStreak===0&&oldOrder.length>0&&session.metadata[METADATA_EPISODE_ORDER]===void 0){session.metadata[METADATA_EPISODE_ORDER]=oldOrder.slice(-MAX_ORDER)}session.metadata[METADATA_DRIFT_STREAK]=streak;if(prevStreak===0)session.metadata[METADATA_DRIFT_SINCE]=Date.now();if(streak>=FOLD_DRIFT_ESCALATE_PASSES&&nonReasoningUnmatched>=FOLD_DRIFT_ESCALATE_MIN_UNMATCHED&&session.metadata[METADATA_DRIFT_ESCALATED]!==true){session.metadata[METADATA_DRIFT_ESCALATED]=true;const dshWitness=dshNativeCompactionWitness(session);if(dshWitness!==void 0){recordConflict(session,"native-compaction-inferred",`compression substrate destroyed (total-loss drift, no checkpoint marker); bili refused ${dshWitness} client-native compaction call(s) this session (#1729/#2028) \u2014 attributed to client-native compaction [inferred] (${realUnmatched.length} covered id(s) missing, #2193/#2709)`)}const since=session.metadata[METADATA_DRIFT_SINCE];const span=typeof since==="number"?`, ${Math.max(1,Math.round((Date.now()-since)/6e4))} min so far`:"";session.metadata[METADATA_EPOCH_CONFIRM]=true;if(opts.log!==void 0){opts.log("error",`${tag}[fold-reconcile] fold epoch confirmation required: ${realUnmatched.length} covered id(s) missing with NO anchor match and NO word evidence for ${streak} consecutive passes${span}${expectedNote} \u2014 the resent history shares nothing with the fold substrate (wholesale replacement: host-native compaction outside bili's knowledge #1729/#2193, or a brand-new conversation on the same session id). Folding is paused for this session until the histories realign (old history resent or a fresh fold on the new one starts a new epoch); bili keeps the existing snapshot \u2014 nothing is deleted (#3641)${driftTok}`)}}}if(realUnmatched.length===0&&plan2.claims.size===0){return{kind:"resend",missing:0,claims:0,byPos:0,byTool:0,byTwin:0,bySim:0,byOrder:0,byNorm:0,byTurn:0,byImage:0,byShape:0,reaped:reapedCount,unmatched:0,expectedRetired:expectedSize}}if(opts.log!==void 0){if(plan2.claims.size>0&&mode==="repair"){opts.log(realUnmatched.length>0?"warn":"info",`${tag}[fold-reconcile] resent history drifted: ${plan2.claims.size+realUnmatched.length} covered id(s) missing${expectedNote} \u2014 reanchored ${plan2.claims.size} (${plan2.byPos} positional${plan2.resyncs>0?`, ${plan2.resyncs} order break(s) resynced`:""}, ${plan2.byTool} by toolCallId${plan2.byTwin>0?`, ${plan2.byTwin} by toolCallId twin`:""}${plan2.bySim>0?`, ${plan2.bySim} by simhash corroboration`:""}${plan2.byOrder>0?`, ${plan2.byOrder} by order bracket`:""}, ${plan2.byNorm} by normalized identity${plan2.byTurn>0?`, ${plan2.byTurn} by assistant-turn key`:""}${plan2.byImage>0?`, ${plan2.byImage} by image-capability variant`:""}${plan2.byShape>0?`, ${plan2.byShape} by shape census`:""}) onto churned bytes, ${realUnmatched.length} unmatched re-enter the wire unfolded${plan2.idRewriteSuspects>0?`; ${plan2.idRewriteSuspects} suspected host-rewritten tool-call ids (identical content under a different toolCallId \u2014 #2396)`:""} (#1921)${driftTok}`)}else if(plan2.claims.size>0){opts.log("warn",`${tag}[fold-reconcile] resent history drifted: ${plan2.claims.size+realUnmatched.length} covered id(s) missing${expectedNote}, ${plan2.claims.size} matchable by anchor (${plan2.byPos} positional${plan2.resyncs>0?`, ${plan2.resyncs} resynced`:""}, ${plan2.byTool} toolCallId${plan2.byTwin>0?`, ${plan2.byTwin} twin`:""}${plan2.bySim>0?`, ${plan2.bySim} simhash`:""}${plan2.byOrder>0?`, ${plan2.byOrder} order-bracket`:""}, ${plan2.byNorm} normalized${plan2.byTurn>0?`, ${plan2.byTurn} turn key`:""}${plan2.byImage>0?`, ${plan2.byImage} image`:""}) but reconcile=warn made no repair (#1921)${driftTok}`)}else if(reasoningOnlyDrop){opts.log("info",`${tag}[fold-reconcile] ${realUnmatched.length} covered reasoning core(s) dropped by the host (cross-model replay discards structured thinking; every text/tool core intact) \u2014 fold substrate healthy, tolerated (#2193 follow-up)`)}else if(markerChurnExplained){if(session.metadata[METADATA_MARKER_CHURN_NOTED]!==true){session.metadata[METADATA_MARKER_CHURN_NOTED]=true;opts.log("info",`${tag}[fold-reconcile] ${realUnmatched.length} covered id(s) missing with no anchor match${expectedNote}, but this pass stripped ${opts.markerStripped} raw marker artifact(s) \u2014 covered ids minted from marker-laden bytes churn once the strip engine cleans the resent history; benign on stateless resend (content still on the wire, re-folds re-cover), tolerated (#2815/#2789)`)}}else if(session.metadata[METADATA_DRIFT_ESCALATED]!==true){opts.log("warn",`${tag}[fold-reconcile] resent history drifted: ${realUnmatched.length} covered id(s) missing with no anchor match${expectedNote} \u2014 mutation (content edit invalidates content-hash refs, fold silently lost) or client-side deletion/truncation (benign, message no longer on the wire)${plan2.idRewriteSuspects>0?`; ${plan2.idRewriteSuspects} of them have an inbound twin with identical normalized content under a different toolCallId \u2014 consistent with the host rewriting authoritative tool-call ids across provider projections (host contract: keep tool-call ids byte-stable per conversation, #2396)`:""} (#1921)${driftTok}`)}}return{kind:plan2.claims.size>0?mode==="repair"?"reanchored":"unmatched":"unmatched",missing:plan2.claims.size+realUnmatched.length,claims:plan2.claims.size,byPos:plan2.byPos,byTool:plan2.byTool,byTwin:plan2.byTwin,bySim:plan2.bySim,byOrder:plan2.byOrder,byNorm:plan2.byNorm,byTurn:plan2.byTurn,byImage:plan2.byImage,byShape:plan2.byShape,reaped:reapedCount,unmatched:realUnmatched.length,expectedRetired:expectedSize}}function noteSystemPromptFingerprint(session,system,opts={}){if(!session.metadata)return;const text2=system===void 0||system===null?"":JSON.stringify(system)??"";const fp2=system===void 0||system===null?"-":createHash12("sha256").update(text2).digest("hex").slice(0,16);const prev=session.metadata[METADATA_SYSTEM_FP];if(prev!==void 0&&prev.fp!==fp2){if(opts.log!==void 0){opts.log("info",`${opts.sessionId===void 0?"":`[${opts.sessionId}] `}[fold-reconcile] system prompt changed (${prev.size} \u2192 ${text2.length} chars); fold state unaffected (#1921)`)}}session.metadata[METADATA_SYSTEM_FP]={fp:fp2,size:text2.length}}function noteCanonicalSystemFingerprint(session,canonical2){if(!session.metadata)return;const text2=canonical2===void 0||canonical2===null?"":JSON.stringify(canonical2)??"";const fp2=canonical2===void 0||canonical2===null?"-":createHash12("sha256").update(text2).digest("hex").slice(0,16);session.metadata[METADATA_CANONICAL_SYS_FP]={fp:fp2,size:text2.length}}init_logger();var MEMBERSHIP_RECORD_SCALE_RATIO=.25;function collectRequestIds(envelopeIds,msgs){const out=[];const seen=new Set;if(Array.isArray(envelopeIds)){for(const v2 of envelopeIds){if(typeof v2==="string"&&v2.length>0&&v2.length<=512&&!v2.startsWith("acp_summary_")&&!seen.has(v2)){seen.add(v2);out.push(v2)}}if(out.length>0)return out}for(const m2 of msgs){const id=m2.toolCallId;if(typeof id==="string"&&id.length>0&&!seen.has(id)){seen.add(id);out.push(id)}}return out}function isForeignMembership(m2){return m2?.member===false}function probeRequestMembership(session,ids,payloadUpper){const t=session.transient;if(!t)return null;if(ids.length===0){delete t.requestMembership;return null}const needle=t.latestKnownMsgId??null;const member=needle===null||ids.includes(needle);const verdict={member,needle};t.requestMembership=verdict;log("debug",`[${session.id}] [#4805] membership probe: ids=${ids.length} needle=${member?"member":"miss"} payloadUpper=${payloadUpper}`);const referenceScale=session.stats.lastInputTokens>0?session.stats.lastInputTokens:t.needlePayloadUpper??0;const mainScale=payloadUpper>=referenceScale*MEMBERSHIP_RECORD_SCALE_RATIO;if(member||mainScale){t.latestKnownMsgId=ids[ids.length-1];t.needlePayloadUpper=payloadUpper}return verdict}init_billing();init_util();init_proxy_tool_result();var FULL_DETAIL_LINES=512;var BOOT_ID=randomUUID3();var SWITCH_COLD_ROUNDS=4;var WARM_HIT_PCT=85;var SIZE_BUCKET_TOK=2e4;var LOST_LOGGED_KEY="foldCoverageLostLogged";function median(xs2){if(xs2.length===0)return null;const s3=[...xs2].sort((x,y)=>x-y);const m2=s3.length>>1;return s3.length%2===1?s3[m2]:Math.round((s3[m2-1]+s3[m2])/2)}var LEDGER_KEY="cacheLedger";function refNum3(ref){return Number(ref.replace(/\D/g,""))||0}function round12(n){return Math.round(n*10)/10}function prefixTokensBeforeRef(session,ref){const byRef=session.state?.messageRefs?.byRef;const snap=session.state?.tokenSnapshot;if(!byRef||!snap||refNum3(ref)===0)return 0;let n=0;for(const key2 of Object.keys(byRef)){if(refNum3(key2)<refNum3(ref))n+=snap[key2]??0}return n}var SEAM_BODY_CAP=512*1024;var SEAM_EVENTS_CAP=8;var PROVIDER_TTL_GAP_MS=6e5;var BODY_FULL_CAP=8*1024*1024;var INBOUND_MSG_CAP=8192;var GENERATED_METERING_FIELDS=["thinkingTokens"];function originEvidenceJson(m2){const r=m2;if(!GENERATED_METERING_FIELDS.some(k2=>k2 in r))return JSON.stringify(m2);const stripped={};for(const[k2,v2]of Object.entries(r)){if(!GENERATED_METERING_FIELDS.includes(k2))stripped[k2]=v2}return JSON.stringify(stripped)}var captures=new AsyncLocalStorage3;var captureOrder=0;async function withCacheCapture(session,fn){if(!session)return fn();return captures.run({session,requestId:randomUUID3(),round:0},async()=>{try{return await fn()}finally{const capture2=captures.getStore();if(capture2){delete capture2.sentBody;delete capture2.inBody;delete capture2.imageFacts}}})}function pendingCapture(session){const capture2=captures.getStore();return capture2?.session===session?capture2:session.transient??={}}function lastForwardedBody(session){return pendingCapture(session).sentBody}function pendingEvidencePair(session){const pending=pendingCapture(session);return{sentBody:pending.sentBody,inBody:pending.inBody}}function noteInboundMessages(session,msgs){const transient2=pendingCapture(session);if(msgs.length>INBOUND_MSG_CAP){delete transient2.inBody;transient2.inBody={msgs:msgs.length,fps:[],meta:[]};return}const fps=[];const meta=[];for(const m2 of msgs){const j2=originEvidenceJson(m2);fps.push(createHash13("sha256").update(j2).digest("hex").slice(0,16));meta.push({role:String(m2.role??"?"),len:j2.length,cls:inboundMessageClass(m2)})}transient2.inBody={msgs:msgs.length,fps,meta}}function inboundMessageClass(m2){const r=m2;if(r.tool_calls!==void 0||r.tool_use!==void 0)return"tool-call";const content=r.content;if(typeof content==="string")return"text";if(Array.isArray(content)){for(const part of content){const t=part?.type;if(t==="image"||t==="image_url"||t==="input_image"||t==="inline_data")return"image"}return"text"}return"other"}function firstDivergentInboundMsg(prev,cur){const n=Math.min(prev.fps.length,cur.fps.length);for(let i=0;i<n;i++){if(prev.fps[i]!==cur.fps[i])return i}return null}var lastClientAbort=new WeakMap;function recordContextObservation(session,tokens,source){if(!Number.isFinite(tokens)||tokens<0){delete session.metadata?.publicContextObservation;return}session.metadata??={};session.metadata.publicContextObservation={sessionId:session.id,tokens,source,at:Date.now(),generation:randomUUID3()}}function currentContextObservation(session){const raw=session.metadata?.publicContextObservation;if(!raw||typeof raw!=="object")return void 0;const o=raw;if(o.sessionId!==session.id||typeof o.tokens!=="number"||!Number.isFinite(o.tokens)||o.tokens<0||o.source!=="usage"&&o.source!=="estimate"||typeof o.at!=="number"||!Number.isFinite(o.at)||o.at<0||typeof o.generation!=="string"||o.generation.length===0)return void 0;return{sessionId:session.id,tokens:o.tokens,source:o.source,at:o.at,generation:o.generation}}function noteClientAbort(session){lastClientAbort.set(session,Date.now())}function credentialFingerprint(headers){if(!headers)return void 0;let cred;for(const[name,value]of Object.entries(headers)){const n=name.toLowerCase();if(n==="authorization"||n==="x-api-key"||n==="api-key"||n==="x-goog-api-key"){const v2=value.trim().replace(/^Bearer\s+/i,"").trim();if(v2!==""){const m2=/^SDK-HMAC-SHA256\s+Access=([^\s,]+)/i.exec(v2);cred=m2!==null?`sdk-hmac:${m2[1]}`:v2;break}}}if(cred===void 0)return void 0;return"sha256:"+createHash13("sha256").update(cred,"utf8").digest("hex").slice(0,12)}function canonicalJson2(v2){if(v2===null||typeof v2!=="object")return JSON.stringify(v2)??"null";if(Array.isArray(v2))return"["+v2.map(canonicalJson2).join(",")+"]";const obj=v2;const keys=Object.keys(obj).filter(k2=>obj[k2]!==void 0).sort();return"{"+keys.map(k2=>JSON.stringify(k2)+":"+canonicalJson2(obj[k2])).join(",")+"}"}function generationParamFp(body){if(!body||typeof body!=="object")return void 0;const parts={};if(body.thinking!==void 0&&body.thinking!==null)parts.thinking=body.thinking;if(body.output_config!==void 0&&body.output_config!==null)parts.output_config=body.output_config;if(typeof body.reasoning_effort==="string"&&body.reasoning_effort!=="")parts.reasoning_effort=body.reasoning_effort;const r=body.reasoning;if(r!==null&&typeof r==="object"){const re2=r.effort;if(typeof re2==="string"&&re2!=="")parts["reasoning.effort"]=re2}const gc=body.generationConfig;if(gc!==null&&typeof gc==="object"){const tc=gc.thinkingConfig;if(tc!==void 0&&tc!==null)parts.thinkingConfig=tc}if(Object.keys(parts).length===0)return void 0;return"sha256:"+createHash13("sha256").update(canonicalJson2(parts),"utf8").digest("hex").slice(0,16)}function noteForwardedBody(session,body,msgs,keyFp,effFp){const buf=Buffer.from(body,"utf8");const digest=createHash13("sha256").update(buf).digest("hex");const transient2=pendingCapture(session);const prior=transient2.sentBody;const samePayload=prior!==void 0&&prior.digest===digest;transient2.sentBody={order:++captureOrder,requestId:"requestId"in transient2?transient2.requestId:void 0,round:"round"in transient2?++transient2.round:void 0,head:buf.byteLength>SEAM_BODY_CAP?Buffer.from(buf.subarray(0,SEAM_BODY_CAP)):buf,bytes:buf.byteLength,msgs:msgs??(samePayload?prior.msgs:null),digest,full:buf.byteLength<=BODY_FULL_CAP?buf:samePayload?prior.full:null,keyFp:keyFp??(samePayload?prior.keyFp:void 0),effFp:effFp??(samePayload?prior.effFp:void 0)};if("round"in transient2&&transient2.round>1){delete transient2.imageFacts;delete transient2.inBody}if(session.stats.contextTokensSource!==void 0)recordContextObservation(session,session.stats.contextTokens,"estimate");else delete session.metadata?.publicContextObservation}var LEARNED_IMAGE_COST_TTL_MS=24*60*60*1e3;var LEARNED_IMAGE_COST_ALPHA=.5;var LEARNED_PER_IMAGE_MAX=1e5;var LEARNED_VARIANCE_BAND=15;var imageFactsLastSent=new WeakMap;function noteForwardedImageFacts(session,facts){const capture2=captures.getStore();if(capture2?.session===session){capture2.imageFacts=facts;return}imageFactsLastSent.set(session,facts)}function settleImageLearning(session,billedTotal){const capture2=captures.getStore();const facts=capture2?.session===session?capture2.imageFacts:imageFactsLastSent.get(session);if(!facts)return;if(capture2?.session===session)delete capture2.imageFacts;else imageFactsLastSent.delete(session);if(facts.nImages<=0||billedTotal<=0)return;const observed=billedTotal-facts.textSide;if(observed<=0)return;const per=observed/facts.nImages;if(!(per>=1&&per<=LEARNED_PER_IMAGE_MAX))return;const store2=session.metadata.learnedImageCosts??{};const prev=store2[facts.host];const fresh=!prev||typeof prev.cost!=="number"||prev.fp!==facts.fp;const cost=fresh?per:prev.cost*(1-LEARNED_IMAGE_COST_ALPHA)+per*LEARNED_IMAGE_COST_ALPHA;store2[facts.host]={cost,seen:fresh?1:(prev.seen??0)+1,ts:Date.now(),fp:facts.fp};session.metadata.learnedImageCosts=store2;markDirty(session)}function learnedImageReserve(session,host,nImages,fp2,cap,prior){if(nImages<=0)return void 0;const entry=session.metadata.learnedImageCosts?.[host];if(!entry||typeof entry.cost!=="number"||entry.seen<1)return void 0;if(Date.now()-entry.ts>LEARNED_IMAGE_COST_TTL_MS)return void 0;if(entry.fp!==fp2)return void 0;let per=cap>0?Math.min(entry.cost,cap):entry.cost;if(typeof prior==="number"&&prior>0){per=Math.min(per,LEARNED_VARIANCE_BAND*prior/nImages)}else{per=Math.min(per,LEARNED_PER_IMAGE_MAX)}return per*nImages}function seamLcp(a,b2){let lcp=0;const n=Math.min(a.length,b2.length);while(lcp<n&&a[lcp]===b2[lcp])lcp++;const msgsOf=s3=>{try{const p2=JSON.parse(s3.toString("utf8"));const arr=p2.messages??p2.input??p2.contents;return Array.isArray(arr)?arr:[]}catch{return[]}};const ma=msgsOf(a);const mb=msgsOf(b2);let i=0;const eq=(x,y)=>JSON.stringify(x)===JSON.stringify(y);while(i<Math.min(ma.length,mb.length)&&eq(ma[i],mb[i]))i++;return{lcpBytes:lcp,msgIndex:ma.length>0&&mb.length>0?i:null,prevMsgs:ma.length,curMsgs:mb.length}}function byteLcp(a,b2){const n=Math.min(a.length,b2.length);if(n===0||a[0]!==b2[0])return 0;let lo2=1;let hi2=n;while(lo2<hi2){const mid=lo2+hi2+1>>>1;if(Buffer.compare(a.subarray(0,mid),b2.subarray(0,mid))===0)lo2=mid;else hi2=mid-1}return lo2}function isMidInsertionAppend(prev,cur,lcp){if(cur.length<=prev.length||lcp>=prev.length)return false;const room=prev.length-lcp;let lo2=0;let hi2=room;while(lo2<hi2){const mid=lo2+hi2+1>>>1;if(Buffer.compare(prev.subarray(prev.length-mid),cur.subarray(cur.length-mid))===0)lo2=mid;else hi2=mid-1}return lcp+lo2===prev.length}function messagesArrayCloseOffset(body){const n=body.length;let depth=0;let inStr=false;let want=-1;let keyAt=-1;let i=0;while(i<n){const c=body[i];if(inStr){if(c===92){let j2=i;while(j2<n&&body[j2]===92)j2++;i=(j2-i)%2===1?j2+1:j2;continue}if(c===34){inStr=false;if(keyAt>=0){const key2=body.subarray(keyAt+1,i).toString("utf8");keyAt=-1;if(depth===1&&(key2==="messages"||key2==="input"||key2==="contents")){let j2=i+1;while(j2<n&&body[j2]<=32)j2++;if(body[j2]===58){j2++;while(j2<n&&body[j2]<=32)j2++;if(body[j2]===91)want=depth+1}}}i++;continue}let m3=n;const q2=body.indexOf(34,i+1);if(q2!==-1&&q2<m3)m3=q2;const b2=body.indexOf(92,i+1);if(b2!==-1&&b2<m3)m3=b2;i=m3;continue}if(c===34){inStr=true;keyAt=depth===1?i:-1;i++;continue}if(c===123||c===91){depth++;i++;continue}if(c===125||c===93){if(want!==-1&&c===93&&depth===want)return i;depth--;i++;continue}let m2=n;for(const code of[34,123,125,91,93]){const p2=body.indexOf(code,i+1);if(p2!==-1&&p2<m2)m2=p2}i=m2}return null}function detectSeam(session,led){const line=led.lines[led.lines.length-1];if(!line||line.unk===1||line.missed<=0)return;if(line.nb===1)return;const abortAt=lastClientAbort.get(session);if(abortAt!==void 0&&Math.abs(line.at-abortAt)<3e4){line.abortedNear=1;led.agg.abortCorrelated+=1}if(line.sw===1||line.pw===1||line.uw===1||line.rs===1||line.cause!==void 0||line.foldSeq!==null)return;if(!(line.tr>8192&&line.tr>.3*line.input))return;const agg=led.agg;const cur=pendingCapture(session).sentBody;const prev=session.transient?.settledBody;if(cur?.order!==void 0&&prev?.order!==void 0&&cur.order<=prev.order){line.evidence="out-of-order";return}const prevSampleAt=led.lines.length>=2?led.lines[led.lines.length-2].at:line.at;const ttlExpired=line.at-prevSampleAt>PROVIDER_TTL_GAP_MS;const bookProvider=()=>{line.prov=ttlExpired?"ttl":"side";if(ttlExpired){agg.providerTtlMisses+=1;agg.providerTtlMissed+=line.tr}else{agg.providerSideMisses+=1;agg.providerSideMissed+=line.tr}};let f2;if(cur!==void 0&&prev!==void 0){f2=seamLcp(prev.head,cur.head);const prevCapped=prev.bytes>SEAM_BODY_CAP;const curCapped=cur.bytes>SEAM_BODY_CAP;if(!prevCapped&&!curCapped&&f2.prevMsgs>0&&f2.curMsgs<f2.prevMsgs){line.prov="rewind";agg.rewinds+=1;agg.rewindMissed+=line.tr;return}if(cur.head.byteLength<prev.head.byteLength&&f2.lcpBytes>=cur.head.byteLength-4){line.prov="rewind";agg.rewinds+=1;agg.rewindMissed+=line.tr;return}if(f2.lcpBytes>=cur.head.byteLength){bookProvider();return}if(!prevCapped&&!curCapped&&f2.prevMsgs>0&&f2.msgIndex===f2.prevMsgs&&f2.curMsgs>f2.prevMsgs){bookProvider();return}if(prev.head.byteLength<cur.head.byteLength&&f2.lcpBytes>=prev.head.byteLength-4){if(prev.msgs!==null&&cur.msgs!==null&&cur.msgs>prev.msgs){bookProvider();return}}}const curIn=pendingCapture(session).inBody;const prevIn=session.transient?.settledInBody;if(curIn!==void 0&&prevIn!==void 0&&curIn.msgs<=INBOUND_MSG_CAP&&prevIn.msgs<=INBOUND_MSG_CAP){const k2=firstDivergentInboundMsg(prevIn,curIn);if(k2!==null&&k2<Math.min(prevIn.msgs,curIn.msgs)){line.prov="client";agg.clientInserts+=1;agg.clientInsertMissed+=line.tr;const m2=curIn.meta[k2]??{role:"?",len:0,cls:"?"};if(cur!==void 0&&prev!==void 0){if(led.seamEvents!==void 0&&led.seamEvents.length>=SEAM_EVENTS_CAP)led.seamEvents.shift();const forensics=f2??seamLcp(prev.head,cur.head);(led.seamEvents??(led.seamEvents=[])).push({seq:line.seq,at:line.at,input:line.input,hitPct:line.hitPct??0,...forensics,prevMsgs:prev.msgs??forensics.prevMsgs,curMsgs:cur.msgs??forensics.curMsgs,client:{idx:k2,role:m2.role,len:m2.len,cls:m2.cls}})}if(agg.clientInserts===1){log("warn",`[${session.id}] [cache-seam] client-side mid-history rewrite: hit ${line.hitPct}% (input=${line.input}, unexplained=${Math.round(line.tr)} tok) \u2014 the client's resent history diverged at inbound message[${k2}] of ${prevIn.msgs}\u2192${curIn.msgs} (${m2.role}/${m2.cls}, ${m2.len}B JSON), so the wire break is the host's own churn, not a bili rebuild (#3023)`)}return}}if((led.sweepThisSample??0)>0){line.prov="orphan-sweep";agg.orphanSweepSeams+=1;agg.orphanSweepMissed+=line.tr;if(agg.orphanSweepSeams===1){log("warn",`[${session.id}] [cache-seam] mid-history break attributed to proactive failed-compress cleanup (${led.sweepThisSample} record(s) rotated out, #3769): hit ${line.hitPct}% (unexplained=${Math.round(line.tr)} tok) \u2014 no fold claimed this break`)}return}agg.seamSuspects+=1;agg.seamMissed+=line.tr;line.seam=1;if(cur!==void 0&&prev!==void 0&&led.seamEvents!==void 0&&led.seamEvents.length>=SEAM_EVENTS_CAP){led.seamEvents.shift()}if(cur!==void 0&&prev!==void 0){const forensics=f2??seamLcp(prev.head,cur.head);const ev={seq:line.seq,at:line.at,input:line.input,hitPct:line.hitPct??0,...forensics,prevMsgs:prev.msgs??forensics.prevMsgs,curMsgs:cur.msgs??forensics.curMsgs};(led.seamEvents??(led.seamEvents=[])).push(ev);if(agg.seamSuspects===1){log("warn",`[${session.id}] [cache-seam] suspected mid-history prefix break: hit ${line.hitPct}% (input=${line.input}, unexplained=${Math.round(line.tr)} tok, no fold/switch/restart attribution); first divergence at byte ${ev.lcpBytes}, message[${ev.msgIndex??"?"}] of ${ev.prevMsgs}\u2192${ev.curMsgs} \u2014 see /acp-cache for the seam section`)}}else if(agg.seamSuspects===1){log("warn",`[${session.id}] [cache-seam] suspected mid-history prefix break: hit ${line.hitPct}% (input=${line.input}, unexplained=${Math.round(line.tr)} tok, no fold/switch/restart attribution); outbound body pair unavailable (lane without body capture) \u2014 aggregate flag only`)}}function getCacheLedger(session){const meta=session.metadata??(session.metadata={});const existing=meta[LEDGER_KEY];if(existing&&existing.v===1){const g2=existing.agg;for(const key2 of["switches","switchMissed","effSwitches","effSwitchMissed","keySwitches","keySwitchMissed","promptSwitches","promptSwitchMissed","projSwitches","projSwitchMissed","wireSwitches","wireSwitchMissed","upstreamSwitches","upstreamSwitchMissed","restartDrops","restartDropMissed","attributedMissed","unknownSamples","unknownInput","nbSamples","nbInput","seamSuspects","seamMissed","providerSideMisses","providerSideMissed","providerTtlMisses","providerTtlMissed","rewinds","rewindMissed","abortCorrelated","clientInserts","clientInsertMissed","orphanSweepSeams","orphanSweepMissed"]){if(typeof g2[key2]!=="number")g2[key2]=0}return existing}const maxBlockId=(session.state?.blocks??[]).reduce((n,b2)=>Math.max(n,refNum3(b2.blockId)),0);const led={v:1,lastBlockId:maxBlockId,consumedFoldSeq:0,sampleSeq:0,foldSeqCounter:0,folds:[],lines:[],agg:{requests:0,input:0,cached:0,output:0,nc:0,cr:0,tr:0,switches:0,switchMissed:0,effSwitches:0,effSwitchMissed:0,keySwitches:0,keySwitchMissed:0,promptSwitches:0,promptSwitchMissed:0,projSwitches:0,projSwitchMissed:0,wireSwitches:0,wireSwitchMissed:0,upstreamSwitches:0,upstreamSwitchMissed:0,restartDrops:0,restartDropMissed:0,attributedMissed:0,unknownSamples:0,unknownInput:0,nbSamples:0,nbInput:0,seamSuspects:0,seamMissed:0,providerSideMisses:0,providerSideMissed:0,providerTtlMisses:0,providerTtlMissed:0,rewinds:0,rewindMissed:0,abortCorrelated:0,clientInserts:0,clientInsertMissed:0,orphanSweepSeams:0,orphanSweepMissed:0}};meta[LEDGER_KEY]=led;return led}function pushFold(led,f2){for(const open of led.folds){if(open.k===null)open.k=open.requestsAfter}led.foldSeqCounter+=1;led.folds.push({...f2,seq:led.foldSeqCounter,T:0,hPct:null,requestsAfter:0,k:null})}function recordCacheFoldsFromBlocks(session,blocks,geo){if(blocks.length===0)return;const led=getCacheLedger(session);for(const b2 of blocks){const id=refNum3(b2.blockId);if(id<=led.lastBlockId)continue;pushFold(led,{at:b2.createdAt||Date.now(),S:b2.compressedTokens,sigma:Math.ceil(b2.summary.length/4),X:b2.startRef?prefixTokensBeforeRef(session,b2.startRef):void 0,V:geo?.V,Vp:geo?.Vp,bid:b2.blockId});led.lastBlockId=Math.max(led.lastBlockId,id)}}function detectNewFolds(session,led){const blocks=session.state?.blocks??[];let maxId=led.lastBlockId;for(const b2 of blocks)maxId=Math.max(maxId,refNum3(b2.blockId));if(maxId>led.lastBlockId){recordCacheFoldsFromBlocks(session,blocks.filter(b2=>refNum3(b2.blockId)>led.lastBlockId))}}function detectOrphanSweeps(session,led){const n=session.state?.sweptOrphanCallIds?.length??0;if(led.lastSweptCount===void 0){led.lastSweptCount=n;led.sweepThisSample=0;return}const delta=n-led.lastSweptCount;led.lastSweptCount=n;led.sweepThisSample=delta>0?delta:0}function recordCacheSample(session,s3){const led=getCacheLedger(session);detectNewFolds(session,led);detectOrphanSweeps(session,led);const prevLine=led.lines[led.lines.length-1];const known=s3.cached!==null;const effCached=s3.cached??0;const eff=typeof s3.effFp==="string"&&s3.effFp!==""?s3.effFp:void 0;const warmLine=known&&s3.input>0&&effCached/s3.input*100>=FOLD_CLAIM_WARM_HIT_PCT;const pendRefs=led.folds.filter(f2=>f2.at<=s3.at&&!f2.retired&&((f2.claims??0)===0||!warmLine));const pending=pendRefs.map(f2=>({at:f2.at,tokensCompressed:f2.S,summaryTokens:f2.sigma,firstFoldStartTokens:f2.X,viewBefore:f2.V,viewAfter:f2.Vp}));if(pending.length>0&&known&&s3.input>0){const rawMissed=s3.input-effCached;if(rawMissed>8192&&rawMissed>.3*s3.input){const{sentBody:curB,inBody:curIn}=pendingEvidencePair(session);const prevB=session.transient?.settledBody;if(curB!==void 0&&prevB!==void 0&&curB.bytes<=SEAM_BODY_CAP&&prevB.bytes<=SEAM_BODY_CAP){const prevIn=session.transient?.settledInBody;const clientBreak=curIn!==void 0&&prevIn!==void 0&&curIn.msgs<=INBOUND_MSG_CAP&&prevIn.msgs<=INBOUND_MSG_CAP&&(()=>{const k2=firstDivergentInboundMsg(prevIn,curIn);return k2!==null&&k2<Math.min(prevIn.msgs,curIn.msgs)})();if(!clientBreak){const lcp=seamLcp(prevB.head,curB.head);if(lcp.msgIndex!==null&&lcp.prevMsgs>0&&lcp.msgIndex<lcp.prevMsgs&&lcp.lcpBytes>0&&lcp.lcpBytes<curB.head.byteLength){const xMeasured=Math.round(s3.input*(lcp.lcpBytes/curB.bytes));for(const p2 of pending)p2.firstFoldStartTokens=Math.min(p2.firstFoldStartTokens??Number.POSITIVE_INFINITY,xMeasured)}}}}}const rawDec=decomposeSample(prevLine?{at:prevLine.at,input:prevLine.input,cached:prevLine.cached}:null,{at:s3.at,input:s3.input,cached:effCached},pending);const noBaseline=!prevLine&&known;const dec=noBaseline?{...rawDec,newContent:rawDec.newContent+rawDec.ttlRepay,ttlRepay:0}:rawDec;let foldSeq=null;if(known&&dec.foldIndex!==null)foldSeq=pendRefs[dec.foldIndex]?.seq??null;if(known&&pendRefs.length>0){for(const f2 of pendRefs){f2.claims=(f2.claims??0)+1;if(f2.claims>=FOLD_CLAIM_COLD_ROUNDS){f2.retired=true;led.consumedFoldSeq=Math.max(led.consumedFoldSeq,f2.seq)}}}if(known&&warmLine){for(const f2 of led.folds){if(f2.at<=s3.at&&!f2.retired){f2.retired=true;led.consumedFoldSeq=Math.max(led.consumedFoldSeq,f2.seq)}}}const hitPct2=known&&s3.input>0?round12(effCached/s3.input*100):null;const model=typeof session.metadata?.lastModel==="string"&&session.metadata.lastModel!==""?session.metadata.lastModel:void 0;const proto=typeof s3.protocol==="string"&&s3.protocol!==""?s3.protocol:void 0;const up=typeof s3.upstream==="string"&&s3.upstream!==""?s3.upstream:void 0;const key2=typeof s3.keyFp==="string"&&s3.keyFp!==""?s3.keyFp:void 0;const sys=typeof s3.sysFp==="string"&&s3.sysFp!==""?s3.sysFp:void 0;const canon2=typeof s3.canonFp==="string"&&s3.canonFp!==""?s3.canonFp:void 0;const modelSwitched=known&&model!==void 0&&led.lastKnownModel!==void 0&&model!==led.lastKnownModel;const effortSwitched=known&&eff!==void 0&&led.lastKnownEff!==void 0&&eff!==led.lastKnownEff;const wireSwitched=known&&proto!==void 0&&led.lastKnownProto!==void 0&&proto!==led.lastKnownProto;const upstreamSwitched=known&&up!==void 0&&led.lastKnownUp!==void 0&&up!==led.lastKnownUp;const keySwitched=known&&key2!==void 0&&led.lastKnownKey!==void 0&&key2!==led.lastKnownKey;const promptSwitched=known&&sys!==void 0&&led.lastKnownSp!==void 0&&sys!==led.lastKnownSp;const canonSwitched=known&&canon2!==void 0&&led.lastKnownCanon!==void 0&&canon2!==led.lastKnownCanon;const projFlip=promptSwitched&&!canonSwitched&&canon2!==void 0&&led.lastKnownCanon!==void 0;const restarted=known&&led.lines.length>0&&led.lastBoot!==void 0&&led.lastBoot!==BOOT_ID;const covAll=session.metadata[METADATA_FOLD_COVERAGE];const lostLogged=session.metadata[LOST_LOGGED_KEY]??{};let lostDirty=false;for(const f2 of led.folds){if(f2.at<=s3.at){const cov=f2.bid!==void 0?covAll?.[f2.bid]:void 0;let frac=1;let lost=null;if(cov!==void 0&&cov.e===1&&typeof cov.t==="number"&&cov.t>0){const present=(cov.p??0)+(cov.r??0);frac=Math.min(1,present/cov.t);lost=present===0}f2.requestsAfter+=frac;if(known&&f2.hPct===null)f2.hPct=hitPct2;if(lost!==null&&f2.bid!==void 0){if(lost&&lostLogged[f2.bid]!==true){lostLogged[f2.bid]=true;lostDirty=true;log("warn",`[${session.id}] [cache-ledger] fold seq ${f2.seq} (block ${f2.bid}) coverage-lost: covered id(s) no longer on the resent wire \u2014 avoided-token accrual frozen at requestsAfter=${f2.requestsAfter.toFixed(1)} (#2202)`)}else if(!lost&&lostLogged[f2.bid]===true){delete lostLogged[f2.bid];lostDirty=true;log("info",`[${session.id}] [cache-ledger] fold seq ${f2.seq} (block ${f2.bid}) coverage restored \u2014 avoided-token accrual resumes (#2202)`)}}}}if(lostDirty)session.metadata[LOST_LOGGED_KEY]=lostLogged;if(foldSeq!==null){const owner=led.folds.find(f2=>f2.seq===foldSeq);if(owner)owner.T+=dec.compRepay}led.sampleSeq+=1;const isWarm=known&&s3.input>0&&(hitPct2??0)>=WARM_HIT_PCT;const seq=led.sampleSeq;const contWithin=inv=>inv!==void 0&&!isWarm&&seq-inv.seq<=SWITCH_COLD_ROUNDS;const freshCause=restarted?"restart":modelSwitched?"model":effortSwitched?"effort":keySwitched?"key":promptSwitched&&!projFlip?"prompt":projFlip?"projection":wireSwitched?"wire":upstreamSwitched?"upstream":null;const cause=freshCause!==null?freshCause:contWithin(led.invModel)?"model":contWithin(led.invEff)?"effort":contWithin(led.invKey)?"key":contWithin(led.invSp)?"prompt":contWithin(led.invProj)?"projection":contWithin(led.invWire)?"wire":contWithin(led.invUp)?"upstream":null;led.lines.push({seq:led.sampleSeq,at:s3.at,input:s3.input,cached:effCached,output:s3.output??0,hitPct:hitPct2,missed:known?dec.missed:0,nc:known?dec.newContent:0,cr:known?dec.compRepay:0,tr:known?dec.ttlRepay:0,foldSeq,model,proto,up,kp:key2,sp:sys,efp:eff,sw:modelSwitched?1:void 0,ef:effortSwitched?1:void 0,pw:wireSwitched?1:void 0,uw:upstreamSwitched?1:void 0,kw:keySwitched?1:void 0,sf:promptSwitched?1:void 0,pf:projFlip?1:void 0,cf:!promptSwitched&&canonSwitched?1:void 0,pm:s3.mode,rs:restarted?1:void 0,unk:known?void 0:1,nb:noBaseline?1:void 0,cause:known&&cause!==null?cause:void 0});led.lastBoot=BOOT_ID;const agg=led.agg;agg.requests+=1;agg.output+=s3.output??0;if(!known){agg.unknownInput+=s3.input;agg.unknownSamples+=1;return}agg.input+=s3.input;agg.cached+=effCached;agg.nc+=dec.newContent;agg.cr+=dec.compRepay;agg.tr+=dec.ttlRepay;if(freshCause==="restart")agg.restartDrops+=1;else if(freshCause==="model")agg.switches+=1;else if(freshCause==="effort")agg.effSwitches+=1;else if(freshCause==="key")agg.keySwitches+=1;else if(freshCause==="prompt")agg.promptSwitches+=1;else if(freshCause==="projection")agg.projSwitches+=1;else if(freshCause==="wire")agg.wireSwitches+=1;else if(freshCause==="upstream")agg.upstreamSwitches+=1;if(cause==="model")agg.switchMissed+=dec.ttlRepay;else if(cause==="effort")agg.effSwitchMissed+=dec.ttlRepay;else if(cause==="key")agg.keySwitchMissed+=dec.ttlRepay;else if(cause==="prompt")agg.promptSwitchMissed+=dec.ttlRepay;else if(cause==="projection")agg.projSwitchMissed+=dec.ttlRepay;else if(cause==="wire")agg.wireSwitchMissed+=dec.ttlRepay;else if(cause==="upstream")agg.upstreamSwitchMissed+=dec.ttlRepay;else if(cause==="restart")agg.restartDropMissed+=dec.ttlRepay;if(cause!==null)agg.attributedMissed+=dec.ttlRepay;if(isWarm){led.invModel=void 0;led.invEff=void 0;led.invWire=void 0;led.invUp=void 0;led.invKey=void 0;led.invSp=void 0;led.invProj=void 0}else{if(led.invModel&&seq-led.invModel.seq>SWITCH_COLD_ROUNDS)led.invModel=void 0;if(led.invEff&&seq-led.invEff.seq>SWITCH_COLD_ROUNDS)led.invEff=void 0;if(led.invWire&&seq-led.invWire.seq>SWITCH_COLD_ROUNDS)led.invWire=void 0;if(led.invUp&&seq-led.invUp.seq>SWITCH_COLD_ROUNDS)led.invUp=void 0;if(led.invKey&&seq-led.invKey.seq>SWITCH_COLD_ROUNDS)led.invKey=void 0;if(led.invSp&&seq-led.invSp.seq>SWITCH_COLD_ROUNDS)led.invSp=void 0;if(led.invProj&&seq-led.invProj.seq>SWITCH_COLD_ROUNDS)led.invProj=void 0}if(modelSwitched)led.invModel={seq,at:s3.at,from:led.lastKnownModel??null,to:model};if(effortSwitched)led.invEff={seq,at:s3.at,from:led.lastKnownEff??null,to:eff};if(wireSwitched)led.invWire={seq,at:s3.at,from:led.lastKnownProto??null,to:proto};if(upstreamSwitched)led.invUp={seq,at:s3.at,from:led.lastKnownUp??null,to:up};if(keySwitched)led.invKey={seq,at:s3.at,from:led.lastKnownKey??null,to:key2};if(promptSwitched&&!projFlip)led.invSp={seq,at:s3.at,from:led.lastKnownSp??null,to:sys};if(projFlip)led.invProj={seq,at:s3.at,from:led.lastKnownSp??null,to:sys};if(model!==void 0)led.lastKnownModel=model;if(eff!==void 0)led.lastKnownEff=eff;if(proto!==void 0)led.lastKnownProto=proto;if(up!==void 0)led.lastKnownUp=up;if(key2!==void 0)led.lastKnownKey=key2;if(sys!==void 0)led.lastKnownSp=sys;if(canon2!==void 0)led.lastKnownCanon=canon2;if(noBaseline){agg.nbSamples+=1;agg.nbInput+=s3.input}}var CALIBRATION_MIN_ESTIMATE=2e3;var CALIBRATION_SAMPLE_MIN=.2;var CALIBRATION_SAMPLE_MAX=5;var CALIBRATION_CLAMP_MIN=.25;var CALIBRATION_CLAMP_MAX=4;var CALIBRATION_SAMPLE_WINDOW=3;var CALIBRATION_CONSISTENCY_RATIO=2;function canonicalSysFpForSettle(session,protocol){if(protocol!=="responses")return void 0;const noted=session.metadata?.[METADATA_CANONICAL_SYS_FP];return typeof noted?.fp==="string"&¬ed.fp!==""?noted.fp:void 0}function ingestCalibrationPair(session,billed,upstream){const settleOrigin=normalizeUpstreamOrigin(upstream);const pendingCalibOrigin=session.stats.lastCalibrationPolicyOrigin!==void 0?normalizeUpstreamOrigin(session.stats.lastCalibrationPolicyOrigin):void 0;const calibPolicy=pendingCalibOrigin===settleOrigin?session.stats.lastCalibrationPolicy:void 0;const pendingEst=session.stats.lastLocalTextEstimate;const pendingOrigin=normalizeUpstreamOrigin(session.stats.lastLocalTextEstimateOrigin);if(pendingEst!==void 0&&pendingEst>=CALIBRATION_MIN_ESTIMATE&&settleOrigin!==void 0&&pendingOrigin===settleOrigin){const rawSample=billed/pendingEst;const settleModel=typeof session.metadata?.lastModel==="string"&&session.metadata.lastModel!==""?session.metadata.lastModel:void 0;let ring=session.stats.calibrationRing;if(!ring||ring.origin!==settleOrigin||ring.model!==void 0&&settleModel!==void 0&&ring.model!==settleModel){ring={origin:settleOrigin,model:settleModel,values:[]}}else if(ring.model===void 0&&settleModel!==void 0){ring.model=settleModel}if(rawSample>=CALIBRATION_SAMPLE_MIN&&rawSample<=CALIBRATION_SAMPLE_MAX){ring.values.push(rawSample);if(ring.values.length>CALIBRATION_SAMPLE_WINDOW)ring.values.shift();const spread=Math.max(...ring.values)/Math.min(...ring.values);if(ring.values.length>=2&&spread<=CALIBRATION_CONSISTENCY_RATIO){const mean=ring.values.reduce((a,b2)=>a+b2,0)/ring.values.length;if(calibPolicy?.disabled===true){delete session.stats.calibratedEstimate;delete session.stats.calibratedEstimateOrigin;delete session.stats.calibratedEstimateModel}else{const clamped=Math.min(CALIBRATION_CLAMP_MAX,Math.max(CALIBRATION_CLAMP_MIN,mean));session.stats.calibratedEstimate=calibPolicy?.max!==void 0?Math.min(clamped,calibPolicy.max):clamped;session.stats.calibratedEstimateOrigin=settleOrigin;session.stats.calibratedEstimateModel=ring.model}}else{delete session.stats.calibratedEstimate;delete session.stats.calibratedEstimateOrigin;delete session.stats.calibratedEstimateModel}}session.stats.calibrationRing=ring}}function settleOverflowCalibration(session,measured,upstream){if(!(measured>0))return;ingestCalibrationPair(session,measured,upstream);session.stats.lastLocalTextEstimate=void 0;session.stats.lastLocalTextEstimateOrigin=void 0}function noteOutboundContextEstimates(session,est){session.stats.localInputEstimate=est.upperBound;session.stats.contextEstimateTokens=Math.round(est.scaledText+est.imageTokens);session.stats.contextEstimateCalibrated=est.calibrated;session.stats.contextTokens=est.upperBound;session.stats.contextTokensSource="estimate"}function settleUsageReport(session,s3,localTextEstimate){if(s3.total>0){session.stats.inputTokens+=s3.total;billInputUsage(session,{total:s3.total,cached:s3.reportedCached,creation:s3.creation});if(isForeignMembership(session.transient?.requestMembership)){const m2=session.transient.requestMembership;log("info",`[${session.id}] [membership] usage sample (total=${s3.total}) refused anchor write: its request did not carry the conversation's latest message id (needle=${m2.needle??"-"}) \u2014 foreign payload under a shared session id (#4805)`)}else{session.stats.lastInputTokens=Math.max(0,s3.total-(session.stats.compressCreditTokens??0));session.stats.lastUsageGradeTokens=session.stats.lastInputTokens;session.stats.lastUsagePayloadUpper=session.stats.localInputEstimate??0;session.stats.lastInputTokensSource="usage";delete session.stats.emergencyShrinkAt;delete session.stats.emergencyShrinkEstimate;session.stats.contextTokens=session.stats.lastInputTokens;session.stats.contextTokensSource="usage";if(session.metadata)session.metadata.contextTokensAt=Date.now();recordContextObservation(session,session.stats.lastInputTokens,(session.stats.compressCreditTokens??0)>0?"estimate":"usage");const settleOrigin=normalizeUpstreamOrigin(s3.upstream);if(settleOrigin!==void 0)session.stats.lastInputTokensOrigin=settleOrigin;ingestCalibrationPair(session,s3.total,s3.upstream);clearPostRebuildAnchor(session);delete session.stats.overflowArmTokens;delete session.stats.overflowArmCompletionReserve}}session.stats.lastLocalTextEstimate=localTextEstimate;session.stats.lastLocalTextEstimateOrigin=localTextEstimate!==void 0?normalizeUpstreamOrigin(s3.upstream):void 0;if(s3.reportedCached!==null&&s3.total>0){session.stats.cachedTokens+=s3.reportedCached;session.stats.cacheSamples+=1}const curKeyFp=pendingCapture(session).sentBody?.keyFp;const curEffFp=pendingCapture(session).sentBody?.effFp;const notedSys=session.metadata?.[METADATA_SYSTEM_FP];const curSysFp=typeof notedSys?.fp==="string"&¬edSys.fp!==""?notedSys.fp:void 0;const curCanonFp=canonicalSysFpForSettle(session,s3.protocol);const lastMode=s3.protocol==="responses"?session.metadata?.[METADATA_LAST_RESPONSES_MODE]:void 0;const led=getCacheLedger(session);recordCacheSample(session,{at:Date.now(),input:s3.total,cached:s3.reportedCached,output:s3.output,protocol:s3.protocol,upstream:s3.upstream,keyFp:curKeyFp,sysFp:curSysFp,canonFp:curCanonFp,effFp:curEffFp,mode:lastMode==="plugin"||lastMode==="proxy"?lastMode:void 0});const capture2=captures.getStore();const sample=led.lines[led.lines.length-1];if(capture2?.session===session&&sample){sample.captureId=capture2.requestId;sample.captureRound=capture2.round}const curSlot=pendingCapture(session).sentBody;if(curSlot!==void 0){const curLine=led.lines[led.lines.length-1];if(curLine!==void 0){curLine.bd=curSlot.digest;const settled2=session.transient?.settledBody;const backwards2=curSlot.order!==void 0&&settled2?.order!==void 0&&curSlot.order<=settled2.order;const prevSlot=backwards2?void 0:settled2;if(backwards2)curLine.evidence="out-of-order";if(prevSlot!==void 0){if(curSlot.digest===prevSlot.digest){curLine.be=1}else{curLine.be=0;if(curSlot.full!==null&&prevSlot.full!==null){const lcp=byteLcp(prevSlot.full,curSlot.full);curLine.bl=lcp;const shorterFull=prevSlot.full.length<=curSlot.full.length?prevSlot.full:curSlot.full;const arrClose=messagesArrayCloseOffset(shorterFull);const midInsert=isMidInsertionAppend(prevSlot.full,curSlot.full,lcp);curLine.bs=lcp>=Math.min(prevSlot.full.length,curSlot.full.length)-64?"append":lcp<1024?"head":arrClose!==null&&lcp>=arrClose?"tail":midInsert?"append":"mid"}else{curLine.bs="unknown"}}}}}settleImageLearning(session,s3.total);detectSeam(session,led);const pending=pendingCapture(session);const settled=session.transient??={};const seamBody=pending.sentBody;const backwards=seamBody?.order!==void 0&&settled.settledBody?.order!==void 0&&seamBody.order<=settled.settledBody.order;if(seamBody!==void 0&&!backwards)settled.settledBody=seamBody;else delete settled.settledBody;delete pending.sentBody;const seamIn=pending.inBody;if(seamBody!==void 0&&seamIn!==void 0&&!backwards)settled.settledInBody=seamIn;else delete settled.settledInBody;delete pending.inBody}function stampedPriceProfile(session){const v2=session.metadata?.cachePriceProfile;if(!v2||typeof v2!=="object"||Array.isArray(v2))return void 0;const o=v2;const out={};for(const key2 of["w","r","q"]){const n=o[key2];if(typeof n==="number"&&Number.isFinite(n)&&n>=0)out[key2]=n}return Object.keys(out).length>0?out:void 0}function buildSessionCacheReport(session){const led=getCacheLedger(session);const price=stampedPriceProfile(session);const effective={w:price?.w??1,r:price?.r??.1,q:price?.q??4};const a=led.agg;const totals={requests:a.requests,input:a.input,cached:a.cached,output:a.output,hitPct:a.input>0?round12(a.cached/a.input*100):0,newContent:a.nc,compRepay:a.cr,ttlRepay:a.tr,residual:a.input-a.cached-(a.nc+a.cr+a.tr),balanced:true};totals.balanced=totals.residual===0;const folds=led.folds.map(f2=>computeFoldEconomics({seq:f2.seq,at:f2.at,S:f2.S,sigma:f2.sigma,Vprime:f2.Vp??null,hPct:f2.hPct,T:f2.T,requestsAfter:f2.requestsAfter,turnsToNextFold:f2.k},effective));const knownLines=led.lines.filter(l=>l.unk!==1);const switchEvents=(flag,value,dim)=>{const evs=[];for(let i=0;i<led.lines.length;i++){const l=led.lines[i];if(!l||l.unk===1||!flag(l))continue;if(l.cause!==void 0&&l.cause!==dim)continue;let from;for(let j2=i-1;j2>=0;j2--){const p2=led.lines[j2];if(p2&&p2.unk!==1){from=value(p2);break}}evs.push({seq:l.seq,at:l.at,from:from??null,to:value(l)??"?",input:l.input,cached:l.cached,hitPct:l.hitPct??0,attributed:l.cause===dim||l.cause===void 0?l.tr:0})}return evs};const restartEvents=[];for(const l of led.lines){if(l.rs!==1||l.unk===1)continue;restartEvents.push({seq:l.seq,at:l.at,from:null,to:"(restart)",input:l.input,cached:l.cached,hitPct:l.hitPct??0,attributed:l.cause==="restart"||l.cause===void 0?l.tr:0})}const invalidation={model:a.switchMissed,effort:a.effSwitchMissed,key:a.keySwitchMissed,prompt:a.promptSwitchMissed,projection:a.projSwitchMissed,wire:a.wireSwitchMissed,upstream:a.upstreamSwitchMissed,restart:a.restartDropMissed,remaining:Math.max(0,a.tr-a.attributedMissed)};let paired=0;let equal=0;let head=0;let append=0;let mid=0;let tail=0;let unknownOffset=0;for(const l of knownLines){if(l.be===void 0)continue;paired+=1;if(l.be===1){equal+=1;continue}if(l.bs==="head")head+=1;else if(l.bs==="append")append+=1;else if(l.bs==="mid")mid+=1;else if(l.bs==="tail")tail+=1;else unknownOffset+=1}const sizeBuckets=[];{const byLo=new Map;for(const l of knownLines){if(l.hitPct===null||l.input<=0)continue;const lo2=Math.floor(l.input/SIZE_BUCKET_TOK)*SIZE_BUCKET_TOK;const hits=byLo.get(lo2);if(hits)hits.push(l.hitPct);else byLo.set(lo2,[l.hitPct])}for(const[lo2,hits]of[...byLo.entries()].sort((x,y)=>x[0]-y[0]).slice(0,24)){sizeBuckets.push({lo:lo2,hi:lo2+SIZE_BUCKET_TOK,n:hits.length,hitMedian:median(hits)??0,hitMin:Math.min(...hits)})}}const lowGaps=[];const highGaps=[];for(let i=1;i<led.lines.length;i++){const p2=led.lines[i-1];const c=led.lines[i];if(!p2||!c||c.hitPct===null)continue;const gap=c.at-p2.at;if(!(gap>0))continue;(c.hitPct<80?lowGaps:highGaps).push(gap)}const stability={paired,equal,diverged:paired-equal,head,append,mid,tail,unknownOffset,sizeBuckets,gapSplit:{lowHitMedGapMs:median(lowGaps),highHitMedGapMs:median(highGaps)}};return{generatedAt:Date.now(),profile:effective,totals,economics:summarizeFoldEconomics(folds),folds,lines:knownLines.map(l=>({seq:l.seq,at:l.at,input:l.input,cached:l.cached,output:l.output,hitPct:l.hitPct??0,missed:l.missed,newContent:l.nc,compRepay:l.cr,ttlRepay:l.tr,foldSeq:l.foldSeq,seam:l.seam,prov:l.prov,captureId:l.captureId,captureRound:l.captureRound,evidence:l.evidence,bodyDigest:l.bd,keyFp:l.kp,sysFp:l.sp,efp:l.efp,bodyEqual:l.be,bodyLcp:l.bl,bodyClass:l.bs})),linesOmitted:led.sampleSeq-led.lines.length,modelSwitches:{count:a.switches,missedTokens:a.switchMissed,events:switchEvents(l=>l.sw===1&&l.model!==void 0,l=>l?.model,"model")},effSwitches:{count:a.effSwitches,missedTokens:a.effSwitchMissed,events:switchEvents(l=>l.ef===1&&l.efp!==void 0,l=>l?.efp,"effort")},keySwitches:{count:a.keySwitches,missedTokens:a.keySwitchMissed,events:switchEvents(l=>l.kw===1&&l.kp!==void 0,l=>l?.kp,"key")},promptSwitches:{count:a.promptSwitches,missedTokens:a.promptSwitchMissed,events:switchEvents(l=>l.sf===1&&l.sp!==void 0,l=>l?.sp,"prompt")},projSwitches:{count:a.projSwitches,missedTokens:a.projSwitchMissed,events:switchEvents(l=>l.pf===1&&l.sp!==void 0,l=>l?.sp,"projection")},wireSwitches:{count:a.wireSwitches,missedTokens:a.wireSwitchMissed,events:switchEvents(l=>l.pw===1&&l.proto!==void 0,l=>l?.proto,"wire")},upstreamSwitches:{count:a.upstreamSwitches,missedTokens:a.upstreamSwitchMissed,events:switchEvents(l=>l.uw===1&&l.up!==void 0,l=>l?.up,"upstream")},restartDrops:{count:a.restartDrops,missedTokens:a.restartDropMissed,events:restartEvents},unmeasured:{samples:a.unknownSamples,inputTokens:a.unknownInput},initialBills:{samples:a.nbSamples,inputTokens:a.nbInput},invalidation,stability,seam:{suspects:a.seamSuspects,missed:a.seamMissed,events:led.seamEvents??[],providerSide:{count:a.providerSideMisses,missed:a.providerSideMissed},providerTtl:{count:a.providerTtlMisses,missed:a.providerTtlMissed},rewinds:{count:a.rewinds,missed:a.rewindMissed},abortCorrelated:a.abortCorrelated,client:{count:a.clientInserts,missed:a.clientInsertMissed},orphanSweep:{count:a.orphanSweepSeams,missed:a.orphanSweepMissed}}}}function readModelSwitchStats(session){const raw=session.metadata?.[LEDGER_KEY];if(!raw||typeof raw!=="object")return null;const led=raw;if(led.v!==1)return null;return{count:typeof led.agg?.switches==="number"?led.agg.switches:0,missedTokens:typeof led.agg?.switchMissed==="number"?led.agg.switchMissed:0}}function readKeySwitchStats(session){const raw=session.metadata?.[LEDGER_KEY];if(!raw||typeof raw!=="object")return null;const led=raw;if(led.v!==1)return null;return{count:typeof led.agg?.keySwitches==="number"?led.agg.keySwitches:0,missedTokens:typeof led.agg?.keySwitchMissed==="number"?led.agg.keySwitchMissed:0}}function readPromptSwitchStats(session){const raw=session.metadata?.[LEDGER_KEY];if(!raw||typeof raw!=="object")return null;const led=raw;if(led.v!==1)return null;return{count:typeof led.agg?.promptSwitches==="number"?led.agg.promptSwitches:0,missedTokens:typeof led.agg?.promptSwitchMissed==="number"?led.agg.promptSwitchMissed:0}}function readProjSwitchStats(session){const raw=session.metadata?.[LEDGER_KEY];if(!raw||typeof raw!=="object")return null;const led=raw;if(led.v!==1)return null;return{count:typeof led.agg?.projSwitches==="number"?led.agg.projSwitches:0,missedTokens:typeof led.agg?.projSwitchMissed==="number"?led.agg.projSwitchMissed:0}}function formatStability(st2){if(st2.paired===0)return"";const out=["BODY STABILITY (per-call outbound byte proof, vs previous settled request)"];out.push(` ${st2.paired} pair(s): ${st2.equal} byte-identical \xB7 ${st2.diverged} diverged`);out.push(` divergence class: head <1KiB ${st2.head} \xB7 tail-append ${st2.append} \xB7 mid-history ${st2.mid} \xB7 tail(params/notes) ${st2.tail} \xB7 offset-unknown(capped) ${st2.unknownOffset}`);if(st2.head>0)out.push(` \u26A0 ${st2.head} head-region divergence(s) \u2014 model/tools/sampling/system changed between calls (host-side parameter change, NOT a bili history rewrite)`);if(st2.mid>0)out.push(` \u26A0 ${st2.mid} mid-history divergence(s) \u2014 real prefix rewrites; inspect the seam events above`);if(st2.tail>0)out.push(` ${st2.tail} tail-region divergence(s) \u2014 trailing top-level params or ephemeral tail notes at/past the message-array end; shared history bytes untouched, but a provider may re-partition its prompt cache on a trailing field such as reasoning effort \u2014 see EFFORT SWITCHES / invalidation above (#3803)`);const sb=st2.sizeBuckets.filter(b2=>b2.n>=3);if(sb.length>=2)out.push(" hit% by input size (median): "+sb.map(b2=>`${Math.round(b2.lo/1e3)}K=${b2.hitMedian}%`).join(" "));const g2=st2.gapSplit;if(g2.lowHitMedGapMs!==null&&g2.highHitMedGapMs!==null){out.push(` inter-request gap median: low-hit(<80%) ${(g2.lowHitMedGapMs/1e3).toFixed(1)}s vs high-hit ${(g2.highHitMedGapMs/1e3).toFixed(1)}s`)}return out.join("\n")}function handleAcpCache(session,args){try{const detail=args?.detail==="full"?"full":"summary";const report=buildSessionCacheReport(session);const stabilityText=formatStability(report.stability);const tail=base=>base+(stabilityText?"\n\n"+stabilityText:"")+(formatSeam(report)?"\n\n"+formatSeam(report):"");const effText=report.effSwitches.count>0?"\n\n"+formatModelSwitches(report.effSwitches,detail,"EFFORT SWITCHES (host changed reasoning effort / thinking config)"):"";const keyText=report.keySwitches.count>0?"\n\n"+formatModelSwitches(report.keySwitches,detail,"KEY SWITCHES (relay account rotation)"):"";const promptText=report.promptSwitches.count>0?"\n\n"+formatModelSwitches(report.promptSwitches,detail,"PROMPT SWITCHES (host rewrote system prompt)"):"";const projText=report.projSwitches.count>0?"\n\n"+formatModelSwitches(report.projSwitches,detail,"PROJECTION SWITCHES (proxy mode/projection change \u2014 bili's own doing, e.g. self-heal degrade-to-proxy)"):"";const wireText=report.wireSwitches.count>0?"\n\n"+formatModelSwitches(report.wireSwitches,detail,"WIRE SWITCHES (client switched protocol wire between requests)"):"";const upstreamText=report.upstreamSwitches.count>0?"\n\n"+formatModelSwitches(report.upstreamSwitches,detail,"UPSTREAM SWITCHES (relay/upstream origin changed between requests)"):"";const restartText=report.restartDrops.count>0?"\n\n"+formatModelSwitches(report.restartDrops,detail,"RESTART/REFORK (first bill under a fresh daemon boot \u2014 prefix re-billed once)"):"";if(detail==="full"&&report.lines.length>FULL_DETAIL_LINES){const dropped=report.lines.length-FULL_DETAIL_LINES;const capped=formatCacheReport({...report,lines:report.lines.slice(-FULL_DETAIL_LINES),linesOmitted:report.linesOmitted+dropped},session.id,{detail});return toolOk(tail(capped+"\n\n"+formatModelSwitches(report.modelSwitches,detail)+effText+keyText+promptText+projText+wireText+upstreamText+restartText+"\n\n"+formatInvalidation(report)))}return toolOk(tail(formatCacheReport(report,session.id,{detail})+"\n\n"+formatModelSwitches(report.modelSwitches,detail)+effText+keyText+promptText+projText+wireText+upstreamText+restartText+"\n\n"+formatInvalidation(report)))}catch(err2){log("warn",`[${session.id}] [acp_cache] report failed: ${String(err2)}`);return toolFail(`[acp_cache FAILED: ${String(err2)}]`)}}function fmtTok2(n){const v2=Math.round(n);return v2>=1e6?`${(v2/1e6).toFixed(2)}M`:v2>=1e4?`${(v2/1e3).toFixed(1)}K`:String(v2)}function fmtTime2(at2){const d=new Date(at2);const p2=x=>String(x).padStart(2,"0");return`${p2(d.getHours())}:${p2(d.getMinutes())}:${p2(d.getSeconds())}`}var SWITCH_LIST_CAP=8;function formatModelSwitches(sw,detail,title="MODEL SWITCHES"){const out=[title];if(sw.count===0){out.push(" none observed");return out.join("\n")}const eventSum=sw.events.reduce((n,e)=>n+e.attributed,0);const tail=sw.missedTokens-eventSum;out.push(` ${sw.count} switch(es) \xB7 ${fmtTok2(sw.missedTokens)} tok re-billed${tail>0?` (${fmtTok2(tail)} on post-switch cold rounds)`:""}`);const shown=detail==="full"?sw.events:sw.events.slice(-SWITCH_LIST_CAP);for(const e of shown){out.push(` #${e.seq} ${fmtTime2(e.at)} ${e.from??"?"} \u2192 ${e.to} \xB7 hit ${e.hitPct.toFixed(1)}% \xB7 attributed ${fmtTok2(e.attributed)}`)}if(shown.length<sw.events.length){out.push(` \u2026 ${sw.events.length-shown.length} earlier switch(es) omitted (detail:"full" lists all)`)}return out.join("\n")}function formatSeam(r){const out=[];if(r.seam.suspects>0){out.push("\u26A0 CACHE SEAM (suspected mid-history prefix breaks)");out.push(` ${r.seam.suspects} sample(s) \xB7 ${fmtTok2(r.seam.missed)} tok re-billed with no fold/switch/restart attribution`);const suspectEvents=r.seam.events.filter(e=>!e.client);for(const e of suspectEvents){out.push(` #${e.seq} ${fmtTime2(e.at)} hit ${e.hitPct.toFixed(1)}% \xB7 input ${fmtTok2(e.input)} \xB7 divergence \u2265${fmtTok2(e.lcpBytes)}B at message[${e.msgIndex??"?"}] of ${e.prevMsgs}\u2192${e.curMsgs}`)}if(suspectEvents.length===0){out.push(" (no body-pair forensics retained for the suspect samples on this lane \u2014 aggregate flag only; client-side rewrites are listed separately below)")}out.push(' if reproducible: /acp-cache detail:"full" + bili.log around the timestamps above (likely a #1548-family round-2/steady render seam)')}if(r.seam.rewinds.count>0){out.push("\u21A9 HISTORY REWOUND (client revert/trim)");out.push(` ${r.seam.rewinds.count} sample(s) \xB7 ${fmtTok2(r.seam.rewinds.missed)} tok re-billed once for the retained prefix \u2014 sanctioned client intent, not a rebuild seam`)}if(r.seam.providerTtl.count>0){out.push("\u23F1 UPSTREAM TTL EXPIRY \u2014 NORMAL (long idle gap)");out.push(` ${r.seam.providerTtl.count} sample(s) \xB7 ${fmtTok2(r.seam.providerTtl.missed)} tok \u2014 byte-stable/append-shaped misses settled more than ${Math.round(PROVIDER_TTL_GAP_MS/6e4)} min after the previous sample: the upstream prefix cache simply aged out. Expected cost, not a failure.`)}if(r.seam.providerSide.count>0){out.push("\u25B2 PROVIDER-SIDE MISS (previous request's message list fully preserved)");out.push(` ${r.seam.providerSide.count} sample(s) \xB7 ${fmtTok2(r.seam.providerSide.missed)} tok \u2014 the previous request's message list is preserved in this one (byte-for-byte under the 512 KiB forensics cap; above it, proven by the stable recorded head plus exact message-count growth \u2014 any difference is only the appended tail), and the sample arrived within ${Math.round(PROVIDER_TTL_GAP_MS/6e4)} min of the previous one, so this is an ABNORMAL provider miss (eviction / relay node rotation), not TTL ageing. Not a bili rebuild seam.`);out.push(` stateful-upstream check (#2483): if your upstream keeps a live session per conversation and validates the echoed history against its own transcript (claude-code-based relays such as magpie), bili's render tags on assistant text trip that check even though bili's own list is unchanged \u2014 set diagnostics.renderNone=true until per-route render-tags control ships; expect exactly ONE replay when flipping the flag mid-session`)}if(r.seam.client.count>0){out.push("\u270E CLIENT MID-HISTORY REWRITE (host-side insert \u2014 NOT a bili seam)");out.push(` ${r.seam.client.count} sample(s) \xB7 ${fmtTok2(r.seam.client.missed)} tok \u2014 the client's own resent history broke mid-list, so bili's faithful rebuild carried the break to the wire (host plugin insert / paste hoisting / re-render). Client-owned re-bill, not a rebuild seam.`);for(const e of r.seam.events){if(e.client)out.push(` #${e.seq} ${fmtTime2(e.at)} hit ${e.hitPct.toFixed(1)}% \xB7 input ${fmtTok2(e.input)} \xB7 inbound message[${e.client.idx}] ${e.client.role}/${e.client.cls} ${e.client.len}B JSON \xB7 outbound ${fmtTok2(e.lcpBytes)}B @ message[${e.msgIndex??"?"}] of ${e.prevMsgs}\u2192${e.curMsgs}`)}}if(r.seam.orphanSweep.count>0){out.push("\u{1F9F9} ORPHAN CLEANUP SEAM (proactive failed-compress rotation \u2014 #3769)");out.push(` ${r.seam.orphanSweep.count} sample(s) \xB7 ${fmtTok2(r.seam.orphanSweep.missed)} tok re-billed when failed-compress records were rotated out of history without a fold claiming the break \u2014 bili's own cleanup, not an upstream or host rewrite`)}if(r.seam.abortCorrelated>0){out.push("\u23FB ABORT-CORRELATED");out.push(` ${r.seam.abortCorrelated} missed sample(s) within 30s of a client mid-stream abort \u2014 abort/retry churn rewrites the resent tail; correlation, not causation (see bili.log 'client aborted mid-stream')`)}return out.length>0?out.join("\n"):""}function formatInvalidation(r){const b2=r.invalidation;const named=b2.model+b2.effort+b2.key+b2.prompt+b2.projection+b2.wire+b2.upstream+b2.restart;const total=named+b2.remaining;const out=["CACHE INVALIDATION"];out.push(` stable-prefix re-bill by cause (mutually exclusive, sums to total): ${fmtTok2(named)} tok charged \xB7 ${fmtTok2(b2.remaining)} tok unattributed (upstream TTL/eviction/wire rewrite)`);out.push(` model switch: ${fmtTok2(b2.model)} (${r.modelSwitches.count})`);out.push(` effort switch: ${fmtTok2(b2.effort)} (${r.effSwitches.count}) \u2014 host changed reasoning effort / thinking config; provider re-partitions its prompt cache on it (#3803)`);out.push(` key switch: ${fmtTok2(b2.key)} (${r.keySwitches.count}) \u2014 relay account rotation, fingerprinted headers never logged raw`);out.push(` prompt rewrite: ${fmtTok2(b2.prompt)} (${r.promptSwitches.count}) \u2014 host rewrote its system prompt between requests (#2350)`);out.push(` projection switch: ${fmtTok2(b2.projection)} (${r.projSwitches.count}) \u2014 proxy switched compression mode/projection (self-heal degrade-to-proxy re-hoists mid-history developer items, #2867)`);out.push(` wire switch: ${fmtTok2(b2.wire)} (${r.wireSwitches.count})`);out.push(` upstream switch: ${fmtTok2(b2.upstream)} (${r.upstreamSwitches.count})`);out.push(` restart/refork: ${fmtTok2(b2.restart)} (${r.restartDrops.count})`);if(b2.remaining>0&&total>0&&b2.remaining/total>=.5){const pct2=Math.round(b2.remaining/total*100);const noCauseEver=r.modelSwitches.count===0&&r.effSwitches.count===0&&r.keySwitches.count===0&&r.promptSwitches.count===0&&r.projSwitches.count===0&&r.wireSwitches.count===0&&r.upstreamSwitches.count===0&&r.restartDrops.count===0;out.push(noCauseEver?` \u26A0 ${pct2}% of your stable-prefix re-bill has no observable cause (no model/wire/upstream switch or restart seen) \u2014 expected provider-side behavior (cache TTL expiry / eviction / relay rotation), NOT a bili bug; if reproducible see #1195 coverage-mismatch`:` \u26A0 ${pct2}% of your stable-prefix re-bill is unnameable provider-side behavior (cache TTL expiry / eviction / relay rotation) beyond the causes listed above`)}if(r.unmeasured.samples>0){out.push(` unmeasured (provider reported no cache tokens): ${r.unmeasured.samples} sample(s) \xB7 ${fmtTok2(r.unmeasured.inputTokens)} tok \u2014 excluded from hit rate`)}if(r.initialBills.samples>0){out.push(` initial bills (no prior baseline): ${r.initialBills.samples} sample(s) \xB7 ${fmtTok2(r.initialBills.inputTokens)} tok \u2014 first request(s) of a session; booked as new content, not a prefix re-pay`)}return out.join("\n")}var{join:join7}=path25;var PERSIST_VERSION=3;var SHADOW_REOPEN_COOLDOWN_MS=3e4;var SHADOW_REOPEN_READ_CHECK_MS=100;var RECON_REPLICAS_WAIT_MS=750;var RECON_REPLICAS_POLL_MS=50;var shadowReopenCooldownMsOverride=null;var shadowReopenReadCheckMsOverride=null;var MIGRATION_MARKER=".bili-migration-286.done";var STALE_WARN_THROTTLE_MS=6e4;var OWN_WRITE_STAMP_EPSILON_MS=1;function hostLabel(upstreamOrigin){if(!upstreamOrigin)return"unknown";try{const host=new URL(upstreamOrigin).hostname||"unknown";return host.replace(/[^a-zA-Z0-9.-]/g,"-").slice(0,48)||"unknown"}catch{return"unknown-"+createHash14("sha256").update(upstreamOrigin,"utf8").digest("hex").slice(0,6)}}function relPathFor(id,protocol,upstreamOrigin){const proto=protocol??"_unknown";const host=protocol?hostLabel(upstreamOrigin)+"_":"";return path25.join(proto,`${host}${createHash14("sha256").update(id,"utf8").digest("hex").slice(0,24)}.json`)}function durableWriteFile(file,data,mode){const fd=openSync(file,"w",mode);try{writeFileSync6(fd,data);fsyncSync(fd)}finally{closeSync(fd)}}function contentStoreRelPathFor(id,protocol,upstreamOrigin){const base=relPathFor(id,protocol,upstreamOrigin);return base.slice(0,-".json".length)+".content-store.json"}function fileNameMatchesId(base,id,protocol,upstreamOrigin){const relBase=path25.basename(relPathFor(id,protocol,upstreamOrigin));const flatBase=flatFileNameFor(id);if(base===relBase||base===flatBase)return true;if(base.endsWith(".fb.json")){const canonicalBase=`${base.slice(0,-".fb.json".length)}.json`;return canonicalBase===relBase||canonicalBase===flatBase}return false}var SessionStore=class{syncSidecarOpen=null;sidecarReopenNextAttemptAt=0;sidecarReadCheckNextAttemptAt=0;enabled;sessionsDir;store;log;staleWarnAt=new Map;ownCommit=new Map;sessionCommitListener;setSessionCommitListener(fn){this.sessionCommitListener=fn}staleGuardFullReads=0;__staleGuardFullReadsForTests(){return this.staleGuardFullReads}__ownWriteStampedForTests(id){return this.ownCommit.get(id)?.written!==void 0}codec;readCodec;boundedReads=false;diskFiles=[];diskFilesSeeded=false;legacyAliases=new Map;sourceFiles=new Map;remainderScan=null;tmpSeq=0;shadow;residentFieldsForBuild;forkBaseCut=new Set;storageMode;jsonWriterOff;mysqlReady=Promise.resolve();networkFullExpected=false;ready(){return this.mysqlReady}writerOffPending=new Map;saveTimers=new Map;saveBuilders=new Map;flushWaiters=new Map;lastSaveLanded=new Map;saveWritesInFlight=new Set;durableRevision=new Map;capWarnAt=new Map;debounceMs;constructor(opts){const debounceMs=opts?.debounceMs??defaultDebounce();this.enabled=(opts?.enabled??true)&&debounceMs>=0;this.debounceMs=Math.max(0,debounceMs);this.sessionsDir=opts?.dir??defaultDir();const baseLog=opts?.log??defaultLogger;this.log=baseLog;const keyEnv=process.env.BILI_ENCRYPTION_KEY;let key2=null;if(keyEnv)key2=parseEncryptionKey(keyEnv);this.codec=createStorageCodec({key:key2,compress:persistZstdEnabled2()});this.readCodec=this.codec??createStorageCodec({compress:true});if(key2){baseLog("info","[persist] session-file encryption enabled (AES-256-GCM)")}else if(this.codec){baseLog("info","[persist] session-file compression enabled (zstd, BILIZSTD1)")}const epermAlert=new PersistEpermAlert({dir:this.sessionsDir,threshold:epermAlertThreshold(),repeatMs:epermAlertRepeatMs()});const storageMode=resolveStorageModeSafe();const unifiedBlockedByEncryption=storageMode!=="legacy"&&key2!==null;if(unifiedBlockedByEncryption){baseLog("warn","[storage] unified sidecar DISABLED: BILI_ENCRYPTION_KEY is active and index.db would hold cleartext ingest payloads \u2014 staying legacy-only")}this.storageMode=storageMode;recordRequestedMode(storageMode,unifiedBlockedByEncryption,!this.enabled);const wantJsonWriterOff=resolveJsonWriterOff(process.env,fileStorageJsonWriter());this.jsonWriterOff=wantJsonWriterOff&&storageMode==="full"&&!unifiedBlockedByEncryption&&resolveBackendName(process.env,fileStorageBackend())==="sqlite";if(wantJsonWriterOff&&!this.jsonWriterOff){baseLog("warn","[storage] storage.jsonWriter=off ignored \u2014 requires storage.unified=full on the sqlite backend (network backends keep the JSON envelope as the sync read path)")}const legacyLoad=recordToLegacyView;const backendName=resolveBackendName(process.env,fileStorageBackend());if(opts?.shadow!==void 0){this.shadow=opts.shadow;this.networkFullExpected=!!(opts.shadow.readsUnified&&opts.shadow.isAsyncBackend)}else if(this.enabled&&!unifiedBlockedByEncryption&&backendName==="mysql"){this.mysqlReady=UnifiedShadow.openAsync(this.sessionsDir,process.env,legacyLoad,fileStorageUnified(),fileStorageWalJournalSizeLimit(),fileStorageBackend(),fileStorageMysqlDsn()).then(sh=>{this.shadow=sh??void 0});this.mysqlReady.catch(()=>{});this.shadow=void 0;this.networkFullExpected=storageMode==="full"}else{if(this.enabled&&!unifiedBlockedByEncryption){this.syncSidecarOpen={legacyLoad};this.shadow=UnifiedShadow.maybeOpen(this.sessionsDir,process.env,legacyLoad,fileStorageUnified(),fileStorageWalJournalSizeLimit(),fileStorageBackend())??void 0}else{this.shadow=void 0}}this.store=new StateStore({dir:this.sessionsDir,version:PERSIST_VERSION,debounceMs:this.debounceMs,enabled:this.enabled,codec:this.codec,log:(level,msg)=>{epermAlert.observe(level,msg);baseLog(level,msg)},relPath:(id,payload)=>relPathFor(id,payload.meta?.protocol??payload.protocol,payload.meta?.upstreamOrigin??payload.upstreamOrigin),legacy:parsed=>isValidRecord(parsed)?{id:parsed.id,payload:parsed,version:parsed.version,savedAt:parsed.savedAt}:null,validate:envelope=>isValidRecord(envelope.payload),foreignFile:file=>path25.basename(file).endsWith(".content-store.json")})}loadContentStore(session){return this.readContentStoreRels(session.id,[contentStoreRelPathFor(session.id,session.meta.protocol,session.meta.upstreamOrigin),contentStoreRelPathFor(session.id)])}contentStoreById(id,meta){return this.readContentStoreRels(id,[contentStoreRelPathFor(id,meta?.protocol,meta?.upstreamOrigin),contentStoreRelPathFor(id)])}candidateContentStorePaths(id,rels){const source=this.sourceFiles.get(id);const sourceCcr=source?source.endsWith(".fb.json")?`${source.slice(0,-".fb.json".length)}.content-store.json`:`${source.slice(0,-".json".length)}.content-store.json`:null;return[...new Set([...sourceCcr?[sourceCcr]:[],...rels.map(rel2=>path25.join(this.sessionsDir,rel2)),...this.diskFiles.filter(file=>fileNameMatchesId(path25.basename(file),id)).map(file=>file.replace(/\.json$/,".content-store.json"))])]}readContentStoreRels(id,rels){if(!this.enabled)return null;for(const file of this.candidateContentStorePaths(id,rels)){let buf;try{buf=readFileSync9(file)}catch(err2){if(err2.code==="ENOENT")continue;if(!this.boundedReads){this.log("warn",`[persist] content store for ${id} unreadable, starting fresh: ${String(err2)}`);return null}throw new Error(`Content store for ${id} cannot be read; refusing to replace its originals`,{cause:err2})}try{const text2=this.readCodec.decode(buf);const parsed=JSON.parse(text2);if(parsed&&typeof parsed==="object"&&parsed.version===1&&parsed.byHash&&typeof parsed.byHash==="object"&&parsed.byRef&&typeof parsed.byRef==="object"){return parsed}throw new Error(`Content store for ${id} is malformed; refusing to replace its originals`)}catch(err2){if(!this.boundedReads){this.log("warn",`[persist] content store for ${id} unreadable, starting fresh: ${String(err2)}`);return null}throw new Error(`Content store for ${id} unreadable; refusing to replace its originals`,{cause:err2})}}return null}writeContentStoreSidecar(id,meta,store2){const rel2=contentStoreRelPathFor(id,meta?.protocol,meta?.upstreamOrigin);const abs=path25.join(this.sessionsDir,rel2);const tmp=path25.join(path25.dirname(abs),`.tmp-${path25.basename(abs,".json")}-${process.pid}-${this.tmpSeq++}`);try{mkdirSync7(path25.dirname(abs),{recursive:true});const text2=JSON.stringify(store2);durableWriteFile(tmp,this.codec?this.codec.encode(text2):text2);renameSync2(tmp,abs)}catch(err2){try{rmSync(tmp,{force:true})}catch{}this.log("warn",`[persist] content-store restore write failed for ${id}: ${err2 instanceof Error?err2.message:String(err2)}`)}}saveContentStore(session){if(!this.enabled||!session.contentStoreDirty)return true;const rel2=contentStoreRelPathFor(session.id,session.meta.protocol,session.meta.upstreamOrigin);const abs=path25.join(this.sessionsDir,rel2);const tmp=path25.join(path25.dirname(abs),`.tmp-${path25.basename(abs,".json")}-${process.pid}-${this.tmpSeq++}`);try{if(!session.contentStore||Object.keys(session.contentStore.byRef).length===0){rmSync(abs,{force:true});session.contentStoreDirty=false;return true}mkdirSync7(path25.dirname(abs),{recursive:true});const text2=JSON.stringify(session.contentStore);durableWriteFile(tmp,this.codec?this.codec.encode(text2):text2,384);renameSync2(tmp,abs);session.contentStoreDirty=false;return true}catch(err2){try{rmSync(tmp,{force:true})}catch{}session.contentStoreDirty=true;this.log("warn",`[persist] content-store write failed for ${session.id}: ${err2 instanceof Error?err2.message:String(err2)}`);return false}}async loadAll(){const out=new Map;if(!this.enabled)return out;let clamped=0;for(const[id,envelope]of await this.store.loadAll()){const session=this.buildForLoadAll(id,envelope.payload);if(hasNegativePersistedTokens(envelope.payload)){const warmProof=session.revisionEpoch;await this.store.writeNow(id,()=>this.buildRecordForSave(session));this.noteDurable(id,warmProof);clamped++;this.ownCommit.delete(id)}out.set(id,session)}if(this.shadow?.readsUnified||this.networkFullExpected){if(this.networkFullExpected)await this.ready();for(const id of await this.unionIds()){if(out.has(id))continue;const session=await this.loadAsync(id);if(session)out.set(id,session)}}if(clamped>0){log("info",`[persist] one-time migration (#408): clamped negative lastInputTokens/contextTokens in ${clamped} session(s) to 0`)}return out}async boot(limits){if(!this.enabled)return new Map;await this.sweepStaleTemps();if(limits)return this.bootBounded(limits);const loaded=await this.store.loadAll();await this.applyLegacyMigration(loaded);const out=new Map;for(const[id,envelope]of loaded){out.set(id,this.buildForLoadAll(id,envelope.payload))}if(this.shadow?.readsUnified||this.networkFullExpected){if(this.networkFullExpected)await this.ready();for(const id of await this.unionIds()){if(out.has(id))continue;const session=await this.loadAsync(id);if(session)out.set(id,session)}}return out}stateFileOnDisk(id){for(const root of[this.sessionsDir,`${this.sessionsDir}-cold`]){if(existsSync7(path25.join(root,relPathFor(id))))return true;if(existsSync7(path25.join(root,flatFileNameFor(id))))return true}return false}async unionIds(){const shadow=this.shadow;if(!shadow)return[];if(!shadow.isAsyncBackend)return shadow.listSessionIds();const rows=await shadow.sessionSummariesAsync();rows.sort((a,b2)=>b2.updatedAt-a.updatedAt);return rows.map(r=>r.sessionId)}async bootBounded(limits){if(!Number.isFinite(limits.maxSessions)||limits.maxSessions<0||!Number.isFinite(limits.maxBytes)||limits.maxBytes<0){throw new Error("Invalid session boot limits")}this.boundedReads=true;mkdirSync7(this.sessionsDir,{recursive:true});this.diskFiles=[];this.diskFilesSeeded=true;this.legacyAliases.clear();const warm=[];const canonical2=new Set;const filesByRoot=new Map;for(const root of[this.sessionsDir,`${this.sessionsDir}-cold`]){const files=existsSync7(root)?await walkJsonFiles(root):[];for(const file of files){if(path25.basename(file).endsWith(".content-store.json"))continue;this.diskFiles.push(file);filesByRoot.set(root,[...filesByRoot.get(root)??[],file])}}if(this.replicasAvailable()){this.seedIndexedAliases(canonical2);const hot=(filesByRoot.get(this.sessionsDir)??[]).map(file=>{try{const st2=statSync6(file);return{file,mtimeMs:st2.mtimeMs,size:st2.size}}catch{return null}}).filter(c=>c!==null).sort((a,b2)=>b2.mtimeMs-a.mtimeMs);const parsedFiles=new Set;const parsedCands=[];let windowBytes=0;for(const cand of hot){if(parsedCands.length>=limits.maxSessions&&windowBytes>=limits.maxBytes)break;if(cand.size>limits.maxBytes)continue;const parsed=await this.readRawFileWithBytes(cand.file);parsedFiles.add(cand.file);if(!parsed)continue;const rec=this.parseBootPayload(parsed.value);if(!rec||!fileNameMatchesId(path25.basename(cand.file),rec.payload.id,rec.meta.protocol,rec.meta.upstreamOrigin))continue;const savedAt=rec.payload.savedAt??0;if(rec.payload.id===rec.meta.label||rec.payload.id.startsWith("pfa-"))this.noteCanonical(rec.payload.id,canonical2);else if(rec.meta.label)this.upsertLegacyAlias(rec.meta.label,{file:cand.file,id:rec.payload.id,savedAt},canonical2);const bytes=parsed.bytes;if(bytes>limits.maxBytes)continue;windowBytes+=bytes;parsedCands.push({file:cand.file,id:rec.payload.id,meta:rec.meta,savedAt,bytes})}parsedCands.sort((a,b2)=>b2.savedAt-a.savedAt);while(parsedCands.length>limits.maxSessions||parsedCands.reduce((sum,item)=>sum+item.bytes,0)>limits.maxBytes)parsedCands.pop();warm.push(...parsedCands);this.remainderScan=this.scanRemainderInBackground(parsedFiles,canonical2);void this.remainderScan}else{for(const root of[this.sessionsDir,`${this.sessionsDir}-cold`]){for(const file of filesByRoot.get(root)??[]){const parsed=await this.readRawFileWithBytes(file);if(!parsed)continue;const rec=this.parseBootPayload(parsed.value);if(!rec||!fileNameMatchesId(path25.basename(file),rec.payload.id,rec.meta.protocol,rec.meta.upstreamOrigin))continue;const savedAt=rec.payload.savedAt??0;if(rec.payload.id===rec.meta.label||rec.payload.id.startsWith("pfa-"))canonical2.add(rec.payload.id);else if(rec.meta.label){const previous=this.legacyAliases.get(rec.meta.label);if(!previous||savedAt>=previous.savedAt)this.legacyAliases.set(rec.meta.label,{file,id:rec.payload.id,savedAt})}if(root!==this.sessionsDir)continue;const bytes=parsed.bytes;if(bytes>limits.maxBytes)continue;warm.push({file,id:rec.payload.id,meta:rec.meta,savedAt,bytes});warm.sort((a,b2)=>b2.savedAt-a.savedAt);while(warm.length>limits.maxSessions||warm.reduce((sum,item)=>sum+item.bytes,0)>limits.maxBytes)warm.pop()}}}for(const id of canonical2)this.legacyAliases.delete(id);const out=new Map;for(const item of warm){const alias=item.meta?.label&&this.legacyAliases.get(item.meta.label);if(alias&&alias.file!==item.file)continue;const id=alias?item.meta.label:item.id;const session=this.loadSync(id,item.meta);if(session)out.set(id,session)}if(this.shadow?.readsUnified||this.networkFullExpected){if(this.networkFullExpected)await this.ready();let warmBytes=0;for(const item of warm)warmBytes+=item.bytes;for(const id of await this.unionIds()){if(out.size>=limits.maxSessions)break;if(warmBytes>=limits.maxBytes)break;if(out.has(id))continue;if(this.stateFileOnDisk(id))continue;const session=await this.loadAsync(id);if(!session)continue;const bytes=this.estimateDecodedBytes(session);if(warmBytes+bytes>limits.maxBytes)continue;warmBytes+=bytes;out.set(id,session)}}this.log("info",`[persist] indexed ${this.diskFiles.length} state files; warmed ${out.size} sessions within ${limits.maxBytes} decoded bytes; older states load on demand`);return out}parseBootPayload(raw){const payload=raw&&typeof raw==="object"&&"payload"in raw?raw.payload:raw;if(!isValidRecord(payload))return null;const meta=payload.meta??{protocol:payload.protocol,upstreamOrigin:payload.upstreamOrigin,label:payload.label};return{payload,meta}}noteCanonical(id,canonical2){canonical2.add(id);this.legacyAliases.delete(id)}upsertLegacyAlias(label,entry,canonical2){if(canonical2.has(label))return false;const previous=this.legacyAliases.get(label);if(previous&&entry.savedAt<previous.savedAt)return false;this.legacyAliases.set(label,entry);return true}seedIndexedAliases(canonical2){const shadow=this.shadow;if(!shadow)return;let rows;try{rows=shadow.sessionSummaries()}catch{return}for(const r of rows){if(!r.label||r.label===r.sessionId||r.sessionId.startsWith("pfa-"))continue;const file=this.resolveIndexedFile(r.sessionId,r.protocol,r.origin);if(!file)continue;this.upsertLegacyAlias(r.label,{file,id:r.sessionId,savedAt:r.updatedAt},canonical2)}}resolveIndexedFile(id,protocol,origin){const candidates=[relPathFor(id,protocol,origin),relPathFor(id),flatFileNameFor(id)];for(const root of[this.sessionsDir,`${this.sessionsDir}-cold`]){for(const rel2 of candidates){const file=path25.join(root,rel2);try{if(statSync6(file).isFile())return file}catch{}}}return null}async scanRemainderInBackground(parsedFiles,canonical2){let scanned=0;let aliased=0;for(const file of this.diskFiles){if(parsedFiles.has(file))continue;scanned++;const parsed=await this.readRawFileWithBytes(file);if(parsed){const rec=this.parseBootPayload(parsed.value);if(rec&&fileNameMatchesId(path25.basename(file),rec.payload.id,rec.meta.protocol,rec.meta.upstreamOrigin)){const savedAt=rec.payload.savedAt??0;if(rec.payload.id===rec.meta.label||rec.payload.id.startsWith("pfa-"))this.noteCanonical(rec.payload.id,canonical2);else if(rec.meta.label)aliased+=this.upsertLegacyAlias(rec.meta.label,{file,id:rec.payload.id,savedAt},canonical2)?1:0}}await new Promise(resolve2=>setImmediate(resolve2))}if(scanned>0){this.log("info",`[persist] background index scan finished after boot: ${scanned} file(s) scanned, ${aliased} alias(es) recorded`)}}backgroundScanComplete(){return this.remainderScan??Promise.resolve()}readEnvelopeFile(file,id){let bytes;try{bytes=readFileSync9(file)}catch(err2){if(err2.code==="ENOENT")return null;throw err2}let raw;try{raw=JSON.parse(bytes.toString("utf8"))}catch{try{raw=JSON.parse(this.readCodec.decode(bytes))}catch(decodeError){this.quarantineCorruptState(file,id,decodeError);return null}}const payload=raw&&typeof raw==="object"&&"payload"in raw?raw.payload:raw;if(!isValidRecord(payload)){this.quarantineCorruptState(file,id,new Error(`record for ${id} failed validation`));return null}if(raw&&typeof raw==="object"&&"payload"in raw&&"id"in raw&&raw.id!==id)return null;if(payload.id!==id)return null;return{id,payload,version:payload.version,savedAt:payload.savedAt}}quarantineCorruptState(file,id,cause){const causeText=cause instanceof Error?cause.message:String(cause);const quarantinePath=`${file}.corrupt-${Date.now()}`;try{renameSync2(file,quarantinePath);this.log("warn",`[persist] quarantined undecodable session state ${path25.basename(file)} \u2192 ${path25.basename(quarantinePath)}; starting ${id} fresh (${causeText})`)}catch(renameErr){this.log("error",`[persist] failed to quarantine corrupt session state ${path25.basename(file)}; resuming ${id} empty this load (${causeText}; rename: ${renameErr instanceof Error?renameErr.message:String(renameErr)})`)}}buildForLoadAll(id,payload){if(this.shadow?.readsUnified){const dbAt=this.shadow.sessionUpdatedAt(id);if(dbAt===null||payload.savedAt>dbAt){this.shadow.importRecord(payload)}const view=this.shadow.viewFor(id);if(view)return buildSession(viewToRecord(view))}return buildSession(payload)}async sweepStaleTemps(){let files;try{files=await walkJsonFiles(this.sessionsDir)}catch{return}for(const file of files){if(isStaleTempName(path25.basename(file))){await rm2(file,{force:true}).catch(()=>{})}}}async migrateLegacyIds(){if(!this.enabled)return;if(existsSync7(this.markerPath()))return;const loaded=await this.store.loadAll();await this.applyLegacyMigration(loaded)}markerPath(){return path25.join(this.sessionsDir,MIGRATION_MARKER)}async applyLegacyMigration(loaded){if(existsSync7(this.markerPath()))return;const claimed=new Set;const byLabel=new Map;let unlabeled=0;for(const[id,envelope]of loaded){if(id.startsWith("pfa-"))continue;const session=buildSession(envelope.payload);const label=session.meta.label;if(!label){unlabeled++;continue}if(label===id){claimed.add(id);continue}const prev=byLabel.get(label);if(!prev||envelope.savedAt>=prev.savedAt){if(prev){await this.removeLegacyFile(prev.id,prev.session);loaded.delete(prev.id)}byLabel.set(label,{id,savedAt:envelope.savedAt,session})}else{await this.removeLegacyFile(id,session);loaded.delete(id)}}let rekeyed=0;for(const[label,{id,session}]of byLabel){if(claimed.has(label)){await this.removeLegacyFile(id,session);loaded.delete(id);continue}session.id=label;const rekeyProof=session.revisionEpoch;await this.store.writeNow(label,()=>this.buildRecordForSave(session));this.noteDurable(label,rekeyProof);this.ownCommit.delete(label);await this.removeLegacyFile(id,session);const envelope=loaded.get(id);if(envelope){loaded.set(label,{...envelope,id:label,payload:{...envelope.payload,id:label}})}loaded.delete(id);claimed.add(label);rekeyed++}try{mkdirSync7(this.sessionsDir,{recursive:true});writeFileSync6(this.markerPath(),String(Date.now()),"utf8")}catch{}if(rekeyed||unlabeled){log("info",`[persist] one-time migration (#286): rekeyed ${rekeyed} legacy session(s), left ${unlabeled} unlabeled legacy file(s) in place`)}}async removeLegacyFile(id,session){this.shadow?.remove(id);await this.removeSessionFiles(id,session.meta)}async findSessionFiles(id,meta){const rels=new Set;for(const rel2 of[relPathFor(id,meta?.protocol,meta?.upstreamOrigin),relPathFor(id),flatFileNameFor(id)]){if(existsSync7(path25.join(this.sessionsDir,rel2)))rels.add(rel2)}const expected=path25.basename(relPathFor(id));const matches=base=>fileNameMatchesId(base,id,meta?.protocol,meta?.upstreamOrigin)||base.endsWith(`_${expected}`);try{for(const entry of await readdir2(this.sessionsDir,{withFileTypes:true})){if(entry.isFile()){if(matches(entry.name))rels.add(entry.name);continue}if(!entry.isDirectory())continue;try{for(const f2 of await readdir2(path25.join(this.sessionsDir,entry.name),{withFileTypes:true})){if(f2.isFile()&&matches(f2.name))rels.add(path25.join(entry.name,f2.name))}}catch{}}}catch{}return[...rels]}async removeSessionFiles(id,meta){for(const rel2 of await this.findSessionFiles(id,meta)){await rm2(path25.join(this.sessionsDir,rel2),{force:true}).catch(()=>{});if(rel2.endsWith(".json")&&!rel2.endsWith(".fb.json")){await rm2(path25.join(this.sessionsDir,`${rel2.slice(0,-".json".length)}.content-store.json`),{force:true}).catch(()=>{})}}}async removeSession(id){let meta;const unifiedAvailable=this.replicasAvailable();if(unifiedAvailable){try{const row=this.liveShadow().sessionSummaries().find(r=>r.sessionId===id);if(row&&(row.protocol||row.origin))meta={protocol:row.protocol,upstreamOrigin:row.origin}}catch{}}const envelope=this.loadEnvelope(id,meta);if(envelope)meta={...meta,...envelope.payload.meta};const unifiedHadRows=unifiedAvailable&&this.liveShadow().sessionUpdatedAt(id)!==null;const files=await this.findSessionFiles(id,meta);if(unifiedAvailable)this.liveShadow().remove(id);await this.removeSessionFiles(id,meta);return{envelopeFound:files.length>0||envelope!==null,unifiedHadRows}}loadEnvelope(id,meta){if(meta?.protocol){const pooled=this.loadNamespacedPool(id,{protocol:meta.protocol,upstreamOrigin:meta.upstreamOrigin});if(pooled)return pooled}const livePaths=new Set([path25.join(this.sessionsDir,relPathFor(id,meta?.protocol,meta?.upstreamOrigin)),path25.join(this.sessionsDir,relPathFor(id)),path25.join(this.sessionsDir,flatFileNameFor(id))]);for(const file of livePaths){if(!existsSync7(file))continue;const envelope=this.readEnvelopeFile(file,id);if(envelope){this.sourceFiles.set(id,file);return envelope}}if(!this.diskFilesSeeded&&this.shadow){this.diskFiles=[...walkJsonFilesSync(this.sessionsDir),...existsSync7(`${this.sessionsDir}-cold`)?walkJsonFilesSync(`${this.sessionsDir}-cold`):[]].filter(f2=>!path25.basename(f2).endsWith(".content-store.json"));this.diskFilesSeeded=true}const expected=path25.basename(relPathFor(id,meta?.protocol,meta?.upstreamOrigin));const candidates=this.diskFiles.filter(file=>fileNameMatchesId(path25.basename(file),id,meta?.protocol,meta?.upstreamOrigin)||!meta?.protocol&&path25.basename(file).endsWith(`_${expected}`));for(const file of candidates){if(!existsSync7(file))continue;const envelope=this.readEnvelopeFile(file,id);if(envelope){this.sourceFiles.set(id,file);return envelope}}const alias=this.legacyAliases.get(id);if(alias){const envelope=this.readEnvelopeFile(alias.file,alias.id);if(envelope&&(!meta?.protocol||envelope.payload.meta?.protocol===meta.protocol)){this.sourceFiles.set(id,alias.file);return{...envelope,id,payload:{...envelope.payload,id}}}}return this.store.loadSync(id,relPathFor(id,meta?.protocol,meta?.upstreamOrigin))}loadNamespacedPool(id,meta){const proto=meta.protocol;const dir=path25.join(this.sessionsDir,proto);const logicalFor=file=>file.endsWith(".fb.json")?`${file.slice(0,-".fb.json".length)}.json`:file;const candidates=new Set([path25.join(dir,path25.basename(relPathFor(id,proto,meta.upstreamOrigin)))]);const suffix=`_${path25.basename(relPathFor(id))}`;for(const file of this.diskFiles){const base=path25.basename(file);if(base.endsWith(".content-store.json"))continue;if(path25.dirname(file)!==dir||!logicalFor(base).endsWith(suffix))continue;candidates.add(file)}const valid=new Map;for(const file of candidates){if(!existsSync7(file))continue;const env=this.readEnvelopeFile(file,id);if(!env)continue;const savedProtocol=env.payload.meta?.protocol??env.payload.protocol;if(savedProtocol&&savedProtocol!==proto)continue;const prior=valid.get(logicalFor(file));if(!prior||(env.savedAt??0)>(prior.env.savedAt??0))valid.set(logicalFor(file),{file,env})}if(valid.size===0)return null;const exact=path25.join(this.sessionsDir,relPathFor(id,proto,meta.upstreamOrigin));const winner=[...valid.values()].sort((a,b2)=>{const ra=a.env.payload.stats?.requests??a.env.payload.requests??0;const rb2=b2.env.payload.stats?.requests??b2.env.payload.requests??0;if(ra!==rb2)return rb2-ra;const na=a.env.payload.state?.nextBlockId??0;const nb=b2.env.payload.state?.nextBlockId??0;if(na!==nb)return nb-na;if(a.file===exact)return-1;if(b2.file===exact)return 1;return(b2.env.savedAt??0)-(a.env.savedAt??0)})[0];this.sourceFiles.set(id,winner.file);if(winner.file!==exact){this.log("info",`[persist] restored ${id} from another upstream route (${path25.basename(winner.file)}; ${winner.env.payload.stats?.requests??winner.env.payload.requests??0} requests) under protocol ${proto} (#3399)`)}return winner.env}adoptRequestedRoute(id,session,meta){if(!meta?.protocol||!meta.upstreamOrigin)return;const src=this.sourceFiles.get(id);if(!src||src===path25.join(this.sessionsDir,relPathFor(id,meta.protocol,meta.upstreamOrigin)))return;if(session.meta.upstreamOrigin===meta.upstreamOrigin)return;session.meta.upstreamOrigin=meta.upstreamOrigin;this.log("info",`[persist] adopted route ${hostLabel(meta.upstreamOrigin)} for ${id} restored from ${path25.basename(src)} (#3399)`);this.scheduleSave(session)}logColdLoad(id,source,session,savedAt){const refs=Object.keys(session.state.messageRefs.byRef??{}).length;const blocks=session.state.blocks.length;const active=session.state.blocks.filter(b2=>b2.active).length;const compressions=session.state.stats?.compressionCount??0;const ageMin=savedAt?Math.round(Math.max(0,Date.now()-savedAt)/6e4):void 0;this.log("info",`[persist] cold-loaded ${id} from ${source}: ${refs} ref(s), ${blocks} block(s) (${active} active), baseline ${session.stats.lastInputTokens} tok, compressions ${compressions}${ageMin!==void 0?`, savedAt ~${ageMin} min ago`:""}`);if(refs>0&&blocks===0){this.log("warn",`[persist] ${id} loaded with ${refs} mapped ref(s) but NO persisted blocks (compressions=${compressions}) \u2014 the folded history will replay raw and preflight must rebuild from scratch (#3573)`)}}loadSync(id,meta){if(!this.enabled)return null;this.durableRevision.delete(id);if(this.shadow?.readsUnified){if(this.shadow.driftedSessions.has(id)){const driftedEnvelope=this.loadEnvelope(id,meta);if(driftedEnvelope){const envActive=countActiveBlocks(driftedEnvelope.payload);const idxActive=this.shadow.activeBlockCount(id);if(idxActive!==null&&idxActive>envActive){const unified2=this.loadUnified(id);if(unified2){this.log("warn",`[persist] serving ${id} from the UNIFIED store despite the drift latch: legacy envelope holds ${envActive} active block(s), the index holds ${idxActive} \u2014 taking the fuller fold coverage instead of the older generation (#4323/#394)`);return this.afterLoad(id,unified2)}}const drifted=buildSession(driftedEnvelope.payload);const unifiedView=this.loadUnified(id);if(unifiedView){const envRefs=Object.keys(drifted.state.messageRefs?.byRef??{}).length;const idxState=unifiedView.state;const idxRefs=Object.keys(idxState.messageRefs?.byRef??{}).length;if(idxRefs>envRefs){this.log("warn",`[persist] drift on ${id}: unified index carries ${idxRefs} mapped ref(s) vs envelope ${envRefs} \u2014 serving the richer index side (multi-writer generation, #4323)`);return this.afterLoad(id,unifiedView)}}if(hasNegativePersistedTokens(driftedEnvelope.payload)){this.scheduleSave(drifted);this.log("info",`[persist] clamped negative token stats on reload for ${id} (#408)`)}this.log("info",`[persist] serving ${id} from the legacy envelope: last sampled digest drifted (#3135 \u2463)`);this.logColdLoad(id,"legacy file (drift fallback)",drifted,driftedEnvelope.payload.savedAt);this.noteDurable(id,drifted.revisionEpoch);return drifted}}const unified=this.loadUnified(id);if(unified){const envelope3=this.loadEnvelope(id,meta);if(envelope3){const indexedRequests=Number(unified.stats.requests??0);const envRequests=Number(envelope3.payload.stats?.requests??0);const ahead=envRequests>indexedRequests||envRequests===indexedRequests&&Number(envelope3.payload.state?.nextBlockId??0)>unified.state.nextBlockId;if(ahead){const recovered=buildSession(envelope3.payload);this.log("info",`[persist] recovering ${id} from a strictly-ahead envelope on cold load (index requests ${indexedRequests}, envelope ${envRequests}${orphanContents(unified)?", orphan-frozen index":""})`);return this.afterLoad(id,this.shadow.importRecord(envelope3.payload)??toLegacyLike(recovered))}}return this.afterLoad(id,unified)}const envelope2=this.loadEnvelope(id,meta);if(!envelope2)return null;const imported=this.shadow.importRecord(envelope2.payload);if(imported){return this.afterLoad(id,imported)}const session2=buildSession(envelope2.payload);if(hasNegativePersistedTokens(envelope2.payload)){this.scheduleSave(session2);this.log("info",`[persist] clamped negative token stats on reload for ${id} (#408)`)}this.logColdLoad(id,"legacy file",session2,envelope2.payload.savedAt);this.adoptRequestedRoute(id,session2,meta);this.noteDurable(id,session2.revisionEpoch);return session2}const envelope=this.loadEnvelope(id,meta);if(!envelope)return null;const session=buildSession(envelope.payload);if(hasNegativePersistedTokens(envelope.payload)){this.scheduleSave(session);this.log("info",`[persist] clamped negative token stats on reload for ${id} (#408)`)}this.logColdLoad(id,"legacy file",session,envelope.payload.savedAt);this.adoptRequestedRoute(id,session,meta);this.noteDurable(id,session.revisionEpoch);return session}async loadAsync(id,meta){const sync=this.loadSync(id,meta);if(sync)return sync;const shadow=this.shadow;if(!shadow||!shadow.readsUnified||!shadow.isAsyncBackend)return null;await this.ready();const view=await shadow.viewForAsync(id);if(!view)return null;return this.afterLoad(id,view)}afterLoad(id,view){const record4=viewToRecord(view);const session=buildSession(record4);this.noteDurable(id,session.revisionEpoch);if(hasNegativePersistedTokens(record4)){this.scheduleSave(session);this.log("info",`[persist] clamped negative token stats on reload for ${id} (#408)`)}this.maybeRestampToLedger(session);this.logColdLoad(id,"unified store",session,record4.savedAt);return session}maybeRestampToLedger(session){const state7=session.state;if(state7.refLedgerAligned===true)return;if(!state7.messageRefs||Object.keys(state7.messageRefs.byRaw).length===0)return;try{const seqByRawId=this.unifiedSeqByRaw(session.id);if(seqByRawId===null||seqByRawId.size===0)return;const outcome=restampRefsToLedger(state7,seqByRawId);if(session.contentStore){const store2=contentStoreOf(session);const restampedStore=restampContentStore(store2,state7.messageRefs.byRaw);if(restampedStore!==store2)session.contentStore=restampedStore}if(outcome.superseded.size>0){session.restampSuperseded=outcome.superseded}else{delete session.restampSuperseded}const snap=state7.tokenSnapshot;if(snap&&outcome.superseded.size>0){const byRawNow=state7.messageRefs.byRaw;const moves=[];for(const[oldRef,rawId]of outcome.superseded){const count=snap[oldRef];const newRef=byRawNow[rawId];if(count===void 0||newRef===void 0||newRef===oldRef)continue;moves.push([oldRef,newRef,count])}if(moves.length>0){for(const[oldRef]of moves)delete snap[oldRef];for(const[,newRef,count]of moves)snap[newRef]=count;this.log("info",`[persist] remapped ${moves.length} token-snapshot entries onto ledger-aligned refs for ${session.id} (#4599)`)}}state7.refLedgerAligned=true;this.log("info",`[persist] ledger-aligned refs for ${session.id}: kept=${outcome.kept} restamped=${outcome.restamped} rehomed=${outcome.rehomed} blocked=${outcome.blocked} superseded=${outcome.superseded.size} (#4316 PR3/3)`);this.scheduleSave(session)}catch(err2){this.log("warn",`[persist] ref/ledger alignment skipped for ${session.id}: ${err2 instanceof Error?err2.message:String(err2)}`)}}loadUnified(id){return this.shadow?this.shadow.viewFor(id):null}loadResidentFields(id,meta,fields){if(this.residentFieldsForBuild?.id===id)return this.residentFieldsForBuild.fields;if(!this.enabled)return null;const indexed=this.shadow?.readsUnified?this.shadow.readResidentFieldsFor(id,fields):null;const envelope=this.loadEnvelope(id,meta);let useEnvelope=indexed===null;if(indexed&&envelope){if(this.shadow?.driftedSessions.has(id)){const envActive=countActiveBlocks(envelope.payload);const envRefs=Object.keys(envelope.payload.state?.messageRefs?.byRef??{}).length;useEnvelope=indexed.header.activeBlockCount<=envActive&&indexed.header.mappedRefCount<=envRefs}else{const requests=Number(envelope.payload.stats?.requests??0);useEnvelope=requests>indexed.header.requests||requests===indexed.header.requests&&Number(envelope.payload.state?.nextBlockId??0)>indexed.header.nextBlockId}}if(useEnvelope){if(!envelope)return null;return{...fields.metadata?{metadata:envelope.payload.metadata??{}}:{},...fields.blockContents?{blockContents:Object.fromEntries(restoreBlockContents(Object.entries(envelope.payload.blockContents??{})))}:{}}}if(!indexed)return null;return{...fields.metadata?{metadata:indexed.metadata}:{},...fields.blockContents?{blockContents:Object.fromEntries(restoreBlockContents(indexed.blockContents??[]))}:{}}}buildRecordForSave(session,storageMode=effectiveFileStorageMode()){const bothDropped=isDroppedMetadata(session.metadata)&&session.blockContents instanceof LazyBlockContents&&session.blockContents.isDropped;if(!bothDropped)return buildRecord(session,storageMode);const previous=this.residentFieldsForBuild;const fields=this.loadResidentFields(session.id,session.meta??{},{metadata:true,blockContents:true});this.residentFieldsForBuild={id:session.id,fields};try{return buildRecord(session,storageMode)}finally{this.residentFieldsForBuild=previous}}loadStateForSearch(id){if(!this.enabled)return null;if(this.shadow?.readsUnified){const view=this.loadUnified(id);if(view)return mergeState(view.state)}const envelope=this.loadEnvelope(id);if(!envelope)return null;return mergeState(envelope.payload.state)}unifiedCcrFor(id){if(!this.shadow?.readsUnified)return null;try{return this.shadow.getCcr(id)}catch{return null}}unifiedMessageRows(sessionId,msgIds){if(!this.shadow?.readsUnified||msgIds.length===0)return null;try{return this.shadow.messagesForIds(sessionId,msgIds,true)}catch{return null}}sidecarDownReason(){return this.shadow===void 0?"sidecar-missing":"sidecar-disabled"}replicasAvailable(){if(this.syncSidecarOpen!==null&&this.shadow===void 0){const now=Date.now();if(now>=this.sidecarReadCheckNextAttemptAt){this.sidecarReadCheckNextAttemptAt=now+(shadowReopenReadCheckMsOverride??SHADOW_REOPEN_READ_CHECK_MS);this.tryRecoverSidecar(true)}}return this.shadow!==void 0&&!this.shadow.stats.disabled}async waitForReplicas(timeoutMs=RECON_REPLICAS_WAIT_MS,pollMs=RECON_REPLICAS_POLL_MS){const deadline=Date.now()+timeoutMs;for(;;){if(this.replicasAvailable())return true;if(this.sidecarDownReason()!=="sidecar-missing")return false;if(Date.now()>=deadline)return false;await new Promise(r=>setTimeout(r,pollMs))}}unifiedReads(){return this.enabled&&this.shadow?.readsUnified===true}unifiedSeqByRaw(id){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.seqByRaw(id)}catch{return null}}unifiedLastLiveSeqAsync(id){if(!this.shadow)return Promise.resolve(null);try{return this.shadow.lastLiveSeqAsync(id)}catch{return Promise.resolve(null)}}unifiedCloneSessionRowsAsync(parentId,childId,throughSeq){if(!this.shadow)return Promise.resolve(false);try{return this.shadow.cloneSessionRowsAsync(parentId,childId,throughSeq)}catch{return Promise.resolve(false)}}unifiedGc(opts={}){if(!this.shadow||this.shadow.stats.disabled)return null;try{const days=opts.archiveAfterDays??resolveArchiveAfterDays(void 0,fileStorageArchiveAfterDays());return this.shadow.gc({archiveAfterDays:days,archiveDir:opts.archiveDir??join7(this.sessionsDir,"archive"),vacuum:opts.vacuum})}catch(err2){this.log("warn",`[persist] unified gc failed: ${String(err2)}`);return null}}unifiedBackup(dst){if(!this.shadow||this.shadow.stats.disabled)return{ok:false,error:"unavailable"};try{const target=dst??join7(this.sessionsDir,"backups",`index-${new Date().toISOString().replace(/[:.]/g,"-")}.db`);const bytes=this.shadow.backupInto(target);this.log("info",`[persist] unified backup written: ${target} (${bytes} bytes)`);return{ok:true,path:target,bytes}}catch(err2){const error=String(err2);this.log("warn",`[persist] unified backup failed: ${error}`);return{ok:false,error}}}unifiedGcPlan(archiveAfterDays,now){if(!this.shadow||this.shadow.stats.disabled)return null;try{const days=archiveAfterDays??resolveArchiveAfterDays(void 0,fileStorageArchiveAfterDays());return this.shadow.gcPlan(days,now)}catch{return null}}unifiedActiveWriter(){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.activeForeignWriter()}catch{return null}}unifiedRestoreArchived(sessionId,archiveDir){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.restoreArchived(sessionId,{archiveDir:archiveDir??join7(this.sessionsDir,"archive")})}catch(err2){this.log("warn",`[persist] unified restore failed: ${String(err2)}`);return null}}unifiedArchiveSession(sessionId,archiveDir){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.archiveSession(sessionId,{archiveDir:archiveDir??join7(this.sessionsDir,"archive")})}catch(err2){this.log("warn",`[persist] unified archive failed: ${String(err2)}`);return null}}unifiedAllMessageIds(sessionId){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.allMessageIds(sessionId)}catch{return null}}unifiedGetBlocks(sessionId){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.getBlocks(sessionId)}catch{return null}}unifiedListSessionIds(){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.listSessionIds()}catch{return null}}unifiedArchiveBlock(sessionId,blockId,archiveDir){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.archiveBlock(sessionId,blockId,{archiveDir:archiveDir??join7(this.sessionsDir,"archive")})}catch(err2){this.log("warn",`[persist] unified block archive failed: ${String(err2)}`);return null}}unifiedRestoreBlock(sessionId,blockId,archiveDir){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.restoreBlock(sessionId,blockId,{archiveDir:archiveDir??join7(this.sessionsDir,"archive")})}catch(err2){this.log("warn",`[persist] unified block restore failed: ${String(err2)}`);return null}}unifiedSessionStorageStats(sessionId){if(!this.replicasAvailable())return null;try{return this.liveShadow().sessionStorageStats(sessionId)}catch{return null}}unifiedVacuum(mode="full"){this.liveShadow().vacuum(mode)}unifiedRawMessages(sessionId,fromSeqExclusive){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.rawMessages(sessionId,fromSeqExclusive)}catch{return null}}unifiedTailSeqs(sessionId){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.tailSeqs(sessionId)}catch{return null}}unifiedTailViewRows(sessionId){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.tailViewRows(sessionId)}catch{return null}}unifiedMessageContentByRefs(sessionId,refNums){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.messageContentByRefNums(sessionId,refNums)}catch{return null}}unifiedMessageIdRows(sessionId){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.messageIdRows(sessionId)}catch{return null}}unifiedUncoveredRows(sessionId,intervals){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.uncoveredRows(sessionId,intervals)}catch{return null}}unifiedSessionSummaries(){if(!this.shadow?.readsUnified)return null;try{return this.shadow.sessionSummaries()}catch{return null}}webSummaryBaseline(){if(!this.shadow||this.shadow.stats.disabled)return null;if(this.shadow.isAsyncBackend)return null;return this.shadow.mode==="full"?"authoritative":"reconcile"}unifiedWebSummaries(){if(this.webSummaryBaseline()===null)return null;const shadow=this.shadow;if(!shadow)return null;try{return shadow.webSummaryRows()}catch{return null}}lookupConversation(namespace,conversationId){if(!this.replicasAvailable())return null;try{return this.shadow.lookupConversation(namespace,conversationId)}catch{return null}}setSessionExt(sessionId,key2,value){this.liveShadow().setSessionExt(sessionId,key2,value)}getSessionExt(sessionId,key2){return this.liveShadow().getSessionExt(sessionId,key2)}listSessionExt(sessionId){return this.liveShadow().listSessionExt(sessionId)}deleteSessionExt(sessionId,key2){return this.liveShadow().deleteSessionExt(sessionId,key2)}setKv(namespace,key2,value){this.liveShadow().setKv(namespace,key2,value)}getKv(namespace,key2){return this.liveShadow().getKv(namespace,key2)}listKv(namespace,keyPrefix){return this.liveShadow().listKv(namespace,keyPrefix)}deleteKv(namespace,key2){return this.liveShadow().deleteKv(namespace,key2)}liveShadow(){if(!this.replicasAvailable())throw new Error("[storage] replicas require the unified store (storage.unified=shadow|full or BILI_STORAGE_UNIFIED); this instance runs legacy-only");return this.shadow}maybeCutForkBase(session){void this.maybeCutForkBaseAsync(session)}async maybeCutForkBaseAsync(session){if(!this.shadow||this.shadow.stats.disabled)return;const retained=session.metadata.publicForkReceipt!==void 0||session.metadata.publicSnapshotRetained===true;if(!retained||!Array.isArray(session.pluginSnapshot)||session.pluginSnapshot.length===0)return;if(this.forkBaseCut.has(session.id))return;try{if((await this.shadow.listCheckpointsAsync(session.id)).some(cp2=>cp2.kind==="fork_base")){this.forkBaseCut.add(session.id);return}const record4=this.buildRecordForSave(session);const activeBlockIds2=session.state.blocks.filter(b2=>b2.active!==false).map(b2=>b2.blockId).sort();await this.shadow.insertCheckpointAsync({cpId:`cp-${randomUUID4()}`,sessionId:session.id,seqAt:session.pluginSnapshot.length,blockSetHash:sha256Hex2(JSON.stringify(activeBlockIds2)),kind:"fork_base",label:`fork-base ${session.id}`,pinned:true,createdAt:Date.now(),stateJson:JSON.stringify(record4)});this.forkBaseCut.add(session.id)}catch(err2){this.log("warn",`[storage] fork_base checkpoint cut failed for ${session.id}: ${err2 instanceof Error?err2.message:String(err2)}`)}}async createReplica(sessionId,opts={}){const shadow=this.liveShadow();const view=await shadow.viewForAsync(sessionId);if(!view)throw new Error(`[storage] session ${sessionId} is not in the unified index (unknown, or never persisted under this mode)`);const record4=viewToRecord(view);const ccr=this.contentStoreById(sessionId,view.meta);if(ccr)record4.forkContentStore=ccr;const cpId=`cp-${randomUUID4()}`;const activeBlockIds2=view.state.blocks.filter(b2=>b2.active!==false).map(b2=>b2.blockId).sort();await shadow.insertCheckpointAsync({cpId,sessionId,seqAt:await this.shadow.sessionTipSeqAsync(sessionId),blockSetHash:sha256Hex2(JSON.stringify(activeBlockIds2)),kind:opts.kind??"replica",label:opts.label??null,pinned:opts.pinned===true,createdAt:Date.now(),stateJson:JSON.stringify(record4)});const row=await shadow.getCheckpointAsync(cpId);if(!row)throw new Error(`[storage] checkpoint ${cpId} missing right after insert (index inconsistency)`);return row}async listReplicas(sessionId){await this.ready();return this.liveShadow().listCheckpointsAsync(sessionId)}async replicaByteLen(cpId){return(await this.liveShadow().checkpointStateAsync(cpId)).byteLen}async restoreReplica(cpId,opts={}){const shadow=this.liveShadow();const cp2=await shadow.getCheckpointAsync(cpId);if(!cp2)throw new Error(`[storage] checkpoint not found: ${cpId}`);const{stateJson}=await shadow.checkpointStateAsync(cpId);const record4=JSON.parse(stateJson);const newId=opts.sessionId??`restore-${randomUUID4().slice(0,8)}`;if(opts.sessionId!==void 0&&this.loadEnvelope(newId)!==null){throw new Error(`[storage] session ${newId} already exists \u2014 restore to a fresh id or delete the existing session first`)}record4.id=newId;record4.savedAt=Date.now();record4.meta={...record4.meta,restoredFrom:cp2.session_id,restoredCheckpoint:cp2.cp_id};await this.store.writeNow(newId,()=>record4);shadow.record(record4);this.ownCommit.set(newId,{requests:record4.stats?.requests??record4.requests??0,nextBlockId:record4.state?.nextBlockId??0,builtAtMs:Date.now()});if(record4.forkContentStore){this.writeContentStoreSidecar(newId,record4.meta,record4.forkContentStore)}return{sessionId:newId,restoredFrom:cp2.session_id,seqAt:cp2.seq_at}}async deleteReplica(cpId){return this.liveShadow().deleteCheckpointAsync(cpId)}get dir(){return this.sessionsDir}async loadSessionFromFile(file,expectId){const parsed=await this.readRawFile(file);if(!parsed||typeof parsed!=="object")return null;const p2=parsed;const rec=p2.payload&&typeof p2.payload==="object"?p2.payload:parsed;if(!isValidRecord(rec))return null;if(expectId!==void 0&&rec.id!==expectId)return null;return buildSession(rec)}async readRawFileWithBytes(file){try{const raw=await readFile4(file);try{return{value:JSON.parse(raw.toString("utf8")),bytes:raw.byteLength}}catch{const text2=this.readCodec.decode(raw);return{value:JSON.parse(text2),bytes:Buffer.byteLength(text2,"utf8")}}}catch{return null}}async readRawFile(file){const parsed=await this.readRawFileWithBytes(file);return parsed?.value??null}async decodedBytesOf(file){const parsed=await this.readRawFileWithBytes(file);return parsed===null?null:parsed.bytes}staleDiskPayload(incoming){if(this.ownershipFastPath(incoming))return null;this.staleGuardFullReads++;const envelope=this.loadEnvelope(incoming.id,incoming.meta);if(!envelope)return null;const disk=envelope.payload;const diskRequests=disk.stats?.requests??disk.requests??0;const incRequests=incoming.stats?.requests??incoming.requests??0;if(incRequests<diskRequests)return disk;if(incRequests===diskRequests){const diskBlocks=disk.state?.nextBlockId??0;const incBlocks=incoming.state?.nextBlockId??0;if(incBlocks<diskBlocks)return disk}return null}ownershipFastPath(incoming){const own=this.ownCommit.get(incoming.id);if(!own)return false;const shadow=this.shadow;if(!shadow||shadow.stats.disabled)return false;const incRequests=incoming.stats?.requests??incoming.requests??0;const incBlocks=incoming.state?.nextBlockId??0;if(incRequests<own.requests||incBlocks<own.nextBlockId)return false;let row=null;try{row=shadow.sessionCounters(incoming.id)}catch{return false}if(!row||row.requests!==own.requests||row.nextBlockId!==own.nextBlockId)return false;const stat5=this.statEnvelope(incoming.id,incoming.meta);if(!stat5)return false;if(!own.written)return false;if(stat5.size!==own.written.size)return false;if(stat5.mtimeMs>own.written.mtimeMs+OWN_WRITE_STAMP_EPSILON_MS)return false;return true}statEnvelope(id,meta){const candidates=[];const known=this.sourceFiles.get(id);if(known)candidates.push(known);candidates.push(path25.join(this.sessionsDir,relPathFor(id,meta?.protocol,meta?.upstreamOrigin)),path25.join(this.sessionsDir,relPathFor(id)),path25.join(this.sessionsDir,flatFileNameFor(id)));for(const file of candidates){try{const st2=statSync6(file);return{size:st2.size,mtimeMs:st2.mtimeMs}}catch{}}return null}estimateDecodedBytes(session){try{return JSON.stringify(this.guardedBuild(session)()).length}catch{return Number.MAX_SAFE_INTEGER}}guardedBuild(session){const stamp2=this.liveStorageStamp;return()=>{const record4=this.buildRecordForSave(session,stamp2);const disk=this.staleDiskPayload(record4);if(disk===null){const payload=session.decompositionLog;if(payload!==void 0)session.decompositionLog=void 0;const tail=session.lastMessagesFolded!==true?session.lastMessages:void 0;this.shadow?.record(payload!==void 0?{...record4,decompositionLog:payload}:record4,tail&&tail.length>0?{lastMessages:tail,lastMessagesFolded:session.lastMessagesFolded}:void 0,session.contentStore??void 0);this.noteOwnCommit(session.id,record4);return record4}const now=Date.now();const last=this.staleWarnAt.get(record4.id)??0;if(now-last>=STALE_WARN_THROTTLE_MS){this.staleWarnAt.set(record4.id,now);this.log("warn",`[persist] rejected stale snapshot for session ${record4.id}: in-memory copy is older than the on-disk one (another bili instance holds newer state) \u2014 keeping disk state and converging in-memory state to it, so subsequent requests serve the fuller fold coverage instead of the stale view (#405/#2401)`)}this.convergeToDisk(session,disk);this.shadow?.record(disk);this.noteOwnCommit(session.id,disk);return disk}}noteOwnCommit(id,committed){const prev=this.ownCommit.get(id);this.ownCommit.set(id,{requests:committed.stats?.requests??committed.requests??0,nextBlockId:committed.state?.nextBlockId??0,builtAtMs:Date.now(),written:prev?.written,meta:committed.meta?{protocol:committed.meta.protocol,upstreamOrigin:committed.meta.upstreamOrigin}:prev?.meta});try{this.sessionCommitListener?.(id)}catch{}}stampOwnWrite(id){const token=this.ownCommit.get(id);if(!token)return;const stat5=this.statEnvelope(id,token.meta);if(!stat5)return;token.written=stat5}convergeToDisk(session,disk){const fresh=buildSession(disk);const droppedRetrievals=session.pendingRetrievals.length;session.state=fresh.state;session.blockContents=fresh.blockContents;session.stats=fresh.stats;session.lastMessages=fresh.lastMessages??session.lastMessages;session.lastMessagesFolded=fresh.lastMessages!==void 0?fresh.lastMessagesFolded:session.lastMessagesFolded;session.pluginSnapshot=fresh.pluginSnapshot;session.decompositionLog=fresh.decompositionLog??session.decompositionLog;session.lastSeen=fresh.lastSeen;if(!session.meta.protocol&&fresh.meta.protocol)session.meta.protocol=fresh.meta.protocol;if(!session.meta.upstreamOrigin&&fresh.meta.upstreamOrigin)session.meta.upstreamOrigin=fresh.meta.upstreamOrigin;if(!session.meta.label&&fresh.meta.label)session.meta.label=fresh.meta.label;session.pendingRetrievals.length=0;delete session.metadata.ccrUndelivered;delete session.metadata.ccrDropNotes;if(droppedRetrievals>0){this.log("warn",`[persist] ${session.id}: dropped ${droppedRetrievals} queued retrieval(s) during state convergence to the newer disk record (#2401)`)}markDirty(session)}scheduleSave(session){if(!this.saveContentStore(session))return;if(this.writerOffActive()||this.envelopeFrozen(session.id)){if(this.writerOffPending.has(session.id))return;const run=()=>{this.writerOffPending.delete(session.id);const proofRevision=session.revisionEpoch;let settledOk=false;try{this.guardedBuild(session)();this.maybeCutForkBase(session);this.noteDurable(session.id,proofRevision);this.lastSaveLanded.set(session.id,true);this.runIdleSpillIfIdle(session.id);settledOk=true}catch(err2){this.log("error",`[persist] writerOff coalesced build failed for ${session.id}: ${String(err2)}`)}finally{this.drainFlushWaiters(session.id,settledOk)}};this.writerOffPending.set(session.id,run);queueMicrotask(()=>{if(this.writerOffPending.get(session.id)===run)run()});return}if(!this.enabled)return;this.tryRecoverSidecar();const id=session.id;this.saveBuilders.set(id,this.guardedBuild(session));const existing=this.saveTimers.get(id);if(existing)return;const timer3=setTimeout(()=>{this.saveTimers.delete(id);const build2=this.saveBuilders.get(id);this.saveBuilders.delete(id);if(!build2)return;const proofRevision=peekSession(id)?.revisionEpoch;this.saveWritesInFlight.add(id);void this.store.writeNow(id,build2).then(()=>{this.stampOwnWrite(id);this.noteDurable(id,proofRevision);this.lastSaveLanded.set(id,true);this.runIdleSpillIfIdle(id)}).catch(()=>{this.lastSaveLanded.set(id,false)}).finally(()=>{this.saveWritesInFlight.delete(id);this.drainFlushWaiters(id,this.lastSaveLanded.get(id)===true)})},this.debounceMs);if(!this.flushWaiters.has(id))timer3.unref?.();this.saveTimers.set(id,timer3)}async afterNextFlush(sessionId){if(!this.saveTimers.has(sessionId)&&!this.writerOffPending.has(sessionId)&&!this.saveWritesInFlight.has(sessionId)){return true}return await new Promise(resolve2=>{const ws2=this.flushWaiters.get(sessionId)??[];ws2.push(ok=>{resolve2(ok)});this.flushWaiters.set(sessionId,ws2);this.saveTimers.get(sessionId)?.ref?.()})}drainFlushWaiters(sessionId,ok){const ws2=this.flushWaiters.get(sessionId);if(!ws2)return;this.flushWaiters.delete(sessionId);for(const w2 of ws2){try{w2(ok)}catch{}}}async spillBetweenTurns(session){if(session.inFlight>0)return;let landed;try{landed=await this.afterNextFlush(session.id)}catch{return}if(!landed)return;if(session.inFlight>0)return;const cap=sessionResidentHardMaxBytes();if(cap>0&&sessionWeight(session)>cap){const now=Date.now();if(now-(this.capWarnAt.get(session.id)??0)>=6e4){this.capWarnAt.set(session.id,now);this.log("warn",`[persist] ${session.id}: resident estimate ${sessionWeight(session)} B exceeds the per-session hard cap ${cap} B (#4788 D1-A) \u2014 discharging droppable fields back to disk now, including pool-exempt sessions; remainder (state/transient) is non-droppable`)}}this.runIdleSpill(session)}runIdleSpillIfIdle(id){const s3=peekSession(id);if(!s3||s3.inFlight>0)return;this.runIdleSpill(s3)}runIdleSpill(session){if(session.inFlight>0)return;if(this.durableRevision.get(session.id)!==(session.revisionEpoch??0))return;this.foldResidentTail(session);this.dropResidentBlockContents(session);this.dropResidentMetadata(session);this.dropResidentContentStore(session)}noteDurable(id,revisionEpoch){this.durableRevision.set(id,revisionEpoch??0)}async writeNow(session){if(!this.saveContentStore(session))throw new Error(`Originals were not saved for ${session.id}`);if(this.writerOffActive()||this.envelopeFrozen(session.id)){this.writerOffPending.delete(session.id);const proofRevision2=session.revisionEpoch;this.guardedBuild(session)();this.maybeCutForkBase(session);this.noteDurable(session.id,proofRevision2);this.lastSaveLanded.set(session.id,true);this.foldResidentTail(session);this.dropResidentBlockContents(session);this.dropResidentMetadata(session);this.dropResidentContentStore(session);return}const proofRevision=session.revisionEpoch;this.saveWritesInFlight.add(session.id);try{await this.store.writeNow(session.id,this.guardedBuild(session))}catch(err2){this.saveWritesInFlight.delete(session.id);throw err2}this.stampOwnWrite(session.id);this.maybeCutForkBase(session);this.noteDurable(session.id,proofRevision);this.lastSaveLanded.set(session.id,true);this.foldResidentTail(session);this.dropResidentBlockContents(session);this.dropResidentMetadata(session);this.dropResidentContentStore(session);this.drainFlushWaiters(session.id,true)}lazySource(id){const sh=this.shadow;if(!sh||!sh.readsUnified||sh.stats.disabled)return"file";if(sh.driftedSessions.has(id))return"file";return"index"}narrowMetadata(id,source,meta){const fromIndex=()=>this.shadow?.getSessionMetadata(id)??null;const fromFile=()=>{const env=this.loadEnvelope(id,meta);return env?env.payload.metadata??{}:null};if(source==="index"){const idx=fromIndex();return idx!==null?idx:fromFile()}const file=fromFile();return file!==null?file:fromIndex()}narrowBlockContents(id,source,meta){const fromIndex=()=>{const rows=this.shadow?.getBlockContents(id);return rows?Object.fromEntries(rows):null};const fromFile=()=>{const env=this.loadEnvelope(id,meta);return env?env.payload.blockContents??{}:null};if(source==="index"){const idx=fromIndex();return idx!==null?idx:fromFile()}const file=fromFile();return file!==null?file:fromIndex()}foldResidentTail(session){if(session.inFlight>0)return;const raw=session.lastMessages;if(!raw||raw.length===0)return;session.lastMessages=boundedFoldedSnapshot(session);session.lastMessagesFolded=true}dropResidentMetadata(session){if(session.inFlight>0||!this.enabled)return;if(isDroppedMetadata(session.metadata))return;if(Object.keys(session.metadata).length===0)return;const meta=session.meta??void 0;const source=this.lazySource(session.id);session.metadata=lazyMetadata(session.id,{protocol:meta?.protocol,upstreamOrigin:meta?.upstreamOrigin},(id,m2)=>{return this.loadResidentFields(id,m2,{metadata:true})?.metadata??null})}dropResidentBlockContents(session){if(session.inFlight>0||!this.enabled)return;const existing=session.blockContents;if(existing instanceof LazyBlockContents){existing.drop();return}if(existing.size===0)return;const source=this.lazySource(session.id);const lazy=new LazyBlockContents(session.id,{protocol:session.meta.protocol,upstreamOrigin:session.meta.upstreamOrigin},(id,meta)=>{return this.loadResidentFields(id,meta,{blockContents:true})?.blockContents??null});lazy.drop();session.blockContents=lazy}dropResidentContentStore(session){if(session.inFlight>0||!this.enabled)return;if(isDroppedContentStore(session.contentStore))return;if(session.contentStoreDirty)return;if(contentStorePinned())return;const store2=session.contentStore;if(!store2||Object.keys(store2.byRef).length===0)return;const meta=session.meta??void 0;if(!this.contentStoreLanded(session.id,meta)){return}session.contentStore=lazyContentStore(session.id,id=>this.unifiedCcrFor(id)??this.contentStoreById(id,{protocol:meta?.protocol,upstreamOrigin:meta?.upstreamOrigin}))}contentStoreLanded(id,meta){if(this.unifiedCcrFor(id)!==null)return true;for(const p2 of this.candidateContentStorePaths(id,[contentStoreRelPathFor(id,meta?.protocol,meta?.upstreamOrigin),contentStoreRelPathFor(id)])){try{if(existsSync7(p2))return true}catch{}}return false}tryRecoverSidecar(force=false){const args=this.syncSidecarOpen;if(!args||this.shadow!==void 0)return;if(hadIntegrityQuickCheckFailure())return;const now=Date.now();if(!force&&now<this.sidecarReopenNextAttemptAt)return;const cooldown=shadowReopenCooldownMsOverride??SHADOW_REOPEN_COOLDOWN_MS;this.sidecarReopenNextAttemptAt=now+cooldown;try{this.shadow=UnifiedShadow.maybeOpen(this.sessionsDir,process.env,args.legacyLoad,fileStorageUnified(),fileStorageWalJournalSizeLimit(),fileStorageBackend())??void 0}catch(err2){this.log("error",`[storage] sidecar reopen attempt failed (${String(err2)}) \u2014 still envelope-served; will retry next window (#5188)`);return}if(this.shadow!==void 0){this.log("info","[storage] unified sidecar recovered after a transient open failure \u2014 unified surfaces resume without a restart (#5188)");return}}flushSync(session){if(!this.saveContentStore(session))return false;this.tryRecoverSidecar();if(this.writerOffActive()||this.envelopeFrozen(session.id)){this.writerOffPending.delete(session.id);const proofRevision2=session.revisionEpoch;try{this.guardedBuild(session)()}catch(err2){this.log("error",`[persist] writerOff flushSync build failed for ${session.id}: ${String(err2)}`);return false}this.maybeCutForkBase(session);this.noteDurable(session.id,proofRevision2);this.lastSaveLanded.set(session.id,true);this.foldResidentTail(session);this.dropResidentBlockContents(session);this.dropResidentMetadata(session);this.dropResidentContentStore(session);return true}const armed2=this.saveTimers.get(session.id);if(armed2){clearTimeout(armed2);this.saveTimers.delete(session.id);this.saveBuilders.delete(session.id)}const proofRevision=session.revisionEpoch;const ok=this.store.flushSync(session.id,this.guardedBuild(session));if(ok){this.stampOwnWrite(session.id);this.noteDurable(session.id,proofRevision);this.maybeCutForkBase(session);this.foldResidentTail(session);this.dropResidentBlockContents(session);this.dropResidentMetadata(session);this.dropResidentContentStore(session)}return ok}async persistForkSession(parentId,session){await this.ready();const record4=buildRecord(session,this.liveStorageStamp);const cloned=await this.shadow?.createForkAsync(parentId,toLegacyLike(session))??false;if(!cloned){if(!this.flushSync(session))throw new Error("fork persistence failed");return}await this.maybeCutForkBaseAsync(session);if(!this.saveContentStore(session))throw new Error("fork content persistence failed; retry the same request");this.noteOwnCommit(session.id,record4);if(!this.writerOffActive()){if(!this.store.flushSync(session.id,()=>record4))throw new Error("fork envelope persistence failed; retry the same request");this.stampOwnWrite(session.id)}this.foldResidentTail(session);this.dropResidentBlockContents(session);this.dropResidentMetadata(session);this.dropResidentContentStore(session)}async recoverCompletedFork(id){await this.ready();if(this.loadEnvelope(id)!==null)return;const view=await this.shadow?.viewForAsync(id);if(!view)return;const record4=viewToRecord(view);const receipt=record4.metadata?.publicForkReceipt;if(typeof receipt?.requestHash!=="string"||receipt.response?.ok!==true||receipt.response.sessionId!==id||receipt.response.childConversationId!==id)return;const session=buildSession(record4);if(!this.saveContentStore(session))throw new Error("fork content recovery failed");this.noteOwnCommit(id,record4);if(!this.writerOffActive()){if(!this.store.flushSync(id,()=>record4))throw new Error("fork envelope recovery failed");this.stampOwnWrite(id)}await this.maybeCutForkBaseAsync(session)}async flushAll(sessions2=[]){this.drainWriterOffPending();for(const session of sessions2)this.saveContentStore(session);await this.flushScheduledSaves();await this.store.flushAll();this.shadow?.close()}async flushScheduledSaves(){const ids=[...this.saveTimers.keys()];for(const timer3 of this.saveTimers.values())clearTimeout(timer3);this.saveTimers.clear();const builders=new Map;for(const id of ids){const build2=this.saveBuilders.get(id);if(build2)builders.set(id,build2);this.saveBuilders.delete(id)}await Promise.all([...builders.entries()].map(([id,build2])=>this.store.writeNow(id,build2).then(()=>{this.stampOwnWrite(id)}).catch(e=>{this.log("error",`[persist] shutdown flush failed for ${id}: ${String(e)}`)})))}get liveStorageStamp(){if(!this.enabled)return"legacy";if(!this.shadow||this.shadow.stats.disabled)return"legacy";return this.storageMode}closeQuietly(){this.cancelAll();this.shadow?.close()}async closeQuietlyAsync(){await this.ready();this.cancelAll();await this.shadow?.closeAsync()}hasPending(id){return this.saveTimers.has(id)||this.writerOffPending.has(id)}writerOffActive(){return this.jsonWriterOff&&this.shadow!==void 0}envelopeFrozen(sessionId){return this.shadow?.envelopeFrozen(sessionId)??false}cancelAll(){for(const timer3 of this.saveTimers.values())clearTimeout(timer3);this.saveTimers.clear();this.saveBuilders.clear();this.store.cancelAll();this.writerOffPending.clear()}drainWriterOffPending(){if(this.writerOffPending.size===0)return;const runs=[...this.writerOffPending.values()];this.writerOffPending.clear();for(const run of runs)run()}};function effectiveFileStorageMode(){const live=peekStoreForStamp();if(live)return live.liveStorageStamp;const mode=resolveStorageModeForProcess();if(mode==="legacy")return"legacy";const keyEnv=process.env.BILI_ENCRYPTION_KEY;return keyEnv!==void 0&&keyEnv!==""?"legacy":mode}function buildRecord(session,storageMode=effectiveFileStorageMode()){const snapshot=boundedFoldedSnapshot(session);const observation=currentContextObservation(session);if(session.pluginSnapshot&&session.contentStore){const previous=session.metadata.publicSnapshotStoredRefs;session.metadata.publicSnapshotStoredRefs=[...new Set([...Array.isArray(previous)?previous:[],...session.pluginSnapshot.flatMap(m2=>{const ref=session.state.messageRefs.byRaw[m2.id];return ref&&session.contentStore.byRef[ref]?[ref]:[]})])]}return{version:PERSIST_VERSION,savedAt:Date.now(),id:session.id,meta:{...session.meta},stats:{...session.stats,...observation?{contextTokens:observation.tokens,contextTokensSource:observation.source}:{}},messages:snapshot,messagesFolded:snapshot?true:void 0,pluginSnapshot:session.metadata.publicForkReceipt!==void 0||session.metadata.publicSnapshotRetained===true?session.pluginSnapshot:void 0,forkContentStore:session.metadata.publicForkReceipt?session.contentStore:void 0,metadata:{...session.metadata,biliVersion:VERSION,storageMode},state:session.state,blockContents:Object.fromEntries(session.blockContents),createdAt:session.createdAt}}function isBlockView(v2){return!!v2&&typeof v2==="object"&&typeof v2.text==="string"&&typeof v2.count==="number"}function restoreCalibratedEstimate(v2){return typeof v2==="number"&&Number.isFinite(v2)&&v2>=CALIBRATION_CLAMP_MIN&&v2<=CALIBRATION_CLAMP_MAX?v2:void 0}function restoreCalibrationRing(v2){if(!v2||typeof v2!=="object")return void 0;const ring=v2;if(typeof ring.origin!=="string"||ring.origin.length===0)return void 0;if(!Array.isArray(ring.values))return void 0;const values=ring.values.filter(x=>typeof x==="number"&&Number.isFinite(x)&&x>=CALIBRATION_SAMPLE_MIN&&x<=CALIBRATION_SAMPLE_MAX);const recent=values.slice(-CALIBRATION_SAMPLE_WINDOW);return recent.length>0?{origin:ring.origin,values:recent}:void 0}function restoreBlockContents(entries2){const blockContents=new Map;for(const[bid,content]of entries2){if(!content||typeof content!=="object")continue;const full=content.full;if(!isBlockView(full))continue;const one=content.one;const oneView=isBlockView(one)?one:null;blockContents.set(bid,{one:oneView&&!(oneView.text===full.text&&oneView.count===full.count)?oneView:null,full})}return blockContents}function recordToLegacyView(record4){const s3=buildSession(record4);return toLegacyLike(s3)}function buildSession(parsed){const blockContents=restoreBlockContents(Object.entries(parsed.blockContents??{}));const meta=parsed.meta??{};const stats=parsed.stats??{};return{id:parsed.id,meta:{protocol:meta.protocol??parsed.protocol,upstreamOrigin:meta.upstreamOrigin??parsed.upstreamOrigin,label:meta.label??parsed.label,title:meta.title,activePack:typeof meta.activePack==="string"?meta.activePack:void 0,hostTitle:typeof meta.hostTitle==="string"?meta.hostTitle:void 0},stats:{requests:stats.requests??parsed.requests??0,tokensSaved:stats.tokensSaved??parsed.tokensSaved??0,inputTokens:stats.inputTokens??parsed.inputTokens??0,cachedTokens:stats.cachedTokens??parsed.cachedTokens??0,outputTokens:stats.outputTokens??parsed.outputTokens??0,cacheSamples:stats.cacheSamples??parsed.cacheSamples??0,lastInputTokens:Math.max(0,stats.lastInputTokens??parsed.lastInputTokens??0),lastInputTokensSource:stats.lastInputTokensSource==="usage"||stats.lastInputTokensSource==="estimate"||stats.lastInputTokensSource==="overflow-arm"?stats.lastInputTokensSource:void 0,overflowArmTokens:typeof stats.overflowArmTokens==="number"&&Number.isFinite(stats.overflowArmTokens)&&stats.overflowArmTokens>0?stats.overflowArmTokens:void 0,overflowArmCompletionReserve:typeof stats.overflowArmCompletionReserve==="number"&&Number.isFinite(stats.overflowArmCompletionReserve)&&stats.overflowArmCompletionReserve>0?stats.overflowArmCompletionReserve:void 0,overflowArmMismatchWarned:stats.overflowArmMismatchWarned===true?true:void 0,provenCompletionWall:typeof stats.provenCompletionWall==="number"&&Number.isFinite(stats.provenCompletionWall)&&stats.provenCompletionWall>0?stats.provenCompletionWall:void 0,provenCompletionWallOrigin:typeof stats.provenCompletionWallOrigin==="string"&&stats.provenCompletionWallOrigin.length>0?stats.provenCompletionWallOrigin:void 0,provenCompletionWallModel:typeof stats.provenCompletionWallModel==="string"&&stats.provenCompletionWallModel.length>0?stats.provenCompletionWallModel:void 0,compressCreditTokens:0,contextTokens:Math.max(0,stats.contextTokens??parsed.contextTokens??0),contextTokensSource:stats.contextTokensSource==="usage"||stats.contextTokensSource==="estimate"?stats.contextTokensSource:void 0,localInputEstimate:typeof stats.localInputEstimate==="number"&&Number.isFinite(stats.localInputEstimate)&&stats.localInputEstimate>0?stats.localInputEstimate:void 0,lastUsageGradeTokens:typeof stats.lastUsageGradeTokens==="number"&&Number.isFinite(stats.lastUsageGradeTokens)&&stats.lastUsageGradeTokens>=0?stats.lastUsageGradeTokens:void 0,lastInputTokensOrigin:typeof stats.lastInputTokensOrigin==="string"&&stats.lastInputTokensOrigin.trim().length>0?stats.lastInputTokensOrigin:void 0,calibratedEstimate:restoreCalibratedEstimate(stats.calibratedEstimate),calibratedEstimateOrigin:typeof stats.calibratedEstimateOrigin==="string"&&stats.calibratedEstimateOrigin.trim().length>0?stats.calibratedEstimateOrigin:void 0,calibrationRing:restoreCalibrationRing(stats.calibrationRing),retrieveCalls:stats.retrieveCalls??0,retrieveHits:stats.retrieveHits??0,retrieveMisses:stats.retrieveMisses??0,retrieveDropped:stats.retrieveDropped??0,retrieveDelivered:stats.retrieveDelivered??0,storedBytes:stats.storedBytes??0,storeBytesSaved:stats.storeBytesSaved??0,rangeRestores:stats.rangeRestores??0,wholeBlockRestores:stats.wholeBlockRestores??0,wholeBlockRestoresPreciseAvailable:stats.wholeBlockRestoresPreciseAvailable??0,costUsd:validCostUsd(stats.costUsd)},metadata:parsed.metadata??{},state:mergeState(parsed.state),createdAt:parsed.createdAt??Date.now(),lastSeen:parsed.savedAt??Date.now(),restored:true,ccrReconcilePending:true,blockContents,lastMessages:Array.isArray(parsed.messages)?parsed.messages:void 0,lastMessagesFolded:parsed.messagesFolded===true,pluginSnapshot:Array.isArray(parsed.pluginSnapshot)?parsed.pluginSnapshot:void 0,decompositionLog:Array.isArray(parsed.decompositionLog)?parsed.decompositionLog:void 0,contentStore:parsed.forkContentStore,inFlight:0,persisted:true,pendingRetrievals:[]}}function isValidRecord(parsed){if(!parsed||typeof parsed!=="object")return false;const r=parsed;return typeof r.id==="string"&&typeof r.state==="object"&&r.state!==null&&Array.isArray(r.state.blocks)}function hasNegativePersistedTokens(parsed){const stats=parsed.stats??{};const last=stats.lastInputTokens??parsed.lastInputTokens;const ctx=stats.contextTokens??parsed.contextTokens;return typeof last==="number"&&last<0||typeof ctx==="number"&&ctx<0}function countActiveBlocks(payload){const blocks=payload.state?.blocks;if(!Array.isArray(blocks))return 0;return blocks.filter(b2=>!!b2&&b2.active===true).length}function viewToRecord(view){const record4={version:PERSIST_VERSION,savedAt:view.lastSeen,id:view.id,createdAt:view.createdAt,meta:view.meta,stats:view.stats,metadata:view.metadata,state:view.state,blockContents:Object.fromEntries(view.blockContents)};if(view.lastMessages!==void 0){record4.messages=view.lastMessages;record4.messagesFolded=view.lastMessagesFolded===true}if(view.pluginSnapshot!==void 0)record4.pluginSnapshot=view.pluginSnapshot;if(view.contentStore!==void 0)record4.forkContentStore=view.contentStore;return record4}function resolveStorageModeSafe(){return resolveStorageModeForProcess()}function resolveStorageModeForProcess(){return resolveStorageMode(process.env,fileStorageUnified())}function storageStatusLabel(){const mode=resolveStorageModeForProcess();if(mode==="legacy")return"storage: legacy (json only)";const encrypted=process.env.BILI_ENCRYPTION_KEY!==void 0&&process.env.BILI_ENCRYPTION_KEY!=="";if(encrypted){return`storage: ${mode} requested \u2014 blocked by BILI_ENCRYPTION_KEY, running legacy-only`}if(mode!=="full")return"storage: shadow (dual-write dry-run \u2192 index.db)";return resolveJsonWriterOff(process.env,fileStorageJsonWriter())&&!encrypted?"storage: full (unified-only, json envelope off)":"storage: full (unified-first reads, dual-write)"}function defaultDir(){return sessionsDir()}function defaultDebounce(){return persistDebounceMs()}function persistEnabled2(){return persistEnabled()}function persistZstdEnabled2(){return persistZstdEnabled()}function isStaleTempName(name){return name.startsWith(".tmp-")||/\.tmp-enc-\d+-\d+$/.test(name)}function walkJsonFilesSync(dir,out=[]){let entries2;try{entries2=readdirSync2(dir,{withFileTypes:true})}catch{return out}for(const e of entries2){const full=path25.join(dir,e.name);if(e.isDirectory())walkJsonFilesSync(full,out);else if(e.isFile()&&(isStaleTempName(e.name)||e.name.endsWith(".json")))out.push(full)}return out}async function walkJsonFiles(dir){const entries2=await readdir2(dir,{withFileTypes:true});const out=[];for(const e of entries2){const full=path25.join(dir,e.name);if(e.isDirectory()){out.push(...await walkJsonFiles(full))}else if(e.isFile()&&(isStaleTempName(e.name)||e.name.endsWith(".json"))){out.push(full)}}return out}function persistTailTokens2(){return persistTailTokens()}function boundedFoldedSnapshot(session){const msgs=session.lastMessages;if(!msgs||msgs.length===0)return void 0;const budget=persistTailTokens2();if(budget===0)return void 0;let view=prune(msgs,session.state);let total=0;for(const m2 of view)total+=defaultCountTokens(m2.text??"");if(total>budget){let acc=0;let start=0;for(let i=view.length-1;i>=0;i--){acc+=defaultCountTokens(view[i].text??"");if(acc>budget){start=Math.min(i+1,view.length-1);break}}if(start>0)view=view.slice(start)}return view}function epermAlertThreshold(){return persistEpermAlertThreshold()}function epermAlertRepeatMs(){return persistEpermAlertRepeatMs()}function defaultLogger(level,m2){log(level,m2)}var _store=null;var globalSessionCommitListener;function peekStoreForStamp(){return _store}function peekStoredTailView(sessionId){const store2=peekStoreForStamp();if(!store2)return null;const rows=store2.unifiedTailViewRows(sessionId);if(!rows||rows.length===0)return null;const messages=[];for(const row of rows){try{const parsed=JSON.parse(row.content);if(typeof parsed?.id!=="string"||typeof parsed?.role!=="string")return null;messages.push(parsed)}catch{return null}}return messages}function getStore(){if(!_store){_store=new SessionStore({enabled:persistEnabled2(),log:defaultLogger});if(globalSessionCommitListener!==void 0)_store.setSessionCommitListener(globalSessionCommitListener)}return _store}init_version();init_knobs();init_config();init_dist();init_config();init_paths();init_logger();init_external_summary_settings();import*as path26 from"path";var CHAT_COMPRESS_PHILOSOPHY=`Your summary IS memory, not an archive: after compression this is the ONLY record of the replaced conversation. Its job is continuity of RELATIONSHIP across compactions and sessions \u2014 who matters to the user, what they care about, what was promised or agreed, where open threads stand. It is NOT a moment-by-moment log of everything said; it records the PAST as state ("this happened"), never as live instructions.`;var CHAT_HOW_TO_COMPRESS=`HOW TO COMPRESS
|
|
901
|
+
`)}let offloadPending=session.metadata[METADATA_OFFLOAD_PENDING]??{};if(plan2.unmatched.length>0&&opts.storedRowLookup!==void 0){const needed=[];for(const id of plan2.unmatched){if(expected[id]!==void 0||offloadPending[id]!==void 0)continue;needed.push(id);if(needed.length>=MAX_REBASE_LOOKUP_PER_PASS)break}if(needed.length>0){const rows=opts.storedRowLookup(needed);if(rows!==null){const best=new Map;for(const row of rows){const cur=best.get(row.msgId);if(cur===void 0||row.seq>cur.seq)best.set(row.msgId,{seq:row.seq,content:row.content})}for(const id of needed){const hit=best.get(id);if(hit===void 0)continue;const content=hit.content;const hasImageMarker=content.includes('"rawAnthropicBlock"')&&content.includes('"type":"image"')||content.includes('"imageBase64":"')||content.includes('"text":"[image]"')||content.includes("data:image/");const hasCarrierMarker=classifyCarrier!==void 0&&dshCarrierRawMarkers.some(mk=>content.includes(mk));if(hasCarrierMarker){let parsed;try{parsed=JSON.parse(content)}catch{continue}if(typeof parsed==="object"&&parsed!==null){const path53=classifyCarrier(parsed);if(path53!==void 0){expected[id]=path53;continue}}}if(hasImageMarker)offloadPending[id]=1}}}}const pendingIds=Object.keys(offloadPending);if(pendingIds.length>0){const claimedTargets=new Set;for(const targets of plan2.claims.values())for(const t of targets)claimedTargets.add(t);const posInOld=new Map;oldOrder.forEach((id,i)=>posInOld.set(id,i));for(const id of pendingIds){if(byId2.has(id)){delete offloadPending[id];continue}const oi2=posInOld.get(id);if(oi2===void 0){delete offloadPending[id];continue}const nid=plan2.newOrder[oi2];if(nid===void 0||nid===id||covered.has(nid)||claimedTargets.has(nid))continue;const nm=byId2.get(nid);if(nm===void 0||nm.toolCallId!==void 0&&nm.toolCallId!=="")continue;const anchor=anchors[id];if(anchor!==void 0&&anchor.r!==void 0&&nm.role!==anchor.r)continue;if(storedMessageCarriesImage(nm))continue;expected[id]="image-offload";delete offloadPending[id]}}const prunedPending=pruneRebaseMemo(offloadPending);if(Object.keys(prunedPending).length>0)session.metadata[METADATA_OFFLOAD_PENDING]=prunedPending;else delete session.metadata[METADATA_OFFLOAD_PENDING];if(Object.keys(expected).length>0)session.metadata[METADATA_EXPECTED_REBASE]=expected;else delete session.metadata[METADATA_EXPECTED_REBASE];expectedSize=Object.keys(expected).length;let turnCtx;const ctxOf=id=>{if(turnCtx===void 0)turnCtx=turnContexts(msgs);return turnCtx.get(id)};const turnCtxFor=message=>message!==void 0&&message.id!==void 0&&message.role==="assistant"&&(message.toolCallId===void 0||message.toolCallId==="")?ctxOf(message.id):void 0;const nextAnchors={};let anchorCount=0;for(const id of covered){const claimed=plan2.claims.get(id);if(claimed!==void 0){for(const nid of new Set(claimed)){if(nextAnchors[nid]!==void 0)continue;const message2=byId2.get(nid);if(message2===void 0)continue;if(anchorCount<MAX_ANCHORS){nextAnchors[nid]=anchorFrom(message2,turnCtxFor(message2));anchorCount++}else if(message2.toolCallId!==void 0&&message2.toolCallId!==""){nextAnchors[nid]=liteToolAnchorFrom(message2)}}continue}const prior=anchors[id];if(prior!==void 0){if(anchorCount>=MAX_ANCHORS){nextAnchors[id]=prior;continue}if(prior.t!==void 0&&prior.m===void 0){const message2=byId2.get(id);nextAnchors[id]=message2!==void 0?anchorFrom(message2):prior}else if(prior.p===void 0&&prior.r==="assistant"&&prior.t===void 0){const message2=byId2.get(id);nextAnchors[id]=message2!==void 0?anchorFrom(message2,ctxOf(id)):prior}else if(prior.c===void 0){const message2=byId2.get(id);nextAnchors[id]=message2!==void 0?anchorFrom(message2,turnCtxFor(message2)):prior}else{nextAnchors[id]=prior}anchorCount++;continue}const message=byId2.get(id);if(message!==void 0){if(anchorCount<MAX_ANCHORS){nextAnchors[id]=anchorFrom(message,turnCtxFor(message));anchorCount++}else if(message.toolCallId!==void 0&&message.toolCallId!==""){nextAnchors[id]=liteToolAnchorFrom(message)}}}const nextOrder=plan2.newOrder.slice(-MAX_ORDER);if(plan2.nextCanon!==void 0){session.metadata[METADATA_POSITIONS]={ids:nextOrder,canon:plan2.nextCanon.slice(-MAX_ORDER)}}const absentSet=new Set(plan2.absentEverywhere);let witness=session.metadata[METADATA_EPISODE_ORDER];const episodeActive=(session.metadata[METADATA_DRIFT_STREAK]??0)>0;if(witness===void 0&&episodeActive&&oldOrder.length>0){witness=oldOrder.slice(-MAX_ORDER);session.metadata[METADATA_EPISODE_ORDER]=witness}const continuityBaseline=witness??oldOrder;let wireContinuity=false;let tailTruncated=false;if(continuityBaseline.length>0){const witness2=continuityBaseline;const inboundSet=new Set(plan2.newOrder);const witnessSet=new Set(witness2);const commonWitness=witness2.filter(id=>inboundSet.has(id));const commonInbound=plan2.newOrder.filter(id=>witnessSet.has(id));wireContinuity=commonWitness.length>0&&witness2.slice(witness2.length-commonWitness.length).every(id=>inboundSet.has(id))&&plan2.newOrder.slice(0,commonInbound.length).every(id=>witnessSet.has(id));const commonPrefix=commonInbound;tailTruncated=commonPrefix.length>0&&commonPrefix.length<witness2.length&&witness2.slice(0,commonPrefix.length).every(id=>inboundSet.has(id))&&plan2.newOrder.slice(0,commonPrefix.length).every(id=>witnessSet.has(id))}const markerChurnExplained=(opts.markerStripped??0)>0;const realUnmatched=plan2.unmatched.filter(id=>expected[id]===void 0);const accountedHere=plan2.unmatched.length-realUnmatched.length;const expectedNote=accountedHere>0?`; ${accountedHere} more covered id(s) accounted as expected host behavior (#5142)`:"";const reasoningOnlyDrop=plan2.claims.size===0&&realUnmatched.length>0&&realUnmatched.every(id=>anchors[id]?.c==="reasoning");const nonReasoningUnmatched=realUnmatched.filter(id=>{const cls=anchors[id]?.c;return cls!==void 0&&cls!=="reasoning"}).length;const classCarryingResidual=realUnmatched.filter(id=>{const cls=anchors[id]?.c;return cls!==void 0&&cls!=="reasoning"});const shapeExplained=plan2.byShape>0||classCarryingResidual.length>0&&plan2.nearDupResidual.length>=.6*classCarryingResidual.length;const truncationExplained=classCarryingResidual.length>0&&plan2.nearDupResidual.length===0&&classCarryingResidual.every(id=>absentSet.has(id))&&wireContinuity;const tailTruncationExplained=classCarryingResidual.length>0&&plan2.nearDupResidual.length===0&&classCarryingResidual.every(id=>absentSet.has(id))&&tailTruncated;const totalDrift=plan2.claims.size===0&&realUnmatched.length>0&&!reasoningOnlyDrop&&!markerChurnExplained&&!shapeExplained&&!truncationExplained&&!tailTruncationExplained;const epochProtected=session.metadata[METADATA_EPOCH_CONFIRM]===true||totalDrift&&nonReasoningUnmatched>=FOLD_DRIFT_ESCALATE_MIN_UNMATCHED;const prevCov=session.metadata[METADATA_FOLD_COVERAGE]??{};const nextCov={};let covCount=0;for(const block of blocks){const bid=block.blockId;if(bid===void 0||bid==="")continue;const ids=(block.effectiveMessageIds??[]).filter(id=>!isResponsesTurnSeparatorId(id)&&expected[id]===void 0);if(ids.length===0)continue;let p2=0,r=0;for(const id of ids){if(byId2.has(id))p2++;else if(plan2.claims.has(id))r++}const rec={p:p2,r,t:ids.length};if(prevCov[bid]?.e===1||p2+r>0)rec.e=1;const hardIds=ids.filter(id=>anchors[id]?.c!=="reasoning");const gone=hardIds.length>0&&2*(p2+r)<hardIds.length;const absentHard=hardIds.filter(id=>!byId2.has(id)&&!plan2.claims.has(id));const structurallyAbsent=absentHard.length>0&&absentHard.every(id=>absentSet.has(id))&&(wireContinuity||tailTruncated);if(gone&&!structurallyAbsent){if(rec.e===1)rec.z=(prevCov[bid]?.z??0)+1}else{rec.z=0}if(covCount>=MAX_ANCHORS)continue;nextCov[bid]=rec;covCount++}let reapedCount=0;if(mode==="repair"&&session.metadata.pluginAgent===void 0&&!epochProtected){const ripe=new Set;for(const block of blocks){const bid=block.blockId;if(bid!==void 0&&(nextCov[bid]?.z??0)>=FOLD_DRIFT_ESCALATE_PASSES)ripe.add(bid)}if(ripe.size>0){const liveRawIds=new Set(msgs.map(m2=>m2.id));const reaped=reapDestroyedSubstrate(session,ripe,liveRawIds,opts.log??(()=>{}));reapedCount=reaped.length;if(reapedCount>0){const deadIds=new Set;for(const block of blocks){if(block.blockId===void 0||!ripe.has(block.blockId))continue;delete nextCov[block.blockId];for(const id of block.effectiveMessageIds??[])deadIds.add(id);for(const id of block.directMessageIds??[])deadIds.add(id)}for(const id of deadIds)delete nextAnchors[id];for(let i=nextOrder.length-1;i>=0;i--){if(deadIds.has(nextOrder[i]))nextOrder.splice(i,1)}const storedPositions=session.metadata[METADATA_POSITIONS];const positionIds=storedPositions?.ids;if(Array.isArray(positionIds)&&positionIds!==nextOrder){for(let i=positionIds.length-1;i>=0;i--){if(deadIds.has(positionIds[i]))positionIds.splice(i,1)}}recordConflict(session,"orphan-reap",`reaped ${reapedCount} zombie fold block(s) [${reaped.join(", ")}]: covered substrate majority-absent for ${FOLD_DRIFT_ESCALATE_PASSES} consecutive passes (#2695)`)}}}session.metadata[METADATA_FOLD_COVERAGE]=nextCov;if(plan2.claims.size>0&&mode==="repair"){rewriteBlocks(blocks,plan2.claims);const prior=new Set(session.state?.lastPassIds??[]);for(const targets of plan2.claims.values()){for(const newId of targets)prior.add(newId)}session.state.lastPassIds=[...prior]}session.metadata[METADATA_ANCHORS]=nextAnchors;session.metadata[METADATA_ORDER]=nextOrder;const tag=opts.sessionId===void 0?"":`[${opts.sessionId}] `;const unfoldedDrift=mode==="repair"?Math.max(0,(plan2.churnTokens??0)-(plan2.claimedChurnTokens??0)):plan2.churnTokens??0;const driftTok=unfoldedDrift>0?` (~${unfoldedDrift} tok unfolded in churn region)`:"";const prevStreak=session.metadata[METADATA_DRIFT_STREAK]??0;if(!totalDrift){if(prevStreak!==0)resetFoldDriftState(session);if(shapeExplained&&session.metadata[METADATA_SHAPE_NOTED]!==true){session.metadata[METADATA_SHAPE_NOTED]=true;opts.log?.("info",`${tag}[fold-reconcile] ${classCarryingResidual.length} covered id(s) churned shape (protocol switch / offload) with word evidence intact \u2014 re-anchored ${plan2.byShape}, ${plan2.nearDupResidual.length} near-duplicate residual kept under watch (#3641); fold state retained`)}if(tailTruncationExplained&&session.metadata[METADATA_TAIL_TRUNC_NOTED]!==true&&session.metadata[METADATA_TRUNC_NOTED]!==true){session.metadata[METADATA_TAIL_TRUNC_NOTED]=true;opts.log?.("info",`${tag}[fold-reconcile] ${classCarryingResidual.length} covered id(s) no longer on the wire with no replacement evidence and the resent history is a prefix of the pre-rewind wire \u2014 host rewind/undo removed the newest turns (incl. a folded span); fold snapshot retained, nothing reaped (#3724)`)}else if(truncationExplained&&session.metadata[METADATA_TRUNC_NOTED]!==true&&session.metadata[METADATA_TAIL_TRUNC_NOTED]!==true){session.metadata[METADATA_TRUNC_NOTED]=true;opts.log?.("info",`${tag}[fold-reconcile] ${classCarryingResidual.length} covered id(s) no longer on the wire with no replacement evidence and remaining substrate present \u2014 host-side truncation/dropped history, fold snapshot retained (#2695/#3641)`)}if(expectedSize>0&&session.metadata[METADATA_EXPECTED_REBASE_NOTED]!==true){let expectedSuppressed=0;for(const id of covered)if(!byId2.has(id)&&expected[id]!==void 0)expectedSuppressed++;if(expectedSuppressed>0){session.metadata[METADATA_EXPECTED_REBASE_NOTED]=true;let carriers=0,offloads=0;for(const reason of Object.values(expected)){if(reason==="image-offload")offloads++;else carriers++}opts.log?.("info",`${tag}[fold-reconcile] ${expectedSize} covered id(s) retired by expected host behavior (${carriers} one-shot carrier(s), ${offloads} image offload rewrite(s)) \u2014 excluded from drift accounting, near-zero steady state restored (#5142)`)}}}else{const streak=prevStreak+1;if(prevStreak===0&&oldOrder.length>0&&session.metadata[METADATA_EPISODE_ORDER]===void 0){session.metadata[METADATA_EPISODE_ORDER]=oldOrder.slice(-MAX_ORDER)}session.metadata[METADATA_DRIFT_STREAK]=streak;if(prevStreak===0)session.metadata[METADATA_DRIFT_SINCE]=Date.now();if(streak>=FOLD_DRIFT_ESCALATE_PASSES&&nonReasoningUnmatched>=FOLD_DRIFT_ESCALATE_MIN_UNMATCHED&&session.metadata[METADATA_DRIFT_ESCALATED]!==true){session.metadata[METADATA_DRIFT_ESCALATED]=true;const dshWitness=dshNativeCompactionWitness(session);if(dshWitness!==void 0){recordConflict(session,"native-compaction-inferred",`compression substrate destroyed (total-loss drift, no checkpoint marker); bili refused ${dshWitness} client-native compaction call(s) this session (#1729/#2028) \u2014 attributed to client-native compaction [inferred] (${realUnmatched.length} covered id(s) missing, #2193/#2709)`)}const since=session.metadata[METADATA_DRIFT_SINCE];const span=typeof since==="number"?`, ${Math.max(1,Math.round((Date.now()-since)/6e4))} min so far`:"";session.metadata[METADATA_EPOCH_CONFIRM]=true;if(opts.log!==void 0){opts.log("error",`${tag}[fold-reconcile] fold epoch confirmation required: ${realUnmatched.length} covered id(s) missing with NO anchor match and NO word evidence for ${streak} consecutive passes${span}${expectedNote} \u2014 the resent history shares nothing with the fold substrate (wholesale replacement: host-native compaction outside bili's knowledge #1729/#2193, or a brand-new conversation on the same session id). Folding is paused for this session until the histories realign (old history resent or a fresh fold on the new one starts a new epoch); bili keeps the existing snapshot \u2014 nothing is deleted (#3641)${driftTok}`)}}}if(realUnmatched.length===0&&plan2.claims.size===0){return{kind:"resend",missing:0,claims:0,byPos:0,byTool:0,byTwin:0,bySim:0,byOrder:0,byNorm:0,byTurn:0,byImage:0,byShape:0,reaped:reapedCount,unmatched:0,expectedRetired:expectedSize}}if(opts.log!==void 0){if(plan2.claims.size>0&&mode==="repair"){opts.log(realUnmatched.length>0?"warn":"info",`${tag}[fold-reconcile] resent history drifted: ${plan2.claims.size+realUnmatched.length} covered id(s) missing${expectedNote} \u2014 reanchored ${plan2.claims.size} (${plan2.byPos} positional${plan2.resyncs>0?`, ${plan2.resyncs} order break(s) resynced`:""}, ${plan2.byTool} by toolCallId${plan2.byTwin>0?`, ${plan2.byTwin} by toolCallId twin`:""}${plan2.bySim>0?`, ${plan2.bySim} by simhash corroboration`:""}${plan2.byOrder>0?`, ${plan2.byOrder} by order bracket`:""}, ${plan2.byNorm} by normalized identity${plan2.byTurn>0?`, ${plan2.byTurn} by assistant-turn key`:""}${plan2.byImage>0?`, ${plan2.byImage} by image-capability variant`:""}${plan2.byShape>0?`, ${plan2.byShape} by shape census`:""}) onto churned bytes, ${realUnmatched.length} unmatched re-enter the wire unfolded${plan2.idRewriteSuspects>0?`; ${plan2.idRewriteSuspects} suspected host-rewritten tool-call ids (identical content under a different toolCallId \u2014 #2396)`:""} (#1921)${driftTok}`)}else if(plan2.claims.size>0){opts.log("warn",`${tag}[fold-reconcile] resent history drifted: ${plan2.claims.size+realUnmatched.length} covered id(s) missing${expectedNote}, ${plan2.claims.size} matchable by anchor (${plan2.byPos} positional${plan2.resyncs>0?`, ${plan2.resyncs} resynced`:""}, ${plan2.byTool} toolCallId${plan2.byTwin>0?`, ${plan2.byTwin} twin`:""}${plan2.bySim>0?`, ${plan2.bySim} simhash`:""}${plan2.byOrder>0?`, ${plan2.byOrder} order-bracket`:""}, ${plan2.byNorm} normalized${plan2.byTurn>0?`, ${plan2.byTurn} turn key`:""}${plan2.byImage>0?`, ${plan2.byImage} image`:""}) but reconcile=warn made no repair (#1921)${driftTok}`)}else if(reasoningOnlyDrop){opts.log("info",`${tag}[fold-reconcile] ${realUnmatched.length} covered reasoning core(s) dropped by the host (cross-model replay discards structured thinking; every text/tool core intact) \u2014 fold substrate healthy, tolerated (#2193 follow-up)`)}else if(markerChurnExplained){if(session.metadata[METADATA_MARKER_CHURN_NOTED]!==true){session.metadata[METADATA_MARKER_CHURN_NOTED]=true;opts.log("info",`${tag}[fold-reconcile] ${realUnmatched.length} covered id(s) missing with no anchor match${expectedNote}, but this pass stripped ${opts.markerStripped} raw marker artifact(s) \u2014 covered ids minted from marker-laden bytes churn once the strip engine cleans the resent history; benign on stateless resend (content still on the wire, re-folds re-cover), tolerated (#2815/#2789)`)}}else if(session.metadata[METADATA_DRIFT_ESCALATED]!==true){opts.log("warn",`${tag}[fold-reconcile] resent history drifted: ${realUnmatched.length} covered id(s) missing with no anchor match${expectedNote} \u2014 mutation (content edit invalidates content-hash refs, fold silently lost) or client-side deletion/truncation (benign, message no longer on the wire)${plan2.idRewriteSuspects>0?`; ${plan2.idRewriteSuspects} of them have an inbound twin with identical normalized content under a different toolCallId \u2014 consistent with the host rewriting authoritative tool-call ids across provider projections (host contract: keep tool-call ids byte-stable per conversation, #2396)`:""} (#1921)${driftTok}`)}}return{kind:plan2.claims.size>0?mode==="repair"?"reanchored":"unmatched":"unmatched",missing:plan2.claims.size+realUnmatched.length,claims:plan2.claims.size,byPos:plan2.byPos,byTool:plan2.byTool,byTwin:plan2.byTwin,bySim:plan2.bySim,byOrder:plan2.byOrder,byNorm:plan2.byNorm,byTurn:plan2.byTurn,byImage:plan2.byImage,byShape:plan2.byShape,reaped:reapedCount,unmatched:realUnmatched.length,expectedRetired:expectedSize}}function noteSystemPromptFingerprint(session,system,opts={}){if(!session.metadata)return;const text2=system===void 0||system===null?"":JSON.stringify(system)??"";const fp2=system===void 0||system===null?"-":createHash12("sha256").update(text2).digest("hex").slice(0,16);const prev=session.metadata[METADATA_SYSTEM_FP];if(prev!==void 0&&prev.fp!==fp2){if(opts.log!==void 0){opts.log("info",`${opts.sessionId===void 0?"":`[${opts.sessionId}] `}[fold-reconcile] system prompt changed (${prev.size} \u2192 ${text2.length} chars); fold state unaffected (#1921)`)}}session.metadata[METADATA_SYSTEM_FP]={fp:fp2,size:text2.length}}function noteCanonicalSystemFingerprint(session,canonical2){if(!session.metadata)return;const text2=canonical2===void 0||canonical2===null?"":JSON.stringify(canonical2)??"";const fp2=canonical2===void 0||canonical2===null?"-":createHash12("sha256").update(text2).digest("hex").slice(0,16);session.metadata[METADATA_CANONICAL_SYS_FP]={fp:fp2,size:text2.length}}init_logger();var MEMBERSHIP_RECORD_SCALE_RATIO=.25;function collectRequestIds(envelopeIds,msgs){const out=[];const seen=new Set;if(Array.isArray(envelopeIds)){for(const v2 of envelopeIds){if(typeof v2==="string"&&v2.length>0&&v2.length<=512&&!v2.startsWith("acp_summary_")&&!seen.has(v2)){seen.add(v2);out.push(v2)}}if(out.length>0)return out}for(const m2 of msgs){const id=m2.toolCallId;if(typeof id==="string"&&id.length>0&&!seen.has(id)){seen.add(id);out.push(id)}}return out}function isForeignMembership(m2){return m2?.member===false}function probeRequestMembership(session,ids,payloadUpper){const t=session.transient;if(!t)return null;if(ids.length===0){delete t.requestMembership;return null}const needle=t.latestKnownMsgId??null;const member=needle===null||ids.includes(needle);const verdict={member,needle};t.requestMembership=verdict;log("debug",`[${session.id}] [#4805] membership probe: ids=${ids.length} needle=${member?"member":"miss"} payloadUpper=${payloadUpper}`);const referenceScale=session.stats.lastInputTokens>0?session.stats.lastInputTokens:t.needlePayloadUpper??0;const mainScale=payloadUpper>=referenceScale*MEMBERSHIP_RECORD_SCALE_RATIO;if(member||mainScale){t.latestKnownMsgId=ids[ids.length-1];t.needlePayloadUpper=payloadUpper}return verdict}init_billing();init_util();init_proxy_tool_result();var FULL_DETAIL_LINES=512;var BOOT_ID=randomUUID3();var SWITCH_COLD_ROUNDS=4;var WARM_HIT_PCT=85;var SIZE_BUCKET_TOK=2e4;var LOST_LOGGED_KEY="foldCoverageLostLogged";function median(xs2){if(xs2.length===0)return null;const s3=[...xs2].sort((x,y)=>x-y);const m2=s3.length>>1;return s3.length%2===1?s3[m2]:Math.round((s3[m2-1]+s3[m2])/2)}var LEDGER_KEY="cacheLedger";function refNum3(ref){return Number(ref.replace(/\D/g,""))||0}function round12(n){return Math.round(n*10)/10}function prefixTokensBeforeRef(session,ref){const byRef=session.state?.messageRefs?.byRef;const snap=session.state?.tokenSnapshot;if(!byRef||!snap||refNum3(ref)===0)return 0;let n=0;for(const key2 of Object.keys(byRef)){if(refNum3(key2)<refNum3(ref))n+=snap[key2]??0}return n}var SEAM_BODY_CAP=512*1024;var SEAM_EVENTS_CAP=8;var PROVIDER_TTL_GAP_MS=6e5;var BODY_FULL_CAP=8*1024*1024;var INBOUND_MSG_CAP=8192;var GENERATED_METERING_FIELDS=["thinkingTokens"];function originEvidenceJson(m2){const r=m2;if(!GENERATED_METERING_FIELDS.some(k2=>k2 in r))return JSON.stringify(m2);const stripped={};for(const[k2,v2]of Object.entries(r)){if(!GENERATED_METERING_FIELDS.includes(k2))stripped[k2]=v2}return JSON.stringify(stripped)}var captures=new AsyncLocalStorage3;var captureOrder=0;async function withCacheCapture(session,fn){if(!session)return fn();return captures.run({session,requestId:randomUUID3(),round:0},async()=>{try{return await fn()}finally{const capture2=captures.getStore();if(capture2){delete capture2.sentBody;delete capture2.inBody;delete capture2.imageFacts}}})}function pendingCapture(session){const capture2=captures.getStore();return capture2?.session===session?capture2:session.transient??={}}function lastForwardedBody(session){return pendingCapture(session).sentBody}function pendingEvidencePair(session){const pending=pendingCapture(session);return{sentBody:pending.sentBody,inBody:pending.inBody}}function noteInboundMessages(session,msgs){const transient2=pendingCapture(session);if(msgs.length>INBOUND_MSG_CAP){delete transient2.inBody;transient2.inBody={msgs:msgs.length,fps:[],meta:[]};return}const fps=[];const meta=[];for(const m2 of msgs){const j2=originEvidenceJson(m2);fps.push(createHash13("sha256").update(j2).digest("hex").slice(0,16));meta.push({role:String(m2.role??"?"),len:j2.length,cls:inboundMessageClass(m2)})}transient2.inBody={msgs:msgs.length,fps,meta}}function inboundMessageClass(m2){const r=m2;if(r.tool_calls!==void 0||r.tool_use!==void 0)return"tool-call";const content=r.content;if(typeof content==="string")return"text";if(Array.isArray(content)){for(const part of content){const t=part?.type;if(t==="image"||t==="image_url"||t==="input_image"||t==="inline_data")return"image"}return"text"}return"other"}function firstDivergentInboundMsg(prev,cur){const n=Math.min(prev.fps.length,cur.fps.length);for(let i=0;i<n;i++){if(prev.fps[i]!==cur.fps[i])return i}return null}var lastClientAbort=new WeakMap;function recordContextObservation(session,tokens,source){if(!Number.isFinite(tokens)||tokens<0){delete session.metadata?.publicContextObservation;return}session.metadata??={};session.metadata.publicContextObservation={sessionId:session.id,tokens,source,at:Date.now(),generation:randomUUID3()}}function currentContextObservation(session){const raw=session.metadata?.publicContextObservation;if(!raw||typeof raw!=="object")return void 0;const o=raw;if(o.sessionId!==session.id||typeof o.tokens!=="number"||!Number.isFinite(o.tokens)||o.tokens<0||o.source!=="usage"&&o.source!=="estimate"||typeof o.at!=="number"||!Number.isFinite(o.at)||o.at<0||typeof o.generation!=="string"||o.generation.length===0)return void 0;return{sessionId:session.id,tokens:o.tokens,source:o.source,at:o.at,generation:o.generation}}function noteClientAbort(session){lastClientAbort.set(session,Date.now())}function credentialFingerprint(headers){if(!headers)return void 0;let cred;for(const[name,value]of Object.entries(headers)){const n=name.toLowerCase();if(n==="authorization"||n==="x-api-key"||n==="api-key"||n==="x-goog-api-key"){const v2=value.trim().replace(/^Bearer\s+/i,"").trim();if(v2!==""){const m2=/^SDK-HMAC-SHA256\s+Access=([^\s,]+)/i.exec(v2);cred=m2!==null?`sdk-hmac:${m2[1]}`:v2;break}}}if(cred===void 0)return void 0;return"sha256:"+createHash13("sha256").update(cred,"utf8").digest("hex").slice(0,12)}function canonicalJson2(v2){if(v2===null||typeof v2!=="object")return JSON.stringify(v2)??"null";if(Array.isArray(v2))return"["+v2.map(canonicalJson2).join(",")+"]";const obj=v2;const keys=Object.keys(obj).filter(k2=>obj[k2]!==void 0).sort();return"{"+keys.map(k2=>JSON.stringify(k2)+":"+canonicalJson2(obj[k2])).join(",")+"}"}function generationParamFp(body){if(!body||typeof body!=="object")return void 0;const parts={};if(body.thinking!==void 0&&body.thinking!==null)parts.thinking=body.thinking;if(body.output_config!==void 0&&body.output_config!==null)parts.output_config=body.output_config;if(typeof body.reasoning_effort==="string"&&body.reasoning_effort!=="")parts.reasoning_effort=body.reasoning_effort;const r=body.reasoning;if(r!==null&&typeof r==="object"){const re2=r.effort;if(typeof re2==="string"&&re2!=="")parts["reasoning.effort"]=re2}const gc=body.generationConfig;if(gc!==null&&typeof gc==="object"){const tc=gc.thinkingConfig;if(tc!==void 0&&tc!==null)parts.thinkingConfig=tc}if(Object.keys(parts).length===0)return void 0;return"sha256:"+createHash13("sha256").update(canonicalJson2(parts),"utf8").digest("hex").slice(0,16)}function noteForwardedBody(session,body,msgs,keyFp,effFp){const buf=Buffer.from(body,"utf8");const digest=createHash13("sha256").update(buf).digest("hex");const transient2=pendingCapture(session);const prior=transient2.sentBody;const samePayload=prior!==void 0&&prior.digest===digest;transient2.sentBody={order:++captureOrder,requestId:"requestId"in transient2?transient2.requestId:void 0,round:"round"in transient2?++transient2.round:void 0,head:buf.byteLength>SEAM_BODY_CAP?Buffer.from(buf.subarray(0,SEAM_BODY_CAP)):buf,bytes:buf.byteLength,msgs:msgs??(samePayload?prior.msgs:null),digest,full:buf.byteLength<=BODY_FULL_CAP?buf:samePayload?prior.full:null,keyFp:keyFp??(samePayload?prior.keyFp:void 0),effFp:effFp??(samePayload?prior.effFp:void 0)};if("round"in transient2&&transient2.round>1){delete transient2.imageFacts;delete transient2.inBody}if(session.stats.contextTokensSource!==void 0)recordContextObservation(session,session.stats.contextTokens,"estimate");else delete session.metadata?.publicContextObservation}var LEARNED_IMAGE_COST_TTL_MS=24*60*60*1e3;var LEARNED_IMAGE_COST_ALPHA=.5;var LEARNED_PER_IMAGE_MAX=1e5;var LEARNED_VARIANCE_BAND=15;var imageFactsLastSent=new WeakMap;function noteForwardedImageFacts(session,facts){const capture2=captures.getStore();if(capture2?.session===session){capture2.imageFacts=facts;return}imageFactsLastSent.set(session,facts)}function settleImageLearning(session,billedTotal){const capture2=captures.getStore();const facts=capture2?.session===session?capture2.imageFacts:imageFactsLastSent.get(session);if(!facts)return;if(capture2?.session===session)delete capture2.imageFacts;else imageFactsLastSent.delete(session);if(facts.nImages<=0||billedTotal<=0)return;const observed=billedTotal-facts.textSide;if(observed<=0)return;const per=observed/facts.nImages;if(!(per>=1&&per<=LEARNED_PER_IMAGE_MAX))return;const store2=session.metadata.learnedImageCosts??{};const prev=store2[facts.host];const fresh=!prev||typeof prev.cost!=="number"||prev.fp!==facts.fp;const cost=fresh?per:prev.cost*(1-LEARNED_IMAGE_COST_ALPHA)+per*LEARNED_IMAGE_COST_ALPHA;store2[facts.host]={cost,seen:fresh?1:(prev.seen??0)+1,ts:Date.now(),fp:facts.fp};session.metadata.learnedImageCosts=store2;markDirty(session)}function learnedImageReserve(session,host,nImages,fp2,cap,prior){if(nImages<=0)return void 0;const entry=session.metadata.learnedImageCosts?.[host];if(!entry||typeof entry.cost!=="number"||entry.seen<1)return void 0;if(Date.now()-entry.ts>LEARNED_IMAGE_COST_TTL_MS)return void 0;if(entry.fp!==fp2)return void 0;let per=cap>0?Math.min(entry.cost,cap):entry.cost;if(typeof prior==="number"&&prior>0){per=Math.min(per,LEARNED_VARIANCE_BAND*prior/nImages)}else{per=Math.min(per,LEARNED_PER_IMAGE_MAX)}return per*nImages}function seamLcp(a,b2){let lcp=0;const n=Math.min(a.length,b2.length);while(lcp<n&&a[lcp]===b2[lcp])lcp++;const msgsOf=s3=>{try{const p2=JSON.parse(s3.toString("utf8"));const arr=p2.messages??p2.input??p2.contents;return Array.isArray(arr)?arr:[]}catch{return[]}};const ma=msgsOf(a);const mb=msgsOf(b2);let i=0;const eq=(x,y)=>JSON.stringify(x)===JSON.stringify(y);while(i<Math.min(ma.length,mb.length)&&eq(ma[i],mb[i]))i++;return{lcpBytes:lcp,msgIndex:ma.length>0&&mb.length>0?i:null,prevMsgs:ma.length,curMsgs:mb.length}}function byteLcp(a,b2){const n=Math.min(a.length,b2.length);if(n===0||a[0]!==b2[0])return 0;let lo2=1;let hi2=n;while(lo2<hi2){const mid=lo2+hi2+1>>>1;if(Buffer.compare(a.subarray(0,mid),b2.subarray(0,mid))===0)lo2=mid;else hi2=mid-1}return lo2}function isMidInsertionAppend(prev,cur,lcp){if(cur.length<=prev.length||lcp>=prev.length)return false;const room=prev.length-lcp;let lo2=0;let hi2=room;while(lo2<hi2){const mid=lo2+hi2+1>>>1;if(Buffer.compare(prev.subarray(prev.length-mid),cur.subarray(cur.length-mid))===0)lo2=mid;else hi2=mid-1}return lcp+lo2===prev.length}function messagesArrayCloseOffset(body){const n=body.length;let depth=0;let inStr=false;let want=-1;let keyAt=-1;let i=0;while(i<n){const c=body[i];if(inStr){if(c===92){let j2=i;while(j2<n&&body[j2]===92)j2++;i=(j2-i)%2===1?j2+1:j2;continue}if(c===34){inStr=false;if(keyAt>=0){const key2=body.subarray(keyAt+1,i).toString("utf8");keyAt=-1;if(depth===1&&(key2==="messages"||key2==="input"||key2==="contents")){let j2=i+1;while(j2<n&&body[j2]<=32)j2++;if(body[j2]===58){j2++;while(j2<n&&body[j2]<=32)j2++;if(body[j2]===91)want=depth+1}}}i++;continue}let m3=n;const q2=body.indexOf(34,i+1);if(q2!==-1&&q2<m3)m3=q2;const b2=body.indexOf(92,i+1);if(b2!==-1&&b2<m3)m3=b2;i=m3;continue}if(c===34){inStr=true;keyAt=depth===1?i:-1;i++;continue}if(c===123||c===91){depth++;i++;continue}if(c===125||c===93){if(want!==-1&&c===93&&depth===want)return i;depth--;i++;continue}let m2=n;for(const code of[34,123,125,91,93]){const p2=body.indexOf(code,i+1);if(p2!==-1&&p2<m2)m2=p2}i=m2}return null}function detectSeam(session,led){const line=led.lines[led.lines.length-1];if(!line||line.unk===1||line.missed<=0)return;if(line.nb===1)return;const abortAt=lastClientAbort.get(session);if(abortAt!==void 0&&Math.abs(line.at-abortAt)<3e4){line.abortedNear=1;led.agg.abortCorrelated+=1}if(line.sw===1||line.pw===1||line.uw===1||line.rs===1||line.cause!==void 0||line.foldSeq!==null)return;if(!(line.tr>8192&&line.tr>.3*line.input))return;const agg=led.agg;const cur=pendingCapture(session).sentBody;const prev=session.transient?.settledBody;if(cur?.order!==void 0&&prev?.order!==void 0&&cur.order<=prev.order){line.evidence="out-of-order";return}const prevSampleAt=led.lines.length>=2?led.lines[led.lines.length-2].at:line.at;const ttlExpired=line.at-prevSampleAt>PROVIDER_TTL_GAP_MS;const bookProvider=()=>{line.prov=ttlExpired?"ttl":"side";if(ttlExpired){agg.providerTtlMisses+=1;agg.providerTtlMissed+=line.tr}else{agg.providerSideMisses+=1;agg.providerSideMissed+=line.tr}};let f2;if(cur!==void 0&&prev!==void 0){f2=seamLcp(prev.head,cur.head);const prevCapped=prev.bytes>SEAM_BODY_CAP;const curCapped=cur.bytes>SEAM_BODY_CAP;if(!prevCapped&&!curCapped&&f2.prevMsgs>0&&f2.curMsgs<f2.prevMsgs){line.prov="rewind";agg.rewinds+=1;agg.rewindMissed+=line.tr;return}if(cur.head.byteLength<prev.head.byteLength&&f2.lcpBytes>=cur.head.byteLength-4){line.prov="rewind";agg.rewinds+=1;agg.rewindMissed+=line.tr;return}if(f2.lcpBytes>=cur.head.byteLength){bookProvider();return}if(!prevCapped&&!curCapped&&f2.prevMsgs>0&&f2.msgIndex===f2.prevMsgs&&f2.curMsgs>f2.prevMsgs){bookProvider();return}if(prev.head.byteLength<cur.head.byteLength&&f2.lcpBytes>=prev.head.byteLength-4){if(prev.msgs!==null&&cur.msgs!==null&&cur.msgs>prev.msgs){bookProvider();return}}}const curIn=pendingCapture(session).inBody;const prevIn=session.transient?.settledInBody;if(curIn!==void 0&&prevIn!==void 0&&curIn.msgs<=INBOUND_MSG_CAP&&prevIn.msgs<=INBOUND_MSG_CAP){const k2=firstDivergentInboundMsg(prevIn,curIn);if(k2!==null&&k2<Math.min(prevIn.msgs,curIn.msgs)){line.prov="client";agg.clientInserts+=1;agg.clientInsertMissed+=line.tr;const m2=curIn.meta[k2]??{role:"?",len:0,cls:"?"};if(cur!==void 0&&prev!==void 0){if(led.seamEvents!==void 0&&led.seamEvents.length>=SEAM_EVENTS_CAP)led.seamEvents.shift();const forensics=f2??seamLcp(prev.head,cur.head);(led.seamEvents??(led.seamEvents=[])).push({seq:line.seq,at:line.at,input:line.input,hitPct:line.hitPct??0,...forensics,prevMsgs:prev.msgs??forensics.prevMsgs,curMsgs:cur.msgs??forensics.curMsgs,client:{idx:k2,role:m2.role,len:m2.len,cls:m2.cls}})}if(agg.clientInserts===1){log("warn",`[${session.id}] [cache-seam] client-side mid-history rewrite: hit ${line.hitPct}% (input=${line.input}, unexplained=${Math.round(line.tr)} tok) \u2014 the client's resent history diverged at inbound message[${k2}] of ${prevIn.msgs}\u2192${curIn.msgs} (${m2.role}/${m2.cls}, ${m2.len}B JSON), so the wire break is the host's own churn, not a bili rebuild (#3023)`)}return}}if((led.sweepThisSample??0)>0){line.prov="orphan-sweep";agg.orphanSweepSeams+=1;agg.orphanSweepMissed+=line.tr;if(agg.orphanSweepSeams===1){log("warn",`[${session.id}] [cache-seam] mid-history break attributed to proactive failed-compress cleanup (${led.sweepThisSample} record(s) rotated out, #3769): hit ${line.hitPct}% (unexplained=${Math.round(line.tr)} tok) \u2014 no fold claimed this break`)}return}agg.seamSuspects+=1;agg.seamMissed+=line.tr;line.seam=1;if(cur!==void 0&&prev!==void 0&&led.seamEvents!==void 0&&led.seamEvents.length>=SEAM_EVENTS_CAP){led.seamEvents.shift()}if(cur!==void 0&&prev!==void 0){const forensics=f2??seamLcp(prev.head,cur.head);const ev={seq:line.seq,at:line.at,input:line.input,hitPct:line.hitPct??0,...forensics,prevMsgs:prev.msgs??forensics.prevMsgs,curMsgs:cur.msgs??forensics.curMsgs};(led.seamEvents??(led.seamEvents=[])).push(ev);if(agg.seamSuspects===1){log("warn",`[${session.id}] [cache-seam] suspected mid-history prefix break: hit ${line.hitPct}% (input=${line.input}, unexplained=${Math.round(line.tr)} tok, no fold/switch/restart attribution); first divergence at byte ${ev.lcpBytes}, message[${ev.msgIndex??"?"}] of ${ev.prevMsgs}\u2192${ev.curMsgs} \u2014 see /acp-cache for the seam section`)}}else if(agg.seamSuspects===1){log("warn",`[${session.id}] [cache-seam] suspected mid-history prefix break: hit ${line.hitPct}% (input=${line.input}, unexplained=${Math.round(line.tr)} tok, no fold/switch/restart attribution); outbound body pair unavailable (lane without body capture) \u2014 aggregate flag only`)}}function getCacheLedger(session){const meta=session.metadata??(session.metadata={});const existing=meta[LEDGER_KEY];if(existing&&existing.v===1){const g2=existing.agg;for(const key2 of["switches","switchMissed","effSwitches","effSwitchMissed","keySwitches","keySwitchMissed","promptSwitches","promptSwitchMissed","projSwitches","projSwitchMissed","wireSwitches","wireSwitchMissed","upstreamSwitches","upstreamSwitchMissed","restartDrops","restartDropMissed","attributedMissed","unknownSamples","unknownInput","nbSamples","nbInput","seamSuspects","seamMissed","providerSideMisses","providerSideMissed","providerTtlMisses","providerTtlMissed","rewinds","rewindMissed","abortCorrelated","clientInserts","clientInsertMissed","orphanSweepSeams","orphanSweepMissed"]){if(typeof g2[key2]!=="number")g2[key2]=0}return existing}const maxBlockId=(session.state?.blocks??[]).reduce((n,b2)=>Math.max(n,refNum3(b2.blockId)),0);const led={v:1,lastBlockId:maxBlockId,consumedFoldSeq:0,sampleSeq:0,foldSeqCounter:0,folds:[],lines:[],agg:{requests:0,input:0,cached:0,output:0,nc:0,cr:0,tr:0,switches:0,switchMissed:0,effSwitches:0,effSwitchMissed:0,keySwitches:0,keySwitchMissed:0,promptSwitches:0,promptSwitchMissed:0,projSwitches:0,projSwitchMissed:0,wireSwitches:0,wireSwitchMissed:0,upstreamSwitches:0,upstreamSwitchMissed:0,restartDrops:0,restartDropMissed:0,attributedMissed:0,unknownSamples:0,unknownInput:0,nbSamples:0,nbInput:0,seamSuspects:0,seamMissed:0,providerSideMisses:0,providerSideMissed:0,providerTtlMisses:0,providerTtlMissed:0,rewinds:0,rewindMissed:0,abortCorrelated:0,clientInserts:0,clientInsertMissed:0,orphanSweepSeams:0,orphanSweepMissed:0}};meta[LEDGER_KEY]=led;return led}function pushFold(led,f2){for(const open of led.folds){if(open.k===null)open.k=open.requestsAfter}led.foldSeqCounter+=1;led.folds.push({...f2,seq:led.foldSeqCounter,T:0,hPct:null,requestsAfter:0,k:null})}function recordCacheFoldsFromBlocks(session,blocks,geo){if(blocks.length===0)return;const led=getCacheLedger(session);for(const b2 of blocks){const id=refNum3(b2.blockId);if(id<=led.lastBlockId)continue;pushFold(led,{at:b2.createdAt||Date.now(),S:b2.compressedTokens,sigma:Math.ceil(b2.summary.length/4),X:b2.startRef?prefixTokensBeforeRef(session,b2.startRef):void 0,V:geo?.V,Vp:geo?.Vp,bid:b2.blockId});led.lastBlockId=Math.max(led.lastBlockId,id)}}function detectNewFolds(session,led){const blocks=session.state?.blocks??[];let maxId=led.lastBlockId;for(const b2 of blocks)maxId=Math.max(maxId,refNum3(b2.blockId));if(maxId>led.lastBlockId){recordCacheFoldsFromBlocks(session,blocks.filter(b2=>refNum3(b2.blockId)>led.lastBlockId))}}function detectOrphanSweeps(session,led){const n=session.state?.sweptOrphanCallIds?.length??0;if(led.lastSweptCount===void 0){led.lastSweptCount=n;led.sweepThisSample=0;return}const delta=n-led.lastSweptCount;led.lastSweptCount=n;led.sweepThisSample=delta>0?delta:0}function recordCacheSample(session,s3){const led=getCacheLedger(session);detectNewFolds(session,led);detectOrphanSweeps(session,led);const prevLine=led.lines[led.lines.length-1];const known=s3.cached!==null;const effCached=s3.cached??0;const eff=typeof s3.effFp==="string"&&s3.effFp!==""?s3.effFp:void 0;const warmLine=known&&s3.input>0&&effCached/s3.input*100>=FOLD_CLAIM_WARM_HIT_PCT;const pendRefs=led.folds.filter(f2=>f2.at<=s3.at&&!f2.retired&&((f2.claims??0)===0||!warmLine));const pending=pendRefs.map(f2=>({at:f2.at,tokensCompressed:f2.S,summaryTokens:f2.sigma,firstFoldStartTokens:f2.X,viewBefore:f2.V,viewAfter:f2.Vp}));if(pending.length>0&&known&&s3.input>0){const rawMissed=s3.input-effCached;if(rawMissed>8192&&rawMissed>.3*s3.input){const{sentBody:curB,inBody:curIn}=pendingEvidencePair(session);const prevB=session.transient?.settledBody;if(curB!==void 0&&prevB!==void 0&&curB.bytes<=SEAM_BODY_CAP&&prevB.bytes<=SEAM_BODY_CAP){const prevIn=session.transient?.settledInBody;const clientBreak=curIn!==void 0&&prevIn!==void 0&&curIn.msgs<=INBOUND_MSG_CAP&&prevIn.msgs<=INBOUND_MSG_CAP&&(()=>{const k2=firstDivergentInboundMsg(prevIn,curIn);return k2!==null&&k2<Math.min(prevIn.msgs,curIn.msgs)})();if(!clientBreak){const lcp=seamLcp(prevB.head,curB.head);if(lcp.msgIndex!==null&&lcp.prevMsgs>0&&lcp.msgIndex<lcp.prevMsgs&&lcp.lcpBytes>0&&lcp.lcpBytes<curB.head.byteLength){const xMeasured=Math.round(s3.input*(lcp.lcpBytes/curB.bytes));for(const p2 of pending)p2.firstFoldStartTokens=Math.min(p2.firstFoldStartTokens??Number.POSITIVE_INFINITY,xMeasured)}}}}}const rawDec=decomposeSample(prevLine?{at:prevLine.at,input:prevLine.input,cached:prevLine.cached}:null,{at:s3.at,input:s3.input,cached:effCached},pending);const noBaseline=!prevLine&&known;const dec=noBaseline?{...rawDec,newContent:rawDec.newContent+rawDec.ttlRepay,ttlRepay:0}:rawDec;let foldSeq=null;if(known&&dec.foldIndex!==null)foldSeq=pendRefs[dec.foldIndex]?.seq??null;if(known&&pendRefs.length>0){for(const f2 of pendRefs){f2.claims=(f2.claims??0)+1;if(f2.claims>=FOLD_CLAIM_COLD_ROUNDS){f2.retired=true;led.consumedFoldSeq=Math.max(led.consumedFoldSeq,f2.seq)}}}if(known&&warmLine){for(const f2 of led.folds){if(f2.at<=s3.at&&!f2.retired){f2.retired=true;led.consumedFoldSeq=Math.max(led.consumedFoldSeq,f2.seq)}}}const hitPct2=known&&s3.input>0?round12(effCached/s3.input*100):null;const model=typeof session.metadata?.lastModel==="string"&&session.metadata.lastModel!==""?session.metadata.lastModel:void 0;const proto=typeof s3.protocol==="string"&&s3.protocol!==""?s3.protocol:void 0;const up=typeof s3.upstream==="string"&&s3.upstream!==""?s3.upstream:void 0;const key2=typeof s3.keyFp==="string"&&s3.keyFp!==""?s3.keyFp:void 0;const sys=typeof s3.sysFp==="string"&&s3.sysFp!==""?s3.sysFp:void 0;const canon2=typeof s3.canonFp==="string"&&s3.canonFp!==""?s3.canonFp:void 0;const modelSwitched=known&&model!==void 0&&led.lastKnownModel!==void 0&&model!==led.lastKnownModel;const effortSwitched=known&&eff!==void 0&&led.lastKnownEff!==void 0&&eff!==led.lastKnownEff;const wireSwitched=known&&proto!==void 0&&led.lastKnownProto!==void 0&&proto!==led.lastKnownProto;const upstreamSwitched=known&&up!==void 0&&led.lastKnownUp!==void 0&&up!==led.lastKnownUp;const keySwitched=known&&key2!==void 0&&led.lastKnownKey!==void 0&&key2!==led.lastKnownKey;const promptSwitched=known&&sys!==void 0&&led.lastKnownSp!==void 0&&sys!==led.lastKnownSp;const canonSwitched=known&&canon2!==void 0&&led.lastKnownCanon!==void 0&&canon2!==led.lastKnownCanon;const projFlip=promptSwitched&&!canonSwitched&&canon2!==void 0&&led.lastKnownCanon!==void 0;const restarted=known&&led.lines.length>0&&led.lastBoot!==void 0&&led.lastBoot!==BOOT_ID;const covAll=session.metadata[METADATA_FOLD_COVERAGE];const lostLogged=session.metadata[LOST_LOGGED_KEY]??{};let lostDirty=false;for(const f2 of led.folds){if(f2.at<=s3.at){const cov=f2.bid!==void 0?covAll?.[f2.bid]:void 0;let frac=1;let lost=null;if(cov!==void 0&&cov.e===1&&typeof cov.t==="number"&&cov.t>0){const present=(cov.p??0)+(cov.r??0);frac=Math.min(1,present/cov.t);lost=present===0}f2.requestsAfter+=frac;if(known&&f2.hPct===null)f2.hPct=hitPct2;if(lost!==null&&f2.bid!==void 0){if(lost&&lostLogged[f2.bid]!==true){lostLogged[f2.bid]=true;lostDirty=true;log("warn",`[${session.id}] [cache-ledger] fold seq ${f2.seq} (block ${f2.bid}) coverage-lost: covered id(s) no longer on the resent wire \u2014 avoided-token accrual frozen at requestsAfter=${f2.requestsAfter.toFixed(1)} (#2202)`)}else if(!lost&&lostLogged[f2.bid]===true){delete lostLogged[f2.bid];lostDirty=true;log("info",`[${session.id}] [cache-ledger] fold seq ${f2.seq} (block ${f2.bid}) coverage restored \u2014 avoided-token accrual resumes (#2202)`)}}}}if(lostDirty)session.metadata[LOST_LOGGED_KEY]=lostLogged;if(foldSeq!==null){const owner=led.folds.find(f2=>f2.seq===foldSeq);if(owner)owner.T+=dec.compRepay}led.sampleSeq+=1;const isWarm=known&&s3.input>0&&(hitPct2??0)>=WARM_HIT_PCT;const seq=led.sampleSeq;const contWithin=inv=>inv!==void 0&&!isWarm&&seq-inv.seq<=SWITCH_COLD_ROUNDS;const freshCause=restarted?"restart":modelSwitched?"model":effortSwitched?"effort":keySwitched?"key":promptSwitched&&!projFlip?"prompt":projFlip?"projection":wireSwitched?"wire":upstreamSwitched?"upstream":null;const cause=freshCause!==null?freshCause:contWithin(led.invModel)?"model":contWithin(led.invEff)?"effort":contWithin(led.invKey)?"key":contWithin(led.invSp)?"prompt":contWithin(led.invProj)?"projection":contWithin(led.invWire)?"wire":contWithin(led.invUp)?"upstream":null;led.lines.push({seq:led.sampleSeq,at:s3.at,input:s3.input,cached:effCached,output:s3.output??0,hitPct:hitPct2,missed:known?dec.missed:0,nc:known?dec.newContent:0,cr:known?dec.compRepay:0,tr:known?dec.ttlRepay:0,foldSeq,model,proto,up,kp:key2,sp:sys,efp:eff,sw:modelSwitched?1:void 0,ef:effortSwitched?1:void 0,pw:wireSwitched?1:void 0,uw:upstreamSwitched?1:void 0,kw:keySwitched?1:void 0,sf:promptSwitched?1:void 0,pf:projFlip?1:void 0,cf:!promptSwitched&&canonSwitched?1:void 0,pm:s3.mode,rs:restarted?1:void 0,unk:known?void 0:1,nb:noBaseline?1:void 0,cause:known&&cause!==null?cause:void 0});led.lastBoot=BOOT_ID;const agg=led.agg;agg.requests+=1;agg.output+=s3.output??0;if(!known){agg.unknownInput+=s3.input;agg.unknownSamples+=1;return}agg.input+=s3.input;agg.cached+=effCached;agg.nc+=dec.newContent;agg.cr+=dec.compRepay;agg.tr+=dec.ttlRepay;if(freshCause==="restart")agg.restartDrops+=1;else if(freshCause==="model")agg.switches+=1;else if(freshCause==="effort")agg.effSwitches+=1;else if(freshCause==="key")agg.keySwitches+=1;else if(freshCause==="prompt")agg.promptSwitches+=1;else if(freshCause==="projection")agg.projSwitches+=1;else if(freshCause==="wire")agg.wireSwitches+=1;else if(freshCause==="upstream")agg.upstreamSwitches+=1;if(cause==="model")agg.switchMissed+=dec.ttlRepay;else if(cause==="effort")agg.effSwitchMissed+=dec.ttlRepay;else if(cause==="key")agg.keySwitchMissed+=dec.ttlRepay;else if(cause==="prompt")agg.promptSwitchMissed+=dec.ttlRepay;else if(cause==="projection")agg.projSwitchMissed+=dec.ttlRepay;else if(cause==="wire")agg.wireSwitchMissed+=dec.ttlRepay;else if(cause==="upstream")agg.upstreamSwitchMissed+=dec.ttlRepay;else if(cause==="restart")agg.restartDropMissed+=dec.ttlRepay;if(cause!==null)agg.attributedMissed+=dec.ttlRepay;if(isWarm){led.invModel=void 0;led.invEff=void 0;led.invWire=void 0;led.invUp=void 0;led.invKey=void 0;led.invSp=void 0;led.invProj=void 0}else{if(led.invModel&&seq-led.invModel.seq>SWITCH_COLD_ROUNDS)led.invModel=void 0;if(led.invEff&&seq-led.invEff.seq>SWITCH_COLD_ROUNDS)led.invEff=void 0;if(led.invWire&&seq-led.invWire.seq>SWITCH_COLD_ROUNDS)led.invWire=void 0;if(led.invUp&&seq-led.invUp.seq>SWITCH_COLD_ROUNDS)led.invUp=void 0;if(led.invKey&&seq-led.invKey.seq>SWITCH_COLD_ROUNDS)led.invKey=void 0;if(led.invSp&&seq-led.invSp.seq>SWITCH_COLD_ROUNDS)led.invSp=void 0;if(led.invProj&&seq-led.invProj.seq>SWITCH_COLD_ROUNDS)led.invProj=void 0}if(modelSwitched)led.invModel={seq,at:s3.at,from:led.lastKnownModel??null,to:model};if(effortSwitched)led.invEff={seq,at:s3.at,from:led.lastKnownEff??null,to:eff};if(wireSwitched)led.invWire={seq,at:s3.at,from:led.lastKnownProto??null,to:proto};if(upstreamSwitched)led.invUp={seq,at:s3.at,from:led.lastKnownUp??null,to:up};if(keySwitched)led.invKey={seq,at:s3.at,from:led.lastKnownKey??null,to:key2};if(promptSwitched&&!projFlip)led.invSp={seq,at:s3.at,from:led.lastKnownSp??null,to:sys};if(projFlip)led.invProj={seq,at:s3.at,from:led.lastKnownSp??null,to:sys};if(model!==void 0)led.lastKnownModel=model;if(eff!==void 0)led.lastKnownEff=eff;if(proto!==void 0)led.lastKnownProto=proto;if(up!==void 0)led.lastKnownUp=up;if(key2!==void 0)led.lastKnownKey=key2;if(sys!==void 0)led.lastKnownSp=sys;if(canon2!==void 0)led.lastKnownCanon=canon2;if(noBaseline){agg.nbSamples+=1;agg.nbInput+=s3.input}}var CALIBRATION_MIN_ESTIMATE=2e3;var CALIBRATION_SAMPLE_MIN=.2;var CALIBRATION_SAMPLE_MAX=5;var CALIBRATION_CLAMP_MIN=.25;var CALIBRATION_CLAMP_MAX=4;var CALIBRATION_SAMPLE_WINDOW=3;var CALIBRATION_CONSISTENCY_RATIO=2;function canonicalSysFpForSettle(session,protocol){if(protocol!=="responses")return void 0;const noted=session.metadata?.[METADATA_CANONICAL_SYS_FP];return typeof noted?.fp==="string"&¬ed.fp!==""?noted.fp:void 0}function ingestCalibrationPair(session,billed,upstream){const settleOrigin=normalizeUpstreamOrigin(upstream);const pendingCalibOrigin=session.stats.lastCalibrationPolicyOrigin!==void 0?normalizeUpstreamOrigin(session.stats.lastCalibrationPolicyOrigin):void 0;const calibPolicy=pendingCalibOrigin===settleOrigin?session.stats.lastCalibrationPolicy:void 0;const pendingEst=session.stats.lastLocalTextEstimate;const pendingOrigin=normalizeUpstreamOrigin(session.stats.lastLocalTextEstimateOrigin);if(pendingEst!==void 0&&pendingEst>=CALIBRATION_MIN_ESTIMATE&&settleOrigin!==void 0&&pendingOrigin===settleOrigin){const rawSample=billed/pendingEst;const settleModel=typeof session.metadata?.lastModel==="string"&&session.metadata.lastModel!==""?session.metadata.lastModel:void 0;let ring=session.stats.calibrationRing;if(!ring||ring.origin!==settleOrigin||ring.model!==void 0&&settleModel!==void 0&&ring.model!==settleModel){ring={origin:settleOrigin,model:settleModel,values:[]}}else if(ring.model===void 0&&settleModel!==void 0){ring.model=settleModel}if(rawSample>=CALIBRATION_SAMPLE_MIN&&rawSample<=CALIBRATION_SAMPLE_MAX){ring.values.push(rawSample);if(ring.values.length>CALIBRATION_SAMPLE_WINDOW)ring.values.shift();const spread=Math.max(...ring.values)/Math.min(...ring.values);if(ring.values.length>=2&&spread<=CALIBRATION_CONSISTENCY_RATIO){const mean=ring.values.reduce((a,b2)=>a+b2,0)/ring.values.length;if(calibPolicy?.disabled===true){delete session.stats.calibratedEstimate;delete session.stats.calibratedEstimateOrigin;delete session.stats.calibratedEstimateModel}else{const clamped=Math.min(CALIBRATION_CLAMP_MAX,Math.max(CALIBRATION_CLAMP_MIN,mean));session.stats.calibratedEstimate=calibPolicy?.max!==void 0?Math.min(clamped,calibPolicy.max):clamped;session.stats.calibratedEstimateOrigin=settleOrigin;session.stats.calibratedEstimateModel=ring.model}}else{delete session.stats.calibratedEstimate;delete session.stats.calibratedEstimateOrigin;delete session.stats.calibratedEstimateModel}}session.stats.calibrationRing=ring}}function settleOverflowCalibration(session,measured,upstream){if(!(measured>0))return;ingestCalibrationPair(session,measured,upstream);session.stats.lastLocalTextEstimate=void 0;session.stats.lastLocalTextEstimateOrigin=void 0}function noteOutboundContextEstimates(session,est){session.stats.localInputEstimate=est.upperBound;session.stats.contextEstimateTokens=Math.round(est.scaledText+est.imageTokens);session.stats.contextEstimateCalibrated=est.calibrated;session.stats.contextTokens=est.upperBound;session.stats.contextTokensSource="estimate"}function settleUsageReport(session,s3,localTextEstimate){if(s3.total>0){session.stats.inputTokens+=s3.total;billInputUsage(session,{total:s3.total,cached:s3.reportedCached,creation:s3.creation});if(isForeignMembership(session.transient?.requestMembership)){const m2=session.transient.requestMembership;log("info",`[${session.id}] [membership] usage sample (total=${s3.total}) refused anchor write: its request did not carry the conversation's latest message id (needle=${m2.needle??"-"}) \u2014 foreign payload under a shared session id (#4805)`)}else{session.stats.lastInputTokens=Math.max(0,s3.total-(session.stats.compressCreditTokens??0));session.stats.lastUsageGradeTokens=session.stats.lastInputTokens;session.stats.lastUsagePayloadUpper=session.stats.localInputEstimate??0;session.stats.lastInputTokensSource="usage";delete session.stats.emergencyShrinkAt;delete session.stats.emergencyShrinkEstimate;session.stats.contextTokens=session.stats.lastInputTokens;session.stats.contextTokensSource="usage";if(session.metadata)session.metadata.contextTokensAt=Date.now();recordContextObservation(session,session.stats.lastInputTokens,(session.stats.compressCreditTokens??0)>0?"estimate":"usage");const settleOrigin=normalizeUpstreamOrigin(s3.upstream);if(settleOrigin!==void 0)session.stats.lastInputTokensOrigin=settleOrigin;ingestCalibrationPair(session,s3.total,s3.upstream);clearPostRebuildAnchor(session);delete session.stats.overflowArmTokens;delete session.stats.overflowArmCompletionReserve}}session.stats.lastLocalTextEstimate=localTextEstimate;session.stats.lastLocalTextEstimateOrigin=localTextEstimate!==void 0?normalizeUpstreamOrigin(s3.upstream):void 0;if(s3.reportedCached!==null&&s3.total>0){session.stats.cachedTokens+=s3.reportedCached;session.stats.cacheSamples+=1}const curKeyFp=pendingCapture(session).sentBody?.keyFp;const curEffFp=pendingCapture(session).sentBody?.effFp;const notedSys=session.metadata?.[METADATA_SYSTEM_FP];const curSysFp=typeof notedSys?.fp==="string"&¬edSys.fp!==""?notedSys.fp:void 0;const curCanonFp=canonicalSysFpForSettle(session,s3.protocol);const lastMode=s3.protocol==="responses"?session.metadata?.[METADATA_LAST_RESPONSES_MODE]:void 0;const led=getCacheLedger(session);recordCacheSample(session,{at:Date.now(),input:s3.total,cached:s3.reportedCached,output:s3.output,protocol:s3.protocol,upstream:s3.upstream,keyFp:curKeyFp,sysFp:curSysFp,canonFp:curCanonFp,effFp:curEffFp,mode:lastMode==="plugin"||lastMode==="proxy"?lastMode:void 0});const capture2=captures.getStore();const sample=led.lines[led.lines.length-1];if(capture2?.session===session&&sample){sample.captureId=capture2.requestId;sample.captureRound=capture2.round}const curSlot=pendingCapture(session).sentBody;if(curSlot!==void 0){const curLine=led.lines[led.lines.length-1];if(curLine!==void 0){curLine.bd=curSlot.digest;const settled2=session.transient?.settledBody;const backwards2=curSlot.order!==void 0&&settled2?.order!==void 0&&curSlot.order<=settled2.order;const prevSlot=backwards2?void 0:settled2;if(backwards2)curLine.evidence="out-of-order";if(prevSlot!==void 0){if(curSlot.digest===prevSlot.digest){curLine.be=1}else{curLine.be=0;if(curSlot.full!==null&&prevSlot.full!==null){const lcp=byteLcp(prevSlot.full,curSlot.full);curLine.bl=lcp;const shorterFull=prevSlot.full.length<=curSlot.full.length?prevSlot.full:curSlot.full;const arrClose=messagesArrayCloseOffset(shorterFull);const midInsert=isMidInsertionAppend(prevSlot.full,curSlot.full,lcp);curLine.bs=lcp>=Math.min(prevSlot.full.length,curSlot.full.length)-64?"append":lcp<1024?"head":arrClose!==null&&lcp>=arrClose?"tail":midInsert?"append":"mid"}else{curLine.bs="unknown"}}}}}settleImageLearning(session,s3.total);detectSeam(session,led);const pending=pendingCapture(session);const settled=session.transient??={};const seamBody=pending.sentBody;const backwards=seamBody?.order!==void 0&&settled.settledBody?.order!==void 0&&seamBody.order<=settled.settledBody.order;if(seamBody!==void 0&&!backwards)settled.settledBody=seamBody;else delete settled.settledBody;delete pending.sentBody;const seamIn=pending.inBody;if(seamBody!==void 0&&seamIn!==void 0&&!backwards)settled.settledInBody=seamIn;else delete settled.settledInBody;delete pending.inBody}function stampedPriceProfile(session){const v2=session.metadata?.cachePriceProfile;if(!v2||typeof v2!=="object"||Array.isArray(v2))return void 0;const o=v2;const out={};for(const key2 of["w","r","q"]){const n=o[key2];if(typeof n==="number"&&Number.isFinite(n)&&n>=0)out[key2]=n}return Object.keys(out).length>0?out:void 0}function buildSessionCacheReport(session){const led=getCacheLedger(session);const price=stampedPriceProfile(session);const effective={w:price?.w??1,r:price?.r??.1,q:price?.q??4};const a=led.agg;const totals={requests:a.requests,input:a.input,cached:a.cached,output:a.output,hitPct:a.input>0?round12(a.cached/a.input*100):0,newContent:a.nc,compRepay:a.cr,ttlRepay:a.tr,residual:a.input-a.cached-(a.nc+a.cr+a.tr),balanced:true};totals.balanced=totals.residual===0;const folds=led.folds.map(f2=>computeFoldEconomics({seq:f2.seq,at:f2.at,S:f2.S,sigma:f2.sigma,Vprime:f2.Vp??null,hPct:f2.hPct,T:f2.T,requestsAfter:f2.requestsAfter,turnsToNextFold:f2.k},effective));const knownLines=led.lines.filter(l=>l.unk!==1);const switchEvents=(flag,value,dim)=>{const evs=[];for(let i=0;i<led.lines.length;i++){const l=led.lines[i];if(!l||l.unk===1||!flag(l))continue;if(l.cause!==void 0&&l.cause!==dim)continue;let from;for(let j2=i-1;j2>=0;j2--){const p2=led.lines[j2];if(p2&&p2.unk!==1){from=value(p2);break}}evs.push({seq:l.seq,at:l.at,from:from??null,to:value(l)??"?",input:l.input,cached:l.cached,hitPct:l.hitPct??0,attributed:l.cause===dim||l.cause===void 0?l.tr:0})}return evs};const restartEvents=[];for(const l of led.lines){if(l.rs!==1||l.unk===1)continue;restartEvents.push({seq:l.seq,at:l.at,from:null,to:"(restart)",input:l.input,cached:l.cached,hitPct:l.hitPct??0,attributed:l.cause==="restart"||l.cause===void 0?l.tr:0})}const invalidation={model:a.switchMissed,effort:a.effSwitchMissed,key:a.keySwitchMissed,prompt:a.promptSwitchMissed,projection:a.projSwitchMissed,wire:a.wireSwitchMissed,upstream:a.upstreamSwitchMissed,restart:a.restartDropMissed,remaining:Math.max(0,a.tr-a.attributedMissed)};let paired=0;let equal=0;let head=0;let append=0;let mid=0;let tail=0;let unknownOffset=0;for(const l of knownLines){if(l.be===void 0)continue;paired+=1;if(l.be===1){equal+=1;continue}if(l.bs==="head")head+=1;else if(l.bs==="append")append+=1;else if(l.bs==="mid")mid+=1;else if(l.bs==="tail")tail+=1;else unknownOffset+=1}const sizeBuckets=[];{const byLo=new Map;for(const l of knownLines){if(l.hitPct===null||l.input<=0)continue;const lo2=Math.floor(l.input/SIZE_BUCKET_TOK)*SIZE_BUCKET_TOK;const hits=byLo.get(lo2);if(hits)hits.push(l.hitPct);else byLo.set(lo2,[l.hitPct])}for(const[lo2,hits]of[...byLo.entries()].sort((x,y)=>x[0]-y[0]).slice(0,24)){sizeBuckets.push({lo:lo2,hi:lo2+SIZE_BUCKET_TOK,n:hits.length,hitMedian:median(hits)??0,hitMin:Math.min(...hits)})}}const lowGaps=[];const highGaps=[];for(let i=1;i<led.lines.length;i++){const p2=led.lines[i-1];const c=led.lines[i];if(!p2||!c||c.hitPct===null)continue;const gap=c.at-p2.at;if(!(gap>0))continue;(c.hitPct<80?lowGaps:highGaps).push(gap)}const stability={paired,equal,diverged:paired-equal,head,append,mid,tail,unknownOffset,sizeBuckets,gapSplit:{lowHitMedGapMs:median(lowGaps),highHitMedGapMs:median(highGaps)}};return{generatedAt:Date.now(),profile:effective,totals,economics:summarizeFoldEconomics(folds),folds,lines:knownLines.map(l=>({seq:l.seq,at:l.at,input:l.input,cached:l.cached,output:l.output,hitPct:l.hitPct??0,missed:l.missed,newContent:l.nc,compRepay:l.cr,ttlRepay:l.tr,foldSeq:l.foldSeq,seam:l.seam,prov:l.prov,captureId:l.captureId,captureRound:l.captureRound,evidence:l.evidence,bodyDigest:l.bd,keyFp:l.kp,sysFp:l.sp,efp:l.efp,bodyEqual:l.be,bodyLcp:l.bl,bodyClass:l.bs})),linesOmitted:led.sampleSeq-led.lines.length,modelSwitches:{count:a.switches,missedTokens:a.switchMissed,events:switchEvents(l=>l.sw===1&&l.model!==void 0,l=>l?.model,"model")},effSwitches:{count:a.effSwitches,missedTokens:a.effSwitchMissed,events:switchEvents(l=>l.ef===1&&l.efp!==void 0,l=>l?.efp,"effort")},keySwitches:{count:a.keySwitches,missedTokens:a.keySwitchMissed,events:switchEvents(l=>l.kw===1&&l.kp!==void 0,l=>l?.kp,"key")},promptSwitches:{count:a.promptSwitches,missedTokens:a.promptSwitchMissed,events:switchEvents(l=>l.sf===1&&l.sp!==void 0,l=>l?.sp,"prompt")},projSwitches:{count:a.projSwitches,missedTokens:a.projSwitchMissed,events:switchEvents(l=>l.pf===1&&l.sp!==void 0,l=>l?.sp,"projection")},wireSwitches:{count:a.wireSwitches,missedTokens:a.wireSwitchMissed,events:switchEvents(l=>l.pw===1&&l.proto!==void 0,l=>l?.proto,"wire")},upstreamSwitches:{count:a.upstreamSwitches,missedTokens:a.upstreamSwitchMissed,events:switchEvents(l=>l.uw===1&&l.up!==void 0,l=>l?.up,"upstream")},restartDrops:{count:a.restartDrops,missedTokens:a.restartDropMissed,events:restartEvents},unmeasured:{samples:a.unknownSamples,inputTokens:a.unknownInput},initialBills:{samples:a.nbSamples,inputTokens:a.nbInput},invalidation,stability,seam:{suspects:a.seamSuspects,missed:a.seamMissed,events:led.seamEvents??[],providerSide:{count:a.providerSideMisses,missed:a.providerSideMissed},providerTtl:{count:a.providerTtlMisses,missed:a.providerTtlMissed},rewinds:{count:a.rewinds,missed:a.rewindMissed},abortCorrelated:a.abortCorrelated,client:{count:a.clientInserts,missed:a.clientInsertMissed},orphanSweep:{count:a.orphanSweepSeams,missed:a.orphanSweepMissed}}}}function readModelSwitchStats(session){const raw=session.metadata?.[LEDGER_KEY];if(!raw||typeof raw!=="object")return null;const led=raw;if(led.v!==1)return null;return{count:typeof led.agg?.switches==="number"?led.agg.switches:0,missedTokens:typeof led.agg?.switchMissed==="number"?led.agg.switchMissed:0}}function readKeySwitchStats(session){const raw=session.metadata?.[LEDGER_KEY];if(!raw||typeof raw!=="object")return null;const led=raw;if(led.v!==1)return null;return{count:typeof led.agg?.keySwitches==="number"?led.agg.keySwitches:0,missedTokens:typeof led.agg?.keySwitchMissed==="number"?led.agg.keySwitchMissed:0}}function readPromptSwitchStats(session){const raw=session.metadata?.[LEDGER_KEY];if(!raw||typeof raw!=="object")return null;const led=raw;if(led.v!==1)return null;return{count:typeof led.agg?.promptSwitches==="number"?led.agg.promptSwitches:0,missedTokens:typeof led.agg?.promptSwitchMissed==="number"?led.agg.promptSwitchMissed:0}}function readProjSwitchStats(session){const raw=session.metadata?.[LEDGER_KEY];if(!raw||typeof raw!=="object")return null;const led=raw;if(led.v!==1)return null;return{count:typeof led.agg?.projSwitches==="number"?led.agg.projSwitches:0,missedTokens:typeof led.agg?.projSwitchMissed==="number"?led.agg.projSwitchMissed:0}}function formatStability(st2){if(st2.paired===0)return"";const out=["BODY STABILITY (per-call outbound byte proof, vs previous settled request)"];out.push(` ${st2.paired} pair(s): ${st2.equal} byte-identical \xB7 ${st2.diverged} diverged`);out.push(` divergence class: head <1KiB ${st2.head} \xB7 tail-append ${st2.append} \xB7 mid-history ${st2.mid} \xB7 tail(params/notes) ${st2.tail} \xB7 offset-unknown(capped) ${st2.unknownOffset}`);if(st2.head>0)out.push(` \u26A0 ${st2.head} head-region divergence(s) \u2014 model/tools/sampling/system changed between calls (host-side parameter change, NOT a bili history rewrite)`);if(st2.mid>0)out.push(` \u26A0 ${st2.mid} mid-history divergence(s) \u2014 real prefix rewrites; inspect the seam events above`);if(st2.tail>0)out.push(` ${st2.tail} tail-region divergence(s) \u2014 trailing top-level params or ephemeral tail notes at/past the message-array end; shared history bytes untouched, but a provider may re-partition its prompt cache on a trailing field such as reasoning effort \u2014 see EFFORT SWITCHES / invalidation above (#3803)`);const sb=st2.sizeBuckets.filter(b2=>b2.n>=3);if(sb.length>=2)out.push(" hit% by input size (median): "+sb.map(b2=>`${Math.round(b2.lo/1e3)}K=${b2.hitMedian}%`).join(" "));const g2=st2.gapSplit;if(g2.lowHitMedGapMs!==null&&g2.highHitMedGapMs!==null){out.push(` inter-request gap median: low-hit(<80%) ${(g2.lowHitMedGapMs/1e3).toFixed(1)}s vs high-hit ${(g2.highHitMedGapMs/1e3).toFixed(1)}s`)}return out.join("\n")}function handleAcpCache(session,args){try{const detail=args?.detail==="full"?"full":"summary";const report=buildSessionCacheReport(session);const stabilityText=formatStability(report.stability);const tail=base=>base+(stabilityText?"\n\n"+stabilityText:"")+(formatSeam(report)?"\n\n"+formatSeam(report):"");const effText=report.effSwitches.count>0?"\n\n"+formatModelSwitches(report.effSwitches,detail,"EFFORT SWITCHES (host changed reasoning effort / thinking config)"):"";const keyText=report.keySwitches.count>0?"\n\n"+formatModelSwitches(report.keySwitches,detail,"KEY SWITCHES (relay account rotation)"):"";const promptText=report.promptSwitches.count>0?"\n\n"+formatModelSwitches(report.promptSwitches,detail,"PROMPT SWITCHES (host rewrote system prompt)"):"";const projText=report.projSwitches.count>0?"\n\n"+formatModelSwitches(report.projSwitches,detail,"PROJECTION SWITCHES (proxy mode/projection change \u2014 bili's own doing, e.g. self-heal degrade-to-proxy)"):"";const wireText=report.wireSwitches.count>0?"\n\n"+formatModelSwitches(report.wireSwitches,detail,"WIRE SWITCHES (client switched protocol wire between requests)"):"";const upstreamText=report.upstreamSwitches.count>0?"\n\n"+formatModelSwitches(report.upstreamSwitches,detail,"UPSTREAM SWITCHES (relay/upstream origin changed between requests)"):"";const restartText=report.restartDrops.count>0?"\n\n"+formatModelSwitches(report.restartDrops,detail,"RESTART/REFORK (first bill under a fresh daemon boot \u2014 prefix re-billed once)"):"";if(detail==="full"&&report.lines.length>FULL_DETAIL_LINES){const dropped=report.lines.length-FULL_DETAIL_LINES;const capped=formatCacheReport({...report,lines:report.lines.slice(-FULL_DETAIL_LINES),linesOmitted:report.linesOmitted+dropped},session.id,{detail});return toolOk(tail(capped+"\n\n"+formatModelSwitches(report.modelSwitches,detail)+effText+keyText+promptText+projText+wireText+upstreamText+restartText+"\n\n"+formatInvalidation(report)))}return toolOk(tail(formatCacheReport(report,session.id,{detail})+"\n\n"+formatModelSwitches(report.modelSwitches,detail)+effText+keyText+promptText+projText+wireText+upstreamText+restartText+"\n\n"+formatInvalidation(report)))}catch(err2){log("warn",`[${session.id}] [acp_cache] report failed: ${String(err2)}`);return toolFail(`[acp_cache FAILED: ${String(err2)}]`)}}function fmtTok2(n){const v2=Math.round(n);return v2>=1e6?`${(v2/1e6).toFixed(2)}M`:v2>=1e4?`${(v2/1e3).toFixed(1)}K`:String(v2)}function fmtTime2(at2){const d=new Date(at2);const p2=x=>String(x).padStart(2,"0");return`${p2(d.getHours())}:${p2(d.getMinutes())}:${p2(d.getSeconds())}`}var SWITCH_LIST_CAP=8;function formatModelSwitches(sw,detail,title="MODEL SWITCHES"){const out=[title];if(sw.count===0){out.push(" none observed");return out.join("\n")}const eventSum=sw.events.reduce((n,e)=>n+e.attributed,0);const tail=sw.missedTokens-eventSum;out.push(` ${sw.count} switch(es) \xB7 ${fmtTok2(sw.missedTokens)} tok re-billed${tail>0?` (${fmtTok2(tail)} on post-switch cold rounds)`:""}`);const shown=detail==="full"?sw.events:sw.events.slice(-SWITCH_LIST_CAP);for(const e of shown){out.push(` #${e.seq} ${fmtTime2(e.at)} ${e.from??"?"} \u2192 ${e.to} \xB7 hit ${e.hitPct.toFixed(1)}% \xB7 attributed ${fmtTok2(e.attributed)}`)}if(shown.length<sw.events.length){out.push(` \u2026 ${sw.events.length-shown.length} earlier switch(es) omitted (detail:"full" lists all)`)}return out.join("\n")}function formatSeam(r){const out=[];if(r.seam.suspects>0){out.push("\u26A0 CACHE SEAM (suspected mid-history prefix breaks)");out.push(` ${r.seam.suspects} sample(s) \xB7 ${fmtTok2(r.seam.missed)} tok re-billed with no fold/switch/restart attribution`);const suspectEvents=r.seam.events.filter(e=>!e.client);for(const e of suspectEvents){out.push(` #${e.seq} ${fmtTime2(e.at)} hit ${e.hitPct.toFixed(1)}% \xB7 input ${fmtTok2(e.input)} \xB7 divergence \u2265${fmtTok2(e.lcpBytes)}B at message[${e.msgIndex??"?"}] of ${e.prevMsgs}\u2192${e.curMsgs}`)}if(suspectEvents.length===0){out.push(" (no body-pair forensics retained for the suspect samples on this lane \u2014 aggregate flag only; client-side rewrites are listed separately below)")}out.push(' if reproducible: /acp-cache detail:"full" + bili.log around the timestamps above (likely a #1548-family round-2/steady render seam)')}if(r.seam.rewinds.count>0){out.push("\u21A9 HISTORY REWOUND (client revert/trim)");out.push(` ${r.seam.rewinds.count} sample(s) \xB7 ${fmtTok2(r.seam.rewinds.missed)} tok re-billed once for the retained prefix \u2014 sanctioned client intent, not a rebuild seam`)}if(r.seam.providerTtl.count>0){out.push("\u23F1 UPSTREAM TTL EXPIRY \u2014 NORMAL (long idle gap)");out.push(` ${r.seam.providerTtl.count} sample(s) \xB7 ${fmtTok2(r.seam.providerTtl.missed)} tok \u2014 byte-stable/append-shaped misses settled more than ${Math.round(PROVIDER_TTL_GAP_MS/6e4)} min after the previous sample: the upstream prefix cache simply aged out. Expected cost, not a failure.`)}if(r.seam.providerSide.count>0){out.push("\u25B2 PROVIDER-SIDE MISS (previous request's message list fully preserved)");out.push(` ${r.seam.providerSide.count} sample(s) \xB7 ${fmtTok2(r.seam.providerSide.missed)} tok \u2014 the previous request's message list is preserved in this one (byte-for-byte under the 512 KiB forensics cap; above it, proven by the stable recorded head plus exact message-count growth \u2014 any difference is only the appended tail), and the sample arrived within ${Math.round(PROVIDER_TTL_GAP_MS/6e4)} min of the previous one, so this is an ABNORMAL provider miss (eviction / relay node rotation), not TTL ageing. Not a bili rebuild seam.`);out.push(` stateful-upstream check (#2483): if your upstream keeps a live session per conversation and validates the echoed history against its own transcript (claude-code-based relays such as magpie), bili's render tags on assistant text trip that check even though bili's own list is unchanged \u2014 set diagnostics.renderNone=true until per-route render-tags control ships; expect exactly ONE replay when flipping the flag mid-session`)}if(r.seam.client.count>0){out.push("\u270E CLIENT MID-HISTORY REWRITE (host-side insert \u2014 NOT a bili seam)");out.push(` ${r.seam.client.count} sample(s) \xB7 ${fmtTok2(r.seam.client.missed)} tok \u2014 the client's own resent history broke mid-list, so bili's faithful rebuild carried the break to the wire (host plugin insert / paste hoisting / re-render). Client-owned re-bill, not a rebuild seam.`);for(const e of r.seam.events){if(e.client)out.push(` #${e.seq} ${fmtTime2(e.at)} hit ${e.hitPct.toFixed(1)}% \xB7 input ${fmtTok2(e.input)} \xB7 inbound message[${e.client.idx}] ${e.client.role}/${e.client.cls} ${e.client.len}B JSON \xB7 outbound ${fmtTok2(e.lcpBytes)}B @ message[${e.msgIndex??"?"}] of ${e.prevMsgs}\u2192${e.curMsgs}`)}}if(r.seam.orphanSweep.count>0){out.push("\u{1F9F9} ORPHAN CLEANUP SEAM (proactive failed-compress rotation \u2014 #3769)");out.push(` ${r.seam.orphanSweep.count} sample(s) \xB7 ${fmtTok2(r.seam.orphanSweep.missed)} tok re-billed when failed-compress records were rotated out of history without a fold claiming the break \u2014 bili's own cleanup, not an upstream or host rewrite`)}if(r.seam.abortCorrelated>0){out.push("\u23FB ABORT-CORRELATED");out.push(` ${r.seam.abortCorrelated} missed sample(s) within 30s of a client mid-stream abort \u2014 abort/retry churn rewrites the resent tail; correlation, not causation (see bili.log 'client aborted mid-stream')`)}return out.length>0?out.join("\n"):""}function formatInvalidation(r){const b2=r.invalidation;const named=b2.model+b2.effort+b2.key+b2.prompt+b2.projection+b2.wire+b2.upstream+b2.restart;const total=named+b2.remaining;const out=["CACHE INVALIDATION"];out.push(` stable-prefix re-bill by cause (mutually exclusive, sums to total): ${fmtTok2(named)} tok charged \xB7 ${fmtTok2(b2.remaining)} tok unattributed (upstream TTL/eviction/wire rewrite)`);out.push(` model switch: ${fmtTok2(b2.model)} (${r.modelSwitches.count})`);out.push(` effort switch: ${fmtTok2(b2.effort)} (${r.effSwitches.count}) \u2014 host changed reasoning effort / thinking config; provider re-partitions its prompt cache on it (#3803)`);out.push(` key switch: ${fmtTok2(b2.key)} (${r.keySwitches.count}) \u2014 relay account rotation, fingerprinted headers never logged raw`);out.push(` prompt rewrite: ${fmtTok2(b2.prompt)} (${r.promptSwitches.count}) \u2014 host rewrote its system prompt between requests (#2350)`);out.push(` projection switch: ${fmtTok2(b2.projection)} (${r.projSwitches.count}) \u2014 proxy switched compression mode/projection (self-heal degrade-to-proxy re-hoists mid-history developer items, #2867)`);out.push(` wire switch: ${fmtTok2(b2.wire)} (${r.wireSwitches.count})`);out.push(` upstream switch: ${fmtTok2(b2.upstream)} (${r.upstreamSwitches.count})`);out.push(` restart/refork: ${fmtTok2(b2.restart)} (${r.restartDrops.count})`);if(b2.remaining>0&&total>0&&b2.remaining/total>=.5){const pct2=Math.round(b2.remaining/total*100);const noCauseEver=r.modelSwitches.count===0&&r.effSwitches.count===0&&r.keySwitches.count===0&&r.promptSwitches.count===0&&r.projSwitches.count===0&&r.wireSwitches.count===0&&r.upstreamSwitches.count===0&&r.restartDrops.count===0;out.push(noCauseEver?` \u26A0 ${pct2}% of your stable-prefix re-bill has no observable cause (no model/wire/upstream switch or restart seen) \u2014 expected provider-side behavior (cache TTL expiry / eviction / relay rotation), NOT a bili bug; if reproducible see #1195 coverage-mismatch`:` \u26A0 ${pct2}% of your stable-prefix re-bill is unnameable provider-side behavior (cache TTL expiry / eviction / relay rotation) beyond the causes listed above`)}if(r.unmeasured.samples>0){out.push(` unmeasured (provider reported no cache tokens): ${r.unmeasured.samples} sample(s) \xB7 ${fmtTok2(r.unmeasured.inputTokens)} tok \u2014 excluded from hit rate`)}if(r.initialBills.samples>0){out.push(` initial bills (no prior baseline): ${r.initialBills.samples} sample(s) \xB7 ${fmtTok2(r.initialBills.inputTokens)} tok \u2014 first request(s) of a session; booked as new content, not a prefix re-pay`)}return out.join("\n")}var{join:join7}=path25;var PERSIST_VERSION=3;var SHADOW_REOPEN_COOLDOWN_MS=3e4;var SHADOW_REOPEN_READ_CHECK_MS=100;var RECON_REPLICAS_WAIT_MS=750;var RECON_REPLICAS_POLL_MS=50;var shadowReopenCooldownMsOverride=null;var shadowReopenReadCheckMsOverride=null;var MIGRATION_MARKER=".bili-migration-286.done";var STALE_WARN_THROTTLE_MS=6e4;var OWN_WRITE_STAMP_EPSILON_MS=1;function hostLabel(upstreamOrigin){if(!upstreamOrigin)return"unknown";try{const host=new URL(upstreamOrigin).hostname||"unknown";return host.replace(/[^a-zA-Z0-9.-]/g,"-").slice(0,48)||"unknown"}catch{return"unknown-"+createHash14("sha256").update(upstreamOrigin,"utf8").digest("hex").slice(0,6)}}function relPathFor(id,protocol,upstreamOrigin){const proto=protocol??"_unknown";const host=protocol?hostLabel(upstreamOrigin)+"_":"";return path25.join(proto,`${host}${createHash14("sha256").update(id,"utf8").digest("hex").slice(0,24)}.json`)}function durableWriteFile(file,data,mode){const fd=openSync(file,"w",mode);try{writeFileSync6(fd,data);fsyncSync(fd)}finally{closeSync(fd)}}function contentStoreRelPathFor(id,protocol,upstreamOrigin){const base=relPathFor(id,protocol,upstreamOrigin);return base.slice(0,-".json".length)+".content-store.json"}function fileNameMatchesId(base,id,protocol,upstreamOrigin){const relBase=path25.basename(relPathFor(id,protocol,upstreamOrigin));const flatBase=flatFileNameFor(id);if(base===relBase||base===flatBase)return true;if(base.endsWith(".fb.json")){const canonicalBase=`${base.slice(0,-".fb.json".length)}.json`;return canonicalBase===relBase||canonicalBase===flatBase}return false}var STALE_COLD_LOAD_WARN_MIN=30;var FROZEN_SKIP_NOTICE_COOLDOWN_MS=10*6e4;var SessionStore=class{syncSidecarOpen=null;sidecarReopenNextAttemptAt=0;sidecarReadCheckNextAttemptAt=0;enabled;sessionsDir;store;log;staleWarnAt=new Map;ownCommit=new Map;sessionCommitListener;setSessionCommitListener(fn){this.sessionCommitListener=fn}staleGuardFullReads=0;__staleGuardFullReadsForTests(){return this.staleGuardFullReads}__ownWriteStampedForTests(id){return this.ownCommit.get(id)?.written!==void 0}codec;readCodec;boundedReads=false;diskFiles=[];diskFilesSeeded=false;legacyAliases=new Map;sourceFiles=new Map;remainderScan=null;tmpSeq=0;shadow;residentFieldsForBuild;forkBaseCut=new Set;storageMode;jsonWriterOff;mysqlReady=Promise.resolve();networkFullExpected=false;ready(){return this.mysqlReady}writerOffPending=new Map;frozenNoticeAt=new Map;saveTimers=new Map;saveBuilders=new Map;flushWaiters=new Map;lastSaveLanded=new Map;saveWritesInFlight=new Set;durableRevision=new Map;capWarnAt=new Map;debounceMs;constructor(opts){const debounceMs=opts?.debounceMs??defaultDebounce();this.enabled=(opts?.enabled??true)&&debounceMs>=0;this.debounceMs=Math.max(0,debounceMs);this.sessionsDir=opts?.dir??defaultDir();const baseLog=opts?.log??defaultLogger;this.log=baseLog;const keyEnv=process.env.BILI_ENCRYPTION_KEY;let key2=null;if(keyEnv)key2=parseEncryptionKey(keyEnv);this.codec=createStorageCodec({key:key2,compress:persistZstdEnabled2()});this.readCodec=this.codec??createStorageCodec({compress:true});if(key2){baseLog("info","[persist] session-file encryption enabled (AES-256-GCM)")}else if(this.codec){baseLog("info","[persist] session-file compression enabled (zstd, BILIZSTD1)")}const epermAlert=new PersistEpermAlert({dir:this.sessionsDir,threshold:epermAlertThreshold(),repeatMs:epermAlertRepeatMs()});const storageMode=resolveStorageModeSafe();const unifiedBlockedByEncryption=storageMode!=="legacy"&&key2!==null;if(unifiedBlockedByEncryption){baseLog("warn","[storage] unified sidecar DISABLED: BILI_ENCRYPTION_KEY is active and index.db would hold cleartext ingest payloads \u2014 staying legacy-only")}this.storageMode=storageMode;recordRequestedMode(storageMode,unifiedBlockedByEncryption,!this.enabled);const wantJsonWriterOff=resolveJsonWriterOff(process.env,fileStorageJsonWriter());this.jsonWriterOff=wantJsonWriterOff&&storageMode==="full"&&!unifiedBlockedByEncryption&&resolveBackendName(process.env,fileStorageBackend())==="sqlite";if(wantJsonWriterOff&&!this.jsonWriterOff){baseLog("warn","[storage] storage.jsonWriter=off ignored \u2014 requires storage.unified=full on the sqlite backend (network backends keep the JSON envelope as the sync read path)")}const legacyLoad=recordToLegacyView;const backendName=resolveBackendName(process.env,fileStorageBackend());if(opts?.shadow!==void 0){this.shadow=opts.shadow;this.networkFullExpected=!!(opts.shadow.readsUnified&&opts.shadow.isAsyncBackend)}else if(this.enabled&&!unifiedBlockedByEncryption&&backendName==="mysql"){this.mysqlReady=UnifiedShadow.openAsync(this.sessionsDir,process.env,legacyLoad,fileStorageUnified(),fileStorageWalJournalSizeLimit(),fileStorageBackend(),fileStorageMysqlDsn()).then(sh=>{this.shadow=sh??void 0});this.mysqlReady.catch(()=>{});this.shadow=void 0;this.networkFullExpected=storageMode==="full"}else{if(this.enabled&&!unifiedBlockedByEncryption){this.syncSidecarOpen={legacyLoad};this.shadow=UnifiedShadow.maybeOpen(this.sessionsDir,process.env,legacyLoad,fileStorageUnified(),fileStorageWalJournalSizeLimit(),fileStorageBackend())??void 0}else{this.shadow=void 0}}this.store=new StateStore({dir:this.sessionsDir,version:PERSIST_VERSION,debounceMs:this.debounceMs,enabled:this.enabled,codec:this.codec,log:(level,msg)=>{epermAlert.observe(level,msg);baseLog(level,msg)},relPath:(id,payload)=>relPathFor(id,payload.meta?.protocol??payload.protocol,payload.meta?.upstreamOrigin??payload.upstreamOrigin),legacy:parsed=>isValidRecord(parsed)?{id:parsed.id,payload:parsed,version:parsed.version,savedAt:parsed.savedAt}:null,validate:envelope=>isValidRecord(envelope.payload),foreignFile:file=>path25.basename(file).endsWith(".content-store.json")})}loadContentStore(session){return this.readContentStoreRels(session.id,[contentStoreRelPathFor(session.id,session.meta.protocol,session.meta.upstreamOrigin),contentStoreRelPathFor(session.id)])}contentStoreById(id,meta){return this.readContentStoreRels(id,[contentStoreRelPathFor(id,meta?.protocol,meta?.upstreamOrigin),contentStoreRelPathFor(id)])}candidateContentStorePaths(id,rels){const source=this.sourceFiles.get(id);const sourceCcr=source?source.endsWith(".fb.json")?`${source.slice(0,-".fb.json".length)}.content-store.json`:`${source.slice(0,-".json".length)}.content-store.json`:null;return[...new Set([...sourceCcr?[sourceCcr]:[],...rels.map(rel2=>path25.join(this.sessionsDir,rel2)),...this.diskFiles.filter(file=>fileNameMatchesId(path25.basename(file),id)).map(file=>file.replace(/\.json$/,".content-store.json"))])]}readContentStoreRels(id,rels){if(!this.enabled)return null;for(const file of this.candidateContentStorePaths(id,rels)){let buf;try{buf=readFileSync9(file)}catch(err2){if(err2.code==="ENOENT")continue;if(!this.boundedReads){this.log("warn",`[persist] content store for ${id} unreadable, starting fresh: ${String(err2)}`);return null}throw new Error(`Content store for ${id} cannot be read; refusing to replace its originals`,{cause:err2})}try{const text2=this.readCodec.decode(buf);const parsed=JSON.parse(text2);if(parsed&&typeof parsed==="object"&&parsed.version===1&&parsed.byHash&&typeof parsed.byHash==="object"&&parsed.byRef&&typeof parsed.byRef==="object"){return parsed}throw new Error(`Content store for ${id} is malformed; refusing to replace its originals`)}catch(err2){if(!this.boundedReads){this.log("warn",`[persist] content store for ${id} unreadable, starting fresh: ${String(err2)}`);return null}throw new Error(`Content store for ${id} unreadable; refusing to replace its originals`,{cause:err2})}}return null}writeContentStoreSidecar(id,meta,store2){const rel2=contentStoreRelPathFor(id,meta?.protocol,meta?.upstreamOrigin);const abs=path25.join(this.sessionsDir,rel2);const tmp=path25.join(path25.dirname(abs),`.tmp-${path25.basename(abs,".json")}-${process.pid}-${this.tmpSeq++}`);try{mkdirSync7(path25.dirname(abs),{recursive:true});const text2=JSON.stringify(store2);durableWriteFile(tmp,this.codec?this.codec.encode(text2):text2);renameSync2(tmp,abs)}catch(err2){try{rmSync(tmp,{force:true})}catch{}this.log("warn",`[persist] content-store restore write failed for ${id}: ${err2 instanceof Error?err2.message:String(err2)}`)}}saveContentStore(session){if(!this.enabled||!session.contentStoreDirty)return true;const rel2=contentStoreRelPathFor(session.id,session.meta.protocol,session.meta.upstreamOrigin);const abs=path25.join(this.sessionsDir,rel2);const tmp=path25.join(path25.dirname(abs),`.tmp-${path25.basename(abs,".json")}-${process.pid}-${this.tmpSeq++}`);try{if(!session.contentStore||Object.keys(session.contentStore.byRef).length===0){rmSync(abs,{force:true});session.contentStoreDirty=false;return true}mkdirSync7(path25.dirname(abs),{recursive:true});const text2=JSON.stringify(session.contentStore);durableWriteFile(tmp,this.codec?this.codec.encode(text2):text2,384);renameSync2(tmp,abs);session.contentStoreDirty=false;return true}catch(err2){try{rmSync(tmp,{force:true})}catch{}session.contentStoreDirty=true;this.log("warn",`[persist] content-store write failed for ${session.id}: ${err2 instanceof Error?err2.message:String(err2)}`);return false}}async loadAll(){const out=new Map;if(!this.enabled)return out;let clamped=0;for(const[id,envelope]of await this.store.loadAll()){const session=this.buildForLoadAll(id,envelope.payload);if(hasNegativePersistedTokens(envelope.payload)){const warmProof=session.revisionEpoch;await this.store.writeNow(id,()=>this.buildRecordForSave(session));this.noteDurable(id,warmProof);clamped++;this.ownCommit.delete(id)}out.set(id,session)}if(this.shadow?.readsUnified||this.networkFullExpected){if(this.networkFullExpected)await this.ready();for(const id of await this.unionIds()){if(out.has(id))continue;const session=await this.loadAsync(id);if(session)out.set(id,session)}}if(clamped>0){log("info",`[persist] one-time migration (#408): clamped negative lastInputTokens/contextTokens in ${clamped} session(s) to 0`)}return out}async boot(limits){if(!this.enabled)return new Map;await this.sweepStaleTemps();if(limits)return this.bootBounded(limits);const loaded=await this.store.loadAll();await this.applyLegacyMigration(loaded);const out=new Map;for(const[id,envelope]of loaded){out.set(id,this.buildForLoadAll(id,envelope.payload))}if(this.shadow?.readsUnified||this.networkFullExpected){if(this.networkFullExpected)await this.ready();for(const id of await this.unionIds()){if(out.has(id))continue;const session=await this.loadAsync(id);if(session)out.set(id,session)}}return out}stateFileOnDisk(id){for(const root of[this.sessionsDir,`${this.sessionsDir}-cold`]){if(existsSync7(path25.join(root,relPathFor(id))))return true;if(existsSync7(path25.join(root,flatFileNameFor(id))))return true}return false}async unionIds(){const shadow=this.shadow;if(!shadow)return[];if(!shadow.isAsyncBackend)return shadow.listSessionIds();const rows=await shadow.sessionSummariesAsync();rows.sort((a,b2)=>b2.updatedAt-a.updatedAt);return rows.map(r=>r.sessionId)}async bootBounded(limits){if(!Number.isFinite(limits.maxSessions)||limits.maxSessions<0||!Number.isFinite(limits.maxBytes)||limits.maxBytes<0){throw new Error("Invalid session boot limits")}this.boundedReads=true;mkdirSync7(this.sessionsDir,{recursive:true});this.diskFiles=[];this.diskFilesSeeded=true;this.legacyAliases.clear();const warm=[];const canonical2=new Set;const filesByRoot=new Map;for(const root of[this.sessionsDir,`${this.sessionsDir}-cold`]){const files=existsSync7(root)?await walkJsonFiles(root):[];for(const file of files){if(path25.basename(file).endsWith(".content-store.json"))continue;this.diskFiles.push(file);filesByRoot.set(root,[...filesByRoot.get(root)??[],file])}}if(this.replicasAvailable()){this.seedIndexedAliases(canonical2);const hot=(filesByRoot.get(this.sessionsDir)??[]).map(file=>{try{const st2=statSync6(file);return{file,mtimeMs:st2.mtimeMs,size:st2.size}}catch{return null}}).filter(c=>c!==null).sort((a,b2)=>b2.mtimeMs-a.mtimeMs);const parsedFiles=new Set;const parsedCands=[];let windowBytes=0;for(const cand of hot){if(parsedCands.length>=limits.maxSessions&&windowBytes>=limits.maxBytes)break;if(cand.size>limits.maxBytes)continue;const parsed=await this.readRawFileWithBytes(cand.file);parsedFiles.add(cand.file);if(!parsed)continue;const rec=this.parseBootPayload(parsed.value);if(!rec||!fileNameMatchesId(path25.basename(cand.file),rec.payload.id,rec.meta.protocol,rec.meta.upstreamOrigin))continue;const savedAt=rec.payload.savedAt??0;if(rec.payload.id===rec.meta.label||rec.payload.id.startsWith("pfa-"))this.noteCanonical(rec.payload.id,canonical2);else if(rec.meta.label)this.upsertLegacyAlias(rec.meta.label,{file:cand.file,id:rec.payload.id,savedAt},canonical2);const bytes=parsed.bytes;if(bytes>limits.maxBytes)continue;windowBytes+=bytes;parsedCands.push({file:cand.file,id:rec.payload.id,meta:rec.meta,savedAt,bytes})}parsedCands.sort((a,b2)=>b2.savedAt-a.savedAt);while(parsedCands.length>limits.maxSessions||parsedCands.reduce((sum,item)=>sum+item.bytes,0)>limits.maxBytes)parsedCands.pop();warm.push(...parsedCands);this.remainderScan=this.scanRemainderInBackground(parsedFiles,canonical2);void this.remainderScan}else{for(const root of[this.sessionsDir,`${this.sessionsDir}-cold`]){for(const file of filesByRoot.get(root)??[]){const parsed=await this.readRawFileWithBytes(file);if(!parsed)continue;const rec=this.parseBootPayload(parsed.value);if(!rec||!fileNameMatchesId(path25.basename(file),rec.payload.id,rec.meta.protocol,rec.meta.upstreamOrigin))continue;const savedAt=rec.payload.savedAt??0;if(rec.payload.id===rec.meta.label||rec.payload.id.startsWith("pfa-"))canonical2.add(rec.payload.id);else if(rec.meta.label){const previous=this.legacyAliases.get(rec.meta.label);if(!previous||savedAt>=previous.savedAt)this.legacyAliases.set(rec.meta.label,{file,id:rec.payload.id,savedAt})}if(root!==this.sessionsDir)continue;const bytes=parsed.bytes;if(bytes>limits.maxBytes)continue;warm.push({file,id:rec.payload.id,meta:rec.meta,savedAt,bytes});warm.sort((a,b2)=>b2.savedAt-a.savedAt);while(warm.length>limits.maxSessions||warm.reduce((sum,item)=>sum+item.bytes,0)>limits.maxBytes)warm.pop()}}}for(const id of canonical2)this.legacyAliases.delete(id);const out=new Map;for(const item of warm){const alias=item.meta?.label&&this.legacyAliases.get(item.meta.label);if(alias&&alias.file!==item.file)continue;const id=alias?item.meta.label:item.id;const session=this.loadSync(id,item.meta);if(session)out.set(id,session)}if(this.shadow?.readsUnified||this.networkFullExpected){if(this.networkFullExpected)await this.ready();let warmBytes=0;for(const item of warm)warmBytes+=item.bytes;for(const id of await this.unionIds()){if(out.size>=limits.maxSessions)break;if(warmBytes>=limits.maxBytes)break;if(out.has(id))continue;if(this.stateFileOnDisk(id))continue;const session=await this.loadAsync(id);if(!session)continue;const bytes=this.estimateDecodedBytes(session);if(warmBytes+bytes>limits.maxBytes)continue;warmBytes+=bytes;out.set(id,session)}}this.log("info",`[persist] indexed ${this.diskFiles.length} state files; warmed ${out.size} sessions within ${limits.maxBytes} decoded bytes; older states load on demand`);return out}parseBootPayload(raw){const payload=raw&&typeof raw==="object"&&"payload"in raw?raw.payload:raw;if(!isValidRecord(payload))return null;const meta=payload.meta??{protocol:payload.protocol,upstreamOrigin:payload.upstreamOrigin,label:payload.label};return{payload,meta}}noteCanonical(id,canonical2){canonical2.add(id);this.legacyAliases.delete(id)}upsertLegacyAlias(label,entry,canonical2){if(canonical2.has(label))return false;const previous=this.legacyAliases.get(label);if(previous&&entry.savedAt<previous.savedAt)return false;this.legacyAliases.set(label,entry);return true}seedIndexedAliases(canonical2){const shadow=this.shadow;if(!shadow)return;let rows;try{rows=shadow.sessionSummaries()}catch{return}for(const r of rows){if(!r.label||r.label===r.sessionId||r.sessionId.startsWith("pfa-"))continue;const file=this.resolveIndexedFile(r.sessionId,r.protocol,r.origin);if(!file)continue;this.upsertLegacyAlias(r.label,{file,id:r.sessionId,savedAt:r.updatedAt},canonical2)}}resolveIndexedFile(id,protocol,origin){const candidates=[relPathFor(id,protocol,origin),relPathFor(id),flatFileNameFor(id)];for(const root of[this.sessionsDir,`${this.sessionsDir}-cold`]){for(const rel2 of candidates){const file=path25.join(root,rel2);try{if(statSync6(file).isFile())return file}catch{}}}return null}async scanRemainderInBackground(parsedFiles,canonical2){let scanned=0;let aliased=0;for(const file of this.diskFiles){if(parsedFiles.has(file))continue;scanned++;const parsed=await this.readRawFileWithBytes(file);if(parsed){const rec=this.parseBootPayload(parsed.value);if(rec&&fileNameMatchesId(path25.basename(file),rec.payload.id,rec.meta.protocol,rec.meta.upstreamOrigin)){const savedAt=rec.payload.savedAt??0;if(rec.payload.id===rec.meta.label||rec.payload.id.startsWith("pfa-"))this.noteCanonical(rec.payload.id,canonical2);else if(rec.meta.label)aliased+=this.upsertLegacyAlias(rec.meta.label,{file,id:rec.payload.id,savedAt},canonical2)?1:0}}await new Promise(resolve2=>setImmediate(resolve2))}if(scanned>0){this.log("info",`[persist] background index scan finished after boot: ${scanned} file(s) scanned, ${aliased} alias(es) recorded`)}}backgroundScanComplete(){return this.remainderScan??Promise.resolve()}readEnvelopeFile(file,id){let bytes;try{bytes=readFileSync9(file)}catch(err2){if(err2.code==="ENOENT")return null;throw err2}let raw;try{raw=JSON.parse(bytes.toString("utf8"))}catch{try{raw=JSON.parse(this.readCodec.decode(bytes))}catch(decodeError){this.quarantineCorruptState(file,id,decodeError);return null}}const payload=raw&&typeof raw==="object"&&"payload"in raw?raw.payload:raw;if(!isValidRecord(payload)){this.quarantineCorruptState(file,id,new Error(`record for ${id} failed validation`));return null}if(raw&&typeof raw==="object"&&"payload"in raw&&"id"in raw&&raw.id!==id)return null;if(payload.id!==id)return null;return{id,payload,version:payload.version,savedAt:payload.savedAt}}quarantineCorruptState(file,id,cause){const causeText=cause instanceof Error?cause.message:String(cause);const quarantinePath=`${file}.corrupt-${Date.now()}`;try{renameSync2(file,quarantinePath);this.log("warn",`[persist] quarantined undecodable session state ${path25.basename(file)} \u2192 ${path25.basename(quarantinePath)}; starting ${id} fresh (${causeText})`)}catch(renameErr){this.log("error",`[persist] failed to quarantine corrupt session state ${path25.basename(file)}; resuming ${id} empty this load (${causeText}; rename: ${renameErr instanceof Error?renameErr.message:String(renameErr)})`)}}buildForLoadAll(id,payload){if(this.shadow?.readsUnified){const dbAt=this.shadow.sessionUpdatedAt(id);if(dbAt===null||payload.savedAt>dbAt){this.shadow.importRecord(payload)}const view=this.shadow.viewFor(id);if(view)return buildSession(viewToRecord(view))}return buildSession(payload)}async sweepStaleTemps(){let files;try{files=await walkJsonFiles(this.sessionsDir)}catch{return}for(const file of files){if(isStaleTempName(path25.basename(file))){await rm2(file,{force:true}).catch(()=>{})}}}async migrateLegacyIds(){if(!this.enabled)return;if(existsSync7(this.markerPath()))return;const loaded=await this.store.loadAll();await this.applyLegacyMigration(loaded)}markerPath(){return path25.join(this.sessionsDir,MIGRATION_MARKER)}async applyLegacyMigration(loaded){if(existsSync7(this.markerPath()))return;const claimed=new Set;const byLabel=new Map;let unlabeled=0;for(const[id,envelope]of loaded){if(id.startsWith("pfa-"))continue;const session=buildSession(envelope.payload);const label=session.meta.label;if(!label){unlabeled++;continue}if(label===id){claimed.add(id);continue}const prev=byLabel.get(label);if(!prev||envelope.savedAt>=prev.savedAt){if(prev){await this.removeLegacyFile(prev.id,prev.session);loaded.delete(prev.id)}byLabel.set(label,{id,savedAt:envelope.savedAt,session})}else{await this.removeLegacyFile(id,session);loaded.delete(id)}}let rekeyed=0;for(const[label,{id,session}]of byLabel){if(claimed.has(label)){await this.removeLegacyFile(id,session);loaded.delete(id);continue}session.id=label;const rekeyProof=session.revisionEpoch;await this.store.writeNow(label,()=>this.buildRecordForSave(session));this.noteDurable(label,rekeyProof);this.ownCommit.delete(label);await this.removeLegacyFile(id,session);const envelope=loaded.get(id);if(envelope){loaded.set(label,{...envelope,id:label,payload:{...envelope.payload,id:label}})}loaded.delete(id);claimed.add(label);rekeyed++}try{mkdirSync7(this.sessionsDir,{recursive:true});writeFileSync6(this.markerPath(),String(Date.now()),"utf8")}catch{}if(rekeyed||unlabeled){log("info",`[persist] one-time migration (#286): rekeyed ${rekeyed} legacy session(s), left ${unlabeled} unlabeled legacy file(s) in place`)}}async removeLegacyFile(id,session){this.shadow?.remove(id);await this.removeSessionFiles(id,session.meta)}async findSessionFiles(id,meta){const rels=new Set;for(const rel2 of[relPathFor(id,meta?.protocol,meta?.upstreamOrigin),relPathFor(id),flatFileNameFor(id)]){if(existsSync7(path25.join(this.sessionsDir,rel2)))rels.add(rel2)}const expected=path25.basename(relPathFor(id));const matches=base=>fileNameMatchesId(base,id,meta?.protocol,meta?.upstreamOrigin)||base.endsWith(`_${expected}`);try{for(const entry of await readdir2(this.sessionsDir,{withFileTypes:true})){if(entry.isFile()){if(matches(entry.name))rels.add(entry.name);continue}if(!entry.isDirectory())continue;try{for(const f2 of await readdir2(path25.join(this.sessionsDir,entry.name),{withFileTypes:true})){if(f2.isFile()&&matches(f2.name))rels.add(path25.join(entry.name,f2.name))}}catch{}}}catch{}return[...rels]}async removeSessionFiles(id,meta){for(const rel2 of await this.findSessionFiles(id,meta)){await rm2(path25.join(this.sessionsDir,rel2),{force:true}).catch(()=>{});if(rel2.endsWith(".json")&&!rel2.endsWith(".fb.json")){await rm2(path25.join(this.sessionsDir,`${rel2.slice(0,-".json".length)}.content-store.json`),{force:true}).catch(()=>{})}}}async removeSession(id){let meta;const unifiedAvailable=this.replicasAvailable();if(unifiedAvailable){try{const row=this.liveShadow().sessionSummaries().find(r=>r.sessionId===id);if(row&&(row.protocol||row.origin))meta={protocol:row.protocol,upstreamOrigin:row.origin}}catch{}}const envelope=this.loadEnvelope(id,meta);if(envelope)meta={...meta,...envelope.payload.meta};const unifiedHadRows=unifiedAvailable&&this.liveShadow().sessionUpdatedAt(id)!==null;const files=await this.findSessionFiles(id,meta);if(unifiedAvailable)this.liveShadow().remove(id);await this.removeSessionFiles(id,meta);return{envelopeFound:files.length>0||envelope!==null,unifiedHadRows}}loadEnvelope(id,meta){if(meta?.protocol){const pooled=this.loadNamespacedPool(id,{protocol:meta.protocol,upstreamOrigin:meta.upstreamOrigin});if(pooled)return pooled}const livePaths=new Set([path25.join(this.sessionsDir,relPathFor(id,meta?.protocol,meta?.upstreamOrigin)),path25.join(this.sessionsDir,relPathFor(id)),path25.join(this.sessionsDir,flatFileNameFor(id))]);for(const file of livePaths){if(!existsSync7(file))continue;const envelope=this.readEnvelopeFile(file,id);if(envelope){this.sourceFiles.set(id,file);return envelope}}if(!this.diskFilesSeeded&&this.shadow){this.diskFiles=[...walkJsonFilesSync(this.sessionsDir),...existsSync7(`${this.sessionsDir}-cold`)?walkJsonFilesSync(`${this.sessionsDir}-cold`):[]].filter(f2=>!path25.basename(f2).endsWith(".content-store.json"));this.diskFilesSeeded=true}const expected=path25.basename(relPathFor(id,meta?.protocol,meta?.upstreamOrigin));const candidates=this.diskFiles.filter(file=>fileNameMatchesId(path25.basename(file),id,meta?.protocol,meta?.upstreamOrigin)||!meta?.protocol&&path25.basename(file).endsWith(`_${expected}`));for(const file of candidates){if(!existsSync7(file))continue;const envelope=this.readEnvelopeFile(file,id);if(envelope){this.sourceFiles.set(id,file);return envelope}}const alias=this.legacyAliases.get(id);if(alias){const envelope=this.readEnvelopeFile(alias.file,alias.id);if(envelope&&(!meta?.protocol||envelope.payload.meta?.protocol===meta.protocol)){this.sourceFiles.set(id,alias.file);return{...envelope,id,payload:{...envelope.payload,id}}}}return this.store.loadSync(id,relPathFor(id,meta?.protocol,meta?.upstreamOrigin))}loadNamespacedPool(id,meta){const proto=meta.protocol;const dir=path25.join(this.sessionsDir,proto);const logicalFor=file=>file.endsWith(".fb.json")?`${file.slice(0,-".fb.json".length)}.json`:file;const candidates=new Set([path25.join(dir,path25.basename(relPathFor(id,proto,meta.upstreamOrigin)))]);const suffix=`_${path25.basename(relPathFor(id))}`;for(const file of this.diskFiles){const base=path25.basename(file);if(base.endsWith(".content-store.json"))continue;if(path25.dirname(file)!==dir||!logicalFor(base).endsWith(suffix))continue;candidates.add(file)}const valid=new Map;for(const file of candidates){if(!existsSync7(file))continue;const env=this.readEnvelopeFile(file,id);if(!env)continue;const savedProtocol=env.payload.meta?.protocol??env.payload.protocol;if(savedProtocol&&savedProtocol!==proto)continue;const prior=valid.get(logicalFor(file));if(!prior||(env.savedAt??0)>(prior.env.savedAt??0))valid.set(logicalFor(file),{file,env})}if(valid.size===0)return null;const exact=path25.join(this.sessionsDir,relPathFor(id,proto,meta.upstreamOrigin));const winner=[...valid.values()].sort((a,b2)=>{const ra=a.env.payload.stats?.requests??a.env.payload.requests??0;const rb2=b2.env.payload.stats?.requests??b2.env.payload.requests??0;if(ra!==rb2)return rb2-ra;const na=a.env.payload.state?.nextBlockId??0;const nb=b2.env.payload.state?.nextBlockId??0;if(na!==nb)return nb-na;if(a.file===exact)return-1;if(b2.file===exact)return 1;return(b2.env.savedAt??0)-(a.env.savedAt??0)})[0];this.sourceFiles.set(id,winner.file);if(winner.file!==exact){this.log("info",`[persist] restored ${id} from another upstream route (${path25.basename(winner.file)}; ${winner.env.payload.stats?.requests??winner.env.payload.requests??0} requests) under protocol ${proto} (#3399)`)}return winner.env}adoptRequestedRoute(id,session,meta){if(!meta?.protocol||!meta.upstreamOrigin)return;const src=this.sourceFiles.get(id);if(!src||src===path25.join(this.sessionsDir,relPathFor(id,meta.protocol,meta.upstreamOrigin)))return;if(session.meta.upstreamOrigin===meta.upstreamOrigin)return;session.meta.upstreamOrigin=meta.upstreamOrigin;this.log("info",`[persist] adopted route ${hostLabel(meta.upstreamOrigin)} for ${id} restored from ${path25.basename(src)} (#3399)`);this.scheduleSave(session)}logColdLoad(id,source,session,savedAt){const refs=Object.keys(session.state.messageRefs.byRef??{}).length;const blocks=session.state.blocks.length;const active=session.state.blocks.filter(b2=>b2.active).length;const compressions=session.state.stats?.compressionCount??0;const ageMin=savedAt?Math.round(Math.max(0,Date.now()-savedAt)/6e4):void 0;this.log("info",`[persist] cold-loaded ${id} from ${source}: ${refs} ref(s), ${blocks} block(s) (${active} active), baseline ${session.stats.lastInputTokens} tok, compressions ${compressions}${ageMin!==void 0?`, savedAt ~${ageMin} min ago`:""}`);if(refs>0&&blocks===0){this.log("warn",`[persist] ${id} loaded with ${refs} mapped ref(s) but NO persisted blocks (compressions=${compressions}) \u2014 the folded history will replay raw and preflight must rebuild from scratch (#3573)`)}if(savedAt!==void 0&&ageMin!==void 0&&ageMin>STALE_COLD_LOAD_WARN_MIN&&compressions>0){this.log("warn",`[persist] ${id} cold-loaded view is ~${ageMin} min old (savedAt ${new Date(savedAt).toISOString()}) with ${compressions} prior compression(s) \u2014 the served fold state predates unseen turns; expect preflight pressure to catch up sharply when traffic resumes (#5408)`)}noteColdLoad(id,source,savedAt)}loadSync(id,meta){if(!this.enabled)return null;this.durableRevision.delete(id);if(this.shadow?.readsUnified){if(this.shadow.driftedSessions.has(id)){const driftedEnvelope=this.loadEnvelope(id,meta);if(driftedEnvelope){const envActive=countActiveBlocks(driftedEnvelope.payload);const idxActive=this.shadow.activeBlockCount(id);if(idxActive!==null&&idxActive>envActive){const unified2=this.loadUnified(id);if(unified2){this.log("warn",`[persist] serving ${id} from the UNIFIED store despite the drift latch: legacy envelope holds ${envActive} active block(s), the index holds ${idxActive} \u2014 taking the fuller fold coverage instead of the older generation (#4323/#394)`);return this.afterLoad(id,unified2)}}const drifted=buildSession(driftedEnvelope.payload);const unifiedView=this.loadUnified(id);if(unifiedView){const envRefs=Object.keys(drifted.state.messageRefs?.byRef??{}).length;const idxState=unifiedView.state;const idxRefs=Object.keys(idxState.messageRefs?.byRef??{}).length;if(idxRefs>envRefs){this.log("warn",`[persist] drift on ${id}: unified index carries ${idxRefs} mapped ref(s) vs envelope ${envRefs} \u2014 serving the richer index side (multi-writer generation, #4323)`);return this.afterLoad(id,unifiedView)}}if(hasNegativePersistedTokens(driftedEnvelope.payload)){this.scheduleSave(drifted);this.log("info",`[persist] clamped negative token stats on reload for ${id} (#408)`)}this.log("info",`[persist] serving ${id} from the legacy envelope: last sampled digest drifted (#3135 \u2463)`);this.logColdLoad(id,"legacy file (drift fallback)",drifted,driftedEnvelope.payload.savedAt);this.noteDurable(id,drifted.revisionEpoch);return drifted}}const unified=this.loadUnified(id);if(unified){const envelope3=this.loadEnvelope(id,meta);if(envelope3){const indexedRequests=Number(unified.stats.requests??0);const envRequests=Number(envelope3.payload.stats?.requests??0);const ahead=envRequests>indexedRequests||envRequests===indexedRequests&&Number(envelope3.payload.state?.nextBlockId??0)>unified.state.nextBlockId;if(ahead){const recovered=buildSession(envelope3.payload);this.log("info",`[persist] recovering ${id} from a strictly-ahead envelope on cold load (index requests ${indexedRequests}, envelope ${envRequests}${orphanContents(unified)?", orphan-frozen index":""})`);return this.afterLoad(id,this.shadow.importRecord(envelope3.payload)??toLegacyLike(recovered))}}return this.afterLoad(id,unified)}const envelope2=this.loadEnvelope(id,meta);if(!envelope2)return null;const imported=this.shadow.importRecord(envelope2.payload);if(imported){return this.afterLoad(id,imported)}const session2=buildSession(envelope2.payload);if(hasNegativePersistedTokens(envelope2.payload)){this.scheduleSave(session2);this.log("info",`[persist] clamped negative token stats on reload for ${id} (#408)`)}this.logColdLoad(id,"legacy file",session2,envelope2.payload.savedAt);this.adoptRequestedRoute(id,session2,meta);this.noteDurable(id,session2.revisionEpoch);return session2}const envelope=this.loadEnvelope(id,meta);if(!envelope)return null;const session=buildSession(envelope.payload);if(hasNegativePersistedTokens(envelope.payload)){this.scheduleSave(session);this.log("info",`[persist] clamped negative token stats on reload for ${id} (#408)`)}this.logColdLoad(id,"legacy file",session,envelope.payload.savedAt);this.adoptRequestedRoute(id,session,meta);this.noteDurable(id,session.revisionEpoch);return session}async loadAsync(id,meta){const sync=this.loadSync(id,meta);if(sync)return sync;const shadow=this.shadow;if(!shadow||!shadow.readsUnified||!shadow.isAsyncBackend)return null;await this.ready();const view=await shadow.viewForAsync(id);if(!view)return null;return this.afterLoad(id,view)}afterLoad(id,view){const record4=viewToRecord(view);const session=buildSession(record4);this.noteDurable(id,session.revisionEpoch);if(hasNegativePersistedTokens(record4)){this.scheduleSave(session);this.log("info",`[persist] clamped negative token stats on reload for ${id} (#408)`)}this.maybeRestampToLedger(session);this.logColdLoad(id,"unified store",session,record4.savedAt);return session}maybeRestampToLedger(session){const state7=session.state;if(state7.refLedgerAligned===true)return;if(!state7.messageRefs||Object.keys(state7.messageRefs.byRaw).length===0)return;try{const seqByRawId=this.unifiedSeqByRaw(session.id);if(seqByRawId===null||seqByRawId.size===0)return;const outcome=restampRefsToLedger(state7,seqByRawId);if(session.contentStore){const store2=contentStoreOf(session);const restampedStore=restampContentStore(store2,state7.messageRefs.byRaw);if(restampedStore!==store2)session.contentStore=restampedStore}if(outcome.superseded.size>0){session.restampSuperseded=outcome.superseded}else{delete session.restampSuperseded}const snap=state7.tokenSnapshot;if(snap&&outcome.superseded.size>0){const byRawNow=state7.messageRefs.byRaw;const moves=[];for(const[oldRef,rawId]of outcome.superseded){const count=snap[oldRef];const newRef=byRawNow[rawId];if(count===void 0||newRef===void 0||newRef===oldRef)continue;moves.push([oldRef,newRef,count])}if(moves.length>0){for(const[oldRef]of moves)delete snap[oldRef];for(const[,newRef,count]of moves)snap[newRef]=count;this.log("info",`[persist] remapped ${moves.length} token-snapshot entries onto ledger-aligned refs for ${session.id} (#4599)`)}}state7.refLedgerAligned=true;this.log("info",`[persist] ledger-aligned refs for ${session.id}: kept=${outcome.kept} restamped=${outcome.restamped} rehomed=${outcome.rehomed} blocked=${outcome.blocked} superseded=${outcome.superseded.size} (#4316 PR3/3)`);this.scheduleSave(session)}catch(err2){this.log("warn",`[persist] ref/ledger alignment skipped for ${session.id}: ${err2 instanceof Error?err2.message:String(err2)}`)}}loadUnified(id){return this.shadow?this.shadow.viewFor(id):null}loadResidentFields(id,meta,fields){if(this.residentFieldsForBuild?.id===id)return this.residentFieldsForBuild.fields;if(!this.enabled)return null;const indexed=this.shadow?.readsUnified?this.shadow.readResidentFieldsFor(id,fields):null;const envelope=this.loadEnvelope(id,meta);let useEnvelope=indexed===null;if(indexed&&envelope){if(this.shadow?.driftedSessions.has(id)){const envActive=countActiveBlocks(envelope.payload);const envRefs=Object.keys(envelope.payload.state?.messageRefs?.byRef??{}).length;useEnvelope=indexed.header.activeBlockCount<=envActive&&indexed.header.mappedRefCount<=envRefs}else{const requests=Number(envelope.payload.stats?.requests??0);useEnvelope=requests>indexed.header.requests||requests===indexed.header.requests&&Number(envelope.payload.state?.nextBlockId??0)>indexed.header.nextBlockId}}if(useEnvelope){if(!envelope)return null;return{...fields.metadata?{metadata:envelope.payload.metadata??{}}:{},...fields.blockContents?{blockContents:Object.fromEntries(restoreBlockContents(Object.entries(envelope.payload.blockContents??{})))}:{}}}if(!indexed)return null;return{...fields.metadata?{metadata:indexed.metadata}:{},...fields.blockContents?{blockContents:Object.fromEntries(restoreBlockContents(indexed.blockContents??[]))}:{}}}buildRecordForSave(session,storageMode=effectiveFileStorageMode()){const bothDropped=isDroppedMetadata(session.metadata)&&session.blockContents instanceof LazyBlockContents&&session.blockContents.isDropped;if(!bothDropped)return buildRecord(session,storageMode);const previous=this.residentFieldsForBuild;const fields=this.loadResidentFields(session.id,session.meta??{},{metadata:true,blockContents:true});this.residentFieldsForBuild={id:session.id,fields};try{return buildRecord(session,storageMode)}finally{this.residentFieldsForBuild=previous}}loadStateForSearch(id){if(!this.enabled)return null;if(this.shadow?.readsUnified){const view=this.loadUnified(id);if(view)return mergeState(view.state)}const envelope=this.loadEnvelope(id);if(!envelope)return null;return mergeState(envelope.payload.state)}unifiedCcrFor(id){if(!this.shadow?.readsUnified)return null;try{return this.shadow.getCcr(id)}catch{return null}}unifiedMessageRows(sessionId,msgIds){if(!this.shadow?.readsUnified||msgIds.length===0)return null;try{return this.shadow.messagesForIds(sessionId,msgIds,true)}catch{return null}}sidecarDownReason(){return this.shadow===void 0?"sidecar-missing":"sidecar-disabled"}replicasAvailable(){if(this.syncSidecarOpen!==null&&this.shadow===void 0){const now=Date.now();if(now>=this.sidecarReadCheckNextAttemptAt){this.sidecarReadCheckNextAttemptAt=now+(shadowReopenReadCheckMsOverride??SHADOW_REOPEN_READ_CHECK_MS);this.tryRecoverSidecar(true)}}return this.shadow!==void 0&&!this.shadow.stats.disabled}async waitForReplicas(timeoutMs=RECON_REPLICAS_WAIT_MS,pollMs=RECON_REPLICAS_POLL_MS){const deadline=Date.now()+timeoutMs;for(;;){if(this.replicasAvailable())return true;if(this.sidecarDownReason()!=="sidecar-missing")return false;if(Date.now()>=deadline)return false;await new Promise(r=>setTimeout(r,pollMs))}}unifiedReads(){return this.enabled&&this.shadow?.readsUnified===true}unifiedSeqByRaw(id){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.seqByRaw(id)}catch{return null}}unifiedLastLiveSeqAsync(id){if(!this.shadow)return Promise.resolve(null);try{return this.shadow.lastLiveSeqAsync(id)}catch{return Promise.resolve(null)}}unifiedCloneSessionRowsAsync(parentId,childId,throughSeq){if(!this.shadow)return Promise.resolve(false);try{return this.shadow.cloneSessionRowsAsync(parentId,childId,throughSeq)}catch{return Promise.resolve(false)}}unifiedGc(opts={}){if(!this.shadow||this.shadow.stats.disabled)return null;try{const days=opts.archiveAfterDays??resolveArchiveAfterDays(void 0,fileStorageArchiveAfterDays());return this.shadow.gc({archiveAfterDays:days,archiveDir:opts.archiveDir??join7(this.sessionsDir,"archive"),vacuum:opts.vacuum})}catch(err2){this.log("warn",`[persist] unified gc failed: ${String(err2)}`);return null}}unifiedBackup(dst){if(!this.shadow||this.shadow.stats.disabled)return{ok:false,error:"unavailable"};try{const target=dst??join7(this.sessionsDir,"backups",`index-${new Date().toISOString().replace(/[:.]/g,"-")}.db`);const bytes=this.shadow.backupInto(target);this.log("info",`[persist] unified backup written: ${target} (${bytes} bytes)`);return{ok:true,path:target,bytes}}catch(err2){const error=String(err2);this.log("warn",`[persist] unified backup failed: ${error}`);return{ok:false,error}}}unifiedGcPlan(archiveAfterDays,now){if(!this.shadow||this.shadow.stats.disabled)return null;try{const days=archiveAfterDays??resolveArchiveAfterDays(void 0,fileStorageArchiveAfterDays());return this.shadow.gcPlan(days,now)}catch{return null}}unifiedActiveWriter(){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.activeForeignWriter()}catch{return null}}unifiedRestoreArchived(sessionId,archiveDir){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.restoreArchived(sessionId,{archiveDir:archiveDir??join7(this.sessionsDir,"archive")})}catch(err2){this.log("warn",`[persist] unified restore failed: ${String(err2)}`);return null}}unifiedArchiveSession(sessionId,archiveDir){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.archiveSession(sessionId,{archiveDir:archiveDir??join7(this.sessionsDir,"archive")})}catch(err2){this.log("warn",`[persist] unified archive failed: ${String(err2)}`);return null}}unifiedAllMessageIds(sessionId){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.allMessageIds(sessionId)}catch{return null}}unifiedGetBlocks(sessionId){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.getBlocks(sessionId)}catch{return null}}unifiedListSessionIds(){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.listSessionIds()}catch{return null}}unifiedArchiveBlock(sessionId,blockId,archiveDir){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.archiveBlock(sessionId,blockId,{archiveDir:archiveDir??join7(this.sessionsDir,"archive")})}catch(err2){this.log("warn",`[persist] unified block archive failed: ${String(err2)}`);return null}}unifiedRestoreBlock(sessionId,blockId,archiveDir){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.restoreBlock(sessionId,blockId,{archiveDir:archiveDir??join7(this.sessionsDir,"archive")})}catch(err2){this.log("warn",`[persist] unified block restore failed: ${String(err2)}`);return null}}unifiedSessionStorageStats(sessionId){if(!this.replicasAvailable())return null;try{return this.liveShadow().sessionStorageStats(sessionId)}catch{return null}}unifiedVacuum(mode="full"){this.liveShadow().vacuum(mode)}unifiedRawMessages(sessionId,fromSeqExclusive){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.rawMessages(sessionId,fromSeqExclusive)}catch{return null}}unifiedTailSeqs(sessionId){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.tailSeqs(sessionId)}catch{return null}}unifiedTailViewRows(sessionId){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.tailViewRows(sessionId)}catch{return null}}unifiedMessageContentByRefs(sessionId,refNums){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.messageContentByRefNums(sessionId,refNums)}catch{return null}}unifiedMessageIdRows(sessionId){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.messageIdRows(sessionId)}catch{return null}}unifiedUncoveredRows(sessionId,intervals){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.uncoveredRows(sessionId,intervals)}catch{return null}}unifiedSessionSummaries(){if(!this.shadow?.readsUnified)return null;try{return this.shadow.sessionSummaries()}catch{return null}}webSummaryBaseline(){if(!this.shadow||this.shadow.stats.disabled)return null;if(this.shadow.isAsyncBackend)return null;return this.shadow.mode==="full"?"authoritative":"reconcile"}unifiedWebSummaries(){if(this.webSummaryBaseline()===null)return null;const shadow=this.shadow;if(!shadow)return null;try{return shadow.webSummaryRows()}catch{return null}}lookupConversation(namespace,conversationId){if(!this.replicasAvailable())return null;try{return this.shadow.lookupConversation(namespace,conversationId)}catch{return null}}setSessionExt(sessionId,key2,value){this.liveShadow().setSessionExt(sessionId,key2,value)}getSessionExt(sessionId,key2){return this.liveShadow().getSessionExt(sessionId,key2)}listSessionExt(sessionId){return this.liveShadow().listSessionExt(sessionId)}deleteSessionExt(sessionId,key2){return this.liveShadow().deleteSessionExt(sessionId,key2)}setKv(namespace,key2,value){this.liveShadow().setKv(namespace,key2,value)}getKv(namespace,key2){return this.liveShadow().getKv(namespace,key2)}listKv(namespace,keyPrefix){return this.liveShadow().listKv(namespace,keyPrefix)}deleteKv(namespace,key2){return this.liveShadow().deleteKv(namespace,key2)}liveShadow(){if(!this.replicasAvailable())throw new Error("[storage] replicas require the unified store (storage.unified=shadow|full or BILI_STORAGE_UNIFIED); this instance runs legacy-only");return this.shadow}maybeCutForkBase(session){void this.maybeCutForkBaseAsync(session)}async maybeCutForkBaseAsync(session){if(!this.shadow||this.shadow.stats.disabled)return;const retained=session.metadata.publicForkReceipt!==void 0||session.metadata.publicSnapshotRetained===true;if(!retained||!Array.isArray(session.pluginSnapshot)||session.pluginSnapshot.length===0)return;if(this.forkBaseCut.has(session.id))return;try{if((await this.shadow.listCheckpointsAsync(session.id)).some(cp2=>cp2.kind==="fork_base")){this.forkBaseCut.add(session.id);return}const record4=this.buildRecordForSave(session);const activeBlockIds2=session.state.blocks.filter(b2=>b2.active!==false).map(b2=>b2.blockId).sort();await this.shadow.insertCheckpointAsync({cpId:`cp-${randomUUID4()}`,sessionId:session.id,seqAt:session.pluginSnapshot.length,blockSetHash:sha256Hex2(JSON.stringify(activeBlockIds2)),kind:"fork_base",label:`fork-base ${session.id}`,pinned:true,createdAt:Date.now(),stateJson:JSON.stringify(record4)});this.forkBaseCut.add(session.id)}catch(err2){this.log("warn",`[storage] fork_base checkpoint cut failed for ${session.id}: ${err2 instanceof Error?err2.message:String(err2)}`)}}async createReplica(sessionId,opts={}){const shadow=this.liveShadow();const view=await shadow.viewForAsync(sessionId);if(!view)throw new Error(`[storage] session ${sessionId} is not in the unified index (unknown, or never persisted under this mode)`);const record4=viewToRecord(view);const ccr=this.contentStoreById(sessionId,view.meta);if(ccr)record4.forkContentStore=ccr;const cpId=`cp-${randomUUID4()}`;const activeBlockIds2=view.state.blocks.filter(b2=>b2.active!==false).map(b2=>b2.blockId).sort();await shadow.insertCheckpointAsync({cpId,sessionId,seqAt:await this.shadow.sessionTipSeqAsync(sessionId),blockSetHash:sha256Hex2(JSON.stringify(activeBlockIds2)),kind:opts.kind??"replica",label:opts.label??null,pinned:opts.pinned===true,createdAt:Date.now(),stateJson:JSON.stringify(record4)});const row=await shadow.getCheckpointAsync(cpId);if(!row)throw new Error(`[storage] checkpoint ${cpId} missing right after insert (index inconsistency)`);return row}async listReplicas(sessionId){await this.ready();return this.liveShadow().listCheckpointsAsync(sessionId)}async replicaByteLen(cpId){return(await this.liveShadow().checkpointStateAsync(cpId)).byteLen}async restoreReplica(cpId,opts={}){const shadow=this.liveShadow();const cp2=await shadow.getCheckpointAsync(cpId);if(!cp2)throw new Error(`[storage] checkpoint not found: ${cpId}`);const{stateJson}=await shadow.checkpointStateAsync(cpId);const record4=JSON.parse(stateJson);const newId=opts.sessionId??`restore-${randomUUID4().slice(0,8)}`;if(opts.sessionId!==void 0&&this.loadEnvelope(newId)!==null){throw new Error(`[storage] session ${newId} already exists \u2014 restore to a fresh id or delete the existing session first`)}record4.id=newId;record4.savedAt=Date.now();record4.meta={...record4.meta,restoredFrom:cp2.session_id,restoredCheckpoint:cp2.cp_id};await this.store.writeNow(newId,()=>record4);shadow.record(record4);this.ownCommit.set(newId,{requests:record4.stats?.requests??record4.requests??0,nextBlockId:record4.state?.nextBlockId??0,builtAtMs:Date.now()});if(record4.forkContentStore){this.writeContentStoreSidecar(newId,record4.meta,record4.forkContentStore)}return{sessionId:newId,restoredFrom:cp2.session_id,seqAt:cp2.seq_at}}async deleteReplica(cpId){return this.liveShadow().deleteCheckpointAsync(cpId)}get dir(){return this.sessionsDir}async loadSessionFromFile(file,expectId){const parsed=await this.readRawFile(file);if(!parsed||typeof parsed!=="object")return null;const p2=parsed;const rec=p2.payload&&typeof p2.payload==="object"?p2.payload:parsed;if(!isValidRecord(rec))return null;if(expectId!==void 0&&rec.id!==expectId)return null;return buildSession(rec)}async readRawFileWithBytes(file){try{const raw=await readFile4(file);try{return{value:JSON.parse(raw.toString("utf8")),bytes:raw.byteLength}}catch{const text2=this.readCodec.decode(raw);return{value:JSON.parse(text2),bytes:Buffer.byteLength(text2,"utf8")}}}catch{return null}}async readRawFile(file){const parsed=await this.readRawFileWithBytes(file);return parsed?.value??null}async decodedBytesOf(file){const parsed=await this.readRawFileWithBytes(file);return parsed===null?null:parsed.bytes}staleDiskPayload(incoming){if(this.ownershipFastPath(incoming))return null;this.staleGuardFullReads++;const envelope=this.loadEnvelope(incoming.id,incoming.meta);if(!envelope)return null;const disk=envelope.payload;const diskRequests=disk.stats?.requests??disk.requests??0;const incRequests=incoming.stats?.requests??incoming.requests??0;if(incRequests<diskRequests)return disk;if(incRequests===diskRequests){const diskBlocks=disk.state?.nextBlockId??0;const incBlocks=incoming.state?.nextBlockId??0;if(incBlocks<diskBlocks)return disk}return null}ownershipFastPath(incoming){const own=this.ownCommit.get(incoming.id);if(!own)return false;const shadow=this.shadow;if(!shadow||shadow.stats.disabled)return false;const incRequests=incoming.stats?.requests??incoming.requests??0;const incBlocks=incoming.state?.nextBlockId??0;if(incRequests<own.requests||incBlocks<own.nextBlockId)return false;let row=null;try{row=shadow.sessionCounters(incoming.id)}catch{return false}if(!row||row.requests!==own.requests||row.nextBlockId!==own.nextBlockId)return false;const stat5=this.statEnvelope(incoming.id,incoming.meta);if(!stat5)return false;if(!own.written)return false;if(stat5.size!==own.written.size)return false;if(stat5.mtimeMs>own.written.mtimeMs+OWN_WRITE_STAMP_EPSILON_MS)return false;return true}statEnvelope(id,meta){const candidates=[];const known=this.sourceFiles.get(id);if(known)candidates.push(known);candidates.push(path25.join(this.sessionsDir,relPathFor(id,meta?.protocol,meta?.upstreamOrigin)),path25.join(this.sessionsDir,relPathFor(id)),path25.join(this.sessionsDir,flatFileNameFor(id)));for(const file of candidates){try{const st2=statSync6(file);return{size:st2.size,mtimeMs:st2.mtimeMs}}catch{}}return null}estimateDecodedBytes(session){try{return JSON.stringify(this.guardedBuild(session)()).length}catch{return Number.MAX_SAFE_INTEGER}}guardedBuild(session){const stamp2=this.liveStorageStamp;return()=>{const record4=this.buildRecordForSave(session,stamp2);const disk=this.staleDiskPayload(record4);if(disk===null){const payload=session.decompositionLog;if(payload!==void 0)session.decompositionLog=void 0;const tail=session.lastMessagesFolded!==true?session.lastMessages:void 0;this.shadow?.record(payload!==void 0?{...record4,decompositionLog:payload}:record4,tail&&tail.length>0?{lastMessages:tail,lastMessagesFolded:session.lastMessagesFolded}:void 0,session.contentStore??void 0);this.noteOwnCommit(session.id,record4);return record4}const now=Date.now();const last=this.staleWarnAt.get(record4.id)??0;if(now-last>=STALE_WARN_THROTTLE_MS){this.staleWarnAt.set(record4.id,now);this.log("warn",`[persist] rejected stale snapshot for session ${record4.id}: in-memory copy is older than the on-disk one (another bili instance holds newer state) \u2014 keeping disk state and converging in-memory state to it, so subsequent requests serve the fuller fold coverage instead of the stale view (#405/#2401)`)}this.convergeToDisk(session,disk);this.shadow?.record(disk);this.noteOwnCommit(session.id,disk);return disk}}noteOwnCommit(id,committed){const prev=this.ownCommit.get(id);this.ownCommit.set(id,{requests:committed.stats?.requests??committed.requests??0,nextBlockId:committed.state?.nextBlockId??0,builtAtMs:Date.now(),written:prev?.written,meta:committed.meta?{protocol:committed.meta.protocol,upstreamOrigin:committed.meta.upstreamOrigin}:prev?.meta});try{this.sessionCommitListener?.(id)}catch{}}stampOwnWrite(id){const token=this.ownCommit.get(id);if(!token)return;const stat5=this.statEnvelope(id,token.meta);if(!stat5)return;token.written=stat5}convergeToDisk(session,disk){const fresh=buildSession(disk);const droppedRetrievals=session.pendingRetrievals.length;session.state=fresh.state;session.blockContents=fresh.blockContents;session.stats=fresh.stats;session.lastMessages=fresh.lastMessages??session.lastMessages;session.lastMessagesFolded=fresh.lastMessages!==void 0?fresh.lastMessagesFolded:session.lastMessagesFolded;session.pluginSnapshot=fresh.pluginSnapshot;session.decompositionLog=fresh.decompositionLog??session.decompositionLog;session.lastSeen=fresh.lastSeen;if(!session.meta.protocol&&fresh.meta.protocol)session.meta.protocol=fresh.meta.protocol;if(!session.meta.upstreamOrigin&&fresh.meta.upstreamOrigin)session.meta.upstreamOrigin=fresh.meta.upstreamOrigin;if(!session.meta.label&&fresh.meta.label)session.meta.label=fresh.meta.label;session.pendingRetrievals.length=0;delete session.metadata.ccrUndelivered;delete session.metadata.ccrDropNotes;if(droppedRetrievals>0){this.log("warn",`[persist] ${session.id}: dropped ${droppedRetrievals} queued retrieval(s) during state convergence to the newer disk record (#2401)`)}markDirty(session)}noteFrozenSkip(sessionId,route){const now=Date.now();const last=this.frozenNoticeAt.get(sessionId)??0;if(now-last<FROZEN_SKIP_NOTICE_COOLDOWN_MS)return;this.frozenNoticeAt.set(sessionId,now);const info=this.shadow?.envelopeFrozenInfo(sessionId);const since=info?new Date(info.sinceMs).toISOString():"?";log("error",`[persist] ${sessionId}: skipping ${route} envelope save \u2014 JSON envelope writes FROZEN since ${since} (digest-drift escalation #4323); the unified store keeps receiving the save and compression continues from the in-memory view, but the two copies are NOT converging \u2014 see the [storage] DIGEST DRIFT lines for the divergence diagnosis (#5408)`)}scheduleSave(session){if(!this.saveContentStore(session))return;if(this.writerOffActive()||this.envelopeFrozen(session.id)){if(this.envelopeFrozen(session.id))this.noteFrozenSkip(session.id,"scheduled");if(this.writerOffPending.has(session.id))return;const run=()=>{this.writerOffPending.delete(session.id);const proofRevision=session.revisionEpoch;let settledOk=false;try{this.guardedBuild(session)();this.maybeCutForkBase(session);this.noteDurable(session.id,proofRevision);this.lastSaveLanded.set(session.id,true);this.runIdleSpillIfIdle(session.id);settledOk=true}catch(err2){this.log("error",`[persist] writerOff coalesced build failed for ${session.id}: ${String(err2)}`)}finally{this.drainFlushWaiters(session.id,settledOk)}};this.writerOffPending.set(session.id,run);queueMicrotask(()=>{if(this.writerOffPending.get(session.id)===run)run()});return}if(!this.enabled)return;this.tryRecoverSidecar();const id=session.id;this.saveBuilders.set(id,this.guardedBuild(session));const existing=this.saveTimers.get(id);if(existing)return;const timer3=setTimeout(()=>{this.saveTimers.delete(id);const build2=this.saveBuilders.get(id);this.saveBuilders.delete(id);if(!build2)return;const proofRevision=peekSession(id)?.revisionEpoch;this.saveWritesInFlight.add(id);void this.store.writeNow(id,build2).then(()=>{this.stampOwnWrite(id);this.noteDurable(id,proofRevision);this.lastSaveLanded.set(id,true);this.runIdleSpillIfIdle(id)}).catch(()=>{this.lastSaveLanded.set(id,false)}).finally(()=>{this.saveWritesInFlight.delete(id);this.drainFlushWaiters(id,this.lastSaveLanded.get(id)===true)})},this.debounceMs);if(!this.flushWaiters.has(id))timer3.unref?.();this.saveTimers.set(id,timer3)}async afterNextFlush(sessionId){if(!this.saveTimers.has(sessionId)&&!this.writerOffPending.has(sessionId)&&!this.saveWritesInFlight.has(sessionId)){return true}return await new Promise(resolve2=>{const ws2=this.flushWaiters.get(sessionId)??[];ws2.push(ok=>{resolve2(ok)});this.flushWaiters.set(sessionId,ws2);this.saveTimers.get(sessionId)?.ref?.()})}drainFlushWaiters(sessionId,ok){const ws2=this.flushWaiters.get(sessionId);if(!ws2)return;this.flushWaiters.delete(sessionId);for(const w2 of ws2){try{w2(ok)}catch{}}}async spillBetweenTurns(session){if(session.inFlight>0)return;let landed;try{landed=await this.afterNextFlush(session.id)}catch{return}if(!landed)return;if(session.inFlight>0)return;const cap=sessionResidentHardMaxBytes();if(cap>0&&sessionWeight(session)>cap){const now=Date.now();if(now-(this.capWarnAt.get(session.id)??0)>=6e4){this.capWarnAt.set(session.id,now);this.log("warn",`[persist] ${session.id}: resident estimate ${sessionWeight(session)} B exceeds the per-session hard cap ${cap} B (#4788 D1-A) \u2014 discharging droppable fields back to disk now, including pool-exempt sessions; remainder (state/transient) is non-droppable`)}}this.runIdleSpill(session)}runIdleSpillIfIdle(id){const s3=peekSession(id);if(!s3||s3.inFlight>0)return;this.runIdleSpill(s3)}runIdleSpill(session){if(session.inFlight>0)return;if(this.durableRevision.get(session.id)!==(session.revisionEpoch??0))return;this.foldResidentTail(session);this.dropResidentBlockContents(session);this.dropResidentMetadata(session);this.dropResidentContentStore(session)}noteDurable(id,revisionEpoch){this.durableRevision.set(id,revisionEpoch??0)}async writeNow(session){if(!this.saveContentStore(session))throw new Error(`Originals were not saved for ${session.id}`);if(this.writerOffActive()||this.envelopeFrozen(session.id)){if(this.envelopeFrozen(session.id))this.noteFrozenSkip(session.id,"writeNow");this.writerOffPending.delete(session.id);const proofRevision2=session.revisionEpoch;this.guardedBuild(session)();this.maybeCutForkBase(session);this.noteDurable(session.id,proofRevision2);this.lastSaveLanded.set(session.id,true);this.foldResidentTail(session);this.dropResidentBlockContents(session);this.dropResidentMetadata(session);this.dropResidentContentStore(session);return}const proofRevision=session.revisionEpoch;this.saveWritesInFlight.add(session.id);try{await this.store.writeNow(session.id,this.guardedBuild(session))}catch(err2){this.saveWritesInFlight.delete(session.id);throw err2}this.stampOwnWrite(session.id);this.maybeCutForkBase(session);this.noteDurable(session.id,proofRevision);this.lastSaveLanded.set(session.id,true);this.foldResidentTail(session);this.dropResidentBlockContents(session);this.dropResidentMetadata(session);this.dropResidentContentStore(session);this.drainFlushWaiters(session.id,true)}lazySource(id){const sh=this.shadow;if(!sh||!sh.readsUnified||sh.stats.disabled)return"file";if(sh.driftedSessions.has(id))return"file";return"index"}narrowMetadata(id,source,meta){const fromIndex=()=>this.shadow?.getSessionMetadata(id)??null;const fromFile=()=>{const env=this.loadEnvelope(id,meta);return env?env.payload.metadata??{}:null};if(source==="index"){const idx=fromIndex();return idx!==null?idx:fromFile()}const file=fromFile();return file!==null?file:fromIndex()}narrowBlockContents(id,source,meta){const fromIndex=()=>{const rows=this.shadow?.getBlockContents(id);return rows?Object.fromEntries(rows):null};const fromFile=()=>{const env=this.loadEnvelope(id,meta);return env?env.payload.blockContents??{}:null};if(source==="index"){const idx=fromIndex();return idx!==null?idx:fromFile()}const file=fromFile();return file!==null?file:fromIndex()}foldResidentTail(session){if(session.inFlight>0)return;const raw=session.lastMessages;if(!raw||raw.length===0)return;session.lastMessages=boundedFoldedSnapshot(session);session.lastMessagesFolded=true}dropResidentMetadata(session){if(session.inFlight>0||!this.enabled)return;if(isDroppedMetadata(session.metadata))return;if(Object.keys(session.metadata).length===0)return;const meta=session.meta??void 0;const source=this.lazySource(session.id);session.metadata=lazyMetadata(session.id,{protocol:meta?.protocol,upstreamOrigin:meta?.upstreamOrigin},(id,m2)=>{return this.loadResidentFields(id,m2,{metadata:true})?.metadata??null})}dropResidentBlockContents(session){if(session.inFlight>0||!this.enabled)return;const existing=session.blockContents;if(existing instanceof LazyBlockContents){existing.drop();return}if(existing.size===0)return;const source=this.lazySource(session.id);const lazy=new LazyBlockContents(session.id,{protocol:session.meta.protocol,upstreamOrigin:session.meta.upstreamOrigin},(id,meta)=>{return this.loadResidentFields(id,meta,{blockContents:true})?.blockContents??null});lazy.drop();session.blockContents=lazy}dropResidentContentStore(session){if(session.inFlight>0||!this.enabled)return;if(isDroppedContentStore(session.contentStore))return;if(session.contentStoreDirty)return;if(contentStorePinned())return;const store2=session.contentStore;if(!store2||Object.keys(store2.byRef).length===0)return;const meta=session.meta??void 0;if(!this.contentStoreLanded(session.id,meta)){return}session.contentStore=lazyContentStore(session.id,id=>this.unifiedCcrFor(id)??this.contentStoreById(id,{protocol:meta?.protocol,upstreamOrigin:meta?.upstreamOrigin}))}contentStoreLanded(id,meta){if(this.unifiedCcrFor(id)!==null)return true;for(const p2 of this.candidateContentStorePaths(id,[contentStoreRelPathFor(id,meta?.protocol,meta?.upstreamOrigin),contentStoreRelPathFor(id)])){try{if(existsSync7(p2))return true}catch{}}return false}tryRecoverSidecar(force=false){const args=this.syncSidecarOpen;if(!args||this.shadow!==void 0)return;if(hadIntegrityQuickCheckFailure())return;const now=Date.now();if(!force&&now<this.sidecarReopenNextAttemptAt)return;const cooldown=shadowReopenCooldownMsOverride??SHADOW_REOPEN_COOLDOWN_MS;this.sidecarReopenNextAttemptAt=now+cooldown;try{this.shadow=UnifiedShadow.maybeOpen(this.sessionsDir,process.env,args.legacyLoad,fileStorageUnified(),fileStorageWalJournalSizeLimit(),fileStorageBackend())??void 0}catch(err2){this.log("error",`[storage] sidecar reopen attempt failed (${String(err2)}) \u2014 still envelope-served; will retry next window (#5188)`);return}if(this.shadow!==void 0){this.log("info","[storage] unified sidecar recovered after a transient open failure \u2014 unified surfaces resume without a restart (#5188)");return}}flushSync(session){if(!this.saveContentStore(session))return false;this.tryRecoverSidecar();if(this.writerOffActive()||this.envelopeFrozen(session.id)){if(this.envelopeFrozen(session.id))this.noteFrozenSkip(session.id,"flushSync");this.writerOffPending.delete(session.id);const proofRevision2=session.revisionEpoch;try{this.guardedBuild(session)()}catch(err2){this.log("error",`[persist] writerOff flushSync build failed for ${session.id}: ${String(err2)}`);return false}this.maybeCutForkBase(session);this.noteDurable(session.id,proofRevision2);this.lastSaveLanded.set(session.id,true);this.foldResidentTail(session);this.dropResidentBlockContents(session);this.dropResidentMetadata(session);this.dropResidentContentStore(session);return true}const armed3=this.saveTimers.get(session.id);if(armed3){clearTimeout(armed3);this.saveTimers.delete(session.id);this.saveBuilders.delete(session.id)}const proofRevision=session.revisionEpoch;const ok=this.store.flushSync(session.id,this.guardedBuild(session));if(ok){this.stampOwnWrite(session.id);this.noteDurable(session.id,proofRevision);this.maybeCutForkBase(session);this.foldResidentTail(session);this.dropResidentBlockContents(session);this.dropResidentMetadata(session);this.dropResidentContentStore(session)}return ok}async persistForkSession(parentId,session){await this.ready();const record4=buildRecord(session,this.liveStorageStamp);const cloned=await this.shadow?.createForkAsync(parentId,toLegacyLike(session))??false;if(!cloned){if(!this.flushSync(session))throw new Error("fork persistence failed");return}await this.maybeCutForkBaseAsync(session);if(!this.saveContentStore(session))throw new Error("fork content persistence failed; retry the same request");this.noteOwnCommit(session.id,record4);if(!this.writerOffActive()){if(!this.store.flushSync(session.id,()=>record4))throw new Error("fork envelope persistence failed; retry the same request");this.stampOwnWrite(session.id)}this.foldResidentTail(session);this.dropResidentBlockContents(session);this.dropResidentMetadata(session);this.dropResidentContentStore(session)}async recoverCompletedFork(id){await this.ready();if(this.loadEnvelope(id)!==null)return;const view=await this.shadow?.viewForAsync(id);if(!view)return;const record4=viewToRecord(view);const receipt=record4.metadata?.publicForkReceipt;if(typeof receipt?.requestHash!=="string"||receipt.response?.ok!==true||receipt.response.sessionId!==id||receipt.response.childConversationId!==id)return;const session=buildSession(record4);if(!this.saveContentStore(session))throw new Error("fork content recovery failed");this.noteOwnCommit(id,record4);if(!this.writerOffActive()){if(!this.store.flushSync(id,()=>record4))throw new Error("fork envelope recovery failed");this.stampOwnWrite(id)}await this.maybeCutForkBaseAsync(session)}async flushAll(sessions2=[]){this.drainWriterOffPending();for(const session of sessions2)this.saveContentStore(session);await this.flushScheduledSaves();await this.store.flushAll();this.shadow?.close()}async flushScheduledSaves(){const ids=[...this.saveTimers.keys()];for(const timer3 of this.saveTimers.values())clearTimeout(timer3);this.saveTimers.clear();const builders=new Map;for(const id of ids){const build2=this.saveBuilders.get(id);if(build2)builders.set(id,build2);this.saveBuilders.delete(id)}await Promise.all([...builders.entries()].map(([id,build2])=>this.store.writeNow(id,build2).then(()=>{this.stampOwnWrite(id)}).catch(e=>{this.log("error",`[persist] shutdown flush failed for ${id}: ${String(e)}`)})))}get liveStorageStamp(){if(!this.enabled)return"legacy";if(!this.shadow||this.shadow.stats.disabled)return"legacy";return this.storageMode}closeQuietly(){this.cancelAll();this.shadow?.close()}async closeQuietlyAsync(){await this.ready();this.cancelAll();await this.shadow?.closeAsync()}hasPending(id){return this.saveTimers.has(id)||this.writerOffPending.has(id)}writerOffActive(){return this.jsonWriterOff&&this.shadow!==void 0}envelopeFrozen(sessionId){return this.shadow?.envelopeFrozen(sessionId)??false}cancelAll(){for(const timer3 of this.saveTimers.values())clearTimeout(timer3);this.saveTimers.clear();this.saveBuilders.clear();this.store.cancelAll();this.writerOffPending.clear()}drainWriterOffPending(){if(this.writerOffPending.size===0)return;const runs=[...this.writerOffPending.values()];this.writerOffPending.clear();for(const run of runs)run()}};function effectiveFileStorageMode(){const live=peekStoreForStamp();if(live)return live.liveStorageStamp;const mode=resolveStorageModeForProcess();if(mode==="legacy")return"legacy";const keyEnv=process.env.BILI_ENCRYPTION_KEY;return keyEnv!==void 0&&keyEnv!==""?"legacy":mode}function buildRecord(session,storageMode=effectiveFileStorageMode()){const snapshot=boundedFoldedSnapshot(session);const observation=currentContextObservation(session);if(session.pluginSnapshot&&session.contentStore){const previous=session.metadata.publicSnapshotStoredRefs;session.metadata.publicSnapshotStoredRefs=[...new Set([...Array.isArray(previous)?previous:[],...session.pluginSnapshot.flatMap(m2=>{const ref=session.state.messageRefs.byRaw[m2.id];return ref&&session.contentStore.byRef[ref]?[ref]:[]})])]}return{version:PERSIST_VERSION,savedAt:Date.now(),id:session.id,meta:{...session.meta},stats:{...session.stats,...observation?{contextTokens:observation.tokens,contextTokensSource:observation.source}:{}},messages:snapshot,messagesFolded:snapshot?true:void 0,pluginSnapshot:session.metadata.publicForkReceipt!==void 0||session.metadata.publicSnapshotRetained===true?session.pluginSnapshot:void 0,forkContentStore:session.metadata.publicForkReceipt?session.contentStore:void 0,metadata:{...session.metadata,biliVersion:VERSION,storageMode},state:session.state,blockContents:Object.fromEntries(session.blockContents),createdAt:session.createdAt}}function isBlockView(v2){return!!v2&&typeof v2==="object"&&typeof v2.text==="string"&&typeof v2.count==="number"}function restoreCalibratedEstimate(v2){return typeof v2==="number"&&Number.isFinite(v2)&&v2>=CALIBRATION_CLAMP_MIN&&v2<=CALIBRATION_CLAMP_MAX?v2:void 0}function restoreCalibrationRing(v2){if(!v2||typeof v2!=="object")return void 0;const ring=v2;if(typeof ring.origin!=="string"||ring.origin.length===0)return void 0;if(!Array.isArray(ring.values))return void 0;const values=ring.values.filter(x=>typeof x==="number"&&Number.isFinite(x)&&x>=CALIBRATION_SAMPLE_MIN&&x<=CALIBRATION_SAMPLE_MAX);const recent=values.slice(-CALIBRATION_SAMPLE_WINDOW);return recent.length>0?{origin:ring.origin,values:recent}:void 0}function restoreBlockContents(entries2){const blockContents=new Map;for(const[bid,content]of entries2){if(!content||typeof content!=="object")continue;const full=content.full;if(!isBlockView(full))continue;const one=content.one;const oneView=isBlockView(one)?one:null;blockContents.set(bid,{one:oneView&&!(oneView.text===full.text&&oneView.count===full.count)?oneView:null,full})}return blockContents}function recordToLegacyView(record4){const s3=buildSession(record4);return toLegacyLike(s3)}function buildSession(parsed){const blockContents=restoreBlockContents(Object.entries(parsed.blockContents??{}));const meta=parsed.meta??{};const stats=parsed.stats??{};return{id:parsed.id,meta:{protocol:meta.protocol??parsed.protocol,upstreamOrigin:meta.upstreamOrigin??parsed.upstreamOrigin,label:meta.label??parsed.label,title:meta.title,activePack:typeof meta.activePack==="string"?meta.activePack:void 0,hostTitle:typeof meta.hostTitle==="string"?meta.hostTitle:void 0},stats:{requests:stats.requests??parsed.requests??0,tokensSaved:stats.tokensSaved??parsed.tokensSaved??0,inputTokens:stats.inputTokens??parsed.inputTokens??0,cachedTokens:stats.cachedTokens??parsed.cachedTokens??0,outputTokens:stats.outputTokens??parsed.outputTokens??0,cacheSamples:stats.cacheSamples??parsed.cacheSamples??0,lastInputTokens:Math.max(0,stats.lastInputTokens??parsed.lastInputTokens??0),lastInputTokensSource:stats.lastInputTokensSource==="usage"||stats.lastInputTokensSource==="estimate"||stats.lastInputTokensSource==="overflow-arm"?stats.lastInputTokensSource:void 0,overflowArmTokens:typeof stats.overflowArmTokens==="number"&&Number.isFinite(stats.overflowArmTokens)&&stats.overflowArmTokens>0?stats.overflowArmTokens:void 0,overflowArmCompletionReserve:typeof stats.overflowArmCompletionReserve==="number"&&Number.isFinite(stats.overflowArmCompletionReserve)&&stats.overflowArmCompletionReserve>0?stats.overflowArmCompletionReserve:void 0,overflowArmMismatchWarned:stats.overflowArmMismatchWarned===true?true:void 0,provenCompletionWall:typeof stats.provenCompletionWall==="number"&&Number.isFinite(stats.provenCompletionWall)&&stats.provenCompletionWall>0?stats.provenCompletionWall:void 0,provenCompletionWallOrigin:typeof stats.provenCompletionWallOrigin==="string"&&stats.provenCompletionWallOrigin.length>0?stats.provenCompletionWallOrigin:void 0,provenCompletionWallModel:typeof stats.provenCompletionWallModel==="string"&&stats.provenCompletionWallModel.length>0?stats.provenCompletionWallModel:void 0,compressCreditTokens:0,contextTokens:Math.max(0,stats.contextTokens??parsed.contextTokens??0),contextTokensSource:stats.contextTokensSource==="usage"||stats.contextTokensSource==="estimate"?stats.contextTokensSource:void 0,localInputEstimate:typeof stats.localInputEstimate==="number"&&Number.isFinite(stats.localInputEstimate)&&stats.localInputEstimate>0?stats.localInputEstimate:void 0,lastUsageGradeTokens:typeof stats.lastUsageGradeTokens==="number"&&Number.isFinite(stats.lastUsageGradeTokens)&&stats.lastUsageGradeTokens>=0?stats.lastUsageGradeTokens:void 0,lastInputTokensOrigin:typeof stats.lastInputTokensOrigin==="string"&&stats.lastInputTokensOrigin.trim().length>0?stats.lastInputTokensOrigin:void 0,calibratedEstimate:restoreCalibratedEstimate(stats.calibratedEstimate),calibratedEstimateOrigin:typeof stats.calibratedEstimateOrigin==="string"&&stats.calibratedEstimateOrigin.trim().length>0?stats.calibratedEstimateOrigin:void 0,calibrationRing:restoreCalibrationRing(stats.calibrationRing),retrieveCalls:stats.retrieveCalls??0,retrieveHits:stats.retrieveHits??0,retrieveMisses:stats.retrieveMisses??0,retrieveDropped:stats.retrieveDropped??0,retrieveDelivered:stats.retrieveDelivered??0,storedBytes:stats.storedBytes??0,storeBytesSaved:stats.storeBytesSaved??0,rangeRestores:stats.rangeRestores??0,wholeBlockRestores:stats.wholeBlockRestores??0,wholeBlockRestoresPreciseAvailable:stats.wholeBlockRestoresPreciseAvailable??0,costUsd:validCostUsd(stats.costUsd)},metadata:parsed.metadata??{},state:mergeState(parsed.state),createdAt:parsed.createdAt??Date.now(),lastSeen:parsed.savedAt??Date.now(),restored:true,ccrReconcilePending:true,blockContents,lastMessages:Array.isArray(parsed.messages)?parsed.messages:void 0,lastMessagesFolded:parsed.messagesFolded===true,pluginSnapshot:Array.isArray(parsed.pluginSnapshot)?parsed.pluginSnapshot:void 0,decompositionLog:Array.isArray(parsed.decompositionLog)?parsed.decompositionLog:void 0,contentStore:parsed.forkContentStore,inFlight:0,persisted:true,pendingRetrievals:[]}}function isValidRecord(parsed){if(!parsed||typeof parsed!=="object")return false;const r=parsed;return typeof r.id==="string"&&typeof r.state==="object"&&r.state!==null&&Array.isArray(r.state.blocks)}function hasNegativePersistedTokens(parsed){const stats=parsed.stats??{};const last=stats.lastInputTokens??parsed.lastInputTokens;const ctx=stats.contextTokens??parsed.contextTokens;return typeof last==="number"&&last<0||typeof ctx==="number"&&ctx<0}function countActiveBlocks(payload){const blocks=payload.state?.blocks;if(!Array.isArray(blocks))return 0;return blocks.filter(b2=>!!b2&&b2.active===true).length}function viewToRecord(view){const record4={version:PERSIST_VERSION,savedAt:view.lastSeen,id:view.id,createdAt:view.createdAt,meta:view.meta,stats:view.stats,metadata:view.metadata,state:view.state,blockContents:Object.fromEntries(view.blockContents)};if(view.lastMessages!==void 0){record4.messages=view.lastMessages;record4.messagesFolded=view.lastMessagesFolded===true}if(view.pluginSnapshot!==void 0)record4.pluginSnapshot=view.pluginSnapshot;if(view.contentStore!==void 0)record4.forkContentStore=view.contentStore;return record4}function resolveStorageModeSafe(){return resolveStorageModeForProcess()}function resolveStorageModeForProcess(){return resolveStorageMode(process.env,fileStorageUnified())}function storageStatusLabel(){const mode=resolveStorageModeForProcess();if(mode==="legacy")return"storage: legacy (json only)";const encrypted=process.env.BILI_ENCRYPTION_KEY!==void 0&&process.env.BILI_ENCRYPTION_KEY!=="";if(encrypted){return`storage: ${mode} requested \u2014 blocked by BILI_ENCRYPTION_KEY, running legacy-only`}if(mode!=="full")return"storage: shadow (dual-write dry-run \u2192 index.db)";return resolveJsonWriterOff(process.env,fileStorageJsonWriter())&&!encrypted?"storage: full (unified-only, json envelope off)":"storage: full (unified-first reads, dual-write)"}function defaultDir(){return sessionsDir()}function defaultDebounce(){return persistDebounceMs()}function persistEnabled2(){return persistEnabled()}function persistZstdEnabled2(){return persistZstdEnabled()}function isStaleTempName(name){return name.startsWith(".tmp-")||/\.tmp-enc-\d+-\d+$/.test(name)}function walkJsonFilesSync(dir,out=[]){let entries2;try{entries2=readdirSync2(dir,{withFileTypes:true})}catch{return out}for(const e of entries2){const full=path25.join(dir,e.name);if(e.isDirectory())walkJsonFilesSync(full,out);else if(e.isFile()&&(isStaleTempName(e.name)||e.name.endsWith(".json")))out.push(full)}return out}async function walkJsonFiles(dir){const entries2=await readdir2(dir,{withFileTypes:true});const out=[];for(const e of entries2){const full=path25.join(dir,e.name);if(e.isDirectory()){out.push(...await walkJsonFiles(full))}else if(e.isFile()&&(isStaleTempName(e.name)||e.name.endsWith(".json"))){out.push(full)}}return out}function persistTailTokens2(){return persistTailTokens()}function boundedFoldedSnapshot(session){const msgs=session.lastMessages;if(!msgs||msgs.length===0)return void 0;const budget=persistTailTokens2();if(budget===0)return void 0;let view=prune(msgs,session.state);let total=0;for(const m2 of view)total+=defaultCountTokens(m2.text??"");if(total>budget){let acc=0;let start=0;for(let i=view.length-1;i>=0;i--){acc+=defaultCountTokens(view[i].text??"");if(acc>budget){start=Math.min(i+1,view.length-1);break}}if(start>0)view=view.slice(start)}return view}function epermAlertThreshold(){return persistEpermAlertThreshold()}function epermAlertRepeatMs(){return persistEpermAlertRepeatMs()}function defaultLogger(level,m2){log(level,m2)}var _store=null;var globalSessionCommitListener;function peekStoreForStamp(){return _store}function peekStoredTailView(sessionId){const store2=peekStoreForStamp();if(!store2)return null;const rows=store2.unifiedTailViewRows(sessionId);if(!rows||rows.length===0)return null;const messages=[];for(const row of rows){try{const parsed=JSON.parse(row.content);if(typeof parsed?.id!=="string"||typeof parsed?.role!=="string")return null;messages.push(parsed)}catch{return null}}return messages}function getStore(){if(!_store){_store=new SessionStore({enabled:persistEnabled2(),log:defaultLogger});if(globalSessionCommitListener!==void 0)_store.setSessionCommitListener(globalSessionCommitListener)}return _store}init_version();init_knobs();init_config();init_dist();init_config();init_paths();init_logger();init_external_summary_settings();import*as path26 from"path";var CHAT_COMPRESS_PHILOSOPHY=`Your summary IS memory, not an archive: after compression this is the ONLY record of the replaced conversation. Its job is continuity of RELATIONSHIP across compactions and sessions \u2014 who matters to the user, what they care about, what was promised or agreed, where open threads stand. It is NOT a moment-by-moment log of everything said; it records the PAST as state ("this happened"), never as live instructions.`;var CHAT_HOW_TO_COMPRESS=`HOW TO COMPRESS
|
|
902
902
|
|
|
903
903
|
Your summary is the ONLY record of the replaced conversation \u2014 a later reader (a fresh turn of the same relationship) must continue as if nothing was lost. It records the PAST: label task state as history ("TASK AS OF THIS BLOCK: ..."), never as a live instruction. Real unicode only, never \\uXXXX escapes.
|
|
904
904
|
|
|
@@ -923,7 +923,7 @@ DROP \u2014 keep the signal, discard the vessel: greetings and small talk once t
|
|
|
923
923
|
|
|
924
924
|
PRIORITY when compacting: 1. people, relationships and ongoing threads \xB7 2. promises, commitments and boundaries \xB7 3. user preferences and how they like things done \xB7 4. exact anchors (dates, names, quoted words with refs, numbers) \xB7 5. emotional moments and their resolution.
|
|
925
925
|
|
|
926
|
-
Format: dense scannable bullets under short thematic headers, not narrative prose; every line earns its place. Do not mimic the style of existing summaries in context; follow these rules.`;var CHAT_PROMPT_SECTIONS={philosophy:CHAT_COMPRESS_PHILOSOPHY,howToCompress:CHAT_HOW_TO_COMPRESS};var chatPack={name:"chat",version:"0.1.0",description:"Companion-oriented compression: prioritizes people, relationships, ongoing threads and promises over code/document detail. For long-term, multi-session companionship use.",source:"shipped:chat",surface:{promptSections:CHAT_PROMPT_SECTIONS,adapters:{pi:{promptSections:CHAT_PROMPT_SECTIONS}}}};var shippedPacksSource={id:"shipped",resolve(name){return name===chatPack.name?chatPack:null},list(){return[chatPack]}};function resolveContextLimitValue(raw,nativeLimit){if(typeof raw==="number"&&Number.isFinite(raw)&&raw>0)return Math.max(1,Math.floor(raw));if(typeof raw==="string"){const pct2=/^(\d+(?:\.\d+)?)\s*%$/.exec(raw.trim());if(pct2)return Math.max(1,Math.floor(nativeLimit*Number(pct2[1])/100));const n=Number(raw);if(Number.isFinite(n)&&n>0)return Math.floor(n)}return Math.max(1,Math.floor(nativeLimit))}function mergeCompress(global2,provider,model){const pick=k2=>model?.[k2]??provider?.[k2]??global2?.[k2];const promptLevels=[global2?.prompts,provider?.prompts,model?.prompts].filter(Boolean);const rangeOf=s3=>s3?.minCompressRangeChars??s3?.minCompressRange;const absorbLevels=[global2?.absorb,provider?.absorb,model?.absorb].filter(Boolean);const ccrLevels=[global2?.ccr,provider?.ccr,model?.ccr].filter(Boolean);const searchLevels=[global2?.search,provider?.search,model?.search].filter(Boolean);const reasoningLevels=[global2?.reasoning,provider?.reasoning,model?.reasoning].filter(Boolean);const reasoningGuardLevels=[global2?.reasoningGuard,provider?.reasoningGuard,model?.reasoningGuard].filter(Boolean);const outputSteeringLevels=[global2?.outputSteering,provider?.outputSteering,model?.outputSteering].filter(Boolean);const priceProfileLevels=[global2?.priceProfile,provider?.priceProfile,model?.priceProfile].filter(Boolean);const tierNudgeLevels=[global2?.tierNudgeTokens,provider?.tierNudgeTokens,model?.tierNudgeTokens].filter(Boolean);return{modelContextLimit:pick("modelContextLimit"),outputHeadroomMaxPct:pick("outputHeadroomMaxPct"),maxContextLimit:pick("maxContextLimit"),emergencyThresholdPercent:pick("emergencyThresholdPercent"),nudgeGrowthTokens:pick("nudgeGrowthTokens"),minPressureBenefitTokens:pick("minPressureBenefitTokens"),tierNudgeTokens:tierNudgeLevels.length>0?Object.assign({},...tierNudgeLevels):void 0,nudgeModelDecided:pick("nudgeModelDecided"),nudgeDecisionMaxTokens:pick("nudgeDecisionMaxTokens"),preserveRecentMessages:pick("preserveRecentMessages"),preserveRecentTokens:pick("preserveRecentTokens"),minCompressRangeChars:rangeOf(model)??rangeOf(provider)??rangeOf(global2),maxSummaryLength:pick("maxSummaryLength"),minSummaryLength:pick("minSummaryLength"),tiers:pick("tiers"),protectedLatestTools:pick("protectedLatestTools"),protectedTools:pick("protectedTools"),neverPreserveRecentTools:pick("neverPreserveRecentTools"),preserveRecentTools:pick("preserveRecentTools"),prompts:promptLevels.length>0?Object.assign({},...promptLevels):void 0,acknowledgePromptsRisk:pick("acknowledgePromptsRisk"),absorb:absorbLevels.length>0?Object.assign({},...absorbLevels):void 0,ccr:ccrLevels.length>0?Object.assign({},...ccrLevels):void 0,search:searchLevels.length>0?Object.assign({},...searchLevels):void 0,rules:pick("rules"),visibilityMarkers:pick("visibilityMarkers"),messageTimestamps:pick("messageTimestamps"),streamSummary:pick("streamSummary"),reasoning:reasoningLevels.length>0?Object.assign({},...reasoningLevels):void 0,reasoningGuard:reasoningGuardLevels.length>0?Object.assign({},...reasoningGuardLevels):void 0,outputSteering:outputSteeringLevels.length>0?Object.assign({},...outputSteeringLevels):void 0,priceProfile:priceProfileLevels.length>0?Object.assign({},...priceProfileLevels):void 0,reconcile:pick("reconcile"),promptPack:pick("promptPack"),externalSummary:pick("externalSummary")}}function resolveCompress(routes,upstreamUrl,model,global2){const route=findRoute(routes,upstreamUrl);return mergeCompress(global2,route?.compress,model?route?.models?.[model]?.compress:void 0)}var warnedPromptsRisk=false;function resolveCompressPrompts(s3){if(!s3.prompts)return defaultPrompts;if(s3.acknowledgePromptsRisk!==true){if(!warnedPromptsRisk){warnedPromptsRisk=true;log("warn","[compress] prompts override IGNORED: acknowledgePromptsRisk !== true. Set it to true to acknowledge the summary-quality risk.")}return defaultPrompts}try{return resolvePrompts(s3.prompts,{acknowledgeRisk:true})}catch{return defaultPrompts}}var warnedUnknownPack=new Set;function packResolver(dirs){return createPackResolver([createDirPackSource("project",dirs?.projectDir??path26.join(process.cwd(),".billion-context","packs")),...(dirs?.userDirs??[path26.join(configDir(),"packs")]).map(dir=>createDirPackSource("user",dir)),shippedPacksSource,builtinSource])}function resolveCompressSurfaceDetailed(s3,dirs){const name=s3.promptPack;if(typeof name!=="string"||name==="default"||!isValidPackName(name))return{surface:{},packName:"default"};const resolver=packResolver(dirs);const pack=resolver.resolve(name);if(!pack){if(!warnedUnknownPack.has(name)){warnedUnknownPack.add(name);log("warn",`[compress] promptPack "${name}" not found (project/user/builtin); using default surface`)}return{surface:{},packName:"default"}}return{surface:pack.surface,packName:name,packVersion:pack.version}}function listResolvedPacks(dirs){return packResolver(dirs).listPacks()}function hasCompressSettings(s3){return Object.values(s3).some(v2=>v2!==void 0)}function resolveAbsorbSettings(s3){if(s3===void 0)return void 0;const d=DEFAULT_ABSORB_CONFIG;return{enabled:s3.enabled===true,toolName:s3.toolName??d.toolName,minToolTokens:s3.minToolTokens??d.minToolTokens,contextThresholdPct:s3.contextThresholdPct!==void 0?parsePercent(s3.contextThresholdPct):d.contextThresholdPct,excludeTools:s3.excludeTools??[...d.excludeTools],mediaOnly:s3.mediaOnly??true}}function applyCompressSettings(base,limit,s3,recipes={}){const nudge={...base.nudge};const truncate={...base.truncate};if(s3.maxContextLimit!==void 0)nudge.maxContextLimitPct=parsePercent(s3.maxContextLimit);if(s3.emergencyThresholdPercent!==void 0){const pct2=parsePercent(s3.emergencyThresholdPercent);nudge.emergencyThresholdPct=pct2;truncate.threshold=pct2}if(s3.nudgeGrowthTokens!==void 0&&s3.nudgeGrowthTokens>0){nudge.growthFloor=s3.nudgeGrowthTokens;nudge.growthCap=s3.nudgeGrowthTokens}if(s3.minPressureBenefitTokens!==void 0)nudge.minPressureBenefitTokens=s3.minPressureBenefitTokens;if(s3.tierNudgeTokens!==void 0){const tg={};if(typeof s3.tierNudgeTokens.t1==="number")tg.t1=s3.tierNudgeTokens.t1;if(typeof s3.tierNudgeTokens.t2==="number")tg.t2=s3.tierNudgeTokens.t2;if(typeof s3.tierNudgeTokens.t3==="number")tg.t3=s3.tierNudgeTokens.t3;if(tg.t1!==void 0||tg.t2!==void 0||tg.t3!==void 0)nudge.tierGrowthTokens=tg}const tiers={...base.tiers};if(s3.tiers!==void 0)tiers.enabled=s3.tiers;const absorb=resolveAbsorbSettings(s3.absorb);let ccr;if(s3.ccr!==void 0){const d=DEFAULT_CCR_CONFIG;ccr={...d,enabled:s3.ccr.enabled===true,toolName:s3.ccr.toolName??d.toolName,minToolTokens:s3.ccr.minToolTokens??d.minToolTokens,excludeTools:s3.ccr.excludeTools??[...d.excludeTools],maxHeadChars:s3.ccr.maxHeadChars??d.maxHeadChars}}const resolved={...base,modelContextLimit:limit,nudge,truncate,tiers,preserveRecentMessages:s3.preserveRecentMessages??base.preserveRecentMessages,preserveRecentTokens:s3.preserveRecentTokens??base.preserveRecentTokens,compress:{...base.compress,minCompressRange:s3.minCompressRangeChars??s3.minCompressRange??base.compress.minCompressRange,maxSummaryLength:s3.maxSummaryLength??base.compress.maxSummaryLength,minSummaryLength:s3.minSummaryLength??base.compress.minSummaryLength},protectedLatestTools:s3.protectedLatestTools??base.protectedLatestTools,protectedTools:s3.protectedTools??base.protectedTools,neverPreserveRecentTools:s3.neverPreserveRecentTools??base.neverPreserveRecentTools,preserveRecentTools:s3.preserveRecentTools??base.preserveRecentTools,externalSummary:s3.externalSummary!==void 0?expandExternalSummaryChainTolerant(s3.externalSummary,recipes):base.externalSummary,...absorb!==void 0?{absorb}:{},...ccr!==void 0?{ccr}:{},...s3.rules!==void 0?{rules:{enabled:s3.rules===true}}:{}};return resolved}function parsePercent(v2){if(typeof v2==="number")return v2;const s3=v2.trim();if(s3.endsWith("%"))return Number(s3.slice(0,-1))/100;return Number(s3)}function resolveRequestConfig(base,routes,embeddedUrl,model,native,globalCompress,namedProviders){const compress=resolveCompress(routes,embeddedUrl,model,globalCompress);const limit=resolveContextLimitValue(compress.modelContextLimit,native??base.modelContextLimit);if(!hasCompressSettings(compress)&&limit===base.modelContextLimit)return base;return applyCompressSettings(base,limit,compress,namedProviders??{})}init_turn_separator();init_turn_separator();var LazyBlockContents=class extends Map{sessionId;sessionMeta;load;dropped=false;constructor(sessionId,meta,loader){super();this.sessionId=sessionId;this.sessionMeta=meta;this.load=loader}drop(){if(this.dropped||!this.load)return;super.clear();this.dropped=true}get isDropped(){return this.dropped}ensure(){if(!this.dropped)return;const record4=this.load(this.sessionId,this.sessionMeta);if(!record4){throw new Error(`[persist] resident block contents for ${this.sessionId} could not be re-materialized from the store \u2014 refusing the thinned view`)}for(const[id,content]of Object.entries(record4))super.set(id,content);this.dropped=false}get(key2){this.ensure();return super.get(key2)}has(key2){this.ensure();return super.has(key2)}set(key2,value){this.ensure();return super.set(key2,value)}delete(key2){this.ensure();return super.delete(key2)}clear(){this.dropped=false;super.clear()}get size(){this.ensure();return super.size}*entries(){this.ensure();yield*super.entries()}*keys(){this.ensure();yield*super.keys()}*values(){this.ensure();yield*super.values()}forEach(callbackfn,thisArg){this.ensure();super.forEach(callbackfn,thisArg)}[Symbol.iterator](){this.ensure();return super[Symbol.iterator]()}};var droppedMetadataProxies=new WeakSet;function isDroppedMetadata(value){return typeof value==="object"&&value!==null&&droppedMetadataProxies.has(value)}function lazyMetadata(sessionId,meta,loader){const target={};let dropped=true;const ensure=()=>{if(!dropped)return;const record4=loader(sessionId,meta);if(!record4){throw new Error(`[persist] resident metadata for ${sessionId} could not be re-materialized from the store \u2014 refusing the thinned view`)}Object.assign(target,record4);dropped=false;droppedMetadataProxies.delete(proxy)};const proxy=new Proxy(target,{get(t,prop,receiver){ensure();return Reflect.get(t,prop,receiver)},has(t,prop){ensure();return Reflect.has(t,prop)},ownKeys(t){ensure();return Reflect.ownKeys(t)},getOwnPropertyDescriptor(t,prop){ensure();return Reflect.getOwnPropertyDescriptor(t,prop)},set(t,prop,value,receiver){ensure();return Reflect.set(t,prop,value,receiver)},deleteProperty(t,prop){ensure();return Reflect.deleteProperty(t,prop)},defineProperty(t,prop,desc){ensure();return Reflect.defineProperty(t,prop,desc)}});droppedMetadataProxies.add(proxy);return proxy}var droppedContentStoreProxies=new WeakSet;function isDroppedContentStore(value){return typeof value==="object"&&value!==null&&droppedContentStoreProxies.has(value)}function lazyContentStore(sessionId,loader){const target={};let dropped=true;const ensure=()=>{if(!dropped)return;const record4=loader(sessionId);if(!record4||typeof record4!=="object"||!("byRef"in record4)||Object.keys(record4.byRef).length===0){throw new Error(`[persist] resident content store for ${sessionId} could not be re-materialized from the store \u2014 refusing the thinned view`)}Object.assign(target,record4);dropped=false;droppedContentStoreProxies.delete(proxy)};const proxy=new Proxy(target,{get(t,prop,receiver){ensure();return Reflect.get(t,prop,receiver)},has(t,prop){ensure();return Reflect.has(t,prop)},ownKeys(t){ensure();return Reflect.ownKeys(t)},getOwnPropertyDescriptor(t,prop){ensure();return Reflect.getOwnPropertyDescriptor(t,prop)},set(t,prop,value,receiver){ensure();return Reflect.set(t,prop,value,receiver)},deleteProperty(t,prop){ensure();return Reflect.deleteProperty(t,prop)},defineProperty(t,prop,desc){ensure();return Reflect.defineProperty(t,prop,desc)}});droppedContentStoreProxies.add(proxy);return proxy}function lastCompressSuffix(info){if(!info)return"";return` [after compress: shrink ${Math.round(info.shrinkRatio*100)}% foldPoint=${info.foldPoint} blocks=${info.blocks} ~${info.tokensCompressed}tok]`}function storeEffectiveConfig(session,config){const cloneSafe={...config};for(const key2 of Object.keys(cloneSafe)){if(typeof cloneSafe[key2]==="function")delete cloneSafe[key2]}session.metadata["effectiveConfig"]=cloneSafe;session.metadata["effectiveConfigEpoch"]=configFileEpoch()}function staleEffectiveStamp(session){const stamped=session?.metadata?.["effectiveConfigEpoch"];return typeof stamped==="string"&&stamped!==configFileEpoch()}function liveFileOverlayConfig(base){const compress=loadConfigFile().compress;if(!compress||!hasCompressSettings(compress))return base;const limit=resolveContextLimitValue(compress.modelContextLimit,base.modelContextLimit);return applyCompressSettings(base,limit,compress,{})}function effectiveConfig(session,fallback){const stored=session?.metadata["effectiveConfig"];if(staleEffectiveStamp(session)){const live=liveFileOverlayConfig(fallback);const lane2=typeof session?.metadata["pluginAgent"]==="string"?session.metadata["pluginAgent"]:void 0;const classifier2=lane2?durableMessageToolPaths[lane2]:void 0;return classifier2&&!live.messagePathOf?withDurableProtection(live,classifier2):live}const base=stored&&typeof stored==="object"?{...fallback,...stored}:fallback;const lane=typeof session?.metadata["pluginAgent"]==="string"?session.metadata["pluginAgent"]:void 0;const classifier=lane?durableMessageToolPaths[lane]:void 0;return classifier&&!base.messagePathOf?withDurableProtection(base,classifier):base}var STALE_ANCHOR_RATIO=.25;function staleSmallAnchorFallback(stats,anchor){const est=stats.contextEstimateTokens;return stats.contextTokensSource==="estimate"&&anchor>0&&typeof est==="number"&&Number.isFinite(est)&&est>0&&anchor<STALE_ANCHOR_RATIO*est?est:null}function usageAnchorCycleStale(stats){if(stats.lastInputTokensSource!=="usage"||stats.contextTokensSource!=="estimate")return false;return(stats.localInputEstimate??0)>0}function statusInputBaseline(session){const stats=session.stats;if(usageAnchorCycleStale(stats))return stats.localInputEstimate??0;const baseline=stats.lastInputTokensSource==="usage"||stats.lastInputTokensSource==="overflow-arm"?stats.lastInputTokens:stats.lastUsageGradeTokens??0;return staleSmallAnchorFallback(stats,baseline)??baseline}function displayContextBest(session){const st2=session.stats;if(st2.contextTokensSource==="usage"&&st2.contextTokens>0){const at2=typeof session.metadata?.contextTokensAt==="number"?session.metadata.contextTokensAt:void 0;return{tokens:st2.contextTokens,kind:"usage",...at2!==void 0?{at:at2}:{}}}const anchored=(st2.lastUsageGradeTokens??0)>0||st2.lastInputTokensSource==="usage";if(anchored&&typeof st2.contextEstimateTokens==="number"&&st2.contextEstimateTokens>0){return{tokens:st2.contextEstimateTokens,kind:"estimate",...st2.contextEstimateCalibrated?{calibrated:true}:{}}}if(st2.contextTokens>0)return{tokens:st2.contextTokens,kind:"upper"};return null}function diagnoseSuccessWithoutUsage(session,wire){if(!session.metadata)return;if(session.metadata["warnedNoUsage"])return;session.metadata["warnedNoUsage"]=true;markDirty(session);log("warn",`[${session.id}] [${wire}] upstream success without usage report \u2014 keeping lastInputTokens=${session.stats.lastInputTokens} (source=${session.stats.lastInputTokensSource??"none"}); nudge decisions ride local estimates until a usage-grade sample lands (#1595)`)}var ABORT_REANCHOR_MAX_AGE_MS=30*60*1e3;function noteAbortedTurn(session){if(!Number.isFinite(session.stats.lastInputTokens)||session.stats.lastInputTokens<=0)return;session.transient??={};session.transient.abortReanchor={anchor:session.stats.lastInputTokens,at:Date.now()}}function absorbAbortedTurnGrowth(session,tokenCount){const t=session.transient;const flag=t?.abortReanchor;if(!t||!flag)return;if(Date.now()-flag.at>ABORT_REANCHOR_MAX_AGE_MS){delete t.abortReanchor;return}if(!(tokenCount>flag.anchor))return;const nudge=session.state.nudge;const oldRef=nudge.lastPerMessageNudgeTokens;nudge.lastPerMessageNudgeTokens=Math.max(oldRef,tokenCount);nudge.lastNudgeShownTokens=0;nudge.lastShownByTier={};delete t.abortReanchor;log("info",`[${session.id}] aborted-turn growth absorbed: nudge reference ${oldRef}\u2192${nudge.lastPerMessageNudgeTokens} (meter ${tokenCount}, pre-abort anchor ${flag.anchor}) (#5293)`)}var POST_REBUILD_ANCHOR_PREPARES=3;function setPostRebuildAnchor(session,tokens){if(!Number.isFinite(tokens)||tokens<=0)return;session.metadata["postRebuildAnchor"]={tokens,remainingPrepares:POST_REBUILD_ANCHOR_PREPARES};markDirty(session)}function postRebuildAnchorTokens(session){const a=session?.metadata?.["postRebuildAnchor"];if(!a||typeof a!=="object")return 0;const t=a.tokens;return typeof t==="number"&&Number.isFinite(t)&&t>0?t:0}function tickPostRebuildAnchor(session){const a=session.metadata?.["postRebuildAnchor"];if(!a||typeof a!=="object")return;const o=a;const rem=typeof o.remainingPrepares==="number"?o.remainingPrepares-1:0;if(rem<=0)delete session.metadata["postRebuildAnchor"];else o.remainingPrepares=rem;markDirty(session)}function clearPostRebuildAnchor(session){if(session.metadata?.["postRebuildAnchor"]===void 0)return;delete session.metadata["postRebuildAnchor"];markDirty(session)}var sessions=new Map;var MAX_SESSIONS=maxSessions();var MAX_RESIDENT_BYTES=sessionResidentMaxBytes();var residentWeights=new WeakMap;var evictedWeights=new Map;var EVICTED_WEIGHT_CAP=256;function stampEvictedWeight(id,bytes){if(evictedWeights.has(id))evictedWeights.delete(id);evictedWeights.set(id,bytes);while(evictedWeights.size>EVICTED_WEIGHT_CAP){const oldest=evictedWeights.keys().next().value;if(oldest===void 0)break;evictedWeights.delete(oldest)}}function deepSizeOf(value){const seen=new WeakSet;const size=v2=>{if(typeof v2==="string")return 32+v2.length*2;if(!v2||typeof v2!=="object")return 8;if(seen.has(v2))return 0;seen.add(v2);if(Buffer.isBuffer(v2))return 64+v2.byteLength;if(v2 instanceof LazyBlockContents&&v2.isDropped)return 64;if(droppedMetadataProxies.has(v2))return 64;let bytes=64;if(v2 instanceof Map){for(const[key2,item]of v2)bytes+=size(key2)+size(item)+32}else if(v2 instanceof Set){for(const item of v2)bytes+=size(item)+16}else if(Array.isArray(v2)){for(const item of v2)bytes+=size(item)+8}else{for(const key2 of Object.keys(v2))bytes+=size(key2)+size(v2[key2])+16}return bytes};return size(value)}function sessionWeight(session){const revision=session.revisionEpoch??0;const cached=residentWeights.get(session);if(cached?.revision===revision)return cached.bytes;const bytes=deepSizeOf(session);residentWeights.set(session,{revision,bytes});return bytes}function residentBreakdown(session){const total=sessionWeight(session);const lastMessages=session.lastMessages?deepSizeOf(session.lastMessages):0;const pluginSnapshot=session.pluginSnapshot?deepSizeOf(session.pluginSnapshot):0;const blockContents=deepSizeOf(session.blockContents);const contentStore=session.contentStore?deepSizeOf(session.contentStore):0;const state7=deepSizeOf(session.state);const metadata=deepSizeOf(session.metadata);const other=Math.max(0,total-lastMessages-pluginSnapshot-blockContents-contentStore-state7-metadata);return{lastMessages,pluginSnapshot,blockContents,contentStore,state:state7,metadata,other,total}}function memoryReport(){const rows=[];const sums={lastMessages:0,pluginSnapshot:0,blockContents:0,contentStore:0,state:0,metadata:0,other:0,total:0};for(const session of sessions.values()){const fields=residentBreakdown(session);sums.lastMessages+=fields.lastMessages;sums.pluginSnapshot+=fields.pluginSnapshot;sums.blockContents+=fields.blockContents;sums.metadata+=fields.metadata;sums.contentStore+=fields.contentStore;sums.state+=fields.state;sums.other+=fields.other;sums.total+=fields.total;rows.push({id:session.id,inFlight:session.inFlight,lastSeen:session.lastSeen,revision:session.revisionEpoch??0,fields})}rows.sort((a,b2)=>b2.fields.total-a.fields.total);return{pool:{sessions:sessions.size,maxSessions:MAX_SESSIONS,residentBytes:residentBytes(),budgetBytes:MAX_RESIDENT_BYTES},breakdown:sums,sessions:rows}}function residentBytes(){let bytes=0;for(const session of sessions.values())bytes+=sessionWeight(session);return bytes}function residentPressure(id){const resident=sessions.get(id);const self2=resident?sessionWeight(resident):0;const total=residentBytes();const known=evictedWeights.get(id);const weightBytes=known!==void 0?Math.max(known,self2):resident?self2:void 0;return{permanent:weightBytes!==void 0&&weightBytes+(total-self2)>MAX_RESIDENT_BYTES,weightBytes,otherBytes:total-self2,residentBytes:total,budgetBytes:MAX_RESIDENT_BYTES}}function makeResidentRoom(incoming=0){while(sessions.size>=MAX_SESSIONS||sessions.size>0&&residentBytes()+incoming>MAX_RESIDENT_BYTES){if(!evictOldest()){if(sessions.size<MAX_SESSIONS)break;const reason=[...sessions.values()].every(session=>session.inFlight>0)?"all in-flight":"active requests or failed saves prevent safe eviction";throw new Error(`session pool exhausted (MAX_SESSIONS=${MAX_SESSIONS}; ${reason})`)}}}var initialized=false;async function initSessions(){if(initialized)return;initialized=true;const store2=getStore();if(!store2.enabled)return;const loaded=await store2.boot({maxSessions:Math.min(MAX_SESSIONS,sessionWarmMax()),maxBytes:sessionWarmMaxBytes()});for(const[id,s3]of loaded)sessions.set(id,s3)}function zeroStats(){return{requests:0,tokensSaved:0,inputTokens:0,cachedTokens:0,outputTokens:0,cacheSamples:0,lastInputTokens:0,compressCreditTokens:0,contextTokens:0,retrieveCalls:0,retrieveHits:0,retrieveMisses:0,retrieveDropped:0,retrieveDelivered:0,storedBytes:0,storeBytesSaved:0,rangeRestores:0}}var pendingSessionLoads=new Map;function stampExisting(existing,meta){existing.lastSeen=Date.now();existing.restored=false;if(meta?.protocol&&!existing.meta.protocol)existing.meta.protocol=meta.protocol;if(meta?.upstreamOrigin&&!existing.meta.upstreamOrigin)existing.meta.upstreamOrigin=meta.upstreamOrigin;if(meta?.label&&!existing.meta.label)existing.meta.label=meta.label}function adoptOrCreate(id,meta,reloaded){if(reloaded){reloaded.lastSeen=Date.now();reloaded.restored=false;reloaded.persisted=true;makeResidentRoom(sessionWeight(reloaded));sessions.set(id,reloaded);return reloaded}if(sessions.size>=MAX_SESSIONS){const evicted=evictOldest();if(!evicted){throw new Error(`session pool exhausted (MAX_SESSIONS=${MAX_SESSIONS}; all in-flight)`)}}const session=createSession(id,meta);makeResidentRoom(sessionWeight(session));sessions.set(id,session);return session}async function getSessionAsync(id,meta){if(publishingForks.has(id))throw new Error("child fork publication in progress");const existing=sessions.get(id);if(existing){stampExisting(existing,meta);return existing}const store2=getStore();makeResidentRoom();let pending=pendingSessionLoads.get(id);if(!pending){pending=(async()=>adoptOrCreate(id,meta,await store2.loadAsync(id,meta)))().finally(()=>{pendingSessionLoads.delete(id)});pendingSessionLoads.set(id,pending)}return pending}function createSession(id,meta){return{id,meta:{protocol:meta?.protocol,upstreamOrigin:meta?.upstreamOrigin,label:meta?.label},stats:zeroStats(),metadata:{biliVersion:VERSION,storageMode:effectiveFileStorageMode()},state:createInitialState(),createdAt:Date.now(),lastSeen:Date.now(),blockContents:new Map,inFlight:0,persisted:false,pendingRetrievals:[]}}var publishingForks=new Set;async function publishForkSession(session,parentId){if(publishingForks.has(session.id))throw new Error("child fork publication in progress");if(sessions.has(session.id)||await getStore().loadAsync(session.id))throw new Error("child session already exists");publishingForks.add(session.id);try{makeResidentRoom(sessionWeight(session));await getStore().persistForkSession(parentId,session);session.persisted=getStore().enabled;sessions.set(session.id,session)}finally{publishingForks.delete(session.id)}}function acquireInFlight(session){session.inFlight++}function releaseInFlight(session){if(session.inFlight>0)session.inFlight--;residentWeights.delete(session);while(residentBytes()>MAX_RESIDENT_BYTES&&evictOldest()){}}function totalInFlight(){let n=0;for(const s3 of sessions.values())n+=s3.inFlight;return n}async function withSessionLock(session,fn){const prev=session.lockChain??Promise.resolve();let release;const done=new Promise(resolve2=>{release=resolve2});session.lockChain=prev.then(()=>done);await prev;try{return await fn()}finally{release()}}function listSessions(){return[...sessions.values()].sort((a,b2)=>b2.lastSeen-a.lastSeen)}var SPLIT_CANARY_FRESH_MS=10*60*1e3;function splitSessionWarnings(sessions2,now=Date.now()){const byBase=new Map;for(const s3 of sessions2){if(s3.metadata?.personaNamespace===true)continue;const base=s3.id.split("|sub:")[0];const arr=byBase.get(base);if(arr)arr.push(s3);else byBase.set(base,[s3])}const out=[];for(const[base,group]of byBase){if(group.length<2)continue;const fresh=group.filter(s3=>now-(s3.lastSeen??0)<SPLIT_CANARY_FRESH_MS);const anyTraffic=fresh.some(s3=>(s3.stats?.requests??0)>0);const anyChild=fresh.some(s3=>s3.id.includes("|sub:"));if(fresh.length>=2&&anyTraffic&&anyChild){out.push({base,sessions:fresh.map(s3=>({id:s3.id,requests:s3.stats?.requests??0,lastSeen:s3.lastSeen??0}))})}}return out}function peekSession(id){return sessions.get(id)}function hasProcessedState(id,meta){const mem=sessions.get(id);if(mem)return processedEvidence(mem);const store2=getStore();if(!store2.enabled)return false;const reloaded=store2.loadSync(id,meta);return reloaded!==null&&processedEvidence(reloaded)}function processedEvidence(s3){return s3.stats.requests>0||s3.state.nextBlockId>1||s3.blockContents.size>0}function dropSessionForGc(id){const s3=sessions.get(id);if(!s3||s3.inFlight>0)return false;sessions.delete(id);return true}function derivedLegacyCanonicalId(sessionId){return`pfa-${createHash15("sha256").update(`legacy:${sessionId}`).digest("hex").slice(0,16)}`}function canonicalIdOf(session){if(session.id.startsWith("pfa-"))return session.id;const c=session.metadata.canonicalId;if(typeof c==="string"&&c.length>0)return c;return derivedLegacyCanonicalId(session.id)}function findSessionByCanonicalId(canonicalId){for(const s3 of sessions.values()){if(canonicalIdOf(s3)===canonicalId)return s3}return void 0}function snapshotMessages(session,messages){if(messages.length>0){session.lastMessages=messages;session.lastMessagesFolded=false;delete session.metadata.handoffResponse}}function markDirty(session){session.revisionEpoch=(session.revisionEpoch??0)+1;getStore().scheduleSave(session)}function cacheBlockContent(session,blockId,content){session.blockContents.set(blockId,content)}function resetSessionCompression(session){session.state=createInitialState();session.blockContents.clear();session.contentStore=void 0;session.contentStoreDirty=true;session.pendingRetrievals.length=0;delete session.metadata.ccrUndelivered;delete session.metadata.ccrDropNotes;session.ccrReconcilePending=false;session.stats.lastInputTokens=0;delete session.stats.lastInputTokensSource;delete session.stats.overflowArmTokens;delete session.stats.overflowArmCompletionReserve;delete session.stats.overflowArmMismatchWarned;session.stats.localInputEstimate=0;delete session.stats.lastUsageGradeTokens;delete session.stats.lastInputTokensOrigin;delete session.stats.calibratedEstimate;delete session.stats.calibratedEstimateOrigin;delete session.stats.calibratedEstimateModel;delete session.stats.calibrationRing;delete session.stats.lastLocalTextEstimate;delete session.stats.lastLocalTextEstimateOrigin;delete session.stats.lastCalibrationPolicy;delete session.stats.lastCalibrationPolicyOrigin;delete session.stats.contextEstimateTokens;delete session.stats.contextEstimateCalibrated;delete session.metadata.postRebuildAnchor;session.stats.contextTokens=0;delete session.stats.contextTokensSource;session.metadata.nativeCompactionAt=Date.now();markDirty(session)}function markNativeCompactionBoundary(session){session.metadata.nativeCompactionBoundary={at:Date.now(),pendingRebase:true};markDirty(session)}function reconcileNativeCompactionBoundary(session){const boundary=session.metadata.nativeCompactionBoundary;if(!boundary||typeof boundary!=="object"||!boundary.pendingRebase){return false}const highestBefore=highestUsedIndex(session.state.messageRefs);resetSessionCompression(session);if(highestBefore>0&&reserveRefsThrough(session,highestBefore)){markDirty(session)}session.metadata.nativeCompactionBoundary={...boundary,pendingRebase:false,rebasedAt:Date.now()};markDirty(session);return true}function markCompactionBoundary(session){session.metadata.compactionBoundary={at:Date.now(),pending:true};markDirty(session)}function readPreCompactionArchive(session){const raw=session.metadata.preCompactionArchive;if(raw&&typeof raw==="object"&&!Array.isArray(raw)){return raw}return{}}function preCompactionArchiveOf(session){return readPreCompactionArchive(session)}var REF_FLOOR_RAW_ID="bili:ref-floor";function reserveRefsThrough(session,index){if(index<=highestUsedIndex(session.state.messageRefs))return false;session.state.messageRefs.byRaw[REF_FLOOR_RAW_ID]=indexToRef(index);return true}function applyCompactionArchive(session,activeBefore,liveRawIds,log2){const boundary=session.metadata.compactionBoundary;if(!boundary||typeof boundary!=="object"||!boundary.pending){return}const activeAfter=new Set(session.state.blocks.filter(b2=>b2.active).map(b2=>b2.blockId));const deactivated=[...activeBefore].filter(id=>!activeAfter.has(id));if(deactivated.length>0){const archive=readPreCompactionArchive(session);const at2=Date.now();for(const id of deactivated){archive[id]={at:at2,reason:"content replaced by client native compaction summary"}}session.metadata.preCompactionArchive=archive}const{byRaw,byRef}=session.state.messageRefs;const droppedIds=new Set(Object.keys(byRaw).filter(id=>id!==REF_FLOOR_RAW_ID&&!liveRawIds.has(id)));let coverageNote="";if(droppedIds.size>0){const affectedBlocks=session.state.blocks.filter(b2=>(b2.effectiveMessageIds??[]).some(id=>droppedIds.has(id))).map(b2=>b2.blockId);coverageNote=`; ${droppedIds.size} ref(s) dropped${affectedBlocks.length>0?`, covering block(s) ${affectedBlocks.join(", ")}`:""}`}pruneRefsToLiveIds(session,liveRawIds,byRaw,byRef);session.metadata.compactionBoundary={...boundary,pending:false,archivedAt:Date.now(),archivedBlocks:deactivated};markDirty(session);log2("info",`[${session.id}] native compaction boundary: archived ${deactivated.length} pre-compaction block(s)${deactivated.length>0?` (${deactivated.join(", ")})`:""}; pruned ref maps to ${liveRawIds.size} live raw id(s)${coverageNote}`)}function pruneRefsToLiveIds(session,liveRawIds,byRaw,byRef){const highestBefore=highestUsedIndex(session.state.messageRefs);const prunedByRaw={};for(const[rawId,ref]of Object.entries(byRaw)){if(liveRawIds.has(rawId))prunedByRaw[rawId]=ref}if(highestBefore>highestUsedIndex({byRaw:prunedByRaw,byRef:{}}))prunedByRaw[REF_FLOOR_RAW_ID]=indexToRef(highestBefore);const prunedByRef={};const droppedRefs=[];for(const[ref,rawId]of Object.entries(byRef)){if(liveRawIds.has(rawId))prunedByRef[ref]=rawId;else droppedRefs.push(ref)}session.state.messageRefs.byRaw=prunedByRaw;session.state.messageRefs.byRef=prunedByRef;if(droppedRefs.length>0){const merged=new Set(session.state.deadRefs??[]);for(const ref of droppedRefs)merged.add(ref);const sorted=[...merged].sort((a,b2)=>Number(a.replace(/^m/,""))-Number(b2.replace(/^m/,"")));session.state.deadRefs=sorted.length>0?sorted:void 0}}function reapDestroyedSubstrate(session,blockIds,liveRawIds,log2){if(blockIds.size===0||session.state.blocks.length===0)return[];const present=new Set(session.state.blocks.map(b2=>b2.blockId));const reaped=[...blockIds].filter(id=>present.has(id));if(reaped.length===0)return[];session.state.blocks=session.state.blocks.filter(b2=>!blockIds.has(b2.blockId));const archive=readPreCompactionArchive(session);const at2=Date.now();for(const id of reaped){archive[id]={at:at2,reason:"covered substrate destroyed by unannounced client history rewrite (#2695)"}}session.metadata.preCompactionArchive=archive;pruneRefsToLiveIds(session,liveRawIds,session.state.messageRefs.byRaw,session.state.messageRefs.byRef);markDirty(session);log2("info",`[${session.id}] zombie fold reap: removed ${reaped.length} block(s) (${reaped.join(", ")}) from ACP state; blockContents retained, refs pruned to live ids (#2695)`);return reaped}var REWRITE_MIN_KNOWN_REFS=20;var REWRITE_MAX_KNOWN_RATIO=.5;var REWRITE_MIN_INCOMING_TOTAL=10;function detectUnannouncedHistoryRewrite(session,knownRefsBefore,liveRawIds,reconcile){const knownBefore=knownRefsBefore.size-(knownRefsBefore.has(REF_FLOOR_RAW_ID)?1:0);let incomingTotal=0;let knownIncoming=0;for(const id of liveRawIds){incomingTotal++;if(knownRefsBefore.has(id))knownIncoming++}const rawDetected=knownBefore>=REWRITE_MIN_KNOWN_REFS&&session.state.blocks.length>0&&incomingTotal>=REWRITE_MIN_INCOMING_TOTAL&&knownIncoming>0&&knownIncoming/incomingTotal<REWRITE_MAX_KNOWN_RATIO&&knownIncoming/knownBefore<REWRITE_MAX_KNOWN_RATIO;const churnExplained=rawDetected&&reconcile!==void 0&&reconcile!==null&&(reconcile.kind==="reanchored"||reconcile.kind==="resend")&&reconcile.unmatched===0;return{detected:rawDetected&&!churnExplained,knownBefore,incomingTotal,knownIncoming,churnExplained}}function foldCoverage(coveredBefore,liveRawIds){if(coveredBefore.size===0)return null;const incoming=new Set(liveRawIds);let matched=0;for(const id of coveredBefore)if(incoming.has(id))matched++;return matched<coveredBefore.size?{expected:coveredBefore.size,matched}:null}function coveredRealHistoryIds(blocks){const covered=new Set;for(const block of blocks){if(!block.active)continue;for(const id of block.effectiveMessageIds??[]){if(!isResponsesTurnSeparatorId(id))covered.add(id)}}return covered}function evictOldest(){let oldestId;let oldestSeen=Infinity;for(const[id,s4]of sessions){if(s4.inFlight>0)continue;if(s4.lastSeen<oldestSeen){oldestSeen=s4.lastSeen;oldestId=id}}if(!oldestId)return false;const s3=sessions.get(oldestId);const ok=getStore().flushSync(s3);if(!ok){return false}sessions.delete(oldestId);stampEvictedWeight(oldestId,sessionWeight(s3));log("info",`[session] evicted ${oldestId} from resident pool (weight ${sessionWeight(s3)} bytes, ${sessions.size} session(s) remain, budget ${MAX_RESIDENT_BYTES} bytes)`);return true}import{randomUUID as randomUUID5}from"crypto";init_knobs();var BILI_PLUGIN_MARKER="x-bili-plugin";function declaredPluginAgent(headers){const v2=headers[BILI_PLUGIN_MARKER];const s3=Array.isArray(v2)?v2[0]:v2;const t=typeof s3==="string"?s3.trim():void 0;return t!==void 0&&t.length>0?t:void 0}var CODEX_COMPACT_ID_PREFIX="fc_bili_";var CODEX_COMPACT_SENTINEL="bili:acp:";var CODEX_UA_PREFIXES=["codex_cli_rs/","codex_exec/","codex desktop/"];function codexCompactMode2(){return codexCompactMode()}function isCodexClient(headers){const ua=headers["user-agent"];if(!ua)return false;const s3=Array.isArray(ua)?ua[0]:ua;if(typeof s3!=="string")return false;if(CODEX_UA_PREFIXES.some(p2=>s3.toLowerCase().startsWith(p2)))return true;return s3.split(/\s+/).some(t=>t.startsWith("codex"))}function isCodexHost(headers){const agent=declaredPluginAgent(headers);if(agent!==void 0)return agent==="codex";return isCodexClient(headers)}function codexHealthBarApplies(headers){return isCodexHost(headers)&&codexCompactMode2()==="intercept"}function hasCompactionTrigger(input){if(!Array.isArray(input))return false;const last=input[input.length-1];return last?.type==="compaction_trigger"}var CODEX_COMPACT_PROMPT_ANCHOR="You are performing a CONTEXT CHECKPOINT COMPACTION.";function messageItemText(content){if(typeof content==="string")return content;if(!Array.isArray(content))return void 0;const parts=[];for(const part of content){const p2=part;if(p2&&typeof p2==="object"&&typeof p2.text==="string"&&(p2.type==="input_text"||p2.type==="output_text"||p2.type==="text"||p2.type===void 0)){parts.push(p2.text)}}return parts.length>0?parts.join(""):void 0}function hasCompactionPrompt(input){if(!Array.isArray(input))return false;for(let i=input.length-1;i>=0;i--){const item=input[i];if(!item||typeof item!=="object"||item.type!=="message")continue;if(item.role!=="user")return false;const text2=messageItemText(item.content);return typeof text2==="string"&&text2.trimStart().startsWith(CODEX_COMPACT_PROMPT_ANCHOR)}return false}var CODEX_LOCAL_COMPACTION_SUMMARY_PREFIX="Another language model started to solve this problem and produced a summary";var CODEX_LOCAL_COMPACTION_MIN_MISSING=8;function carriesCodexLocalCompactionSummary(msgs){return msgs.some(m2=>typeof m2.text==="string"&&m2.text.startsWith(CODEX_LOCAL_COMPACTION_SUMMARY_PREFIX))}function isBiliCompactionItem(item){const it2=item;if(!it2||it2.type!=="compaction")return false;if(typeof it2.id==="string"&&it2.id.startsWith(CODEX_COMPACT_ID_PREFIX))return true;if(typeof it2.encrypted_content==="string"&&it2.encrypted_content.startsWith(CODEX_COMPACT_SENTINEL))return true;return false}function stripBiliCompactionItems(input){return input.filter(item=>!isBiliCompactionItem(item))}function extractBiliSummary(item){const it2=item;if(!it2||typeof it2.encrypted_content!=="string")return void 0;if(!it2.encrypted_content.startsWith(CODEX_COMPACT_SENTINEL))return void 0;const text2=it2.encrypted_content.slice(CODEX_COMPACT_SENTINEL.length);return text2.length>0?text2:void 0}var CODEX_FORGED_HANDOFF_HEADER="[bili] context summary after compaction:";function replaceBiliCompactionItems(input){const items=[];let replaced=0;let dropped=0;for(const item of input){if(!isBiliCompactionItem(item)){items.push(item);continue}const summary=extractBiliSummary(item);if(summary===void 0){dropped++;continue}items.push({type:"message",role:"user",content:[{type:"input_text",text:`${CODEX_FORGED_HANDOFF_HEADER}
|
|
926
|
+
Format: dense scannable bullets under short thematic headers, not narrative prose; every line earns its place. Do not mimic the style of existing summaries in context; follow these rules.`;var CHAT_PROMPT_SECTIONS={philosophy:CHAT_COMPRESS_PHILOSOPHY,howToCompress:CHAT_HOW_TO_COMPRESS};var chatPack={name:"chat",version:"0.1.0",description:"Companion-oriented compression: prioritizes people, relationships, ongoing threads and promises over code/document detail. For long-term, multi-session companionship use.",source:"shipped:chat",surface:{promptSections:CHAT_PROMPT_SECTIONS,adapters:{pi:{promptSections:CHAT_PROMPT_SECTIONS}}}};var shippedPacksSource={id:"shipped",resolve(name){return name===chatPack.name?chatPack:null},list(){return[chatPack]}};function resolveContextLimitValue(raw,nativeLimit){if(typeof raw==="number"&&Number.isFinite(raw)&&raw>0)return Math.max(1,Math.floor(raw));if(typeof raw==="string"){const pct2=/^(\d+(?:\.\d+)?)\s*%$/.exec(raw.trim());if(pct2)return Math.max(1,Math.floor(nativeLimit*Number(pct2[1])/100));const n=Number(raw);if(Number.isFinite(n)&&n>0)return Math.floor(n)}return Math.max(1,Math.floor(nativeLimit))}function mergeCompress(global2,provider,model){const pick=k2=>model?.[k2]??provider?.[k2]??global2?.[k2];const promptLevels=[global2?.prompts,provider?.prompts,model?.prompts].filter(Boolean);const rangeOf=s3=>s3?.minCompressRangeChars??s3?.minCompressRange;const absorbLevels=[global2?.absorb,provider?.absorb,model?.absorb].filter(Boolean);const ccrLevels=[global2?.ccr,provider?.ccr,model?.ccr].filter(Boolean);const searchLevels=[global2?.search,provider?.search,model?.search].filter(Boolean);const reasoningLevels=[global2?.reasoning,provider?.reasoning,model?.reasoning].filter(Boolean);const reasoningGuardLevels=[global2?.reasoningGuard,provider?.reasoningGuard,model?.reasoningGuard].filter(Boolean);const outputSteeringLevels=[global2?.outputSteering,provider?.outputSteering,model?.outputSteering].filter(Boolean);const priceProfileLevels=[global2?.priceProfile,provider?.priceProfile,model?.priceProfile].filter(Boolean);const tierNudgeLevels=[global2?.tierNudgeTokens,provider?.tierNudgeTokens,model?.tierNudgeTokens].filter(Boolean);return{modelContextLimit:pick("modelContextLimit"),outputHeadroomMaxPct:pick("outputHeadroomMaxPct"),maxContextLimit:pick("maxContextLimit"),emergencyThresholdPercent:pick("emergencyThresholdPercent"),nudgeGrowthTokens:pick("nudgeGrowthTokens"),minPressureBenefitTokens:pick("minPressureBenefitTokens"),tierNudgeTokens:tierNudgeLevels.length>0?Object.assign({},...tierNudgeLevels):void 0,nudgeModelDecided:pick("nudgeModelDecided"),nudgeDecisionMaxTokens:pick("nudgeDecisionMaxTokens"),preserveRecentMessages:pick("preserveRecentMessages"),preserveRecentTokens:pick("preserveRecentTokens"),minCompressRangeChars:rangeOf(model)??rangeOf(provider)??rangeOf(global2),maxSummaryLength:pick("maxSummaryLength"),minSummaryLength:pick("minSummaryLength"),tiers:pick("tiers"),protectedLatestTools:pick("protectedLatestTools"),protectedTools:pick("protectedTools"),neverPreserveRecentTools:pick("neverPreserveRecentTools"),preserveRecentTools:pick("preserveRecentTools"),prompts:promptLevels.length>0?Object.assign({},...promptLevels):void 0,acknowledgePromptsRisk:pick("acknowledgePromptsRisk"),absorb:absorbLevels.length>0?Object.assign({},...absorbLevels):void 0,ccr:ccrLevels.length>0?Object.assign({},...ccrLevels):void 0,search:searchLevels.length>0?Object.assign({},...searchLevels):void 0,rules:pick("rules"),visibilityMarkers:pick("visibilityMarkers"),messageTimestamps:pick("messageTimestamps"),streamSummary:pick("streamSummary"),reasoning:reasoningLevels.length>0?Object.assign({},...reasoningLevels):void 0,reasoningGuard:reasoningGuardLevels.length>0?Object.assign({},...reasoningGuardLevels):void 0,outputSteering:outputSteeringLevels.length>0?Object.assign({},...outputSteeringLevels):void 0,priceProfile:priceProfileLevels.length>0?Object.assign({},...priceProfileLevels):void 0,reconcile:pick("reconcile"),promptPack:pick("promptPack"),externalSummary:pick("externalSummary")}}function resolveCompress(routes,upstreamUrl,model,global2){const route=findRoute(routes,upstreamUrl);return mergeCompress(global2,route?.compress,model?route?.models?.[model]?.compress:void 0)}var warnedPromptsRisk=false;function resolveCompressPrompts(s3){if(!s3.prompts)return defaultPrompts;if(s3.acknowledgePromptsRisk!==true){if(!warnedPromptsRisk){warnedPromptsRisk=true;log("warn","[compress] prompts override IGNORED: acknowledgePromptsRisk !== true. Set it to true to acknowledge the summary-quality risk.")}return defaultPrompts}try{return resolvePrompts(s3.prompts,{acknowledgeRisk:true})}catch{return defaultPrompts}}var warnedUnknownPack=new Set;function packResolver(dirs){return createPackResolver([createDirPackSource("project",dirs?.projectDir??path26.join(process.cwd(),".billion-context","packs")),...(dirs?.userDirs??[path26.join(configDir(),"packs")]).map(dir=>createDirPackSource("user",dir)),shippedPacksSource,builtinSource])}function resolveCompressSurfaceDetailed(s3,dirs){const name=s3.promptPack;if(typeof name!=="string"||name==="default"||!isValidPackName(name))return{surface:{},packName:"default"};const resolver=packResolver(dirs);const pack=resolver.resolve(name);if(!pack){if(!warnedUnknownPack.has(name)){warnedUnknownPack.add(name);log("warn",`[compress] promptPack "${name}" not found (project/user/builtin); using default surface`)}return{surface:{},packName:"default"}}return{surface:pack.surface,packName:name,packVersion:pack.version}}function listResolvedPacks(dirs){return packResolver(dirs).listPacks()}function hasCompressSettings(s3){return Object.values(s3).some(v2=>v2!==void 0)}function resolveAbsorbSettings(s3){if(s3===void 0)return void 0;const d=DEFAULT_ABSORB_CONFIG;return{enabled:s3.enabled===true,toolName:s3.toolName??d.toolName,minToolTokens:s3.minToolTokens??d.minToolTokens,contextThresholdPct:s3.contextThresholdPct!==void 0?parsePercent(s3.contextThresholdPct):d.contextThresholdPct,excludeTools:s3.excludeTools??[...d.excludeTools],mediaOnly:s3.mediaOnly??true}}function applyCompressSettings(base,limit,s3,recipes={}){const nudge={...base.nudge};const truncate={...base.truncate};if(s3.maxContextLimit!==void 0)nudge.maxContextLimitPct=parsePercent(s3.maxContextLimit);if(s3.emergencyThresholdPercent!==void 0){const pct2=parsePercent(s3.emergencyThresholdPercent);nudge.emergencyThresholdPct=pct2;truncate.threshold=pct2}if(s3.nudgeGrowthTokens!==void 0&&s3.nudgeGrowthTokens>0){nudge.growthFloor=s3.nudgeGrowthTokens;nudge.growthCap=s3.nudgeGrowthTokens}if(s3.minPressureBenefitTokens!==void 0)nudge.minPressureBenefitTokens=s3.minPressureBenefitTokens;if(s3.tierNudgeTokens!==void 0){const tg={};if(typeof s3.tierNudgeTokens.t1==="number")tg.t1=s3.tierNudgeTokens.t1;if(typeof s3.tierNudgeTokens.t2==="number")tg.t2=s3.tierNudgeTokens.t2;if(typeof s3.tierNudgeTokens.t3==="number")tg.t3=s3.tierNudgeTokens.t3;if(tg.t1!==void 0||tg.t2!==void 0||tg.t3!==void 0)nudge.tierGrowthTokens=tg}const tiers={...base.tiers};if(s3.tiers!==void 0)tiers.enabled=s3.tiers;const absorb=resolveAbsorbSettings(s3.absorb);let ccr;if(s3.ccr!==void 0){const d=DEFAULT_CCR_CONFIG;ccr={...d,enabled:s3.ccr.enabled===true,toolName:s3.ccr.toolName??d.toolName,minToolTokens:s3.ccr.minToolTokens??d.minToolTokens,excludeTools:s3.ccr.excludeTools??[...d.excludeTools],maxHeadChars:s3.ccr.maxHeadChars??d.maxHeadChars}}const resolved={...base,modelContextLimit:limit,nudge,truncate,tiers,preserveRecentMessages:s3.preserveRecentMessages??base.preserveRecentMessages,preserveRecentTokens:s3.preserveRecentTokens??base.preserveRecentTokens,compress:{...base.compress,minCompressRange:s3.minCompressRangeChars??s3.minCompressRange??base.compress.minCompressRange,maxSummaryLength:s3.maxSummaryLength??base.compress.maxSummaryLength,minSummaryLength:s3.minSummaryLength??base.compress.minSummaryLength},protectedLatestTools:s3.protectedLatestTools??base.protectedLatestTools,protectedTools:s3.protectedTools??base.protectedTools,neverPreserveRecentTools:s3.neverPreserveRecentTools??base.neverPreserveRecentTools,preserveRecentTools:s3.preserveRecentTools??base.preserveRecentTools,externalSummary:s3.externalSummary!==void 0?expandExternalSummaryChainTolerant(s3.externalSummary,recipes):base.externalSummary,...absorb!==void 0?{absorb}:{},...ccr!==void 0?{ccr}:{},...s3.rules!==void 0?{rules:{enabled:s3.rules===true}}:{}};return resolved}function parsePercent(v2){if(typeof v2==="number")return v2;const s3=v2.trim();if(s3.endsWith("%"))return Number(s3.slice(0,-1))/100;return Number(s3)}function resolveRequestConfig(base,routes,embeddedUrl,model,native,globalCompress,namedProviders){const compress=resolveCompress(routes,embeddedUrl,model,globalCompress);const limit=resolveContextLimitValue(compress.modelContextLimit,native??base.modelContextLimit);if(!hasCompressSettings(compress)&&limit===base.modelContextLimit)return base;return applyCompressSettings(base,limit,compress,namedProviders??{})}init_turn_separator();init_turn_separator();var LazyBlockContents=class extends Map{sessionId;sessionMeta;load;dropped=false;constructor(sessionId,meta,loader){super();this.sessionId=sessionId;this.sessionMeta=meta;this.load=loader}drop(){if(this.dropped||!this.load)return;super.clear();this.dropped=true}get isDropped(){return this.dropped}ensure(){if(!this.dropped)return;const record4=this.load(this.sessionId,this.sessionMeta);if(!record4){throw new Error(`[persist] resident block contents for ${this.sessionId} could not be re-materialized from the store \u2014 refusing the thinned view`)}for(const[id,content]of Object.entries(record4))super.set(id,content);this.dropped=false}get(key2){this.ensure();return super.get(key2)}has(key2){this.ensure();return super.has(key2)}set(key2,value){this.ensure();return super.set(key2,value)}delete(key2){this.ensure();return super.delete(key2)}clear(){this.dropped=false;super.clear()}get size(){this.ensure();return super.size}*entries(){this.ensure();yield*super.entries()}*keys(){this.ensure();yield*super.keys()}*values(){this.ensure();yield*super.values()}forEach(callbackfn,thisArg){this.ensure();super.forEach(callbackfn,thisArg)}[Symbol.iterator](){this.ensure();return super[Symbol.iterator]()}};var droppedMetadataProxies=new WeakSet;function isDroppedMetadata(value){return typeof value==="object"&&value!==null&&droppedMetadataProxies.has(value)}function lazyMetadata(sessionId,meta,loader){const target={};let dropped=true;const ensure=()=>{if(!dropped)return;const record4=loader(sessionId,meta);if(!record4){throw new Error(`[persist] resident metadata for ${sessionId} could not be re-materialized from the store \u2014 refusing the thinned view`)}Object.assign(target,record4);dropped=false;droppedMetadataProxies.delete(proxy)};const proxy=new Proxy(target,{get(t,prop,receiver){ensure();return Reflect.get(t,prop,receiver)},has(t,prop){ensure();return Reflect.has(t,prop)},ownKeys(t){ensure();return Reflect.ownKeys(t)},getOwnPropertyDescriptor(t,prop){ensure();return Reflect.getOwnPropertyDescriptor(t,prop)},set(t,prop,value,receiver){ensure();return Reflect.set(t,prop,value,receiver)},deleteProperty(t,prop){ensure();return Reflect.deleteProperty(t,prop)},defineProperty(t,prop,desc){ensure();return Reflect.defineProperty(t,prop,desc)}});droppedMetadataProxies.add(proxy);return proxy}var droppedContentStoreProxies=new WeakSet;function isDroppedContentStore(value){return typeof value==="object"&&value!==null&&droppedContentStoreProxies.has(value)}function lazyContentStore(sessionId,loader){const target={};let dropped=true;const ensure=()=>{if(!dropped)return;const record4=loader(sessionId);if(!record4||typeof record4!=="object"||!("byRef"in record4)||Object.keys(record4.byRef).length===0){throw new Error(`[persist] resident content store for ${sessionId} could not be re-materialized from the store \u2014 refusing the thinned view`)}Object.assign(target,record4);dropped=false;droppedContentStoreProxies.delete(proxy)};const proxy=new Proxy(target,{get(t,prop,receiver){ensure();return Reflect.get(t,prop,receiver)},has(t,prop){ensure();return Reflect.has(t,prop)},ownKeys(t){ensure();return Reflect.ownKeys(t)},getOwnPropertyDescriptor(t,prop){ensure();return Reflect.getOwnPropertyDescriptor(t,prop)},set(t,prop,value,receiver){ensure();return Reflect.set(t,prop,value,receiver)},deleteProperty(t,prop){ensure();return Reflect.deleteProperty(t,prop)},defineProperty(t,prop,desc){ensure();return Reflect.defineProperty(t,prop,desc)}});droppedContentStoreProxies.add(proxy);return proxy}function lastCompressSuffix(info){if(!info)return"";return` [after compress: shrink ${Math.round(info.shrinkRatio*100)}% foldPoint=${info.foldPoint} blocks=${info.blocks} ~${info.tokensCompressed}tok]`}function storeEffectiveConfig(session,config){const cloneSafe={...config};for(const key2 of Object.keys(cloneSafe)){if(typeof cloneSafe[key2]==="function")delete cloneSafe[key2]}session.metadata["effectiveConfig"]=cloneSafe;session.metadata["effectiveConfigEpoch"]=configFileEpoch()}function staleEffectiveStamp(session){const stamped=session?.metadata?.["effectiveConfigEpoch"];return typeof stamped==="string"&&stamped!==configFileEpoch()}function liveFileOverlayConfig(base){const compress=loadConfigFile().compress;if(!compress||!hasCompressSettings(compress))return base;const limit=resolveContextLimitValue(compress.modelContextLimit,base.modelContextLimit);return applyCompressSettings(base,limit,compress,{})}function effectiveConfig(session,fallback){const stored=session?.metadata["effectiveConfig"];if(staleEffectiveStamp(session)){const live=liveFileOverlayConfig(fallback);const lane2=typeof session?.metadata["pluginAgent"]==="string"?session.metadata["pluginAgent"]:void 0;const classifier2=lane2?durableMessageToolPaths[lane2]:void 0;return classifier2&&!live.messagePathOf?withDurableProtection(live,classifier2):live}const base=stored&&typeof stored==="object"?{...fallback,...stored}:fallback;const lane=typeof session?.metadata["pluginAgent"]==="string"?session.metadata["pluginAgent"]:void 0;const classifier=lane?durableMessageToolPaths[lane]:void 0;return classifier&&!base.messagePathOf?withDurableProtection(base,classifier):base}var STALE_ANCHOR_RATIO=.25;function staleSmallAnchorFallback(stats,anchor){const est=stats.contextEstimateTokens;return stats.contextTokensSource==="estimate"&&anchor>0&&typeof est==="number"&&Number.isFinite(est)&&est>0&&anchor<STALE_ANCHOR_RATIO*est?est:null}function usageAnchorCycleStale(stats){if(stats.lastInputTokensSource!=="usage"||stats.contextTokensSource!=="estimate")return false;return(stats.localInputEstimate??0)>0}function statusInputBaseline(session){const stats=session.stats;if(usageAnchorCycleStale(stats))return stats.localInputEstimate??0;const baseline=stats.lastInputTokensSource==="usage"||stats.lastInputTokensSource==="overflow-arm"?stats.lastInputTokens:stats.lastUsageGradeTokens??0;return staleSmallAnchorFallback(stats,baseline)??baseline}function displayContextBest(session){const st2=session.stats;if(st2.contextTokensSource==="usage"&&st2.contextTokens>0){const at2=typeof session.metadata?.contextTokensAt==="number"?session.metadata.contextTokensAt:void 0;return{tokens:st2.contextTokens,kind:"usage",...at2!==void 0?{at:at2}:{}}}const anchored=(st2.lastUsageGradeTokens??0)>0||st2.lastInputTokensSource==="usage";if(anchored&&typeof st2.contextEstimateTokens==="number"&&st2.contextEstimateTokens>0){return{tokens:st2.contextEstimateTokens,kind:"estimate",...st2.contextEstimateCalibrated?{calibrated:true}:{}}}if(st2.contextTokens>0)return{tokens:st2.contextTokens,kind:"upper"};return null}function diagnoseSuccessWithoutUsage(session,wire){if(!session.metadata)return;if(session.metadata["warnedNoUsage"])return;session.metadata["warnedNoUsage"]=true;markDirty(session);log("warn",`[${session.id}] [${wire}] upstream success without usage report \u2014 keeping lastInputTokens=${session.stats.lastInputTokens} (source=${session.stats.lastInputTokensSource??"none"}); nudge decisions ride local estimates until a usage-grade sample lands (#1595)`)}var ABORT_REANCHOR_MAX_AGE_MS=30*60*1e3;function noteAbortedTurn(session){if(!Number.isFinite(session.stats.lastInputTokens)||session.stats.lastInputTokens<=0)return;session.transient??={};session.transient.abortReanchor={anchor:session.stats.lastInputTokens,at:Date.now()}}function absorbAbortedTurnGrowth(session,tokenCount){const t=session.transient;const flag=t?.abortReanchor;if(!t||!flag)return;if(Date.now()-flag.at>ABORT_REANCHOR_MAX_AGE_MS){delete t.abortReanchor;return}if(!(tokenCount>flag.anchor))return;const nudge=session.state.nudge;const oldRef=nudge.lastPerMessageNudgeTokens;const recovered=Math.max(0,flag.anchor-oldRef);nudge.absorbCount=(nudge.absorbCount??0)+1;if(recovered>0)nudge.absorbedDebt=(nudge.absorbedDebt??0)+recovered;nudge.lastPerMessageNudgeTokens=Math.max(oldRef,tokenCount);nudge.lastNudgeShownTokens=0;nudge.lastShownByTier={};delete t.abortReanchor;log("info",`[${session.id}] aborted-turn growth absorbed: nudge reference ${oldRef}\u2192${nudge.lastPerMessageNudgeTokens} (meter ${tokenCount}, pre-abort anchor ${flag.anchor}, growth debt +${recovered} \u2192 ${nudge.absorbedDebt??0} over ${nudge.absorbCount} absorb(s)) (#5293/#5415)`)}var POST_REBUILD_ANCHOR_PREPARES=3;function setPostRebuildAnchor(session,tokens){if(!Number.isFinite(tokens)||tokens<=0)return;session.metadata["postRebuildAnchor"]={tokens,remainingPrepares:POST_REBUILD_ANCHOR_PREPARES};markDirty(session)}function postRebuildAnchorTokens(session){const a=session?.metadata?.["postRebuildAnchor"];if(!a||typeof a!=="object")return 0;const t=a.tokens;return typeof t==="number"&&Number.isFinite(t)&&t>0?t:0}function tickPostRebuildAnchor(session){const a=session.metadata?.["postRebuildAnchor"];if(!a||typeof a!=="object")return;const o=a;const rem=typeof o.remainingPrepares==="number"?o.remainingPrepares-1:0;if(rem<=0)delete session.metadata["postRebuildAnchor"];else o.remainingPrepares=rem;markDirty(session)}function clearPostRebuildAnchor(session){if(session.metadata?.["postRebuildAnchor"]===void 0)return;delete session.metadata["postRebuildAnchor"];markDirty(session)}var sessions=new Map;var MAX_SESSIONS=maxSessions();var MAX_RESIDENT_BYTES=sessionResidentMaxBytes();var residentWeights=new WeakMap;var evictedWeights=new Map;var EVICTED_WEIGHT_CAP=256;function stampEvictedWeight(id,bytes){if(evictedWeights.has(id))evictedWeights.delete(id);evictedWeights.set(id,bytes);while(evictedWeights.size>EVICTED_WEIGHT_CAP){const oldest=evictedWeights.keys().next().value;if(oldest===void 0)break;evictedWeights.delete(oldest)}}function deepSizeOf(value){const seen=new WeakSet;const size=v2=>{if(typeof v2==="string")return 32+v2.length*2;if(!v2||typeof v2!=="object")return 8;if(seen.has(v2))return 0;seen.add(v2);if(Buffer.isBuffer(v2))return 64+v2.byteLength;if(v2 instanceof LazyBlockContents&&v2.isDropped)return 64;if(droppedMetadataProxies.has(v2))return 64;let bytes=64;if(v2 instanceof Map){for(const[key2,item]of v2)bytes+=size(key2)+size(item)+32}else if(v2 instanceof Set){for(const item of v2)bytes+=size(item)+16}else if(Array.isArray(v2)){for(const item of v2)bytes+=size(item)+8}else{for(const key2 of Object.keys(v2))bytes+=size(key2)+size(v2[key2])+16}return bytes};return size(value)}function sessionWeight(session){const revision=session.revisionEpoch??0;const cached=residentWeights.get(session);if(cached?.revision===revision)return cached.bytes;const bytes=deepSizeOf(session);residentWeights.set(session,{revision,bytes});return bytes}function residentBreakdown(session){const total=sessionWeight(session);const lastMessages=session.lastMessages?deepSizeOf(session.lastMessages):0;const pluginSnapshot=session.pluginSnapshot?deepSizeOf(session.pluginSnapshot):0;const blockContents=deepSizeOf(session.blockContents);const contentStore=session.contentStore?deepSizeOf(session.contentStore):0;const state7=deepSizeOf(session.state);const metadata=deepSizeOf(session.metadata);const other=Math.max(0,total-lastMessages-pluginSnapshot-blockContents-contentStore-state7-metadata);return{lastMessages,pluginSnapshot,blockContents,contentStore,state:state7,metadata,other,total}}function memoryReport(){const rows=[];const sums={lastMessages:0,pluginSnapshot:0,blockContents:0,contentStore:0,state:0,metadata:0,other:0,total:0};for(const session of sessions.values()){const fields=residentBreakdown(session);sums.lastMessages+=fields.lastMessages;sums.pluginSnapshot+=fields.pluginSnapshot;sums.blockContents+=fields.blockContents;sums.metadata+=fields.metadata;sums.contentStore+=fields.contentStore;sums.state+=fields.state;sums.other+=fields.other;sums.total+=fields.total;rows.push({id:session.id,inFlight:session.inFlight,lastSeen:session.lastSeen,revision:session.revisionEpoch??0,fields})}rows.sort((a,b2)=>b2.fields.total-a.fields.total);return{pool:{sessions:sessions.size,maxSessions:MAX_SESSIONS,residentBytes:residentBytes(),budgetBytes:MAX_RESIDENT_BYTES},breakdown:sums,sessions:rows}}function residentBytes(){let bytes=0;for(const session of sessions.values())bytes+=sessionWeight(session);return bytes}function residentPressure(id){const resident=sessions.get(id);const self2=resident?sessionWeight(resident):0;const total=residentBytes();const known=evictedWeights.get(id);const weightBytes=known!==void 0?Math.max(known,self2):resident?self2:void 0;return{permanent:weightBytes!==void 0&&weightBytes+(total-self2)>MAX_RESIDENT_BYTES,weightBytes,otherBytes:total-self2,residentBytes:total,budgetBytes:MAX_RESIDENT_BYTES}}function makeResidentRoom(incoming=0){while(sessions.size>=MAX_SESSIONS||sessions.size>0&&residentBytes()+incoming>MAX_RESIDENT_BYTES){if(!evictOldest()){if(sessions.size<MAX_SESSIONS)break;const reason=[...sessions.values()].every(session=>session.inFlight>0)?"all in-flight":"active requests or failed saves prevent safe eviction";throw new Error(`session pool exhausted (MAX_SESSIONS=${MAX_SESSIONS}; ${reason})`)}}}var initialized=false;async function initSessions(){if(initialized)return;initialized=true;const store2=getStore();if(!store2.enabled)return;const loaded=await store2.boot({maxSessions:Math.min(MAX_SESSIONS,sessionWarmMax()),maxBytes:sessionWarmMaxBytes()});for(const[id,s3]of loaded)sessions.set(id,s3)}function zeroStats(){return{requests:0,tokensSaved:0,inputTokens:0,cachedTokens:0,outputTokens:0,cacheSamples:0,lastInputTokens:0,compressCreditTokens:0,contextTokens:0,retrieveCalls:0,retrieveHits:0,retrieveMisses:0,retrieveDropped:0,retrieveDelivered:0,storedBytes:0,storeBytesSaved:0,rangeRestores:0}}var pendingSessionLoads=new Map;function stampExisting(existing,meta){existing.lastSeen=Date.now();existing.restored=false;if(meta?.protocol&&!existing.meta.protocol)existing.meta.protocol=meta.protocol;if(meta?.upstreamOrigin&&!existing.meta.upstreamOrigin)existing.meta.upstreamOrigin=meta.upstreamOrigin;if(meta?.label&&!existing.meta.label)existing.meta.label=meta.label}function adoptOrCreate(id,meta,reloaded){if(reloaded){reloaded.lastSeen=Date.now();reloaded.restored=false;reloaded.persisted=true;makeResidentRoom(sessionWeight(reloaded));sessions.set(id,reloaded);return reloaded}if(sessions.size>=MAX_SESSIONS){const evicted=evictOldest();if(!evicted){throw new Error(`session pool exhausted (MAX_SESSIONS=${MAX_SESSIONS}; all in-flight)`)}}const session=createSession(id,meta);makeResidentRoom(sessionWeight(session));sessions.set(id,session);return session}async function getSessionAsync(id,meta){if(publishingForks.has(id))throw new Error("child fork publication in progress");const existing=sessions.get(id);if(existing){stampExisting(existing,meta);return existing}const store2=getStore();makeResidentRoom();let pending=pendingSessionLoads.get(id);if(!pending){pending=(async()=>adoptOrCreate(id,meta,await store2.loadAsync(id,meta)))().finally(()=>{pendingSessionLoads.delete(id)});pendingSessionLoads.set(id,pending)}return pending}function createSession(id,meta){return{id,meta:{protocol:meta?.protocol,upstreamOrigin:meta?.upstreamOrigin,label:meta?.label},stats:zeroStats(),metadata:{biliVersion:VERSION,storageMode:effectiveFileStorageMode()},state:createInitialState(),createdAt:Date.now(),lastSeen:Date.now(),blockContents:new Map,inFlight:0,persisted:false,pendingRetrievals:[]}}var publishingForks=new Set;async function publishForkSession(session,parentId){if(publishingForks.has(session.id))throw new Error("child fork publication in progress");if(sessions.has(session.id)||await getStore().loadAsync(session.id))throw new Error("child session already exists");publishingForks.add(session.id);try{makeResidentRoom(sessionWeight(session));await getStore().persistForkSession(parentId,session);session.persisted=getStore().enabled;sessions.set(session.id,session)}finally{publishingForks.delete(session.id)}}function acquireInFlight(session){session.inFlight++}function releaseInFlight(session){if(session.inFlight>0)session.inFlight--;residentWeights.delete(session);while(residentBytes()>MAX_RESIDENT_BYTES&&evictOldest()){}}function totalInFlight(){let n=0;for(const s3 of sessions.values())n+=s3.inFlight;return n}async function withSessionLock(session,fn){const prev=session.lockChain??Promise.resolve();let release;const done=new Promise(resolve2=>{release=resolve2});session.lockChain=prev.then(()=>done);await prev;try{return await fn()}finally{release()}}function listSessions(){return[...sessions.values()].sort((a,b2)=>b2.lastSeen-a.lastSeen)}var SPLIT_CANARY_FRESH_MS=10*60*1e3;function splitSessionWarnings(sessions2,now=Date.now()){const byBase=new Map;for(const s3 of sessions2){if(s3.metadata?.personaNamespace===true)continue;const base=s3.id.split("|sub:")[0];const arr=byBase.get(base);if(arr)arr.push(s3);else byBase.set(base,[s3])}const out=[];for(const[base,group]of byBase){if(group.length<2)continue;const fresh=group.filter(s3=>now-(s3.lastSeen??0)<SPLIT_CANARY_FRESH_MS);const anyTraffic=fresh.some(s3=>(s3.stats?.requests??0)>0);const anyChild=fresh.some(s3=>s3.id.includes("|sub:"));if(fresh.length>=2&&anyTraffic&&anyChild){out.push({base,sessions:fresh.map(s3=>({id:s3.id,requests:s3.stats?.requests??0,lastSeen:s3.lastSeen??0}))})}}return out}function peekSession(id){return sessions.get(id)}function hasProcessedState(id,meta){const mem=sessions.get(id);if(mem)return processedEvidence(mem);const store2=getStore();if(!store2.enabled)return false;const reloaded=store2.loadSync(id,meta);return reloaded!==null&&processedEvidence(reloaded)}function processedEvidence(s3){return s3.stats.requests>0||s3.state.nextBlockId>1||s3.blockContents.size>0}function dropSessionForGc(id){const s3=sessions.get(id);if(!s3||s3.inFlight>0)return false;sessions.delete(id);return true}function derivedLegacyCanonicalId(sessionId){return`pfa-${createHash15("sha256").update(`legacy:${sessionId}`).digest("hex").slice(0,16)}`}function canonicalIdOf(session){if(session.id.startsWith("pfa-"))return session.id;const c=session.metadata.canonicalId;if(typeof c==="string"&&c.length>0)return c;return derivedLegacyCanonicalId(session.id)}function findSessionByCanonicalId(canonicalId){for(const s3 of sessions.values()){if(canonicalIdOf(s3)===canonicalId)return s3}return void 0}function snapshotMessages(session,messages){if(messages.length>0){session.lastMessages=messages;session.lastMessagesFolded=false;delete session.metadata.handoffResponse}}function markDirty(session){session.revisionEpoch=(session.revisionEpoch??0)+1;getStore().scheduleSave(session)}function cacheBlockContent(session,blockId,content){session.blockContents.set(blockId,content)}function resetSessionCompression(session){session.state=createInitialState();session.blockContents.clear();session.contentStore=void 0;session.contentStoreDirty=true;session.pendingRetrievals.length=0;delete session.metadata.ccrUndelivered;delete session.metadata.ccrDropNotes;session.ccrReconcilePending=false;session.stats.lastInputTokens=0;delete session.stats.lastInputTokensSource;delete session.stats.overflowArmTokens;delete session.stats.overflowArmCompletionReserve;delete session.stats.overflowArmMismatchWarned;session.stats.localInputEstimate=0;delete session.stats.lastUsageGradeTokens;delete session.stats.lastInputTokensOrigin;delete session.stats.calibratedEstimate;delete session.stats.calibratedEstimateOrigin;delete session.stats.calibratedEstimateModel;delete session.stats.calibrationRing;delete session.stats.lastLocalTextEstimate;delete session.stats.lastLocalTextEstimateOrigin;delete session.stats.lastCalibrationPolicy;delete session.stats.lastCalibrationPolicyOrigin;delete session.stats.contextEstimateTokens;delete session.stats.contextEstimateCalibrated;delete session.metadata.postRebuildAnchor;session.stats.contextTokens=0;delete session.stats.contextTokensSource;session.metadata.nativeCompactionAt=Date.now();markDirty(session)}function markNativeCompactionBoundary(session){session.metadata.nativeCompactionBoundary={at:Date.now(),pendingRebase:true};markDirty(session)}function reconcileNativeCompactionBoundary(session){const boundary=session.metadata.nativeCompactionBoundary;if(!boundary||typeof boundary!=="object"||!boundary.pendingRebase){return false}const highestBefore=highestUsedIndex(session.state.messageRefs);resetSessionCompression(session);if(highestBefore>0&&reserveRefsThrough(session,highestBefore)){markDirty(session)}session.metadata.nativeCompactionBoundary={...boundary,pendingRebase:false,rebasedAt:Date.now()};markDirty(session);return true}function markCompactionBoundary(session){session.metadata.compactionBoundary={at:Date.now(),pending:true};markDirty(session)}function readPreCompactionArchive(session){const raw=session.metadata.preCompactionArchive;if(raw&&typeof raw==="object"&&!Array.isArray(raw)){return raw}return{}}function preCompactionArchiveOf(session){return readPreCompactionArchive(session)}var REF_FLOOR_RAW_ID="bili:ref-floor";function reserveRefsThrough(session,index){if(index<=highestUsedIndex(session.state.messageRefs))return false;session.state.messageRefs.byRaw[REF_FLOOR_RAW_ID]=indexToRef(index);return true}function applyCompactionArchive(session,activeBefore,liveRawIds,log2){const boundary=session.metadata.compactionBoundary;if(!boundary||typeof boundary!=="object"||!boundary.pending){return}const activeAfter=new Set(session.state.blocks.filter(b2=>b2.active).map(b2=>b2.blockId));const deactivated=[...activeBefore].filter(id=>!activeAfter.has(id));if(deactivated.length>0){const archive=readPreCompactionArchive(session);const at2=Date.now();for(const id of deactivated){archive[id]={at:at2,reason:"content replaced by client native compaction summary"}}session.metadata.preCompactionArchive=archive}const{byRaw,byRef}=session.state.messageRefs;const droppedIds=new Set(Object.keys(byRaw).filter(id=>id!==REF_FLOOR_RAW_ID&&!liveRawIds.has(id)));let coverageNote="";if(droppedIds.size>0){const affectedBlocks=session.state.blocks.filter(b2=>(b2.effectiveMessageIds??[]).some(id=>droppedIds.has(id))).map(b2=>b2.blockId);coverageNote=`; ${droppedIds.size} ref(s) dropped${affectedBlocks.length>0?`, covering block(s) ${affectedBlocks.join(", ")}`:""}`}pruneRefsToLiveIds(session,liveRawIds,byRaw,byRef);session.metadata.compactionBoundary={...boundary,pending:false,archivedAt:Date.now(),archivedBlocks:deactivated};markDirty(session);log2("info",`[${session.id}] native compaction boundary: archived ${deactivated.length} pre-compaction block(s)${deactivated.length>0?` (${deactivated.join(", ")})`:""}; pruned ref maps to ${liveRawIds.size} live raw id(s)${coverageNote}`)}function pruneRefsToLiveIds(session,liveRawIds,byRaw,byRef){const highestBefore=highestUsedIndex(session.state.messageRefs);const prunedByRaw={};for(const[rawId,ref]of Object.entries(byRaw)){if(liveRawIds.has(rawId))prunedByRaw[rawId]=ref}if(highestBefore>highestUsedIndex({byRaw:prunedByRaw,byRef:{}}))prunedByRaw[REF_FLOOR_RAW_ID]=indexToRef(highestBefore);const prunedByRef={};const droppedRefs=[];for(const[ref,rawId]of Object.entries(byRef)){if(liveRawIds.has(rawId))prunedByRef[ref]=rawId;else droppedRefs.push(ref)}session.state.messageRefs.byRaw=prunedByRaw;session.state.messageRefs.byRef=prunedByRef;if(droppedRefs.length>0){const merged=new Set(session.state.deadRefs??[]);for(const ref of droppedRefs)merged.add(ref);const sorted=[...merged].sort((a,b2)=>Number(a.replace(/^m/,""))-Number(b2.replace(/^m/,"")));session.state.deadRefs=sorted.length>0?sorted:void 0}}function reapDestroyedSubstrate(session,blockIds,liveRawIds,log2){if(blockIds.size===0||session.state.blocks.length===0)return[];const present=new Set(session.state.blocks.map(b2=>b2.blockId));const reaped=[...blockIds].filter(id=>present.has(id));if(reaped.length===0)return[];session.state.blocks=session.state.blocks.filter(b2=>!blockIds.has(b2.blockId));const archive=readPreCompactionArchive(session);const at2=Date.now();for(const id of reaped){archive[id]={at:at2,reason:"covered substrate destroyed by unannounced client history rewrite (#2695)"}}session.metadata.preCompactionArchive=archive;pruneRefsToLiveIds(session,liveRawIds,session.state.messageRefs.byRaw,session.state.messageRefs.byRef);markDirty(session);log2("info",`[${session.id}] zombie fold reap: removed ${reaped.length} block(s) (${reaped.join(", ")}) from ACP state; blockContents retained, refs pruned to live ids (#2695)`);return reaped}var REWRITE_MIN_KNOWN_REFS=20;var REWRITE_MAX_KNOWN_RATIO=.5;var REWRITE_MIN_INCOMING_TOTAL=10;function detectUnannouncedHistoryRewrite(session,knownRefsBefore,liveRawIds,reconcile){const knownBefore=knownRefsBefore.size-(knownRefsBefore.has(REF_FLOOR_RAW_ID)?1:0);let incomingTotal=0;let knownIncoming=0;for(const id of liveRawIds){incomingTotal++;if(knownRefsBefore.has(id))knownIncoming++}const rawDetected=knownBefore>=REWRITE_MIN_KNOWN_REFS&&session.state.blocks.length>0&&incomingTotal>=REWRITE_MIN_INCOMING_TOTAL&&knownIncoming>0&&knownIncoming/incomingTotal<REWRITE_MAX_KNOWN_RATIO&&knownIncoming/knownBefore<REWRITE_MAX_KNOWN_RATIO;const churnExplained=rawDetected&&reconcile!==void 0&&reconcile!==null&&(reconcile.kind==="reanchored"||reconcile.kind==="resend")&&reconcile.unmatched===0;return{detected:rawDetected&&!churnExplained,knownBefore,incomingTotal,knownIncoming,churnExplained}}function foldCoverage(coveredBefore,liveRawIds){if(coveredBefore.size===0)return null;const incoming=new Set(liveRawIds);let matched=0;for(const id of coveredBefore)if(incoming.has(id))matched++;return matched<coveredBefore.size?{expected:coveredBefore.size,matched}:null}function coveredRealHistoryIds(blocks){const covered=new Set;for(const block of blocks){if(!block.active)continue;for(const id of block.effectiveMessageIds??[]){if(!isResponsesTurnSeparatorId(id))covered.add(id)}}return covered}function evictOldest(){let oldestId;let oldestSeen=Infinity;for(const[id,s4]of sessions){if(s4.inFlight>0)continue;if(s4.lastSeen<oldestSeen){oldestSeen=s4.lastSeen;oldestId=id}}if(!oldestId)return false;const s3=sessions.get(oldestId);const ok=getStore().flushSync(s3);if(!ok){return false}sessions.delete(oldestId);stampEvictedWeight(oldestId,sessionWeight(s3));log("info",`[session] evicted ${oldestId} from resident pool (weight ${sessionWeight(s3)} bytes, ${sessions.size} session(s) remain, budget ${MAX_RESIDENT_BYTES} bytes)`);return true}import{randomUUID as randomUUID5}from"crypto";init_knobs();var BILI_PLUGIN_MARKER="x-bili-plugin";function declaredPluginAgent(headers){const v2=headers[BILI_PLUGIN_MARKER];const s3=Array.isArray(v2)?v2[0]:v2;const t=typeof s3==="string"?s3.trim():void 0;return t!==void 0&&t.length>0?t:void 0}var CODEX_COMPACT_ID_PREFIX="fc_bili_";var CODEX_COMPACT_SENTINEL="bili:acp:";var CODEX_UA_PREFIXES=["codex_cli_rs/","codex_exec/","codex desktop/"];function codexCompactMode2(){return codexCompactMode()}function isCodexClient(headers){const ua=headers["user-agent"];if(!ua)return false;const s3=Array.isArray(ua)?ua[0]:ua;if(typeof s3!=="string")return false;if(CODEX_UA_PREFIXES.some(p2=>s3.toLowerCase().startsWith(p2)))return true;return s3.split(/\s+/).some(t=>t.startsWith("codex"))}function isCodexHost(headers){const agent=declaredPluginAgent(headers);if(agent!==void 0)return agent==="codex";return isCodexClient(headers)}function codexHealthBarApplies(headers){return isCodexHost(headers)&&codexCompactMode2()==="intercept"}function hasCompactionTrigger(input){if(!Array.isArray(input))return false;const last=input[input.length-1];return last?.type==="compaction_trigger"}var CODEX_COMPACT_PROMPT_ANCHOR="You are performing a CONTEXT CHECKPOINT COMPACTION.";function messageItemText(content){if(typeof content==="string")return content;if(!Array.isArray(content))return void 0;const parts=[];for(const part of content){const p2=part;if(p2&&typeof p2==="object"&&typeof p2.text==="string"&&(p2.type==="input_text"||p2.type==="output_text"||p2.type==="text"||p2.type===void 0)){parts.push(p2.text)}}return parts.length>0?parts.join(""):void 0}function hasCompactionPrompt(input){if(!Array.isArray(input))return false;for(let i=input.length-1;i>=0;i--){const item=input[i];if(!item||typeof item!=="object"||item.type!=="message")continue;if(item.role!=="user")return false;const text2=messageItemText(item.content);return typeof text2==="string"&&text2.trimStart().startsWith(CODEX_COMPACT_PROMPT_ANCHOR)}return false}var CODEX_LOCAL_COMPACTION_SUMMARY_PREFIX="Another language model started to solve this problem and produced a summary";var CODEX_LOCAL_COMPACTION_MIN_MISSING=8;function carriesCodexLocalCompactionSummary(msgs){return msgs.some(m2=>typeof m2.text==="string"&&m2.text.startsWith(CODEX_LOCAL_COMPACTION_SUMMARY_PREFIX))}function isBiliCompactionItem(item){const it2=item;if(!it2||it2.type!=="compaction")return false;if(typeof it2.id==="string"&&it2.id.startsWith(CODEX_COMPACT_ID_PREFIX))return true;if(typeof it2.encrypted_content==="string"&&it2.encrypted_content.startsWith(CODEX_COMPACT_SENTINEL))return true;return false}function stripBiliCompactionItems(input){return input.filter(item=>!isBiliCompactionItem(item))}function extractBiliSummary(item){const it2=item;if(!it2||typeof it2.encrypted_content!=="string")return void 0;if(!it2.encrypted_content.startsWith(CODEX_COMPACT_SENTINEL))return void 0;const text2=it2.encrypted_content.slice(CODEX_COMPACT_SENTINEL.length);return text2.length>0?text2:void 0}var CODEX_FORGED_HANDOFF_HEADER="[bili] context summary after compaction:";function replaceBiliCompactionItems(input){const items=[];let replaced=0;let dropped=0;for(const item of input){if(!isBiliCompactionItem(item)){items.push(item);continue}const summary=extractBiliSummary(item);if(summary===void 0){dropped++;continue}items.push({type:"message",role:"user",content:[{type:"input_text",text:`${CODEX_FORGED_HANDOFF_HEADER}
|
|
927
927
|
${summary}`}]});replaced++}return{items,replaced,dropped}}var CODEX_COMPACT_HEALTH_RATIO=.9;function codexCompactGatePre(session,effectiveLimit){if(effectiveLimit<=0)return false;if(statusInputBaseline(session)>=effectiveLimit*CODEX_COMPACT_HEALTH_RATIO)return false;return session.state.blocks.some(b2=>b2.active)}function codexCompactGate(session,effectiveLimit,transformOk){return transformOk&&codexCompactGatePre(session,effectiveLimit)}function buildTriggerForgeBody(summaryText,usage,stream2){const compactionItem={type:"compaction",id:`${CODEX_COMPACT_ID_PREFIX}${randomUUID5()}`,encrypted_content:`${CODEX_COMPACT_SENTINEL}${summaryText}`};const usageJson={input_tokens:usage.inputTokens,output_tokens:usage.outputTokens,total_tokens:usage.totalTokens};const id=`resp_bili_${randomUUID5()}`;if(!stream2){return{body:JSON.stringify({id,output:[compactionItem],usage:usageJson}),contentType:"application/json"}}const frame1=`data: ${JSON.stringify({type:"response.output_item.done",item:compactionItem})}
|
|
928
928
|
|
|
929
929
|
`;const frame2=`data: ${JSON.stringify({type:"response.completed",response:{id,usage:usageJson}})}
|
|
@@ -973,7 +973,7 @@ ${hostname}
|
|
|
973
973
|
${home}`).digest("hex").slice(0,32)}function featureEnabled(feature){return resolveRollout(feature,{id:rolloutInstallId()}).enabled}init_config();init_knobs();init_store();import{createHash as createHash23}from"crypto";var MAX_CHAIN_WALK=8192;var MIN_SEAM_RUN=2;function identitySig(m2){const text2=typeof m2.text==="string"?m2.text:"";const img=m2.imagePart===true?`|img:${sha256Hex2(m2.imageBase64??"").slice(0,24)}`:"";return`${m2.role}|${m2.contentType}|${m2.toolName??""}|${text2}${img}`}function noteRender(session,deps){const prior=typeof session.metadata["snapshotRenderTurns"]==="number"?session.metadata["snapshotRenderTurns"]:0;session.metadata["snapshotRenderTurns"]=prior+1;if(prior===0)deps.log?.("info",`[snapshot-render] active: outbound prefix now rendered from the unified transcript (issue #3756)`)}function legacyFor(session,deps,clientMsgs,reason){session.metadata["snapshotRenderDegradeReason"]=reason;deps.log?.("debug",`[snapshot-render] legacy fallback (${reason})`);return clientMsgs}function parseRow(content,seq,ts2){try{const parsed=JSON.parse(content);if(typeof parsed.id!=="string"||typeof parsed.role!=="string")return null;const msg=parsed;msg.ledgerSeq=seq+1;if(typeof ts2==="number")msg.ts=ts2;return msg}catch{return null}}function loadTranscriptBase(session){const store2=getStore();if(!store2)return{reason:"store-unavailable"};let rows=[];try{const light=store2.unifiedMessageIdRows(session.id);const seqs=store2.unifiedTailSeqs(session.id);if(!light||light.length===0||!seqs||seqs.length===0)return{reason:"transcript-empty"};const bySeq=new Map;for(const row of light)bySeq.set(row.seq,{seq:row.seq,msgId:row.msgId});for(const seq of seqs){const v2=bySeq.get(seq);if(!v2)return{reason:"view-pointer-missing-row"};rows.push(v2)}}catch{return{reason:"transcript-error"}}if(rows.length===0)return{reason:"transcript-empty"};const activeBlocks2=session.state.blocks.filter(b2=>b2.active);const blockSeeds=[];const coveredSeqUnion=new Set;for(const block of activeBlocks2){const blockSeqs=new Set;const wanted=new Set(block.effectiveMessageIds);for(let i=0;i<rows.length;i++){if(wanted.has(rows[i].msgId))blockSeqs.add(rows[i].seq)}if(blockSeqs.size===0)return{reason:"block-unanchored"};for(const seq of blockSeqs)coveredSeqUnion.add(seq);blockSeeds.push({blockId:block.blockId,seqs:blockSeqs})}try{const intervals=[];{const sorted=[...coveredSeqUnion].sort((a,b2)=>a-b2);for(const seq of sorted){const last=intervals[intervals.length-1];if(last&&seq<=last[1]+1)last[1]=Math.max(last[1],seq);else intervals.push([seq,seq])}}const contentRows=store2.unifiedUncoveredRows(session.id,intervals);if(contentRows!==null){const bySeq=new Map;for(const row of contentRows){const msg=parseRow(row.content,row.seq,row.ts);if(!msg)return{reason:"row-unparsable"};bySeq.set(row.seq,{seq:row.seq,msgId:row.msgId,msg})}let coveredSeen=0;for(const r of rows){const v2=bySeq.get(r.seq);if(v2)r.msg=v2.msg;else if(coveredSeqUnion.has(r.seq))coveredSeen++}if(coveredSeen!==[...coveredSeqUnion].filter(seq=>rows.some(r=>r.seq===seq)).length||rows.some(r=>!r.msg&&!coveredSeqUnion.has(r.seq))){const full=store2.unifiedTailViewRows(session.id);if(full!==null){const fullBySeq=new Map;for(const row of full){const msg=parseRow(row.content,row.seq,row.ts);if(msg)fullBySeq.set(row.seq,msg)}for(const r of rows){if(!r.msg){const m2=fullBySeq.get(r.seq);if(!m2&&!coveredSeqUnion.has(r.seq))return{reason:"row-unparsable"};if(m2)r.msg=m2}}}}}}catch{return{reason:"transcript-error"}}return{rows,blockSeeds,coveredSeqUnion}}function assembleView(rows,blockSeeds,coveredSeqUnion,d,tailMsgs){const anchors=[];for(const{blockId,seqs:blockSeqs}of blockSeeds){let maxCover=-1;for(const seq of blockSeqs)maxCover=Math.max(maxCover,seq);let at2=d;for(let i=0;i<d;i++){if(rows[i].seq>maxCover){at2=i;break}}anchors.push({at:at2,msg:{id:`acp_summary_${blockId}`,role:"system",contentType:"text",text:""}})}anchors.sort((a,b2)=>a.at-b2.at);const merged=[];let ai2=0;for(let i=0;i<d;i++){while(ai2<anchors.length&&anchors[ai2].at===i)merged.push(anchors[ai2++].msg);if(coveredSeqUnion.has(rows[i].seq))continue;const m2=rows[i].msg;if(!m2)return null;merged.push(m2)}while(ai2<anchors.length)merged.push(anchors[ai2++].msg);for(const m2 of tailMsgs)merged.push(m2);return merged}function buildView(session,clientMsgs){const activeBlocks2=session.state.blocks.filter(b2=>b2.active);if(activeBlocks2.length===0)return{ok:false,reason:"no-active-blocks"};const base=loadTranscriptBase(session);if("reason"in base)return{ok:false,reason:base.reason};const{rows,blockSeeds,coveredSeqUnion}=base;let joinRow=-1;let clientJoin=clientMsgs.length;{const byId2=new Map;for(let i=0;i<rows.length;i++)byId2.set(rows[i].msgId,i);const bySig=new Map;for(let i=rows.length-1;i>=0;i--){if(coveredSeqUnion.has(rows[i].seq))continue;const m2=rows[i].msg;if(!m2)continue;const sig=identitySig(m2);const list=bySig.get(sig);if(list)list.push(i);else bySig.set(sig,[i])}let cursor=rows.length;let started=false;let run=0;let gapped=false;for(let k2=clientMsgs.length-1;k2>=0&&clientMsgs.length-1-k2<MAX_CHAIN_WALK;k2--){const m2=clientMsgs[k2];const sig=identitySig(m2);let hit=-1;const byIdHit=byId2.get(m2.id);if(byIdHit!==void 0&&byIdHit<cursor)hit=byIdHit;else{const cands=bySig.get(sig);if(cands){for(const idx of cands){if(idx<cursor){hit=idx;break}}}}if(hit<0){if(started){if(gapped)break;gapped=true;continue}continue}gapped=false;if(!started){started=true;clientJoin=k2+1;joinRow=hit}run++;cursor=hit}if(!started)return{ok:false,reason:"chain-not-started"};if(run<MIN_SEAM_RUN)return{ok:false,reason:"seam-too-short"}}const d=joinRow+1;const merged=assembleView(rows,blockSeeds,coveredSeqUnion,d,clientMsgs.slice(clientJoin));if(merged===null)return{ok:false,reason:"row-unparsable"};const tailCount=clientMsgs.length-clientJoin;return{ok:true,view:merged,tailStart:merged.length-tailCount}}var SnapshotAnchorFallbackError=class extends Error{constructor(reason){super(`snapshot anchor fallback (${reason})`);this.reason=reason;this.name="SnapshotAnchorFallbackError"}reason};var WS_ANCHORED_REQ_PROP=Symbol.for("bili.wsAnchored");function wsAnchoredPayload(req){const v2=req[WS_ANCHORED_REQ_PROP];if(!v2||typeof v2!=="object")return void 0;const p2=v2;return typeof p2.tailSig==="string"&&p2.tailSig.length>0?p2:void 0}function noteAnchoredRender(session,log2){const prior=typeof session.metadata["wsDeltaTurns"]==="number"?session.metadata["wsDeltaTurns"]:0;session.metadata["wsDeltaTurns"]=prior+1;if(prior===0)log2?.("info","[ws-delta] active: outbound prefix rendered from the unified transcript, delta continuations verified against it (issue #4804)")}function buildAnchoredView(session,tailMsgs,probeSig){if(probeSig===null)return{ok:false,reason:"anchor-probe-unavailable"};const base=loadTranscriptBase(session);if("reason"in base)return{ok:false,reason:base.reason};const{rows,blockSeeds,coveredSeqUnion}=base;const store2=getStore();if(!store2)return{ok:false,reason:"store-unavailable"};const last=rows[rows.length-1];const line=store2.unifiedMessageRows(session.id,[last.msgId])?.find(r=>r.msgId===last.msgId&&r.seq===last.seq);const probeMsg=line?parseRow(line.content,line.seq):null;if(!probeMsg)return{ok:false,reason:"row-unparsable"};if(identitySig(probeMsg)!==probeSig)return{ok:false,reason:"anchor-mismatch"};const d=rows.length;const merged=assembleView(rows,blockSeeds,coveredSeqUnion,d,tailMsgs);if(merged===null)return{ok:false,reason:"row-unparsable"};return{ok:true,view:merged,tailStart:merged.length-tailMsgs.length}}function maybeSnapshotView(session,clientMsgs,deps){delete session.metadata["snapshotRenderTailStart"];if(deps.pluginMode)return clientMsgs;const live=featureEnabled("snapshotRender");const shadow=!live&&shadowLaneEnabled();if(!live&&!shadow)return clientMsgs;if(!session.state.blocks.some(b2=>b2.active))return clientMsgs;const r=buildView(session,clientMsgs);if(live){if(!r.ok)return legacyFor(session,deps,clientMsgs,r.reason);delete session.metadata["snapshotRenderDegradeReason"];session.metadata["snapshotRenderTailStart"]=r.tailStart;noteRender(session,deps);return r.view}noteShadow(session,deps,r,clientMsgs);return clientMsgs}function shadowLaneEnabled(){return resolveSnapshotShadow(process.env,loadConfigFile().snapshot?.shadow)}function classifyShadowForTest(x){const digest=msgs=>createHash23("sha256").update(msgs.map(m2=>`${m2.id}\0${identitySig(m2)}`).join("")).digest("hex").slice(0,16);const isAnchor=m2=>typeof m2.id==="string"&&m2.id.startsWith("acp_summary_");const viewIds=new Set;const viewSigCount=new Map;const idCount=new Map;for(const m2 of x.view){if(isAnchor(m2))continue;viewIds.add(m2.id);idCount.set(m2.id,(idCount.get(m2.id)??0)+1);const sig=identitySig(m2);viewSigCount.set(sig,(viewSigCount.get(sig)??0)+1)}let lostTail=0;let suppressed=0;for(const m2 of x.clientMsgs){const inView=viewIds.has(m2.id)||(viewSigCount.get(identitySig(m2))??0)>0;if(x.coveredClientIds.has(m2.id)){if(!inView)suppressed++;continue}if(!inView)lostTail++}const duplicateIds=[...idCount.entries()].filter(([,c])=>c>1).map(([id])=>id);const inputDigest=digest(x.clientMsgs);const viewDigest=digest(x.view);const unstablePrefix=x.prev?.inputDigest!==void 0&&x.prev.inputDigest===inputDigest&&x.prev.viewDigest!==void 0&&x.prev.viewDigest!==viewDigest;return{lostTail,duplicateIds,unstablePrefix,suppressed,inputDigest,viewDigest}}function noteShadow(session,deps,result,clientMsgs){const prior=session.metadata["snapshotShadow"];const blob=prior&&typeof prior==="object"&&typeof prior.turns==="number"?prior:{turns:0,errors:0,lastClass:"watch"};blob.turns++;if(!result.ok){blob.lastClass="degraded";blob.lastReason=result.reason;delete blob.lastErrors;delete blob.inputDigest;delete blob.viewDigest;if(blob.lastLogged!==result.reason){deps.log?.("warn",`[snapshot-shadow] view degraded on ${session.id} (${result.reason}) \u2014 legacy outbound kept`);blob.lastLogged=result.reason}session.metadata["snapshotShadow"]=blob;return}const covered=new Set;for(const b2 of session.state.blocks){if(!b2.active)continue;for(const id of b2.effectiveMessageIds)covered.add(id)}const c=classifyShadowForTest({view:result.view,clientMsgs,coveredClientIds:covered,prev:{inputDigest:blob.inputDigest,viewDigest:blob.viewDigest}});blob.inputDigest=c.inputDigest;blob.viewDigest=c.viewDigest;const errors=[];if(c.lostTail>0)errors.push(`lost-tail:${c.lostTail}`);if(c.duplicateIds.length>0)errors.push(`duplicate:${c.duplicateIds.length}`);if(c.unstablePrefix)errors.push("unstable-prefix");const signature=errors.length>0?errors.join(","):"ok";if(errors.length>0){blob.errors+=errors.length;blob.lastClass="error";blob.lastErrors=errors;delete blob.lastReason;if(blob.lastLogged!==signature){deps.log?.("error",`[snapshot-shadow] mechanical mismatch on ${session.id} (${errors.join("; ")}) \u2014 diagnostics: /__bili/diagnostics?topic=snapshot-shadow`);blob.lastLogged=signature}}else{blob.lastClass="watch";delete blob.lastReason;delete blob.lastErrors}session.metadata["snapshotShadow"]=blob}function snapshotShadowStatusWire(){const enabled=shadowLaneEnabled();let watching=0;let errors=0;let worst;for(const s3 of listSessions()){const blob=s3.metadata["snapshotShadow"];if(!blob||typeof blob!=="object"||!(blob.turns>0))continue;watching++;errors+=blob.errors??0;if((blob.errors??0)>0&&(!worst||(blob.errors??0)>worst.n)){worst={sessionId:s3.id,label:s3.meta.label!==s3.id?s3.meta.label:void 0,lastErrors:blob.lastErrors??[],n:blob.errors??0}}}return enabled?{enabled,watching,errors,...worst?{worst:{sessionId:worst.sessionId,label:worst.label,lastErrors:worst.lastErrors}}:{}}:{enabled,watching,errors}}init_fetch_transport();function safeSessionId(id){return(id??"unknown").replace(/[^a-zA-Z0-9._-]/g,"_")}var NO_IDENTITY_MESSAGE="Missing stable conversation identity. Send one of the headers: x-session-id, x-session-affinity, x-acp-session, x-opencode-session-id, x-opencode-session, x-claude-code-session-id, session-id \u2014 or body session_id / prompt_cache_key (responses/openai/anthropic). Requests replaying a conversation history are matched by content prefix affinity (#309); this one carries no usable history signal.";var UPSTREAM_HOP_HEADERS=new Set(["host","content-length","connection","keep-alive","transfer-encoding","proxy-authenticate","proxy-authorization","proxy-connection","x-bili-passthrough","te","trailer","upgrade"]);var RESPONSE_ONLY_STRIP_HEADERS=new Set(["content-encoding"]);function connectionNamedHeaders(conn){const out=new Set;if(!conn)return out;for(const part of Array.isArray(conn)?conn:[conn]){for(const name of part.split(",")){const t=name.trim().toLowerCase();if(t)out.add(t)}}return out}function stripRemoteCompactionBetaFeature(headers){const betaKey=Object.keys(headers).find(h=>h.toLowerCase()==="x-codex-beta-features");if(!betaKey)return;const kept=headers[betaKey].split(",").map(s3=>s3.trim()).filter(f2=>f2&&f2!=="remote_compaction_v2");if(kept.length>0)headers[betaKey]=kept.join(",");else delete headers[betaKey]}function buildForwardHeaders(headers){const out={};for(const[k2,v2]of Object.entries(headers)){if(k2.toLowerCase()==="content-length"||k2.toLowerCase()==="host")continue;out[k2]=v2}out["content-type"]="application/json";return out}function normalizeSseLineEndings(buf){if(buf.indexOf("\r")===-1)return buf;const trailingCr=buf.endsWith("\r");const head=trailingCr?buf.slice(0,-1):buf;return head.replace(/\r\n|\r/g,"\n")+(trailingCr?"\r":"")}function finalizeSseLineEndings(buf){if(buf.indexOf("\r")===-1)return buf;return buf.replace(/\r\n|\r/g,"\n")}function closeCode(event){return"code"in event&&typeof event.code==="number"?event.code:"none"}function isHandshakeRefusal(error){return error instanceof Error&&error.message==="Responses WebSocket handshake failed"}function releaseUpstreamWatchdog(response,release){const inner=response.body;if(!inner){release();return response}const reader=inner.getReader();let released=false;const finish2=()=>{if(!released){released=true;release()}};const wrapped=new ReadableStream({async pull(controller){try{const chunk=await reader.read();if(chunk.done){controller.close();finish2();return}controller.enqueue(chunk.value)}catch(err2){controller.error(err2);finish2()}},async cancel(reason){try{await reader.cancel(reason)}catch{}finish2()}});return new Response(wrapped,{status:response.status,statusText:response.statusText,headers:response.headers})}var ResponsesWsUpstreamError=class extends Error{constructor(message,closeCode2,phase,receivedEvents){super(message);this.closeCode=closeCode2;this.phase=phase;this.receivedEvents=receivedEvents;this.name="ResponsesWsUpstreamError"}closeCode;phase;receivedEvents};function object2(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function describeEventType(frame){if(frame===null)return"null";if(!object2(frame))return Array.isArray(frame)?"array":String(typeof frame);return typeof frame.type==="string"?frame.type:"<missing type>"}function isAzureOpenAiHost(url){try{return new URL(url).hostname.toLowerCase().endsWith(".openai.azure.com")}catch{return false}}function finalizeResponsesWsUpstreamHeaders(url,rawHeaders){const headers=Object.fromEntries(new Headers(rawHeaders).entries());for(const key2 of Object.keys(headers))if(UPSTREAM_HOP_HEADERS.has(key2)||key2.startsWith("sec-websocket-"))delete headers[key2];stripRemoteCompactionBetaFeature(headers);if(isAzureOpenAiHost(url)){for(const key2 of Object.keys(headers))if(key2.startsWith("x-bili-"))delete headers[key2]}return headers}function unsupportedTransportOptions(frame,allowStreamFlag){const offenders=[];if(frame.stream_id!==void 0)offenders.push("stream_id");const badStreamFlag=allowStreamFlag?frame.stream!==void 0&&frame.stream!==true:frame.stream!==void 0;if(badStreamFlag)offenders.push(allowStreamFlag?`stream=${JSON.stringify(frame.stream)} (must be true)`:"stream flag (the lane streams unconditionally)");if(frame.background!==void 0)offenders.push("background");return offenders}function canonical(value){if(Array.isArray(value))return`[${value.map(canonical).join(",")}]`;if(object2(value))return`{${Object.keys(value).filter(k2=>value[k2]!==void 0).sort().map(k2=>`${JSON.stringify(k2)}:${canonical(value[k2])}`).join(",")}}`;return JSON.stringify(value)??"null"}function comparable(item){if(!object2(item))return item;const result={...item};delete result.status;if(!result.type&&typeof result.role==="string")result.type="message";return result}var ECHOABLE_OUTPUT_ITEM_TYPES=new Set(["message","function_call","custom_tool_call","reasoning"]);function computeTailSig(body){try{const{msgs}=responsesToCoreWithToolImages(body);const last=msgs[msgs.length-1];return last?identitySig(last):null}catch{return null}}var ResponsesWsOutput=class{constructor(limitBytes=limitsReceiveBytes()){this.limitBytes=limitBytes}limitBytes;items=new Map;bytes=0;observe(frame){if(frame.type==="response.created"){this.items.clear();this.bytes=0}if(frame.type==="response.output_item.done"&&object2(frame.item)&&Number.isSafeInteger(frame.output_index)&&frame.output_index>=0){const index=frame.output_index;const bytes=Buffer.byteLength(JSON.stringify(frame.item));this.bytes+=bytes-(this.items.get(index)?.bytes??0);if(this.bytes>this.limitBytes)throw new Error("Responses WebSocket checkpoint buffer limit exceeded");this.items.set(index,{item:frame.item,bytes})}if(frame.type!=="response.completed"||!object2(frame.response))return void 0;const response=frame.response;const output=new Map([...this.items].map(([index,value])=>[index,value.item]));const indexes=new Map([...this.items].flatMap(([index,value])=>typeof value.item.id==="string"?[[value.item.id,index]]:[]));if(Array.isArray(response.output)){response.output.forEach((item,index)=>{const slot=object2(item)&&typeof item.id==="string"?indexes.get(item.id):void 0;output.set(slot??index,item)})}return{...response,output:[...output].sort(([a],[b2])=>a-b2).map(([,item])=>item)}}};var ResponsesWsHistory=class{constructor(limitBytes=limitsReceiveBytes()){this.limitBytes=limitBytes}limitBytes;checkpoint;expand(frame){const{type:_type,previous_response_id:previous,...request}=frame;if(typeof request.input==="string")request.input=[{type:"message",role:"user",content:request.input}];if(!Array.isArray(request.input))throw new Error("response.create requires an input array");if(previous!==void 0&&previous!==null){if(previous!==this.checkpoint?.id)throw new Error("previous_response_not_found");const levels=[];let cursor=this.checkpoint;while(cursor){levels.unshift(cursor);cursor=cursor.base}const base=levels[0];if(!base||!Array.isArray(base.request.input))throw new Error("previous_response_not_found");let input=[];for(let i=0;i<levels.length;i++){const level=levels[i];if(i===0&&Array.isArray(level.request.input))input=[...input,...level.request.input];else if(Array.isArray(level.tail))input=[...input,...level.tail];input=[...input,...level.output]}const{generate:_priorGenerate,...topRequest}=levels[levels.length-1].request;return{...topRequest,...request,input:[...input,...request.input]}}return request}continuation(request){const prior=this.checkpoint;if(!prior||!Array.isArray(request.input)||!Array.isArray(prior.request.input))return request;const{input:_input,...fields}=request;const items=request.input;const{input:_priorInput,...priorFields}=prior.request;if(canonical(fields)!==canonical(priorFields))return request;const baseline=[...prior.request.input,...prior.output];if(items.length<=baseline.length||!baseline.every((item,i)=>canonical(comparable(item))===canonical(comparable(items[i]))))return request;return{...fields,input:items.slice(baseline.length),previous_response_id:prior.id}}current(){return this.checkpoint}commit(request,response,opts){if(!object2(response)||response.status!=="completed"||typeof response.id!=="string"||!Array.isArray(response.output))return;if(Buffer.byteLength(JSON.stringify(request))+Buffer.byteLength(JSON.stringify(response.output))>this.limitBytes){this.clear();return}const contId=opts?.continuedId??(typeof request.previous_response_id==="string"?request.previous_response_id:void 0);const prior=this.checkpoint;const chained=contId!==void 0&&prior!==void 0&&contId===prior.id;this.checkpoint={id:response.id,request,output:response.output,...chained&&prior?{base:prior}:{},...opts?.tailSig?{tailSig:opts.tailSig}:{},...opts?.tail?{tail:[...opts.tail]}:{}}}clear(){this.checkpoint=void 0}};function bodyToText(body){if(typeof body==="string")return body;if(Buffer.isBuffer(body))return body.toString("utf8");if(body instanceof ArrayBuffer)return Buffer.from(body).toString("utf8");if(ArrayBuffer.isView(body))return Buffer.from(body.buffer,body.byteOffset,body.byteLength).toString("utf8");return void 0}var ResponsesWsUpstream=class{constructor(log2=()=>{},requestBytes=limitsReceiveBytes(),hopStamp,forwardTransportFields=false){this.log=log2;this.requestBytes=requestBytes;this.hopStamp=hopStamp;this.forwardTransportFields=forwardTransportFields}log;requestBytes;hopStamp;forwardTransportFields;socket;key;history=new ResponsesWsHistory;active;resetHistory(reason){this.history.clear();this.log("debug",`upstream checkpoint reset reason=${reason}`)}close(reason="transport-close"){const socket=this.socket;this.socket=void 0;this.key=void 0;if(this.active)this.active.fail(new Error("Responses WebSocket closed"),reason);else if(socket)this.resetHistory(reason);else this.history.clear();if(socket&&socket.readyState<import_undici3.WebSocket.CLOSING)socket.close()}async connect(url,options){const stamped=Object.fromEntries(new Headers(options.headers).entries());if(this.hopStamp!==void 0&&!Object.keys(stamped).includes(BILI_HOP_HEADER))stamped[BILI_HOP_HEADER]=this.hopStamp;stamped[BILI_TUNNEL_HEADER]="1";const headers=finalizeResponsesWsUpstreamHeaders(url,stamped);const wsUrl=url.replace(/^http/,"ws");const key2=`${wsUrl}:${canonical(Object.fromEntries(Object.entries(headers).filter(([k2])=>!k2.startsWith("x-bili-"))))}`;if(this.key===key2&&this.socket?.readyState===import_undici3.WebSocket.OPEN)return this.socket;this.close(this.key!==key2?"connection-key-changed":"reconnect");this.log("debug","upstream connecting phase=handshake");const socket=new import_undici3.WebSocket(wsUrl,{headers,dispatcher:options.dispatcher});this.socket=socket;this.key=key2;await new Promise((resolve2,reject)=>{const clean=()=>{socket.removeEventListener("open",opened);socket.removeEventListener("error",failed);socket.removeEventListener("close",failed);options.signal?.removeEventListener("abort",aborted)};const opened=()=>{clean();this.log("debug","upstream connected phase=handshake");resolve2()};const failed=event=>{clean();this.log("warn",`upstream failed phase=handshake event=${event.type} close_code=${closeCode(event)}`);reject(new Error("Responses WebSocket handshake failed"))};const aborted=()=>{clean();this.log("debug","upstream aborted phase=handshake");this.close("handshake-abort");reject(new DOMException("Aborted","AbortError"))};socket.addEventListener("open",opened,{once:true});socket.addEventListener("error",failed,{once:true});socket.addEventListener("close",failed,{once:true});if(options.signal?.aborted)aborted();else options.signal?.addEventListener("abort",aborted,{once:true})});return socket}async egressHttp(url,options,body,egressTransportFields){const stamped=Object.fromEntries(new Headers(options.headers).entries());if(this.hopStamp!==void 0&&!Object.keys(stamped).includes(BILI_HOP_HEADER))stamped[BILI_HOP_HEADER]=this.hopStamp;stamped[BILI_TUNNEL_HEADER]="1";const headers=finalizeResponsesWsUpstreamHeaders(url,stamped);headers["content-type"]="application/json";const httpBody={...body,...egressTransportFields,stream:true};const{response,clearTimer}=await fetchWithTimeout(url,{method:"POST",headers,body:JSON.stringify(httpBody),dispatcher:options.dispatcher},void 0,options.signal??void 0,true);return releaseUpstreamWatchdog(response,clearTimer)}async fetch(url,options,rotateRetry=true){const bodyText=bodyToText(options.body);if(options.method!=="POST"||!new URL(url).pathname.endsWith("/responses")||bodyText===void 0)throw new Error("Unsupported request in Responses WebSocket transport");const parsed=JSON.parse(bodyText);if(!object2(parsed)||!Array.isArray(parsed.input))throw new Error("Invalid Responses WebSocket request");const{stream:stream2,stream_options:streamOptions,background:_background,previous_response_id:_previous,type:_type,...body}=parsed;const egressTransportFields={};if(this.forwardTransportFields){if(stream2!==void 0)egressTransportFields.stream=stream2;if(streamOptions!==void 0)egressTransportFields.stream_options=streamOptions}let socket;try{socket=await this.connect(url,options)}catch(error){if(!isHandshakeRefusal(error))throw error;this.close("ws-refused-http-fallback");this.log("debug","upstream egress mode=http reason=ws-handshake-refused");return this.egressHttp(url,options,body,egressTransportFields)}if(this.active)throw new Error("Responses WebSocket exchange already active");const request=this.history.continuation(body);this.log("debug",`upstream request mode=${request.previous_response_id===void 0?"full":"delta"}`);return new Promise((resolve2,reject)=>{const output=new ResponsesWsOutput;let controller;let settled=false;let ended=false;let retryFull=request.previous_response_id!==void 0;let receivedEvents=0;const encoder=new TextEncoder;const sendCreate=payload=>{const frameText=JSON.stringify({...payload,...egressTransportFields,type:"response.create"});this.log("info",`upstream send mode=${payload.previous_response_id===void 0?"full":"delta"} bytes=${Buffer.byteLength(frameText)}`);socket.send(frameText)};let retained=0;const clean=()=>{ended=true;socket.removeEventListener("message",message);socket.removeEventListener("error",failed);socket.removeEventListener("close",failed);options.signal?.removeEventListener("abort",aborted);this.active=void 0};const fail=(error,reason="transport-close")=>{if(ended)return;this.resetHistory(reason);clean();if(settled)controller?.error(error);else reject(error)};const failed=event=>{const phase=receivedEvents>0?"stream":"await-first-event";this.log("warn",`upstream failed phase=${phase} event=${event.type} close_code=${closeCode(event)} received_events=${receivedEvents}`);fail(new ResponsesWsUpstreamError(`Responses WebSocket upstream disconnected before completion (close_code=${closeCode(event)}, received_events=${receivedEvents})`,closeCode(event),phase,receivedEvents),"upstream-disconnect")};const aborted=()=>{this.log("debug",`upstream aborted phase=${receivedEvents>0?"stream":"await-first-event"}`);fail(new DOMException("Aborted","AbortError"),"request-abort");this.close("request-abort")};const message=event=>{if(ended)return;try{if(typeof event.data!=="string"||Buffer.byteLength(event.data)>this.requestBytes)throw new Error("Invalid or oversized Responses WebSocket frame");const frame=JSON.parse(event.data);if(!object2(frame)||typeof frame.type!=="string")throw new Error("Invalid Responses WebSocket event");receivedEvents++;const completed2=output.observe(frame);if(frame.type==="error"&&!settled){const error=object2(frame.error)?frame.error:{};if(rotateRetry&&error.code==="websocket_connection_limit_reached"){this.log("debug","upstream retry reason=connection-limit action=reconnect-full");clean();this.close("connection-limit");resolve2(this.fetch(url,options,false));return}if(retryFull&&(error.code==="previous_response_not_found"||frame.status===400&&(error.code===void 0||error.code==="invalid_request_error"))){retryFull=false;this.resetHistory("continuation-rejected");this.log("debug","upstream retry reason=continuation-rejected action=resend-full");sendCreate(body);return}clean();this.resetHistory("upstream-error");const status=typeof frame.status==="number"&&frame.status>=400&&frame.status<=599?frame.status:400;this.log("warn",`upstream rejected phase=await-first-event status=${status}`);resolve2(new Response(JSON.stringify(frame),{status,headers:{"content-type":"application/json"}}));return}if(stream2!==true){if(frame.type==="response.completed"||frame.type==="response.failed"||frame.type==="response.incomplete"){clean();if(completed2)this.history.clear();else this.resetHistory(frame.type);this.history.commit(body,completed2);resolve2(new Response(JSON.stringify(completed2??frame.response),{headers:{"content-type":"application/json"}}))}else if(frame.type==="error")fail(new Error("Responses WebSocket upstream error"),"upstream-error");return}if(!settled){settled=true;const readable=new ReadableStream({start:c=>{controller=c},cancel:()=>{fail(new DOMException("Aborted","AbortError"),"response-cancel");this.close("response-cancel")}},{highWaterMark:this.requestBytes,size:chunk=>chunk.byteLength});resolve2(new Response(readable,{headers:{"content-type":"text/event-stream"}}))}const block=`event: ${frame.type}
|
|
974
974
|
data: ${event.data}
|
|
975
975
|
|
|
976
|
-
`;const desired=controller?.desiredSize??0;retained=desired>0?this.requestBytes-desired:retained+Buffer.byteLength(block);controller?.enqueue(encoder.encode(block));if(retained>2*this.requestBytes)throw new Error("Responses WebSocket upstream buffer limit exceeded");if(frame.type==="response.completed"||frame.type==="response.failed"||frame.type==="response.incomplete"||frame.type==="error"){clean();if(completed2)this.history.clear();else this.resetHistory(String(frame.type));this.history.commit(body,completed2);controller?.close()}}catch(error){fail(error instanceof Error?error:new Error("Invalid Responses WebSocket event"),"invalid-event");this.close("invalid-event")}};this.active={fail};socket.addEventListener("message",message);socket.addEventListener("error",failed);socket.addEventListener("close",failed);options.signal?.addEventListener("abort",aborted,{once:true});if(options.signal?.aborted)aborted();else{try{sendCreate(request)}catch(error){fail(error instanceof Error?error:new Error("Responses WebSocket send failed"),"send-failed")}}})}};function errorFrame(code,message,status=400){return JSON.stringify({type:"error",status,error:{type:"invalid_request_error",code,message}})}var ResponsesWsResponse=class extends http2.ServerResponse{constructor(req,peer){super(req);this.peer=peer;Object.defineProperty(this,"headersSent",{get:()=>this.sent});Object.defineProperty(this,"writableEnded",{get:()=>this.ended});Object.defineProperty(this,"socket",{get:()=>req.socket})}peer;ended=false;sent=false;buffer="";decoder=new TextDecoder;limitBytes=limitsReceiveBytes();output=new ResponsesWsOutput;response;restoredOutputItems=0;terminal=false;write(chunk,encoding,callback){this.sent=true;const cb=typeof encoding==="function"?encoding:callback;this.buffer+=typeof chunk==="string"?chunk:this.decoder.decode(chunk,{stream:true});if(this.buffer.length>this.limitBytes)throw new Error("Responses WebSocket output buffer limit exceeded");this.buffer=normalizeSseLineEndings(this.buffer);this.drainSse();cb?.();if(this.peer.bufferedAmount>this.limitBytes){this.peer.close(1013,"Output buffer limit exceeded");this.destroy()}return true}drainSse(){let index;while((index=this.buffer.indexOf("\n\n"))>=0){const block=this.buffer.slice(0,index);this.buffer=this.buffer.slice(index+2);const data=block.split("\n").filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trimStart()).join("\n");if(!data||data==="[DONE]")continue;const frame=JSON.parse(data);if(object2(frame)){const completed2=this.output.observe(frame);if(completed2){this.response=completed2;const terminal=object2(frame.response)&&Array.isArray(frame.response.output)?frame.response.output.length:0;this.restoredOutputItems=completed2.output.length-terminal}if(["response.completed","response.failed","response.incomplete","error"].includes(String(frame.type)))this.terminal=true}if(this.peer.readyState===wrapper_default.OPEN)this.peer.send(data,{binary:false})}}end(chunk,encoding,callback){if(this.ended)return this;if(typeof chunk==="string"||chunk instanceof Uint8Array)this.write(chunk);this.buffer=finalizeSseLineEndings(this.buffer);this.drainSse();if(!this.terminal&&this.peer.readyState===wrapper_default.OPEN){let details;try{details=JSON.parse(this.buffer)}catch{details=void 0}this.peer.send(object2(details)?JSON.stringify({...details,type:"error",status:this.statusCode>=400?this.statusCode:502}):errorFrame("incomplete_response","Responses exchange ended without a terminal event",502))}this.ended=true;this.emit("finish");this.emit("close");const cb=typeof chunk==="function"?chunk:typeof encoding==="function"?encoding:callback;if(typeof cb==="function")cb();return this}};var ResponsesWsSession=class{constructor(context){this.context=context;this.transport=new ResponsesWsUpstream(context.log,void 0,context.instanceId,context.codec.allowStreamFlag===true);context.log("info","Responses socket connected (ACP request pipeline)")}context;transport;history=new ResponsesWsHistory;budget=limitsReceiveBytes();active;busy=false;onMessage(data,binary){const peer=this.context.peer;if(binary){peer.close(1003,"Responses requires text frames");return}if(this.busy){this.context.log("warn","client rejected reason=response-in-progress");peer.send(errorFrame("response_in_progress","Only one active response is supported",409));return}const refuse=(code,message,status)=>{this.context.log("warn",`client rejected reason=${code} detail=${message}`);peer.send(errorFrame(code,message,status))};let body;let wire="";let anchoredTailSig;let deltaContinuation;try{const rawFrame=JSON.parse(data.toString());if(!object2(rawFrame)||rawFrame.type!=="response.create"){refuse("invalid_request",`expected a response.create frame, got ${describeEventType(rawFrame)}`,400);return}const frame=rawFrame;const unsupported=unsupportedTransportOptions(frame,this.context.codec.allowStreamFlag);if(unsupported.length>0){refuse("invalid_request",`response.create carries unsupported transport option(s): ${unsupported.join(", ")}`,400);return}const cp2=this.history.current();const continuedId=typeof frame.previous_response_id==="string"?frame.previous_response_id:void 0;const deltaEligible=featureEnabled("wsDeltaContinuation")&&!this.context.source.headers["x-bili-plugin"]&&cp2!==void 0&&continuedId!==void 0&&continuedId===cp2.id&&Array.isArray(frame.input)&&cp2.tailSig!==void 0&&getStore()?.unifiedReads()===true&&cp2.output.every(item=>object2(item)&&ECHOABLE_OUTPUT_ITEM_TYPES.has(String(item.type)));if(deltaEligible){const{type:_type,previous_response_id:_prev,...requestFields}=frame;const{generate:_priorGenerate,...priorRequest}=cp2.request;body={...priorRequest,...requestFields,input:[...cp2.output,...frame.input],stream:true};anchoredTailSig=cp2.tailSig;deltaContinuation={id:continuedId,tail:frame.input}}else{body={...this.history.expand(frame),stream:true}}wire=JSON.stringify(body);if(Buffer.byteLength(wire)>this.budget){refuse("request_too_large",`response.create exceeds the ${Math.round(this.budget/(1024*1024))} MiB request limit`,413);return}}catch(error){if(error instanceof Error&&error.message==="previous_response_not_found"){refuse("previous_response_not_found","Send full input without previous_response_id",400);return}refuse("invalid_request",error instanceof SyntaxError?"response.create frame is not valid JSON":error instanceof Error?error.message:"malformed response.create frame",400);return}this.busy=true;const source=this.context.source;const handshakeHeaders={};const connectionHeaders=connectionNamedHeaders(source.headers.connection);for(const[key2,value]of Object.entries(source.headers)){if(!UPSTREAM_HOP_HEADERS.has(key2)&&!connectionHeaders.has(key2)&&!key2.startsWith("sec-websocket-")&&key2!=="content-encoding")handshakeHeaders[key2]=Array.isArray(value)?value.join(", "):String(value)}if(Array.isArray(body.input)&&body.input.length===0&&body.generate===false){void(async()=>{const sendFrame=payload=>{if(peer.readyState===wrapper_default.OPEN)peer.send(payload)};let sawTerminal=false;try{const response=await this.transport.fetch(this.context.upstreamUrl,{method:"POST",headers:{...handshakeHeaders,"content-type":"application/json"},body:JSON.stringify(body)});if(response.body===null){const text2=await response.text();if(!response.ok){this.history.clear();sendFrame(text2||errorFrame("probe_failed","Warmup failed",response.status>=400?response.status:502));return}sendFrame(text2);return}const reader=response.body.getReader();const decoder=new TextDecoder;let buffer="";for(;;){const{done,value}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:true});if(buffer.length>this.budget)throw new Error("Warmup output buffer limit exceeded");for(;;){const index=buffer.indexOf("\n\n");if(index<0)break;const block=buffer.slice(0,index);buffer=buffer.slice(index+2);for(const line of block.split("\n")){if(!line.startsWith("data: "))continue;const payload=line.slice(6);sendFrame(payload);let frame;try{frame=JSON.parse(payload)}catch{continue}if(!object2(frame))continue;if(["response.completed","response.failed","response.incomplete","error"].includes(String(frame.type))){sawTerminal=true;if(frame.type==="response.completed"&&object2(frame.response))this.history.commit(body,frame.response)}}}}if(!sawTerminal){this.history.clear();sendFrame(response.ok?errorFrame("incomplete_response","Warmup ended without a terminal event",502):errorFrame("probe_failed","Warmup failed",response.status>=400?response.status:502))}}catch{this.history.clear();this.context.log("warn","probe relay failed");sendFrame(errorFrame("invalid_request","Probe relay failed",502))}finally{this.active=void 0;this.busy=false}})();return}const req=new http2.IncomingMessage(source.socket);req.complete=true;req.method="POST";req.url=source.url;Object.assign(req.headers,handshakeHeaders);req.headers["content-type"]="application/json";if(anchoredTailSig!==void 0){Object.defineProperty(req,WS_ANCHORED_REQ_PROP,{value:{tailSig:anchoredTailSig},enumerable:false})}req.push(Buffer.from(wire));req.push(null);const res=new ResponsesWsResponse(req,peer);res.on("error",()=>{});this.active=res;void withFetchTransport(markWsLaneTransport((url,options)=>this.transport.fetch(url,options)),async()=>{try{await this.context.dispatch(req,res);if(res.response){this.history.commit(body,res.response,{tailSig:computeTailSig(body)??void 0,continuedId:deltaContinuation?.id,tail:deltaContinuation?.tail});if(res.restoredOutputItems>0)this.context.log("debug",`checkpoint restored ${res.restoredOutputItems} streamed output item(s) absent from terminal output`)}}catch(error){if(error instanceof SnapshotAnchorFallbackError){this.history.clear();this.context.log("warn",`delta continuation rejected reason=${error.reason} \u2014 requesting full replay`);this.active?.destroy();if(peer.readyState===wrapper_default.OPEN)peer.send(errorFrame("previous_response_not_found","Send full input without previous_response_id",400));return}this.context.log("warn",`exchange failed phase=dispatch terminal=${res.terminal}`);if(!res.writableEnded)res.end()}finally{this.active=void 0;this.busy=false}})}onClose(code){this.context.log("debug",`client closed phase=${this.busy?"active":"idle"} close_code=${code}`);this.active?.destroy();this.transport.close("client-close");this.history.clear();this.context.log("debug","client checkpoint reset reason=client-close")}shutdown(reason){this.transport.close(reason);this.history.clear();this.active?.destroy()}};var responsesCodec={name:"responses-ws",pluginMarker:"opencode",matchUpgrade:url=>/^\/bili\/responses\/(https?:\/\/.*\/responses(?:\?.*)?)$/.exec(url??"")?.[1],createSession:context=>new ResponsesWsSession(context)};var codexResponsesCodec={name:"codex-responses-ws",conversationHeader:"session-id",matchUpgrade:url=>/^\/bili\/(https?:\/\/.*\/responses(?:\?.*)?)$/.exec(url??"")?.[1],allowStreamFlag:true,createSession:context=>new ResponsesWsSession(context)};async function startInlineWsBridge(options){const server2=http3.createServer((req,res)=>{res.writeHead(426,{"content-type":"text/plain; charset=utf-8"});res.end("bili inline WS bridge: WebSocket upgrade required\n")});const upgrade=installWebSocketBridge(server2,options.dispatchHttp,options.log,[responsesCodec,codexResponsesCodec],options.isEgressProxied,options.instanceId);server2.on("upgrade",(source,socket,head)=>{if(upgrade(source,socket,head))return;socket.end("HTTP/1.1 426 Upgrade Required\r\nConnection: close\r\nContent-Length: 0\r\n\r\n")});await new Promise((resolve2,reject)=>{server2.once("error",reject);server2.listen(0,"127.0.0.1",()=>resolve2())});server2.unref();const{port}=server2.address();options.log("info",`[inline] codex WS bridge listening on 127.0.0.1:${port} (loopback only)`);return{origin:`http://127.0.0.1:${port}`,close:()=>new Promise(resolve2=>{server2.close(()=>resolve2())})}}init_dist();import http4 from"http";import fs31 from"fs";import net4 from"net";import tls5 from"tls";import{randomUUID as randomUUID12}from"crypto";import{performance as performance3}from"perf_hooks";init_config();var DEFAULT_COMPRESS_REASONING={drop:true,threshold:2048};function resolveReasoningDrop(cfg){let threshold=DEFAULT_COMPRESS_REASONING.threshold;if(cfg?.threshold!==void 0){const t=cfg.threshold;if(typeof t==="number"&&Number.isFinite(t)&&t>=0){threshold=Math.floor(t)}}return{drop:cfg?.drop!==false,threshold}}function dropCompressReasoningIds(messages,cfg){const{drop,threshold}=resolveReasoningDrop(cfg);const ids=new Set;if(!drop||messages.length===0)return ids;try{const last=messages.length-1;const resultAt=new Map;for(let i=0;i<=last;i++){const m2=messages[i];if(m2.contentType==="tool-result"&&typeof m2.toolCallId==="string"&&!resultAt.has(m2.toolCallId)){resultAt.set(m2.toolCallId,i)}}for(let i=0;i<=last;i++){const m2=messages[i];if(m2.contentType!=="tool-call"||typeof m2.toolName!=="string"||!isMcpBiliCompress(m2.toolName))continue;const ri2=typeof m2.toolCallId==="string"?resultAt.get(m2.toolCallId):void 0;if(ri2===void 0||ri2<=i||ri2>=last)continue;let total=0;let j2=i-1;while(j2>=0&&messages[j2].contentType==="reasoning"){total+=(messages[j2].text??"").length;j2--}if(total>threshold){for(let k2=j2+1;k2<i;k2++)ids.add(messages[k2].id)}}}catch{}return ids}init_config();init_registry();init_fetch_util();init_upstream_proxy();init_upstream_fail();init_log_mask();init_dist();init_config();init_util();function yieldToEventLoop(){return new Promise(resolve2=>setImmediate(resolve2))}var DEFAULT_DECIDE_MAX_TOKENS=200;var DECIDE_TIMEOUT_MS=15e3;var DECIDE_FALLBACK_THRESHOLD=3;var LADDER_KEY="nudgeDecideFails";var RANGE_RE=/^m(\d{4,})-m(\d{4,})$/;var SPANS_SHOWN=8;var TOPIC_MAX_CHARS=80;function formatK3(n){if(n>=1e3)return`${(n/1e3).toFixed(1)}K`;return`${n}`}function buildDecisionPrompt(ranges){const spans=ranges.slice(0,SPANS_SHOWN).map(r=>` ${r.startRef}\u2013${r.endRef} ${r.count} msgs ${formatK3(r.tokens)} [tool ${r.toolPct}% | text ${r.textPct}%]`);return["[bili-compress-decision] Side-channel question \u2014 answer ONLY this. Do not continue your task, do not call any tools.","Given the conversation above exactly as it stands now, is compressing older consumed context NOW net-beneficial for the current task?","Reply with ONLY one line of JSON, nothing else:",'{"compress": false}','or {"compress": true, "range": "mNNNNN-mNNNNN", "topic": "<short topic>"}',"Rules: compress=true only if the task has clearly moved past the targeted content AND reclaiming it is worth more than keeping it verbatim. Prefer a span from the list below when one fits; otherwise cite any older span you can see in the ACP tags above. Do NOT perform the compression now \u2014 only answer.",...spans.length>0?[`Compressible spans (oldest first):`,...spans]:["No pre-detected compressible spans \u2014 judge from the ACP tags above."]].join("\n")}function buildDirectiveText(startRef,endRef,topic){return["[bili-compress-directive] Compress NOW \u2014 this is a directive issued from your own decision above, not a suggestion.",`Target span: ${startRef}\u2013${endRef}${topic?` (topic: "${topic}")`:""}. Call your compress tool on exactly this span in this turn and write the summary per the compression rules. Do not widen or narrow the span unless it contains protected content \u2014 then trim to the unprotected part.`].join("\n")}function parseDecision(raw){let s3=raw.trim();if(!s3)return{kind:"failed",detail:"empty response"};const fence=s3.match(/^```(?:json)?\s*([\s\S]*?)\s*```\s*$/i);if(fence)s3=fence[1].trim();if(!s3.startsWith("{")||!s3.endsWith("}"))return{kind:"failed",detail:"not a bare JSON object"};let obj;try{obj=JSON.parse(s3)}catch(e){return{kind:"failed",detail:`invalid JSON (${String(e)})`}}if(typeof obj!=="object"||obj===null||Array.isArray(obj))return{kind:"failed",detail:"not an object"};const o=obj;if(typeof o.compress!=="boolean")return{kind:"failed",detail:"compress must be boolean"};if(!o.compress)return{kind:"no"};let range;if(o.range!==void 0){if(typeof o.range==="string"&&RANGE_RE.test(o.range))range=o.range;else return{kind:"failed",detail:"malformed range"}}let topic;if(o.topic!==void 0){if(typeof o.topic!=="string")return{kind:"failed",detail:"topic must be a string"};topic=o.topic.trim().slice(0,TOPIC_MAX_CHARS)||void 0}return{kind:"yes",range,topic}}function refNum4(ref){const m2=ref.match(/\d+/);return m2?parseInt(m2[0],10):0}function resolveDecisionRange(decision,ranges){if(ranges.length===0)return void 0;if(decision.range){const m2=decision.range.match(RANGE_RE);if(m2){const a=parseInt(m2[1],10);const b2=parseInt(m2[2],10);if(a<=b2){for(const r of ranges){if(a>=refNum4(r.startRef)&&b2<=refNum4(r.endRef)){return{startRef:r.startRef,endRef:r.endRef}}}}}}let best;for(const r of ranges){if(!best||r.tokens>best.tokens)best=r}return best?{startRef:best.startRef,endRef:best.endRef}:void 0}function ladderMode(metadata){return typeof metadata[LADDER_KEY]==="number"&&metadata[LADDER_KEY]>=DECIDE_FALLBACK_THRESHOLD?"fallback":"try"}function recordDecision(metadata,ok){metadata[LADDER_KEY]=ok?0:(typeof metadata[LADDER_KEY]==="number"?metadata[LADDER_KEY]:0)+1}function consumeFallback(metadata){metadata[LADDER_KEY]=0}function stripDecisionReasoningFields(protocol,body){if(protocol==="openai"){delete body["reasoning_effort"];delete body["reasoning"];delete body["thinking"]}else if(protocol==="anthropic"){delete body["thinking"];delete body["interleaved_thinking"]}else if(protocol==="google"){delete body["thinkingConfig"];const gc=body["generationConfig"];if(gc!==null&&typeof gc==="object")delete gc["thinkingConfig"]}else{delete body["reasoning"]}}function extractDecisionText(protocol,json){if(!json)return"";const parts=[];if(protocol==="anthropic"){const content=json.content;if(Array.isArray(content)){for(const b2 of content){const o=b2;if(o&&o.type==="text"&&typeof o.text==="string")parts.push(o.text)}}}else if(protocol==="openai"){const choices=json.choices;const c0=Array.isArray(choices)?choices[0]:void 0;const msg=c0?c0.message:void 0;if(msg&&typeof msg.content==="string")parts.push(msg.content)}else if(protocol==="google"){const cands=json.candidates;const c0=Array.isArray(cands)?cands[0]:void 0;const cont=c0?c0.content:void 0;const ps2=cont?cont.parts:void 0;if(Array.isArray(ps2)){for(const p2 of ps2){const o=p2;if(o&&typeof o.text==="string")parts.push(o.text)}}}else{if(typeof json.output_text==="string")parts.push(json.output_text);const out=json.output;if(Array.isArray(out)){for(const item of out){const o=item;const c=o?o.content:void 0;if(Array.isArray(c)){for(const b2 of c){const bo2=b2;if(bo2&&bo2.type==="output_text"&&typeof bo2.text==="string")parts.push(bo2.text)}}}}}return parts.join("")}init_dist();init_config();init_logger();init_util();var KEEPALIVE_TIER_5M_MS=3e5;var KEEPALIVE_TIER_1H_MS=36e5;var KEEPALIVE_DEFAULT_TTL_FACTOR=.9;var KEEPALIVE_DEFAULT_MAX_DURATION_MS=864e5;var KEEPALIVE_DEFAULT_MAX_PINGS=4;var PING_TIMEOUT_MS=6e4;var BUSY_RESCHEDULE_MS=5e3;var MAX_FAIL_STREAK=3;var MAX_SNAPSHOT_BYTES=64*1024*1024;function envBool(name){const raw=process.env[name];if(raw===void 0||raw.trim()==="")return void 0;if(raw==="1"||raw.toLowerCase()==="true")return true;if(raw==="0"||raw.toLowerCase()==="false")return false;return void 0}function envNum(name){const raw=process.env[name];if(raw===void 0||raw.trim()==="")return void 0;const n=Number(raw);return Number.isFinite(n)?n:void 0}function fileNum(v2){return typeof v2==="number"&&Number.isFinite(v2)?v2:void 0}function pickMs(envName,fileValue,valid,fallback){const env=envNum(envName);if(env!==void 0&&valid(env))return env;const file=fileNum(fileValue);if(file!==void 0&&valid(file))return file;return fallback}function modelTierPresent(routes,upstreamUrl){const models=routes?findRoute(routes,upstreamUrl)?.models:void 0;if(!models)return false;return Object.values(models).some(e=>e!==null&&typeof e==="object"&&"cacheKeepalive"in e)}function resolveCacheKeepalive(routes,upstreamUrl,model){const g2=loadConfigFile().cacheKeepalive??{};const route=routes?findRoute(routes,upstreamUrl):void 0;const p2=route?.cacheKeepalive??{};const m2=typeof model==="string"&&model.length>0?route?.models?.[model]?.cacheKeepalive??{}:{};const lvl=k2=>m2[k2]!==void 0?m2[k2]:p2[k2]!==void 0?p2[k2]:g2[k2];let assumeTtl;const assumeEnv=process.env["BILI_CACHE_KEEPALIVE_ASSUME_TTL"];if(assumeEnv==="5m"||assumeEnv==="1h")assumeTtl=assumeEnv;else{const l=lvl("assumeTtl");if(l==="5m"||l==="1h")assumeTtl=l}return{enabled:envBool("BILI_CACHE_KEEPALIVE")??lvl("enabled")===true,ttlFactor:pickMs("BILI_CACHE_KEEPALIVE_TTL_FACTOR",lvl("ttlFactor"),n=>n>0&&n<=1,KEEPALIVE_DEFAULT_TTL_FACTOR)??KEEPALIVE_DEFAULT_TTL_FACTOR,maxDurationMs:pickMs("BILI_CACHE_KEEPALIVE_MAX_DURATION_MS",lvl("maxDurationMs"),n=>Number.isInteger(n)&&n>0,KEEPALIVE_DEFAULT_MAX_DURATION_MS)??KEEPALIVE_DEFAULT_MAX_DURATION_MS,maxConcurrentPings:pickMs("BILI_CACHE_KEEPALIVE_MAX_PINGS",lvl("maxConcurrentPings"),n=>Number.isInteger(n)&&n>=1,KEEPALIVE_DEFAULT_MAX_PINGS)??KEEPALIVE_DEFAULT_MAX_PINGS,assumeTtl,armWithoutBreakpoints:envBool("BILI_CACHE_KEEPALIVE_ARM_WITHOUT_BREAKPOINTS")??lvl("armWithoutBreakpoints")===true,intervalMs:pickMs("BILI_CACHE_KEEPALIVE_INTERVAL_MS",lvl("intervalMs"),n=>Number.isInteger(n)&&n>0,void 0)}}function detectKeepaliveTier(body){let found;const walk=n=>{if(found==="1h"||n===null||typeof n!=="object")return;if(Array.isArray(n)){for(const item of n)walk(item);return}const o=n;const cc=o["cache_control"];if(cc&&typeof cc==="object"&&!Array.isArray(cc)){const ttl=cc["ttl"];if(ttl==="1h"){found="1h";return}if(ttl==="5m")found="5m"}for(const v2 of Object.values(o))walk(v2)};walk(body);return found}function buildPingBody(snapshot){const obj=JSON.parse(snapshot);obj["max_tokens"]=1;obj["stream"]=false;return JSON.stringify(obj)}var registry3=new Map;var clock=()=>Date.now();var scheduleFn=(fn,ms2)=>setTimeout(fn,ms2);var cancelFn=id=>clearTimeout(id);function noteSuccessfulForward(inp){try{armInternal(inp)}catch(err2){log("warn",`[${inp.sessionId}] [keepalive] arm failed: ${err2 instanceof Error?err2.message:String(err2)}`)}}function keepaliveStatusFor(sessionId){const e=registry3.get(sessionId);if(!e)return void 0;return{tierLabel:e.tierLabel,cadenceMs:e.cadenceMs,pingCount:e.pingCount,failStreak:e.failStreak,armedAt:e.armedAt,lastRealActivityAt:e.lastRealActivityAt,lastPingAt:e.lastPingAt,lastHitAt:e.lastHitAt}}function armInternal(inp){if(inp.protocol!=="anthropic"||inp.reqMethod!=="POST"||inp.sidePassthrough||inp.resignLane)return;if(typeof inp.wireBody!=="string"||inp.wireBody.length===0)return;if(inp.wireBody.length>MAX_SNAPSHOT_BYTES){log("warn",`[${inp.sessionId}] [keepalive] snapshot skipped: body ${inp.wireBody.length} bytes exceeds ${MAX_SNAPSHOT_BYTES} cap`);return}if(!resolveCacheKeepalive(inp.routes,inp.upstreamUrl).enabled&&!modelTierPresent(inp.routes,inp.upstreamUrl)){disarm(inp.sessionId,"disabled");return}let parsed;try{parsed=JSON.parse(inp.wireBody)}catch{return}if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return;const rec=parsed;const model=typeof inp.model==="string"&&inp.model.length>0?inp.model:typeof rec.model==="string"?rec.model:void 0;const cfg=resolveCacheKeepalive(inp.routes,inp.upstreamUrl,model);if(!cfg.enabled){disarm(inp.sessionId,"disabled");return}const now=clock();const credFp=credentialFingerprint(inp.headers);const prev=registry3.get(inp.sessionId);if(prev&&prev.credFp!==credFp)registry3.delete(inp.sessionId);const breakpointTier=detectKeepaliveTier(parsed);let cadenceMs;let tierLabel2;if(cfg.intervalMs!==void 0){cadenceMs=cfg.intervalMs;tierLabel2=`interval:${cfg.intervalMs}ms`}else if(cfg.assumeTtl){cadenceMs=Math.round((cfg.assumeTtl==="1h"?KEEPALIVE_TIER_1H_MS:KEEPALIVE_TIER_5M_MS)*cfg.ttlFactor);tierLabel2=`${cfg.assumeTtl}(assumed)`}else if(breakpointTier){cadenceMs=Math.round((breakpointTier==="1h"?KEEPALIVE_TIER_1H_MS:KEEPALIVE_TIER_5M_MS)*cfg.ttlFactor);tierLabel2=breakpointTier}else if(cfg.armWithoutBreakpoints){cadenceMs=Math.round(KEEPALIVE_TIER_5M_MS*cfg.ttlFactor);tierLabel2="5m(no-breakpoints)"}else{return}if(!registry3.has(inp.sessionId)&®istry3.size>=cfg.maxConcurrentPings){let oldestId;let oldestAt=Infinity;for(const[id,e]of registry3){if(e.armedAt<oldestAt){oldestAt=e.armedAt;oldestId=id}}if(oldestId!==void 0)disarm(oldestId,"concurrency-cap")}if(prev)cancelFn(prev.timerId);const entry={sessionId:inp.sessionId,body:inp.wireBody,upstreamUrl:inp.upstreamUrl,headers:{...inp.headers},dispatcher:inp.dispatcher,credFp,cadenceMs,tierLabel:tierLabel2,armedAt:now,lastRealActivityAt:now,maxDurationMs:cfg.maxDurationMs,pingCount:0,failStreak:0,timerId:void 0,pingInFlight:false};registry3.set(inp.sessionId,entry);entry.timerId=scheduleFn(()=>{void firePing(entry)},entry.cadenceMs);log("info",`[${entry.sessionId}] [keepalive] armed tier=${tierLabel2} cadence=${Math.round(entry.cadenceMs/1e3)}s body=${Math.ceil(entry.body.length/1024)}KiB`)}async function firePing(entry){if(registry3.get(entry.sessionId)!==entry)return;const now=clock();if(now-entry.lastRealActivityAt>entry.maxDurationMs){disarm(entry.sessionId,"max-duration");return}const session=peekSession(entry.sessionId);if(!session){disarm(entry.sessionId,"session-gone");return}if(entry.pingInFlight||session.inFlight>0){entry.timerId=scheduleFn(()=>{void firePing(entry)},BUSY_RESCHEDULE_MS);return}entry.pingInFlight=true;entry.lastPingAt=clock();let resp;try{resp=await sendPing(entry)}catch(err2){entry.pingInFlight=false;handleFailure(entry,`network: ${err2 instanceof Error?err2.message:String(err2)}`);return}entry.pingInFlight=false;if(registry3.get(entry.sessionId)!==entry)return;const text2=await resp.text().catch(()=>"");if(!resp.ok){if(resp.status===429){disarm(entry.sessionId,"rate-limited(429)");return}handleFailure(entry,`http ${resp.status}: ${text2.slice(0,200)}`);return}let usage;try{const j2=JSON.parse(text2);if(j2&&typeof j2==="object"&&j2.usage&&typeof j2.usage==="object")usage=j2.usage}catch{usage=void 0}const cached=usage?usageTotals("anthropic",usage).cached:void 0;entry.pingCount+=1;if(typeof cached==="number"&&cached>0){entry.failStreak=0;entry.lastHitAt=clock();log("info",`[${entry.sessionId}] [keepalive] ping#${entry.pingCount} hit=${cached}tok`);reschedule(entry)}else{disarm(entry.sessionId,"prefix-dead(cache_read=0)")}}function handleFailure(entry,detail){if(registry3.get(entry.sessionId)!==entry)return;entry.failStreak+=1;log("warn",`[${entry.sessionId}] [keepalive] ping failed (${entry.failStreak}/${MAX_FAIL_STREAK}): ${detail}`);if(entry.failStreak>=MAX_FAIL_STREAK){disarm(entry.sessionId,`errors(${detail})`);return}reschedule(entry)}function reschedule(entry){if(registry3.get(entry.sessionId)!==entry)return;entry.timerId=scheduleFn(()=>{void firePing(entry)},entry.cadenceMs)}async function sendPing(entry){const headers={};for(const[k2,v2]of Object.entries(entry.headers)){const lk=k2.toLowerCase();if(lk==="content-length"||lk==="transfer-encoding"||lk==="connection")continue;headers[k2]=v2}const init={method:"POST",headers,body:buildPingBody(entry.body),signal:AbortSignal.timeout(PING_TIMEOUT_MS)};if(entry.dispatcher)init.dispatcher=entry.dispatcher;return await fetch(entry.upstreamUrl,init)}function disarm(sessionId,reason){const entry=registry3.get(sessionId);if(!entry)return;registry3.delete(sessionId);if(entry.timerId!==void 0)cancelFn(entry.timerId);log("info",`[${sessionId}] [keepalive] disarmed reason=${reason} pings=${entry.pingCount}`)}init_logger();init_upstream_fail();init_log_mask();var ALERT_KINDS=new Set(["connect-timeout","connect-refused","proxy-reset","upstream-reset","dns","tls"]);var MAX_ALERTS=32;var alerts=new Map;function hostOf(url){try{return new URL(url).host}catch{return url}}function keyFor(kind,host){return kind+"\0"+host}function errnoCode(error){const c=typeof error==="object"&&error!==null?error.code:void 0;return typeof c==="string"&&c.length>0?c:void 0}function recordUpstreamAlert(url,error,viaProxy,skipped){const kind=classifyUpstreamFailure(error,{viaProxy});if(!ALERT_KINDS.has(kind))return;const host=hostOf(url);const now=Date.now();const code=errnoCode(error);const key2=keyFor(kind,host);const skippedFields=skipped?{skippedProxy:redactedSkippedProxy(skipped),skippedSource:skipped.source}:{};const hint=hintWithSkippedProxy(kind,skipped);const existing=alerts.get(key2);if(existing){existing.lastSeen=now;existing.count+=1;existing.hint=hint;if(code!==void 0)existing.code=code;Object.assign(existing,skippedFields);return}if(alerts.size>=MAX_ALERTS){let oldestKey;let oldestAt=Infinity;for(const[k2,a]of alerts){if(a.lastSeen<oldestAt){oldestAt=a.lastSeen;oldestKey=k2}}if(oldestKey!==void 0)alerts.delete(oldestKey)}alerts.set(key2,{kind,host,hint,firstSeen:now,lastSeen:now,count:1,...code!==void 0?{code}:{},...skippedFields})}function clearUpstreamAlertsForHost(url){const host=hostOf(url);for(const[key2,a]of alerts){if(a.host===host)alerts.delete(key2)}}function getUpstreamAlerts(){return[...alerts.values()].sort((a,b2)=>b2.lastSeen-a.lastSeen)}var CIRCUIT_OPEN_AFTER=3;var circuitProbeCooldownMs=6e4;var MAX_CIRCUITS=32;var circuits=new Map;function blockReasonText(c,now){const lf=c.lastFailure?` \xB7 last failure ${c.lastFailure.kind}${c.lastFailure.detail?` (${c.lastFailure.detail})`:""} @ ${new Date(c.lastFailure.at).toISOString()}`:"";const waitS=Math.max(0,Math.ceil(((c.nextProbeAt??now)-now)/1e3));return`${maskHostPortForLog(c.host)}: ${c.consecutiveFailures} consecutive pre-response failures since ${new Date(c.openedAt??now).toISOString()}${lf}; next probe ${new Date(c.nextProbeAt??now).toISOString()} (~${waitS}s) \u2014 endpoint unreachable, stop resending full context`}function upstreamCircuitBlockReason(url,now=Date.now()){const entry=circuits.get(hostOf(url));if(!entry||entry.state.openedAt===null)return void 0;const c=entry.state;if(now<(c.nextProbeAt??0))return blockReasonText(c,now);if(entry.probeInFlight)return blockReasonText(c,now);entry.probeInFlight=true;return void 0}function upstreamCircuitLastFailureKind(url){const entry=circuits.get(hostOf(url));if(!entry||entry.state.openedAt===null)return void 0;return entry.state.lastFailure?.kind}var FAIL_FAST_LOG_INTERVAL_MS=6e4;function noteCircuitFailFastLog(url,now=Date.now()){const entry=circuits.get(hostOf(url));if(!entry||entry.state.openedAt===null)return true;if(now-entry.lastFailFastLogAt>=FAIL_FAST_LOG_INTERVAL_MS){entry.lastFailFastLogAt=now;return true}return false}function upstreamCircuitRetryAfterSeconds(url,now=Date.now()){const entry=circuits.get(hostOf(url));if(!entry||entry.state.openedAt===null)return void 0;const np=entry.state.nextProbeAt;if(np===null)return void 0;return Math.max(0,Math.ceil((np-now)/1e3))}function truncateAtBoundary(s3,max){if(!s3)return"";if(s3.length<=max)return s3;const head=s3.slice(0,max);const lastSpace=head.lastIndexOf(" ");return`${lastSpace>0?head.slice(0,lastSpace):head}\u2026`}function recordUpstreamCircuitFailure(url,error,viaProxy,detail){const kind=classifyUpstreamFailure(error,{viaProxy});const host=hostOf(url);const now=Date.now();const code=errnoCode(error);let entry=circuits.get(host);if(!entry){if(!ALERT_KINDS.has(kind))return;if(circuits.size>=MAX_CIRCUITS){let oldestKey;let oldestAt=Infinity;for(const[k2,e]of circuits){const t=e.state.lastFailure?.at??e.state.openedAt??Infinity;if(t<oldestAt){oldestAt=t;oldestKey=k2}}if(oldestKey!==void 0)circuits.delete(oldestKey)}entry={state:{host,consecutiveFailures:0,openedAt:null,nextProbeAt:null,lastFailure:null},probeInFlight:false,lastFailFastLogAt:0};circuits.set(host,entry)}const c=entry.state;const shortDetail=truncateAtBoundary(detail,240);if(c.openedAt!==null){c.lastFailure={kind,detail:shortDetail,at:now,...code!==void 0?{code}:{}};entry.probeInFlight=false;c.nextProbeAt=now+circuitProbeCooldownMs;log("warn",`[acp-proxy] upstream circuit probe FAILED for ${host} (${kind}) \u2014 re-armed until ${new Date(c.nextProbeAt).toISOString()} (#3148)`);return}if(!ALERT_KINDS.has(kind))return;c.lastFailure={kind,detail:shortDetail,at:now,...code!==void 0?{code}:{}};c.consecutiveFailures+=1;if(c.consecutiveFailures>=CIRCUIT_OPEN_AFTER){c.openedAt=now;c.nextProbeAt=now+circuitProbeCooldownMs;log("warn",`[acp-proxy] upstream circuit OPEN for ${host} after ${c.consecutiveFailures} consecutive pre-response failures (last: ${kind}) \u2014 requests to this host fail fast until a probe succeeds (next probe ${new Date(c.nextProbeAt).toISOString()}) (#3148)`)}}function recordUpstreamCircuitSuccess(url){const entry=circuits.get(hostOf(url));if(!entry)return;if(entry.state.openedAt!==null){log("info",`[acp-proxy] upstream circuit CLOSED for ${entry.state.host} \u2014 a response arrived from the endpoint; normal retry ladder resumes (#3148)`)}circuits.delete(entry.state.host)}function getOpenUpstreamCircuits(){return[...circuits.values()].filter(e=>e.state.openedAt!==null).map(e=>({...e.state})).sort((a,b2)=>(b2.openedAt??0)-(a.openedAt??0))}function getUpstreamHealthReport(now=Date.now()){const byHost=new Map;const touch=host=>{let acc=byHost.get(host);if(!acc){acc={alerts:[],circuit:null};byHost.set(host,acc)}return acc};for(const a of alerts.values())touch(a.host).alerts.push(a);for(const e of circuits.values()){if(e.state.openedAt!==null)touch(e.state.host).circuit=e.state}const upstreams=[];for(const[host,{alerts:hostAlerts,circuit}]of byHost.entries()){const latest=hostAlerts.length>0?hostAlerts.reduce((m2,a)=>a.lastSeen>m2.lastSeen?a:m2):void 0;const kind=circuit?.lastFailure?.kind??latest?.kind??"unknown";const code=circuit?.lastFailure?.code??latest?.code;const hint=latest?.hint??circuit?.lastFailure?.detail;const count=circuit?circuit.consecutiveFailures:hostAlerts.reduce((s3,a)=>s3+a.count,0);const beginTimes=[...hostAlerts.map(a=>a.firstSeen),...circuit?[circuit.openedAt??now]:[]];const endTimes=[...hostAlerts.map(a=>a.lastSeen),...circuit?[circuit.lastFailure?.at??now]:[]];let port=null;const colon=host.lastIndexOf(":");if(colon>=0){const p2=Number(host.slice(colon+1));if(Number.isInteger(p2)&&p2>0&&p2<=65535)port=p2}upstreams.push({host,port,kind,...code!==void 0?{code}:{},...hint!==void 0?{hint}:{},count,firstSeen:Math.min(...beginTimes),lastSeen:Math.max(...endTimes),circuit:circuit?{state:"open",nextProbeInMs:Math.max(0,(circuit.nextProbeAt??now)-now)}:null})}upstreams.sort((a,b2)=>b2.lastSeen-a.lastSeen);return{upstreams}}init_logger();init_knobs();var MAX_HOLDS=64;var PROBE_INFLIGHT_TTL_MS=3e4;var RETRY_AFTER_CAP_MS=6e5;var holds=new Map;function parseRetryAfterMs(headerValue3,now){if(headerValue3===null)return null;const v2=headerValue3.trim();if(/^\d+$/.test(v2)){const sec=Number(v2);return Number.isFinite(sec)?Math.min(sec,RETRY_AFTER_CAP_MS/1e3)*1e3:null}const t=Date.parse(v2);if(!Number.isFinite(t))return null;return Math.max(0,Math.min(t-now,RETRY_AFTER_CAP_MS))}function holdKey(url,headers){let host=url;try{host=new URL(url).host}catch{}const cred=credentialFingerprint(headers);return{key:cred===void 0?host:`${host}\0${cred}`,host,cred}}function evictOldest2(){const oldest=holds.keys().next().value;if(oldest!==void 0)holds.delete(oldest)}function makeReject(st2,now){const maxC=throttle429MaxConsecutive();const terminal=st2.streak>=maxC;const secsLeft=Math.max(1,Math.ceil((st2.nextAttemptAt-now)/1e3));if(terminal){const capSec=Math.ceil(throttle429MaxDelayMs()/1e3);return{status:424,code:"bili_throttle_terminal",message:`upstream rate-limited ${st2.streak} consecutive request(s) to ${st2.host}; bili stops amplifying after ${maxC} consecutive rate limits \u2014 resend manually once the provider recovers (a background probe keeps checking at most every ${capSec}s) (#4204)`,retryAfterSec:null,streak:st2.streak,maxConsecutive:maxC,nextAttemptAt:st2.nextAttemptAt,host:st2.host}}return{status:429,code:"bili_throttle_hold",message:`upstream rate-limited ${st2.streak} consecutive request(s) to ${st2.host}; bili is holding outbound sends until ${new Date(st2.nextAttemptAt).toISOString()} (~${secsLeft}s, exponential backoff) instead of amplifying \u2014 zero egress while held, auto-resumes when the limit clears (#4204)`,retryAfterSec:secsLeft,streak:st2.streak,maxConsecutive:maxC,nextAttemptAt:st2.nextAttemptAt,host:st2.host}}function upstreamThrottleLocalReject(url,headers,now=Date.now()){if(!throttle429Enabled())return void 0;const{key:key2}=holdKey(url,headers);const st2=holds.get(key2);if(st2===void 0)return void 0;if(now<st2.nextAttemptAt)return makeReject(st2,now);if(now-st2.probeAt<PROBE_INFLIGHT_TTL_MS)return makeReject(st2,now);st2.probeAt=now;return void 0}function noteUpstreamThrottle429(url,headers,retryAfterHeader,now=Date.now()){if(!throttle429Enabled())return;const{key:key2,host,cred}=holdKey(url,headers);const prev=holds.get(key2);const streak=(prev?.streak??0)+1;const maxC=throttle429MaxConsecutive();const base=throttle429BaseDelayMs();const cap=throttle429MaxDelayMs();const exp=Math.min(cap,base*2**Math.min(streak-1,30));const jittered=exp*(.5+Math.random()*.5);const raMs=parseRetryAfterMs(retryAfterHeader,now);const delay=Math.max(jittered,raMs??0);const nextAttemptAt=now+delay;if(!prev&&holds.size>=MAX_HOLDS)evictOldest2();holds.set(key2,{streak,nextAttemptAt,probeAt:0,host,cred});const delaySec=Math.round(delay/1e3);const raNote=raMs!==null&&raMs>=jittered?", upstream Retry-After honored":"";if(streak===1){log("warn",`[acp-proxy] [429-hold] ${host}: upstream 429 \u2014 arming egress hold (~${delaySec}s backoff+jitter${raNote}) instead of letting host retries amplify (#4204)`)}else if(streak===maxC){log("warn",`[acp-proxy] [429-hold] ${host}: ${streak} consecutive upstream 429s \u2014 hold is TERMINAL: answering locally with 424 (outside SDK retry sets) until a probe succeeds (${raNote.trim()}) (#4204)`)}else{log("info",`[acp-proxy] [429-hold] ${host}: consecutive 429 #${streak} \u2014 hold extended to ~${delaySec}s${raNote} (#4204)`)}}function noteUpstreamThrottleResolved(url,headers,status,now=Date.now()){void now;if(!throttle429Enabled())return;const{key:key2,host}=holdKey(url,headers);const st2=holds.get(key2);if(st2===void 0)return;holds.delete(key2);log("info",`[acp-proxy] [429-hold] ${host}: cleared after HTTP ${status} (was ${st2.streak} consecutive 429s) (#4204)`)}function activeThrottleHolds(){const maxC=throttle429MaxConsecutive();return[...holds.values()].map(st2=>({host:st2.host,streak:st2.streak,nextAttemptAt:st2.nextAttemptAt,terminal:st2.streak>=maxC}))}init_dist();init_dist();import{createHash as createHash26}from"crypto";var REMOTE_IMAGE_TOKENS=4096;var PIXEL_IMAGE_FALLBACK_TOKENS=16384;function resolveImageBilling(mode,_upstreamUrl){if(mode==="bytes")return"bytes";return"pixels"}function effectiveCap(configuredCap){const v2=Number(process.env.BILI_IMAGE_TOKEN_CAP??"");if(Number.isInteger(v2)&&v2>0)return v2;return typeof configuredCap==="number"&&Number.isInteger(configuredCap)&&configuredCap>0?configuredCap:0}function applyCap(cost,configuredCap){const cap=effectiveCap(configuredCap);return cap>0?Math.min(cost,cap):cost}var PNG_SIG=[137,80,78,71];function pngDims(b2){if(b2.length<24||!PNG_SIG.every((v2,i)=>b2[i]===v2))return void 0;const w2=b2.readUInt32BE(16),h=b2.readUInt32BE(20);return w2>0&&h>0?{w:w2,h}:void 0}function gifDims(b2){if(b2.length<10||b2[0]!==71||b2[1]!==73||b2[2]!==70)return void 0;const w2=b2.readUInt16LE(6),h=b2.readUInt16LE(8);return w2>0&&h>0?{w:w2,h}:void 0}function bmpDims(b2){if(b2.length<26||b2[0]!==66||b2[1]!==77)return void 0;const w2=b2.readUInt32LE(18),h=Math.abs(b2.readInt32LE(22));return w2>0&&h>0?{w:w2,h}:void 0}function webpDims(b2){if(b2.length<30||b2.toString("ascii",0,4)!=="RIFF"||b2.toString("ascii",8,12)!=="WEBP")return void 0;const fourcc=b2.toString("ascii",12,16);if(fourcc==="VP8 "){if(b2[23]!==157||b2[24]!==1||b2[25]!==42)return void 0;const w2=b2.readUInt16LE(26)&16383,h=b2.readUInt16LE(28)&16383;return w2>0&&h>0?{w:w2,h}:void 0}if(fourcc==="VP8L"){if(b2[20]!==47)return void 0;const w2=((b2[22]&63)<<8|b2[21])+1,h=((b2[24]&15)<<10|b2[23]<<2|(b2[22]&192)>>6)+1;return w2>0&&h>0?{w:w2,h}:void 0}if(fourcc==="VP8X"){const w2=(b2[24]|b2[25]<<8|b2[26]<<16)+1,h=(b2[27]|b2[28]<<8|b2[29]<<16)+1;return w2>0&&h>0?{w:w2,h}:void 0}return void 0}function jpegDims(b2){if(b2.length<4||b2[0]!==255||b2[1]!==216)return void 0;let off=2;while(off+4<=b2.length){if(b2[off]!==255){off+=1;continue}const marker=b2[off+1];if(marker===216||marker===1||marker>=208&&marker<=217){off+=2;continue}if(marker===218)break;const segLen=b2.readUInt16BE(off+2);if(segLen<2)break;if(marker>=192&&marker<=207&&marker!==196&&marker!==200&&marker!==204){if(off+9>b2.length)break;const h=b2.readUInt16BE(off+5),w2=b2.readUInt16BE(off+7);if(w2>0&&h>0)return{w:w2,h};break}off+=2+segLen}return void 0}var HEADER_SCAN_CHARS=64;var JPEG_SCAN_CHARS=35e4;function decodeImageDims(b64){const head=Buffer.from(b64.slice(0,HEADER_SCAN_CHARS),"base64");for(const parse4 of[pngDims,gifDims,bmpDims,webpDims]){const d=parse4(head);if(d)return d}if(head.length>=2&&head[0]===255&&head[1]===216){return jpegDims(Buffer.from(b64.slice(0,JPEG_SCAN_CHARS),"base64"))}return void 0}var TILE_EDGE=512;var TILE_SHORT_SIDE=768;var TILE_MAX_EDGE=2048;function pixelTileEstimate(w2,h){let sw=w2,sh=h;const shortSide=Math.min(sw,sh);if(shortSide>0&&shortSide<TILE_SHORT_SIDE){const s3=TILE_SHORT_SIDE/shortSide;sw*=s3;sh*=s3}const longSide=Math.max(sw,sh);if(longSide>TILE_MAX_EDGE){const s3=TILE_MAX_EDGE/longSide;sw*=s3;sh*=s3}const tiles=Math.ceil(sw/TILE_EDGE)*Math.ceil(sh/TILE_EDGE);return 85+170*tiles}function base64ImageCost(b64,billing,configuredCap){if(billing==="pixels"){const dims=decodeImageDims(b64);return applyCap(dims?pixelTileEstimate(dims.w,dims.h):PIXEL_IMAGE_FALLBACK_TOKENS,configuredCap)}return applyCap(Math.ceil(b64.length/4),configuredCap)}function costForUrl(url,billing,configuredCap){if(url.startsWith("data:")){const i=url.indexOf("base64,");if(i>=0)return base64ImageCost(url.slice(i+"base64,".length),billing,configuredCap)}return applyCap(REMOTE_IMAGE_TOKENS,configuredCap)}function isObj(v2){return typeof v2==="object"&&v2!==null}function urlOf(v2){if(typeof v2==="string")return v2;if(isObj(v2)&&typeof v2.url==="string")return v2.url;return void 0}function opaquePartCost(part,configuredCap){return applyCap(Math.ceil(JSON.stringify(part).length/4),configuredCap)}function imageTokensInParsedBody(protocol,body,billing="bytes",configuredCap){if(!isObj(body))return 0;let total=0;if(protocol==="google"){const contents=body.contents;if(!Array.isArray(contents))return 0;for(const c of contents){if(!isObj(c)||!Array.isArray(c.parts))continue;for(const part of c.parts){if(!isObj(part))continue;const inline=part.inlineData;if(isObj(inline)&&typeof inline.data==="string"){total+=base64ImageCost(inline.data,billing,configuredCap);continue}const file=part.fileData;if(isObj(file)&&typeof file.fileUri==="string"){total+=costForUrl(file.fileUri,billing,configuredCap);continue}if(typeof part.text==="string"||isObj(part.functionCall)||isObj(part.functionResponse)||isObj(part.videoMetadata))continue;total+=opaquePartCost(part,configuredCap)}}return total}if(protocol==="responses"){const input=body.input;if(!Array.isArray(input))return 0;for(const item of input){if(!isObj(item))continue;const parts=Array.isArray(item.content)?item.content:responsesToolImageParts(item);if(!parts){continue}for(const part of parts){if(!isObj(part))continue;if(part.type==="input_image"){const url=urlOf(part.image_url);if(url)total+=costForUrl(url,billing,configuredCap);continue}if(item.type==="message"&&item.role==="user"&&part.type!=="input_text"&&part.type!=="output_text"){total+=opaquePartCost(part,configuredCap)}}}return total}const messages=body.messages;if(!Array.isArray(messages))return 0;for(const m2 of messages){if(!isObj(m2)||!Array.isArray(m2.content))continue;for(const part of m2.content){if(!isObj(part))continue;if(protocol==="openai"){if(part.type==="image_url"){const url=urlOf(part.image_url);if(url)total+=costForUrl(url,billing,configuredCap);continue}if(part.type==="file"){const f2=isObj(part.file)?part.file:{};const ref=typeof f2.file_data==="string"?f2.file_data:typeof f2.url==="string"?f2.url:void 0;total+=ref?costForUrl(ref,billing,configuredCap):applyCap(REMOTE_IMAGE_TOKENS,configuredCap);continue}if(part.type==="text")continue;if(m2.role==="user")total+=opaquePartCost(part,configuredCap);continue}else{if(part.type==="image"){const src=part.source;if(isObj(src)&&src.type==="base64"&&typeof src.data==="string")total+=base64ImageCost(src.data,billing,configuredCap);else if(isObj(src)&&src.type==="url"&&typeof src.url==="string")total+=costForUrl(src.url,billing,configuredCap);continue}if(part.type==="redacted_thinking"&&typeof part.data==="string"){total+=applyCap(Math.ceil(part.data.length/4),configuredCap);continue}if(part.type==="tool_result"&&Array.isArray(part.content)){for(const c of part.content){if(!isObj(c)||c.type==="text")continue;const src=c.source;if(isObj(src)&&src.type==="base64"&&typeof src.data==="string")total+=base64ImageCost(src.data,billing,configuredCap);else if(isObj(src)&&src.type==="url"&&typeof src.url==="string")total+=costForUrl(src.url,billing,configuredCap);else total+=opaquePartCost(c,configuredCap)}continue}}}}return total}function bodyHasImagesProbe(protocol,s3){return protocol==="google"?s3.includes("inlineData")||s3.includes("fileData"):protocol==="responses"?s3.includes("input_image")||s3.includes('"content":[')||s3.includes('"content": ['):protocol==="openai"?s3.includes("image_url")||s3.includes('"type":"file"')||s3.includes('"type": "file"')||s3.includes('"content":[')||s3.includes('"content": ['):s3.includes('"type":"image"')||s3.includes('"type": "image"')||s3.includes('"type":"redacted_thinking"')||s3.includes('"type":"document"')}function imageTokensInRawBody(protocol,raw,billing="bytes",configuredCap){const s3=typeof raw==="string"?raw:raw.toString("utf8");if(!bodyHasImagesProbe(protocol,s3))return 0;try{return imageTokensInParsedBody(protocol,JSON.parse(s3),billing,configuredCap)}catch{return 0}}function upstreamHost(url){if(!url)return"unknown";try{return new URL(url).hostname.toLowerCase()}catch{return url.toLowerCase()}}function countImagesInParsedBody(protocol,body){if(!isObj(body))return 0;let n=0;if(protocol==="google"){const contents=body.contents;if(!Array.isArray(contents))return 0;for(const c of contents){if(!isObj(c)||!Array.isArray(c.parts))continue;for(const part of c.parts){if(!isObj(part))continue;const inline=part.inlineData;if(isObj(inline)&&typeof inline.data==="string"){n+=1;continue}const file=part.fileData;if(isObj(file)&&typeof file.fileUri==="string"){n+=1;continue}if(typeof part.text==="string"||isObj(part.functionCall)||isObj(part.functionResponse)||isObj(part.videoMetadata))continue;n+=1}}return n}if(protocol==="responses"){const input=body.input;if(!Array.isArray(input))return 0;for(const item of input){if(!isObj(item))continue;const parts=Array.isArray(item.content)?item.content:responsesToolImageParts(item);if(!parts)continue;for(const part of parts){if(!isObj(part))continue;if(part.type==="input_image"){if(urlOf(part.image_url))n+=1;continue}if(item.type==="message"&&item.role==="user"&&part.type!=="input_text"&&part.type!=="output_text")n+=1}}return n}const messages=body.messages;if(!Array.isArray(messages))return 0;for(const m2 of messages){if(!isObj(m2)||!Array.isArray(m2.content))continue;for(const part of m2.content){if(!isObj(part))continue;if(protocol==="openai"){if(part.type==="image_url"){if(urlOf(part.image_url))n+=1;continue}if(part.type==="file"){n+=1;continue}if(part.type==="text")continue;if(m2.role==="user")n+=1;continue}else{if(part.type==="image"){const src=part.source;if(isObj(src)&&src.type==="base64"&&typeof src.data==="string")n+=1;else if(isObj(src)&&src.type==="url"&&typeof src.url==="string")n+=1;continue}if(part.type==="redacted_thinking"&&typeof part.data==="string"){n+=1;continue}if(part.type==="tool_result"&&Array.isArray(part.content)){for(const c of part.content){if(!isObj(c)||c.type==="text")continue;n+=1}continue}}}}return n}function countImagesInRawBody(protocol,raw){const s3=typeof raw==="string"?raw:raw.toString("utf8");if(!bodyHasImagesProbe(protocol,s3))return 0;try{return countImagesInParsedBody(protocol,JSON.parse(s3))}catch{return 0}}var IMAGE_PLACEHOLDER="[image]";function isObj2(v2){return typeof v2==="object"&&v2!==null}function refFromDataUrl(url){if(typeof url!=="string")return void 0;const d=parseDataUrl(url);return d?{mediaType:d.mediaType,b64:d.base64}:void 0}function opaqueLabel(part){const t=typeof part.type==="string"?part.type:"media";const kb=Math.max(1,Math.round(JSON.stringify(part).length/1024));return`${t} ~${kb}KB`}function messageImages(m2){const mm=m2;const ab2=mm.rawAnthropicBlock;if(isObj2(ab2)&&ab2.type==="image"){const s3=ab2.source;const mediaType=isObj2(s3)&&typeof s3.media_type==="string"?s3.media_type:void 0;if(isObj2(s3)&&s3.type==="base64"&&typeof s3.data==="string"){return[{mediaType,b64:s3.data}]}if(isObj2(s3)&&s3.type==="url"){return[refFromDataUrl(s3.url)??{mediaType}]}return[{mediaType}]}if(isObj2(ab2)&&ab2.type==="tool_result"&&Array.isArray(ab2.content)){const refs=[];for(const c of ab2.content){if(!isObj2(c)||c.type==="text")continue;const s3=c.source;if(isObj2(s3)&&s3.type==="base64"&&typeof s3.data==="string"){refs.push({mediaType:isObj2(s3)&&typeof s3.media_type==="string"?s3.media_type:void 0,b64:s3.data})}else if(isObj2(s3)&&s3.type==="url"){refs.push(refFromDataUrl(s3.url)??{})}else{refs.push({label:opaqueLabel(c)})}}if(refs.length>0)return refs}const ri2=mm.rawResponsesItem;const responseParts=isObj2(ri2)&&Array.isArray(ri2.content)?ri2.content:responsesToolImageParts(ri2);if(responseParts){const refs=[];for(const part of responseParts){if(!isObj2(part)||part.type!=="input_image")continue;refs.push(refFromDataUrl(part.image_url)??{})}if(refs.length>0)return refs}if(typeof mm.imageBase64==="string"){return[{mediaType:mm.imageMediaType,b64:mm.imageBase64}]}if(Array.isArray(mm.rawOpenaiContentParts)){const refs=[];for(const p2 of mm.rawOpenaiContentParts){if(!isObj2(p2))continue;if(p2.type==="image_url"){refs.push(refFromDataUrl(isObj2(p2.image_url)?p2.image_url.url:void 0)??{});continue}refs.push({label:opaqueLabel(p2)})}if(refs.length>0)return refs}if(isObj2(mm.rawOpenaiContent)&&mm.rawOpenaiContent.type==="image_url"){return[refFromDataUrl(isObj2(mm.rawOpenaiContent.image_url)?mm.rawOpenaiContent.image_url.url:void 0)??{}]}return[]}function imagePlaceholders(m2){return messageImages(m2).map(ref=>{if(ref.label&&!ref.b64)return`[media: ${ref.label}]`;let note="";if(ref.mediaType)note+=ref.mediaType.includes("/")?ref.mediaType.split("/").pop():ref.mediaType;if(ref.b64){const dims=decodeImageDims(ref.b64);if(dims)note+=`${note?" ":""}${dims.w}x${dims.h}`}return note?`[image: ${note}]`:IMAGE_PLACEHOLDER})}function imagePlaceholdersForSummary(m2,ref){const notes=imagePlaceholders(m2);if(ref===void 0)return notes;return notes.map(n=>`${n.slice(0,-1)} \xB7 ${ref}]`)}init_dist();init_dist();init_logger();init_proxy_tool_result();var EFFECTIVE_RULES_KEY="effectiveRules";function rulesEnabled(config){return config.rules?.enabled===true}function effectiveRulesConfig(session,fallback){const meta=session?.metadata[EFFECTIVE_RULES_KEY];if(meta&&typeof meta==="object"&&typeof meta.enabled==="boolean"){return meta}return fallback.rules}function storeEffectiveRules(session,config){session.metadata[EFFECTIVE_RULES_KEY]=config.rules??null}function effectiveRulesEnabled(session,fallback){return effectiveRulesConfig(session,fallback)?.enabled===true}function executeRule(args,ctx){const log2=ctx.log??(msg=>log("info",msg));const state7=ctx.session.state;const rawDelete=args.delete;const delId=typeof rawDelete==="string"?rawDelete.trim():"";const wantsClear=args.clear===true;const raw=args.rule;const rule=typeof raw==="string"?raw.trim():"";const ops=[delId.length>0,wantsClear,rule.length>0].filter(Boolean).length;if(ops>1){return toolFail("Use one operation per call: record (rule), remove one (delete), remove all (clear: true), or list (no arguments).")}if(wantsClear){const result2=clearRules(state7);log2(`[acp-rule] cleared ${result2.count} rule(s)`);return toolOk(result2.count===0?"No rules to clear.":`Cleared ${result2.count} rule(s).`)}if(delId.length>0){const result2=removeRule(state7,delId);if(!result2.ok){log2(`[acp-rule] ${result2.error}`);return toolFail(result2.error)}log2(`[acp-rule] removed ${result2.rule.id}: ${result2.rule.text}`);return toolOk(`Removed ${result2.rule.id}: ${result2.rule.text}`)}if(rule.length===0){const rules=listRules(state7);return toolOk(rules.length===0?"No rules recorded.":formatRulesList(rules))}const result=addRule(state7,rule,resolveRuleLimits(ctx.config));if(!result.ok){log2(`[acp-rule] ${result.error}`);return toolFail(result.error)}log2(`[acp-rule] added ${result.rule.id}: ${result.rule.text}`);return toolOk(`Recorded ${result.rule.id}: ${result.rule.text}`)}init_logger();init_proxy_tool_result();var EFFECTIVE_ABSORB_KEY="effectiveAbsorb";function absorbEnabled(config){return config.absorb?.enabled===true}function absorbToolName(config){return config.absorb?.toolName??ABSORB_TOOL_NAME}function effectiveAbsorbConfig(session,fallback){const meta=session?.metadata[EFFECTIVE_ABSORB_KEY];if(meta&&typeof meta==="object"&&typeof meta.enabled==="boolean"){return meta}return fallback.absorb}function storeEffectiveAbsorb(session,config){session.metadata[EFFECTIVE_ABSORB_KEY]=config.absorb??null}function isProxyToolFor(name,session,config){if(ACP_TOOL_NAMES.has(name))return true;if(name===READ_ORIGINAL_IMAGE_TOOL_NAME)return true;const absorb=effectiveAbsorbConfig(session,config);if(absorb?.enabled===true&&name===(absorb.toolName??ABSORB_TOOL_NAME))return true;if(ccrEnabled(session)&&name===retrieveToolName(session))return true;return effectiveRulesEnabled(session,config)&&name===RULE_TOOL_NAME}function applyAbsorbView(messages,state7,config,tokenCount){const hidden=hideAbsorbedMessages(messages,state7);const prompted=appendAbsorbPrompts(hidden,state7,config,tokenCount,defaultCountTokens);return prompted.messages}function executeAbsorb(args,callId,absorb,ctx){const log2=ctx.log??(msg=>log("info",msg));const parsed=parseAbsorbInput(args,callId,w2=>log2(`[acp-absorb] ${w2}`));if(!parsed){return toolFail('[absorb FAILED: invalid input \u2014 expected { ref: "mNNNNN", summary: "..." }]')}const before=ctx.session.state.absorbed?.length??0;let outcome;try{outcome=applyAbsorb({ref:parsed.ref,summary:parsed.summary,absorbCallId:parsed.absorbCallId,messages:ctx.messages,state:ctx.session.state,config:{...ctx.config,absorb}})}catch(err2){log2(`[acp-absorb] error: ${String(err2)}`);return toolFail(`[absorb FAILED: ${String(err2)}]`)}ctx.session.state=outcome.state;if(!outcome.ok){log2(`[acp-absorb] ${outcome.resultText}`);return toolFail(`[absorb FAILED: ${outcome.resultText}]`)}const records=outcome.state.absorbed??[];const record4=records.length>before?records[records.length-1]:void 0;if(record4){ctx.session.stats.compressCreditTokens=(ctx.session.stats.compressCreditTokens??0)+record4.tokensReclaimed;ctx.session.stats.lastInputTokens=Math.max(0,ctx.session.stats.lastInputTokens-record4.tokensReclaimed);log2(`[acp-absorb] ${outcome.resultText} (credit -${record4.tokensReclaimed} tok)`)}else{log2(`[acp-absorb] ${outcome.resultText}`)}return toolOk(outcome.resultText)}init_dist();init_config();import{createHash as createHash25,randomBytes as randomBytes3}from"crypto";init_dist();import{existsSync as existsSync10,mkdirSync as mkdirSync10,unlinkSync as unlinkSync4,writeFileSync as writeFileSync9}from"fs";import{dirname as dirname5,join as join10,resolve as resolvePath}from"path";import{tmpdir}from"os";import{fileURLToPath as fileURLToPath5}from"url";init_text_safe();init_knobs();init_proxy_tool_result();import{existsSync as existsSync9,mkdirSync as mkdirSync9,readdirSync as readdirSync4,rmdirSync,statSync as statSync7,unlinkSync as unlinkSync3,writeFileSync as writeFileSync8}from"fs";import{createHash as createHash24}from"crypto";import{join as join9}from"path";init_logger();init_paths();function isObj3(v2){return typeof v2==="object"&&v2!==null}function dataUrlRef(url){if(typeof url!=="string")return void 0;const d=parseDataUrl(url);return d?{mediaType:d.mediaType,b64:d.base64}:void 0}function b64Bytes(b64){return Math.floor(Buffer.byteLength(b64,"base64")||0)}function messageImageBytes(m2){const mm=m2;const out=[];const ab2=mm.rawAnthropicBlock;if(isObj3(ab2)&&ab2.type==="image"){const s3=ab2.source;const mediaType=isObj3(s3)&&typeof s3.media_type==="string"?s3.media_type:"image/png";if(isObj3(s3)){if(s3.type==="base64"&&typeof s3.data==="string"){out.push({mediaType,b64:s3.data,bytes:b64Bytes(s3.data)})}else if(s3.type==="url"){const r=dataUrlRef(s3.url);if(r?.b64)out.push({mediaType:r.mediaType??mediaType,b64:r.b64,bytes:b64Bytes(r.b64)})}}return out}if(isObj3(ab2)&&ab2.type==="tool_result"&&Array.isArray(ab2.content)){for(const c of ab2.content){if(!isObj3(c)||c.type!=="image")continue;const s3=c.source;const mediaType=isObj3(s3)&&typeof s3.media_type==="string"?s3.media_type:"image/png";if(!isObj3(s3))continue;if(s3.type==="base64"&&typeof s3.data==="string"){out.push({mediaType,b64:s3.data,bytes:b64Bytes(s3.data)})}else if(s3.type==="url"){const r=dataUrlRef(s3.url);if(r?.b64)out.push({mediaType:r.mediaType??mediaType,b64:r.b64,bytes:b64Bytes(r.b64)})}}return out}const ri2=mm.rawResponsesItem;if(isObj3(ri2)){const arr=ri2.type==="function_call_output"||ri2.type==="custom_tool_call_output"?Array.isArray(ri2.output)?ri2.output:void 0:Array.isArray(ri2.content)?ri2.content:void 0;if(arr){for(const part of arr){if(!isObj3(part)||part.type!=="input_image")continue;const u2=isObj3(part.image_url)?part.image_url.url:part.image_url;const r=dataUrlRef(u2);if(r?.b64)out.push({mediaType:r.mediaType??"image/png",b64:r.b64,bytes:b64Bytes(r.b64)})}if(out.length>0)return out}}if(Array.isArray(mm.rawGoogleParts)){for(const part of mm.rawGoogleParts){if(!isObj3(part))continue;const inline=part.inlineData;if(isObj3(inline)&&typeof inline.data==="string"){const mediaType=typeof inline.mimeType==="string"?inline.mimeType:"image/png";out.push({mediaType,b64:inline.data,bytes:b64Bytes(inline.data)})}const fr2=part.functionResponse;if(isObj3(fr2)&&Array.isArray(fr2.parts)){const refGuarded=JSON.stringify(fr2.response??null).includes('"$ref"');if(!refGuarded){for(const np of fr2.parts){if(!isObj3(np))continue;const ni2=np.inlineData;if(isObj3(ni2)&&typeof ni2.data==="string"&&typeof ni2.mimeType==="string"&&ni2.mimeType.startsWith("image/")){out.push({mediaType:ni2.mimeType,b64:ni2.data,bytes:b64Bytes(ni2.data)})}}}}}if(out.length>0)return out}if(Array.isArray(mm.rawOpenaiContentParts)){for(const p2 of mm.rawOpenaiContentParts){if(!isObj3(p2)||p2.type!=="image_url")continue;const u2=isObj3(p2.image_url)?p2.image_url.url:void 0;const r=dataUrlRef(u2);if(r?.b64)out.push({mediaType:r.mediaType??"image/png",b64:r.b64,bytes:b64Bytes(r.b64)})}if(out.length>0)return out}if(isObj3(mm.rawOpenaiContent)&&mm.rawOpenaiContent.type==="image_url"){const u2=isObj3(mm.rawOpenaiContent.image_url)?mm.rawOpenaiContent.image_url.url:void 0;const r=dataUrlRef(u2);if(r?.b64)out.push({mediaType:r.mediaType??"image/png",b64:r.b64,bytes:b64Bytes(r.b64)});if(out.length>0)return out}if(typeof mm.imageBase64==="string"){out.push({mediaType:typeof mm.imageMediaType==="string"?mm.imageMediaType:"image/png",b64:mm.imageBase64,bytes:b64Bytes(mm.imageBase64)})}return out}function coreMsgsOf(result){if(Array.isArray(result))return result;if(isObj3(result)&&Array.isArray(result.msgs)){return result.msgs}return void 0}function bodyMightCarryImages(bodyText,protocol){switch(protocol){case"anthropic":return/"data:[^;,"]+(?:;base64)?,/i.test(bodyText)||/"type"\s*:\s*"base64"/.test(bodyText);case"google":return/"inlineData"\s*:/.test(bodyText);default:return/"data:[^;,"]+(?:;base64)?,/i.test(bodyText)}}var conversionWarned=new Set;function buildIncomingImageIndex(parsed,protocol,state7,sessionId){const index=new Map;const byRaw=state7?.messageRefs?.byRaw;if(!byRaw)return index;let result;try{switch(protocol){case"anthropic":result=anthropicToCore(parsed);break;case"openai":result=openaiToCore(parsed);break;case"google":result=googleToCore(parsed);break;case"responses":result=responsesToCore(parsed);break}}catch(e){const sig=`${protocol}:${String(e?.message??e).slice(0,120)}`;if(!conversionWarned.has(sig)){conversionWarned.add(sig);log("warn",`[image-restore] inbound index conversion failed \u2014 images in affected sessions are NOT recoverable until this wire shape is handled (${sig}; #2824 class \u2014 please report the body shape)`)}return index}const msgs=coreMsgsOf(result);if(!msgs)return index;for(const m2 of msgs){const ref=m2.id?byRaw[m2.id]:void 0;if(!ref)continue;const imgs=messageImageBytes(m2);if(imgs.length===0)continue;const arr=index.get(ref)??[];if(!index.has(ref))index.set(ref,arr);imgs.forEach((im,i)=>{const path53=writeRestoredImage(ref,i,im,sessionId);if(!path53)return;let width;let height;try{const d=decodeImageDims(im.b64);if(d){width=d.w;height=d.h}}catch{}arr.push({mediaType:im.mediaType,bytes:im.bytes,width,height,path:path53})})}return index}function refreshIncomingImageIndex(parsed,protocol,state7,sessionId,existing){const fresh=buildIncomingImageIndex(parsed,protocol,state7,sessionId);if(fresh.size===0)return existing??new Map;const merged=existing?new Map(existing):new Map;const seen=new Set;for(const imgs of merged.values())for(const im of imgs)seen.add(im.path);for(const[ref,imgs]of fresh){const kept=imgs.filter(im=>!seen.has(im.path));if(kept.length===0)continue;for(const im of kept)seen.add(im.path);const prev=merged.get(ref);merged.set(ref,prev?[...prev,...kept]:kept)}return merged}function pruneRetrieveImgExports(sessionId,ttlMs=7*24*3600*1e3){const dir=restoreExportDir(sessionId);let entries2;try{entries2=readdirSync4(dir)}catch{return 0}const now=Date.now();let removed=0;for(const name of entries2){const p2=join9(dir,name);try{const st2=statSync7(p2);if(st2.isFile()&&now-st2.mtimeMs>ttlMs){unlinkSync3(p2);removed++}}catch{}}if(removed>0){try{if(readdirSync4(dir).length===0)rmdirSync(dir)}catch{}}return removed}function refNum5(ref){const m2=/^m(\d+)$/i.exec(ref.trim());return m2?Number.parseInt(m2[1],10):Number.MAX_SAFE_INTEGER}function describeRestorable(index,cap=50){const lines=[];const refs=[...index.keys()].sort((a,b2)=>refNum5(a)-refNum5(b2));outer:for(const ref of refs){const imgs=index.get(ref);for(let i=0;i<imgs.length;i++){const im=imgs[i];let note=im.mediaType.includes("/")?im.mediaType.split("/").pop():im.mediaType;if(im.width!=null&&im.height!=null)note+=` ${im.width}x${im.height}`;note+=` \xB7 ${Math.max(1,Math.round(im.bytes/1024))}KB`;lines.push(`${ref}${i>0?`[-${i}]`:""} [${note}]`);if(lines.length>=cap)break outer}}return lines}function restoreExportDirName(sessionId){const safe=sessionId.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,100);return safe===sessionId?safe||"session":`${safe||"session"}-${createHash24("sha256").update(sessionId).digest("hex").slice(0,8)}`}function restoreExportDir(sessionId){return join9(stateDir(),"retrieve","img",restoreExportDirName(sessionId))}function extFor(mediaType){const sub=(mediaType.split("/")[1]??"").toLowerCase();const map={png:"png",jpeg:"jpg",jpg:"jpg",gif:"gif",webp:"webp",svg:"svg"};return map[sub]??"img"}function writeRestoredImage(ref,idx,img,sessionId){const safeRef=ref.replace(/[^a-zA-Z0-9_-]/g,"-");const dir=restoreExportDir(sessionId);const body=Buffer.from(img.b64,"base64");const digest=createHash24("sha256").update(body).digest("hex").slice(0,8);const path53=join9(dir,`${safeRef}${idx>0?`-${idx}`:""}-${digest}.${extFor(img.mediaType)}`);try{if(existsSync9(path53))return path53;mkdirSync9(dir,{recursive:true});writeFileSync8(path53,body,{mode:384});return path53}catch(e){log("warn",`[image-restore] write failed (${path53}): ${String(e)}`);return null}}var trackedTempFiles=[];function getDecompressTmpCap(){return decompressTmpCap()}function reapTempFiles(){const cap=getDecompressTmpCap();while(trackedTempFiles.length>cap){trackedTempFiles.sort((a,b2)=>a.mtimeMs-b2.mtimeMs);const oldest=trackedTempFiles.shift();if(!oldest)break;try{unlinkSync4(oldest.path)}catch{}}}process.on("beforeExit",()=>{for(const f2 of trackedTempFiles){try{unlinkSync4(f2.path)}catch{}}trackedTempFiles.length=0});function resolveToFileTarget(target){const uri=target.match(/^([a-zA-Z][a-zA-Z0-9+.\-]*):\/\//);if(uri&&uri[1].length>=2){const scheme=uri[1].toLowerCase();if(scheme==="file"){try{return{resolved:fileURLToPath5(new URL(target))}}catch(e){return{refusal:`malformed file:// URI "${target}" (${String(e)})`}}}return{refusal:`unsupported virtual URI scheme "${scheme}" in toFile "${target}" \u2014 bili writes to the local filesystem only; pass an actual filesystem path (absolute, or relative to the proxy cwd) or a file:// URI`}}return{resolved:resolvePath(target)}}function exportFailureReceipt(path53,err2,body){const preview=safePrefix(body,4e3);const scope=preview.length<body.length?`partial content follows (${preview.length} of ${body.length} chars)`:"full content follows";return toolFail(`[decompress FAILED: could not write export to ${path53}: ${String(err2)}]
|
|
976
|
+
`;const desired=controller?.desiredSize??0;retained=desired>0?this.requestBytes-desired:retained+Buffer.byteLength(block);controller?.enqueue(encoder.encode(block));if(retained>2*this.requestBytes)throw new Error("Responses WebSocket upstream buffer limit exceeded");if(frame.type==="response.completed"||frame.type==="response.failed"||frame.type==="response.incomplete"||frame.type==="error"){clean();if(completed2)this.history.clear();else this.resetHistory(String(frame.type));this.history.commit(body,completed2);controller?.close()}}catch(error){fail(error instanceof Error?error:new Error("Invalid Responses WebSocket event"),"invalid-event");this.close("invalid-event")}};this.active={fail};socket.addEventListener("message",message);socket.addEventListener("error",failed);socket.addEventListener("close",failed);options.signal?.addEventListener("abort",aborted,{once:true});if(options.signal?.aborted)aborted();else{try{sendCreate(request)}catch(error){fail(error instanceof Error?error:new Error("Responses WebSocket send failed"),"send-failed")}}})}};function errorFrame(code,message,status=400){return JSON.stringify({type:"error",status,error:{type:"invalid_request_error",code,message}})}var ResponsesWsResponse=class extends http2.ServerResponse{constructor(req,peer){super(req);this.peer=peer;Object.defineProperty(this,"headersSent",{get:()=>this.sent});Object.defineProperty(this,"writableEnded",{get:()=>this.ended});Object.defineProperty(this,"socket",{get:()=>req.socket})}peer;ended=false;sent=false;buffer="";decoder=new TextDecoder;limitBytes=limitsReceiveBytes();output=new ResponsesWsOutput;response;restoredOutputItems=0;terminal=false;write(chunk,encoding,callback){this.sent=true;const cb=typeof encoding==="function"?encoding:callback;this.buffer+=typeof chunk==="string"?chunk:this.decoder.decode(chunk,{stream:true});if(this.buffer.length>this.limitBytes)throw new Error("Responses WebSocket output buffer limit exceeded");this.buffer=normalizeSseLineEndings(this.buffer);this.drainSse();cb?.();if(this.peer.bufferedAmount>this.limitBytes){this.peer.close(1013,"Output buffer limit exceeded");this.destroy()}return true}drainSse(){let index;while((index=this.buffer.indexOf("\n\n"))>=0){const block=this.buffer.slice(0,index);this.buffer=this.buffer.slice(index+2);const data=block.split("\n").filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trimStart()).join("\n");if(!data||data==="[DONE]")continue;const frame=JSON.parse(data);if(object2(frame)){const completed2=this.output.observe(frame);if(completed2){this.response=completed2;const terminal=object2(frame.response)&&Array.isArray(frame.response.output)?frame.response.output.length:0;this.restoredOutputItems=completed2.output.length-terminal}if(["response.completed","response.failed","response.incomplete","error"].includes(String(frame.type)))this.terminal=true}if(this.peer.readyState===wrapper_default.OPEN)this.peer.send(data,{binary:false})}}end(chunk,encoding,callback){if(this.ended)return this;if(typeof chunk==="string"||chunk instanceof Uint8Array)this.write(chunk);this.buffer=finalizeSseLineEndings(this.buffer);this.drainSse();if(!this.terminal&&this.peer.readyState===wrapper_default.OPEN){let details;try{details=JSON.parse(this.buffer)}catch{details=void 0}this.peer.send(object2(details)?JSON.stringify({...details,type:"error",status:this.statusCode>=400?this.statusCode:502}):errorFrame("incomplete_response","Responses exchange ended without a terminal event",502))}this.ended=true;this.emit("finish");this.emit("close");const cb=typeof chunk==="function"?chunk:typeof encoding==="function"?encoding:callback;if(typeof cb==="function")cb();return this}};var ResponsesWsSession=class{constructor(context){this.context=context;this.transport=new ResponsesWsUpstream(context.log,void 0,context.instanceId,context.codec.allowStreamFlag===true);context.log("info","Responses socket connected (ACP request pipeline)")}context;transport;history=new ResponsesWsHistory;budget=limitsReceiveBytes();active;busy=false;onMessage(data,binary){const peer=this.context.peer;if(binary){peer.close(1003,"Responses requires text frames");return}if(this.busy){this.context.log("warn","client rejected reason=response-in-progress");peer.send(errorFrame("response_in_progress","Only one active response is supported",409));return}const refuse=(code,message,status)=>{this.context.log("warn",`client rejected reason=${code} detail=${message}`);peer.send(errorFrame(code,message,status))};let body;let wire="";let anchoredTailSig;let deltaContinuation;try{const rawFrame=JSON.parse(data.toString());if(!object2(rawFrame)||rawFrame.type!=="response.create"){refuse("invalid_request",`expected a response.create frame, got ${describeEventType(rawFrame)}`,400);return}const frame=rawFrame;const unsupported=unsupportedTransportOptions(frame,this.context.codec.allowStreamFlag);if(unsupported.length>0){refuse("invalid_request",`response.create carries unsupported transport option(s): ${unsupported.join(", ")}`,400);return}const cp2=this.history.current();const continuedId=typeof frame.previous_response_id==="string"?frame.previous_response_id:void 0;const deltaEligible=featureEnabled("wsDeltaContinuation")&&!this.context.source.headers["x-bili-plugin"]&&cp2!==void 0&&continuedId!==void 0&&continuedId===cp2.id&&Array.isArray(frame.input)&&cp2.tailSig!==void 0&&getStore()?.unifiedReads()===true&&cp2.output.every(item=>object2(item)&&ECHOABLE_OUTPUT_ITEM_TYPES.has(String(item.type)));if(deltaEligible){const{type:_type,previous_response_id:_prev,...requestFields}=frame;const{generate:_priorGenerate,...priorRequest}=cp2.request;body={...priorRequest,...requestFields,input:[...cp2.output,...frame.input],stream:true};anchoredTailSig=cp2.tailSig;deltaContinuation={id:continuedId,tail:frame.input}}else{body={...this.history.expand(frame),stream:true}}wire=JSON.stringify(body);if(Buffer.byteLength(wire)>this.budget){refuse("request_too_large",`response.create exceeds the ${Math.round(this.budget/(1024*1024))} MiB request limit`,413);return}}catch(error){if(error instanceof Error&&error.message==="previous_response_not_found"){refuse("previous_response_not_found","Send full input without previous_response_id",400);return}refuse("invalid_request",error instanceof SyntaxError?"response.create frame is not valid JSON":error instanceof Error?error.message:"malformed response.create frame",400);return}this.busy=true;const source=this.context.source;const handshakeHeaders={};const connectionHeaders=connectionNamedHeaders(source.headers.connection);for(const[key2,value]of Object.entries(source.headers)){if(!UPSTREAM_HOP_HEADERS.has(key2)&&!connectionHeaders.has(key2)&&!key2.startsWith("sec-websocket-")&&key2!=="content-encoding")handshakeHeaders[key2]=Array.isArray(value)?value.join(", "):String(value)}if(Array.isArray(body.input)&&body.input.length===0&&body.generate===false){void(async()=>{const sendFrame=payload=>{if(peer.readyState===wrapper_default.OPEN)peer.send(payload)};let sawTerminal=false;try{const response=await this.transport.fetch(this.context.upstreamUrl,{method:"POST",headers:{...handshakeHeaders,"content-type":"application/json"},body:JSON.stringify(body)});if(response.body===null){const text2=await response.text();if(!response.ok){this.history.clear();sendFrame(text2||errorFrame("probe_failed","Warmup failed",response.status>=400?response.status:502));return}sendFrame(text2);return}const reader=response.body.getReader();const decoder=new TextDecoder;let buffer="";for(;;){const{done,value}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:true});if(buffer.length>this.budget)throw new Error("Warmup output buffer limit exceeded");for(;;){const index=buffer.indexOf("\n\n");if(index<0)break;const block=buffer.slice(0,index);buffer=buffer.slice(index+2);for(const line of block.split("\n")){if(!line.startsWith("data: "))continue;const payload=line.slice(6);sendFrame(payload);let frame;try{frame=JSON.parse(payload)}catch{continue}if(!object2(frame))continue;if(["response.completed","response.failed","response.incomplete","error"].includes(String(frame.type))){sawTerminal=true;if(frame.type==="response.completed"&&object2(frame.response))this.history.commit(body,frame.response)}}}}if(!sawTerminal){this.history.clear();sendFrame(response.ok?errorFrame("incomplete_response","Warmup ended without a terminal event",502):errorFrame("probe_failed","Warmup failed",response.status>=400?response.status:502))}}catch{this.history.clear();this.context.log("warn","probe relay failed");sendFrame(errorFrame("invalid_request","Probe relay failed",502))}finally{this.active=void 0;this.busy=false}})();return}const req=new http2.IncomingMessage(source.socket);req.complete=true;req.method="POST";req.url=source.url;Object.assign(req.headers,handshakeHeaders);req.headers["content-type"]="application/json";if(anchoredTailSig!==void 0){Object.defineProperty(req,WS_ANCHORED_REQ_PROP,{value:{tailSig:anchoredTailSig},enumerable:false})}req.push(Buffer.from(wire));req.push(null);const res=new ResponsesWsResponse(req,peer);res.on("error",()=>{});this.active=res;void withFetchTransport(markWsLaneTransport((url,options)=>this.transport.fetch(url,options)),async()=>{try{await this.context.dispatch(req,res);if(res.response){this.history.commit(body,res.response,{tailSig:computeTailSig(body)??void 0,continuedId:deltaContinuation?.id,tail:deltaContinuation?.tail});if(res.restoredOutputItems>0)this.context.log("debug",`checkpoint restored ${res.restoredOutputItems} streamed output item(s) absent from terminal output`)}}catch(error){if(error instanceof SnapshotAnchorFallbackError){this.history.clear();this.context.log("warn",`delta continuation rejected reason=${error.reason} \u2014 requesting full replay`);this.active?.destroy();if(peer.readyState===wrapper_default.OPEN)peer.send(errorFrame("previous_response_not_found","Send full input without previous_response_id",400));return}this.context.log("warn",`exchange failed phase=dispatch terminal=${res.terminal}`);if(!res.writableEnded)res.end()}finally{this.active=void 0;this.busy=false}})}onClose(code){this.context.log("debug",`client closed phase=${this.busy?"active":"idle"} close_code=${code}`);this.active?.destroy();this.transport.close("client-close");this.history.clear();this.context.log("debug","client checkpoint reset reason=client-close")}shutdown(reason){this.transport.close(reason);this.history.clear();this.active?.destroy()}};var responsesCodec={name:"responses-ws",pluginMarker:"opencode",matchUpgrade:url=>/^\/bili\/responses\/(https?:\/\/.*\/responses(?:\?.*)?)$/.exec(url??"")?.[1],createSession:context=>new ResponsesWsSession(context)};var codexResponsesCodec={name:"codex-responses-ws",conversationHeader:"session-id",matchUpgrade:url=>/^\/bili\/(https?:\/\/.*\/responses(?:\?.*)?)$/.exec(url??"")?.[1],allowStreamFlag:true,createSession:context=>new ResponsesWsSession(context)};async function startInlineWsBridge(options){const server2=http3.createServer((req,res)=>{res.writeHead(426,{"content-type":"text/plain; charset=utf-8"});res.end("bili inline WS bridge: WebSocket upgrade required\n")});const upgrade=installWebSocketBridge(server2,options.dispatchHttp,options.log,[responsesCodec,codexResponsesCodec],options.isEgressProxied,options.instanceId);server2.on("upgrade",(source,socket,head)=>{if(upgrade(source,socket,head))return;socket.end("HTTP/1.1 426 Upgrade Required\r\nConnection: close\r\nContent-Length: 0\r\n\r\n")});await new Promise((resolve2,reject)=>{server2.once("error",reject);server2.listen(0,"127.0.0.1",()=>resolve2())});server2.unref();const{port}=server2.address();options.log("info",`[inline] codex WS bridge listening on 127.0.0.1:${port} (loopback only)`);return{origin:`http://127.0.0.1:${port}`,close:()=>new Promise(resolve2=>{server2.close(()=>resolve2())})}}init_dist();import http4 from"http";import fs31 from"fs";import net4 from"net";import tls5 from"tls";import{randomUUID as randomUUID12}from"crypto";import{performance as performance3}from"perf_hooks";init_config();var DEFAULT_COMPRESS_REASONING={drop:true,threshold:2048};function resolveReasoningDrop(cfg){let threshold=DEFAULT_COMPRESS_REASONING.threshold;if(cfg?.threshold!==void 0){const t=cfg.threshold;if(typeof t==="number"&&Number.isFinite(t)&&t>=0){threshold=Math.floor(t)}}return{drop:cfg?.drop!==false,threshold}}function dropCompressReasoningIds(messages,cfg){const{drop,threshold}=resolveReasoningDrop(cfg);const ids=new Set;if(!drop||messages.length===0)return ids;try{const last=messages.length-1;const resultAt=new Map;for(let i=0;i<=last;i++){const m2=messages[i];if(m2.contentType==="tool-result"&&typeof m2.toolCallId==="string"&&!resultAt.has(m2.toolCallId)){resultAt.set(m2.toolCallId,i)}}for(let i=0;i<=last;i++){const m2=messages[i];if(m2.contentType!=="tool-call"||typeof m2.toolName!=="string"||!isMcpBiliCompress(m2.toolName))continue;const ri2=typeof m2.toolCallId==="string"?resultAt.get(m2.toolCallId):void 0;if(ri2===void 0||ri2<=i||ri2>=last)continue;let total=0;let j2=i-1;while(j2>=0&&messages[j2].contentType==="reasoning"){total+=(messages[j2].text??"").length;j2--}if(total>threshold){for(let k2=j2+1;k2<i;k2++)ids.add(messages[k2].id)}}}catch{}return ids}init_config();init_registry();init_fetch_util();init_upstream_proxy();init_upstream_fail();init_log_mask();init_dist();init_config();init_util();function yieldToEventLoop(){return new Promise(resolve2=>setImmediate(resolve2))}var DEFAULT_DECIDE_MAX_TOKENS=200;var DECIDE_TIMEOUT_MS=15e3;var DECIDE_FALLBACK_THRESHOLD=3;var LADDER_KEY="nudgeDecideFails";var RANGE_RE=/^m(\d{4,})-m(\d{4,})$/;var SPANS_SHOWN=8;var TOPIC_MAX_CHARS=80;function formatK3(n){if(n>=1e3)return`${(n/1e3).toFixed(1)}K`;return`${n}`}function buildDecisionPrompt(ranges){const spans=ranges.slice(0,SPANS_SHOWN).map(r=>` ${r.startRef}\u2013${r.endRef} ${r.count} msgs ${formatK3(r.tokens)} [tool ${r.toolPct}% | text ${r.textPct}%]`);return["[bili-compress-decision] Side-channel question \u2014 answer ONLY this. Do not continue your task, do not call any tools.","Given the conversation above exactly as it stands now, is compressing older consumed context NOW net-beneficial for the current task?","Reply with ONLY one line of JSON, nothing else:",'{"compress": false}','or {"compress": true, "range": "mNNNNN-mNNNNN", "topic": "<short topic>"}',"Rules: compress=true only if the task has clearly moved past the targeted content AND reclaiming it is worth more than keeping it verbatim. Prefer a span from the list below when one fits; otherwise cite any older span you can see in the ACP tags above. Do NOT perform the compression now \u2014 only answer.",...spans.length>0?[`Compressible spans (oldest first):`,...spans]:["No pre-detected compressible spans \u2014 judge from the ACP tags above."]].join("\n")}function buildDirectiveText(startRef,endRef,topic){return["[bili-compress-directive] Compress NOW \u2014 this is a directive issued from your own decision above, not a suggestion.",`Target span: ${startRef}\u2013${endRef}${topic?` (topic: "${topic}")`:""}. Call your compress tool on exactly this span in this turn and write the summary per the compression rules. Do not widen or narrow the span unless it contains protected content \u2014 then trim to the unprotected part.`].join("\n")}function parseDecision(raw){let s3=raw.trim();if(!s3)return{kind:"failed",detail:"empty response"};const fence=s3.match(/^```(?:json)?\s*([\s\S]*?)\s*```\s*$/i);if(fence)s3=fence[1].trim();if(!s3.startsWith("{")||!s3.endsWith("}"))return{kind:"failed",detail:"not a bare JSON object"};let obj;try{obj=JSON.parse(s3)}catch(e){return{kind:"failed",detail:`invalid JSON (${String(e)})`}}if(typeof obj!=="object"||obj===null||Array.isArray(obj))return{kind:"failed",detail:"not an object"};const o=obj;if(typeof o.compress!=="boolean")return{kind:"failed",detail:"compress must be boolean"};if(!o.compress)return{kind:"no"};let range;if(o.range!==void 0){if(typeof o.range==="string"&&RANGE_RE.test(o.range))range=o.range;else return{kind:"failed",detail:"malformed range"}}let topic;if(o.topic!==void 0){if(typeof o.topic!=="string")return{kind:"failed",detail:"topic must be a string"};topic=o.topic.trim().slice(0,TOPIC_MAX_CHARS)||void 0}return{kind:"yes",range,topic}}function refNum4(ref){const m2=ref.match(/\d+/);return m2?parseInt(m2[0],10):0}function resolveDecisionRange(decision,ranges){if(ranges.length===0)return void 0;if(decision.range){const m2=decision.range.match(RANGE_RE);if(m2){const a=parseInt(m2[1],10);const b2=parseInt(m2[2],10);if(a<=b2){for(const r of ranges){if(a>=refNum4(r.startRef)&&b2<=refNum4(r.endRef)){return{startRef:r.startRef,endRef:r.endRef}}}}}}let best;for(const r of ranges){if(!best||r.tokens>best.tokens)best=r}return best?{startRef:best.startRef,endRef:best.endRef}:void 0}function ladderMode(metadata){return typeof metadata[LADDER_KEY]==="number"&&metadata[LADDER_KEY]>=DECIDE_FALLBACK_THRESHOLD?"fallback":"try"}function recordDecision(metadata,ok){metadata[LADDER_KEY]=ok?0:(typeof metadata[LADDER_KEY]==="number"?metadata[LADDER_KEY]:0)+1}function consumeFallback(metadata){metadata[LADDER_KEY]=0}function stripDecisionReasoningFields(protocol,body){if(protocol==="openai"){delete body["reasoning_effort"];delete body["reasoning"];delete body["thinking"]}else if(protocol==="anthropic"){delete body["thinking"];delete body["interleaved_thinking"]}else if(protocol==="google"){delete body["thinkingConfig"];const gc=body["generationConfig"];if(gc!==null&&typeof gc==="object")delete gc["thinkingConfig"]}else{delete body["reasoning"]}}function extractDecisionText(protocol,json){if(!json)return"";const parts=[];if(protocol==="anthropic"){const content=json.content;if(Array.isArray(content)){for(const b2 of content){const o=b2;if(o&&o.type==="text"&&typeof o.text==="string")parts.push(o.text)}}}else if(protocol==="openai"){const choices=json.choices;const c0=Array.isArray(choices)?choices[0]:void 0;const msg=c0?c0.message:void 0;if(msg&&typeof msg.content==="string")parts.push(msg.content)}else if(protocol==="google"){const cands=json.candidates;const c0=Array.isArray(cands)?cands[0]:void 0;const cont=c0?c0.content:void 0;const ps2=cont?cont.parts:void 0;if(Array.isArray(ps2)){for(const p2 of ps2){const o=p2;if(o&&typeof o.text==="string")parts.push(o.text)}}}else{if(typeof json.output_text==="string")parts.push(json.output_text);const out=json.output;if(Array.isArray(out)){for(const item of out){const o=item;const c=o?o.content:void 0;if(Array.isArray(c)){for(const b2 of c){const bo2=b2;if(bo2&&bo2.type==="output_text"&&typeof bo2.text==="string")parts.push(bo2.text)}}}}}return parts.join("")}init_dist();init_config();init_logger();init_util();var KEEPALIVE_TIER_5M_MS=3e5;var KEEPALIVE_TIER_1H_MS=36e5;var KEEPALIVE_DEFAULT_TTL_FACTOR=.9;var KEEPALIVE_DEFAULT_MAX_DURATION_MS=864e5;var KEEPALIVE_DEFAULT_MAX_PINGS=4;var PING_TIMEOUT_MS=6e4;var BUSY_RESCHEDULE_MS=5e3;var MAX_FAIL_STREAK=3;var MAX_SNAPSHOT_BYTES=64*1024*1024;function envBool(name){const raw=process.env[name];if(raw===void 0||raw.trim()==="")return void 0;if(raw==="1"||raw.toLowerCase()==="true")return true;if(raw==="0"||raw.toLowerCase()==="false")return false;return void 0}function envNum(name){const raw=process.env[name];if(raw===void 0||raw.trim()==="")return void 0;const n=Number(raw);return Number.isFinite(n)?n:void 0}function fileNum(v2){return typeof v2==="number"&&Number.isFinite(v2)?v2:void 0}function pickMs(envName,fileValue,valid,fallback){const env=envNum(envName);if(env!==void 0&&valid(env))return env;const file=fileNum(fileValue);if(file!==void 0&&valid(file))return file;return fallback}function modelTierPresent(routes,upstreamUrl){const models=routes?findRoute(routes,upstreamUrl)?.models:void 0;if(!models)return false;return Object.values(models).some(e=>e!==null&&typeof e==="object"&&"cacheKeepalive"in e)}function resolveCacheKeepalive(routes,upstreamUrl,model){const g2=loadConfigFile().cacheKeepalive??{};const route=routes?findRoute(routes,upstreamUrl):void 0;const p2=route?.cacheKeepalive??{};const m2=typeof model==="string"&&model.length>0?route?.models?.[model]?.cacheKeepalive??{}:{};const lvl=k2=>m2[k2]!==void 0?m2[k2]:p2[k2]!==void 0?p2[k2]:g2[k2];let assumeTtl;const assumeEnv=process.env["BILI_CACHE_KEEPALIVE_ASSUME_TTL"];if(assumeEnv==="5m"||assumeEnv==="1h")assumeTtl=assumeEnv;else{const l=lvl("assumeTtl");if(l==="5m"||l==="1h")assumeTtl=l}return{enabled:envBool("BILI_CACHE_KEEPALIVE")??lvl("enabled")===true,ttlFactor:pickMs("BILI_CACHE_KEEPALIVE_TTL_FACTOR",lvl("ttlFactor"),n=>n>0&&n<=1,KEEPALIVE_DEFAULT_TTL_FACTOR)??KEEPALIVE_DEFAULT_TTL_FACTOR,maxDurationMs:pickMs("BILI_CACHE_KEEPALIVE_MAX_DURATION_MS",lvl("maxDurationMs"),n=>Number.isInteger(n)&&n>0,KEEPALIVE_DEFAULT_MAX_DURATION_MS)??KEEPALIVE_DEFAULT_MAX_DURATION_MS,maxConcurrentPings:pickMs("BILI_CACHE_KEEPALIVE_MAX_PINGS",lvl("maxConcurrentPings"),n=>Number.isInteger(n)&&n>=1,KEEPALIVE_DEFAULT_MAX_PINGS)??KEEPALIVE_DEFAULT_MAX_PINGS,assumeTtl,armWithoutBreakpoints:envBool("BILI_CACHE_KEEPALIVE_ARM_WITHOUT_BREAKPOINTS")??lvl("armWithoutBreakpoints")===true,intervalMs:pickMs("BILI_CACHE_KEEPALIVE_INTERVAL_MS",lvl("intervalMs"),n=>Number.isInteger(n)&&n>0,void 0)}}function detectKeepaliveTier(body){let found;const walk=n=>{if(found==="1h"||n===null||typeof n!=="object")return;if(Array.isArray(n)){for(const item of n)walk(item);return}const o=n;const cc=o["cache_control"];if(cc&&typeof cc==="object"&&!Array.isArray(cc)){const ttl=cc["ttl"];if(ttl==="1h"){found="1h";return}if(ttl==="5m")found="5m"}for(const v2 of Object.values(o))walk(v2)};walk(body);return found}function buildPingBody(snapshot){const obj=JSON.parse(snapshot);obj["max_tokens"]=1;obj["stream"]=false;return JSON.stringify(obj)}var registry3=new Map;var clock=()=>Date.now();var scheduleFn=(fn,ms2)=>setTimeout(fn,ms2);var cancelFn=id=>clearTimeout(id);function noteSuccessfulForward(inp){try{armInternal(inp)}catch(err2){log("warn",`[${inp.sessionId}] [keepalive] arm failed: ${err2 instanceof Error?err2.message:String(err2)}`)}}function keepaliveStatusFor(sessionId){const e=registry3.get(sessionId);if(!e)return void 0;return{tierLabel:e.tierLabel,cadenceMs:e.cadenceMs,pingCount:e.pingCount,failStreak:e.failStreak,armedAt:e.armedAt,lastRealActivityAt:e.lastRealActivityAt,lastPingAt:e.lastPingAt,lastHitAt:e.lastHitAt}}function armInternal(inp){if(inp.protocol!=="anthropic"||inp.reqMethod!=="POST"||inp.sidePassthrough||inp.resignLane)return;if(typeof inp.wireBody!=="string"||inp.wireBody.length===0)return;if(inp.wireBody.length>MAX_SNAPSHOT_BYTES){log("warn",`[${inp.sessionId}] [keepalive] snapshot skipped: body ${inp.wireBody.length} bytes exceeds ${MAX_SNAPSHOT_BYTES} cap`);return}if(!resolveCacheKeepalive(inp.routes,inp.upstreamUrl).enabled&&!modelTierPresent(inp.routes,inp.upstreamUrl)){disarm2(inp.sessionId,"disabled");return}let parsed;try{parsed=JSON.parse(inp.wireBody)}catch{return}if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return;const rec=parsed;const model=typeof inp.model==="string"&&inp.model.length>0?inp.model:typeof rec.model==="string"?rec.model:void 0;const cfg=resolveCacheKeepalive(inp.routes,inp.upstreamUrl,model);if(!cfg.enabled){disarm2(inp.sessionId,"disabled");return}const now=clock();const credFp=credentialFingerprint(inp.headers);const prev=registry3.get(inp.sessionId);if(prev&&prev.credFp!==credFp)registry3.delete(inp.sessionId);const breakpointTier=detectKeepaliveTier(parsed);let cadenceMs;let tierLabel2;if(cfg.intervalMs!==void 0){cadenceMs=cfg.intervalMs;tierLabel2=`interval:${cfg.intervalMs}ms`}else if(cfg.assumeTtl){cadenceMs=Math.round((cfg.assumeTtl==="1h"?KEEPALIVE_TIER_1H_MS:KEEPALIVE_TIER_5M_MS)*cfg.ttlFactor);tierLabel2=`${cfg.assumeTtl}(assumed)`}else if(breakpointTier){cadenceMs=Math.round((breakpointTier==="1h"?KEEPALIVE_TIER_1H_MS:KEEPALIVE_TIER_5M_MS)*cfg.ttlFactor);tierLabel2=breakpointTier}else if(cfg.armWithoutBreakpoints){cadenceMs=Math.round(KEEPALIVE_TIER_5M_MS*cfg.ttlFactor);tierLabel2="5m(no-breakpoints)"}else{return}if(!registry3.has(inp.sessionId)&®istry3.size>=cfg.maxConcurrentPings){let oldestId;let oldestAt=Infinity;for(const[id,e]of registry3){if(e.armedAt<oldestAt){oldestAt=e.armedAt;oldestId=id}}if(oldestId!==void 0)disarm2(oldestId,"concurrency-cap")}if(prev)cancelFn(prev.timerId);const entry={sessionId:inp.sessionId,body:inp.wireBody,upstreamUrl:inp.upstreamUrl,headers:{...inp.headers},dispatcher:inp.dispatcher,credFp,cadenceMs,tierLabel:tierLabel2,armedAt:now,lastRealActivityAt:now,maxDurationMs:cfg.maxDurationMs,pingCount:0,failStreak:0,timerId:void 0,pingInFlight:false};registry3.set(inp.sessionId,entry);entry.timerId=scheduleFn(()=>{void firePing(entry)},entry.cadenceMs);log("info",`[${entry.sessionId}] [keepalive] armed tier=${tierLabel2} cadence=${Math.round(entry.cadenceMs/1e3)}s body=${Math.ceil(entry.body.length/1024)}KiB`)}async function firePing(entry){if(registry3.get(entry.sessionId)!==entry)return;const now=clock();if(now-entry.lastRealActivityAt>entry.maxDurationMs){disarm2(entry.sessionId,"max-duration");return}const session=peekSession(entry.sessionId);if(!session){disarm2(entry.sessionId,"session-gone");return}if(entry.pingInFlight||session.inFlight>0){entry.timerId=scheduleFn(()=>{void firePing(entry)},BUSY_RESCHEDULE_MS);return}entry.pingInFlight=true;entry.lastPingAt=clock();let resp;try{resp=await sendPing(entry)}catch(err2){entry.pingInFlight=false;handleFailure(entry,`network: ${err2 instanceof Error?err2.message:String(err2)}`);return}entry.pingInFlight=false;if(registry3.get(entry.sessionId)!==entry)return;const text2=await resp.text().catch(()=>"");if(!resp.ok){if(resp.status===429){disarm2(entry.sessionId,"rate-limited(429)");return}handleFailure(entry,`http ${resp.status}: ${text2.slice(0,200)}`);return}let usage;try{const j2=JSON.parse(text2);if(j2&&typeof j2==="object"&&j2.usage&&typeof j2.usage==="object")usage=j2.usage}catch{usage=void 0}const cached=usage?usageTotals("anthropic",usage).cached:void 0;entry.pingCount+=1;if(typeof cached==="number"&&cached>0){entry.failStreak=0;entry.lastHitAt=clock();log("info",`[${entry.sessionId}] [keepalive] ping#${entry.pingCount} hit=${cached}tok`);reschedule(entry)}else{disarm2(entry.sessionId,"prefix-dead(cache_read=0)")}}function handleFailure(entry,detail){if(registry3.get(entry.sessionId)!==entry)return;entry.failStreak+=1;log("warn",`[${entry.sessionId}] [keepalive] ping failed (${entry.failStreak}/${MAX_FAIL_STREAK}): ${detail}`);if(entry.failStreak>=MAX_FAIL_STREAK){disarm2(entry.sessionId,`errors(${detail})`);return}reschedule(entry)}function reschedule(entry){if(registry3.get(entry.sessionId)!==entry)return;entry.timerId=scheduleFn(()=>{void firePing(entry)},entry.cadenceMs)}async function sendPing(entry){const headers={};for(const[k2,v2]of Object.entries(entry.headers)){const lk=k2.toLowerCase();if(lk==="content-length"||lk==="transfer-encoding"||lk==="connection")continue;headers[k2]=v2}const init={method:"POST",headers,body:buildPingBody(entry.body),signal:AbortSignal.timeout(PING_TIMEOUT_MS)};if(entry.dispatcher)init.dispatcher=entry.dispatcher;return await fetch(entry.upstreamUrl,init)}function disarm2(sessionId,reason){const entry=registry3.get(sessionId);if(!entry)return;registry3.delete(sessionId);if(entry.timerId!==void 0)cancelFn(entry.timerId);log("info",`[${sessionId}] [keepalive] disarmed reason=${reason} pings=${entry.pingCount}`)}init_logger();init_upstream_fail();init_log_mask();var ALERT_KINDS=new Set(["connect-timeout","connect-refused","proxy-reset","upstream-reset","dns","tls"]);var MAX_ALERTS=32;var alerts=new Map;function hostOf(url){try{return new URL(url).host}catch{return url}}function keyFor(kind,host){return kind+"\0"+host}function errnoCode(error){const c=typeof error==="object"&&error!==null?error.code:void 0;return typeof c==="string"&&c.length>0?c:void 0}function recordUpstreamAlert(url,error,viaProxy,skipped){const kind=classifyUpstreamFailure(error,{viaProxy});if(!ALERT_KINDS.has(kind))return;const host=hostOf(url);const now=Date.now();const code=errnoCode(error);const key2=keyFor(kind,host);const skippedFields=skipped?{skippedProxy:redactedSkippedProxy(skipped),skippedSource:skipped.source}:{};const hint=hintWithSkippedProxy(kind,skipped);const existing=alerts.get(key2);if(existing){existing.lastSeen=now;existing.count+=1;existing.hint=hint;if(code!==void 0)existing.code=code;Object.assign(existing,skippedFields);return}if(alerts.size>=MAX_ALERTS){let oldestKey;let oldestAt=Infinity;for(const[k2,a]of alerts){if(a.lastSeen<oldestAt){oldestAt=a.lastSeen;oldestKey=k2}}if(oldestKey!==void 0)alerts.delete(oldestKey)}alerts.set(key2,{kind,host,hint,firstSeen:now,lastSeen:now,count:1,...code!==void 0?{code}:{},...skippedFields})}function clearUpstreamAlertsForHost(url){const host=hostOf(url);for(const[key2,a]of alerts){if(a.host===host)alerts.delete(key2)}}function getUpstreamAlerts(){return[...alerts.values()].sort((a,b2)=>b2.lastSeen-a.lastSeen)}var CIRCUIT_OPEN_AFTER=3;var circuitProbeCooldownMs=6e4;var MAX_CIRCUITS=32;var circuits=new Map;function blockReasonText(c,now){const lf=c.lastFailure?` \xB7 last failure ${c.lastFailure.kind}${c.lastFailure.detail?` (${c.lastFailure.detail})`:""} @ ${new Date(c.lastFailure.at).toISOString()}`:"";const waitS=Math.max(0,Math.ceil(((c.nextProbeAt??now)-now)/1e3));return`${maskHostPortForLog(c.host)}: ${c.consecutiveFailures} consecutive pre-response failures since ${new Date(c.openedAt??now).toISOString()}${lf}; next probe ${new Date(c.nextProbeAt??now).toISOString()} (~${waitS}s) \u2014 endpoint unreachable, stop resending full context`}function upstreamCircuitBlockReason(url,now=Date.now()){const entry=circuits.get(hostOf(url));if(!entry||entry.state.openedAt===null)return void 0;const c=entry.state;if(now<(c.nextProbeAt??0))return blockReasonText(c,now);if(entry.probeInFlight)return blockReasonText(c,now);entry.probeInFlight=true;return void 0}function upstreamCircuitLastFailureKind(url){const entry=circuits.get(hostOf(url));if(!entry||entry.state.openedAt===null)return void 0;return entry.state.lastFailure?.kind}var FAIL_FAST_LOG_INTERVAL_MS=6e4;function noteCircuitFailFastLog(url,now=Date.now()){const entry=circuits.get(hostOf(url));if(!entry||entry.state.openedAt===null)return true;if(now-entry.lastFailFastLogAt>=FAIL_FAST_LOG_INTERVAL_MS){entry.lastFailFastLogAt=now;return true}return false}function upstreamCircuitRetryAfterSeconds(url,now=Date.now()){const entry=circuits.get(hostOf(url));if(!entry||entry.state.openedAt===null)return void 0;const np=entry.state.nextProbeAt;if(np===null)return void 0;return Math.max(0,Math.ceil((np-now)/1e3))}function truncateAtBoundary(s3,max){if(!s3)return"";if(s3.length<=max)return s3;const head=s3.slice(0,max);const lastSpace=head.lastIndexOf(" ");return`${lastSpace>0?head.slice(0,lastSpace):head}\u2026`}function recordUpstreamCircuitFailure(url,error,viaProxy,detail){const kind=classifyUpstreamFailure(error,{viaProxy});const host=hostOf(url);const now=Date.now();const code=errnoCode(error);let entry=circuits.get(host);if(!entry){if(!ALERT_KINDS.has(kind))return;if(circuits.size>=MAX_CIRCUITS){let oldestKey;let oldestAt=Infinity;for(const[k2,e]of circuits){const t=e.state.lastFailure?.at??e.state.openedAt??Infinity;if(t<oldestAt){oldestAt=t;oldestKey=k2}}if(oldestKey!==void 0)circuits.delete(oldestKey)}entry={state:{host,consecutiveFailures:0,openedAt:null,nextProbeAt:null,lastFailure:null},probeInFlight:false,lastFailFastLogAt:0};circuits.set(host,entry)}const c=entry.state;const shortDetail=truncateAtBoundary(detail,240);if(c.openedAt!==null){c.lastFailure={kind,detail:shortDetail,at:now,...code!==void 0?{code}:{}};entry.probeInFlight=false;c.nextProbeAt=now+circuitProbeCooldownMs;log("warn",`[acp-proxy] upstream circuit probe FAILED for ${host} (${kind}) \u2014 re-armed until ${new Date(c.nextProbeAt).toISOString()} (#3148)`);return}if(!ALERT_KINDS.has(kind))return;c.lastFailure={kind,detail:shortDetail,at:now,...code!==void 0?{code}:{}};c.consecutiveFailures+=1;if(c.consecutiveFailures>=CIRCUIT_OPEN_AFTER){c.openedAt=now;c.nextProbeAt=now+circuitProbeCooldownMs;log("warn",`[acp-proxy] upstream circuit OPEN for ${host} after ${c.consecutiveFailures} consecutive pre-response failures (last: ${kind}) \u2014 requests to this host fail fast until a probe succeeds (next probe ${new Date(c.nextProbeAt).toISOString()}) (#3148)`)}}function recordUpstreamCircuitSuccess(url){const entry=circuits.get(hostOf(url));if(!entry)return;if(entry.state.openedAt!==null){log("info",`[acp-proxy] upstream circuit CLOSED for ${entry.state.host} \u2014 a response arrived from the endpoint; normal retry ladder resumes (#3148)`)}circuits.delete(entry.state.host)}function getOpenUpstreamCircuits(){return[...circuits.values()].filter(e=>e.state.openedAt!==null).map(e=>({...e.state})).sort((a,b2)=>(b2.openedAt??0)-(a.openedAt??0))}function getUpstreamHealthReport(now=Date.now()){const byHost=new Map;const touch=host=>{let acc=byHost.get(host);if(!acc){acc={alerts:[],circuit:null};byHost.set(host,acc)}return acc};for(const a of alerts.values())touch(a.host).alerts.push(a);for(const e of circuits.values()){if(e.state.openedAt!==null)touch(e.state.host).circuit=e.state}const upstreams=[];for(const[host,{alerts:hostAlerts,circuit}]of byHost.entries()){const latest=hostAlerts.length>0?hostAlerts.reduce((m2,a)=>a.lastSeen>m2.lastSeen?a:m2):void 0;const kind=circuit?.lastFailure?.kind??latest?.kind??"unknown";const code=circuit?.lastFailure?.code??latest?.code;const hint=latest?.hint??circuit?.lastFailure?.detail;const count=circuit?circuit.consecutiveFailures:hostAlerts.reduce((s3,a)=>s3+a.count,0);const beginTimes=[...hostAlerts.map(a=>a.firstSeen),...circuit?[circuit.openedAt??now]:[]];const endTimes=[...hostAlerts.map(a=>a.lastSeen),...circuit?[circuit.lastFailure?.at??now]:[]];let port=null;const colon=host.lastIndexOf(":");if(colon>=0){const p2=Number(host.slice(colon+1));if(Number.isInteger(p2)&&p2>0&&p2<=65535)port=p2}upstreams.push({host,port,kind,...code!==void 0?{code}:{},...hint!==void 0?{hint}:{},count,firstSeen:Math.min(...beginTimes),lastSeen:Math.max(...endTimes),circuit:circuit?{state:"open",nextProbeInMs:Math.max(0,(circuit.nextProbeAt??now)-now)}:null})}upstreams.sort((a,b2)=>b2.lastSeen-a.lastSeen);return{upstreams}}init_logger();init_knobs();var MAX_HOLDS=64;var PROBE_INFLIGHT_TTL_MS=3e4;var RETRY_AFTER_CAP_MS=6e5;var holds=new Map;function parseRetryAfterMs(headerValue3,now){if(headerValue3===null)return null;const v2=headerValue3.trim();if(/^\d+$/.test(v2)){const sec=Number(v2);return Number.isFinite(sec)?Math.min(sec,RETRY_AFTER_CAP_MS/1e3)*1e3:null}const t=Date.parse(v2);if(!Number.isFinite(t))return null;return Math.max(0,Math.min(t-now,RETRY_AFTER_CAP_MS))}function holdKey(url,headers){let host=url;try{host=new URL(url).host}catch{}const cred=credentialFingerprint(headers);return{key:cred===void 0?host:`${host}\0${cred}`,host,cred}}function evictOldest2(){const oldest=holds.keys().next().value;if(oldest!==void 0)holds.delete(oldest)}function makeReject(st2,now){const maxC=throttle429MaxConsecutive();const terminal=st2.streak>=maxC;const secsLeft=Math.max(1,Math.ceil((st2.nextAttemptAt-now)/1e3));if(terminal){const capSec=Math.ceil(throttle429MaxDelayMs()/1e3);return{status:424,code:"bili_throttle_terminal",message:`upstream rate-limited ${st2.streak} consecutive request(s) to ${st2.host}; bili stops amplifying after ${maxC} consecutive rate limits \u2014 resend manually once the provider recovers (a background probe keeps checking at most every ${capSec}s) (#4204)`,retryAfterSec:null,streak:st2.streak,maxConsecutive:maxC,nextAttemptAt:st2.nextAttemptAt,host:st2.host}}return{status:429,code:"bili_throttle_hold",message:`upstream rate-limited ${st2.streak} consecutive request(s) to ${st2.host}; bili is holding outbound sends until ${new Date(st2.nextAttemptAt).toISOString()} (~${secsLeft}s, exponential backoff) instead of amplifying \u2014 zero egress while held, auto-resumes when the limit clears (#4204)`,retryAfterSec:secsLeft,streak:st2.streak,maxConsecutive:maxC,nextAttemptAt:st2.nextAttemptAt,host:st2.host}}function upstreamThrottleLocalReject(url,headers,now=Date.now()){if(!throttle429Enabled())return void 0;const{key:key2}=holdKey(url,headers);const st2=holds.get(key2);if(st2===void 0)return void 0;if(now<st2.nextAttemptAt)return makeReject(st2,now);if(now-st2.probeAt<PROBE_INFLIGHT_TTL_MS)return makeReject(st2,now);st2.probeAt=now;return void 0}function noteUpstreamThrottle429(url,headers,retryAfterHeader,now=Date.now()){if(!throttle429Enabled())return;const{key:key2,host,cred}=holdKey(url,headers);const prev=holds.get(key2);const streak=(prev?.streak??0)+1;const maxC=throttle429MaxConsecutive();const base=throttle429BaseDelayMs();const cap=throttle429MaxDelayMs();const exp=Math.min(cap,base*2**Math.min(streak-1,30));const jittered=exp*(.5+Math.random()*.5);const raMs=parseRetryAfterMs(retryAfterHeader,now);const delay=Math.max(jittered,raMs??0);const nextAttemptAt=now+delay;if(!prev&&holds.size>=MAX_HOLDS)evictOldest2();holds.set(key2,{streak,nextAttemptAt,probeAt:0,host,cred});const delaySec=Math.round(delay/1e3);const raNote=raMs!==null&&raMs>=jittered?", upstream Retry-After honored":"";if(streak===1){log("warn",`[acp-proxy] [429-hold] ${host}: upstream 429 \u2014 arming egress hold (~${delaySec}s backoff+jitter${raNote}) instead of letting host retries amplify (#4204)`)}else if(streak===maxC){log("warn",`[acp-proxy] [429-hold] ${host}: ${streak} consecutive upstream 429s \u2014 hold is TERMINAL: answering locally with 424 (outside SDK retry sets) until a probe succeeds (${raNote.trim()}) (#4204)`)}else{log("info",`[acp-proxy] [429-hold] ${host}: consecutive 429 #${streak} \u2014 hold extended to ~${delaySec}s${raNote} (#4204)`)}}function noteUpstreamThrottleResolved(url,headers,status,now=Date.now()){void now;if(!throttle429Enabled())return;const{key:key2,host}=holdKey(url,headers);const st2=holds.get(key2);if(st2===void 0)return;holds.delete(key2);log("info",`[acp-proxy] [429-hold] ${host}: cleared after HTTP ${status} (was ${st2.streak} consecutive 429s) (#4204)`)}function activeThrottleHolds(){const maxC=throttle429MaxConsecutive();return[...holds.values()].map(st2=>({host:st2.host,streak:st2.streak,nextAttemptAt:st2.nextAttemptAt,terminal:st2.streak>=maxC}))}init_dist();init_dist();import{createHash as createHash26}from"crypto";var REMOTE_IMAGE_TOKENS=4096;var PIXEL_IMAGE_FALLBACK_TOKENS=16384;function resolveImageBilling(mode,_upstreamUrl){if(mode==="bytes")return"bytes";return"pixels"}function effectiveCap(configuredCap){const v2=Number(process.env.BILI_IMAGE_TOKEN_CAP??"");if(Number.isInteger(v2)&&v2>0)return v2;return typeof configuredCap==="number"&&Number.isInteger(configuredCap)&&configuredCap>0?configuredCap:0}function applyCap(cost,configuredCap){const cap=effectiveCap(configuredCap);return cap>0?Math.min(cost,cap):cost}var PNG_SIG=[137,80,78,71];function pngDims(b2){if(b2.length<24||!PNG_SIG.every((v2,i)=>b2[i]===v2))return void 0;const w2=b2.readUInt32BE(16),h=b2.readUInt32BE(20);return w2>0&&h>0?{w:w2,h}:void 0}function gifDims(b2){if(b2.length<10||b2[0]!==71||b2[1]!==73||b2[2]!==70)return void 0;const w2=b2.readUInt16LE(6),h=b2.readUInt16LE(8);return w2>0&&h>0?{w:w2,h}:void 0}function bmpDims(b2){if(b2.length<26||b2[0]!==66||b2[1]!==77)return void 0;const w2=b2.readUInt32LE(18),h=Math.abs(b2.readInt32LE(22));return w2>0&&h>0?{w:w2,h}:void 0}function webpDims(b2){if(b2.length<30||b2.toString("ascii",0,4)!=="RIFF"||b2.toString("ascii",8,12)!=="WEBP")return void 0;const fourcc=b2.toString("ascii",12,16);if(fourcc==="VP8 "){if(b2[23]!==157||b2[24]!==1||b2[25]!==42)return void 0;const w2=b2.readUInt16LE(26)&16383,h=b2.readUInt16LE(28)&16383;return w2>0&&h>0?{w:w2,h}:void 0}if(fourcc==="VP8L"){if(b2[20]!==47)return void 0;const w2=((b2[22]&63)<<8|b2[21])+1,h=((b2[24]&15)<<10|b2[23]<<2|(b2[22]&192)>>6)+1;return w2>0&&h>0?{w:w2,h}:void 0}if(fourcc==="VP8X"){const w2=(b2[24]|b2[25]<<8|b2[26]<<16)+1,h=(b2[27]|b2[28]<<8|b2[29]<<16)+1;return w2>0&&h>0?{w:w2,h}:void 0}return void 0}function jpegDims(b2){if(b2.length<4||b2[0]!==255||b2[1]!==216)return void 0;let off=2;while(off+4<=b2.length){if(b2[off]!==255){off+=1;continue}const marker=b2[off+1];if(marker===216||marker===1||marker>=208&&marker<=217){off+=2;continue}if(marker===218)break;const segLen=b2.readUInt16BE(off+2);if(segLen<2)break;if(marker>=192&&marker<=207&&marker!==196&&marker!==200&&marker!==204){if(off+9>b2.length)break;const h=b2.readUInt16BE(off+5),w2=b2.readUInt16BE(off+7);if(w2>0&&h>0)return{w:w2,h};break}off+=2+segLen}return void 0}var HEADER_SCAN_CHARS=64;var JPEG_SCAN_CHARS=35e4;function decodeImageDims(b64){const head=Buffer.from(b64.slice(0,HEADER_SCAN_CHARS),"base64");for(const parse4 of[pngDims,gifDims,bmpDims,webpDims]){const d=parse4(head);if(d)return d}if(head.length>=2&&head[0]===255&&head[1]===216){return jpegDims(Buffer.from(b64.slice(0,JPEG_SCAN_CHARS),"base64"))}return void 0}var TILE_EDGE=512;var TILE_SHORT_SIDE=768;var TILE_MAX_EDGE=2048;function pixelTileEstimate(w2,h){let sw=w2,sh=h;const shortSide=Math.min(sw,sh);if(shortSide>0&&shortSide<TILE_SHORT_SIDE){const s3=TILE_SHORT_SIDE/shortSide;sw*=s3;sh*=s3}const longSide=Math.max(sw,sh);if(longSide>TILE_MAX_EDGE){const s3=TILE_MAX_EDGE/longSide;sw*=s3;sh*=s3}const tiles=Math.ceil(sw/TILE_EDGE)*Math.ceil(sh/TILE_EDGE);return 85+170*tiles}function base64ImageCost(b64,billing,configuredCap){if(billing==="pixels"){const dims=decodeImageDims(b64);return applyCap(dims?pixelTileEstimate(dims.w,dims.h):PIXEL_IMAGE_FALLBACK_TOKENS,configuredCap)}return applyCap(Math.ceil(b64.length/4),configuredCap)}function costForUrl(url,billing,configuredCap){if(url.startsWith("data:")){const i=url.indexOf("base64,");if(i>=0)return base64ImageCost(url.slice(i+"base64,".length),billing,configuredCap)}return applyCap(REMOTE_IMAGE_TOKENS,configuredCap)}function isObj(v2){return typeof v2==="object"&&v2!==null}function urlOf(v2){if(typeof v2==="string")return v2;if(isObj(v2)&&typeof v2.url==="string")return v2.url;return void 0}function opaquePartCost(part,configuredCap){return applyCap(Math.ceil(JSON.stringify(part).length/4),configuredCap)}function imageTokensInParsedBody(protocol,body,billing="bytes",configuredCap){if(!isObj(body))return 0;let total=0;if(protocol==="google"){const contents=body.contents;if(!Array.isArray(contents))return 0;for(const c of contents){if(!isObj(c)||!Array.isArray(c.parts))continue;for(const part of c.parts){if(!isObj(part))continue;const inline=part.inlineData;if(isObj(inline)&&typeof inline.data==="string"){total+=base64ImageCost(inline.data,billing,configuredCap);continue}const file=part.fileData;if(isObj(file)&&typeof file.fileUri==="string"){total+=costForUrl(file.fileUri,billing,configuredCap);continue}if(typeof part.text==="string"||isObj(part.functionCall)||isObj(part.functionResponse)||isObj(part.videoMetadata))continue;total+=opaquePartCost(part,configuredCap)}}return total}if(protocol==="responses"){const input=body.input;if(!Array.isArray(input))return 0;for(const item of input){if(!isObj(item))continue;const parts=Array.isArray(item.content)?item.content:responsesToolImageParts(item);if(!parts){continue}for(const part of parts){if(!isObj(part))continue;if(part.type==="input_image"){const url=urlOf(part.image_url);if(url)total+=costForUrl(url,billing,configuredCap);continue}if(item.type==="message"&&item.role==="user"&&part.type!=="input_text"&&part.type!=="output_text"){total+=opaquePartCost(part,configuredCap)}}}return total}const messages=body.messages;if(!Array.isArray(messages))return 0;for(const m2 of messages){if(!isObj(m2)||!Array.isArray(m2.content))continue;for(const part of m2.content){if(!isObj(part))continue;if(protocol==="openai"){if(part.type==="image_url"){const url=urlOf(part.image_url);if(url)total+=costForUrl(url,billing,configuredCap);continue}if(part.type==="file"){const f2=isObj(part.file)?part.file:{};const ref=typeof f2.file_data==="string"?f2.file_data:typeof f2.url==="string"?f2.url:void 0;total+=ref?costForUrl(ref,billing,configuredCap):applyCap(REMOTE_IMAGE_TOKENS,configuredCap);continue}if(part.type==="text")continue;if(m2.role==="user")total+=opaquePartCost(part,configuredCap);continue}else{if(part.type==="image"){const src=part.source;if(isObj(src)&&src.type==="base64"&&typeof src.data==="string")total+=base64ImageCost(src.data,billing,configuredCap);else if(isObj(src)&&src.type==="url"&&typeof src.url==="string")total+=costForUrl(src.url,billing,configuredCap);continue}if(part.type==="redacted_thinking"&&typeof part.data==="string"){total+=applyCap(Math.ceil(part.data.length/4),configuredCap);continue}if(part.type==="tool_result"&&Array.isArray(part.content)){for(const c of part.content){if(!isObj(c)||c.type==="text")continue;const src=c.source;if(isObj(src)&&src.type==="base64"&&typeof src.data==="string")total+=base64ImageCost(src.data,billing,configuredCap);else if(isObj(src)&&src.type==="url"&&typeof src.url==="string")total+=costForUrl(src.url,billing,configuredCap);else total+=opaquePartCost(c,configuredCap)}continue}}}}return total}function bodyHasImagesProbe(protocol,s3){return protocol==="google"?s3.includes("inlineData")||s3.includes("fileData"):protocol==="responses"?s3.includes("input_image")||s3.includes('"content":[')||s3.includes('"content": ['):protocol==="openai"?s3.includes("image_url")||s3.includes('"type":"file"')||s3.includes('"type": "file"')||s3.includes('"content":[')||s3.includes('"content": ['):s3.includes('"type":"image"')||s3.includes('"type": "image"')||s3.includes('"type":"redacted_thinking"')||s3.includes('"type":"document"')}function imageTokensInRawBody(protocol,raw,billing="bytes",configuredCap){const s3=typeof raw==="string"?raw:raw.toString("utf8");if(!bodyHasImagesProbe(protocol,s3))return 0;try{return imageTokensInParsedBody(protocol,JSON.parse(s3),billing,configuredCap)}catch{return 0}}function upstreamHost(url){if(!url)return"unknown";try{return new URL(url).hostname.toLowerCase()}catch{return url.toLowerCase()}}function countImagesInParsedBody(protocol,body){if(!isObj(body))return 0;let n=0;if(protocol==="google"){const contents=body.contents;if(!Array.isArray(contents))return 0;for(const c of contents){if(!isObj(c)||!Array.isArray(c.parts))continue;for(const part of c.parts){if(!isObj(part))continue;const inline=part.inlineData;if(isObj(inline)&&typeof inline.data==="string"){n+=1;continue}const file=part.fileData;if(isObj(file)&&typeof file.fileUri==="string"){n+=1;continue}if(typeof part.text==="string"||isObj(part.functionCall)||isObj(part.functionResponse)||isObj(part.videoMetadata))continue;n+=1}}return n}if(protocol==="responses"){const input=body.input;if(!Array.isArray(input))return 0;for(const item of input){if(!isObj(item))continue;const parts=Array.isArray(item.content)?item.content:responsesToolImageParts(item);if(!parts)continue;for(const part of parts){if(!isObj(part))continue;if(part.type==="input_image"){if(urlOf(part.image_url))n+=1;continue}if(item.type==="message"&&item.role==="user"&&part.type!=="input_text"&&part.type!=="output_text")n+=1}}return n}const messages=body.messages;if(!Array.isArray(messages))return 0;for(const m2 of messages){if(!isObj(m2)||!Array.isArray(m2.content))continue;for(const part of m2.content){if(!isObj(part))continue;if(protocol==="openai"){if(part.type==="image_url"){if(urlOf(part.image_url))n+=1;continue}if(part.type==="file"){n+=1;continue}if(part.type==="text")continue;if(m2.role==="user")n+=1;continue}else{if(part.type==="image"){const src=part.source;if(isObj(src)&&src.type==="base64"&&typeof src.data==="string")n+=1;else if(isObj(src)&&src.type==="url"&&typeof src.url==="string")n+=1;continue}if(part.type==="redacted_thinking"&&typeof part.data==="string"){n+=1;continue}if(part.type==="tool_result"&&Array.isArray(part.content)){for(const c of part.content){if(!isObj(c)||c.type==="text")continue;n+=1}continue}}}}return n}function countImagesInRawBody(protocol,raw){const s3=typeof raw==="string"?raw:raw.toString("utf8");if(!bodyHasImagesProbe(protocol,s3))return 0;try{return countImagesInParsedBody(protocol,JSON.parse(s3))}catch{return 0}}var IMAGE_PLACEHOLDER="[image]";function isObj2(v2){return typeof v2==="object"&&v2!==null}function refFromDataUrl(url){if(typeof url!=="string")return void 0;const d=parseDataUrl(url);return d?{mediaType:d.mediaType,b64:d.base64}:void 0}function opaqueLabel(part){const t=typeof part.type==="string"?part.type:"media";const kb=Math.max(1,Math.round(JSON.stringify(part).length/1024));return`${t} ~${kb}KB`}function messageImages(m2){const mm=m2;const ab2=mm.rawAnthropicBlock;if(isObj2(ab2)&&ab2.type==="image"){const s3=ab2.source;const mediaType=isObj2(s3)&&typeof s3.media_type==="string"?s3.media_type:void 0;if(isObj2(s3)&&s3.type==="base64"&&typeof s3.data==="string"){return[{mediaType,b64:s3.data}]}if(isObj2(s3)&&s3.type==="url"){return[refFromDataUrl(s3.url)??{mediaType}]}return[{mediaType}]}if(isObj2(ab2)&&ab2.type==="tool_result"&&Array.isArray(ab2.content)){const refs=[];for(const c of ab2.content){if(!isObj2(c)||c.type==="text")continue;const s3=c.source;if(isObj2(s3)&&s3.type==="base64"&&typeof s3.data==="string"){refs.push({mediaType:isObj2(s3)&&typeof s3.media_type==="string"?s3.media_type:void 0,b64:s3.data})}else if(isObj2(s3)&&s3.type==="url"){refs.push(refFromDataUrl(s3.url)??{})}else{refs.push({label:opaqueLabel(c)})}}if(refs.length>0)return refs}const ri2=mm.rawResponsesItem;const responseParts=isObj2(ri2)&&Array.isArray(ri2.content)?ri2.content:responsesToolImageParts(ri2);if(responseParts){const refs=[];for(const part of responseParts){if(!isObj2(part)||part.type!=="input_image")continue;refs.push(refFromDataUrl(part.image_url)??{})}if(refs.length>0)return refs}if(typeof mm.imageBase64==="string"){return[{mediaType:mm.imageMediaType,b64:mm.imageBase64}]}if(Array.isArray(mm.rawOpenaiContentParts)){const refs=[];for(const p2 of mm.rawOpenaiContentParts){if(!isObj2(p2))continue;if(p2.type==="image_url"){refs.push(refFromDataUrl(isObj2(p2.image_url)?p2.image_url.url:void 0)??{});continue}refs.push({label:opaqueLabel(p2)})}if(refs.length>0)return refs}if(isObj2(mm.rawOpenaiContent)&&mm.rawOpenaiContent.type==="image_url"){return[refFromDataUrl(isObj2(mm.rawOpenaiContent.image_url)?mm.rawOpenaiContent.image_url.url:void 0)??{}]}return[]}function imagePlaceholders(m2){return messageImages(m2).map(ref=>{if(ref.label&&!ref.b64)return`[media: ${ref.label}]`;let note="";if(ref.mediaType)note+=ref.mediaType.includes("/")?ref.mediaType.split("/").pop():ref.mediaType;if(ref.b64){const dims=decodeImageDims(ref.b64);if(dims)note+=`${note?" ":""}${dims.w}x${dims.h}`}return note?`[image: ${note}]`:IMAGE_PLACEHOLDER})}function imagePlaceholdersForSummary(m2,ref){const notes=imagePlaceholders(m2);if(ref===void 0)return notes;return notes.map(n=>`${n.slice(0,-1)} \xB7 ${ref}]`)}init_dist();init_dist();init_logger();init_proxy_tool_result();var EFFECTIVE_RULES_KEY="effectiveRules";function rulesEnabled(config){return config.rules?.enabled===true}function effectiveRulesConfig(session,fallback){const meta=session?.metadata[EFFECTIVE_RULES_KEY];if(meta&&typeof meta==="object"&&typeof meta.enabled==="boolean"){return meta}return fallback.rules}function storeEffectiveRules(session,config){session.metadata[EFFECTIVE_RULES_KEY]=config.rules??null}function effectiveRulesEnabled(session,fallback){return effectiveRulesConfig(session,fallback)?.enabled===true}function executeRule(args,ctx){const log2=ctx.log??(msg=>log("info",msg));const state7=ctx.session.state;const rawDelete=args.delete;const delId=typeof rawDelete==="string"?rawDelete.trim():"";const wantsClear=args.clear===true;const raw=args.rule;const rule=typeof raw==="string"?raw.trim():"";const ops=[delId.length>0,wantsClear,rule.length>0].filter(Boolean).length;if(ops>1){return toolFail("Use one operation per call: record (rule), remove one (delete), remove all (clear: true), or list (no arguments).")}if(wantsClear){const result2=clearRules(state7);log2(`[acp-rule] cleared ${result2.count} rule(s)`);return toolOk(result2.count===0?"No rules to clear.":`Cleared ${result2.count} rule(s).`)}if(delId.length>0){const result2=removeRule(state7,delId);if(!result2.ok){log2(`[acp-rule] ${result2.error}`);return toolFail(result2.error)}log2(`[acp-rule] removed ${result2.rule.id}: ${result2.rule.text}`);return toolOk(`Removed ${result2.rule.id}: ${result2.rule.text}`)}if(rule.length===0){const rules=listRules(state7);return toolOk(rules.length===0?"No rules recorded.":formatRulesList(rules))}const result=addRule(state7,rule,resolveRuleLimits(ctx.config));if(!result.ok){log2(`[acp-rule] ${result.error}`);return toolFail(result.error)}log2(`[acp-rule] added ${result.rule.id}: ${result.rule.text}`);return toolOk(`Recorded ${result.rule.id}: ${result.rule.text}`)}init_logger();init_proxy_tool_result();var EFFECTIVE_ABSORB_KEY="effectiveAbsorb";function absorbEnabled(config){return config.absorb?.enabled===true}function absorbToolName(config){return config.absorb?.toolName??ABSORB_TOOL_NAME}function effectiveAbsorbConfig(session,fallback){const meta=session?.metadata[EFFECTIVE_ABSORB_KEY];if(meta&&typeof meta==="object"&&typeof meta.enabled==="boolean"){return meta}return fallback.absorb}function storeEffectiveAbsorb(session,config){session.metadata[EFFECTIVE_ABSORB_KEY]=config.absorb??null}function isProxyToolFor(name,session,config){if(ACP_TOOL_NAMES.has(name))return true;if(name===READ_ORIGINAL_IMAGE_TOOL_NAME)return true;const absorb=effectiveAbsorbConfig(session,config);if(absorb?.enabled===true&&name===(absorb.toolName??ABSORB_TOOL_NAME))return true;if(ccrEnabled(session)&&name===retrieveToolName(session))return true;return effectiveRulesEnabled(session,config)&&name===RULE_TOOL_NAME}function applyAbsorbView(messages,state7,config,tokenCount){const hidden=hideAbsorbedMessages(messages,state7);const prompted=appendAbsorbPrompts(hidden,state7,config,tokenCount,defaultCountTokens);return prompted.messages}function executeAbsorb(args,callId,absorb,ctx){const log2=ctx.log??(msg=>log("info",msg));const parsed=parseAbsorbInput(args,callId,w2=>log2(`[acp-absorb] ${w2}`));if(!parsed){return toolFail('[absorb FAILED: invalid input \u2014 expected { ref: "mNNNNN", summary: "..." }]')}const before=ctx.session.state.absorbed?.length??0;let outcome;try{outcome=applyAbsorb({ref:parsed.ref,summary:parsed.summary,absorbCallId:parsed.absorbCallId,messages:ctx.messages,state:ctx.session.state,config:{...ctx.config,absorb}})}catch(err2){log2(`[acp-absorb] error: ${String(err2)}`);return toolFail(`[absorb FAILED: ${String(err2)}]`)}ctx.session.state=outcome.state;if(!outcome.ok){log2(`[acp-absorb] ${outcome.resultText}`);return toolFail(`[absorb FAILED: ${outcome.resultText}]`)}const records=outcome.state.absorbed??[];const record4=records.length>before?records[records.length-1]:void 0;if(record4){ctx.session.stats.compressCreditTokens=(ctx.session.stats.compressCreditTokens??0)+record4.tokensReclaimed;ctx.session.stats.lastInputTokens=Math.max(0,ctx.session.stats.lastInputTokens-record4.tokensReclaimed);log2(`[acp-absorb] ${outcome.resultText} (credit -${record4.tokensReclaimed} tok)`)}else{log2(`[acp-absorb] ${outcome.resultText}`)}return toolOk(outcome.resultText)}init_dist();init_config();import{createHash as createHash25,randomBytes as randomBytes3}from"crypto";init_dist();import{existsSync as existsSync10,mkdirSync as mkdirSync10,unlinkSync as unlinkSync4,writeFileSync as writeFileSync9}from"fs";import{dirname as dirname5,join as join10,resolve as resolvePath}from"path";import{tmpdir}from"os";import{fileURLToPath as fileURLToPath5}from"url";init_text_safe();init_knobs();init_proxy_tool_result();import{existsSync as existsSync9,mkdirSync as mkdirSync9,readdirSync as readdirSync4,rmdirSync,statSync as statSync7,unlinkSync as unlinkSync3,writeFileSync as writeFileSync8}from"fs";import{createHash as createHash24}from"crypto";import{join as join9}from"path";init_logger();init_paths();function isObj3(v2){return typeof v2==="object"&&v2!==null}function dataUrlRef(url){if(typeof url!=="string")return void 0;const d=parseDataUrl(url);return d?{mediaType:d.mediaType,b64:d.base64}:void 0}function b64Bytes(b64){return Math.floor(Buffer.byteLength(b64,"base64")||0)}function messageImageBytes(m2){const mm=m2;const out=[];const ab2=mm.rawAnthropicBlock;if(isObj3(ab2)&&ab2.type==="image"){const s3=ab2.source;const mediaType=isObj3(s3)&&typeof s3.media_type==="string"?s3.media_type:"image/png";if(isObj3(s3)){if(s3.type==="base64"&&typeof s3.data==="string"){out.push({mediaType,b64:s3.data,bytes:b64Bytes(s3.data)})}else if(s3.type==="url"){const r=dataUrlRef(s3.url);if(r?.b64)out.push({mediaType:r.mediaType??mediaType,b64:r.b64,bytes:b64Bytes(r.b64)})}}return out}if(isObj3(ab2)&&ab2.type==="tool_result"&&Array.isArray(ab2.content)){for(const c of ab2.content){if(!isObj3(c)||c.type!=="image")continue;const s3=c.source;const mediaType=isObj3(s3)&&typeof s3.media_type==="string"?s3.media_type:"image/png";if(!isObj3(s3))continue;if(s3.type==="base64"&&typeof s3.data==="string"){out.push({mediaType,b64:s3.data,bytes:b64Bytes(s3.data)})}else if(s3.type==="url"){const r=dataUrlRef(s3.url);if(r?.b64)out.push({mediaType:r.mediaType??mediaType,b64:r.b64,bytes:b64Bytes(r.b64)})}}return out}const ri2=mm.rawResponsesItem;if(isObj3(ri2)){const arr=ri2.type==="function_call_output"||ri2.type==="custom_tool_call_output"?Array.isArray(ri2.output)?ri2.output:void 0:Array.isArray(ri2.content)?ri2.content:void 0;if(arr){for(const part of arr){if(!isObj3(part)||part.type!=="input_image")continue;const u2=isObj3(part.image_url)?part.image_url.url:part.image_url;const r=dataUrlRef(u2);if(r?.b64)out.push({mediaType:r.mediaType??"image/png",b64:r.b64,bytes:b64Bytes(r.b64)})}if(out.length>0)return out}}if(Array.isArray(mm.rawGoogleParts)){for(const part of mm.rawGoogleParts){if(!isObj3(part))continue;const inline=part.inlineData;if(isObj3(inline)&&typeof inline.data==="string"){const mediaType=typeof inline.mimeType==="string"?inline.mimeType:"image/png";out.push({mediaType,b64:inline.data,bytes:b64Bytes(inline.data)})}const fr2=part.functionResponse;if(isObj3(fr2)&&Array.isArray(fr2.parts)){const refGuarded=JSON.stringify(fr2.response??null).includes('"$ref"');if(!refGuarded){for(const np of fr2.parts){if(!isObj3(np))continue;const ni2=np.inlineData;if(isObj3(ni2)&&typeof ni2.data==="string"&&typeof ni2.mimeType==="string"&&ni2.mimeType.startsWith("image/")){out.push({mediaType:ni2.mimeType,b64:ni2.data,bytes:b64Bytes(ni2.data)})}}}}}if(out.length>0)return out}if(Array.isArray(mm.rawOpenaiContentParts)){for(const p2 of mm.rawOpenaiContentParts){if(!isObj3(p2)||p2.type!=="image_url")continue;const u2=isObj3(p2.image_url)?p2.image_url.url:void 0;const r=dataUrlRef(u2);if(r?.b64)out.push({mediaType:r.mediaType??"image/png",b64:r.b64,bytes:b64Bytes(r.b64)})}if(out.length>0)return out}if(isObj3(mm.rawOpenaiContent)&&mm.rawOpenaiContent.type==="image_url"){const u2=isObj3(mm.rawOpenaiContent.image_url)?mm.rawOpenaiContent.image_url.url:void 0;const r=dataUrlRef(u2);if(r?.b64)out.push({mediaType:r.mediaType??"image/png",b64:r.b64,bytes:b64Bytes(r.b64)});if(out.length>0)return out}if(typeof mm.imageBase64==="string"){out.push({mediaType:typeof mm.imageMediaType==="string"?mm.imageMediaType:"image/png",b64:mm.imageBase64,bytes:b64Bytes(mm.imageBase64)})}return out}function coreMsgsOf(result){if(Array.isArray(result))return result;if(isObj3(result)&&Array.isArray(result.msgs)){return result.msgs}return void 0}function bodyMightCarryImages(bodyText,protocol){switch(protocol){case"anthropic":return/"data:[^;,"]+(?:;base64)?,/i.test(bodyText)||/"type"\s*:\s*"base64"/.test(bodyText);case"google":return/"inlineData"\s*:/.test(bodyText);default:return/"data:[^;,"]+(?:;base64)?,/i.test(bodyText)}}var conversionWarned=new Set;function buildIncomingImageIndex(parsed,protocol,state7,sessionId){const index=new Map;const byRaw=state7?.messageRefs?.byRaw;if(!byRaw)return index;let result;try{switch(protocol){case"anthropic":result=anthropicToCore(parsed);break;case"openai":result=openaiToCore(parsed);break;case"google":result=googleToCore(parsed);break;case"responses":result=responsesToCore(parsed);break}}catch(e){const sig=`${protocol}:${String(e?.message??e).slice(0,120)}`;if(!conversionWarned.has(sig)){conversionWarned.add(sig);log("warn",`[image-restore] inbound index conversion failed \u2014 images in affected sessions are NOT recoverable until this wire shape is handled (${sig}; #2824 class \u2014 please report the body shape)`)}return index}const msgs=coreMsgsOf(result);if(!msgs)return index;for(const m2 of msgs){const ref=m2.id?byRaw[m2.id]:void 0;if(!ref)continue;const imgs=messageImageBytes(m2);if(imgs.length===0)continue;const arr=index.get(ref)??[];if(!index.has(ref))index.set(ref,arr);imgs.forEach((im,i)=>{const path53=writeRestoredImage(ref,i,im,sessionId);if(!path53)return;let width;let height;try{const d=decodeImageDims(im.b64);if(d){width=d.w;height=d.h}}catch{}arr.push({mediaType:im.mediaType,bytes:im.bytes,width,height,path:path53})})}return index}function refreshIncomingImageIndex(parsed,protocol,state7,sessionId,existing){const fresh=buildIncomingImageIndex(parsed,protocol,state7,sessionId);if(fresh.size===0)return existing??new Map;const merged=existing?new Map(existing):new Map;const seen=new Set;for(const imgs of merged.values())for(const im of imgs)seen.add(im.path);for(const[ref,imgs]of fresh){const kept=imgs.filter(im=>!seen.has(im.path));if(kept.length===0)continue;for(const im of kept)seen.add(im.path);const prev=merged.get(ref);merged.set(ref,prev?[...prev,...kept]:kept)}return merged}function pruneRetrieveImgExports(sessionId,ttlMs=7*24*3600*1e3){const dir=restoreExportDir(sessionId);let entries2;try{entries2=readdirSync4(dir)}catch{return 0}const now=Date.now();let removed=0;for(const name of entries2){const p2=join9(dir,name);try{const st2=statSync7(p2);if(st2.isFile()&&now-st2.mtimeMs>ttlMs){unlinkSync3(p2);removed++}}catch{}}if(removed>0){try{if(readdirSync4(dir).length===0)rmdirSync(dir)}catch{}}return removed}function refNum5(ref){const m2=/^m(\d+)$/i.exec(ref.trim());return m2?Number.parseInt(m2[1],10):Number.MAX_SAFE_INTEGER}function describeRestorable(index,cap=50){const lines=[];const refs=[...index.keys()].sort((a,b2)=>refNum5(a)-refNum5(b2));outer:for(const ref of refs){const imgs=index.get(ref);for(let i=0;i<imgs.length;i++){const im=imgs[i];let note=im.mediaType.includes("/")?im.mediaType.split("/").pop():im.mediaType;if(im.width!=null&&im.height!=null)note+=` ${im.width}x${im.height}`;note+=` \xB7 ${Math.max(1,Math.round(im.bytes/1024))}KB`;lines.push(`${ref}${i>0?`[-${i}]`:""} [${note}]`);if(lines.length>=cap)break outer}}return lines}function restoreExportDirName(sessionId){const safe=sessionId.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,100);return safe===sessionId?safe||"session":`${safe||"session"}-${createHash24("sha256").update(sessionId).digest("hex").slice(0,8)}`}function restoreExportDir(sessionId){return join9(stateDir(),"retrieve","img",restoreExportDirName(sessionId))}function extFor(mediaType){const sub=(mediaType.split("/")[1]??"").toLowerCase();const map={png:"png",jpeg:"jpg",jpg:"jpg",gif:"gif",webp:"webp",svg:"svg"};return map[sub]??"img"}function writeRestoredImage(ref,idx,img,sessionId){const safeRef=ref.replace(/[^a-zA-Z0-9_-]/g,"-");const dir=restoreExportDir(sessionId);const body=Buffer.from(img.b64,"base64");const digest=createHash24("sha256").update(body).digest("hex").slice(0,8);const path53=join9(dir,`${safeRef}${idx>0?`-${idx}`:""}-${digest}.${extFor(img.mediaType)}`);try{if(existsSync9(path53))return path53;mkdirSync9(dir,{recursive:true});writeFileSync8(path53,body,{mode:384});return path53}catch(e){log("warn",`[image-restore] write failed (${path53}): ${String(e)}`);return null}}var trackedTempFiles=[];function getDecompressTmpCap(){return decompressTmpCap()}function reapTempFiles(){const cap=getDecompressTmpCap();while(trackedTempFiles.length>cap){trackedTempFiles.sort((a,b2)=>a.mtimeMs-b2.mtimeMs);const oldest=trackedTempFiles.shift();if(!oldest)break;try{unlinkSync4(oldest.path)}catch{}}}process.on("beforeExit",()=>{for(const f2 of trackedTempFiles){try{unlinkSync4(f2.path)}catch{}}trackedTempFiles.length=0});function resolveToFileTarget(target){const uri=target.match(/^([a-zA-Z][a-zA-Z0-9+.\-]*):\/\//);if(uri&&uri[1].length>=2){const scheme=uri[1].toLowerCase();if(scheme==="file"){try{return{resolved:fileURLToPath5(new URL(target))}}catch(e){return{refusal:`malformed file:// URI "${target}" (${String(e)})`}}}return{refusal:`unsupported virtual URI scheme "${scheme}" in toFile "${target}" \u2014 bili writes to the local filesystem only; pass an actual filesystem path (absolute, or relative to the proxy cwd) or a file:// URI`}}return{resolved:resolvePath(target)}}function exportFailureReceipt(path53,err2,body){const preview=safePrefix(body,4e3);const scope=preview.length<body.length?`partial content follows (${preview.length} of ${body.length} chars)`:"full content follows";return toolFail(`[decompress FAILED: could not write export to ${path53}: ${String(err2)}]
|
|
977
977
|
The export did NOT complete \u2014 ${scope}. Retry with a writable filesystem path, or omit toFile to restore inline.
|
|
978
978
|
`+preview)}function toFilePointer(args,ctx,header,body){const raw=args.toFile;if(raw===void 0||raw===null)return null;if(typeof raw!=="string"){ctx.log(`[acp-decompress] toFile must be a string (got ${typeof raw}) \u2014 using default output`);return null}const target=raw.trim();if(target==="")return null;const t=resolveToFileTarget(target);if(t.refusal!==void 0){ctx.log(`[acp-decompress] toFile refused before any file operation: ${t.refusal}`);return toolFail(`[decompress FAILED: ${t.refusal}]`)}const resolved=t.resolved;try{mkdirSync10(dirname5(resolved),{recursive:true});writeFileSync9(resolved,body,{encoding:"utf8",mode:384});return toolOk(`${header}
|
|
979
979
|
Content (${body.length} chars) written to: ${resolved}
|
|
@@ -1044,7 +1044,7 @@ ${subagentSessionNote(b2.blockId,ids)}`;msg+=note;logMsg2+=note}}if(changedBlock
|
|
|
1044
1044
|
[truncated: ${omitted} more character(s)]
|
|
1045
1045
|
`;const available=budget-textBytes(marker(text2.length),escaped);let lo2=0;let hi2=Math.min(text2.length,Math.max(0,Math.floor(available)));while(lo2<hi2){const mid=Math.ceil((lo2+hi2)/2);if(textBytes(safePrefix(text2,mid),escaped)<=available)lo2=mid;else hi2=mid-1}const prefix=safePrefix(text2,lo2);return prefix+marker(text2.length-prefix.length)}function dumpRejectedBody(status,sessionId,body){if(!dump4xxEnabled())return null;const raw=typeof body==="string"?body:body.toString("utf8");if(!raw)return null;try{const cap=cappedBudget();let text2=raw;if(Buffer.byteLength(raw)<=cap){try{text2=JSON.stringify(JSON.parse(raw),null,2)}catch{}}text2=capText(text2,cap);const dir=dumpsDir();fs17.mkdirSync(dir,{recursive:true});const sid=sessionId.replace(/[^a-zA-Z0-9_-]/g,"_");const out=path33.join(dir,`err-${Date.now()}-${sid}-${status}.json`);fs17.writeFileSync(out,`${DUMP_PLAINTEXT_BANNER}
|
|
1046
1046
|
${text2}`);log("info",`[dump] upstream ${status} rejected body written to ${out}`);gcDumpDirIfConfigured(dir);return out}catch(err2){warnDumpFailure(err2);return null}}function dumpSummaryRejection(status,sessionId,request,response){if(!dump4xxEnabled())return null;if(!request&&!response)return null;try{const cap=cappedBudget();const side=raw=>{if(Buffer.byteLength(raw)>cap)return raw;try{return JSON.stringify(JSON.parse(raw))}catch{return raw}};const requestText2=side(request);const responseText=side(response);const overhead=Buffer.byteLength(JSON.stringify({status,request:"",response:""},null,2));const budget=cap-overhead;const requestBytes=textBytes(requestText2,true,budget);const responseBytes=textBytes(responseText,true,budget);const requestBudget=Math.min(requestBytes,Math.max(budget-responseBytes,Math.floor(budget/2)));const envelope={status,request:capText(requestText2,requestBudget,true),response:capText(responseText,budget-requestBudget,true)};const dir=dumpsDir();fs17.mkdirSync(dir,{recursive:true});const sid=sessionId.replace(/[^a-zA-Z0-9_-]/g,"_");const out=path33.join(dir,`summary-err-${Date.now()}-${sid}-${status}.json`);fs17.writeFileSync(out,`${DUMP_PLAINTEXT_BANNER}
|
|
1047
|
-
${JSON.stringify(envelope,null,2)}`);log("info",`[dump] upstream ${status} rejected summary exchange written to ${out}`);gcDumpDirIfConfigured(dir);return out}catch(err2){warnDumpFailure(err2);return null}}init_upstream_proxy();init_upstream_fail();var MAX_DEAD_RANGES=64;var STORAGE_KEY="preflightDeadRanges";function readStore(session){const raw=session.metadata?.[STORAGE_KEY];if(!Array.isArray(raw))return[];return raw.filter(e=>!!e&&typeof e==="object"&&typeof e.key==="string"&&typeof e.startRef==="string"&&typeof e.endRef==="string"&&Array.isArray(e.blocks)&&Array.isArray(e.activeSnapshot))}function writeStore(session,store2){(session.metadata??(session.metadata={}))[STORAGE_KEY]=store2;markDirty(session)}function activeBlockIds(session){return session.state.blocks.filter(b2=>b2.active).map(b2=>b2.blockId).sort()}var STRUCTURAL_EMPTY_VERDICTS=/no (?:new )?compressible messages|folded nothing — every message in it is already covered by active block\(s\)|folded nothing — all of its content is protected or filtered/;function parseStructuralEmptyVerdict(verdict){if(!STRUCTURAL_EMPTY_VERDICTS.test(verdict))return null;const named=/active block\(s\) ([A-Za-z0-9]+(?:,\s*[A-Za-z0-9]+)*)/.exec(verdict)?.[1]??"";return named?named.split(/,\s*/).filter(Boolean):[]}function recordDeadRange(session,startRef,endRef,namedBlocks){const key2=`${startRef}:${endRef}`;const store2=readStore(session).filter(e=>e.key!==key2);store2.push({key:key2,startRef,endRef,blocks:namedBlocks,activeSnapshot:activeBlockIds(session)});while(store2.length>MAX_DEAD_RANGES)store2.shift();writeStore(session,store2)}function deadSkipKeys(session){const current=new Set(activeBlockIds(session));const seen=readStore(session);const kept=seen.filter(e=>e.activeSnapshot.every(id=>current.has(id)));if(kept.length!==seen.length)writeStore(session,kept);return new Set(kept.map(e=>e.key))}function filterDeadRanges(session,ranges){const dead=deadSkipKeys(session);return ranges.filter(r=>!dead.has(`${r.startRef}:${r.endRef}`))}init_registry();init_text_safe();init_util();var MAX_PREFLIGHT_ROUNDS=16;var CHUNK_FRACTION=.6;var MIN_CHUNK_TOKENS=2e3;var MIN_SUMMARY_CHARS=50;var SUMMARY_JOIN_GAP=2;var MAX_SUMMARY_OUTPUT_TOKENS=32768;var MAX_SUMMARY_CALLS_PER_PREFLIGHT=16;var MAX_PREFLIGHT_SUMMARY_BATCH=4;var MAX_TIER_DISTILL_CALLS=6;var TIER_DISTILL_SOURCE_CHAR_BUDGET=6e4;var NET_SHRINK_TOLERANCE=1.05;var TRANSIENT_EMPTY_SUMMARY_RETRIES=2;var TRANSIENT_EMPTY_RETRY_BUDGET=4;var DETERMINISTIC_EMPTY_STICKY_LIMIT=3;var FUTILITY_SLACK=1.2;var EMERGENCY_FOLD_COVERAGE=MAX_PREFLIGHT_ROUNDS*2*CHUNK_FRACTION;var EMERGENCY_ROUND_CAP=512;var DIGEST_HEAD_CHARS=120;var BILLING_ATTRIBUTION_PREFIX="x-anthropic-billing-header:";function extractBillingAttributionBlock(system){if(!Array.isArray(system))return void 0;for(const block of system){if(!block||typeof block!=="object"||block.type!=="text")continue;const text2=block.text;if(typeof text2==="string"&&text2.trimStart().startsWith(BILLING_ATTRIBUTION_PREFIX)){return{type:"text",text:text2}}}return void 0}function isCredentialShapeRejection(status,body){if(status!==429)return false;try{const parsed=JSON.parse(body);return parsed.error?.type==="rate_limit_error"&&parsed.error.message==="Error"}catch{return false}}function foldTargetKey(block,state7){return JSON.stringify([block.directMessageIds,block.effectiveMessageIds,block.directBlockIds.map(id=>{const source=state7.blocks.find(candidate=>candidate.blockId===id);return source&&[source.blockId,source.tier,source.topic,source.summary,source.directMessageIds,source.effectiveMessageIds,source.directBlockIds]})])}function previewFoldTargetKey(core,messages,state7,config,startRef,endRef){const summary="x".repeat(Math.max(MIN_SUMMARY_CHARS,config.compress.minSummaryLength));const preview=core.applyCompression({messages,state:state7,config,ranges:[{startRef,endRef,summary}]});const known=new Set(state7.blocks.map(block=>block.blockId));const target=preview.state.blocks.find(block=>!known.has(block.blockId));return target&&foldTargetKey(target,state7)}function refMaps(messages,state7){const refToIdx=new Map;const idxToRef=new Map;const byRaw=state7.messageRefs?.byRaw??{};messages.forEach((m2,i)=>{const ref=byRaw[m2.id];if(!ref)return;if(!refToIdx.has(ref))refToIdx.set(ref,i);idxToRef.set(i,ref)});return{refToIdx,idxToRef}}function refNum9(ref){return Number(ref.replace(/\D/g,""))||0}var messageTokenMemo=new Map;var MESSAGE_TOKEN_MEMO_CAP=2e5;var KERNEL_MINTED_ID=/^h_[0-9a-f]{16}(?:_\d+)?$/;function estimateCoreMessages(messages){let tokens=0;for(const m2 of messages){const id=m2.id;if(KERNEL_MINTED_ID.test(id)){const textLength=m2.text===void 0?-1:m2.text.length;const key2=`${id}|${textLength}|${m2.thinkingTokens??""}`;const cached=messageTokenMemo.get(key2);if(cached!==void 0){tokens+=cached;continue}const counted=countMessageTokens(m2,defaultCountTokens);if(messageTokenMemo.size>=MESSAGE_TOKEN_MEMO_CAP)messageTokenMemo.clear();messageTokenMemo.set(key2,counted);tokens+=counted}else{tokens+=countMessageTokens(m2,defaultCountTokens)}}return tokens}var NON_TEXT_BODY_KEYS=new Set(["data","url","b64_json","file_data"]);function estimateRawBodyTokens(parsed){let tokens=0;const walk=(value,key2)=>{if(typeof value==="string"){if(!key2||!NON_TEXT_BODY_KEYS.has(key2))tokens+=defaultCountTokens(value);return}if(Array.isArray(value)){for(const item of value)walk(item,key2);return}if(value&&typeof value==="object"){for(const[k2,v2]of Object.entries(value))walk(v2,k2)}};walk(parsed);return tokens}function estimateCoreMessagesUpper(messages){let chars=0;for(const m2 of messages)chars+=(m2.text??"").length;return chars}function estimateCoreMessagesUpperBytes(messages){let bytes=0;for(const m2 of messages)bytes+=Buffer.byteLength(m2.text??"","utf8");return bytes}var ACP_REF_TAG_PREFIX=/^\n?\x3cacp\s[^>]*\x3em\d+\x3c\/acp\x3e\n?/;function measureCoreTextDuplication(messages){const distinct=new Map;let totalBytes=0;let messageCount=0;for(const m2 of messages){const text2=(m2.text??"").replace(ACP_REF_TAG_PREFIX,"");const bytes=Buffer.byteLength(text2,"utf8");if(bytes===0)continue;messageCount++;totalBytes+=bytes;const key2=createHash26("sha256").update(text2,"utf8").digest("base64");if(!distinct.has(key2))distinct.set(key2,bytes)}let uniqueBytes=0;for(const bytes of distinct.values())uniqueBytes+=bytes;return{messageCount,totalBytes,uniqueBytes,distinctTexts:distinct.size}}function describeCoreTextDuplication(messages){const d=measureCoreTextDuplication(messages);if(d.totalBytes===0)return"core text is empty";const ratio=1-d.uniqueBytes/d.totalBytes;return`${d.messageCount} message(s), ${d.totalBytes}B core over ${d.distinctTexts} distinct text(s), ${d.uniqueBytes}B unique, duplicateRatio=${ratio.toFixed(3)} \u2014 repeats are billed as tokens; a high ratio means the payload grew by repetition (fold/view build), not by content (#4079)`}function spanUnitsOf(messages,startIdx,endIdx,countText){let units=0;for(let i=startIdx;i<=endIdx&&i<messages.length;i++){units+=countText(messages[i].text??"")}return units}function snapToUsableBounds(idxToRef,lo2,hi2){let l=lo2;let h=hi2;const usable=i=>{const ref=idxToRef.get(i);return ref!==void 0&&ref!==BLOCKED_REF};while(l<=h&&!usable(l))l+=1;while(h>=l&&!usable(h))h-=1;return l<=h?[l,h]:null}function pushSpanHalves(idxToRef,spans,cs2,ce2){const mid=Math.floor((cs2+ce2)/2);const upper=snapToUsableBounds(idxToRef,mid+1,ce2);if(upper)spans.push(upper);const lower=snapToUsableBounds(idxToRef,cs2,mid);if(lower)spans.push(lower)}function splitSummaryContent(content,budget,countTokens){const chunks=[];let offset=0;while(offset<content.length){let low=offset+1;let high=content.length;while(low<high){const mid=Math.ceil((low+high)/2);if(countTokens(content.slice(offset,mid))<=budget)low=mid;else high=mid-1}if(low-offset>1&&low<content.length){const c=content.charCodeAt(low-1);if(c>=55296&&c<=56319)low-=1}chunks.push(content.slice(offset,low));offset=low}return chunks}function truncateSummaryToLimit(text2,maxChars,minChars){if(text2.length<=maxChars)return text2;const marker="\n[truncated]";const room=maxChars-marker.length;if(room<minChars)return null;let cut=text2.lastIndexOf("\n",room);if(cut<minChars)cut=room;const out=`${text2.slice(0,cut)}${marker}`;return out.length<=maxChars&&out.trim().length>=minChars?out:null}function mergeSubMinimumFragments(messages,spans,minChars,isCoveredIdx){if(minChars<=0||spans.length===0)return spans;const chars=s3=>{let total=0;for(let i=s3[0];i<=s3[1];i++)total+=(messages[i]?.text??"").length;return total};const out=[];let fragStart=-1;for(let i=0;i<spans.length;i++){const s3=spans[i];const run=fragStart>=0?[fragStart,s3[1]]:[s3[0],s3[1]];const blockedByCoverage=i+1<spans.length&&(isCoveredIdx?.(spans[i+1][0])??false);if(chars(run)<minChars&&i<spans.length-1&&!blockedByCoverage){fragStart=run[0];continue}if(chars(run)<minChars&&out.length>0)out[out.length-1][1]=run[1];else out.push(run);fragStart=-1}return out}function splitChunks(messages,startIdx,endIdx,budget,minUnits,countText=defaultCountTokens){const chunks=[];let cur=startIdx;while(cur<=endIdx){let total=0;let last=cur;for(let i=cur;i<=endIdx;i++){const t=countText(messages[i].text??"");if(total+t>budget&&i>cur&&(minUnits<=0||total>=minUnits))break;total+=t;last=i}chunks.push([cur,last]);cur=last+1}return chunks}function safeHost(url){try{return new URL(url).host}catch{return void 0}}function summaryOutputTokens(model,host){const known=peekRegistryOutputLimit(model,host);return known===void 0?MAX_SUMMARY_OUTPUT_TOKENS:Math.min(MAX_SUMMARY_OUTPUT_TOKENS,known)}var SUMMARY_SCRAFFOLDING_TOKENS=256;var MIN_CLAMPED_SUMMARY_OUTPUT=64;function windowClampedOutput(base,window2,system,content){if(!window2||window2<=0)return base;const input=defaultCountTokens(system)+defaultCountTokens(content)+SUMMARY_SCRAFFOLDING_TOKENS;const headroom=window2-input;if(headroom<=0)return base;return Math.min(base,Math.max(MIN_CLAMPED_SUMMARY_OUTPUT,headroom))}function summaryPayload(protocol,model,system,content,stream2,includeMaxOutputTokens,host,window2,billingBlock,codexClient){const maxOutputTokens=windowClampedOutput(summaryOutputTokens(model,host),window2,system,content);if(protocol==="anthropic"){const systemOut=billingBlock?[billingBlock,{type:"text",text:system}]:system;return{model,max_tokens:maxOutputTokens,system:systemOut,messages:[{role:"user",content}],stream:stream2}}if(protocol==="openai"){return{model,max_tokens:maxOutputTokens,messages:[{role:"system",content:system},{role:"user",content}],stream:stream2}}if(protocol==="google"){const payload2={contents:[{role:"user",parts:[{text:content}]}]};if(system)payload2.systemInstruction={parts:[{text:system}]};if(includeMaxOutputTokens)payload2.generationConfig={maxOutputTokens:MAX_SUMMARY_OUTPUT_TOKENS};return payload2}const input=codexClient?[{type:"message",role:"user",content:[{type:"input_text",text:content}]}]:[{role:"user",content}];const payload={model,instructions:system,input,stream:stream2,store:false};if(codexClient)payload.include=["reasoning.encrypted_content"];if(includeMaxOutputTokens)payload.max_output_tokens=maxOutputTokens;return payload}var STREAM_REQUIRED_RE=/\bstream\b[^\n]{0,60}\btrue\b/i;var MAX_OUTPUT_TOKENS_REJECTED_RE=/\bmax_output_tokens\b/i;function noMaxOutputTokensKey(deps){return`${deps.url}\0${deps.model}`}function hasLearnedNoMaxOutputTokens(deps){const learned=deps.session.metadata.preflightNoMaxOutputTokens;return typeof learned==="object"&&learned!==null&&learned[noMaxOutputTokensKey(deps)]===true}function rememberNoMaxOutputTokens(deps){const learned=deps.session.metadata.preflightNoMaxOutputTokens;const map=typeof learned==="object"&&learned!==null?learned:{};map[noMaxOutputTokensKey(deps)]=true;deps.session.metadata.preflightNoMaxOutputTokens=map}var SUMMARY_STRIP_HEADERS=new Set(["x-openai-internal-codex-responses-lite"]);function summaryHeaders(deps){const headers={};for(const[k2,v2]of Object.entries(deps.headers)){if(SUMMARY_STRIP_HEADERS.has(k2.toLowerCase()))continue;headers[k2]=v2}return headers}function googleChunkText(chunk){const candidates=chunk.candidates;if(!Array.isArray(candidates)||candidates.length===0)return"";const first=candidates[0];if(!first||typeof first!=="object")return"";const content=first.content;if(!content||typeof content!=="object")return"";const parts=content.parts;if(!Array.isArray(parts))return"";let out="";for(const p2 of parts){if(!p2||typeof p2!=="object")continue;const part=p2;if(part.thought===true)continue;if(typeof part.text==="string")out+=part.text}return out}function extractSummaryFromSse(protocol,text2){const framed=/\r?\n\r?\n$/.test(text2);let out="";let terminalText="";let completed2=false;let invalid=false;let badFrame=false;let eventType="";for(const line of text2.split("\n")){if(line.trim()===""){eventType="";continue}if(line.startsWith("event:")){eventType=line.slice(6).trim();continue}if(!line.startsWith("data:"))continue;const payload=line.slice(5).trim();if(!payload||payload==="[DONE]")continue;let obj;try{obj=JSON.parse(payload)}catch{badFrame=true;continue}if(!obj||typeof obj!=="object"){badFrame=true;continue}const o=obj;const type=typeof o.type==="string"?o.type:eventType;if(type==="error"||type==="response.incomplete"||type==="response.failed"||type==="response.error"||!type&&o.error&&typeof o.error==="object"){invalid=true;continue}if(protocol==="anthropic"){if(type==="content_block_delta"){const d=o.delta;if(d&&d.type==="text_delta"&&typeof d.text==="string")out+=d.text}}else if(protocol==="openai"){const choices=o.choices;if(Array.isArray(choices)&&choices.length>0){const delta=choices[0].delta;if(delta&&typeof delta.content==="string")out+=delta.content}}else if(protocol==="google"){out+=googleChunkText(o)}else{if(type==="response.output_text.delta"&&typeof o.delta==="string"){out+=o.delta}else if(type==="response.output_text.done"&&typeof o.text==="string"){terminalText+=o.text}else if(type==="response.output_item.done"&&o.item&&typeof o.item==="object"){terminalText+=extractSummaryText("responses",{output:[o.item]})}else if(type==="response.completed"&&o.response&&typeof o.response==="object"){completed2=true;const full=extractSummaryText("responses",o.response);if(full)terminalText=full}}}if(invalid)return"";if(protocol==="responses")return completed2?terminalText||out:"";if(badFrame||!framed)return"";return out||terminalText}function extractSummaryText(protocol,json){if(protocol==="anthropic"){const content=json.content;if(!Array.isArray(content))return"";return content.map(c=>c&&typeof c==="object"&&c.type==="text"&&typeof c.text==="string"?c.text:"").join("")}if(protocol==="openai"){const choices=json.choices;if(!Array.isArray(choices)||choices.length===0)return"";const msg=choices[0].message;if(!msg||typeof msg!=="object")return"";const c=msg.content;if(typeof c==="string")return c;if(Array.isArray(c)){return c.map(p2=>p2&&typeof p2==="object"&&typeof p2.text==="string"?p2.text:"").join("")}return""}if(protocol==="google"){const chunks=Array.isArray(json)?json:[json];return chunks.map(c=>c&&typeof c==="object"?googleChunkText(c):"").join("")}const status=typeof json.status==="string"?json.status:void 0;if(status==="incomplete"||status==="failed")return"";if(typeof json.output_text==="string")return json.output_text;const output=json.output;if(!Array.isArray(output))return"";return output.map(o=>{if(!o||typeof o!=="object")return void 0;const item=o;const itemType=typeof item.type==="string"?item.type:"";if(itemType!==""&&itemType!=="message")return void 0;return item.content}).filter(c=>Array.isArray(c)).flatMap(c=>c).map(p2=>{if(!p2||typeof p2!=="object")return"";const part=p2;const partType=typeof part.type==="string"?part.type:"";if(partType!==""&&partType!=="output_text")return"";return typeof part.text==="string"?part.text:""}).join("")}function extractStreamError(o){const t=typeof o.type==="string"?o.type:void 0;if(t==="error"){const e=o.error;if(e&&typeof e==="object"){const eo2=e;return`the upstream reported an in-stream error: ${typeof eo2.message==="string"?eo2.message:JSON.stringify(eo2).slice(0,200)}`}if(typeof o.message==="string")return`the upstream reported an in-stream error: ${o.message}`;return"the upstream reported an in-stream error"}if(t==="response.failed"||t==="response.error"){const resp=o.response;if(resp&&typeof resp==="object"){const e=resp.error;if(e&&typeof e==="object"){const eo2=e;const code=typeof eo2.code==="string"?` (${eo2.code})`:"";return`the upstream stream ended with a failed response${code}: ${typeof eo2.message==="string"?eo2.message:JSON.stringify(eo2).slice(0,200)}`}}return"the upstream stream ended with a failed response"}if(t==="response.incomplete"){const resp=o.response??{};const status=typeof resp.status==="string"?resp.status:"unknown";const e=resp.error;const msg=e&&typeof e.message==="string"?` (${e.message})`:"";return`the upstream stream ended incomplete (status=${status}${msg})`}if(!t&&o.error&&typeof o.error==="object"){const eo2=o.error;return`the upstream reported an error: ${typeof eo2.message==="string"?eo2.message:JSON.stringify(eo2).slice(0,200)}`}return null}function responsesTerminalDiagnosis(json){const status=typeof json.status==="string"?json.status:void 0;if(status!=="incomplete"&&status!=="failed")return null;if(!Array.isArray(json.output)&&typeof json.output_text!=="string")return null;const parts=[`status=${status}`];if(status==="incomplete"){const details=json.incomplete_details;const reason=details&&typeof details==="object"&&typeof details.reason==="string"?details.reason:void 0;if(reason)parts.push(`reason=${reason}`)}else{const e=json.error;if(e&&typeof e==="object"){const eo2=e;if(typeof eo2.code==="string")parts.push(eo2.code);if(typeof eo2.message==="string")parts.push(eo2.message.slice(0,200))}}const article=status==="incomplete"?"an":"a";return`the upstream returned ${article} ${status} Responses summary (${parts.join(", ")})`}function emptySummaryIsSizeDriven(diagnosis){return/context_length_exceeded|too long|finish_reason=length\b|stop_reason=max_tokens\b|reason=max_output_tokens\b/i.test(diagnosis)}function isDeterministicEmptyCompletion(protocol,json){if(!json||typeof json!=="object")return false;if(extractSummaryText(protocol,json).trim().length>0)return false;const o=json;switch(protocol){case"anthropic":{return o.stop_reason==="end_turn"&&Array.isArray(o.content)}case"openai":{const choices=o.choices;if(!Array.isArray(choices)||choices.length===0)return false;const first=choices[0];if(!first||typeof first!=="object")return false;return first.finish_reason==="stop"}case"responses":{if(!Array.isArray(o.output))return false;if(typeof o.status==="string"&&o.status!=="completed")return false;return true}default:return false}}function diagnoseEmptySummary(text2,json){if(json&&typeof json==="object"){const o=json;const terminal=responsesTerminalDiagnosis(o);if(terminal)return terminal;const err2=extractStreamError(o);if(err2)return err2}let sseEvents=0;let halfLines=0;let firstPayload="";for(const line of text2.split("\n")){if(!line.startsWith("data:"))continue;const payload=line.slice(5).trim();if(!payload||payload==="[DONE]")continue;if(!firstPayload)firstPayload=payload.slice(0,200);let obj;try{obj=JSON.parse(payload)}catch{halfLines+=1;continue}if(!obj||typeof obj!=="object"){halfLines+=1;continue}sseEvents+=1;const err2=extractStreamError(obj);if(err2)return err2}if(halfLines>0&&sseEvents===0)return`the upstream stream had ${halfLines} incomplete data line(s) and no parseable events (stream appears truncated)`;if(sseEvents>0){const truncated=halfLines>0||!/\r?\n\r?\n$/.test(text2)?` (stream appears truncated: ${halfLines>0?`${halfLines} incomplete data line(s)`:"no final frame terminator"})`:"";return`the upstream stream carried ${sseEvents} SSE event(s) but no summary text${truncated} (first event: ${firstPayload})`}const trimmed=text2.trim();if(!trimmed)return"the upstream returned an empty body";const detail=json&&typeof json==="object"?emptyCompletionDetail(json):null;if(detail!==null)return`the upstream returned a plain-JSON completion with empty content${detail}`;return`the upstream returned a non-SSE body with no summary text (first 200 bytes: ${trimmed.slice(0,200)})`}function emptyCompletionDetail(json){const parts=[];const choices=json.choices;if(Array.isArray(choices)&&choices.length>0){const first=choices[0];if(!first||typeof first!=="object")return null;const choice=first;const fr2=choice.finish_reason;if(typeof fr2==="string")parts.push(`finish_reason=${fr2}`);const message=choice.message;if(message&&typeof message==="object"){const msg=message;if(typeof msg.content==="string"){parts.push(`text_chars=${msg.content.length}`)}else if(Array.isArray(msg.content)){let textBlocks=0;for(const part of msg.content){if(part&&typeof part==="object"&&typeof part.text==="string")textBlocks+=1}parts.push(`text_blocks=${textBlocks}`)}if(typeof msg.reasoning_content==="string"&&msg.reasoning_content.length>0){parts.push(`reasoning_chars=${msg.reasoning_content.length}`)}}}else if(typeof json.stop_reason==="string"){parts.push(`stop_reason=${json.stop_reason}`);if(Array.isArray(json.content)){let textBlocks=0;let thinkingBlocks=0;let reasoningChars=0;for(const block of json.content){if(!block||typeof block!=="object")continue;const b2=block;if(b2.type==="text")textBlocks+=1;else if(b2.type==="thinking"||b2.type==="redacted_thinking"){thinkingBlocks+=1;if(typeof b2.thinking==="string")reasoningChars+=b2.thinking.length}}parts.push(`text_blocks=${textBlocks}`);if(thinkingBlocks>0)parts.push(`thinking_blocks=${thinkingBlocks}`);if(reasoningChars>0)parts.push(`reasoning_chars=${reasoningChars}`)}}else if(Array.isArray(json.output)){if(typeof json.status==="string")parts.push(`status=${json.status}`);let textParts=0;let reasoningChars=0;for(const item of json.output){if(!item||typeof item!=="object")continue;const it2=item;const itemType=typeof it2.type==="string"?it2.type:"";if(itemType==="reasoning"){for(const arr of[it2.content,it2.summary]){if(!Array.isArray(arr))continue;for(const p2 of arr){if(p2&&typeof p2==="object"&&typeof p2.text==="string"){reasoningChars+=p2.text.length}}}}else if(itemType===""||itemType==="message"){const content=it2.content;if(!Array.isArray(content))continue;for(const p2 of content){if(!p2||typeof p2!=="object")continue;const part=p2;const partType=typeof part.type==="string"?part.type:"";if((partType===""||partType==="output_text")&&typeof part.text==="string")textParts+=1}}}parts.push(`text_parts=${textParts}`);if(reasoningChars>0)parts.push(`reasoning_chars=${reasoningChars}`)}else{return null}if(typeof json.model==="string")parts.push(`answered as model=${json.model}`);return parts.length>0?` (${parts.join(", ")})`:""}async function summarizeRange(deps,content,startRef,endRef,lengthBudget,systemOverride){const system=systemOverride??buildCompressSystemPrompt(deps.prompts,messageTimestampSections(deps.surface?.promptSections))+`
|
|
1047
|
+
${JSON.stringify(envelope,null,2)}`);log("info",`[dump] upstream ${status} rejected summary exchange written to ${out}`);gcDumpDirIfConfigured(dir);return out}catch(err2){warnDumpFailure(err2);return null}}init_upstream_proxy();init_upstream_fail();var MAX_DEAD_RANGES=64;var STORAGE_KEY="preflightDeadRanges";function readStore(session){const raw=session.metadata?.[STORAGE_KEY];if(!Array.isArray(raw))return[];return raw.filter(e=>!!e&&typeof e==="object"&&typeof e.key==="string"&&typeof e.startRef==="string"&&typeof e.endRef==="string"&&Array.isArray(e.blocks)&&Array.isArray(e.activeSnapshot))}function writeStore(session,store2){(session.metadata??(session.metadata={}))[STORAGE_KEY]=store2;markDirty(session)}function activeBlockIds(session){return session.state.blocks.filter(b2=>b2.active).map(b2=>b2.blockId).sort()}var STRUCTURAL_EMPTY_VERDICTS=/no (?:new )?compressible messages|folded nothing — every message in it is already covered by active block\(s\)|folded nothing — all of its content is protected or filtered/;function parseStructuralEmptyVerdict(verdict){if(!STRUCTURAL_EMPTY_VERDICTS.test(verdict))return null;const named=/active block\(s\) ([A-Za-z0-9]+(?:,\s*[A-Za-z0-9]+)*)/.exec(verdict)?.[1]??"";return named?named.split(/,\s*/).filter(Boolean):[]}function recordDeadRange(session,startRef,endRef,namedBlocks){const key2=`${startRef}:${endRef}`;const store2=readStore(session).filter(e=>e.key!==key2);store2.push({key:key2,startRef,endRef,blocks:namedBlocks,activeSnapshot:activeBlockIds(session)});while(store2.length>MAX_DEAD_RANGES)store2.shift();writeStore(session,store2)}function deadSkipKeys(session){const current=new Set(activeBlockIds(session));const seen=readStore(session);const kept=seen.filter(e=>e.activeSnapshot.every(id=>current.has(id)));if(kept.length!==seen.length)writeStore(session,kept);return new Set(kept.map(e=>e.key))}function filterDeadRanges(session,ranges){const dead=deadSkipKeys(session);return ranges.filter(r=>!dead.has(`${r.startRef}:${r.endRef}`))}init_registry();init_text_safe();init_util();var MAX_PREFLIGHT_ROUNDS=16;var CHUNK_FRACTION=.6;var MIN_CHUNK_TOKENS=2e3;var MIN_SUMMARY_CHARS=50;var SUMMARY_JOIN_GAP=2;var MAX_SUMMARY_OUTPUT_TOKENS=32768;var MAX_SUMMARY_CALLS_PER_PREFLIGHT=16;var MAX_PREFLIGHT_SUMMARY_BATCH=4;var MAX_TIER_DISTILL_CALLS=6;var TIER_DISTILL_SOURCE_CHAR_BUDGET=6e4;var NET_SHRINK_TOLERANCE=1.05;var TRANSIENT_EMPTY_SUMMARY_RETRIES=2;var TRANSIENT_EMPTY_RETRY_BUDGET=4;var DETERMINISTIC_EMPTY_STICKY_LIMIT=3;var FUTILITY_SLACK=1.2;var FIT_FORWARD_ESTIMATE_ONLY_MARGIN=.85;var EMERGENCY_FOLD_COVERAGE=MAX_PREFLIGHT_ROUNDS*2*CHUNK_FRACTION;var EMERGENCY_ROUND_CAP=512;var DIGEST_HEAD_CHARS=120;var BILLING_ATTRIBUTION_PREFIX="x-anthropic-billing-header:";function extractBillingAttributionBlock(system){if(!Array.isArray(system))return void 0;for(const block of system){if(!block||typeof block!=="object"||block.type!=="text")continue;const text2=block.text;if(typeof text2==="string"&&text2.trimStart().startsWith(BILLING_ATTRIBUTION_PREFIX)){return{type:"text",text:text2}}}return void 0}function isCredentialShapeRejection(status,body){if(status!==429)return false;try{const parsed=JSON.parse(body);return parsed.error?.type==="rate_limit_error"&&parsed.error.message==="Error"}catch{return false}}function foldTargetKey(block,state7){return JSON.stringify([block.directMessageIds,block.effectiveMessageIds,block.directBlockIds.map(id=>{const source=state7.blocks.find(candidate=>candidate.blockId===id);return source&&[source.blockId,source.tier,source.topic,source.summary,source.directMessageIds,source.effectiveMessageIds,source.directBlockIds]})])}function previewFoldTargetKey(core,messages,state7,config,startRef,endRef){const summary="x".repeat(Math.max(MIN_SUMMARY_CHARS,config.compress.minSummaryLength));const preview=core.applyCompression({messages,state:state7,config,ranges:[{startRef,endRef,summary}]});const known=new Set(state7.blocks.map(block=>block.blockId));const target=preview.state.blocks.find(block=>!known.has(block.blockId));return target&&foldTargetKey(target,state7)}function refMaps(messages,state7){const refToIdx=new Map;const idxToRef=new Map;const byRaw=state7.messageRefs?.byRaw??{};messages.forEach((m2,i)=>{const ref=byRaw[m2.id];if(!ref)return;if(!refToIdx.has(ref))refToIdx.set(ref,i);idxToRef.set(i,ref)});return{refToIdx,idxToRef}}function refNum9(ref){return Number(ref.replace(/\D/g,""))||0}var messageTokenMemo=new Map;var MESSAGE_TOKEN_MEMO_CAP=2e5;var KERNEL_MINTED_ID=/^h_[0-9a-f]{16}(?:_\d+)?$/;function estimateCoreMessages(messages){let tokens=0;for(const m2 of messages){const id=m2.id;if(KERNEL_MINTED_ID.test(id)){const textLength=m2.text===void 0?-1:m2.text.length;const key2=`${id}|${textLength}|${m2.thinkingTokens??""}`;const cached=messageTokenMemo.get(key2);if(cached!==void 0){tokens+=cached;continue}const counted=countMessageTokens(m2,defaultCountTokens);if(messageTokenMemo.size>=MESSAGE_TOKEN_MEMO_CAP)messageTokenMemo.clear();messageTokenMemo.set(key2,counted);tokens+=counted}else{tokens+=countMessageTokens(m2,defaultCountTokens)}}return tokens}var NON_TEXT_BODY_KEYS=new Set(["data","url","b64_json","file_data"]);function estimateRawBodyTokens(parsed){let tokens=0;const walk=(value,key2)=>{if(typeof value==="string"){if(!key2||!NON_TEXT_BODY_KEYS.has(key2))tokens+=defaultCountTokens(value);return}if(Array.isArray(value)){for(const item of value)walk(item,key2);return}if(value&&typeof value==="object"){for(const[k2,v2]of Object.entries(value))walk(v2,k2)}};walk(parsed);return tokens}function estimateCoreMessagesUpper(messages){let chars=0;for(const m2 of messages)chars+=(m2.text??"").length;return chars}function estimateCoreMessagesUpperBytes(messages){let bytes=0;for(const m2 of messages)bytes+=Buffer.byteLength(m2.text??"","utf8");return bytes}var ACP_REF_TAG_PREFIX=/^\n?\x3cacp\s[^>]*\x3em\d+\x3c\/acp\x3e\n?/;function measureCoreTextDuplication(messages){const distinct=new Map;let totalBytes=0;let messageCount=0;for(const m2 of messages){const text2=(m2.text??"").replace(ACP_REF_TAG_PREFIX,"");const bytes=Buffer.byteLength(text2,"utf8");if(bytes===0)continue;messageCount++;totalBytes+=bytes;const key2=createHash26("sha256").update(text2,"utf8").digest("base64");if(!distinct.has(key2))distinct.set(key2,bytes)}let uniqueBytes=0;for(const bytes of distinct.values())uniqueBytes+=bytes;return{messageCount,totalBytes,uniqueBytes,distinctTexts:distinct.size}}function describeCoreTextDuplication(messages){const d=measureCoreTextDuplication(messages);if(d.totalBytes===0)return"core text is empty";const ratio=1-d.uniqueBytes/d.totalBytes;return`${d.messageCount} message(s), ${d.totalBytes}B core over ${d.distinctTexts} distinct text(s), ${d.uniqueBytes}B unique, duplicateRatio=${ratio.toFixed(3)} \u2014 repeats are billed as tokens; a high ratio means the payload grew by repetition (fold/view build), not by content (#4079)`}function spanUnitsOf(messages,startIdx,endIdx,countText){let units=0;for(let i=startIdx;i<=endIdx&&i<messages.length;i++){units+=countText(messages[i].text??"")}return units}function snapToUsableBounds(idxToRef,lo2,hi2){let l=lo2;let h=hi2;const usable=i=>{const ref=idxToRef.get(i);return ref!==void 0&&ref!==BLOCKED_REF};while(l<=h&&!usable(l))l+=1;while(h>=l&&!usable(h))h-=1;return l<=h?[l,h]:null}function pushSpanHalves(idxToRef,spans,cs2,ce2){const mid=Math.floor((cs2+ce2)/2);const upper=snapToUsableBounds(idxToRef,mid+1,ce2);if(upper)spans.push(upper);const lower=snapToUsableBounds(idxToRef,cs2,mid);if(lower)spans.push(lower)}function splitSummaryContent(content,budget,countTokens){const chunks=[];let offset=0;while(offset<content.length){let low=offset+1;let high=content.length;while(low<high){const mid=Math.ceil((low+high)/2);if(countTokens(content.slice(offset,mid))<=budget)low=mid;else high=mid-1}if(low-offset>1&&low<content.length){const c=content.charCodeAt(low-1);if(c>=55296&&c<=56319)low-=1}chunks.push(content.slice(offset,low));offset=low}return chunks}function truncateSummaryToLimit(text2,maxChars,minChars){if(text2.length<=maxChars)return text2;const marker="\n[truncated]";const room=maxChars-marker.length;if(room<minChars)return null;let cut=text2.lastIndexOf("\n",room);if(cut<minChars)cut=room;const out=`${text2.slice(0,cut)}${marker}`;return out.length<=maxChars&&out.trim().length>=minChars?out:null}function mergeSubMinimumFragments(messages,spans,minChars,isCoveredIdx){if(minChars<=0||spans.length===0)return spans;const chars=s3=>{let total=0;for(let i=s3[0];i<=s3[1];i++)total+=(messages[i]?.text??"").length;return total};const out=[];let fragStart=-1;for(let i=0;i<spans.length;i++){const s3=spans[i];const run=fragStart>=0?[fragStart,s3[1]]:[s3[0],s3[1]];const blockedByCoverage=i+1<spans.length&&(isCoveredIdx?.(spans[i+1][0])??false);if(chars(run)<minChars&&i<spans.length-1&&!blockedByCoverage){fragStart=run[0];continue}if(chars(run)<minChars&&out.length>0)out[out.length-1][1]=run[1];else out.push(run);fragStart=-1}return out}function splitChunks(messages,startIdx,endIdx,budget,minUnits,countText=defaultCountTokens){const chunks=[];let cur=startIdx;while(cur<=endIdx){let total=0;let last=cur;for(let i=cur;i<=endIdx;i++){const t=countText(messages[i].text??"");if(total+t>budget&&i>cur&&(minUnits<=0||total>=minUnits))break;total+=t;last=i}chunks.push([cur,last]);cur=last+1}return chunks}function safeHost(url){try{return new URL(url).host}catch{return void 0}}function summaryOutputTokens(model,host){const known=peekRegistryOutputLimit(model,host);return known===void 0?MAX_SUMMARY_OUTPUT_TOKENS:Math.min(MAX_SUMMARY_OUTPUT_TOKENS,known)}var SUMMARY_SCRAFFOLDING_TOKENS=256;var MIN_CLAMPED_SUMMARY_OUTPUT=64;function windowClampedOutput(base,window2,system,content){if(!window2||window2<=0)return base;const input=defaultCountTokens(system)+defaultCountTokens(content)+SUMMARY_SCRAFFOLDING_TOKENS;const headroom=window2-input;if(headroom<=0)return base;return Math.min(base,Math.max(MIN_CLAMPED_SUMMARY_OUTPUT,headroom))}function summaryPayload(protocol,model,system,content,stream2,includeMaxOutputTokens,host,window2,billingBlock,codexClient){const maxOutputTokens=windowClampedOutput(summaryOutputTokens(model,host),window2,system,content);if(protocol==="anthropic"){const systemOut=billingBlock?[billingBlock,{type:"text",text:system}]:system;return{model,max_tokens:maxOutputTokens,system:systemOut,messages:[{role:"user",content}],stream:stream2}}if(protocol==="openai"){return{model,max_tokens:maxOutputTokens,messages:[{role:"system",content:system},{role:"user",content}],stream:stream2}}if(protocol==="google"){const payload2={contents:[{role:"user",parts:[{text:content}]}]};if(system)payload2.systemInstruction={parts:[{text:system}]};if(includeMaxOutputTokens)payload2.generationConfig={maxOutputTokens:MAX_SUMMARY_OUTPUT_TOKENS};return payload2}const input=codexClient?[{type:"message",role:"user",content:[{type:"input_text",text:content}]}]:[{role:"user",content}];const payload={model,instructions:system,input,stream:stream2,store:false};if(codexClient)payload.include=["reasoning.encrypted_content"];if(includeMaxOutputTokens)payload.max_output_tokens=maxOutputTokens;return payload}var STREAM_REQUIRED_RE=/\bstream\b[^\n]{0,60}\btrue\b/i;var MAX_OUTPUT_TOKENS_REJECTED_RE=/\bmax_output_tokens\b/i;function noMaxOutputTokensKey(deps){return`${deps.url}\0${deps.model}`}function hasLearnedNoMaxOutputTokens(deps){const learned=deps.session.metadata.preflightNoMaxOutputTokens;return typeof learned==="object"&&learned!==null&&learned[noMaxOutputTokensKey(deps)]===true}function rememberNoMaxOutputTokens(deps){const learned=deps.session.metadata.preflightNoMaxOutputTokens;const map=typeof learned==="object"&&learned!==null?learned:{};map[noMaxOutputTokensKey(deps)]=true;deps.session.metadata.preflightNoMaxOutputTokens=map}var SUMMARY_STRIP_HEADERS=new Set(["x-openai-internal-codex-responses-lite"]);function summaryHeaders(deps){const headers={};for(const[k2,v2]of Object.entries(deps.headers)){if(SUMMARY_STRIP_HEADERS.has(k2.toLowerCase()))continue;headers[k2]=v2}return headers}function googleChunkText(chunk){const candidates=chunk.candidates;if(!Array.isArray(candidates)||candidates.length===0)return"";const first=candidates[0];if(!first||typeof first!=="object")return"";const content=first.content;if(!content||typeof content!=="object")return"";const parts=content.parts;if(!Array.isArray(parts))return"";let out="";for(const p2 of parts){if(!p2||typeof p2!=="object")continue;const part=p2;if(part.thought===true)continue;if(typeof part.text==="string")out+=part.text}return out}function extractSummaryFromSse(protocol,text2){const framed=/\r?\n\r?\n$/.test(text2);let out="";let terminalText="";let completed2=false;let invalid=false;let badFrame=false;let eventType="";for(const line of text2.split("\n")){if(line.trim()===""){eventType="";continue}if(line.startsWith("event:")){eventType=line.slice(6).trim();continue}if(!line.startsWith("data:"))continue;const payload=line.slice(5).trim();if(!payload||payload==="[DONE]")continue;let obj;try{obj=JSON.parse(payload)}catch{badFrame=true;continue}if(!obj||typeof obj!=="object"){badFrame=true;continue}const o=obj;const type=typeof o.type==="string"?o.type:eventType;if(type==="error"||type==="response.incomplete"||type==="response.failed"||type==="response.error"||!type&&o.error&&typeof o.error==="object"){invalid=true;continue}if(protocol==="anthropic"){if(type==="content_block_delta"){const d=o.delta;if(d&&d.type==="text_delta"&&typeof d.text==="string")out+=d.text}}else if(protocol==="openai"){const choices=o.choices;if(Array.isArray(choices)&&choices.length>0){const delta=choices[0].delta;if(delta&&typeof delta.content==="string")out+=delta.content}}else if(protocol==="google"){out+=googleChunkText(o)}else{if(type==="response.output_text.delta"&&typeof o.delta==="string"){out+=o.delta}else if(type==="response.output_text.done"&&typeof o.text==="string"){terminalText+=o.text}else if(type==="response.output_item.done"&&o.item&&typeof o.item==="object"){terminalText+=extractSummaryText("responses",{output:[o.item]})}else if(type==="response.completed"&&o.response&&typeof o.response==="object"){completed2=true;const full=extractSummaryText("responses",o.response);if(full)terminalText=full}}}if(invalid)return"";if(protocol==="responses")return completed2?terminalText||out:"";if(badFrame||!framed)return"";return out||terminalText}function extractSummaryText(protocol,json){if(protocol==="anthropic"){const content=json.content;if(!Array.isArray(content))return"";return content.map(c=>c&&typeof c==="object"&&c.type==="text"&&typeof c.text==="string"?c.text:"").join("")}if(protocol==="openai"){const choices=json.choices;if(!Array.isArray(choices)||choices.length===0)return"";const msg=choices[0].message;if(!msg||typeof msg!=="object")return"";const c=msg.content;if(typeof c==="string")return c;if(Array.isArray(c)){return c.map(p2=>p2&&typeof p2==="object"&&typeof p2.text==="string"?p2.text:"").join("")}return""}if(protocol==="google"){const chunks=Array.isArray(json)?json:[json];return chunks.map(c=>c&&typeof c==="object"?googleChunkText(c):"").join("")}const status=typeof json.status==="string"?json.status:void 0;if(status==="incomplete"||status==="failed")return"";if(typeof json.output_text==="string")return json.output_text;const output=json.output;if(!Array.isArray(output))return"";return output.map(o=>{if(!o||typeof o!=="object")return void 0;const item=o;const itemType=typeof item.type==="string"?item.type:"";if(itemType!==""&&itemType!=="message")return void 0;return item.content}).filter(c=>Array.isArray(c)).flatMap(c=>c).map(p2=>{if(!p2||typeof p2!=="object")return"";const part=p2;const partType=typeof part.type==="string"?part.type:"";if(partType!==""&&partType!=="output_text")return"";return typeof part.text==="string"?part.text:""}).join("")}function extractStreamError(o){const t=typeof o.type==="string"?o.type:void 0;if(t==="error"){const e=o.error;if(e&&typeof e==="object"){const eo2=e;return`the upstream reported an in-stream error: ${typeof eo2.message==="string"?eo2.message:JSON.stringify(eo2).slice(0,200)}`}if(typeof o.message==="string")return`the upstream reported an in-stream error: ${o.message}`;return"the upstream reported an in-stream error"}if(t==="response.failed"||t==="response.error"){const resp=o.response;if(resp&&typeof resp==="object"){const e=resp.error;if(e&&typeof e==="object"){const eo2=e;const code=typeof eo2.code==="string"?` (${eo2.code})`:"";return`the upstream stream ended with a failed response${code}: ${typeof eo2.message==="string"?eo2.message:JSON.stringify(eo2).slice(0,200)}`}}return"the upstream stream ended with a failed response"}if(t==="response.incomplete"){const resp=o.response??{};const status=typeof resp.status==="string"?resp.status:"unknown";const e=resp.error;const msg=e&&typeof e.message==="string"?` (${e.message})`:"";return`the upstream stream ended incomplete (status=${status}${msg})`}if(!t&&o.error&&typeof o.error==="object"){const eo2=o.error;return`the upstream reported an error: ${typeof eo2.message==="string"?eo2.message:JSON.stringify(eo2).slice(0,200)}`}return null}function responsesTerminalDiagnosis(json){const status=typeof json.status==="string"?json.status:void 0;if(status!=="incomplete"&&status!=="failed")return null;if(!Array.isArray(json.output)&&typeof json.output_text!=="string")return null;const parts=[`status=${status}`];if(status==="incomplete"){const details=json.incomplete_details;const reason=details&&typeof details==="object"&&typeof details.reason==="string"?details.reason:void 0;if(reason)parts.push(`reason=${reason}`)}else{const e=json.error;if(e&&typeof e==="object"){const eo2=e;if(typeof eo2.code==="string")parts.push(eo2.code);if(typeof eo2.message==="string")parts.push(eo2.message.slice(0,200))}}const article=status==="incomplete"?"an":"a";return`the upstream returned ${article} ${status} Responses summary (${parts.join(", ")})`}function emptySummaryIsSizeDriven(diagnosis){return/context_length_exceeded|too long|finish_reason=length\b|stop_reason=max_tokens\b|reason=max_output_tokens\b/i.test(diagnosis)}function isDeterministicEmptyCompletion(protocol,json){if(!json||typeof json!=="object")return false;if(extractSummaryText(protocol,json).trim().length>0)return false;const o=json;switch(protocol){case"anthropic":{return o.stop_reason==="end_turn"&&Array.isArray(o.content)}case"openai":{const choices=o.choices;if(!Array.isArray(choices)||choices.length===0)return false;const first=choices[0];if(!first||typeof first!=="object")return false;return first.finish_reason==="stop"}case"responses":{if(!Array.isArray(o.output))return false;if(typeof o.status==="string"&&o.status!=="completed")return false;return true}default:return false}}function diagnoseEmptySummary(text2,json){if(json&&typeof json==="object"){const o=json;const terminal=responsesTerminalDiagnosis(o);if(terminal)return terminal;const err2=extractStreamError(o);if(err2)return err2}let sseEvents=0;let halfLines=0;let firstPayload="";for(const line of text2.split("\n")){if(!line.startsWith("data:"))continue;const payload=line.slice(5).trim();if(!payload||payload==="[DONE]")continue;if(!firstPayload)firstPayload=payload.slice(0,200);let obj;try{obj=JSON.parse(payload)}catch{halfLines+=1;continue}if(!obj||typeof obj!=="object"){halfLines+=1;continue}sseEvents+=1;const err2=extractStreamError(obj);if(err2)return err2}if(halfLines>0&&sseEvents===0)return`the upstream stream had ${halfLines} incomplete data line(s) and no parseable events (stream appears truncated)`;if(sseEvents>0){const truncated=halfLines>0||!/\r?\n\r?\n$/.test(text2)?` (stream appears truncated: ${halfLines>0?`${halfLines} incomplete data line(s)`:"no final frame terminator"})`:"";return`the upstream stream carried ${sseEvents} SSE event(s) but no summary text${truncated} (first event: ${firstPayload})`}const trimmed=text2.trim();if(!trimmed)return"the upstream returned an empty body";const detail=json&&typeof json==="object"?emptyCompletionDetail(json):null;if(detail!==null)return`the upstream returned a plain-JSON completion with empty content${detail}`;return`the upstream returned a non-SSE body with no summary text (first 200 bytes: ${trimmed.slice(0,200)})`}function emptyCompletionDetail(json){const parts=[];const choices=json.choices;if(Array.isArray(choices)&&choices.length>0){const first=choices[0];if(!first||typeof first!=="object")return null;const choice=first;const fr2=choice.finish_reason;if(typeof fr2==="string")parts.push(`finish_reason=${fr2}`);const message=choice.message;if(message&&typeof message==="object"){const msg=message;if(typeof msg.content==="string"){parts.push(`text_chars=${msg.content.length}`)}else if(Array.isArray(msg.content)){let textBlocks=0;for(const part of msg.content){if(part&&typeof part==="object"&&typeof part.text==="string")textBlocks+=1}parts.push(`text_blocks=${textBlocks}`)}if(typeof msg.reasoning_content==="string"&&msg.reasoning_content.length>0){parts.push(`reasoning_chars=${msg.reasoning_content.length}`)}}}else if(typeof json.stop_reason==="string"){parts.push(`stop_reason=${json.stop_reason}`);if(Array.isArray(json.content)){let textBlocks=0;let thinkingBlocks=0;let reasoningChars=0;for(const block of json.content){if(!block||typeof block!=="object")continue;const b2=block;if(b2.type==="text")textBlocks+=1;else if(b2.type==="thinking"||b2.type==="redacted_thinking"){thinkingBlocks+=1;if(typeof b2.thinking==="string")reasoningChars+=b2.thinking.length}}parts.push(`text_blocks=${textBlocks}`);if(thinkingBlocks>0)parts.push(`thinking_blocks=${thinkingBlocks}`);if(reasoningChars>0)parts.push(`reasoning_chars=${reasoningChars}`)}}else if(Array.isArray(json.output)){if(typeof json.status==="string")parts.push(`status=${json.status}`);let textParts=0;let reasoningChars=0;for(const item of json.output){if(!item||typeof item!=="object")continue;const it2=item;const itemType=typeof it2.type==="string"?it2.type:"";if(itemType==="reasoning"){for(const arr of[it2.content,it2.summary]){if(!Array.isArray(arr))continue;for(const p2 of arr){if(p2&&typeof p2==="object"&&typeof p2.text==="string"){reasoningChars+=p2.text.length}}}}else if(itemType===""||itemType==="message"){const content=it2.content;if(!Array.isArray(content))continue;for(const p2 of content){if(!p2||typeof p2!=="object")continue;const part=p2;const partType=typeof part.type==="string"?part.type:"";if((partType===""||partType==="output_text")&&typeof part.text==="string")textParts+=1}}}parts.push(`text_parts=${textParts}`);if(reasoningChars>0)parts.push(`reasoning_chars=${reasoningChars}`)}else{return null}if(typeof json.model==="string")parts.push(`answered as model=${json.model}`);return parts.length>0?` (${parts.join(", ")})`:""}async function summarizeRange(deps,content,startRef,endRef,lengthBudget,systemOverride){const system=systemOverride??buildCompressSystemPrompt(deps.prompts,messageTimestampSections(deps.surface?.promptSections))+`
|
|
1048
1048
|
|
|
1049
1049
|
TASK: The conversation segment below (messages ${startRef}\u2013${endRef}) must be compressed because the session context exceeds the current model's window. Write a tier-1 compression summary of the segment following every rule above. Output ONLY the summary text \u2014 no preamble, no closing remarks, no tool calls.`+summaryLengthBudgetClause(lengthBudget,MIN_SUMMARY_CHARS);if(deps.externalSummary){const batch=await deps.externalSummary.summarize([{instructions:system,content,minSummaryChars:MIN_SUMMARY_CHARS,maxSummaryChars:deps.config.compress.maxSummaryLength}],deps.signal);const result=batch.results[0];deps.log("info",`[external-summary] completed (preflight) 1/1 range(s); ${describeExternalSummaryFailure(batch)}`);return result?.status==="success"?{summary:result.summary,external:true}:{unusable:describeExternalSummaryFailure(batch),transient:false}}let stream2=!deps.streamSummaryOff&&(deps.session.metadata.preflightStreamSummary===true||deps.forceStreamSummary===true);let includeMaxOutputTokens=!(deps.protocol==="responses"&&hasLearnedNoMaxOutputTokens(deps));for(;;){try{return await requestSummary(deps,system,content,stream2,includeMaxOutputTokens)}catch(err2){if(err2 instanceof UpstreamHttpError&&!stream2&&!deps.streamSummaryOff&&(err2.status===524||err2.status===504)){deps.session.metadata.preflightStreamSummary=true;stream2=true;deps.log("info",`[preflight] non-streaming summary timed out at the gateway (HTTP ${err2.status}); retrying with SSE (learned for this session, #2155)`);continue}if(err2 instanceof UpstreamHttpError&&err2.status===400){let adapted=false;const paramRejected=deps.protocol==="responses"&&includeMaxOutputTokens&&MAX_OUTPUT_TOKENS_REJECTED_RE.test(err2.body);if(!stream2&&!deps.streamSummaryOff&&deps.protocol!=="google"&&!paramRejected){deps.session.metadata.preflightStreamSummary=true;stream2=true;adapted=true;deps.log("info",STREAM_REQUIRED_RE.test(err2.body)?"[preflight] upstream requires stream for summaries; retrying with SSE (learned for this session)":"[preflight] non-streaming summary rejected with HTTP 400; probing once with SSE \u2014 upstream likely requires streaming (learned for this session, #2494)")}if(paramRejected){rememberNoMaxOutputTokens(deps);includeMaxOutputTokens=false;adapted=true;deps.log("info",`[preflight] upstream rejects max_output_tokens for summaries (model=${deps.model}); retrying without it (learned for this session+upstream+model)`)}if(adapted)continue}throw err2}}}var TRANSIENT_SUMMARY_CODES=new Set(["ECONNRESET","ECONNREFUSED","EPIPE","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","UND_ERR_SOCKET","ENOTFOUND","UND_ERR_CONNECT_TIMEOUT","ECONNABORTED"]);var SUMMARY_DIAGNOSTIC_CODES=new Set([...TRANSIENT_SUMMARY_CODES,"ETIMEDOUT","UND_ERR_ABORTED","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","Z_DATA_ERROR","Z_BUF_ERROR","Z_MEM_ERROR",...TLS_TRUST_CODES]);var SummaryTransportError=class extends Error{retryable;aborted;code;constructor(stage,error,attempts){let code;let aborted=false;let cause=error;for(let depth=0;depth<6&&cause&&typeof cause==="object";depth++){const value=cause;if(value.name==="AbortError"||value.name==="TimeoutError")aborted=true;if(!code&&typeof value.code==="string"&&SUMMARY_DIAGNOSTIC_CODES.has(value.code))code=value.code;cause=value.cause}const name=error instanceof Error&&["Error","TypeError","AbortError","TimeoutError"].includes(error.name)?error.name:"Error";super(`summary ${stage} failed (${name}${code?`, code=${code}`:""}; ${attempts} attempt${attempts===1?"":"s"})`);this.name="SummaryTransportError";this.retryable=!aborted&&code!==void 0&&TRANSIENT_SUMMARY_CODES.has(code);this.aborted=aborted;this.code=code}};async function requestSummaryBody(deps,body,stream2){const maxAttempts=replayMaxAttempts2();for(let attempt=1;;attempt++){deps.signal?.throwIfAborted();let clearTimer;let stage="request";let retryDetail;try{const outHeaders={"content-type":"application/json",...summaryHeaders(deps)};deps.resign?.(outHeaders,body);const result=await fetchWithTimeout(deps.url,{method:"POST",headers:outHeaders,body,dispatcher:proxyDispatcher(deps.proxyUrl)},void 0,deps.signal);clearTimer=result.clearTimer;stage="response body";const text2=await result.response.text();deps.signal?.throwIfAborted();if(!result.response.ok)throw new UpstreamHttpError(result.response.status,text2,attempt);return text2}catch(err2){deps.signal?.throwIfAborted();const failure=err2 instanceof UpstreamHttpError?err2:new SummaryTransportError(stage,err2,attempt);if(failure instanceof UpstreamHttpError&&!stream2&&!deps.streamSummaryOff&&(failure.status===524||failure.status===504)){throw failure}const shapeRejection=failure instanceof UpstreamHttpError&&isCredentialShapeRejection(failure.status,failure.body);if(shapeRejection){deps.log("warn",`[preflight] summary rejected with HTTP 429 rate_limit_error "Error" \u2014 suspected credential-shape rejection rather than a rate limit (upstream requires a request attribute missing from this summary call, e.g. the client's billing-attribution system block; #2189); not retrying`)}const retryable=shapeRejection?false:failure instanceof UpstreamHttpError?isTransientUpstreamError(failure.status,failure.body):failure.retryable;if(!retryable||attempt>=maxAttempts){if(failure instanceof UpstreamHttpError&&failure.status>=400&&failure.status<500){dumpSummaryRejection(failure.status,deps.session.id,body,failure.body)}throw failure}retryDetail=failure instanceof UpstreamHttpError?`HTTP ${failure.status}`:failure.message}finally{clearTimer?.()}const delayMs=replayBackoffMs(attempt);deps.log("warn",`[preflight] summary attempt ${attempt} got ${retryDetail}; retrying in ${delayMs}ms${lastCompressSuffix(deps.session.lastCompress)}`);await sleep(delayMs,deps.signal)}}var SSE_DATA_LINE_RE=/(?:^|\n)data:/;async function requestSummary(deps,system,content,stream2,includeMaxOutputTokens){const text2=await requestSummaryBody(deps,JSON.stringify(summaryPayload(deps.protocol,deps.model,system,content,stream2,includeMaxOutputTokens,safeHost(deps.url),deps.config.modelContextLimit,deps.billingBlock,isCodexClient(deps.headers))),stream2);let json;try{json=JSON.parse(text2)}catch{json=null}const sseBody=SSE_DATA_LINE_RE.test(text2);const summary=(json&&typeof json==="object"?extractSummaryText(deps.protocol,json):stream2||sseBody?extractSummaryFromSse(deps.protocol,text2):"").trim();if(!json&&!stream2&&!sseBody){deps.log("warn",`[preflight] summary response was not JSON: ${text2.slice(0,200)}`)}if(summary.length<MIN_SUMMARY_CHARS){const diagnosis=diagnoseEmptySummary(text2,json);const deterministic=isDeterministicEmptyCompletion(deps.protocol,json);deps.log("warn",`[preflight] summary too short (${summary.length} chars): ${diagnosis}${deterministic?" [deterministic empty completion: normal stop with zero text \u2014 retrying the identical payload cannot succeed]":""}`);return deterministic?{unusable:diagnosis,transient:false,deterministic:true}:{unusable:diagnosis,transient:!emptySummaryIsSizeDriven(diagnosis)}}return{summary}}var ABORTED_FAILURE={kind:"aborted",detail:"the client disconnected during preflight compression"};function readDeterministicProbeState(metadata){const stored=metadata["deterministicEmptyProbe"];if(!stored||typeof stored!=="object")return void 0;const o=stored;if(typeof o["key"]!=="string"||typeof o["strikes"]!=="number"||typeof o["dead"]!=="boolean")return void 0;return{key:o["key"],strikes:o["strikes"],dead:o["dead"]}}function relaxedConfig(config){return{...config,preserveRecentMessages:0,preserveRecentTokens:0}}function noEmergencyTruncate(config){return{...config,modelContextLimit:config.modelContextLimit*100}}function recentZoneBoundaryRef(deps,messages,tokenCount){const probe=deps.core.processTurn({messages,state:deps.session.state,config:noEmergencyTruncate(ccrLoopConfig(deps.session,deps.config)),tokenCount,renderTags:"text-only",contentStore:contentStoreOf(deps.session)});let boundary=-1;for(const r of probe.nudge?.compressibleRanges??[]){boundary=Math.max(boundary,refNum9(r.endRef))}return boundary}function digestLabelCategory(label){const m2=/^(?:assistant tool-call|tool result) (\S+)/.exec(label);if(m2)return m2[1];return label}function deterministicDigest(entries2,startRef,endRef,opts){const{maxSummary,minSummaryLength,shrinkBound,countText}=opts;const totalChars=entries2.reduce((sum,entry)=>sum+entry.text.length,0);const header=`[deterministic digest ${startRef}:${endRef}] ${entries2.length} message(s), ~${totalChars} char(s) total. Emergency fast-path under extreme overflow (#2383): structural digest, no LLM summary; originals preserved - decompress this block to restore them verbatim.`;let structureLine="";if(entries2.length>0){const counts=new Map;for(const e of entries2){const cat=digestLabelCategory(e.label);counts.set(cat,(counts.get(cat)??0)+1)}const parts=[...counts.entries()].sort((a,b2)=>b2[1]-a[1]).map(([cat,n])=>`${n}\xD7${cat}`);structureLine=`Structure: ${parts.join(", ")}.`}const fits=form=>countText(form)<=shrinkBound&&(maxSummary===void 0||maxSummary<=0||form.length<=maxSummary);const line=(entry,headChars)=>{const head=headChars>0?` :: ${entry.text.replace(/\s+/g," ").trim().slice(0,headChars)}`:"";return`[${entry.ref} ${entry.label}] ${entry.text.length}ch${head}`};const preamble=entries2.length>0?`${header}
|
|
1050
1050
|
${structureLine}
|
|
@@ -1053,7 +1053,7 @@ ${blk.summary}`);while(i<=hi2){const mm=messages[i];if(mm&&cover.get(mm.id)===ci
|
|
|
1053
1053
|
|
|
1054
1054
|
${rules}
|
|
1055
1055
|
|
|
1056
|
-
TASK: The tier-${sourceTier} block summaries below must be distilled into ONE tier-${sourceTier+1} summary because the session context exceeds the model window and raw-message folding alone cannot close the gap. Follow every rule above. Output ONLY the distilled summary text \u2014 no preamble, no closing remarks, no tool calls.`;const content=spanContent(lo2,hi2);const targetKey=previewFoldTargetKey(deps.core,messages,deps.session.state,activeConfig,first.blockId,last.blockId);if(targetKey===void 0){stopReason="unavailable";break}let outcome;try{outcome=await summarizeRange(deps,content,first.blockId,last.blockId,void 0,system)}catch(error){const distillBodySnippet=error instanceof UpstreamHttpError?safePrefix(error.body.trim(),200):"";const distillDetail=error instanceof UpstreamHttpError?`HTTP ${error.status} after ${error.attempts} attempt(s)${distillBodySnippet?`: ${distillBodySnippet}`:""}`:safePrefix(error instanceof Error?error.message:String(error),200);deps.log("warn",`[preflight] tier-${sourceTier}->${sourceTier+1} distillation summary call failed (${distillDetail}); stopping recovery (#2952)`);stopReason="unavailable";break}if("unusable"in outcome){deps.log("warn",`[preflight] tier-${sourceTier}->${sourceTier+1} distillation produced no usable summary (${outcome.unusable}); stopping recovery (#2952)`);stopReason="unavailable";break}if(previewFoldTargetKey(deps.core,messages,deps.session.state,activeConfig,first.blockId,last.blockId)!==targetKey){deps.log("warn",`[preflight] discarded tier-distillation summary: fold targets changed while awaiting the summary`);stopReason="unavailable";break}const ctx={core:deps.core,config:activeConfig,messages,session:deps.session,lastNudge:measuredNudge,log:m2=>deps.log("info",m2)};const fold=parseCompressInput({content:[{startId:first.blockId,endId:last.blockId,summary:outcome.summary,topic:`preflight tier-${sourceTier+1} distill (#2952)`}]});const applied=applyRanges(fold,ctx,{loopTracking:false});if(applied.outcome==="refused"){deps.log("warn",`[preflight] tier distillation apply refused: ${safePrefix(applied.text,200)}; stopping recovery (#2952)`);stopReason="unavailable";break}deps.session.stats.lastInputTokens+=defaultCountTokens(outcome.summary);const after=measureEst();const gained=est-after;callsUsed+=1;summaryCalls+=1;result.compressedRanges+=1;result.savedTokens+=Math.max(0,gained);if(gained<=0){deps.log("warn",`[preflight] tier-${sourceTier}->${sourceTier+1} distillation netted ${gained} tokens (no shrink); stopping recovery (#2952)`);stopReason="no-shrink";break}netSaved+=gained;est=after;if(est<limit){stopReason="fit";break}deps.log("info",`[preflight] tier-${sourceTier}->${sourceTier+1} distillation merged b-range ${first.blockId}..${last.blockId} into one block; net -${gained} tok, payload ~${after} vs window ${limit} (${callsUsed}/${MAX_TIER_DISTILL_CALLS} calls, #2952)`)}if(stopReason==="fit"&&est>=limit)stopReason="cap";const recovered=est<limit;if(recovered)currentTokens=Math.min(currentTokens,est);const overBy=Math.max(0,est-limit);const why=stopReason==="exhausted"?exhaustedWhy??"every compression tier is exhausted":stopReason==="cap"?`the bounded distillation call budget was reached after ${callsUsed} call(s)`:stopReason==="unavailable"?"the distillation summary was unavailable":"a distillation pass produced no further shrink";const honestDetail=`futile round: folding compressible raw messages plus tier distillation (${callsUsed} summary call(s), net ~${netSaved} tokens saved) still leaves the payload ~${overBy} tokens over the window \u2014 ${why}. These figures are measured on the post-fold wire view; the separately displayed context total additionally floors on the upstream usage baseline, which also bills the system prompt and tool definitions. Raise the model context window or restart the session.`;return{recovered,callsUsed,netSaved,honestDetail}};for(let round=0;round<effectiveRoundCap;round++){if(deps.signal?.aborted){failure=ABORTED_FAILURE;break}if(poolQueueDrop)break;await yieldToEventLoop();const turn=deps.core.processTurn({messages,state:deps.session.state,config:noEmergencyTruncate(ccrLoopConfig(deps.session,activeConfig)),tokenCount:currentTokens,renderTags:"text-only",contentStore:contentStoreOf(deps.session)});deps.session.state=turn.state;adoptContentStore(deps.session,turn.contentStore);turn.messages=applyAbsorbView(turn.messages,turn.state,activeConfig,currentTokens);const baselineFloor=messages.length>0?deps.session.stats.lastInputTokensSource==="usage"||deps.session.stats.lastInputTokensSource==="overflow-arm"?deps.session.stats.lastInputTokens:0:deps.session.stats.lastInputTokens;const rawRoundText=estimateCoreMessages(turn.messages)+wireOverhead;const roundText=applyEstimateCalibration(rawRoundText,kFactor,kOrigin,deps.upstreamOrigin);currentTokens=Math.max(baselineFloor,roundText+imageReserve);decisionTokens=Math.max(Math.max(0,baselineFloor-imageReserve),roundText);if(!baselineKnown){finalUpper=estimateCoreMessagesUpper(turn.messages)+imageReserve+wireOverhead;currentTokens=Math.max(currentTokens,finalUpper)}result.payloadEstimate=roundText+imageReserve;if(startTokens<0)startTokens=currentTokens;const armedBaseline=deps.session.stats.lastInputTokensSource==="overflow-arm";if(armedBaseline?decisionTokens<textTarget:roundText<textTarget){fitExitForward=true;if(baselineFloor>=textTarget&&!armedBaseline){deps.log("info",`[preflight] payload fits by its own estimate (~${Math.round(result.payloadEstimate)}/${textTarget} target, window ${limit}); stopping instead of folding further despite a higher usage baseline (~${Math.round(baselineFloor)} tok measured under a prior model/route) \u2014 forwarding (#4288)`)}break}const viable=viableRanges(turn.nudge?.compressibleRanges??[]);const aboveMin=viable.filter(r=>minChars<=0||(r.chars??r.tokens*4)>=minChars);let ranges=filterDeadRanges(deps.session,aboveMin);const deadDropped=aboveMin.length-ranges.length;if(deadDropped>0){deadDroppedTotal+=deadDropped;if(!deadNoted){deadNoted=true;deps.log("debug",`[preflight] ${deadDropped} candidate range(s) suppressed: previously-dead structural verdicts (#2638)`)}}if(ranges.length===0&&aboveMin.length===0&&viable.length>0&&!subMinNoted){subMinNoted=true;deps.log("warn",`[preflight] ${viable.length} viable range(s) are below minCompressRange (${minChars} chars); none foldable`);noteSkip(`all ${viable.length} viable range(s) below minCompressRange (${minChars} chars)`)}rangesRemaining=ranges.length;if(ranges.length>0)result.hadFoldableCandidates=true;if(!emergencyFold||(round&31)===0){deps.log("info",`[preflight] round ${round+1}/${effectiveRoundCap}: payload ~${Math.round(result.payloadEstimate)} tok vs window ${limit} (deficit ${Math.max(0,Math.round(result.payloadEstimate-limit))}), ${ranges.length} viable range(s)`)}if(baselineKnown&&ranges.length>0){const{refToIdx:gateRefs}=refMaps(messages,deps.session.state);const resolvableMass=rs2=>rs2.reduce((sum,r)=>{const si2=gateRefs.get(r.startRef);const ei2=gateRefs.get(r.endRef);return si2!==void 0&&ei2!==void 0&&si2<=ei2?sum+r.tokens:sum},0);let potential=resolvableMass(ranges);const deficit=result.payloadEstimate-limit;if(potential>0&&deficit>0&&calibrateFoldMass(potential)*FUTILITY_SLACK<deficit){if(!relaxed){const probe=deps.core.processTurn({messages,state:deps.session.state,config:noEmergencyTruncate(ccrLoopConfig(deps.session,relaxedConfig(deps.config))),tokenCount:currentTokens,renderTags:"text-only",contentStore:contentStoreOf(deps.session)});const relaxedRanges=filterDeadRanges(deps.session,viableRanges(probe.nudge?.compressibleRanges??[]).filter(r=>minChars<=0||(r.chars??r.tokens*4)>=minChars));const relaxedPotential=resolvableMass(relaxedRanges);if(calibrateFoldMass(relaxedPotential)*FUTILITY_SLACK>=deficit){activeConfig=relaxedConfig(deps.config);relaxed=true;textTarget=Math.max(0,limit-imageReserve);summaryCalls=0;budgetHit=false;transientRetryBudget=TRANSIENT_EMPTY_RETRY_BUDGET;deps.log("warn",`[preflight] foldable mass outside the protected recent zone (~${calibrateFoldMass(potential)} tok) cannot close the ${deficit}-tok gap; relaxing soft protection up front and retrying (#1841)`);continue}potential=relaxedPotential}const zoneNote=relaxed?", including the relaxed recent zone":"";if(eligibleForTierRecovery()){deps.log("info",`[preflight] raw-fold pool (~${calibrateFoldMass(potential)} tok${zoneNote}) below deficit (~${deficit} tok); deferring to bounded tier-distillation recovery (#2952)`);break}failure={kind:"exhausted",deterministic:lastUnusableDetail===void 0&&!poolQueueDrop,detail:`futile round: the maximum possible saving from all foldable content (~${calibrateFoldMass(potential)} tokens${zoneNote}) is below the required reduction (~${deficit} tokens) \u2014 no combination of folds can bring the payload under the target. Raise the model context window or restart the session.`};deps.log("warn",`[preflight] skipping futile round: max possible saving ~${calibrateFoldMass(potential)} tok < required ~${deficit} tok${zoneNote}; zero summarization calls spent (#1841)`);break}}if(ranges.length===0){if(!relaxed&&result.payloadEstimate>=limit){activeConfig=relaxedConfig(deps.config);relaxed=true;textTarget=Math.max(0,limit-imageReserve);summaryCalls=0;budgetHit=false;transientRetryBudget=TRANSIENT_EMPTY_RETRY_BUDGET;deps.log("warn","[preflight] no compressible ranges outside the protected recent zone; relaxing soft protection (preserveRecentMessages/Tokens -> 0) and retrying");continue}if(eligibleForTierRecovery()){deps.log("info",`[preflight] no compressible ranges remain${relaxed?" even with the soft zone relaxed":""}; deferring to bounded tier-distillation recovery (#2952)`);break}failure={kind:"exhausted",deterministic:true,detail:relaxed?relaxedExhaustedDetail:subMinNoted?`no foldable compressible ranges remain: all ${viable.length} viable range(s) are below minCompressRange (${minChars} chars)`:deadNoted?`no foldable compressible ranges remain: ${deadDroppedTotal} range(s) carry previously-dead structural verdicts (#2638)`:"no compressible ranges remain in the conversation"};break}const zoneBoundary=relaxed?recentZoneBoundaryRef(deps,messages,currentTokens):null;const tierOf=r=>zoneBoundary!==null&&refNum9(r.endRef)>zoneBoundary?2:1;const ordered=[...ranges].sort((a,b2)=>tierOf(a)-tierOf(b2)||(tierOf(a)===1?b2.tokens-a.tokens:0)||refNum9(a.startRef)-refNum9(b2.startRef));if(!foldOrderLogged&&ordered.length>0){foldOrderLogged=true;const shown=ordered.slice(0,8).map(r=>`${r.startRef}:${r.endRef} (${r.tokens} tok${tierOf(r)===2?", zone":""})`).join(", ");deps.log("info",`[preflight] fold order (largest first outside the recent zone, #2682): ${shown}${ordered.length>8?`, ... (+${ordered.length-8} more)`:""}`)}let appliedThisRound=0;let futileBail=false;let bailRemaining=0;let bailDeficit=0;const commitFold=(skipKey,startRef,endRef,summary,effectiveMessageIds,externalFold,targetKey)=>{const state7=deps.session.state;const preview=deps.core.applyCompression({messages,state:state7,config:activeConfig,ranges:[{startRef,endRef,summary}]});const known=new Set(state7.blocks.map(block=>block.blockId));const target=preview.state.blocks.find(block=>!known.has(block.blockId));if(!target||foldTargetKey(target,state7)!==targetKey){deps.log("warn",`[preflight] discarded summary for ${skipKey}: fold targets changed while awaiting the summary`);noteSkip(`${skipKey}: fold targets changed while awaiting the summary`);skipSet.add(skipKey);return false}const ctx={core:deps.core,config:activeConfig,messages,session:deps.session,lastNudge:turn.nudge,log:msg=>deps.log("info",msg)};const creditBefore=deps.session.stats.compressCreditTokens;const fold=parseCompressInput({content:[{startId:startRef,endId:endRef,summary,topic:deps.compressReason==="growth"?"preflight auto-fold (growth)":"preflight overflow compress"}]});if(externalFold)for(const range of fold.ranges)range.compressCallId=newExternalCallId();const applied=applyRanges(fold,ctx,{loopTracking:false});if(applied.outcome==="refused"){deps.log("warn",`[preflight] ${applied.text}`);noteSkip(`${skipKey}: apply failed \u2014 ${safePrefix(applied.text.replace(/^\[Compression (?:FAILED|refused)[:\s]*/,""),200)}`);skipSet.add(skipKey);return false}failure=void 0;const compressed=deps.session.stats.compressCreditTokens-creditBefore;const folded=baselineKnown?compressed:messages.filter(message=>effectiveMessageIds.includes(message.id)).reduce((total,message)=>total+(message.text??"").length,0);currentTokens=Math.max(0,currentTokens-folded+countText(summary));deps.session.stats.lastInputTokens+=defaultCountTokens(summary);appliedThisRound+=1;result.compressedRanges+=1;return true};if(!emergencyFold&&ordered.length>=2&&!budgetHit){const batchPlan=deps.externalSummary;if(batchPlan){const nominations=[];let workTotal=0;let reservedCalls=0;for(let oi2=0;oi2<ordered.length&&nominations.length<MAX_PREFLIGHT_SUMMARY_BATCH;oi2++){const range=ordered[oi2];const skipKey=`${range.startRef}:${range.endRef}`;if(skipSet.has(skipKey))continue;const{refToIdx}=refMaps(messages,deps.session.state);const startIdx=refToIdx.get(range.startRef);const endIdx=refToIdx.get(range.endRef);if(startIdx===void 0||endIdx===void 0||startIdx>endIdx){skipSet.add(skipKey);const why=startIdx===void 0?`start ref ${range.startRef} is absent from the current messages`:endIdx===void 0?`end ref ${range.endRef} is absent from the current messages`:`position resolution inverted the range (${startIdx} > ${endIdx})`;deps.log("warn",`[preflight] skipping range ${skipKey}: ${why}`);noteSkip(`${skipKey}: ${why}`);continue}if(!triedKeys.has(skipKey)){triedKeys.add(skipKey);rangesTried+=1}const spans=mergeSubMinimumFragments(messages,splitChunks(messages,startIdx,endIdx,budget,baselineKnown?0:minChars,countText),minChars,coveredIdx).slice().reverse();const span=spans.pop();if(!span)continue;const[cs2,ce2]=span;const maps=refMaps(messages,deps.session.state);let startRef=maps.idxToRef.get(cs2);let endRef=maps.idxToRef.get(ce2);if(!startRef||!endRef){deps.log("warn",`[preflight] dropping span ${cs2}..${ce2} of range ${skipKey}: boundary message has no ref in the current state`);noteSkip(`${skipKey}: span ${cs2}..${ce2} boundary message has no ref`);continue}if(refNum9(startRef)>refNum9(endRef)){deps.log("warn",`[preflight] normalized reversed range ${startRef}\u2013${endRef} \u2192 ${endRef}\u2013${startRef} (non-monotonic refs after client history rewrite, #1001)`);[startRef,endRef]=[endRef,startRef]}const preview=deps.core.applyCompression({messages,state:deps.session.state,config:activeConfig,ranges:[{startRef,endRef,summary:"x".repeat(Math.max(MIN_SUMMARY_CHARS,activeConfig.compress.minSummaryLength))}]});const previousBlockIds=new Set(deps.session.state.blocks.map(block=>block.blockId));const planned=preview.state.blocks.find(block=>!previousBlockIds.has(block.blockId));if(!planned){const verdict=safePrefix([...preview.result.errors,...preview.result.warnings].join("; "),300)||"the kernel created no block and reported no error";deps.log("warn",`[preflight] preview rejected range ${skipKey}: ${verdict}`);noteSkip(`${skipKey}: preview rejected \u2014 ${verdict}`);continue}const idxById=new Map(messages.map((m2,i)=>[m2.id,i]));const byRaw=deps.session.state?.messageRefs?.byRaw;const parts=[];const droppedParts=[];for(const id of planned.directMessageIds){const i=idxById.get(id);if(i===void 0){droppedParts.push(`message ${id} not found in current messages`);continue}const m2=messages[i];let text2=m2.text??"";const notes=imagePlaceholdersForSummary(m2,byRaw?.[m2.id]);if(notes.length>0){const note=notes.join(" ");text2=text2===IMAGE_PLACEHOLDER?note:text2?`${text2}
|
|
1056
|
+
TASK: The tier-${sourceTier} block summaries below must be distilled into ONE tier-${sourceTier+1} summary because the session context exceeds the model window and raw-message folding alone cannot close the gap. Follow every rule above. Output ONLY the distilled summary text \u2014 no preamble, no closing remarks, no tool calls.`;const content=spanContent(lo2,hi2);const targetKey=previewFoldTargetKey(deps.core,messages,deps.session.state,activeConfig,first.blockId,last.blockId);if(targetKey===void 0){stopReason="unavailable";break}let outcome;try{outcome=await summarizeRange(deps,content,first.blockId,last.blockId,void 0,system)}catch(error){const distillBodySnippet=error instanceof UpstreamHttpError?safePrefix(error.body.trim(),200):"";const distillDetail=error instanceof UpstreamHttpError?`HTTP ${error.status} after ${error.attempts} attempt(s)${distillBodySnippet?`: ${distillBodySnippet}`:""}`:safePrefix(error instanceof Error?error.message:String(error),200);deps.log("warn",`[preflight] tier-${sourceTier}->${sourceTier+1} distillation summary call failed (${distillDetail}); stopping recovery (#2952)`);stopReason="unavailable";break}if("unusable"in outcome){deps.log("warn",`[preflight] tier-${sourceTier}->${sourceTier+1} distillation produced no usable summary (${outcome.unusable}); stopping recovery (#2952)`);stopReason="unavailable";break}if(previewFoldTargetKey(deps.core,messages,deps.session.state,activeConfig,first.blockId,last.blockId)!==targetKey){deps.log("warn",`[preflight] discarded tier-distillation summary: fold targets changed while awaiting the summary`);stopReason="unavailable";break}const ctx={core:deps.core,config:activeConfig,messages,session:deps.session,lastNudge:measuredNudge,log:m2=>deps.log("info",m2)};const fold=parseCompressInput({content:[{startId:first.blockId,endId:last.blockId,summary:outcome.summary,topic:`preflight tier-${sourceTier+1} distill (#2952)`}]});const applied=applyRanges(fold,ctx,{loopTracking:false});if(applied.outcome==="refused"){deps.log("warn",`[preflight] tier distillation apply refused: ${safePrefix(applied.text,200)}; stopping recovery (#2952)`);stopReason="unavailable";break}deps.session.stats.lastInputTokens+=defaultCountTokens(outcome.summary);const after=measureEst();const gained=est-after;callsUsed+=1;summaryCalls+=1;result.compressedRanges+=1;result.savedTokens+=Math.max(0,gained);if(gained<=0){deps.log("warn",`[preflight] tier-${sourceTier}->${sourceTier+1} distillation netted ${gained} tokens (no shrink); stopping recovery (#2952)`);stopReason="no-shrink";break}netSaved+=gained;est=after;if(est<limit){stopReason="fit";break}deps.log("info",`[preflight] tier-${sourceTier}->${sourceTier+1} distillation merged b-range ${first.blockId}..${last.blockId} into one block; net -${gained} tok, payload ~${after} vs window ${limit} (${callsUsed}/${MAX_TIER_DISTILL_CALLS} calls, #2952)`)}if(stopReason==="fit"&&est>=limit)stopReason="cap";const recovered=est<limit;if(recovered)currentTokens=Math.min(currentTokens,est);const overBy=Math.max(0,est-limit);const why=stopReason==="exhausted"?exhaustedWhy??"every compression tier is exhausted":stopReason==="cap"?`the bounded distillation call budget was reached after ${callsUsed} call(s)`:stopReason==="unavailable"?"the distillation summary was unavailable":"a distillation pass produced no further shrink";const honestDetail=`futile round: folding compressible raw messages plus tier distillation (${callsUsed} summary call(s), net ~${netSaved} tokens saved) still leaves the payload ~${overBy} tokens over the window \u2014 ${why}. These figures are measured on the post-fold wire view; the separately displayed context total additionally floors on the upstream usage baseline, which also bills the system prompt and tool definitions. Raise the model context window or restart the session.`;return{recovered,callsUsed,netSaved,honestDetail}};for(let round=0;round<effectiveRoundCap;round++){if(deps.signal?.aborted){failure=ABORTED_FAILURE;break}if(poolQueueDrop)break;await yieldToEventLoop();const turn=deps.core.processTurn({messages,state:deps.session.state,config:noEmergencyTruncate(ccrLoopConfig(deps.session,activeConfig)),tokenCount:currentTokens,renderTags:"text-only",contentStore:contentStoreOf(deps.session)});deps.session.state=turn.state;adoptContentStore(deps.session,turn.contentStore);turn.messages=applyAbsorbView(turn.messages,turn.state,activeConfig,currentTokens);const baselineFloor=messages.length>0?deps.session.stats.lastInputTokensSource==="usage"||deps.session.stats.lastInputTokensSource==="overflow-arm"?deps.session.stats.lastInputTokens:0:deps.session.stats.lastInputTokens;const rawRoundText=estimateCoreMessages(turn.messages)+wireOverhead;const roundText=applyEstimateCalibration(rawRoundText,kFactor,kOrigin,deps.upstreamOrigin);currentTokens=Math.max(baselineFloor,roundText+imageReserve);decisionTokens=Math.max(Math.max(0,baselineFloor-imageReserve),roundText);if(!baselineKnown){finalUpper=estimateCoreMessagesUpper(turn.messages)+imageReserve+wireOverhead;currentTokens=Math.max(currentTokens,finalUpper)}result.payloadEstimate=roundText+imageReserve;if(startTokens<0)startTokens=currentTokens;const armedBaseline=deps.session.stats.lastInputTokensSource==="overflow-arm";if(armedBaseline?decisionTokens<textTarget:roundText<textTarget){fitExitForward=true;if(baselineFloor>=textTarget&&!armedBaseline){deps.log("info",`[preflight] payload fits by its own estimate (~${Math.round(result.payloadEstimate)}/${textTarget} target, window ${limit}); stopping instead of folding further despite a higher usage baseline (~${Math.round(baselineFloor)} tok measured under a prior model/route) \u2014 forwarding (#4288)`)}if(!armedBaseline&&baselineFloor<textTarget&&result.payloadEstimate>=FIT_FORWARD_ESTIMATE_ONLY_MARGIN*limit){deps.log("warn",`[preflight] fit-forward on estimate only: ~${Math.round(result.payloadEstimate)} tok vs window ${limit} with no usage measurement backing the fit (baseline ~${Math.round(baselineFloor)}) \u2014 the local estimate excludes the system prompt + tool definitions, so upstream may still reject with context overflow; if it does, the overflow-arm rescue folds next turn (#5408/#4288)`)}break}const viable=viableRanges(turn.nudge?.compressibleRanges??[]);const aboveMin=viable.filter(r=>minChars<=0||(r.chars??r.tokens*4)>=minChars);let ranges=filterDeadRanges(deps.session,aboveMin);const deadDropped=aboveMin.length-ranges.length;if(deadDropped>0){deadDroppedTotal+=deadDropped;if(!deadNoted){deadNoted=true;deps.log("debug",`[preflight] ${deadDropped} candidate range(s) suppressed: previously-dead structural verdicts (#2638)`)}}if(ranges.length===0&&aboveMin.length===0&&viable.length>0&&!subMinNoted){subMinNoted=true;deps.log("warn",`[preflight] ${viable.length} viable range(s) are below minCompressRange (${minChars} chars); none foldable`);noteSkip(`all ${viable.length} viable range(s) below minCompressRange (${minChars} chars)`)}rangesRemaining=ranges.length;if(ranges.length>0)result.hadFoldableCandidates=true;if(!emergencyFold||(round&31)===0){deps.log("info",`[preflight] round ${round+1}/${effectiveRoundCap}: payload ~${Math.round(result.payloadEstimate)} tok vs window ${limit} (deficit ${Math.max(0,Math.round(result.payloadEstimate-limit))}), ${ranges.length} viable range(s)`)}if(baselineKnown&&ranges.length>0){const{refToIdx:gateRefs}=refMaps(messages,deps.session.state);const resolvableMass=rs2=>rs2.reduce((sum,r)=>{const si2=gateRefs.get(r.startRef);const ei2=gateRefs.get(r.endRef);return si2!==void 0&&ei2!==void 0&&si2<=ei2?sum+r.tokens:sum},0);let potential=resolvableMass(ranges);const deficit=result.payloadEstimate-limit;if(potential>0&&deficit>0&&calibrateFoldMass(potential)*FUTILITY_SLACK<deficit){if(!relaxed){const probe=deps.core.processTurn({messages,state:deps.session.state,config:noEmergencyTruncate(ccrLoopConfig(deps.session,relaxedConfig(deps.config))),tokenCount:currentTokens,renderTags:"text-only",contentStore:contentStoreOf(deps.session)});const relaxedRanges=filterDeadRanges(deps.session,viableRanges(probe.nudge?.compressibleRanges??[]).filter(r=>minChars<=0||(r.chars??r.tokens*4)>=minChars));const relaxedPotential=resolvableMass(relaxedRanges);if(calibrateFoldMass(relaxedPotential)*FUTILITY_SLACK>=deficit){activeConfig=relaxedConfig(deps.config);relaxed=true;textTarget=Math.max(0,limit-imageReserve);summaryCalls=0;budgetHit=false;transientRetryBudget=TRANSIENT_EMPTY_RETRY_BUDGET;deps.log("warn",`[preflight] foldable mass outside the protected recent zone (~${calibrateFoldMass(potential)} tok) cannot close the ${deficit}-tok gap; relaxing soft protection up front and retrying (#1841)`);continue}potential=relaxedPotential}const zoneNote=relaxed?", including the relaxed recent zone":"";if(eligibleForTierRecovery()){deps.log("info",`[preflight] raw-fold pool (~${calibrateFoldMass(potential)} tok${zoneNote}) below deficit (~${deficit} tok); deferring to bounded tier-distillation recovery (#2952)`);break}failure={kind:"exhausted",deterministic:lastUnusableDetail===void 0&&!poolQueueDrop,detail:`futile round: the maximum possible saving from all foldable content (~${calibrateFoldMass(potential)} tokens${zoneNote}) is below the required reduction (~${deficit} tokens) \u2014 no combination of folds can bring the payload under the target. Raise the model context window or restart the session.`};deps.log("warn",`[preflight] skipping futile round: max possible saving ~${calibrateFoldMass(potential)} tok < required ~${deficit} tok${zoneNote}; zero summarization calls spent (#1841)`);break}}if(ranges.length===0){if(!relaxed&&result.payloadEstimate>=limit){activeConfig=relaxedConfig(deps.config);relaxed=true;textTarget=Math.max(0,limit-imageReserve);summaryCalls=0;budgetHit=false;transientRetryBudget=TRANSIENT_EMPTY_RETRY_BUDGET;deps.log("warn","[preflight] no compressible ranges outside the protected recent zone; relaxing soft protection (preserveRecentMessages/Tokens -> 0) and retrying");continue}if(eligibleForTierRecovery()){deps.log("info",`[preflight] no compressible ranges remain${relaxed?" even with the soft zone relaxed":""}; deferring to bounded tier-distillation recovery (#2952)`);break}failure={kind:"exhausted",deterministic:true,detail:relaxed?relaxedExhaustedDetail:subMinNoted?`no foldable compressible ranges remain: all ${viable.length} viable range(s) are below minCompressRange (${minChars} chars)`:deadNoted?`no foldable compressible ranges remain: ${deadDroppedTotal} range(s) carry previously-dead structural verdicts (#2638)`:"no compressible ranges remain in the conversation"};break}const zoneBoundary=relaxed?recentZoneBoundaryRef(deps,messages,currentTokens):null;const tierOf=r=>zoneBoundary!==null&&refNum9(r.endRef)>zoneBoundary?2:1;const ordered=[...ranges].sort((a,b2)=>tierOf(a)-tierOf(b2)||(tierOf(a)===1?b2.tokens-a.tokens:0)||refNum9(a.startRef)-refNum9(b2.startRef));if(!foldOrderLogged&&ordered.length>0){foldOrderLogged=true;const shown=ordered.slice(0,8).map(r=>`${r.startRef}:${r.endRef} (${r.tokens} tok${tierOf(r)===2?", zone":""})`).join(", ");deps.log("info",`[preflight] fold order (largest first outside the recent zone, #2682): ${shown}${ordered.length>8?`, ... (+${ordered.length-8} more)`:""}`)}let appliedThisRound=0;let futileBail=false;let bailRemaining=0;let bailDeficit=0;const commitFold=(skipKey,startRef,endRef,summary,effectiveMessageIds,externalFold,targetKey)=>{const state7=deps.session.state;const preview=deps.core.applyCompression({messages,state:state7,config:activeConfig,ranges:[{startRef,endRef,summary}]});const known=new Set(state7.blocks.map(block=>block.blockId));const target=preview.state.blocks.find(block=>!known.has(block.blockId));if(!target||foldTargetKey(target,state7)!==targetKey){deps.log("warn",`[preflight] discarded summary for ${skipKey}: fold targets changed while awaiting the summary`);noteSkip(`${skipKey}: fold targets changed while awaiting the summary`);skipSet.add(skipKey);return false}const ctx={core:deps.core,config:activeConfig,messages,session:deps.session,lastNudge:turn.nudge,log:msg=>deps.log("info",msg)};const creditBefore=deps.session.stats.compressCreditTokens;const fold=parseCompressInput({content:[{startId:startRef,endId:endRef,summary,topic:deps.compressReason==="growth"?"preflight auto-fold (growth)":"preflight overflow compress"}]});if(externalFold)for(const range of fold.ranges)range.compressCallId=newExternalCallId();const applied=applyRanges(fold,ctx,{loopTracking:false});if(applied.outcome==="refused"){deps.log("warn",`[preflight] ${applied.text}`);noteSkip(`${skipKey}: apply failed \u2014 ${safePrefix(applied.text.replace(/^\[Compression (?:FAILED|refused)[:\s]*/,""),200)}`);skipSet.add(skipKey);return false}failure=void 0;const compressed=deps.session.stats.compressCreditTokens-creditBefore;const folded=baselineKnown?compressed:messages.filter(message=>effectiveMessageIds.includes(message.id)).reduce((total,message)=>total+(message.text??"").length,0);currentTokens=Math.max(0,currentTokens-folded+countText(summary));deps.session.stats.lastInputTokens+=defaultCountTokens(summary);appliedThisRound+=1;result.compressedRanges+=1;return true};if(!emergencyFold&&ordered.length>=2&&!budgetHit){const batchPlan=deps.externalSummary;if(batchPlan){const nominations=[];let workTotal=0;let reservedCalls=0;for(let oi2=0;oi2<ordered.length&&nominations.length<MAX_PREFLIGHT_SUMMARY_BATCH;oi2++){const range=ordered[oi2];const skipKey=`${range.startRef}:${range.endRef}`;if(skipSet.has(skipKey))continue;const{refToIdx}=refMaps(messages,deps.session.state);const startIdx=refToIdx.get(range.startRef);const endIdx=refToIdx.get(range.endRef);if(startIdx===void 0||endIdx===void 0||startIdx>endIdx){skipSet.add(skipKey);const why=startIdx===void 0?`start ref ${range.startRef} is absent from the current messages`:endIdx===void 0?`end ref ${range.endRef} is absent from the current messages`:`position resolution inverted the range (${startIdx} > ${endIdx})`;deps.log("warn",`[preflight] skipping range ${skipKey}: ${why}`);noteSkip(`${skipKey}: ${why}`);continue}if(!triedKeys.has(skipKey)){triedKeys.add(skipKey);rangesTried+=1}const spans=mergeSubMinimumFragments(messages,splitChunks(messages,startIdx,endIdx,budget,baselineKnown?0:minChars,countText),minChars,coveredIdx).slice().reverse();const span=spans.pop();if(!span)continue;const[cs2,ce2]=span;const maps=refMaps(messages,deps.session.state);let startRef=maps.idxToRef.get(cs2);let endRef=maps.idxToRef.get(ce2);if(!startRef||!endRef){deps.log("warn",`[preflight] dropping span ${cs2}..${ce2} of range ${skipKey}: boundary message has no ref in the current state`);noteSkip(`${skipKey}: span ${cs2}..${ce2} boundary message has no ref`);continue}if(refNum9(startRef)>refNum9(endRef)){deps.log("warn",`[preflight] normalized reversed range ${startRef}\u2013${endRef} \u2192 ${endRef}\u2013${startRef} (non-monotonic refs after client history rewrite, #1001)`);[startRef,endRef]=[endRef,startRef]}const preview=deps.core.applyCompression({messages,state:deps.session.state,config:activeConfig,ranges:[{startRef,endRef,summary:"x".repeat(Math.max(MIN_SUMMARY_CHARS,activeConfig.compress.minSummaryLength))}]});const previousBlockIds=new Set(deps.session.state.blocks.map(block=>block.blockId));const planned=preview.state.blocks.find(block=>!previousBlockIds.has(block.blockId));if(!planned){const verdict=safePrefix([...preview.result.errors,...preview.result.warnings].join("; "),300)||"the kernel created no block and reported no error";deps.log("warn",`[preflight] preview rejected range ${skipKey}: ${verdict}`);noteSkip(`${skipKey}: preview rejected \u2014 ${verdict}`);continue}const idxById=new Map(messages.map((m2,i)=>[m2.id,i]));const byRaw=deps.session.state?.messageRefs?.byRaw;const parts=[];const droppedParts=[];for(const id of planned.directMessageIds){const i=idxById.get(id);if(i===void 0){droppedParts.push(`message ${id} not found in current messages`);continue}const m2=messages[i];let text2=m2.text??"";const notes=imagePlaceholdersForSummary(m2,byRaw?.[m2.id]);if(notes.length>0){const note=notes.join(" ");text2=text2===IMAGE_PLACEHOLDER?note:text2?`${text2}
|
|
1057
1057
|
${note}`:note}if(!text2){droppedParts.push(`message ${id} rendered no text`);continue}const label=m2.contentType==="tool-call"?`assistant tool-call ${m2.toolName??"?"}`:m2.contentType==="tool-result"?`tool result ${m2.toolName??"?"}`:m2.contentType==="reasoning"?"assistant reasoning":m2.role;parts.push(`[${label}]
|
|
1058
1058
|
${text2}`)}for(const nid of planned.directBlockIds){const nb=deps.session.state.blocks.find(b2=>b2.blockId===nid);if(!nb){droppedParts.push(`child block ${nid} missing from state`);continue}const label=nb.topic?`${nb.blockId}: ${nb.topic}`:nb.blockId;parts.push(`[summarized ${label}]
|
|
1059
1059
|
${nb.summary}`)}if(droppedParts.length>0){deps.log("debug",`[preflight] range ${skipKey}: ${droppedParts.length} part(s) rendered nothing (${droppedParts.slice(0,3).join("; ")})`)}const content=parts.join("\n\n");if(content.length===0){deps.log("warn",`[preflight] planned block for range ${skipKey} rendered no text: ${droppedParts.slice(0,5).join("; ")||"all parts empty"}`);noteSkip(`${skipKey}: planned block rendered no text (${droppedParts.slice(0,3).join("; ")||"all parts empty"})`);continue}const spanUnits=baselineKnown?planned.compressedTokens:messages.filter(message=>planned.effectiveMessageIds.includes(message.id)).reduce((total,message)=>total+(message.text??"").length,0);const chunks=splitSummaryContent(content,budget,countText);if(summaryCalls+reservedCalls+chunks.length>summaryBudget)break;reservedCalls+=chunks.length;const maxSummary=activeConfig.compress.maxSummaryLength;const perChunkBudget=maxSummary>0?Math.floor((maxSummary-(chunks.length-1)*SUMMARY_JOIN_GAP)/chunks.length):void 0;const instructions=buildCompressSystemPrompt(deps.prompts,messageTimestampSections(deps.surface?.promptSections))+`
|
|
@@ -1063,7 +1063,7 @@ ${note}`:note}if(!text2){droppedParts.push(`message ${id} rendered no text`);con
|
|
|
1063
1063
|
${text2}`);if(emergencyFold)entries2.push({ref:maps.idxToRef.get(i)??"?",label,text:text2})}for(const nid of planned.directBlockIds){const nb=deps.session.state.blocks.find(b2=>b2.blockId===nid);if(!nb){droppedParts.push(`child block ${nid} missing from state`);continue}const label=nb.topic?`${nb.blockId}: ${nb.topic}`:nb.blockId;parts.push(`[summarized ${label}]
|
|
1064
1064
|
${nb.summary}`);if(emergencyFold)entries2.push({ref:nb.blockId,label:`summarized ${label}`,text:nb.summary})}if(droppedParts.length>0){deps.log("debug",`[preflight] range ${skipKey}: ${droppedParts.length} part(s) rendered nothing (${droppedParts.slice(0,3).join("; ")})`)}const content=parts.join("\n\n");if(content.length===0){deps.log("warn",`[preflight] planned block for range ${skipKey} rendered no text: ${droppedParts.slice(0,5).join("; ")||"all parts empty"}`);noteSkip(`${skipKey}: planned block rendered no text (${droppedParts.slice(0,3).join("; ")||"all parts empty"})`);continue}let summary=null;let outcome;let externalFold=false;const spanUnits=baselineKnown?planned.compressedTokens:messages.filter(message=>planned.effectiveMessageIds.includes(message.id)).reduce((total,message)=>total+(message.text??"").length,0);if(emergencyFold){const shrinkBound=Math.max(activeConfig.compress.minSummaryLength,Math.floor(spanUnits/NET_SHRINK_TOLERANCE));summary=deterministicDigest(entries2,startRef,endRef,{maxSummary:activeConfig.compress.maxSummaryLength,minSummaryLength:activeConfig.compress.minSummaryLength,shrinkBound,countText});deps.log("info",`[preflight] range ${skipKey}: deterministic digest fold of ${entries2.length} part(s) -> ${summary.length} chars, no summarization call (#2383)`)}else{try{const parts2=[];const chunks=splitSummaryContent(content,budget,countText);const maxSummary=activeConfig.compress.maxSummaryLength;const perChunkBudget=maxSummary>0?Math.floor((maxSummary-(chunks.length-1)*SUMMARY_JOIN_GAP)/chunks.length):void 0;for(const chunk of chunks){if(summaryCalls>=summaryBudget){budgetHit=true;break}summaryCalls+=1;if(probeGated&&probeDead)canarySpent=true;let part=await summarizeRange(deps,chunk,startRef,endRef,perChunkBudget);let transientTries=0;while("unusable"in part&&part.transient&&transientTries<TRANSIENT_EMPTY_SUMMARY_RETRIES&&transientRetryBudget>0&&summaryCalls<summaryBudget&&!deps.signal?.aborted){transientTries+=1;transientRetryBudget-=1;const delayMs=replayBackoffMs(transientTries);deps.log("warn",`[preflight] transient empty summary on ${startRef}:${endRef} (${part.unusable.slice(0,160)}); retrying same span in ${delayMs}ms (${transientTries}/${TRANSIENT_EMPTY_SUMMARY_RETRIES})`);await sleep(delayMs,deps.signal);summaryCalls+=1;part=await summarizeRange(deps,chunk,startRef,endRef,perChunkBudget)}if("unusable"in part&&part.deterministic)recordDeterministicEmpty();if("unusable"in part){outcome=part;break}if(part.external)externalFold=true;else clearDeterministicProbe();parts2.push(part.summary)}if(!budgetHit&&!outcome&&parts2.length===chunks.length){const candidate=parts2.join("\n\n");const shrinkOk=text2=>countText(text2)<=spanUnits*NET_SHRINK_TOLERANCE;if(maxSummary<=0||candidate.length<=maxSummary){if(shrinkOk(candidate)){summary=candidate}else{outcome={unusable:`assembled summary (~${countText(candidate)} units) does not shrink its range (~${spanUnits} units) \u2014 suspected regurgitation`}}}else if(candidate.length<content.length){const rescued=truncateSummaryToLimit(candidate,maxSummary,activeConfig.compress.minSummaryLength);if(rescued!==null&&shrinkOk(rescued)){deps.log("warn",`[preflight] range ${skipKey}: assembled summary ${candidate.length} chars exceeded maxSummaryLength (${maxSummary}); truncated to ${rescued.length} chars`);summary=rescued}else if(rescued!==null){outcome={unusable:`assembled summary (~${countText(rescued)} units after truncation) does not shrink its range (~${spanUnits} units) \u2014 suspected regurgitation`}}else{outcome={unusable:`assembled summary (${candidate.length} chars) exceeds maxSummaryLength (${maxSummary}) and cannot be truncated to a usable length`}}}else{outcome={unusable:`assembled summary (${candidate.length} chars) exceeds maxSummaryLength (${maxSummary}) and is not shorter than the folded content (${content.length} chars)`}}}}catch(err2){if(err2 instanceof UpstreamHttpError){const transient2=isTransientUpstreamError(err2.status,err2.body);const shapeRejection=isCredentialShapeRejection(err2.status,err2.body);const bodySnippet=safePrefix(err2.body.trim(),200);failure={kind:"upstream",status:err2.status,retryable:shapeRejection?false:transient2,detail:err2.status===429?shapeRejection?`the summarization call was rejected with HTTP 429 (rate_limit_error "Error") \u2014 suspected credential-shape rejection rather than a rate limit (the upstream requires a request attribute missing from the summary call, e.g. the client's billing-attribution system block; #2189)`:`the summarization call was rate-limited by the upstream (HTTP 429)`:`the summarization call was rejected by the upstream (HTTP ${err2.status})${bodySnippet?`: ${bodySnippet}`:""}`};deps.log("warn",`[preflight] summarization failed: HTTP ${err2.status} after ${err2.attempts} attempt(s)${bodySnippet?`: ${bodySnippet}`:""}`);const floorUnits=baselineKnown?2*MIN_CHUNK_TOKENS:2*minChars;if((err2.status===400||err2.status===413)&&!transient2&&ce2>cs2&&spanUnitsOf(messages,cs2,ce2,countText)>=floorUnits){lastUnusableDetail=`HTTP ${err2.status}: ${bodySnippet}`;deps.log("warn",`[preflight] chunk ${startRef}:${endRef} rejected with HTTP ${err2.status}; retrying with smaller chunks`);pushSpanHalves(maps.idxToRef,spans,cs2,ce2);continue}}else if(deps.signal?.aborted){failure=ABORTED_FAILURE;deps.log("warn",`[preflight] summarization aborted: client disconnected`)}else if(err2 instanceof SummaryTransportError){const caNote=isTlsTrustCode(err2.code)?` \u2014 ${tlsTrustRemediation()}`:"";failure={kind:"upstream",detail:`the summarization call failed: ${err2.message}${caNote}`,...err2.aborted?{}:{retryable:true}};deps.log("warn",`[preflight] summarization failed: ${err2.message}`)}else{failure={kind:"upstream",detail:"the summarization call failed unexpectedly"};deps.log("warn","[preflight] summarization failed unexpectedly")}break}}if(summary===null){const unusableDetail=outcome&&"unusable"in outcome?outcome.unusable:"unknown";if(outcome)lastUnusableDetail=unusableDetail;const deterministicUnusable=outcome!==void 0&&"unusable"in outcome&&outcome.deterministic===true;if(deterministicUnusable){deps.log("warn",`[preflight] range ${skipKey} got a deterministic empty summary (${unusableDetail}); skipping without halving \u2014 a normal stop with zero text is not size-driven (#2832)`);noteSkip(`${skipKey}: deterministic empty summary (${unusableDetail})`);skipSet.add(skipKey);break}const floorUnits=baselineKnown?2*MIN_CHUNK_TOKENS:2*minChars;if(ce2>cs2&&spanUnitsOf(messages,cs2,ce2,countText)>=floorUnits){deps.log("warn",`[preflight] chunk ${startRef}:${endRef} produced no usable summary (${unusableDetail}); retrying with smaller chunks`);pushSpanHalves(maps.idxToRef,spans,cs2,ce2);continue}deps.log("warn",`[preflight] range ${skipKey} produced no usable summary even at minimum size (${unusableDetail}); skipping it`);noteSkip(`${skipKey}: no usable summary even at minimum size (${unusableDetail})`);skipSet.add(skipKey);break}commitFold(skipKey,startRef,endRef,summary,planned.effectiveMessageIds,outcome?.external||externalFold,targetKey);break}if(appliedThisRound>=maxFoldsPerRound)break;if(failure||budgetHit)break}if(appliedThisRound===0){if(futileBail&&!budgetHit&&(relaxed||result.payloadEstimate<limit)){const zoneNote=relaxed?", including the relaxed recent zone":"";const skipNote=skipReasons.length>0?` Skipped: ${skipReasons.slice(0,3).join(" | ")}.`:"";if(eligibleForTierRecovery()){deps.log("info",`[preflight] remaining raw-fold pool (~${bailRemaining} tok${zoneNote}) below deficit (~${bailDeficit} tok); deferring to bounded tier-distillation recovery (#2952)`);break}failure={kind:"exhausted",deterministic:lastUnusableDetail===void 0&&!poolQueueDrop,detail:`futile round: after the folds so far, the remaining foldable content (~${bailRemaining} tokens${zoneNote}) cannot close the ~${bailDeficit}-token gap to the target even if every remaining range folded successfully.${skipNote} Raise the model context window or restart the session.`};break}if(!failure&&!budgetHit&&!relaxed&&result.payloadEstimate>=limit){activeConfig=relaxedConfig(deps.config);relaxed=true;summaryCalls=0;budgetHit=false;transientRetryBudget=TRANSIENT_EMPTY_RETRY_BUDGET;deps.log("warn","[preflight] no usable ranges outside the protected recent zone; relaxing soft protection (preserveRecentMessages/Tokens -> 0) and retrying");continue}break}}if(currentTokens>=limit&&!failure){if(!tierRecoveryAttempted&&eligibleForTierRecovery()){tierRecoveryAttempted=true;const rec=await attemptTierRecovery();deps.log("info",`[preflight] tier-distillation recovery finished: ${rec.recovered?"recovered":"not recovered"}; ${rec.callsUsed} summary call(s), net ~${rec.netSaved} tok saved (#2952)`);if(!rec.recovered){failure={kind:"exhausted",detail:rec.honestDetail}}}if(currentTokens>=limit&&!failure){const unusableNote=lastUnusableDetail?` Last unusable summary: ${safePrefix(lastUnusableDetail,300)}.`:"";const skipNote=skipReasons.length>0?` Skipped: ${skipReasons.slice(0,3).join(" | ")}.`:"";if(budgetHit){failure={kind:"exhausted",detail:`the preflight summarization budget (${summaryBudget} calls per protection regime) was exhausted before the payload fit the window${unusableNote}${skipNote}`}}else if(relaxed&&result.compressedRanges>0){failure={kind:"exhausted",deterministic:lastUnusableDetail===void 0&&!poolQueueDrop,detail:`${relaxedExhaustedDetail}${skipNote}`}}else if(result.compressedRanges===0){const cause=poolQueueDrop?"the shared summary pool was saturated and no summary call was ever dispatched (scheduler congestion, not a chain failure; auto-fold retries next turn)":skipReasons.length>0?skipReasons.slice(0,3).join(" | "):"each was below minCompressRange, had an unusable summary, or failed to apply";failure={kind:"exhausted",deterministic:rangesTried===0&&!poolQueueDrop&&lastUnusableDetail===void 0,detail:rangesTried===0?`no viable range could be compressed: ${cause}${unusableNote}`:`no range could be compressed across ${rangesTried} viable range${rangesTried===1?"":"s"}: ${cause}${unusableNote}`}}else{failure={kind:"exhausted",detail:`the compress budget was exhausted after ${effectiveRoundCap} rounds${unusableNote}${skipNote}`}}}}result.rangesRemaining=rangesRemaining;result.savedTokens=Math.max(0,startTokens-currentTokens);if(deps.signal?.aborted)failure=ABORTED_FAILURE;if(currentTokens>=limit&&!fitExitForward||failure?.kind==="aborted")result.failure=failure;result.fitsWindow=result.payloadEstimate<limit;if(deps.externalSummary!==void 0){result.externalDispatch={calls:deps.externalSummary.stats.calls,attempts:deps.externalSummary.stats.attempts}}return result}var SELF_HEAL_WINDOW=5;var SELF_HEAL_SUPPRESS_CAP_MS=10*60*1e3;var counters=new WeakMap;function selfHealOf(session){const raw=session.metadata["selfHeal"];if(raw===null||typeof raw!=="object")return void 0;const rec=raw;if(typeof rec["detected"]!=="string"||typeof rec["action"]!=="string"||typeof rec["since"]!=="number")return void 0;return{detected:rec["detected"],action:rec["action"],since:rec["since"]}}function nudgeSuppressed(session){return selfHealOf(session)?.action==="suppress-nudge"}function pluginLaneDegraded(session){return selfHealOf(session)?.action==="degrade-to-proxy"}function pluginLaneRestore(session,headerPresent,log2){if(!headerPresent||selfHealOf(session)?.action!=="degrade-to-proxy")return false;clearSelfHeal(session);const st2=counters.get(session);if(st2){st2.zombieStreak=0;st2.idleStreak=0}log2("info",`[${session.id}] [self-heal] plugin lane is back (plugin header) \u2014 session restored to plugin mode`);return true}function clearSelfHeal(session){delete session.metadata["selfHeal"]}function armSelfHeal(session,detected,action){session.metadata["selfHeal"]={detected,action,since:Date.now()}}function reductionKeyOf(session){return`${session.state.nextBlockId}:${session.lastCompress?.at??0}`}function isBiliToolName(name){return name.startsWith("mcp__bili__")||ACP_TOOL_NAMES.has(name)}var TOOL_WALK_MAX_DEPTH=8;var MCP_BILI_NAMESPACE_NAME="mcp__bili";function declaresMcpBiliInList(entries2,depth){if(!Array.isArray(entries2)||depth>TOOL_WALK_MAX_DEPTH)return false;for(const entry of entries2){if(entry===null||typeof entry!=="object")continue;const rec=entry;const name=rec["name"];if(typeof name==="string"&&(name.startsWith("mcp__bili__")||name===MCP_BILI_NAMESPACE_NAME))return true;const fn=rec["function"];if(fn!==null&&typeof fn==="object"){const name2=fn["name"];if(typeof name2==="string"&&name2.startsWith("mcp__bili__"))return true}if(declaresMcpBiliInList(rec["functionDeclarations"],depth+1))return true;if(declaresMcpBiliInList(rec["tools"],depth+1))return true}return false}function declaresMcpBiliToolsOnWire(parsed){if(parsed===null||typeof parsed!=="object")return false;return declaresMcpBiliInList(parsed["tools"],0)}function countBiliToolUses(messages){let n=0;for(const m2 of messages)if(m2.toolName!==void 0&&isBiliToolName(m2.toolName))n+=1;return n}function evaluateSelfHealRound(session,inputs,log2){const st2=counters.get(session)??{lastReductionKey:void 0,zombieStreak:0,idleStreak:0};counters.set(session,st2);const key2=reductionKeyOf(session);const reduction=st2.lastReductionKey!==void 0&&key2!==st2.lastReductionKey;st2.lastReductionKey=key2;const active=selfHealOf(session);if(active!==void 0&&active.action==="suppress-nudge"&&Date.now()-active.since>=SELF_HEAL_SUPPRESS_CAP_MS){clearSelfHeal(session);st2.zombieStreak=0;st2.idleStreak=0;log2("info",`[${session.id}] [self-heal] nudge suppression expired after ${Math.round((Date.now()-active.since)/6e4)} min without compression evidence \u2014 re-enabling the nudge channel (re-arms after ${SELF_HEAL_WINDOW} more idle rounds if still ignored) (#3004)`)}if(active!==void 0&&selfHealOf(session)!==void 0){if(active.action==="degrade-to-proxy"&&inputs.pluginHeaderPresent){clearSelfHeal(session);st2.zombieStreak=0;st2.idleStreak=0;log2("info",`[${session.id}] [self-heal] plugin lane is back (live marker on request) \u2014 session restored to plugin mode`)}else if(active.action==="suppress-nudge"&&(reduction||inputs.biliToolUses>0)){clearSelfHeal(session);st2.zombieStreak=0;st2.idleStreak=0;log2("info",`[${session.id}] [self-heal] compression resumed \u2014 nudge suppression lifted`)}}const pluginBound=typeof session.metadata["pluginAgent"]==="string";if(inputs.nudgeActive){const zombieSignal=pluginBound&&!inputs.pluginHeaderPresent&&!inputs.biliToolsDeclared;if(reduction||inputs.biliToolUses>0){st2.zombieStreak=0;st2.idleStreak=0}else{st2.idleStreak+=1;st2.zombieStreak=zombieSignal?st2.zombieStreak+1:0}}if(selfHealOf(session)!==void 0)return;if(pluginBound&&st2.zombieStreak>=SELF_HEAL_WINDOW){if(inputs.degradeAvailable){armSelfHeal(session,"plugin-lane-gone","degrade-to-proxy");log2("warn",`[${session.id}] [self-heal] plugin lane gone for ${st2.zombieStreak} nudged rounds (no x-bili-plugin header, no bili tools declared) \u2014 session degraded to proxy mode: ACP tools re-injected wire-side, nudge kept`)}else{armSelfHeal(session,"plugin-lane-gone","suppress-nudge");log2("warn",`[${session.id}] [self-heal] plugin lane gone for ${st2.zombieStreak} nudged rounds \u2014 wire injection unavailable (compress.injectTool=false), nudge suppressed for this session`)}st2.zombieStreak=0;st2.idleStreak=0;return}if(st2.idleStreak>=SELF_HEAL_WINDOW){armSelfHeal(session,"nudge-idle","suppress-nudge");log2("warn",`[${session.id}] [self-heal] nudge idle for ${st2.idleStreak} rounds (injected but nothing ever compressed) \u2014 nudge suppressed for this session until compression resumes`);st2.idleStreak=0;st2.zombieStreak=0}}function biliToolsDeclaredOnWire(parsed,protocol,named){if(parsed===null||typeof parsed!=="object")return false;const body=parsed;const tools=body["tools"];const wanted=name=>named===void 0?isBiliToolName(name):name===named;if(!Array.isArray(tools))return false;for(const t of tools){if(t===null||typeof t!=="object")continue;const rec=t;const flat=typeof rec["name"]==="string"?rec["name"]:void 0;if(flat!==void 0&&wanted(flat))return true;const fn=rec["function"];if(fn!==null&&typeof fn==="object"){const inner=fn["name"];if(typeof inner==="string"&&wanted(inner))return true}const decls=rec["functionDeclarations"];if(Array.isArray(decls)){for(const d of decls){if(d!==null&&typeof d==="object"){const n=d["name"];if(typeof n==="string"&&wanted(n))return true}}}}void protocol;return false}init_util();init_util();init_dist();var SIDE_REQUEST_MAX_TOKENS=200;var SIDE_REQUEST_AGENTS=new Set(["title"]);var SERVER_EXECUTED_TOOL_TYPES=/^(?:web_search|web_fetch)_\d{8}$/;function isServerToolUtilityCall(parsed){if(!parsed||typeof parsed!=="object")return false;const p2=parsed;const messages=p2.messages;if(!Array.isArray(messages)||messages.length!==1)return false;const tools=p2.tools;if(!Array.isArray(tools)||tools.length===0)return false;const declared=new Set;for(const t of tools){if(t===null||typeof t!=="object")return false;const type=t.type;if(typeof type!=="string"||!SERVER_EXECUTED_TOOL_TYPES.test(type))return false;const name=t.name;if(typeof name==="string"&&name.length>0)declared.add(name)}const choice=p2.tool_choice;if(choice===void 0)return true;if(choice==="auto"||choice==="any")return true;if(choice!==null&&typeof choice==="object"){const c=choice;if(c.type==="auto"||c.type==="any")return true;if(c.type==="tool"&&typeof c.name==="string"&&declared.has(c.name))return true}return false}function isSideRequest(parsed,requestAgent){if(!parsed||typeof parsed!=="object")return false;if(requestAgent!==void 0&&SIDE_REQUEST_AGENTS.has(requestAgent))return true;if(requestAgent==="main")return false;const p2=parsed;if(isServerToolUtilityCall(p2))return true;if(Array.isArray(p2.tools)&&p2.tools.length>0)return false;const field=outputBudgetField(parsed);if(!field)return false;const raw=readOutputBudget(p2,field);return typeof raw==="number"&&raw>0&&raw<=SIDE_REQUEST_MAX_TOKENS}var DSH_TITLE_SYSTEM_PREFIX="Create a concise title for an AI coding-assistant session";function isDshTitleRequest(parsed){if(!parsed||typeof parsed!=="object")return false;const p2=parsed;if(Array.isArray(p2.tools)&&p2.tools.length>0)return false;return systemCarrierTexts(p2).some(t=>t.startsWith(DSH_TITLE_SYSTEM_PREFIX))}var DSH_AUTO_REVIEW_SYSTEM_PREFIX="You are the final authorization reviewer for exactly one pending tool call";function isDshAutoReviewRequest(protocol,parsed){if(protocol===null||!parsed||typeof parsed!=="object")return false;const p2=parsed;if(Array.isArray(p2.tools)&&p2.tools.length>0)return false;if(!systemCarrierTexts(p2).some(t=>t.trimStart().startsWith(DSH_AUTO_REVIEW_SYSTEM_PREFIX)))return false;const entries2=protocol==="responses"?p2.input:protocol==="google"?p2.contents:p2.messages;if(!Array.isArray(entries2))return false;let users=0;let userHasContent=false;for(const entry of entries2){if(entry===null||typeof entry!=="object")continue;const rec=entry;const role=rec.role;if(role==="system"||role==="developer")continue;if(role!=="user")return false;if(rec.type!==void 0&&rec.type!=="message")return false;users+=1;const c=rec.content??rec.parts;if(typeof c==="string"){if(c.length>0)userHasContent=true}else if(Array.isArray(c)&&c.length>0){userHasContent=true}}return users===1&&userHasContent}var CLAUDE_CODE_TITLE_SESSION_TAG="<session>";function isClaudeCodeTitleRequest(protocol,parsed){if(protocol===null||!parsed||typeof parsed!=="object")return false;const p2=parsed;if(Array.isArray(p2.tools)&&p2.tools.length>0)return false;const entries2=protocol==="responses"?p2.input:protocol==="google"?p2.contents:p2.messages;if(!Array.isArray(entries2)||entries2.length!==1)return false;const entry=entries2[0];if(entry===null||typeof entry!=="object")return false;const rec=entry;if(rec.role!=="user")return false;if(rec.type!==void 0&&rec.type!=="message")return false;const c=rec.content??rec.parts;let text2="";if(typeof c==="string"){text2=c}else if(Array.isArray(c)){for(const b2 of c){if(b2!==null&&typeof b2==="object"&&typeof b2.text==="string"){text2+=b2.text}}}return text2.trimStart().startsWith(CLAUDE_CODE_TITLE_SESSION_TAG)}function demoteGate(s3){return!s3.countTokens&&!s3.responsesCompact&&s3.protocol!==null&&s3.pluginMode&&s3.requestAgent!=="main"&&!s3.wsLaneEnvelope&&!s3.publicForkPrefix}function resolveSideLane(s3){if(s3.countTokens||s3.responsesCompact||s3.protocol===null){return{lane:"main",demoted:false,reason:"not a model turn"}}if(s3.stripApplied){return{lane:"side",demoted:true,reason:"leaked bili tools stripped (#1897)"}}if(s3.sideIntent){const reason=s3.sideLabel??(s3.requestAgent!==void 0?`agent=${s3.requestAgent}`:`max_tokens<=${SIDE_REQUEST_MAX_TOKENS}`);return{lane:"side",demoted:false,reason}}return{lane:"main",demoted:false,reason:"main turn"}}var BILI_TOOL_NAMES=new Set([...ACP_TOOL_NAMES,ABSORB_TOOL_NAME,RULE_TOOL_NAME,RETRIEVE_TOOL_NAME,READ_ORIGINAL_IMAGE_TOOL_NAME]);function biliToolNamesIn(parsed){const tools=parsed.tools;if(!Array.isArray(tools)||tools.length===0)return null;const names=[];for(const t of tools){if(!t||typeof t!=="object")return null;const o=t;const decls=o.functionDeclarations;if(Array.isArray(decls)){for(const d of decls){if(!d||typeof d!=="object"||typeof d.name!=="string")return null;names.push(d.name)}continue}let name=o.name;if(typeof name!=="string"){const fn=o.function;if(fn&&typeof fn==="object"&&typeof fn.name==="string")name=fn.name}if(typeof name!=="string")return null;names.push(name)}return names}function hasLeakedBiliToolsOnly(parsed){if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return false;const p2=parsed;const names=biliToolNamesIn(p2);if(names===null||!names.every(n=>BILI_TOOL_NAMES.has(n)))return false;const field=outputBudgetField(p2);if(field){const raw=readOutputBudget(p2,field);if(typeof raw==="number"&&raw>0&&raw<=SIDE_REQUEST_MAX_TOKENS)return false}return true}function stripLeakedBiliTools(parsed){if(!hasLeakedBiliToolsOnly(parsed))return false;delete parsed.tools;return true}function outputBudgetField(parsed){if(!parsed||typeof parsed!=="object")return null;const p2=parsed;for(const field of["max_tokens","max_completion_tokens","max_output_tokens"]){if(typeof p2[field]==="number"&&p2[field]>0)return field}const gen=p2.generationConfig;if(gen&&typeof gen==="object"){const v2=gen.maxOutputTokens;if(typeof v2==="number"&&v2>0)return"generationConfig.maxOutputTokens"}return null}function readOutputBudget(parsed,field){if(field!=="generationConfig.maxOutputTokens"){const v3=parsed[field];return typeof v3==="number"?v3:void 0}const gen=parsed.generationConfig;if(!gen||typeof gen!=="object")return void 0;const v2=gen.maxOutputTokens;return typeof v2==="number"?v2:void 0}function writeOutputBudget(parsed,field,value){const tokens=Number.isInteger(value)?value:Math.floor(value);if(field!=="generationConfig.maxOutputTokens"){parsed[field]=tokens;return}const gen=parsed.generationConfig;parsed.generationConfig={...gen&&typeof gen==="object"?gen:{},maxOutputTokens:tokens}}var OUTPUT_RESTORE_ABSOLUTE_FLOOR=32768;var OUTPUT_HIGH_WATER_TRUST_MIN=4096;var warnedNoOutputCeiling=new Set;var WARNED_NO_OUTPUT_CEILING_CAP=4096;function noteNoOutputCeilingWarning(sessionId,model){const key2=`${sessionId}|${model}`;if(warnedNoOutputCeiling.has(key2))return false;if(warnedNoOutputCeiling.size>=WARNED_NO_OUTPUT_CEILING_CAP)warnedNoOutputCeiling.clear();warnedNoOutputCeiling.add(key2);return true}function noCeilingWarnText(sessionId,model,from,to2){return`[${sessionId}] output-budget restore has NO known output ceiling for model=${model} (raised ${from} -> ${to2}) \u2014 the target was the client's own raw-history estimate, which decays unbounded; while it stays pathologically small every turn truncates at max-tokens. Declare the model's max output in the bili config (providers.<url>.models."${model}".output) or have the client report it to floor the restore higher (#1840/#3071)`}var warnedDshMidBandNoCeiling=new Set;function noteDshMidBandNoCeilingWarning(sessionId,model){const key2=`${sessionId}|${model}`;if(warnedDshMidBandNoCeiling.has(key2))return false;if(warnedDshMidBandNoCeiling.size>=WARNED_NO_OUTPUT_CEILING_CAP)warnedDshMidBandNoCeiling.clear();warnedDshMidBandNoCeiling.add(key2);return true}function clearNoCeilingDegraded(session,model){const cur=session.metadata.outputBudgetDegraded;if(cur!==void 0&&cur.model===model)delete session.metadata.outputBudgetDegraded}function restoreOutputBudget(parsed,session,log2,outputCeiling,dshLane){const field=outputBudgetField(parsed);if(!field)return;const p2=parsed;const value=readOutputBudget(p2,field);if(value===void 0)return;const modelName=typeof p2.model==="string"&&p2.model.length>0?p2.model:"?";const ceiling=typeof outputCeiling==="number"&&outputCeiling>SIDE_REQUEST_MAX_TOKENS?outputCeiling:void 0;const collapsed=dshLane===true&&ceiling!==void 0&&value<ceiling;if(value>SIDE_REQUEST_MAX_TOKENS&&!collapsed){session.metadata.outputBudgetHighWater=value;clearNoCeilingDegraded(session,modelName);if(dshLane===true&&ceiling===void 0&&Array.isArray(p2.tools)&&p2.tools.length>0&¬eDshMidBandNoCeilingWarning(session.id,modelName)){log2("warn",`[${session.id}] dsh-lane main request carries output budget ${value} with NO known output ceiling for model=${modelName} \u2014 cannot tell a raw-history collapse from deliberate intent, forwarding verbatim; declare the model's max output (providers.<url>.models."${modelName}".output) to arm the mid-band collapse rescue (#3438)`)}return}if(!Array.isArray(p2.tools)||p2.tools.length===0)return;const highWaterRaw=session.metadata.outputBudgetHighWater;const highWater=typeof highWaterRaw==="number"&&highWaterRaw>SIDE_REQUEST_MAX_TOKENS?highWaterRaw:void 0;let target=highWater;if(ceiling!==void 0){if(highWater!==void 0&&highWater>ceiling){session.metadata.outputBudgetHighWater=ceiling;log2("warn",`[${session.id}] output budget high-water ${highWater} exceeds ${modelName}'s declared output ceiling ${ceiling} \u2014 corrected the session high-water to the ceiling in place so subsequent turns stop replaying the over-bound value (#3833: a cross-model high-water must not outlive its origin model)`)}target=ceiling}else if(target===void 0||target<OUTPUT_HIGH_WATER_TRUST_MIN){target=OUTPUT_RESTORE_ABSOLUTE_FLOOR}if(typeof target==="number"){writeOutputBudget(p2,field,target);const note=ceiling!==void 0?highWater===void 0?"; no healthy high-water yet \u2014 using known output ceiling (#1665/#1840)":highWater>ceiling?`; high-water ${highWater} exceeded the ceiling \u2014 clamped to it and the water corrected in place (#3833)`:`; high-water ${highWater} below known output ceiling \u2014 floored (#1665/#1840)`:target===highWater?"; no known output ceiling \u2014 restored to the session's own recorded budget, never raised above it (#3406)":"; no known output ceiling \u2014 floored to the absolute capability minimum (#3071)";const origin=collapsed&&value>SIDE_REQUEST_MAX_TOKENS?"#3438: dsh-lane mid-band collapse above the <=200 starve gate":"#546: client shrank it from its raw-history estimate";log2("info",`[${session.id}] output budget restored ${value} -> ${target} (${origin}${note})`)}if(ceiling!==void 0)clearNoCeilingDegraded(session,modelName);else session.metadata.outputBudgetDegraded={model:modelName,value:typeof target==="number"?target:value,ts:Date.now()};if(ceiling===void 0&¬eNoOutputCeilingWarning(session.id,modelName)){log2("warn",noCeilingWarnText(session.id,modelName,value,typeof target==="number"?target:value))}}var SIDE_REQUEST_GUARD_TOLERANCE=1.15;function sideRequestGuard(parsed,protocol,modelContextLimit,imageBilling="bytes",configuredCap,headroomCap=1,armedLimit=0,imageReserve,reserveHeadroom=false){let limit=modelContextLimit;if(armedLimit>0&&(limit<=0||armedLimit<limit))limit=armedLimit;const field=outputBudgetField(parsed);const maxOut=(field?readOutputBudget(parsed,field):void 0)??0;if(reserveHeadroom&&limit>0)limit=reserveOutputHeadroom(limit,maxOut,headroomCap);const imageMass=imageReserve??imageTokensInParsedBody(protocol,parsed,imageBilling,configuredCap);const estimate=estimateRawBodyTokens(parsed)+imageMass;return{blocked:limit>0&&estimate>=limit*SIDE_REQUEST_GUARD_TOLERANCE,estimate,limit}}var OUTPUT_CLAMP_MARGIN_PCT=.05;var OUTPUT_CLAMP_MIN_MARGIN=2048;var OUTPUT_CLAMP_ESTIMATE_SAFETY=1.12;var OUTPUT_CLAMP_FLOOR=1024;var OUTPUT_CLAMP_MIN_OUTPUT=4096;var OUTPUT_LEDGER_FLOOR_GIANT_REQUEST_PCT=.25;var EMERGENCY_NUDGE_ESCALATION_PCT=.7;function modelVisibleTools(tools){if(!Array.isArray(tools)||!tools.some(t=>t?.type==="tool_search"))return tools??[];const project=tool=>{if(!tool||typeof tool!=="object")return tool;const item=tool;if(item.type==="namespace"&&Array.isArray(item.tools)){return{...item,tools:item.tools.map(project)}}if(item.type==="function"&&typeof item.name==="string"&&item.parameters&&typeof item.parameters==="object"&&!Array.isArray(item.parameters)&&item.defer_loading===true){return{type:item.type,name:item.name,defer_loading:true}}return tool};return tools.map(project)}function countLoadedToolTokens(body){if(!Array.isArray(body.input))return 0;let tokens=0;for(const item of body.input){if(["additional_tools","tool_search_call","tool_search_output","mcp_list_tools"].includes(item?.type)){tokens+=defaultCountTokens(JSON.stringify(item))}}return tokens}function countSystemAndToolsTokens(systemText,tools){return defaultCountTokens(systemText??"")+defaultCountTokens(JSON.stringify(modelVisibleTools(tools)))}function estimateInputTokens(processedMessages,systemText,tools,lastInputTokens,lastInputTokensSource,kFactor,kOrigin,origin,loadedToolTokens=0,imageTokens=0){const est=applyEstimateCalibration(estimateCoreMessages(processedMessages)+countSystemAndToolsTokens(systemText,tools)+loadedToolTokens,kFactor,kOrigin,origin)+imageTokens;const baseline=lastInputTokens>0&&lastInputTokensSource==="usage"?lastInputTokens:0;return Math.max(baseline,est)}function projectThinkingMass(msgs,input){if(!input.measured||!(input.providerInputTokens>0))return 0;const targets=[];for(const m2 of msgs){if(m2.contentType!=="reasoning")continue;if(typeof m2.thinkingSignature!=="string"||m2.thinkingSignature.length===0)continue;if(typeof m2.text==="string"&&m2.text.trim().length>0)continue;targets.push({msg:m2,sig:m2.thinkingSignature.length})}if(targets.length===0)return 0;const overhead=typeof input.storedOverhead==="number"&&Number.isFinite(input.storedOverhead)&&input.storedOverhead>0?input.storedOverhead:countSystemAndToolsTokens(input.systemText,input.tools);const gap=Math.max(0,input.providerInputTokens-estimateCoreMessages(msgs)-overhead-Math.max(0,input.imageTokens));if(gap<=0)return 0;const totalSig=targets.reduce((s3,t)=>s3+t.sig,0);let assigned=0;for(let i=0;i<targets.length;i++){const t=targets[i];const share=i===targets.length-1?gap-assigned:Math.floor(gap*t.sig/totalSig);t.msg.thinkingTokens=share;assigned+=share}return gap}function responsesSysDevItemText(item){const c=item.content;if(typeof c==="string")return c;if(Array.isArray(c)){return c.map(p2=>p2&&typeof p2==="object"&&typeof p2.text==="string"?p2.text:"").join("\n")}return""}function estimateWireOverhead(protocol,body){let parsed;if(typeof body==="object"&&!Buffer.isBuffer(body)){parsed=body}else{try{parsed=JSON.parse(typeof body==="string"?body:body.toString("utf8"))}catch{return 0}}const sysRaw=protocol==="responses"?parsed.instructions:protocol==="google"?googleSystemText(parsed):parsed.system;let sysText="";if(typeof sysRaw==="string"){sysText=sysRaw}else if(Array.isArray(sysRaw)){sysText=sysRaw.map(part=>typeof part?.text==="string"?part.text:"").join("\n")}if(protocol==="openai"&&Array.isArray(parsed.messages)){const hoisted=parsed.messages.filter(m2=>m2.role==="system"||m2.role==="developer").map(m2=>typeof m2.content==="string"?m2.content:"").join("\n");sysText=sysText?`${sysText}
|
|
1065
1065
|
${hoisted}`:hoisted}if(protocol==="responses"&&Array.isArray(parsed.input)){const hoisted=parsed.input.filter(item=>item.role==="system"||item.role==="developer").map(responsesSysDevItemText).filter(t=>t.length>0).join("\n");if(hoisted)sysText=sysText?`${sysText}
|
|
1066
|
-
${hoisted}`:hoisted}return defaultCountTokens(sysText)+defaultCountTokens(JSON.stringify(protocol==="responses"?modelVisibleTools(parsed.tools):parsed.tools??[]))+(protocol==="responses"?countLoadedToolTokens(parsed):0)}function clampOutputBudget(requested,inputEstimate,nativeWindow,knownOutputCeiling){const ceilingBound=typeof knownOutputCeiling==="number"&&Number.isFinite(knownOutputCeiling)?knownOutputCeiling:Number.POSITIVE_INFINITY;const clampFor=est=>{const margin=Math.max(OUTPUT_CLAMP_MIN_MARGIN,Math.ceil(est*OUTPUT_CLAMP_MARGIN_PCT));const cap=Math.min(Math.floor(nativeWindow-est-margin),ceilingBound);if(cap<OUTPUT_CLAMP_FLOOR||cap>=requested)return void 0;const floorOut=Math.min(OUTPUT_CLAMP_MIN_OUTPUT,Math.floor(nativeWindow-est),ceilingBound);const clamped=Math.max(cap,floorOut);if(clamped>=requested)return void 0;return clamped};const safe=clampFor(Math.ceil(inputEstimate*OUTPUT_CLAMP_ESTIMATE_SAFETY));if(safe!==void 0)return safe;return clampFor(inputEstimate)}function dshLedgerFloorTokens(metadata){const bytes=metadata?.["dshCompactionRefusedBytes"];if(typeof bytes!=="number"||!Number.isFinite(bytes)||bytes<=0)return 0;return Math.ceil(bytes/4)}function emergencyNudge(nudge,escalationPct=EMERGENCY_NUDGE_ESCALATION_PCT,minCompressRange=0){if(!nudge||nudge.shouldInject)return false;if(nudge.contextUsage<escalationPct)return false;if(!nudge.compressibleRanges.some(r=>minCompressRange<=0||(r.chars??r.tokens*4)>=minCompressRange))return false;const b2=nudge.breakdown;const minBenefit=b2?.minPressureBenefit;return!(typeof minBenefit==="number"&&Number.isFinite(minBenefit)&&minBenefit>0&&(b2.maxPending??0)<minBenefit)}function emergencyNudgeArmed(session,nudge,minCompressRange,tokenCount,growthStep){if(!emergencyNudge(nudge,void 0,minCompressRange))return false;const now=Date.now();const key2=reductionKeyOf(session);const raw=session.metadata["emergencyNudgeGate"];if(raw===null||typeof raw!=="object"){session.metadata["emergencyNudgeGate"]={at:now,tokens:tokenCount,reductionKey:key2};return true}const g2=raw;const prevAt=typeof g2["at"]==="number"?g2["at"]:NaN;const prevTokens=typeof g2["tokens"]==="number"?g2["tokens"]:NaN;const prevKey=typeof g2["reductionKey"]==="string"?g2["reductionKey"]:void 0;const step=typeof growthStep==="number"&&Number.isFinite(growthStep)&&growthStep>0?growthStep:5e4;let arm=false;if(!Number.isFinite(prevAt)||!Number.isFinite(prevTokens)||prevKey===void 0){arm=true}else if(prevKey!==key2){arm=true}else if(tokenCount-prevTokens>=step){arm=true}else if(now-prevAt>=SELF_HEAL_SUPPRESS_CAP_MS){arm=true}if(arm)session.metadata["emergencyNudgeGate"]={at:now,tokens:tokenCount,reductionKey:key2};return arm}function clampOutgoingOutput(rebuilt,field,ctx,sessionId,log2,onClamped){const raw=readOutputBudget(rebuilt,field);if(typeof raw!=="number")return;const loadedToolTokens=field==="max_output_tokens"?countLoadedToolTokens(rebuilt):0;const inputEstimate=estimateInputTokens(ctx.processedMessages,ctx.systemText,ctx.tools,ctx.lastInputTokens,ctx.lastInputTokensSource,ctx.kFactor,ctx.kOrigin,ctx.origin,loadedToolTokens,ctx.imageTokens);const ledgerFloor=typeof ctx.ledgerFloorTokens==="number"&&Number.isFinite(ctx.ledgerFloorTokens)?Math.max(0,Math.floor(ctx.ledgerFloorTokens)):0;const viewAtEnforcedTarget=typeof ctx.headroomWindow==="number"&&Number.isFinite(ctx.headroomWindow)&&ctx.headroomWindow>0&&inputEstimate>=ctx.headroomWindow;const giantRequestedBudget=ctx.nativeWindow>0&&raw>=OUTPUT_LEDGER_FLOOR_GIANT_REQUEST_PCT*ctx.nativeWindow;const planningInput=viewAtEnforcedTarget||giantRequestedBudget?Math.max(inputEstimate,ledgerFloor):inputEstimate;const capped=clampOutputBudget(raw,planningInput,ctx.nativeWindow,ctx.knownOutputCeiling);if(capped!==void 0){writeOutputBudget(rebuilt,field,capped);const overTarget=ctx.headroomWindow!==void 0&&ctx.headroomWindow<ctx.nativeWindow&&planningInput>=ctx.headroomWindow;log2("info",`[${sessionId}] output budget clamped ${raw} -> ${capped} (input~${inputEstimate}${ledgerFloor>inputEstimate?`, planning floor ${ledgerFloor} from the refused dsh compaction replay (#2490)`:""}, window=${ctx.nativeWindow}); prevents input+output overflow (#453)${overTarget?`; input already exceeds the headroom-adjusted target ~${ctx.headroomWindow} that nudge/preflight enforce \u2014 only compression can recover it, this clamp guarantees native-window fit only (#2096)`:""}`);onClamped?.({raw,capped,window:ctx.nativeWindow,planningInput,ledgerFloor})}}init_util();init_logger();var MAX_SESSIONS_TRACKED=8;var MAX_SESSIONS_REMEMBERED=32;var MAX_ABLATION_ENTRIES=64;var entries=new Map;function keyOf(origin,model){return`${origin}\0${model??""}`}function evictStaleEntries(){if(entries.size<=MAX_ABLATION_ENTRIES)return;const oldestFirst=[...entries.values()].sort((a,b2)=>a.lastAt-b2.lastAt);for(const rec of oldestFirst){if(entries.size<=MAX_ABLATION_ENTRIES)break;entries.delete(keyOf(rec.origin,rec.model))}}function pckKeyAbated(egressUrl,fallbackOrigin,modelId){const origin=normalizeUpstreamOrigin(egressUrl)??normalizeUpstreamOrigin(fallbackOrigin);if(!origin)return false;const model=typeof modelId==="string"&&modelId!==""?modelId:void 0;return entries.has(keyOf(origin,model))}function recordPckAblation(facts){const origin=normalizeUpstreamOrigin(facts.origin)??facts.origin.trim();if(!origin)return;const model=typeof facts.model==="string"&&facts.model!==""?facts.model:void 0;const now=Date.now();const k2=keyOf(origin,model);let e=entries.get(k2);const where=`${origin}${model?` (model ${model})`:""}`;if(!e){e={origin,model,firstAt:now,lastAt:now,confirmations:1,sessions:[],sessionCounts:new Map};entries.set(k2,e);evictStaleEntries();const snippet=facts.errSnippet.replace(/\s+/g," ").slice(0,200);log("warn",`[pck] ${where} rejected prompt_cache_key \u2014 A/B confirmed (with key: HTTP ${facts.statusWithKey}; identical request without the key was accepted). bili now withholds the cache-routing key from this destination until proxy restart (#2645 probe-and-remember). Affected session(s): ${facts.sessionId}. Upstream error: ${snippet||"(empty body)"}. CAVEAT: if this destination is a relay/account pool keyed by prompt_cache_key, its prefix-cache affinity for these conversations may degrade for the rest of this process's lifetime (a transient unrelated 400 can be misattributed); restart resets.`)}else{e.confirmations+=1;e.lastAt=now;log("debug",`[pck] ${where} ablation reconfirmed (${e.confirmations}\xD7 total, session ${facts.sessionId}, #2645)`)}if(facts.sessionId){e.sessionCounts.set(facts.sessionId,(e.sessionCounts.get(facts.sessionId)??0)+1);while(e.sessionCounts.size>MAX_SESSIONS_REMEMBERED){let dropKey;let dropCount=Infinity;for(const[sid,n]of e.sessionCounts)if(n<dropCount){dropCount=n;dropKey=sid}if(dropKey===void 0)break;e.sessionCounts.delete(dropKey)}e.sessions=[...e.sessionCounts.entries()].sort((a,b2)=>b2[1]-a[1]).map(([s3])=>s3).slice(0,MAX_SESSIONS_TRACKED)}}function pckAblations(){return[...entries.values()].sort((a,b2)=>b2.lastAt-a.lastAt).map(({sessionCounts:_sessionCounts,...rest})=>rest)}init_logger();init_log_mask();init_knobs();function bodyDumpEnabled2(){return bodyDumpEnabled()}var dumpFailCount=0;var lastDumpFailLog=0;function logDumpFailure(where,err2){dumpFailCount++;const now=Date.now();if(dumpFailCount===1||now-lastDumpFailLog>=6e4){lastDumpFailLog=now;const msg=err2 instanceof Error?err2.message:String(err2);log("warn",`[dump] ${where} failed (total ${dumpFailCount}x): ${msg}`)}}var unrecognizedPathCounts=new Map;function logUnrecognizedPath(log2,url){const key2=maskUrlsInText(url.split("?")[0]);const n=(unrecognizedPathCounts.get(key2)??0)+1;unrecognizedPathCounts.set(key2,n);if(n<=3){log2("warn",`unrecognized path ${key2} \u2014 not a known protocol (/chat/completions, /llm_raw_chat, /v1/messages, /responses, /responses/compact); forwarding unchanged`)}else if(n===4){log2("info",`unrecognized path ${key2}: forwarding unchanged; further occurrences suppressed`)}}function getUnrecognizedPathStats(){const paths={};let total=0;for(const[path53,n]of unrecognizedPathCounts){paths[path53]=n;total+=n}return{total,paths}}function isModelDiscoveryPath(path53){return path53.replace(/\/+$/,"").endsWith("/models")}function isV1InternalControlPlanePath(path53){const p2=path53.split("?",2)[0];return/\/v1internal:(?!streamGenerateContent$|generateContent$|countTokens$)/.test(p2)}init_turn_separator();init_dist();init_knobs();init_dist();init_billing();init_dist();init_logger();init_knobs();var RENDER_TAG_RE=/\n?\x3cacp\s[^>]*\x3e[\s\S]*?\x3c\/acp\x3e/g;var CHAIN_TAG_PREFIX="<bili-chain ";var SUMMARY_MARKER="[Compressed conversation section]";var CRUSH_KEY2="__acp_crush";function normText(m2){return normalizeEchoArtifacts((m2.text??"").replace(RENDER_TAG_RE,"")).trim()}function isReasoning(m2){return m2.contentType==="reasoning"}function isCarrier(m2){if(m2.summaryOfBlockId!==void 0)return true;const t=m2.text??"";return t.startsWith(CHAIN_TAG_PREFIX)||t.includes(SUMMARY_MARKER)}function isSummaryCarrier(m2){if(m2.summaryOfBlockId!==void 0)return true;const t=m2.text??"";return t.includes(SUMMARY_MARKER)||m2.id.startsWith("acp_summary")}function isCrushedToolResult(m2){if(m2.contentType!=="tool-result")return false;const t=(m2.text??"").trim();if(!t.startsWith("{"))return false;try{const o=JSON.parse(t);return!!o&&typeof o==="object"&&Object.hasOwn(o,CRUSH_KEY2)}catch{return false}}function isCcrStoredResult(m2){return m2.contentType==="tool-result"&&parseStoredPlaceholder(m2.text??"")!==null}var TRUNCATION_LINE_RE=/\n\.\.\.\[truncated for context space\][^\n]*\n/;function isTruncationExit(m2){return TRUNCATION_LINE_RE.test(m2.text??"")}function isTruncatedTwin(a,b2){const bt2=b2.text??"";const m2=TRUNCATION_LINE_RE.exec(bt2);if(!m2)return false;const at2=a.text??"";if(!at2||at2.length<=bt2.length)return false;const strip=s3=>s3.replace(RENDER_TAG_RE,"").trim();const pre=strip(bt2.slice(0,m2.index));const post=strip(bt2.slice(m2.index+m2[0].length));const na=strip(at2);return pre.length>0&&post.length>0&&na.startsWith(pre)&&na.endsWith(post)}function fp(m2){const id=m2.toolCallId?`#${m2.toolCallId}`:"";const name=m2.contentType==="tool-call"&&m2.toolName?`:${m2.toolName}`:"";const t=normText(m2).replace(/\s+/g," ").trim().slice(0,80);return`${m2.role}/${m2.contentType}${name}${id}|${t}`}function stableEqual(a,b2){if(a.role!==b2.role||a.contentType!==b2.contentType)return false;if(a.contentType==="tool-call"&&a.toolName&&b2.toolName&&a.toolName!==b2.toolName)return false;if(isCrushedToolResult(b2))return true;if(a.contentType==="tool-result"&&isCcrStoredResult(b2))return true;if(isTruncatedTwin(a,b2))return true;return normText(a)===normText(b2)}function isCompressToolName2(toolName){return toolName==="compress"||toolName==="mcp__bili__compress"}function pairingState(msgs){const opened=new Set;const unopenedResultIds=new Set;for(const m2 of msgs){if(m2.contentType==="tool-call"&&m2.toolCallId)opened.add(m2.toolCallId);else if(m2.contentType==="tool-result"&&m2.toolCallId&&!opened.has(m2.toolCallId))unopenedResultIds.add(m2.toolCallId)}const answered=new Set;const unansweredCallIds=new Set;for(let i=msgs.length-1;i>=0;i--){const m2=msgs[i];if(m2.contentType==="tool-result"&&m2.toolCallId)answered.add(m2.toolCallId);else if(m2.contentType==="tool-call"&&m2.toolCallId&&!answered.has(m2.toolCallId))unansweredCallIds.add(m2.toolCallId)}return{unansweredCallIds,unopenedResultIds}}function egressPairingViolations(entry,exit){const client=pairingState(entry);const egress=pairingState(exit);const out=[];const countUnanswered=(msgs,st2)=>msgs.filter(m2=>m2.contentType==="tool-call"&&m2.toolCallId&&st2.unansweredCallIds.has(m2.toolCallId)&&!isCompressToolName2(m2.toolName)).length;if(countUnanswered(exit,egress)>countUnanswered(entry,client)){exit.forEach((m2,i)=>{if(m2.contentType!=="tool-call"||!m2.toolCallId||!egress.unansweredCallIds.has(m2.toolCallId))return;if(isCompressToolName2(m2.toolName))return;if(client.unansweredCallIds.has(m2.toolCallId))return;out.push({kind:"unpaired-tool-call",index:i,detail:`outbound[${i}] tool-call #${m2.toolCallId}${m2.toolName?` (${m2.toolName})`:""} has no same-id tool-result after it \u2014 upstream rejects half-pairs with a 400 (#4862)`})})}const countUnopened=(msgs,st2)=>msgs.filter(m2=>m2.contentType==="tool-result"&&m2.toolCallId&&st2.unopenedResultIds.has(m2.toolCallId)).length;if(countUnopened(exit,egress)>countUnopened(entry,client)){exit.forEach((m2,i)=>{if(m2.contentType!=="tool-result"||!m2.toolCallId||!egress.unopenedResultIds.has(m2.toolCallId))return;if(client.unopenedResultIds.has(m2.toolCallId))return;out.push({kind:"unpaired-tool-result",index:i,detail:`outbound[${i}] tool-result #${m2.toolCallId} has no same-id tool-call before it \u2014 upstream rejects half-pairs with a 400 (#4862)`})})}return out}function judgeInboundOutbound(entry,exit,opts={}){const maxGap=opts.maxCarrierGap??4;const maxExempt=opts.maxExempt??128;const violations=[];let matched=0;let total=0;const sumIdx=exit.findIndex(isSummaryCarrier);const folded=sumIdx!==-1;const freezeEnd=folded?sumIdx:exit.length;let foldStart=-1;const rts=opts.renderTailStart;const renderLane=typeof rts==="number"&&Number.isFinite(rts)&&rts>=0;let j2=0;if(renderLane){let located=false;for(let i=rts;i<entry.length;i++){const e=entry[i];if(isReasoning(e))continue;total++;const eCarrier=isCarrier(e);let found=-1;let nearTwin=false;let scanned=0;const cap=located?maxGap:Number.POSITIVE_INFINITY;for(let k2=j2;k2<exit.length;k2++){const x=exit[k2];if(isReasoning(x))continue;if(!eCarrier&&isCarrier(x))continue;scanned++;if(scanned>cap)break;if(stableEqual(e,x)){found=k2;break}if(x.role===e.role&&x.contentType===e.contentType&&(!e.toolCallId||!x.toolCallId||x.toolCallId===e.toolCallId))nearTwin=true}if(found<0){violations.push({kind:nearTwin?"mid-history-rewrite":"mid-history-drop",index:i,detail:`tail inbound[${i}] ${fp(e)} absent from outbound`});j2++;continue}if(located){for(let k2=j2;k2<found;k2++){const x=exit[k2];if(!isCarrier(x)&&!isReasoning(x)){violations.push({kind:"mid-insertion",index:i,detail:`unexplained outbound element before tail inbound[${i}]: ${fp(x)}`})}}}matched++;j2=found+1;located=true}foldStart=rts>0?0:-1}else{for(let i=0;i<entry.length;i++){const e=entry[i];if(isReasoning(e))continue;if(folded&&j2>=freezeEnd){foldStart=i;break}total++;const eCarrier=isCarrier(e);let found=-1;let nearTwin=false;let scanned=0;for(let k2=j2;k2<freezeEnd;k2++){const x=exit[k2];if(isReasoning(x))continue;if(!eCarrier&&isCarrier(x))continue;scanned++;if(scanned>maxGap)break;if(stableEqual(e,x)){found=k2;break}if(x.role===e.role&&x.contentType===e.contentType&&(!e.toolCallId||!x.toolCallId||x.toolCallId===e.toolCallId))nearTwin=true}if(found<0){violations.push({kind:nearTwin?"mid-history-rewrite":"mid-history-drop",index:i,detail:`inbound[${i}] ${fp(e)} absent from outbound frozen prefix`});j2++;continue}for(let k2=j2;k2<found;k2++){const x=exit[k2];if(!isCarrier(x)&&!isReasoning(x)){violations.push({kind:"mid-insertion",index:i,detail:`unexplained outbound element before inbound[${i}]: ${fp(x)}`})}}matched++;j2=found+1}if(folded&&sumIdx>matched){for(let k2=matched;k2<sumIdx;k2++){const x=exit[k2];if(!isCarrier(x)&&!isReasoning(x)){violations.push({kind:"carrier-drift",index:-1,detail:`element before fold carrier at outbound[${k2}]: ${fp(x)}`});break}}}}const carrierExempt=exit.filter(isCarrier).length;const reasoningExempt=exit.filter(isReasoning).length;const crushExempt=exit.filter(isCrushedToolResult).length;const ccrExempt=exit.filter(isCcrStoredResult).length;const truncateExempt=exit.filter(isTruncationExit).length;const exemptTotal=carrierExempt+reasoningExempt+crushExempt+ccrExempt+truncateExempt;if(exemptTotal>maxExempt){violations.push({kind:"exemption-overflow",index:-1,detail:`named-exemption volume ${exemptTotal} exceeds cap ${maxExempt} (carrier=${carrierExempt} reasoning=${reasoningExempt} crush=${crushExempt} ccr=${ccrExempt} truncate=${truncateExempt})`})}violations.push(...egressPairingViolations(entry,exit));return{ok:violations.length===0,folded,...folded&&foldStart>=0?{foldStart}:{},matched,total,violations,exempt:{carrier:carrierExempt,reasoning:reasoningExempt,crush:crushExempt,ccr:ccrExempt,truncate:truncateExempt},...renderLane?{renderLane:true}:{}}}function parseExitCores(body,protocol,parsed){if(!body||!protocol)return null;let value=parsed;if(value===void 0){const text2=typeof body==="string"?body:body.toString("utf8");try{value=JSON.parse(text2)}catch{return null}}try{switch(protocol){case"openai":return openaiToCore(value).msgs;case"anthropic":return anthropicToCore(value).msgs;case"responses":return responsesToCore(value).msgs;case"google":return googleToCore(value).msgs;default:return null}}catch{return null}}var armedOverride=null;var sink=null;var fault=null;function defaultSink(sessionId,lane){return v2=>{const where=`[${sessionId??"unknown"}] [invariant-judge${v2.lane?`/${v2.lane}`:``}]`;if(!v2.ok){const head=v2.violations[0];const inv=head.kind==="unpaired-tool-call"||head.kind==="unpaired-tool-result"?3:v2.folded?2:1;log("warn",`${where} I${inv} violation: ${head.kind} @${head.index} \u2014 ${head.detail} (${v2.violations.length} finding(s), matched ${v2.matched}/${v2.total}${v2.exempt?`, exempt carrier=${v2.exempt.carrier} reasoning=${v2.exempt.reasoning} crush=${v2.exempt.crush} ccr=${v2.exempt.ccr} truncate=${v2.exempt.truncate}`:``})`)}else{log("debug",`${where} clean ${v2.folded?"fold":"growth"} verdict: matched ${v2.matched}/${v2.total}${v2.exempt?`, exempt carrier=${v2.exempt.carrier} reasoning=${v2.exempt.reasoning} crush=${v2.exempt.crush} ccr=${v2.exempt.ccr} truncate=${v2.exempt.truncate}`:``}`)}}}function armed(){if(armedOverride!==null)return armedOverride;return invariantJudgeEnabled()}function maybeRunInvariantJudge(input){if(!armed())return;try{const entry=input.originalMessages??[];const exitCores0=parseExitCores(input.body,input.protocol,input.parsed);if(!exitCores0)return;const exitCores=fault?fault([...exitCores0]):exitCores0;const v2=judgeInboundOutbound(entry,exitCores,{renderTailStart:input.renderTailStart});(sink??defaultSink(input.sessionId,"main"))({...v2,lane:"main"})}catch{}}function maybeJudgeContinuity(prev,body,protocol,sessionId){if(!armed()||!prev)return;try{const entry=parseExitCores(prev,protocol);const exitCores0=parseExitCores(body,protocol);if(!entry||!exitCores0)return;const exitCores=fault?fault([...exitCores0]):exitCores0;const v2=judgeInboundOutbound(entry,exitCores);(sink??defaultSink(sessionId,"loop"))({...v2,lane:"loop"})}catch{}}import{createHash as createHash27}from"crypto";import{readFile as readFile5}from"fs/promises";init_knobs();init_proxy_tool_result();init_logger();var RESCALE_TRIGGER_BYTES=100*1024;var KEEP_RATIO=.8;var JPEG_QUALITY=80;var ENCODE_CACHE_MAX=512;var MIME_TO_JIMP={"image/png":"image/png","image/jpeg":"image/jpeg","image/jpg":"image/jpeg","image/bmp":"image/bmp"};function normalizeMime(mediaType){if(typeof mediaType!=="string")return void 0;return MIME_TO_JIMP[mediaType.trim().toLowerCase()]}function b64Bytes2(b64){const pad=b64.endsWith("==")?2:b64.endsWith("=")?1:0;return Math.max(0,Math.floor(b64.length/4)*3-pad)}var encodeCache=new Map;var jimpLoad;function loadJimp(){if(jimpLoad===void 0){jimpLoad=import("jimp").catch(err2=>{log("warn",`[image-rescale] jimp unavailable (${err2 instanceof Error?err2.message:String(err2)}) \u2014 image rescaling disabled for this process (originals pass through)`);return null})}return jimpLoad}async function doRescale(mime,b64,origBytes,maxDim,force=false){try{const mod=await loadJimp();if(mod===null)return null;const img=await mod.Jimp.read(Buffer.from(b64,"base64"));const ow=img.width;const oh=img.height;const scale=Math.min(1,maxDim/Math.max(ow,oh));if(scale>=1&&(!force||origBytes<=RESCALE_TRIGGER_BYTES))return null;const tw=Math.max(1,Math.round(ow*scale));const th=Math.max(1,Math.round(oh*scale));if(tw!==ow||th!==oh)await img.resize({w:tw,h:th});const out=mime==="image/jpeg"?await img.getBuffer("image/jpeg",{quality:JPEG_QUALITY}):await img.getBuffer(mime);if(force?out.length>=origBytes:out.length>=origBytes*KEEP_RATIO)return null;return{base64:out.toString("base64"),width:tw,height:th,origWidth:ow,origHeight:oh,origBytes,newBytes:out.length,mime,fresh:true}}catch{return null}}async function rescaleImage(mediaType,b64,maxDim){const mime=normalizeMime(mediaType);if(!mime||typeof b64!=="string"||b64.length===0)return null;const origBytes=b64Bytes2(b64);const dims=decodeImageDims(b64);const gated=dims!==void 0&&Math.max(dims.w,dims.h)>maxDim||origBytes>RESCALE_TRIGGER_BYTES;if(!gated)return null;const hash=createHash27("sha256").update(b64,"utf8").digest("hex");let pending=encodeCache.get(hash);const cacheHit=pending!==void 0;if(!pending){pending=doRescale(mime,b64,origBytes,maxDim);encodeCache.set(hash,pending);while(encodeCache.size>ENCODE_CACHE_MAX){const oldest=encodeCache.keys().next().value;if(oldest===void 0||oldest===hash)break;encodeCache.delete(oldest)}}const result=await pending;if(result!==null&&cacheHit)return{...result,fresh:false};return result}async function shedDownscaleImage(mediaType,b64,maxDim){const mime=normalizeMime(mediaType);if(!mime||typeof b64!=="string"||b64.length===0||!Number.isFinite(maxDim)||maxDim<=0)return null;const dim=Math.floor(maxDim);const hash=createHash27("sha256").update(`${dim}:${b64}`,"utf8").digest("hex");let pending=encodeCache.get(hash);if(!pending){pending=doRescale(mime,b64,b64Bytes2(b64),dim,true);encodeCache.set(hash,pending);while(encodeCache.size>ENCODE_CACHE_MAX){const oldest=encodeCache.keys().next().value;if(oldest===void 0||oldest===hash)break;encodeCache.delete(oldest)}}const r=await pending;return r===null?null:r.base64}function formatKb(bytes){return Math.round(bytes/1024)}function buildRescaleNote(opts){const head=`[bili] \u672C\u56FE\u5DF2\u964D\u91C7\u6837:\u5F53\u524D ${opts.width}\xD7${opts.height} / ${opts.kb}KB;\u539F\u56FE ${opts.origWidth}\xD7${opts.origHeight} / ${opts.origKb}KB`;if(opts.ref!==void 0&&opts.toolArmed){return`${head}(\u7EA6 ${opts.ratio.toFixed(1)} \u500D)\u3002\u9700\u8981\u539F\u5206\u8FA8\u7387\u7EC6\u8282(\u5C0F\u5B57\u3001\u989C\u8272\u3001\u5BF9\u9F50)\u65F6,\u8C03\u7528 acp_read_original_image("${opts.ref}") \u8BFB\u53D6\u539F\u56FE\u3002\u539F\u56FE\u8F83\u5927,\u6309\u9700\u8BFB\u53D6\u3002`}return`${head}\u3002`}function noteFor(ctx,ref,r){return buildRescaleNote({ref,toolArmed:ctx.toolArmed,width:r.width,height:r.height,kb:formatKb(r.newBytes),origWidth:r.origWidth,origHeight:r.origHeight,origKb:formatKb(r.origBytes),ratio:r.newBytes>0?r.origBytes/r.newBytes:0})}function refFor(session,id){if(typeof id!=="string"||id.length===0)return void 0;const ref=session.state.messageRefs.byRaw[id];return typeof ref==="string"&&ref.length>0?ref:void 0}function logCompression(ctx,ref,r){if(!r.fresh)return;ctx.log("info",`[${ctx.sessionId}] [image-rescale] ${r.mime}${ref!==void 0?` ${ref}`:""} ${r.origWidth}x${r.origHeight}/${formatKb(r.origBytes)}KB -> ${r.width}x${r.height}/${formatKb(r.newBytes)}KB`)}function asPart(v2){return typeof v2==="object"&&v2!==null&&!Array.isArray(v2)?v2:void 0}function matchesOriginalImageReceipt(b64,parts){const hashes=new Set;for(const part of parts){const p2=asPart(part);if(typeof p2?.text!=="string")continue;for(const line of p2.text.split(/\r?\n/)){const match=/^Billion original image receipt v1 sha256=([a-f0-9]{64})$/.exec(line);if(match)hashes.add(match[1])}}if(hashes.size===0)return false;return hashes.has(createHash27("sha256").update(Buffer.from(b64,"base64")).digest("hex"))}async function rescaleAnthropic(m2,ctx){const block=asPart(m2.rawAnthropicBlock);if(!block)return void 0;if(block.type==="image"){const src=asPart(block.source);if(!src||src.type!=="base64"||typeof src.data!=="string")return void 0;const r=await rescaleImage(typeof src.media_type==="string"?src.media_type:"image/png",src.data,ctx.maxDim);if(!r)return void 0;const ref=refFor(ctx.session,m2.id);logCompression(ctx,ref,r);const copy={...m2,rawAnthropicBlock:{...block,source:{...src,data:r.base64}}};const noteMsg={id:`acp_imgnote_${m2.id}`,role:m2.role,contentType:"text",text:noteFor(ctx,ref,r)};return[copy,noteMsg]}if(block.type==="tool_result"&&Array.isArray(block.content)){const content=block.content;const changed=[];let any=false;const ref=refFor(ctx.session,m2.id);for(const part of content){const p2=asPart(part);if(p2?.type==="image"){const src=asPart(p2.source);if(src?.type==="base64"&&typeof src.data==="string"&&!matchesOriginalImageReceipt(src.data,content)){const r=await rescaleImage(typeof src.media_type==="string"?src.media_type:"image/png",src.data,ctx.maxDim);if(r){any=true;logCompression(ctx,ref,r);changed.push({...p2,source:{...src,data:r.base64}});changed.push({type:"text",text:noteFor(ctx,ref,r)});continue}}}changed.push(part)}if(!any)return void 0;return[{...m2,rawAnthropicBlock:{...block,content:changed}}]}return void 0}async function rescaleOpenaiParts(m2,ctx){const ref=refFor(ctx.session,m2.id);if(Array.isArray(m2.rawOpenaiContentParts)){const parts=m2.rawOpenaiContentParts;const changed=[];let any=false;for(const part of parts){const p2=asPart(part);if(p2?.type==="image_url"){const url=asPart(p2.image_url)?.url;if(typeof url==="string"&&url.startsWith("data:")){const d=parseDataUrl(url);if(d){const r=await rescaleImage(d.mediaType,d.base64,ctx.maxDim);if(r){any=true;logCompression(ctx,ref,r);changed.push({...p2,image_url:{...asPart(p2.image_url)??{},url:`data:${d.mediaType};base64,${r.base64}`}});changed.push({type:"text",text:noteFor(ctx,ref,r)});continue}}}}changed.push(part)}if(!any)return void 0;return[{...m2,rawOpenaiContentParts:changed}]}if(m2.rawOpenaiContent!==void 0){const p2=asPart(m2.rawOpenaiContent);if(!p2||p2.type!=="image_url")return void 0;const url=asPart(p2.image_url)?.url;if(typeof url!=="string"||!url.startsWith("data:"))return void 0;const d=parseDataUrl(url);if(!d)return void 0;const r=await rescaleImage(d.mediaType,d.base64,ctx.maxDim);if(!r)return void 0;logCompression(ctx,ref,r);const copy={...m2,rawOpenaiContentParts:[{...p2,image_url:{...asPart(p2.image_url)??{},url:`data:${d.mediaType};base64,${r.base64}`}},{type:"text",text:noteFor(ctx,ref,r)}]};delete copy.rawOpenaiContent;delete copy.imageBase64;delete copy.imageMediaType;return[copy]}return void 0}async function rescaleGoogle(m2,ctx){if(!Array.isArray(m2.rawGoogleParts))return void 0;const parts=m2.rawGoogleParts;const changed=[];let any=false;const notes=[];const ref=refFor(ctx.session,m2.id);for(const part of parts){const p2=asPart(part);const inline=p2?asPart(p2.inlineData):void 0;if(inline&&typeof inline.data==="string"&&!matchesOriginalImageReceipt(inline.data,parts)){const r=await rescaleImage(typeof inline.mimeType==="string"?inline.mimeType:"image/png",inline.data,ctx.maxDim);if(r){any=true;logCompression(ctx,ref,r);changed.push({...p2,inlineData:{...inline,data:r.base64}});notes.push(noteFor(ctx,ref,r));continue}}changed.push(part)}if(!any)return void 0;const text2=(m2.text??"")+((m2.text??"").length>0?"\n\n":"")+notes.join("\n");return[{...m2,rawGoogleParts:changed,text:text2}]}async function rescaleResponsesItem(m2,ctx){const item=asPart(m2.rawResponsesItem);if(!item)return void 0;const toolOutput=item.type==="function_call_output"||item.type==="custom_tool_call_output";const partsKey=toolOutput?"output":item.type==="message"?"content":void 0;if(partsKey===void 0||!Array.isArray(item[partsKey]))return void 0;const content=item[partsKey];const changed=[];let first;const ref=refFor(ctx.session,m2.id);for(const part of content){const p2=asPart(part);if(p2?.type==="input_image"&&typeof p2.image_url==="string"&&p2.image_url.startsWith("data:")){const d=parseDataUrl(p2.image_url);if(d&&!(toolOutput&&matchesOriginalImageReceipt(d.base64,content))){const r=await rescaleImage(d.mediaType,d.base64,ctx.maxDim);if(r){if(!first)first=r;logCompression(ctx,ref,r);changed.push({...p2,image_url:`data:${d.mediaType};base64,${r.base64}`});continue}}}changed.push(part)}if(!first)return void 0;const copy={...m2,rawResponsesItem:{...item,[partsKey]:changed}};if(toolOutput)return[{...copy,text:`${m2.text??""}
|
|
1066
|
+
${hoisted}`:hoisted}return defaultCountTokens(sysText)+defaultCountTokens(JSON.stringify(protocol==="responses"?modelVisibleTools(parsed.tools):parsed.tools??[]))+(protocol==="responses"?countLoadedToolTokens(parsed):0)}function clampOutputBudget(requested,inputEstimate,nativeWindow,knownOutputCeiling){const ceilingBound=typeof knownOutputCeiling==="number"&&Number.isFinite(knownOutputCeiling)?knownOutputCeiling:Number.POSITIVE_INFINITY;const clampFor=est=>{const margin=Math.max(OUTPUT_CLAMP_MIN_MARGIN,Math.ceil(est*OUTPUT_CLAMP_MARGIN_PCT));const cap=Math.min(Math.floor(nativeWindow-est-margin),ceilingBound);if(cap<OUTPUT_CLAMP_FLOOR||cap>=requested)return void 0;const floorOut=Math.min(OUTPUT_CLAMP_MIN_OUTPUT,Math.floor(nativeWindow-est),ceilingBound);const clamped=Math.max(cap,floorOut);if(clamped>=requested)return void 0;return clamped};const safe=clampFor(Math.ceil(inputEstimate*OUTPUT_CLAMP_ESTIMATE_SAFETY));if(safe!==void 0)return safe;return clampFor(inputEstimate)}function dshLedgerFloorTokens(metadata){const bytes=metadata?.["dshCompactionRefusedBytes"];if(typeof bytes!=="number"||!Number.isFinite(bytes)||bytes<=0)return 0;return Math.ceil(bytes/4)}function emergencyNudge(nudge,escalationPct=EMERGENCY_NUDGE_ESCALATION_PCT,minCompressRange=0){if(!nudge||nudge.shouldInject)return false;if(nudge.contextUsage<escalationPct)return false;if(!nudge.compressibleRanges.some(r=>minCompressRange<=0||(r.chars??r.tokens*4)>=minCompressRange))return false;const b2=nudge.breakdown;const minBenefit=b2?.minPressureBenefit;return!(typeof minBenefit==="number"&&Number.isFinite(minBenefit)&&minBenefit>0&&(b2.maxPending??0)<minBenefit)}function emergencyNudgeArmed(session,nudge,minCompressRange,tokenCount,growthStep){if(!emergencyNudge(nudge,void 0,minCompressRange))return false;const now=Date.now();const key2=reductionKeyOf(session);const raw=session.metadata["emergencyNudgeGate"];if(raw===null||typeof raw!=="object"){session.metadata["emergencyNudgeGate"]={at:now,tokens:tokenCount,reductionKey:key2};return true}const g2=raw;const prevAt=typeof g2["at"]==="number"?g2["at"]:NaN;const prevTokens=typeof g2["tokens"]==="number"?g2["tokens"]:NaN;const prevKey=typeof g2["reductionKey"]==="string"?g2["reductionKey"]:void 0;const step=typeof growthStep==="number"&&Number.isFinite(growthStep)&&growthStep>0?growthStep:5e4;let arm=false;if(!Number.isFinite(prevAt)||!Number.isFinite(prevTokens)||prevKey===void 0){arm=true}else if(prevKey!==key2){arm=true}else if(tokenCount-prevTokens>=step){arm=true}else if(now-prevAt>=SELF_HEAL_SUPPRESS_CAP_MS){arm=true}if(arm)session.metadata["emergencyNudgeGate"]={at:now,tokens:tokenCount,reductionKey:key2};return arm}function clampOutgoingOutput(rebuilt,field,ctx,sessionId,log2,onClamped){const raw=readOutputBudget(rebuilt,field);if(typeof raw!=="number")return;const loadedToolTokens=field==="max_output_tokens"?countLoadedToolTokens(rebuilt):0;const inputEstimate=estimateInputTokens(ctx.processedMessages,ctx.systemText,ctx.tools,ctx.lastInputTokens,ctx.lastInputTokensSource,ctx.kFactor,ctx.kOrigin,ctx.origin,loadedToolTokens,ctx.imageTokens);const ledgerFloor=typeof ctx.ledgerFloorTokens==="number"&&Number.isFinite(ctx.ledgerFloorTokens)?Math.max(0,Math.floor(ctx.ledgerFloorTokens)):0;const viewAtEnforcedTarget=typeof ctx.headroomWindow==="number"&&Number.isFinite(ctx.headroomWindow)&&ctx.headroomWindow>0&&inputEstimate>=ctx.headroomWindow;const giantRequestedBudget=ctx.nativeWindow>0&&raw>=OUTPUT_LEDGER_FLOOR_GIANT_REQUEST_PCT*ctx.nativeWindow;const planningInput=viewAtEnforcedTarget||giantRequestedBudget?Math.max(inputEstimate,ledgerFloor):inputEstimate;const capped=clampOutputBudget(raw,planningInput,ctx.nativeWindow,ctx.knownOutputCeiling);if(capped!==void 0){writeOutputBudget(rebuilt,field,capped);const overTarget=ctx.headroomWindow!==void 0&&ctx.headroomWindow<ctx.nativeWindow&&planningInput>=ctx.headroomWindow;log2("info",`[${sessionId}] output budget clamped ${raw} -> ${capped} (input~${inputEstimate}${ledgerFloor>inputEstimate?`, planning floor ${ledgerFloor} from the refused dsh compaction replay (#2490)`:""}, window=${ctx.nativeWindow}); prevents input+output overflow (#453)${overTarget?`; input already exceeds the headroom-adjusted target ~${ctx.headroomWindow} that nudge/preflight enforce \u2014 only compression can recover it, this clamp guarantees native-window fit only (#2096)`:""}`);onClamped?.({raw,capped,window:ctx.nativeWindow,planningInput,ledgerFloor})}}init_util();init_logger();var MAX_SESSIONS_TRACKED=8;var MAX_SESSIONS_REMEMBERED=32;var MAX_ABLATION_ENTRIES=64;var entries=new Map;function keyOf(origin,model){return`${origin}\0${model??""}`}function evictStaleEntries(){if(entries.size<=MAX_ABLATION_ENTRIES)return;const oldestFirst=[...entries.values()].sort((a,b2)=>a.lastAt-b2.lastAt);for(const rec of oldestFirst){if(entries.size<=MAX_ABLATION_ENTRIES)break;entries.delete(keyOf(rec.origin,rec.model))}}function pckKeyAbated(egressUrl,fallbackOrigin,modelId){const origin=normalizeUpstreamOrigin(egressUrl)??normalizeUpstreamOrigin(fallbackOrigin);if(!origin)return false;const model=typeof modelId==="string"&&modelId!==""?modelId:void 0;return entries.has(keyOf(origin,model))}function recordPckAblation(facts){const origin=normalizeUpstreamOrigin(facts.origin)??facts.origin.trim();if(!origin)return;const model=typeof facts.model==="string"&&facts.model!==""?facts.model:void 0;const now=Date.now();const k2=keyOf(origin,model);let e=entries.get(k2);const where=`${origin}${model?` (model ${model})`:""}`;if(!e){e={origin,model,firstAt:now,lastAt:now,confirmations:1,sessions:[],sessionCounts:new Map};entries.set(k2,e);evictStaleEntries();const snippet=facts.errSnippet.replace(/\s+/g," ").slice(0,200);log("warn",`[pck] ${where} rejected prompt_cache_key \u2014 A/B confirmed (with key: HTTP ${facts.statusWithKey}; identical request without the key was accepted). bili now withholds the cache-routing key from this destination until proxy restart (#2645 probe-and-remember). Affected session(s): ${facts.sessionId}. Upstream error: ${snippet||"(empty body)"}. CAVEAT: if this destination is a relay/account pool keyed by prompt_cache_key, its prefix-cache affinity for these conversations may degrade for the rest of this process's lifetime (a transient unrelated 400 can be misattributed); restart resets.`)}else{e.confirmations+=1;e.lastAt=now;log("debug",`[pck] ${where} ablation reconfirmed (${e.confirmations}\xD7 total, session ${facts.sessionId}, #2645)`)}if(facts.sessionId){e.sessionCounts.set(facts.sessionId,(e.sessionCounts.get(facts.sessionId)??0)+1);while(e.sessionCounts.size>MAX_SESSIONS_REMEMBERED){let dropKey;let dropCount=Infinity;for(const[sid,n]of e.sessionCounts)if(n<dropCount){dropCount=n;dropKey=sid}if(dropKey===void 0)break;e.sessionCounts.delete(dropKey)}e.sessions=[...e.sessionCounts.entries()].sort((a,b2)=>b2[1]-a[1]).map(([s3])=>s3).slice(0,MAX_SESSIONS_TRACKED)}}function pckAblations(){return[...entries.values()].sort((a,b2)=>b2.lastAt-a.lastAt).map(({sessionCounts:_sessionCounts,...rest})=>rest)}init_logger();init_log_mask();init_knobs();function bodyDumpEnabled2(){return bodyDumpEnabled()}var dumpFailCount=0;var lastDumpFailLog=0;function logDumpFailure(where,err2){dumpFailCount++;const now=Date.now();if(dumpFailCount===1||now-lastDumpFailLog>=6e4){lastDumpFailLog=now;const msg=err2 instanceof Error?err2.message:String(err2);log("warn",`[dump] ${where} failed (total ${dumpFailCount}x): ${msg}`)}}var unrecognizedPathCounts=new Map;function logUnrecognizedPath(log2,url){const key2=maskUrlsInText(url.split("?")[0]);const n=(unrecognizedPathCounts.get(key2)??0)+1;unrecognizedPathCounts.set(key2,n);if(n<=3){log2("warn",`unrecognized path ${key2} \u2014 not a known protocol (/chat/completions, /llm_raw_chat, /v1/messages, /responses, /responses/compact); forwarding unchanged`)}else if(n===4){log2("info",`unrecognized path ${key2}: forwarding unchanged; further occurrences suppressed`)}}function getUnrecognizedPathStats(){const paths={};let total=0;for(const[path53,n]of unrecognizedPathCounts){paths[path53]=n;total+=n}return{total,paths}}function isModelDiscoveryPath(path53){return path53.replace(/\/+$/,"").endsWith("/models")}function isV1InternalControlPlanePath(path53){const p2=path53.split("?",2)[0];return/\/v1internal:(?!streamGenerateContent$|generateContent$|countTokens$)/.test(p2)}init_turn_separator();init_dist();init_knobs();init_dist();init_billing();init_dist();init_logger();init_knobs();var RENDER_TAG_RE=/\n?\x3cacp\s[^>]*\x3e[\s\S]*?\x3c\/acp\x3e/g;var CHAIN_TAG_PREFIX="<bili-chain ";var SUMMARY_MARKER="[Compressed conversation section]";var CRUSH_KEY2="__acp_crush";function normText(m2){return normalizeEchoArtifacts((m2.text??"").replace(RENDER_TAG_RE,"")).trim()}function isReasoning(m2){return m2.contentType==="reasoning"}function isCarrier(m2){if(m2.summaryOfBlockId!==void 0)return true;const t=m2.text??"";return t.startsWith(CHAIN_TAG_PREFIX)||t.includes(SUMMARY_MARKER)}function isSummaryCarrier(m2){if(m2.summaryOfBlockId!==void 0)return true;const t=m2.text??"";return t.includes(SUMMARY_MARKER)||m2.id.startsWith("acp_summary")}function isCrushedToolResult(m2){if(m2.contentType!=="tool-result")return false;const t=(m2.text??"").trim();if(!t.startsWith("{"))return false;try{const o=JSON.parse(t);return!!o&&typeof o==="object"&&Object.hasOwn(o,CRUSH_KEY2)}catch{return false}}function isCcrStoredResult(m2){return m2.contentType==="tool-result"&&parseStoredPlaceholder(m2.text??"")!==null}var TRUNCATION_LINE_RE=/\n\.\.\.\[truncated for context space\][^\n]*\n/;function isTruncationExit(m2){return TRUNCATION_LINE_RE.test(m2.text??"")}function isTruncatedTwin(a,b2){const bt2=b2.text??"";const m2=TRUNCATION_LINE_RE.exec(bt2);if(!m2)return false;const at2=a.text??"";if(!at2||at2.length<=bt2.length)return false;const strip=s3=>s3.replace(RENDER_TAG_RE,"").trim();const pre=strip(bt2.slice(0,m2.index));const post=strip(bt2.slice(m2.index+m2[0].length));const na=strip(at2);return pre.length>0&&post.length>0&&na.startsWith(pre)&&na.endsWith(post)}function fp(m2){const id=m2.toolCallId?`#${m2.toolCallId}`:"";const name=m2.contentType==="tool-call"&&m2.toolName?`:${m2.toolName}`:"";const t=normText(m2).replace(/\s+/g," ").trim().slice(0,80);return`${m2.role}/${m2.contentType}${name}${id}|${t}`}function stableEqual(a,b2){if(a.role!==b2.role||a.contentType!==b2.contentType)return false;if(a.contentType==="tool-call"&&a.toolName&&b2.toolName&&a.toolName!==b2.toolName)return false;if(isCrushedToolResult(b2))return true;if(a.contentType==="tool-result"&&isCcrStoredResult(b2))return true;if(isTruncatedTwin(a,b2))return true;return normText(a)===normText(b2)}function isCompressToolName2(toolName){return toolName==="compress"||toolName==="mcp__bili__compress"}function pairingState(msgs){const opened=new Set;const unopenedResultIds=new Set;for(const m2 of msgs){if(m2.contentType==="tool-call"&&m2.toolCallId)opened.add(m2.toolCallId);else if(m2.contentType==="tool-result"&&m2.toolCallId&&!opened.has(m2.toolCallId))unopenedResultIds.add(m2.toolCallId)}const answered=new Set;const unansweredCallIds=new Set;for(let i=msgs.length-1;i>=0;i--){const m2=msgs[i];if(m2.contentType==="tool-result"&&m2.toolCallId)answered.add(m2.toolCallId);else if(m2.contentType==="tool-call"&&m2.toolCallId&&!answered.has(m2.toolCallId))unansweredCallIds.add(m2.toolCallId)}return{unansweredCallIds,unopenedResultIds}}function egressPairingViolations(entry,exit){const client=pairingState(entry);const egress=pairingState(exit);const out=[];const countUnanswered=(msgs,st2)=>msgs.filter(m2=>m2.contentType==="tool-call"&&m2.toolCallId&&st2.unansweredCallIds.has(m2.toolCallId)&&!isCompressToolName2(m2.toolName)).length;if(countUnanswered(exit,egress)>countUnanswered(entry,client)){exit.forEach((m2,i)=>{if(m2.contentType!=="tool-call"||!m2.toolCallId||!egress.unansweredCallIds.has(m2.toolCallId))return;if(isCompressToolName2(m2.toolName))return;if(client.unansweredCallIds.has(m2.toolCallId))return;out.push({kind:"unpaired-tool-call",index:i,detail:`outbound[${i}] tool-call #${m2.toolCallId}${m2.toolName?` (${m2.toolName})`:""} has no same-id tool-result after it \u2014 upstream rejects half-pairs with a 400 (#4862)`})})}const countUnopened=(msgs,st2)=>msgs.filter(m2=>m2.contentType==="tool-result"&&m2.toolCallId&&st2.unopenedResultIds.has(m2.toolCallId)).length;if(countUnopened(exit,egress)>countUnopened(entry,client)){exit.forEach((m2,i)=>{if(m2.contentType!=="tool-result"||!m2.toolCallId||!egress.unopenedResultIds.has(m2.toolCallId))return;if(client.unopenedResultIds.has(m2.toolCallId))return;out.push({kind:"unpaired-tool-result",index:i,detail:`outbound[${i}] tool-result #${m2.toolCallId} has no same-id tool-call before it \u2014 upstream rejects half-pairs with a 400 (#4862)`})})}return out}function judgeInboundOutbound(entry,exit,opts={}){const maxGap=opts.maxCarrierGap??4;const maxExempt=opts.maxExempt??128;const violations=[];let matched=0;let total=0;const sumIdx=exit.findIndex(isSummaryCarrier);const folded=sumIdx!==-1;const freezeEnd=folded?sumIdx:exit.length;let foldStart=-1;const rts=opts.renderTailStart;const renderLane=typeof rts==="number"&&Number.isFinite(rts)&&rts>=0;let j2=0;if(renderLane){let located=false;for(let i=rts;i<entry.length;i++){const e=entry[i];if(isReasoning(e))continue;total++;const eCarrier=isCarrier(e);let found=-1;let nearTwin=false;let scanned=0;const cap=located?maxGap:Number.POSITIVE_INFINITY;for(let k2=j2;k2<exit.length;k2++){const x=exit[k2];if(isReasoning(x))continue;if(!eCarrier&&isCarrier(x))continue;scanned++;if(scanned>cap)break;if(stableEqual(e,x)){found=k2;break}if(x.role===e.role&&x.contentType===e.contentType&&(!e.toolCallId||!x.toolCallId||x.toolCallId===e.toolCallId))nearTwin=true}if(found<0){violations.push({kind:nearTwin?"mid-history-rewrite":"mid-history-drop",index:i,detail:`tail inbound[${i}] ${fp(e)} absent from outbound`});j2++;continue}if(located){for(let k2=j2;k2<found;k2++){const x=exit[k2];if(!isCarrier(x)&&!isReasoning(x)){violations.push({kind:"mid-insertion",index:i,detail:`unexplained outbound element before tail inbound[${i}]: ${fp(x)}`})}}}matched++;j2=found+1;located=true}foldStart=rts>0?0:-1}else{for(let i=0;i<entry.length;i++){const e=entry[i];if(isReasoning(e))continue;if(folded&&j2>=freezeEnd){foldStart=i;break}total++;const eCarrier=isCarrier(e);let found=-1;let nearTwin=false;let scanned=0;for(let k2=j2;k2<freezeEnd;k2++){const x=exit[k2];if(isReasoning(x))continue;if(!eCarrier&&isCarrier(x))continue;scanned++;if(scanned>maxGap)break;if(stableEqual(e,x)){found=k2;break}if(x.role===e.role&&x.contentType===e.contentType&&(!e.toolCallId||!x.toolCallId||x.toolCallId===e.toolCallId))nearTwin=true}if(found<0){violations.push({kind:nearTwin?"mid-history-rewrite":"mid-history-drop",index:i,detail:`inbound[${i}] ${fp(e)} absent from outbound frozen prefix`});j2++;continue}for(let k2=j2;k2<found;k2++){const x=exit[k2];if(!isCarrier(x)&&!isReasoning(x)){violations.push({kind:"mid-insertion",index:i,detail:`unexplained outbound element before inbound[${i}]: ${fp(x)}`})}}matched++;j2=found+1}if(folded&&sumIdx>matched){for(let k2=matched;k2<sumIdx;k2++){const x=exit[k2];if(!isCarrier(x)&&!isReasoning(x)){violations.push({kind:"carrier-drift",index:-1,detail:`element before fold carrier at outbound[${k2}]: ${fp(x)}`});break}}}}const carrierExempt=exit.filter(isCarrier).length;const reasoningExempt=exit.filter(isReasoning).length;const crushExempt=exit.filter(isCrushedToolResult).length;const ccrExempt=exit.filter(isCcrStoredResult).length;const truncateExempt=exit.filter(isTruncationExit).length;const exemptTotal=carrierExempt+reasoningExempt+crushExempt+ccrExempt+truncateExempt;if(exemptTotal>maxExempt){violations.push({kind:"exemption-overflow",index:-1,detail:`named-exemption volume ${exemptTotal} exceeds cap ${maxExempt} (carrier=${carrierExempt} reasoning=${reasoningExempt} crush=${crushExempt} ccr=${ccrExempt} truncate=${truncateExempt})`})}violations.push(...egressPairingViolations(entry,exit));return{ok:violations.length===0,folded,...folded&&foldStart>=0?{foldStart}:{},matched,total,violations,exempt:{carrier:carrierExempt,reasoning:reasoningExempt,crush:crushExempt,ccr:ccrExempt,truncate:truncateExempt},...renderLane?{renderLane:true}:{}}}function parseExitCores(body,protocol,parsed){if(!body||!protocol)return null;let value=parsed;if(value===void 0){const text2=typeof body==="string"?body:body.toString("utf8");try{value=JSON.parse(text2)}catch{return null}}try{switch(protocol){case"openai":return openaiToCore(value).msgs;case"anthropic":return anthropicToCore(value).msgs;case"responses":return responsesToCore(value).msgs;case"google":return googleToCore(value).msgs;default:return null}}catch{return null}}var armedOverride=null;var sink=null;var fault=null;function defaultSink(sessionId,lane){return v2=>{const where=`[${sessionId??"unknown"}] [invariant-judge${v2.lane?`/${v2.lane}`:``}]`;if(!v2.ok){const head=v2.violations[0];const inv=head.kind==="unpaired-tool-call"||head.kind==="unpaired-tool-result"?3:v2.folded?2:1;log("warn",`${where} I${inv} violation: ${head.kind} @${head.index} \u2014 ${head.detail} (${v2.violations.length} finding(s), matched ${v2.matched}/${v2.total}${v2.exempt?`, exempt carrier=${v2.exempt.carrier} reasoning=${v2.exempt.reasoning} crush=${v2.exempt.crush} ccr=${v2.exempt.ccr} truncate=${v2.exempt.truncate}`:``})`)}else{log("debug",`${where} clean ${v2.folded?"fold":"growth"} verdict: matched ${v2.matched}/${v2.total}${v2.exempt?`, exempt carrier=${v2.exempt.carrier} reasoning=${v2.exempt.reasoning} crush=${v2.exempt.crush} ccr=${v2.exempt.ccr} truncate=${v2.exempt.truncate}`:``}`)}}}function armed2(){if(armedOverride!==null)return armedOverride;return invariantJudgeEnabled()}function maybeRunInvariantJudge(input){if(!armed2())return;try{const entry=input.originalMessages??[];const exitCores0=parseExitCores(input.body,input.protocol,input.parsed);if(!exitCores0)return;const exitCores=fault?fault([...exitCores0]):exitCores0;const v2=judgeInboundOutbound(entry,exitCores,{renderTailStart:input.renderTailStart});(sink??defaultSink(input.sessionId,"main"))({...v2,lane:"main"})}catch{}}function maybeJudgeContinuity(prev,body,protocol,sessionId){if(!armed2()||!prev)return;try{const entry=parseExitCores(prev,protocol);const exitCores0=parseExitCores(body,protocol);if(!entry||!exitCores0)return;const exitCores=fault?fault([...exitCores0]):exitCores0;const v2=judgeInboundOutbound(entry,exitCores);(sink??defaultSink(sessionId,"loop"))({...v2,lane:"loop"})}catch{}}import{createHash as createHash27}from"crypto";import{readFile as readFile5}from"fs/promises";init_knobs();init_proxy_tool_result();init_logger();var RESCALE_TRIGGER_BYTES=100*1024;var KEEP_RATIO=.8;var JPEG_QUALITY=80;var ENCODE_CACHE_MAX=512;var MIME_TO_JIMP={"image/png":"image/png","image/jpeg":"image/jpeg","image/jpg":"image/jpeg","image/bmp":"image/bmp"};function normalizeMime(mediaType){if(typeof mediaType!=="string")return void 0;return MIME_TO_JIMP[mediaType.trim().toLowerCase()]}function b64Bytes2(b64){const pad=b64.endsWith("==")?2:b64.endsWith("=")?1:0;return Math.max(0,Math.floor(b64.length/4)*3-pad)}var encodeCache=new Map;var jimpLoad;function loadJimp(){if(jimpLoad===void 0){jimpLoad=import("jimp").catch(err2=>{log("warn",`[image-rescale] jimp unavailable (${err2 instanceof Error?err2.message:String(err2)}) \u2014 image rescaling disabled for this process (originals pass through)`);return null})}return jimpLoad}async function doRescale(mime,b64,origBytes,maxDim,force=false){try{const mod=await loadJimp();if(mod===null)return null;const img=await mod.Jimp.read(Buffer.from(b64,"base64"));const ow=img.width;const oh=img.height;const scale=Math.min(1,maxDim/Math.max(ow,oh));if(scale>=1&&(!force||origBytes<=RESCALE_TRIGGER_BYTES))return null;const tw=Math.max(1,Math.round(ow*scale));const th=Math.max(1,Math.round(oh*scale));if(tw!==ow||th!==oh)await img.resize({w:tw,h:th});const out=mime==="image/jpeg"?await img.getBuffer("image/jpeg",{quality:JPEG_QUALITY}):await img.getBuffer(mime);if(force?out.length>=origBytes:out.length>=origBytes*KEEP_RATIO)return null;return{base64:out.toString("base64"),width:tw,height:th,origWidth:ow,origHeight:oh,origBytes,newBytes:out.length,mime,fresh:true}}catch{return null}}async function rescaleImage(mediaType,b64,maxDim){const mime=normalizeMime(mediaType);if(!mime||typeof b64!=="string"||b64.length===0)return null;const origBytes=b64Bytes2(b64);const dims=decodeImageDims(b64);const gated=dims!==void 0&&Math.max(dims.w,dims.h)>maxDim||origBytes>RESCALE_TRIGGER_BYTES;if(!gated)return null;const hash=createHash27("sha256").update(b64,"utf8").digest("hex");let pending=encodeCache.get(hash);const cacheHit=pending!==void 0;if(!pending){pending=doRescale(mime,b64,origBytes,maxDim);encodeCache.set(hash,pending);while(encodeCache.size>ENCODE_CACHE_MAX){const oldest=encodeCache.keys().next().value;if(oldest===void 0||oldest===hash)break;encodeCache.delete(oldest)}}const result=await pending;if(result!==null&&cacheHit)return{...result,fresh:false};return result}async function shedDownscaleImage(mediaType,b64,maxDim){const mime=normalizeMime(mediaType);if(!mime||typeof b64!=="string"||b64.length===0||!Number.isFinite(maxDim)||maxDim<=0)return null;const dim=Math.floor(maxDim);const hash=createHash27("sha256").update(`${dim}:${b64}`,"utf8").digest("hex");let pending=encodeCache.get(hash);if(!pending){pending=doRescale(mime,b64,b64Bytes2(b64),dim,true);encodeCache.set(hash,pending);while(encodeCache.size>ENCODE_CACHE_MAX){const oldest=encodeCache.keys().next().value;if(oldest===void 0||oldest===hash)break;encodeCache.delete(oldest)}}const r=await pending;return r===null?null:r.base64}function formatKb(bytes){return Math.round(bytes/1024)}function buildRescaleNote(opts){const head=`[bili] \u672C\u56FE\u5DF2\u964D\u91C7\u6837:\u5F53\u524D ${opts.width}\xD7${opts.height} / ${opts.kb}KB;\u539F\u56FE ${opts.origWidth}\xD7${opts.origHeight} / ${opts.origKb}KB`;if(opts.ref!==void 0&&opts.toolArmed){return`${head}(\u7EA6 ${opts.ratio.toFixed(1)} \u500D)\u3002\u9700\u8981\u539F\u5206\u8FA8\u7387\u7EC6\u8282(\u5C0F\u5B57\u3001\u989C\u8272\u3001\u5BF9\u9F50)\u65F6,\u8C03\u7528 acp_read_original_image("${opts.ref}") \u8BFB\u53D6\u539F\u56FE\u3002\u539F\u56FE\u8F83\u5927,\u6309\u9700\u8BFB\u53D6\u3002`}return`${head}\u3002`}function noteFor(ctx,ref,r){return buildRescaleNote({ref,toolArmed:ctx.toolArmed,width:r.width,height:r.height,kb:formatKb(r.newBytes),origWidth:r.origWidth,origHeight:r.origHeight,origKb:formatKb(r.origBytes),ratio:r.newBytes>0?r.origBytes/r.newBytes:0})}function refFor(session,id){if(typeof id!=="string"||id.length===0)return void 0;const ref=session.state.messageRefs.byRaw[id];return typeof ref==="string"&&ref.length>0?ref:void 0}function logCompression(ctx,ref,r){if(!r.fresh)return;ctx.log("info",`[${ctx.sessionId}] [image-rescale] ${r.mime}${ref!==void 0?` ${ref}`:""} ${r.origWidth}x${r.origHeight}/${formatKb(r.origBytes)}KB -> ${r.width}x${r.height}/${formatKb(r.newBytes)}KB`)}function asPart(v2){return typeof v2==="object"&&v2!==null&&!Array.isArray(v2)?v2:void 0}function matchesOriginalImageReceipt(b64,parts){const hashes=new Set;for(const part of parts){const p2=asPart(part);if(typeof p2?.text!=="string")continue;for(const line of p2.text.split(/\r?\n/)){const match=/^Billion original image receipt v1 sha256=([a-f0-9]{64})$/.exec(line);if(match)hashes.add(match[1])}}if(hashes.size===0)return false;return hashes.has(createHash27("sha256").update(Buffer.from(b64,"base64")).digest("hex"))}async function rescaleAnthropic(m2,ctx){const block=asPart(m2.rawAnthropicBlock);if(!block)return void 0;if(block.type==="image"){const src=asPart(block.source);if(!src||src.type!=="base64"||typeof src.data!=="string")return void 0;const r=await rescaleImage(typeof src.media_type==="string"?src.media_type:"image/png",src.data,ctx.maxDim);if(!r)return void 0;const ref=refFor(ctx.session,m2.id);logCompression(ctx,ref,r);const copy={...m2,rawAnthropicBlock:{...block,source:{...src,data:r.base64}}};const noteMsg={id:`acp_imgnote_${m2.id}`,role:m2.role,contentType:"text",text:noteFor(ctx,ref,r)};return[copy,noteMsg]}if(block.type==="tool_result"&&Array.isArray(block.content)){const content=block.content;const changed=[];let any=false;const ref=refFor(ctx.session,m2.id);for(const part of content){const p2=asPart(part);if(p2?.type==="image"){const src=asPart(p2.source);if(src?.type==="base64"&&typeof src.data==="string"&&!matchesOriginalImageReceipt(src.data,content)){const r=await rescaleImage(typeof src.media_type==="string"?src.media_type:"image/png",src.data,ctx.maxDim);if(r){any=true;logCompression(ctx,ref,r);changed.push({...p2,source:{...src,data:r.base64}});changed.push({type:"text",text:noteFor(ctx,ref,r)});continue}}}changed.push(part)}if(!any)return void 0;return[{...m2,rawAnthropicBlock:{...block,content:changed}}]}return void 0}async function rescaleOpenaiParts(m2,ctx){const ref=refFor(ctx.session,m2.id);if(Array.isArray(m2.rawOpenaiContentParts)){const parts=m2.rawOpenaiContentParts;const changed=[];let any=false;for(const part of parts){const p2=asPart(part);if(p2?.type==="image_url"){const url=asPart(p2.image_url)?.url;if(typeof url==="string"&&url.startsWith("data:")){const d=parseDataUrl(url);if(d){const r=await rescaleImage(d.mediaType,d.base64,ctx.maxDim);if(r){any=true;logCompression(ctx,ref,r);changed.push({...p2,image_url:{...asPart(p2.image_url)??{},url:`data:${d.mediaType};base64,${r.base64}`}});changed.push({type:"text",text:noteFor(ctx,ref,r)});continue}}}}changed.push(part)}if(!any)return void 0;return[{...m2,rawOpenaiContentParts:changed}]}if(m2.rawOpenaiContent!==void 0){const p2=asPart(m2.rawOpenaiContent);if(!p2||p2.type!=="image_url")return void 0;const url=asPart(p2.image_url)?.url;if(typeof url!=="string"||!url.startsWith("data:"))return void 0;const d=parseDataUrl(url);if(!d)return void 0;const r=await rescaleImage(d.mediaType,d.base64,ctx.maxDim);if(!r)return void 0;logCompression(ctx,ref,r);const copy={...m2,rawOpenaiContentParts:[{...p2,image_url:{...asPart(p2.image_url)??{},url:`data:${d.mediaType};base64,${r.base64}`}},{type:"text",text:noteFor(ctx,ref,r)}]};delete copy.rawOpenaiContent;delete copy.imageBase64;delete copy.imageMediaType;return[copy]}return void 0}async function rescaleGoogle(m2,ctx){if(!Array.isArray(m2.rawGoogleParts))return void 0;const parts=m2.rawGoogleParts;const changed=[];let any=false;const notes=[];const ref=refFor(ctx.session,m2.id);for(const part of parts){const p2=asPart(part);const inline=p2?asPart(p2.inlineData):void 0;if(inline&&typeof inline.data==="string"&&!matchesOriginalImageReceipt(inline.data,parts)){const r=await rescaleImage(typeof inline.mimeType==="string"?inline.mimeType:"image/png",inline.data,ctx.maxDim);if(r){any=true;logCompression(ctx,ref,r);changed.push({...p2,inlineData:{...inline,data:r.base64}});notes.push(noteFor(ctx,ref,r));continue}}changed.push(part)}if(!any)return void 0;const text2=(m2.text??"")+((m2.text??"").length>0?"\n\n":"")+notes.join("\n");return[{...m2,rawGoogleParts:changed,text:text2}]}async function rescaleResponsesItem(m2,ctx){const item=asPart(m2.rawResponsesItem);if(!item)return void 0;const toolOutput=item.type==="function_call_output"||item.type==="custom_tool_call_output";const partsKey=toolOutput?"output":item.type==="message"?"content":void 0;if(partsKey===void 0||!Array.isArray(item[partsKey]))return void 0;const content=item[partsKey];const changed=[];let first;const ref=refFor(ctx.session,m2.id);for(const part of content){const p2=asPart(part);if(p2?.type==="input_image"&&typeof p2.image_url==="string"&&p2.image_url.startsWith("data:")){const d=parseDataUrl(p2.image_url);if(d&&!(toolOutput&&matchesOriginalImageReceipt(d.base64,content))){const r=await rescaleImage(d.mediaType,d.base64,ctx.maxDim);if(r){if(!first)first=r;logCompression(ctx,ref,r);changed.push({...p2,image_url:`data:${d.mediaType};base64,${r.base64}`});continue}}}changed.push(part)}if(!first)return void 0;const copy={...m2,rawResponsesItem:{...item,[partsKey]:changed}};if(toolOutput)return[{...copy,text:`${m2.text??""}
|
|
1067
1067
|
|
|
1068
1068
|
${noteFor(ctx,ref,first)}`}];const noteMsg={id:`acp_imgnote_${m2.id}`,role:"user",contentType:"text",text:noteFor(ctx,ref,first)};return[copy,noteMsg]}async function rescaleBareSidecar(m2,ctx){if(typeof m2.imageBase64!=="string"||m2.imageBase64.length===0)return void 0;const r=await rescaleImage(m2.imageMediaType??"image/png",m2.imageBase64,ctx.maxDim);if(!r)return void 0;const ref=refFor(ctx.session,m2.id);logCompression(ctx,ref,r);const note=noteFor(ctx,ref,r);const text2=(m2.text??"")+((m2.text??"").length>0?"\n\n":"")+note;return[{...m2,imageBase64:r.base64,text:text2}]}async function applyImageRescalePass(messages,ctx){if(!imageRescaleEnabled())return messages;const out=[];for(const m2 of messages){if(m2.toolName===READ_ORIGINAL_IMAGE_TOOL_NAME){out.push(m2);continue}let handled;if(m2.rawAnthropicBlock!==void 0)handled=await rescaleAnthropic(m2,ctx);else if(Array.isArray(m2.rawGoogleParts))handled=await rescaleGoogle(m2,ctx);else if(m2.rawResponsesItem!==void 0)handled=await rescaleResponsesItem(m2,ctx);else if(m2.rawOpenaiContentParts!==void 0||m2.rawOpenaiContent!==void 0)handled=await rescaleOpenaiParts(m2,ctx);else if(m2.imageBase64!==void 0)handled=await rescaleBareSidecar(m2,ctx);if(handled)out.push(...handled);else out.push(m2)}return out}async function refForItemBytes(session,mediaType,b64){const index=session.incomingImageIndex;if(!index)return void 0;const want=b64Bytes2(b64);const candidates=[];for(const[ref,entries2]of index.entries()){for(const e of entries2){if(e.bytes===want&&e.mediaType===mediaType)candidates.push({ref,mediaType:e.mediaType,bytes:e.bytes,path:e.path})}}if(candidates.length===0)return void 0;if(candidates.length===1)return candidates[0].ref;let matched;for(const c of candidates){try{const buf=await readFile5(c.path);if(buf.toString("base64")===b64){if(matched!==void 0&&matched!==c.ref)return void 0;matched=c.ref}}catch{}}return matched}async function applyImageRescaleItems(items,ctx){if(!imageRescaleEnabled())return items;const nameByCallId=new Map;for(const item of items){const i=asPart(item);if((i?.type==="function_call"||i?.type==="custom_tool_call")&&typeof i.call_id==="string"&&typeof i.name==="string"){nameByCallId.set(i.call_id,i.name)}}const out=[];for(const item of items){const i=asPart(item);if(i&&(i.type==="function_call_output"||i.type==="custom_tool_call_output")&&typeof i.call_id==="string"&&nameByCallId.get(i.call_id)===READ_ORIGINAL_IMAGE_TOOL_NAME){out.push(item);continue}const partsKey=i?.type==="message"?"content":i?.type==="function_call_output"||i?.type==="custom_tool_call_output"?"output":void 0;if(partsKey!==void 0&&i!==void 0&&Array.isArray(i[partsKey])){const parts=i[partsKey];const changed=[];let any=false;for(const part of parts){const p2=asPart(part);if(p2?.type==="input_image"&&typeof p2.image_url==="string"&&p2.image_url.startsWith("data:")){const d=parseDataUrl(p2.image_url);if(d&&!(partsKey==="output"&&matchesOriginalImageReceipt(d.base64,parts))){const r=await rescaleImage(d.mediaType,d.base64,ctx.maxDim);if(r){any=true;const ref=await refForItemBytes(ctx.session,d.mediaType,d.base64);logCompression(ctx,ref,r);changed.push({...p2,image_url:`data:${d.mediaType};base64,${r.base64}`});changed.push({type:"input_text",text:noteFor(ctx,ref,r)});continue}}}changed.push(part)}if(any){out.push({...i,[partsKey]:changed});continue}}out.push(item)}return out}var REF_PATTERN3=/^m\d{5,}$/;async function executeReadOriginalImage(args,session,log2){const ref=typeof args.ref==="string"?args.ref.trim():"";if(!REF_PATTERN3.test(ref)){return toolFail(`acp_read_original_image: invalid ref "${ref}" \u2014 pass the mNNNNN message ref quoted in the [bili] note beside the shrunken image.`)}const entries2=session.incomingImageIndex?.get(ref);if(!entries2||entries2.length===0){return toolFail(`acp_read_original_image: no original image stored for ${ref} (it may no longer ride the conversation history). Work from the downscaled version you already have.`)}const entry=entries2[0];let buf;try{buf=await readFile5(entry.path)}catch{return toolFail(`acp_read_original_image: the original for ${ref} was evicted from local storage; it becomes readable again while the image rides the resent history.`)}const counterMeta=session.metadata.imageRescaleReads;const counter=counterMeta&&typeof counterMeta==="object"?counterMeta:{count:0,bytes:0};counter.count+=1;counter.bytes+=buf.length;session.metadata.imageRescaleReads=counter;log2("info",`[${session.id}] [image-rescale] acp_read_original_image ${ref}: ${entry.width??"?"}x${entry.height??"?"}/${formatKb(buf.length)}KB session-cumulative ${counter.count} read(s)/${formatKb(counter.bytes)}KB`);const dims=`${entry.width??"?"}x${entry.height??"?"}`;return{...toolOk(`Original image for ${ref} restored (${dims}, ${formatKb(buf.length)}KB${entry.mediaType?`, ${entry.mediaType}`:""}). Local copy: ${entry.path}. It is larger than the downscaled copy you saw \u2014 use it for fine detail (small text, colors, alignment).
|
|
1069
1069
|
Billion original image receipt v1 sha256=${createHash27("sha256").update(buf).digest("hex")}`),image:{base64:buf.toString("base64"),mediaType:entry.mediaType}}}var THREAD_TAIL_KEY="anthropicThreadTail";var CONSUMED_CAP=20;function readThreadTail(session){const v2=session.metadata[THREAD_TAIL_KEY];if(!v2||typeof v2!=="object")return void 0;const t=v2;if(typeof t.tail!=="string")return void 0;const consumed=Array.isArray(t.consumed)?t.consumed.filter(x=>typeof x==="string"):[];return{tail:t.tail,consumed}}function recordThreadTail(session,id){const prev=readThreadTail(session);if(prev&&prev.tail===id)return;if(prev){const consumed=[...prev.consumed.filter(x=>x!==prev.tail&&x!==id),prev.tail];while(consumed.length>CONSUMED_CAP)consumed.shift();session.metadata[THREAD_TAIL_KEY]={tail:id,consumed}}else{session.metadata[THREAD_TAIL_KEY]={tail:id,consumed:[]}}}function resetThreadTailTracking(session){delete session.metadata[THREAD_TAIL_KEY]}function rewriteInboundThreadContinue(parsed,session,log2,sessionId){const thread=parsed.thread;if(!thread||typeof thread!=="object")return;const t=thread;if(t.type==="create"){if(session.metadata[THREAD_TAIL_KEY]!==void 0){resetThreadTailTracking(session);log2("info",`[${sessionId}] [threads] create \u2014 tail tracking reset (#2701)`)}return}if(t.type!=="continue"||typeof t.previous_message_id!=="string")return;const tracking=readThreadTail(session);if(!tracking||t.previous_message_id===tracking.tail)return;if(!tracking.consumed.includes(t.previous_message_id))return;const from=t.previous_message_id;t.previous_message_id=tracking.tail;log2("info",`[${sessionId}] [threads] inbound continue target ${from} was already consumed by an internal loop round \u2014 retargeted to current tail ${tracking.tail} (#2701)`)}init_proxy_tool_result();init_fetch_util();init_upstream_fail();init_upstream_proxy();init_logger();var MIN_INPUT=8e3;var HIGH_HIT=.5;var LOW_HIT=.1;var LOW_RUN=5;var MAX_TRACKED_SESSIONS=1024;var watches=new Map;function warnCacheCollapse(session,input,cached){if(input<MIN_INPUT)return;if(watches.size>MAX_TRACKED_SESSIONS){const oldest=watches.keys().next().value;if(oldest!==void 0)watches.delete(oldest)}const watch=watches.get(session.id)??{sawHigh:false,lowRun:0,warned:false};watches.set(session.id,watch);const hit=cached/input;if(hit>=HIGH_HIT){watch.sawHigh=true;watch.lowRun=0;return}if(!watch.sawHigh||watch.warned)return;if(hit>LOW_HIT){watch.lowRun=0;return}watch.lowRun++;if(watch.lowRun<LOW_RUN)return;watch.warned=true;log("warn",`[${session.id}] upstream prompt-cache collapse: ${LOW_RUN} consecutive large requests at ~0% hit (last: input=${input}, cached=${cached}) after earlier \u2265${Math.round(HIGH_HIT*100)}% hits \u2014 the context is being resent cold every turn. Likely causes: proxy/session restart re-forked the session (#499), or the upstream KV cache was dropped (window/deployment change). Check the session id upstream sees and compress.modelContextLimit.`)}init_fetch_transport();init_knobs();function isObj4(v2){return typeof v2==="object"&&v2!==null&&!Array.isArray(v2)}var PROTECTED_TAIL_ENTRIES=8;var DOWNSCALE_DIM_LADDER=[1024,768,512,384];var MAX_SHED_IMAGES=64;function byteLen(s3){return Buffer.byteLength(s3)}function formatMiB2(bytes){return(bytes/(1024*1024)).toFixed(1)}function dataUrl(mediaType,b64){return`data:${mediaType};base64,${b64}`}async function shedNote(mediaType,b64,resolveRef){const mime=mediaType.replace(/^image\//i,"");const bits=[];if(mime)bits.push(mime);const dims=decodeImageDims(b64);if(dims)bits.push(`${dims.w}x${dims.h}`);const ref=await resolveRef?.(mediaType,b64);if(ref)bits.push(ref);return`[image: ${bits.join(" ")} omitted for size limit]`}function callNameMap(protocol,body){const map=new Map;if(protocol==="responses"){const input=body.input;if(!Array.isArray(input))return map;for(const item of input){if(!isObj4(item))continue;if((item.type==="function_call"||item.type==="custom_tool_call")&&typeof item.call_id==="string"&&typeof item.name==="string"){map.set(item.call_id,item.name)}}return map}const messages=body.messages;if(!Array.isArray(messages))return map;for(const m2 of messages){if(!isObj4(m2))continue;if(protocol==="openai"){const calls=m2.tool_calls;if(Array.isArray(calls)){for(const c of calls){if(isObj4(c)&&typeof c.id==="string"&&isObj4(c.function)&&typeof c.function.name==="string"){map.set(c.id,c.function.name)}}}}else{const content=m2.content;if(Array.isArray(content)){for(const b2 of content){if(isObj4(b2)&&b2.type==="tool_use"&&typeof b2.id==="string"&&typeof b2.name==="string"){map.set(b2.id,b2.name)}}}}}return map}function isExemptOutput(protocol,item,names){const id=protocol==="responses"?item.call_id:protocol==="openai"?item.tool_call_id:item.tool_use_id;return typeof id==="string"&&names.get(id)===READ_ORIGINAL_IMAGE_TOOL_NAME}function collectOccurrences(protocol,body){const occ=[];const addAnthropicImages=(parts,entryIndex,toolOutput)=>{parts.forEach((part,pos)=>{if(!isObj4(part)||part.type!=="image")return;const src=part.source;if(!isObj4(src)||src.type!=="base64"||typeof src.data!=="string"||src.data.length===0)return;if(toolOutput&&matchesOriginalImageReceipt(src.data,parts))return;const mediaType=typeof src.media_type==="string"?src.media_type:"image/png";occ.push({entryIndex,b64:src.data,mediaType,protectedTail:false,archived:false,applyArchive:note=>{parts[pos]={type:"text",text:note}},applyShrink:b64=>{src.data=b64}})})};if(protocol==="google"){const contents=body.contents;if(!Array.isArray(contents))return occ;contents.forEach((c,entryIndex)=>{if(!isObj4(c)||!Array.isArray(c.parts))return;const parts=c.parts;parts.forEach((part,pos)=>{if(!isObj4(part))return;const inline=part.inlineData;if(!isObj4(inline)||typeof inline.data!=="string"||inline.data.length===0)return;if(matchesOriginalImageReceipt(inline.data,parts))return;const mediaType=typeof inline.mimeType==="string"?inline.mimeType:"image/png";occ.push({entryIndex,b64:inline.data,mediaType,protectedTail:false,archived:false,applyArchive:note=>{parts[pos]={text:note}},applyShrink:b64=>{inline.data=b64}})})});return occ}if(protocol==="responses"){const input=body.input;if(!Array.isArray(input))return occ;const names2=callNameMap(protocol,body);input.forEach((item,entryIndex)=>{if(!isObj4(item))return;const partsKey=item.type==="message"?"content":item.type==="function_call_output"||item.type==="custom_tool_call_output"?"output":void 0;if(partsKey===void 0||!Array.isArray(item[partsKey]))return;if((item.type==="function_call_output"||item.type==="custom_tool_call_output")&&isExemptOutput(protocol,item,names2))return;const parts=item[partsKey];parts.forEach((part,pos)=>{if(!isObj4(part)||part.type!=="input_image"||typeof part.image_url!=="string")return;const d=parseDataUrl(part.image_url);if(!d||partsKey==="output"&&matchesOriginalImageReceipt(d.base64,parts))return;occ.push({entryIndex,b64:d.base64,mediaType:d.mediaType,protectedTail:false,archived:false,applyArchive:note=>{parts[pos]={type:"input_text",text:note}},applyShrink:b64=>{part.image_url=dataUrl(d.mediaType,b64)}})})});return occ}const messages=body.messages;if(!Array.isArray(messages))return occ;const names=callNameMap(protocol,body);messages.forEach((m2,entryIndex)=>{if(!isObj4(m2))return;if(protocol==="openai"&&m2.role==="tool"&&isExemptOutput(protocol,m2,names))return;if(protocol==="anthropic"&&Array.isArray(m2.content)&&m2.content.some(b2=>isObj4(b2)&&b2.type==="tool_result"&&isExemptOutput(protocol,b2,names)))return;if(!Array.isArray(m2.content))return;const content=m2.content;if(protocol==="anthropic")addAnthropicImages(content,entryIndex,false);content.forEach((part,pos)=>{const p2=isObj4(part)?part:void 0;if(!p2)return;if(protocol==="openai"){if(p2.type!=="image_url")return;const iu=p2.image_url;const url=typeof iu==="string"?iu:isObj4(iu)&&typeof iu.url==="string"?iu.url:void 0;if(typeof url!=="string")return;const d=parseDataUrl(url);if(!d)return;occ.push({entryIndex,b64:d.base64,mediaType:d.mediaType,protectedTail:false,archived:false,applyArchive:note=>{content[pos]={type:"text",text:note}},applyShrink:b64=>{p2.image_url=typeof iu==="string"?dataUrl(d.mediaType,b64):{...iu??{},url:dataUrl(d.mediaType,b64)}}})}else if(p2.type==="tool_result"&&Array.isArray(p2.content)){addAnthropicImages(p2.content,entryIndex,true)}})});return occ}async function shedWireImages(body,protocol,targetBytes,opts={}){const originalBytes=byteLen(body);const noop={originalBytes,finalBytes:originalBytes,archived:0,downscaled:0,changed:false};if(targetBytes<=0||originalBytes<=targetBytes)return{body,stats:noop};let parsed;try{parsed=JSON.parse(body)}catch{return{body,stats:noop}}if(!isObj4(parsed))return{body,stats:noop};const occurrences=collectOccurrences(protocol,parsed);if(occurrences.length===0)return{body,stats:noop};const totalEntries=protocol==="google"?Array.isArray(parsed.contents)?parsed.contents.length:0:protocol==="responses"?Array.isArray(parsed.input)?parsed.input.length:0:Array.isArray(parsed.messages)?parsed.messages.length:0;const protectFrom=Math.max(0,totalEntries-PROTECTED_TAIL_ENTRIES);for(const o of occurrences)o.protectedTail=o.entryIndex>=protectFrom;let est=originalBytes;let archived=0;let downscaled=0;const work=occurrences.slice(0,MAX_SHED_IMAGES);for(const o of work){if(est<=targetBytes)break;if(o.protectedTail)continue;const note=await shedNote(o.mediaType,o.b64,opts.resolveRef);o.applyArchive(note);o.archived=true;est+=byteLen(JSON.stringify(note))-byteLen(dataUrl(o.mediaType,o.b64));archived++}if(est>targetBytes){outer:for(const dim of DOWNSCALE_DIM_LADDER){for(const o of work){if(est<=targetBytes)break;if(o.archived)continue;const dims=decodeImageDims(o.b64);if(dims!==void 0&&Math.max(dims.w,dims.h)<=dim)continue;const smaller=await shedDownscaleImage(o.mediaType,o.b64,dim);if(smaller===null||smaller.length>=o.b64.length)continue;o.applyShrink(smaller);est+=smaller.length-o.b64.length;o.b64=smaller;downscaled++}if(est<=targetBytes)break outer}}if(archived===0&&downscaled===0)return{body,stats:noop};const next=JSON.stringify(parsed);return{body:next,stats:{originalBytes,finalBytes:byteLen(next),archived,downscaled,changed:true}}}async function shedWireImagesToCount(body,protocol,maxImages,opts={}){const originalBytes=byteLen(body);const noop={originalBytes,finalBytes:originalBytes,archived:0,downscaled:0,changed:false};if(!Number.isInteger(maxImages)||maxImages<0)return{body,stats:noop};let parsed;try{parsed=JSON.parse(body)}catch{return{body,stats:noop}}if(!isObj4(parsed))return{body,stats:noop};const occurrences=collectOccurrences(protocol,parsed);if(occurrences.length<=maxImages)return{body,stats:noop};const totalEntries=protocol==="google"?Array.isArray(parsed.contents)?parsed.contents.length:0:protocol==="responses"?Array.isArray(parsed.input)?parsed.input.length:0:Array.isArray(parsed.messages)?parsed.messages.length:0;const protectFrom=Math.max(0,totalEntries-PROTECTED_TAIL_ENTRIES);for(const o of occurrences)o.protectedTail=o.entryIndex>=protectFrom;let remaining=occurrences.length;let archived=0;for(const allowTail of[false,true]){if(remaining<=maxImages)break;for(const o of occurrences){if(remaining<=maxImages)break;if(o.archived)continue;if(!allowTail&&o.protectedTail)continue;const note=await shedNote(o.mediaType,o.b64,opts.resolveRef);o.applyArchive(note);o.archived=true;remaining--;archived++}}if(archived===0)return{body,stats:noop};const next=JSON.stringify(parsed);return{body:next,stats:{originalBytes,finalBytes:byteLen(next),archived,downscaled:0,changed:true}}}async function shedEgressIfOverBudget(body,protocol,ctx){const originalBytes=byteLen(body);const t=currentFetchTransport();let budget;let lane;if(isWsLaneTransport(t)){budget=limitsWsOutboundBytes();lane="ws"}else if(t===void 0){budget=limitsHttpOutboundBytes();lane="http"}else{return{body,stats:{originalBytes,finalBytes:originalBytes,archived:0,downscaled:0,changed:false}}}if(budget<=0||originalBytes<=budget){return{body,stats:{originalBytes,finalBytes:originalBytes,archived:0,downscaled:0,changed:false}}}const tag=`${lane}-byte-shed`;const metaKey=lane==="ws"?"wsByteShed":"httpByteShed";const{body:next,stats}=await shedWireImages(body,protocol,budget,{resolveRef:ctx.session?(mt2,b64)=>refForItemBytes(ctx.session,mt2,b64):void 0});if(!stats.changed){ctx.log?.("warn",`[${ctx.sessionId??"?"}] [${tag}] ${ctx.phase??"send"}: outbound ${formatMiB2(originalBytes)} MiB over budget ${formatMiB2(budget)} MiB but no sheddable images outside the protected tail \u2014 sending as-is`);return{body,stats}}if(ctx.session){ctx.session.metadata[metaKey]={at:Date.now(),phase:ctx.phase??"send",fromBytes:stats.originalBytes,toBytes:stats.finalBytes,archived:stats.archived,downscaled:stats.downscaled}}if(stats.finalBytes<=budget){ctx.log?.("info",`[${ctx.sessionId??"?"}] [${tag}] ${ctx.phase??"send"}: ${formatMiB2(stats.originalBytes)} -> ${formatMiB2(stats.finalBytes)} MiB (archived=${stats.archived} downscaled=${stats.downscaled} budget=${formatMiB2(budget)} MiB) \u2014 originals stay in session storage`)}else{ctx.log?.("warn",`[${ctx.sessionId??"?"}] [${tag}] ${ctx.phase??"send"}: shed to ${formatMiB2(stats.finalBytes)} MiB but still over budget ${formatMiB2(budget)} MiB (protected recent messages hold the rest) \u2014 sending anyway; hard cap network.outboundBodyBytes unchanged`)}return{body:next,stats}}function extractWsOversizeError(error){let cur=error;for(let hop=0;cur!==null&&typeof cur==="object"&&hop<4;hop++){if(cur instanceof ResponsesWsUpstreamError&&cur.closeCode===1009&&cur.receivedEvents===0){return cur}cur=cur.cause}return void 0}init_knobs();init_paths();function isStrictReasoningEcho(session,upstreamOrigin,model){if(session.metadata.strictReasoningEcho===true)return true;if(upstreamOrigin!==void 0&&/deepseek/i.test(upstreamOrigin))return true;return typeof model==="string"&&model.length>0&&/deepseek/i.test(model)}function modelIdOf(body){const m2=body?.model;return typeof m2==="string"?m2:void 0}function normalizeStrictEchoReasoning(messages,enabled,log2,sessionId){if(!enabled)return messages;let patched=0;const out=messages.map(m2=>{if(m2.role!=="assistant")return m2;if(!Array.isArray(m2.tool_calls)||m2.tool_calls.length===0)return m2;if(typeof m2.reasoning_content==="string")return m2;patched++;return{...m2,reasoning_content:""}});if(patched>0){log2("info",`[${sessionId}] strict-echo: injected blank reasoning_content on ${patched} assistant tool-call message(s) (#762)`)}return patched>0?out:messages}function hasBlankReasoningContent(item){if(item.type!=="reasoning")return false;const content=item.content;if(!Array.isArray(content)||content.length===0)return false;let sawTextPart=false;for(const part of content){if(part===null||typeof part!=="object")return false;const p2=part;if(p2.type!=="reasoning_text"||typeof p2.text!=="string")return false;sawTextPart=true;if(p2.text.trim().length>0)return false}return sawTextPart}function normalizeStrictEchoResponsesInput(input,enabled,log2,sessionId){if(!enabled)return input;let hasReasoning=false;for(const it2 of input){if(it2?.type==="reasoning"){hasReasoning=true;break}}if(!hasReasoning)return input;const insertAt=new Set;let runStart=-1;let runCalls=0;let runReasoning=0;const closeRun=()=>{if(runStart>=0&&runCalls>0&&runReasoning===0)insertAt.add(runStart);runStart=-1;runCalls=0;runReasoning=0};for(let i=0;i<input.length;i++){const it2=input[i];const t=typeof it2?.type==="string"?it2.type:void 0;const inRun=t==="reasoning"||t==="function_call"||t==="custom_tool_call"||t==="function_call_output"||t==="custom_tool_call_output"||t==="message"&&it2?.role==="assistant";if(!inRun){closeRun();continue}if(runStart<0)runStart=i;if(t==="function_call"||t==="custom_tool_call")runCalls++;else if(t==="reasoning")runReasoning++}closeRun();const clearAt=new Set;for(let i=0;i<input.length;i++){if(hasBlankReasoningContent(input[i]))clearAt.add(i)}if(insertAt.size===0&&clearAt.size===0)return input;const out=[];for(let i=0;i<input.length;i++){if(insertAt.has(i))out.push({type:"reasoning",summary:[{type:"summary_text",text:""}]});if(clearAt.has(i)){const copy={...input[i]};delete copy.content;out.push(copy)}else{out.push(input[i])}}if(clearAt.size>0)log2("info",`[${sessionId}] strict-echo-responses: cleared whitespace-only reasoning content on ${clearAt.size} item(s) \u2014 blank reasoning_text echoes are rejected by strict-echo upstreams (#2169)`);if(insertAt.size>0)log2("info",`[${sessionId}] strict-echo-responses: injected ${insertAt.size} blank reasoning item(s) before tool-call run(s) missing their echo (#1479)`);return out}function normalizeStrictEchoBody(body,enabled,log2,sessionId){if(!enabled)return body;let out=body;if(Array.isArray(body.messages)){const patched=normalizeStrictEchoReasoning(body.messages,true,log2,sessionId);if(patched!==body.messages)out={...out,messages:patched}}if(Array.isArray(body.input)){const patched=normalizeStrictEchoResponsesInput(body.input,true,log2,sessionId);if(patched!==body.input)out={...out,input:patched}}return out}init_logger();init_util();init_fetch_util();init_upstream_proxy();function appendTrailingUserText(protocol,body,text2){const raw=typeof body==="string"?body:body.toString("utf8");let obj;try{obj=JSON.parse(raw)}catch{return null}if(protocol==="responses"){const input=obj.input;if(!Array.isArray(input))return null;const arr2=input;const last2=arr2[arr2.length-1];if(last2&&typeof last2==="object"&&last2.role==="user"){const c=last2.content;if(typeof c==="string")last2.content=`${c}
|
|
@@ -7229,7 +7229,7 @@ data: ${JSON.stringify({type:"error",error:{type:"server_error",code:"upstream_e
|
|
|
7229
7229
|
${v2}`}if(data===null||data==="[DONE]")return;let obj;try{obj=JSON.parse(data)}catch{return}processParsed(obj)};const pumpFrames=()=>{if(frameBuf.length>=NDJSON_FALLBACK_MIN&&frameBuf.includes("\n")&&!HAS_FRAME_SEP_RE.test(frameBuf)){const lines=frameBuf.split("\n");frameBuf="";for(const lineRaw of lines){const line=lineRaw.endsWith("\r")?lineRaw.slice(0,-1):lineRaw;if(line.length===0||line.charAt(0)!=="{"&&line.charAt(0)!=="[")continue;let obj;try{obj=JSON.parse(line)}catch{continue}processParsed(obj);if(walkTripped)return}return}if(frameBuf.length>FRAME_BUF_CAP){frameBuf="";return}FRAME_SEP_RE.lastIndex=0;let m2;while((m2=FRAME_SEP_RE.exec(frameBuf))!==null){const frame=frameBuf.slice(0,m2.index);frameBuf=frameBuf.slice(m2.index+m2[0].length);processSseFrame(frame);if(walkTripped)return;if(frameBuf.length>FRAME_BUF_CAP){frameBuf="";return}}};const trip=controller=>{settled=true;onTrip(tripVerdict??{tripped:true});controller.close();reader.cancel().catch(()=>{})};return new ReadableStream({async pull(controller){if(settled)return;const r=await reader.read();if(r.done){settled=true;controller.close();return}const value=r.value;const text2=decoder.decode(value,{stream:true});if(text2.length>0){if(text2.includes("<")){const v2=guard.feed(text2);if(v2.tripped){tripVerdict=v2;trip(controller);return}}else{guard.feedGapOnly(text2)}frameBuf+=text2;pumpFrames();if(walkTripped){trip(controller);return}}controller.enqueue(value)},cancel(reason){settled=true;reader.cancel(reason).catch(()=>{})}})}async function rewriteGoogleJsonResponseAsync(body,ctx,signal){return runJsonRewriteAsync(rewriteGoogleJsonSteps(body,ctx),async call=>(await executeProxyToolAsync(call.name,call.args,ctx,call.id,void 0,signal)).text)}function*rewriteGoogleJsonSteps(body,ctx){if(!body||typeof body!=="object")return body;const b2=body;const candidate=b2.candidates?.[0];const content=candidate?.content;const parts=content?.parts;if(!candidate||!content||!Array.isArray(parts))return body;let converted=false;let sawReal=false;const noteParts=[];const keptParts=[];const absorbArmed=effectiveAbsorbConfig(ctx.session,ctx.config)?.enabled===true;const requestText2=JSON.stringify(ctx.messages);for(const part of parts){if(!part||typeof part!=="object")continue;const fc=part.functionCall;if(fc&&typeof fc.name==="string"&&isProxyToolFor(fc.name,ctx.session,ctx.config)){converted=true;const args=fc.args!==null&&typeof fc.args==="object"?fc.args:{};noteParts.push(yield{name:fc.name,args,id:typeof fc.id==="string"?fc.id:void 0});continue}if(fc)sawReal=true;if(part.thought!==true&&typeof part.text==="string"&&(containsRenderTagText(part.text)||containsMarkerLineText(part.text)||containsBiliInternalText(part.text)||absorbArmed&&containsToolCallEmissionText(part.text))){ctx.log(`[tag-echo] stripped: non-stream google output ACP echo (render tags/markers/internal artifacts): ${part.text.slice(0,120).replace(/\n/g," ")}`);part.text=stripAcpTags(part.text,absorbArmed,requestText2)}keptParts.push(part)}for(const injection of drainPendingRetrievals(ctx.session)){if(typeof injection.text==="string")noteParts.push(injection.text)}if(!converted)return body;content.parts=[...keptParts,{text:noteParts.join("\n")}];if(!sawReal){candidate.finishReason="STOP"}return body}async function rewriteOpenaiJsonResponseAsync(body,ctx,signal){return runJsonRewriteAsync(rewriteOpenaiJsonSteps(body,ctx),async call=>(await applyConfiguredCompression(call.args,ctx,call.id,signal)).text)}function*rewriteOpenaiJsonSteps(body,ctx){if(!body||typeof body!=="object")return body;const b2=body;const choice=b2.choices?.[0];const msg=choice?.message;if(!choice||!msg)return body;let converted=false;let sawReal=false;const noteParts=[];const keepToolCalls=[];let existingText=typeof msg.content==="string"?msg.content:"";const toolCalls=msg.tool_calls;if(Array.isArray(toolCalls)){for(const tc of toolCalls){if(tc.function?.name===COMPRESS_TOOL_NAME){converted=true;noteParts.push(yield{name:COMPRESS_TOOL_NAME,args:tc.function?.arguments??"",id:tc.id})}else{sawReal=true;keepToolCalls.push(tc)}}const namelessToolCallIdx=[];for(let i=0;i<toolCalls.length;i++){const nm=(toolCalls[i]??{})?.function?.name;if(typeof nm!=="string"||nm.length===0)namelessToolCallIdx.push(i)}if(namelessToolCallIdx.length>0){ctx.log(`[warn: nameless tool call] non-stream openai response carries ${namelessToolCallIdx.length} nameless tool_call(s) at index ${namelessToolCallIdx.join(",")} \u2014 forwarded verbatim (#1501 observe-only)`)}}const absorbArmed=effectiveAbsorbConfig(ctx.session,ctx.config)?.enabled===true;const requestText2=JSON.stringify(ctx.messages);if(existingText&&(containsRenderTagText(existingText)||containsMarkerLineText(existingText)||containsBiliInternalText(existingText)||absorbArmed&&containsToolCallEmissionText(existingText))){ctx.log(`[tag-echo] stripped: non-stream openai output ACP echo (render tags/markers/internal artifacts): ${existingText.slice(0,120).replace(/\n/g," ")}`);existingText=stripAcpTags(existingText,absorbArmed,requestText2);msg.content=existingText}if(!converted)return body;const note=noteParts.join("\n");msg.content=existingText?`${existingText}
|
|
7230
7230
|
${note}`:note;if(keepToolCalls.length>0){msg.tool_calls=keepToolCalls}else{delete msg.tool_calls}if(!sawReal){choice.finish_reason="stop"}return body}async function rewriteResponsesJsonResponseAsync(body,ctx,signal){return runJsonRewriteAsync(rewriteResponsesJsonSteps(body,ctx),async call=>(await applyConfiguredCompression(call.args,ctx,call.id,signal)).text)}function*rewriteResponsesJsonSteps(body,ctx){if(!body||typeof body!=="object")return body;const b2=body;if(!Array.isArray(b2.output))return body;const probe=JSON.stringify(b2.output);const absorbArmed=effectiveAbsorbConfig(ctx.session,ctx.config)?.enabled===true;const requestText2=JSON.stringify(ctx.messages);if(containsRenderTagText(probe)||containsMarkerLineText(probe)||containsBiliInternalText(probe)||absorbArmed&&containsToolCallEmissionText(probe)){ctx.log(`[tag-echo] stripped: non-stream responses output ACP echo (render tags/markers/internal artifacts): ${probe.slice(0,120).replace(/\n/g," ")}`);stripResponsesText(b2,absorbArmed,requestText2)}let converted=false;let sawReal=false;const noteParts=[];const keep=[];for(const item of b2.output){if(item.type==="function_call"&&item.name===COMPRESS_TOOL_NAME){converted=true;noteParts.push(yield{name:COMPRESS_TOOL_NAME,args:String(item.arguments??""),id:typeof item.call_id==="string"?item.call_id:void 0})}else{if(item.type==="function_call")sawReal=true;keep.push(item)}}if(!converted)return body;const note=noteParts.join("\n");if(note){keep.unshift({type:"message",role:"assistant",content:[{type:"output_text",text:note}]})}b2.output=keep;if(!sawReal)b2.status="completed";return body}var SUCCEEDED="response.completed";var FAILED_EVENTS=new Set(["response.failed","response.incomplete"]);var MAX_JSON_BYTES=16<<20;async function observeResponsesTerminalState(stream2,isStream){return isStream?observeSseTerminalState(stream2):observeJsonTerminalState(stream2)}function terminalFromSseLine(line){if(line.startsWith("event:")){const name=line.slice(6).trim();if(name===SUCCEEDED)return"completed";if(FAILED_EVENTS.has(name))return"failed";return null}if(line.startsWith("data:")){const data=line.slice(5).trim();if(!data.startsWith("{"))return null;try{const type=JSON.parse(data).type;if(type===SUCCEEDED)return"completed";if(type==="response.failed"||type==="response.incomplete")return"failed"}catch{return null}}return null}async function observeSseTerminalState(stream2){const reader=stream2.getReader();const decoder=new TextDecoder;let buf="";let state7="unknown";try{for(;;){const{done,value}=await reader.read();if(done)break;buf+=decoder.decode(value,{stream:true});let nl;while((nl=buf.indexOf("\n"))>=0){const line=buf.slice(0,nl).replace(/\r$/,"");buf=buf.slice(nl+1);const next=terminalFromSseLine(line);if(next!==null){state7=next;break}}if(state7!=="unknown"){await reader.cancel().catch(()=>{});break}}}catch{return"unknown"}finally{reader.releaseLock()}return state7}async function observeJsonTerminalState(stream2){const reader=stream2.getReader();const chunks=[];let size=0;let overflow=false;try{for(;;){const{done,value}=await reader.read();if(done)break;if(!overflow){size+=value.length;if(size<=MAX_JSON_BYTES){chunks.push(Buffer.from(value))}else{overflow=true}}}}catch{return"unknown"}finally{reader.releaseLock()}if(overflow)return"unknown";const text2=Buffer.concat(chunks).toString("utf8").trim();if(!text2)return"unknown";let body;try{body=JSON.parse(text2)}catch{return"unknown"}if(typeof body!=="object"||body===null)return"unknown";const rec=body;if(rec.error!==void 0)return"failed";if(Array.isArray(rec.output))return"completed";return"unknown"}init_text_safe();init_upstream_proxy();init_upstream_fail();init_util();init_billing();init_logger();init_dist();var SENTINEL="<bili_output_steering>";var SUFFIX="</bili_output_steering>";function steeringText(level){return renderSteeringBlock(level,SENTINEL)}function replaceOrAppend(existing,block){const start=existing.indexOf(SENTINEL);if(start>=0){const found=existing.indexOf(SUFFIX,start);const end=found<0?existing.length:found+SUFFIX.length;const prefix=existing.slice(0,start).replace(/\s+$/,"");const suffix=existing.slice(end).replace(/^\n+/,"");const parts=[prefix,block,suffix].filter(p2=>p2.length>0);const updated2=parts.join("\n\n");return[updated2,updated2!==existing]}const trimmed=existing.trim();const updated=trimmed.length>0?`${existing.replace(/\s+$/,"")}
|
|
7231
7231
|
|
|
7232
|
-
${block}`:block;return[updated,updated!==existing]}function asRecord2(v2){return v2&&typeof v2==="object"&&!Array.isArray(v2)?v2:null}function normalizeAnthropic(messages){if(!Array.isArray(messages)||messages.length===0)return[];const last=asRecord2(messages[messages.length-1]);if(!last||last.role!=="user")return[{role:"user",text:""}];const content=last.content;if(typeof content==="string")return[{role:"user",text:content}];if(!Array.isArray(content)||content.length===0)return[{role:"user",text:""}];const blocks=[];for(const raw of content){const b2=asRecord2(raw);if(!b2)return[{role:"user",text:""}];const t=b2.type;if(t==="tool_result")blocks.push({kind:"tool_result",isError:b2.is_error===true});else if(t==="text"||t==="image"||t==="document")blocks.push({kind:t});else return[{role:"user",text:""}]}return[{role:"user",blocks}]}function normalizeOpenAi(messages){if(!Array.isArray(messages)||messages.length===0)return[];const last=asRecord2(messages[messages.length-1]);if(!last)return[{role:"user",text:""}];if(last.role==="tool"){let i=messages.length-1;while(i>=0&&asRecord2(messages[i])?.role==="tool")i--;const n=messages.length-1-i;const blocks=[];for(let k2=0;k2<n;k2++)blocks.push({kind:"tool_result"});return[{role:"user",blocks}]}if(last.role==="user"){const c=last.content;if(typeof c==="string")return[{role:"user",text:c}];if(Array.isArray(c)){for(const raw of c){const b2=asRecord2(raw);if(b2&&b2.type==="text"&&typeof b2.text==="string"&&b2.text.trim())return[{role:"user",blocks:[{kind:"text"}]}]}}}return[{role:"user",text:""}]}var RESPONSES_OUTPUT_TYPES=new Set(["custom_tool_call_output","function_call_output","local_shell_call_output","apply_patch_call_output"]);var RESPONSES_NEUTRAL_TYPES=new Set(["message","function_call","custom_tool_call","local_shell_call","apply_patch_call","reasoning"]);function responsesIsUserSignal(item){if(item.type==="input_text")return typeof item.text==="string"&&item.text.trim()!=="";if(item.type==="input_image"||item.type==="input_file")return true;if(item.role==="user"){const c=item.content??item.input;if(typeof c==="string")return c.trim()!=="";if(Array.isArray(c)){for(const raw of c){const b2=asRecord2(raw);if(!b2)continue;if((b2.type==="input_text"||b2.type==="text")&&typeof b2.text==="string"&&b2.text.trim())return true;if(b2.type==="input_image"||b2.type==="input_file")return true}}}return false}function normalizeResponses(input){if(typeof input==="string")return[{role:"user",text:input}];if(!Array.isArray(input)||input.length===0)return[{role:"user",text:""}];const last=asRecord2(input[input.length-1]);if(last&&responsesIsUserSignal(last))return[{role:"user",blocks:[{kind:"text"}]}];let foundOutput=false;for(let i=input.length-1;i>=0;i--){const item=asRecord2(input[i]);if(!item)break;const t=typeof item.type==="string"?item.type:"";if(RESPONSES_OUTPUT_TYPES.has(t)){foundOutput=true;break}if(RESPONSES_NEUTRAL_TYPES.has(t))continue;break}if(foundOutput)return[{role:"user",blocks:[{kind:"tool_result"}]}];return[{role:"user",text:""}]}function normalizeGoogle(contents){if(!Array.isArray(contents)||contents.length===0)return[];const last=asRecord2(contents[contents.length-1]);if(!last||last.role!=="user")return[{role:"user",text:""}];const parts=last.parts;if(!Array.isArray(parts)||parts.length===0)return[{role:"user",text:""}];const blocks=[];for(const raw of parts){const p2=asRecord2(raw);if(!p2)return[{role:"user",text:""}];if(p2.functionResponse)blocks.push({kind:"tool_result"});else if(typeof p2.text==="string"){if(p2.text.trim()!=="")blocks.push({kind:"text"})}else if(p2.inlineData||p2.fileData||p2.videoMetadata)blocks.push({kind:"image"});else return[{role:"user",text:""}]}return[{role:"user",blocks}]}function toStructural(protocol,obj){switch(protocol){case"anthropic":return normalizeAnthropic(obj.messages);case"openai":return normalizeOpenAi(obj.messages);case"responses":return normalizeResponses(obj.input);case"google":return normalizeGoogle(obj.contents)}}function steerSystemPrompt(obj,protocol,level){const block=steeringText(level);if(!block)return false;switch(protocol){case"anthropic":return steerAnthropicSystem(obj,block);case"openai":return steerOpenAiSystem(obj,block);case"responses":return steerResponsesInstructions(obj,block);case"google":return steerGoogleSystem(obj,block)}}function steerAnthropicSystem(obj,block){const sys=obj.system;if(sys===void 0)return false;if(typeof sys==="string"){const[updated,changed]=replaceOrAppend(sys,block);if(changed)obj.system=updated;return changed}if(Array.isArray(sys)){for(const raw of sys){const b2=asRecord2(raw);if(!b2)continue;const t=typeof b2.text==="string"?b2.text:"";if(t.startsWith(SENTINEL)){if(t===block)return false;b2.text=block;return true}}sys.push({type:"text",text:block});return true}return false}function steerOpenAiSystem(obj,block){const msgs=obj.messages;if(!Array.isArray(msgs))return false;const arr=msgs;let target=null;for(let i=arr.length-1;i>=0;i--){const m2=arr[i];if(m2&&typeof m2==="object"&&(m2.role==="system"||m2.role==="developer")){target=m2;break}}if(!target)return false;const content=target.content;if(content===null||content===void 0){target.content=block;return true}if(typeof content==="string"){const[updated,changed]=replaceOrAppend(content,block);if(changed)target.content=updated;return changed}if(Array.isArray(content)){for(const raw of content){const b2=asRecord2(raw);if(!b2)continue;if(b2.type==="text"&&typeof b2.text==="string"&&b2.text.startsWith(SENTINEL)){if(b2.text===block)return false;b2.text=block;return true}}content.push({type:"text",text:block});return true}return false}function steerResponsesInstructions(obj,block){const ins=obj.instructions;if(ins===void 0)return false;if(typeof ins!=="string")return false;const[updated,changed]=replaceOrAppend(ins,block);if(changed)obj.instructions=updated;return changed}function steerGoogleSystem(obj,block){const si2=asRecord2(obj.systemInstruction);if(!si2)return false;const parts=si2.parts;if(!Array.isArray(parts))return false;for(const raw of parts){const p2=asRecord2(raw);if(!p2)continue;const t=typeof p2.text==="string"?p2.text:"";if(t.startsWith(SENTINEL)){if(t===block)return false;p2.text=block;return true}}parts.push({text:block});return true}var ANTHROPIC_MIN_THINKING_BUDGET=1024;var GOOGLE_MIN_THINKING_BUDGET=128;function lowerEffort(obj,protocol){switch(protocol){case"openai":{const v2=clampEffortToFloor(obj.reasoning_effort,"low");if(v2!==null){obj.reasoning_effort=v2;return true}return false}case"responses":{const r=asRecord2(obj.reasoning);if(!r)return false;const v2=clampEffortToFloor(r.effort,"low");if(v2!==null){r.effort=v2;return true}return false}case"anthropic":{let changed=false;const oc=asRecord2(obj.output_config);if(oc){const v2=clampEffortToFloor(oc.effort,"low");if(v2!==null){oc.effort=v2;changed=true}}const th=asRecord2(obj.thinking);if(th&&typeof th.budget_tokens==="number"&&th.budget_tokens>ANTHROPIC_MIN_THINKING_BUDGET){th.budget_tokens=ANTHROPIC_MIN_THINKING_BUDGET;changed=true}return changed}case"google":{const gc=asRecord2(obj.generationConfig);const tc=gc?asRecord2(gc.thinkingConfig):null;if(tc&&typeof tc.thinkingBudget==="number"&&tc.thinkingBudget>GOOGLE_MIN_THINKING_BUDGET){tc.thinkingBudget=GOOGLE_MIN_THINKING_BUDGET;return true}return false}}}function detectProtocolFromBody(obj){if(Array.isArray(obj.input))return"responses";if(Array.isArray(obj.contents))return"google";if(Array.isArray(obj.messages)){return obj.system!==void 0?"anthropic":"openai"}return null}function applyOutputSteering(body,protocol,cfg){if(!cfg.enabled)return{body,changed:false,labels:[]};let obj;try{obj=JSON.parse(body)}catch{return{body,changed:false,labels:[]}}const proto=protocol??detectProtocolFromBody(obj);if(!proto)return{body,changed:false,labels:[]};const labels=applyOutputSteeringJson(obj,proto,cfg);if(labels.length===0)return{body,changed:false,labels:[]};return{body:JSON.stringify(obj),changed:true,labels}}function applyOutputSteeringJson(parsed,protocol,cfg,opts={}){if(!cfg.enabled)return[];const proto=protocol??detectProtocolFromBody(parsed);if(!proto)return[];const decision=decideOutputSteering(toStructural(proto,parsed),cfg);const labels=[];if(opts.verbosity!==false&&decision.verbosityLevel>0&&steerSystemPrompt(parsed,proto,decision.verbosityLevel)){labels.push(`steering:L${decision.verbosityLevel}`)}if(decision.lowerEffort&&lowerEffort(parsed,proto)){labels.push("effort:low")}return labels}function inferWireProtocol(path53){const p2=path53.split("?",2)[0];if(p2.endsWith("/chat/completions")||p2.endsWith("/llm_raw_chat"))return"openai";if(p2.endsWith("/responses")||p2.endsWith("/responses/compact"))return"responses";if(googlePathKind(p2)!==null)return"google";return null}function installV1ResponseFramer(res){let buf="";const origWrite=res.write.bind(res);const origEnd=res.end.bind(res);const flushFrames=()=>{let out="";let idx;while((idx=buf.indexOf("\n\n"))>=0){out+=wrapV1SseFrame(buf.slice(0,idx))+"\n\n";buf=buf.slice(idx+2)}return out};const toStr=c=>typeof c==="string"?c:c==null?"":Buffer.isBuffer(c)?c.toString("utf8"):Buffer.from(c).toString("utf8");const pickCb=(a,b2)=>{if(typeof a==="function")return a;if(typeof b2==="function")return b2;return void 0};const wrapChunk=s3=>/(^|\n)\s*data:/.test(s3)?wrapV1SseFrame(s3):wrapV1ResponseJson(s3);res.write=((chunk,a,b2)=>{const cb=pickCb(a,b2);if(chunk==null){if(cb)setImmediate(cb);return true}buf+=toStr(chunk);const s3=flushFrames();if(s3.length>0)return origWrite(s3,cb);if(cb)setImmediate(cb);return true});res.end=((chunk,a,b2)=>{const cb=pickCb(a,b2);if(chunk!=null){buf+=toStr(chunk);const s3=flushFrames();if(s3.length>0)origWrite(s3)}if(buf.trim().length>0){origWrite(wrapChunk(buf));buf=""}return origEnd(cb)})}function armFailureShrink(prepared,log2,reason,est){const s3=prepared.session;if(!Number.isFinite(est)||est<=0)return;if(s3.stats.lastInputTokensSource==="overflow-arm")return;if(est>s3.stats.lastInputTokens){s3.stats.lastInputTokens=est;s3.stats.lastInputTokensSource="estimate";s3.stats.emergencyShrinkAt=Date.now();s3.stats.emergencyShrinkEstimate=est;markDirty(s3);log2("warn",`[${s3.id}] ${reason} with no usage report \u2014 armed emergency shrink with local estimate ${est} tokens`)}}function wsOversizeDiagnosis(sentBytes,stats,budget){const why=!stats||!stats.archived&&!stats.downscaled?"no sheddable images outside the protected recent messages":`shedding removed ${formatMiB2(Math.max(0,sentBytes-stats.finalBytes))} MiB but the remainder is protected recent content`;return`WS upstream rejected the ${formatMiB2(sentBytes)} MiB request with close 1009 (zero events received) and the payload cannot be reduced further (${why}). Trim older images/history so the frame fits under the wire limit (current pre-send budget: ${budget>0?`${formatMiB2(budget)} MiB`:"disabled"} \u2014 network.wsOutboundBytes / BILI_WS_OUTBOUND_BYTES).`}var UPSTREAM_FIRST_BYTE_WARN_MS=3e4;var firstByteWarnMs=UPSTREAM_FIRST_BYTE_WARN_MS;var firstByteWarnedOrigins=new Set;function armFirstByteWatchdog(o){const threshold=firstByteWarnMs;if(!Number.isFinite(threshold)||threshold<=0)return void 0;let origin;try{origin=new URL(o.url).origin}catch{origin=o.url}if(firstByteWarnedOrigins.has(origin))return void 0;if(o.signal.aborted)return void 0;const seconds=Math.round(threshold/1e3);const fire=()=>{if(firstByteWarnedOrigins.has(origin))return;firstByteWarnedOrigins.add(origin);o.log("warn",`[${o.sessionId}] upstream awaiting first byte \u2265${seconds}s: ${o.method} ${maskUrlForLog(o.url)} (lane=${o.lane})`)};const timer3=setTimeout(fire,threshold);timer3.unref();o.signal.addEventListener("abort",()=>clearTimeout(timer3),{once:true});return timer3}function forward(...args){return withCacheCapture(args[4]?.session,()=>forwardCaptured(...args))}async function forwardCaptured(req,res,opts,body,prepared,core,config,log2,route,instanceId,affinity,overflowRefold,v1Meta){const forwardStartedAt=Date.now();const reply=prepared&&!prepared.sidePassthrough?createHandoffReply(prepared.session,()=>!res.destroyed):void 0;if(prepared?.codexForge){log2("info",`[${prepared.session.id}] codex compact served locally (${prepared.codexForge.kind}); upstream not contacted`);if(!res.headersSent)res.writeHead(200,{"content-type":prepared.codexForge.contentType});res.end(prepared.codexForge.body);return}if(prepared?.autoModeForge){log2("info",`[${prepared.session.id}] auto-mode classifier served locally (${prepared.autoModeForge.variant}); upstream not contacted`);if(!res.headersSent)res.writeHead(200,{"content-type":prepared.autoModeForge.contentType});res.end(prepared.autoModeForge.body);return}let wireBody=body;let compatRoles=null;let compatProtocol=null;let compatDropPaths=[];const{upstreamUrl,headers,proxyUrl,skippedProxy}=buildForwardTarget(req,opts,route,affinity,prepared!==null?instanceId:void 0);const v1Active=v1Meta!==void 0&&prepared!==null;const v1Wrap=b2=>{if(!v1Active||typeof b2!=="string")return b2;try{return JSON.stringify(wrapV1Internal(JSON.parse(b2),v1Meta))}catch{return b2}};const resignCtx=inboundResignCredential(req.headers,opts,upstreamUrl);if(resignCtx!==void 0){log2("info",`[${prepared?.session.id??"passthrough"}] [resign] re-sign arm active (${APIG_RESIGN_SCHEME}) \u2014 every egress body is re-signed (#1884)`)}if(resignCtx===void 0){const laneCred=laneCredential(opts.routes,upstreamUrl,message=>log2("warn",`[${prepared?.session.id??"passthrough"}] ${message}`));if(laneCred!==void 0){applyLaneCredential(headers,laneCred,message=>log2("warn",`[${prepared?.session.id??"passthrough"}] ${message}`));log2("debug",`[${prepared?.session.id??"passthrough"}] [lane-credential] applied ${laneCred.reference} for ${maskUrlForLog(upstreamUrl)} (#2336)`)}}const applyResign=(hdrs,bodyStr)=>{if(resignCtx===void 0||req.method==="GET"||req.method==="HEAD")return;try{resignApig(hdrs,resignCtx,req.method??"POST",upstreamUrl,bodyStr,findRoute(opts.routes,upstreamUrl))}catch(err2){log2("warn",`[${prepared?.session.id??"passthrough"}] [resign] re-sign failed; sending the previous signature: ${String(err2)}`)}};const steerRaw=resolveCompress(opts.routes,upstreamUrl,void 0,opts.compress).outputSteering;const steerResolved=steerRaw!==void 0?resolveOutputSteeringConfig(steerRaw):null;const steerCfg=steerResolved?.config??null;for(const w2 of steerResolved?.warnings??[])log2("warn",`[${prepared?.session.id??"passthrough"}] [output-steering] ${w2}`);let steerProtocol=null;if(typeof body==="string"){const configured=resolveCompatRoles(opts.routes,upstreamUrl,opts.compat?.roles);const learned=prepared?.session.metadata.learnedCompatRoles??{};const roles={...configured,...learned};const protocol=prepared?.protocol??route?.explicitProtocol??resolveDeclaredProtocol(opts.routes,upstreamUrl)??inferWireProtocol(req.url??"");if(protocol==="openai"||protocol==="responses"){compatProtocol=protocol;if(Object.keys(roles).length>0){compatRoles=roles;const applied=applyCompatRoles(body,protocol,roles);if(applied.rewritten>0){wireBody=applied.body;log2("info",`[${prepared?.session.id??"passthrough"}] [compat] rewrote ${applied.rewritten} message role(s) per compat.roles (${Object.entries(roles).map(([f2,t])=>`${f2}\u2192${t}`).join(",")})`)}}}steerProtocol=protocol;if(steerCfg&&steerCfg.enabled&&typeof wireBody==="string"){const applied=applyOutputSteering(wireBody,protocol,steerCfg);if(applied.changed){wireBody=applied.body;log2("info",`[${prepared?.session.id??"passthrough"}] [output-steering] applied (${applied.labels.join(", ")})`)}}compatDropPaths=resolveCompatDropFields(opts.routes,upstreamUrl,opts.compat?.dropFields);if(compatDropPaths.length>0&&typeof wireBody==="string"){const applied=applyCompatDropFields(wireBody,compatDropPaths);if(applied.dropped>0){wireBody=applied.body;log2("info",`[${prepared?.session.id??"passthrough"}] [compat] dropped ${applied.dropped} field(s) per compat.dropFields (${compatDropPaths.join(", ")}) (#1757)`)}}}if(prepared&&!prepared.sidePassthrough&&prepared.processedMessages.length>0&&typeof wireBody==="string"&&opts.chainEgressStamp===true){try{const stamped=stampOutbound(JSON.parse(wireBody),prepared.protocol,instanceId);if(stamped!==null){wireBody=JSON.stringify(stamped);log2("debug",`[${prepared.session.id}] [stamp] outbound ${prepared.protocol} request carries checkpoint carrier`)}}catch(err2){log2("debug",`[${prepared.session.id}] [chain] outbound stamping failed (${String(err2)}); forwarding unstamped`)}}if(res.destroyed||res.writableEnded)return;const wireTransform=compatProtocol||steerCfg!==null&&steerCfg.enabled||compatDropPaths.length>0||v1Active?b2=>{if(compatProtocol&&compatRoles)applyCompatRolesJson(b2,compatProtocol,compatRoles);if(steerCfg&&steerCfg.enabled&&steerProtocol)applyOutputSteeringJson(b2,steerProtocol,steerCfg);if(compatDropPaths.length>0)dropCompatFieldsJson(b2,compatDropPaths);return v1Active?wrapV1Internal(b2,v1Meta):b2}:void 0;log2("info",currentFetchTransport()?`forward WS \u2192 ${maskUrlForLog(upstreamUrl.replace(/^http/,"ws"))}`:`forward ${req.method} \u2192 ${maskUrlForLog(upstreamUrl)}`);if(opts.debug&&prepared){const sid=prepared.session.id;const hdrKeys=Object.keys(req.headers);log2("info",`[${sid}] client headers: ${hdrKeys.join(",")}`);for(const k2 of["authorization","x-api-key","x-session-id","x-session-affinity","x-acp-session","x-opencode-session","prompt-cache-key","anthropic-beta"]){const v2=req.headers[k2]??req.headers[k2.toLowerCase()];if(v2){const s3=Array.isArray(v2)?v2.join(","):String(v2);const masked=CREDENTIAL_HEADER_RE.test(k2)?safePrefix(s3,8)+"..."+safeSuffix(s3,4)+` (${s3.length} chars)`:safePrefix(s3,60);log2("info",`[${sid}] client hdr ${k2}=${masked}`)}}}if(opts.debug||bodyDumpEnabled2()){const wireText=typeof wireBody==="string"?wireBody:wireBody.toString("utf8");try{const parsed=JSON.parse(wireText);if(opts.debug){const toolNames=(parsed.tools??[]).map(t=>{const fn=t.function;return fn?.name??t.name??"?"});log2("info",`[debug] tools=[${toolNames.join(",")}] msgs=${parsed.messages?.length??0} stream=${parsed.stream??false} system_len=${JSON.stringify(parsed.messages?.find(m2=>m2.role==="system")?.content??"").length}`)}if(bodyDumpEnabled2()&&dumpReqAllowed()){const dumpDir=dumpsDir();try{fs30.mkdirSync(dumpDir,{recursive:true})}catch{}const sid=prepared?.session.id??"unknown";const out=path52.join(dumpDir,`req-${Date.now()}-${safeSessionId(sid)}.json`);try{const pretty=JSON.stringify(JSON.parse(wireText),null,2);fs30.writeFileSync(out,`${DUMP_PLAINTEXT_BANNER}
|
|
7232
|
+
${block}`:block;return[updated,updated!==existing]}function asRecord2(v2){return v2&&typeof v2==="object"&&!Array.isArray(v2)?v2:null}function normalizeAnthropic(messages){if(!Array.isArray(messages)||messages.length===0)return[];const last=asRecord2(messages[messages.length-1]);if(!last||last.role!=="user")return[{role:"user",text:""}];const content=last.content;if(typeof content==="string")return[{role:"user",text:content}];if(!Array.isArray(content)||content.length===0)return[{role:"user",text:""}];const blocks=[];for(const raw of content){const b2=asRecord2(raw);if(!b2)return[{role:"user",text:""}];const t=b2.type;if(t==="tool_result")blocks.push({kind:"tool_result",isError:b2.is_error===true});else if(t==="text"||t==="image"||t==="document")blocks.push({kind:t});else return[{role:"user",text:""}]}return[{role:"user",blocks}]}function normalizeOpenAi(messages){if(!Array.isArray(messages)||messages.length===0)return[];const last=asRecord2(messages[messages.length-1]);if(!last)return[{role:"user",text:""}];if(last.role==="tool"){let i=messages.length-1;while(i>=0&&asRecord2(messages[i])?.role==="tool")i--;const n=messages.length-1-i;const blocks=[];for(let k2=0;k2<n;k2++)blocks.push({kind:"tool_result"});return[{role:"user",blocks}]}if(last.role==="user"){const c=last.content;if(typeof c==="string")return[{role:"user",text:c}];if(Array.isArray(c)){for(const raw of c){const b2=asRecord2(raw);if(b2&&b2.type==="text"&&typeof b2.text==="string"&&b2.text.trim())return[{role:"user",blocks:[{kind:"text"}]}]}}}return[{role:"user",text:""}]}var RESPONSES_OUTPUT_TYPES=new Set(["custom_tool_call_output","function_call_output","local_shell_call_output","apply_patch_call_output"]);var RESPONSES_NEUTRAL_TYPES=new Set(["message","function_call","custom_tool_call","local_shell_call","apply_patch_call","reasoning"]);function responsesIsUserSignal(item){if(item.type==="input_text")return typeof item.text==="string"&&item.text.trim()!=="";if(item.type==="input_image"||item.type==="input_file")return true;if(item.role==="user"){const c=item.content??item.input;if(typeof c==="string")return c.trim()!=="";if(Array.isArray(c)){for(const raw of c){const b2=asRecord2(raw);if(!b2)continue;if((b2.type==="input_text"||b2.type==="text")&&typeof b2.text==="string"&&b2.text.trim())return true;if(b2.type==="input_image"||b2.type==="input_file")return true}}}return false}function normalizeResponses(input){if(typeof input==="string")return[{role:"user",text:input}];if(!Array.isArray(input)||input.length===0)return[{role:"user",text:""}];const last=asRecord2(input[input.length-1]);if(last&&responsesIsUserSignal(last))return[{role:"user",blocks:[{kind:"text"}]}];let foundOutput=false;for(let i=input.length-1;i>=0;i--){const item=asRecord2(input[i]);if(!item)break;const t=typeof item.type==="string"?item.type:"";if(RESPONSES_OUTPUT_TYPES.has(t)){foundOutput=true;break}if(RESPONSES_NEUTRAL_TYPES.has(t))continue;break}if(foundOutput)return[{role:"user",blocks:[{kind:"tool_result"}]}];return[{role:"user",text:""}]}function normalizeGoogle(contents){if(!Array.isArray(contents)||contents.length===0)return[];const last=asRecord2(contents[contents.length-1]);if(!last||last.role!=="user")return[{role:"user",text:""}];const parts=last.parts;if(!Array.isArray(parts)||parts.length===0)return[{role:"user",text:""}];const blocks=[];for(const raw of parts){const p2=asRecord2(raw);if(!p2)return[{role:"user",text:""}];if(p2.functionResponse)blocks.push({kind:"tool_result"});else if(typeof p2.text==="string"){if(p2.text.trim()!=="")blocks.push({kind:"text"})}else if(p2.inlineData||p2.fileData||p2.videoMetadata)blocks.push({kind:"image"});else return[{role:"user",text:""}]}return[{role:"user",blocks}]}function toStructural(protocol,obj){switch(protocol){case"anthropic":return normalizeAnthropic(obj.messages);case"openai":return normalizeOpenAi(obj.messages);case"responses":return normalizeResponses(obj.input);case"google":return normalizeGoogle(obj.contents)}}function steerSystemPrompt(obj,protocol,level){const block=steeringText(level);if(!block)return false;switch(protocol){case"anthropic":return steerAnthropicSystem(obj,block);case"openai":return steerOpenAiSystem(obj,block);case"responses":return steerResponsesInstructions(obj,block);case"google":return steerGoogleSystem(obj,block)}}function steerAnthropicSystem(obj,block){const sys=obj.system;if(sys===void 0)return false;if(typeof sys==="string"){const[updated,changed]=replaceOrAppend(sys,block);if(changed)obj.system=updated;return changed}if(Array.isArray(sys)){for(const raw of sys){const b2=asRecord2(raw);if(!b2)continue;const t=typeof b2.text==="string"?b2.text:"";if(t.startsWith(SENTINEL)){if(t===block)return false;b2.text=block;return true}}sys.push({type:"text",text:block});return true}return false}function steerOpenAiSystem(obj,block){const msgs=obj.messages;if(!Array.isArray(msgs))return false;const arr=msgs;let target=null;for(let i=arr.length-1;i>=0;i--){const m2=arr[i];if(m2&&typeof m2==="object"&&(m2.role==="system"||m2.role==="developer")){target=m2;break}}if(!target)return false;const content=target.content;if(content===null||content===void 0){target.content=block;return true}if(typeof content==="string"){const[updated,changed]=replaceOrAppend(content,block);if(changed)target.content=updated;return changed}if(Array.isArray(content)){for(const raw of content){const b2=asRecord2(raw);if(!b2)continue;if(b2.type==="text"&&typeof b2.text==="string"&&b2.text.startsWith(SENTINEL)){if(b2.text===block)return false;b2.text=block;return true}}content.push({type:"text",text:block});return true}return false}function steerResponsesInstructions(obj,block){const ins=obj.instructions;if(ins===void 0)return false;if(typeof ins!=="string")return false;const[updated,changed]=replaceOrAppend(ins,block);if(changed)obj.instructions=updated;return changed}function steerGoogleSystem(obj,block){const si2=asRecord2(obj.systemInstruction);if(!si2)return false;const parts=si2.parts;if(!Array.isArray(parts))return false;for(const raw of parts){const p2=asRecord2(raw);if(!p2)continue;const t=typeof p2.text==="string"?p2.text:"";if(t.startsWith(SENTINEL)){if(t===block)return false;p2.text=block;return true}}parts.push({text:block});return true}var ANTHROPIC_MIN_THINKING_BUDGET=1024;var GOOGLE_MIN_THINKING_BUDGET=128;function lowerEffort(obj,protocol){switch(protocol){case"openai":{const v2=clampEffortToFloor(obj.reasoning_effort,"low");if(v2!==null){obj.reasoning_effort=v2;return true}return false}case"responses":{const r=asRecord2(obj.reasoning);if(!r)return false;const v2=clampEffortToFloor(r.effort,"low");if(v2!==null){r.effort=v2;return true}return false}case"anthropic":{let changed=false;const oc=asRecord2(obj.output_config);if(oc){const v2=clampEffortToFloor(oc.effort,"low");if(v2!==null){oc.effort=v2;changed=true}}const th=asRecord2(obj.thinking);if(th&&typeof th.budget_tokens==="number"&&th.budget_tokens>ANTHROPIC_MIN_THINKING_BUDGET){th.budget_tokens=ANTHROPIC_MIN_THINKING_BUDGET;changed=true}return changed}case"google":{const gc=asRecord2(obj.generationConfig);const tc=gc?asRecord2(gc.thinkingConfig):null;if(tc&&typeof tc.thinkingBudget==="number"&&tc.thinkingBudget>GOOGLE_MIN_THINKING_BUDGET){tc.thinkingBudget=GOOGLE_MIN_THINKING_BUDGET;return true}return false}}}function detectProtocolFromBody(obj){if(Array.isArray(obj.input))return"responses";if(Array.isArray(obj.contents))return"google";if(Array.isArray(obj.messages)){return obj.system!==void 0?"anthropic":"openai"}return null}function applyOutputSteering(body,protocol,cfg){if(!cfg.enabled)return{body,changed:false,labels:[]};let obj;try{obj=JSON.parse(body)}catch{return{body,changed:false,labels:[]}}const proto=protocol??detectProtocolFromBody(obj);if(!proto)return{body,changed:false,labels:[]};const labels=applyOutputSteeringJson(obj,proto,cfg);if(labels.length===0)return{body,changed:false,labels:[]};return{body:JSON.stringify(obj),changed:true,labels}}function applyOutputSteeringJson(parsed,protocol,cfg,opts={}){if(!cfg.enabled)return[];const proto=protocol??detectProtocolFromBody(parsed);if(!proto)return[];const decision=decideOutputSteering(toStructural(proto,parsed),cfg);const labels=[];if(opts.verbosity!==false&&decision.verbosityLevel>0&&steerSystemPrompt(parsed,proto,decision.verbosityLevel)){labels.push(`steering:L${decision.verbosityLevel}`)}if(decision.lowerEffort&&lowerEffort(parsed,proto)){labels.push("effort:low")}return labels}function inferWireProtocol(path53){const p2=path53.split("?",2)[0];if(p2.endsWith("/chat/completions")||p2.endsWith("/llm_raw_chat"))return"openai";if(p2.endsWith("/responses")||p2.endsWith("/responses/compact"))return"responses";if(googlePathKind(p2)!==null)return"google";return null}function installV1ResponseFramer(res){let buf="";const origWrite=res.write.bind(res);const origEnd=res.end.bind(res);const flushFrames=()=>{let out="";let idx;while((idx=buf.indexOf("\n\n"))>=0){out+=wrapV1SseFrame(buf.slice(0,idx))+"\n\n";buf=buf.slice(idx+2)}return out};const toStr=c=>typeof c==="string"?c:c==null?"":Buffer.isBuffer(c)?c.toString("utf8"):Buffer.from(c).toString("utf8");const pickCb=(a,b2)=>{if(typeof a==="function")return a;if(typeof b2==="function")return b2;return void 0};const wrapChunk=s3=>/(^|\n)\s*data:/.test(s3)?wrapV1SseFrame(s3):wrapV1ResponseJson(s3);res.write=((chunk,a,b2)=>{const cb=pickCb(a,b2);if(chunk==null){if(cb)setImmediate(cb);return true}buf+=toStr(chunk);const s3=flushFrames();if(s3.length>0)return origWrite(s3,cb);if(cb)setImmediate(cb);return true});res.end=((chunk,a,b2)=>{const cb=pickCb(a,b2);if(chunk!=null){buf+=toStr(chunk);const s3=flushFrames();if(s3.length>0)origWrite(s3)}if(buf.trim().length>0){origWrite(wrapChunk(buf));buf=""}return origEnd(cb)})}function armFailureShrink(prepared,log2,reason,est){const s3=prepared.session;if(!Number.isFinite(est)||est<=0)return;if(s3.stats.lastInputTokensSource==="overflow-arm")return;if(est>s3.stats.lastInputTokens){s3.stats.lastInputTokens=est;s3.stats.lastInputTokensSource="estimate";s3.stats.emergencyShrinkAt=Date.now();s3.stats.emergencyShrinkEstimate=est;markDirty(s3);log2("warn",`[${s3.id}] ${reason} with no usage report \u2014 armed emergency shrink with local estimate ${est} tokens`)}}function wsOversizeDiagnosis(sentBytes,stats,budget){const why=!stats||!stats.archived&&!stats.downscaled?"no sheddable images outside the protected recent messages":`shedding removed ${formatMiB2(Math.max(0,sentBytes-stats.finalBytes))} MiB but the remainder is protected recent content`;return`WS upstream rejected the ${formatMiB2(sentBytes)} MiB request with close 1009 (zero events received) and the payload cannot be reduced further (${why}). Trim older images/history so the frame fits under the wire limit (current pre-send budget: ${budget>0?`${formatMiB2(budget)} MiB`:"disabled"} \u2014 network.wsOutboundBytes / BILI_WS_OUTBOUND_BYTES).`}var UPSTREAM_FIRST_BYTE_WARN_MS=3e4;var firstByteWarnMs=UPSTREAM_FIRST_BYTE_WARN_MS;var firstByteWarnedOrigins=new Set;function armFirstByteWatchdog(o){const threshold=firstByteWarnMs;if(!Number.isFinite(threshold)||threshold<=0)return void 0;let origin;try{origin=new URL(o.url).origin}catch{origin=o.url}if(firstByteWarnedOrigins.has(origin))return void 0;if(o.signal.aborted)return void 0;const seconds=Math.round(threshold/1e3);const fire2=()=>{if(firstByteWarnedOrigins.has(origin))return;firstByteWarnedOrigins.add(origin);o.log("warn",`[${o.sessionId}] upstream awaiting first byte \u2265${seconds}s: ${o.method} ${maskUrlForLog(o.url)} (lane=${o.lane})`)};const timer3=setTimeout(fire2,threshold);timer3.unref();o.signal.addEventListener("abort",()=>clearTimeout(timer3),{once:true});return timer3}function forward(...args){return withCacheCapture(args[4]?.session,()=>forwardCaptured(...args))}async function forwardCaptured(req,res,opts,body,prepared,core,config,log2,route,instanceId,affinity,overflowRefold,v1Meta){const forwardStartedAt=Date.now();const reply=prepared&&!prepared.sidePassthrough?createHandoffReply(prepared.session,()=>!res.destroyed):void 0;if(prepared?.codexForge){log2("info",`[${prepared.session.id}] codex compact served locally (${prepared.codexForge.kind}); upstream not contacted`);if(!res.headersSent)res.writeHead(200,{"content-type":prepared.codexForge.contentType});res.end(prepared.codexForge.body);return}if(prepared?.autoModeForge){log2("info",`[${prepared.session.id}] auto-mode classifier served locally (${prepared.autoModeForge.variant}); upstream not contacted`);if(!res.headersSent)res.writeHead(200,{"content-type":prepared.autoModeForge.contentType});res.end(prepared.autoModeForge.body);return}let wireBody=body;let compatRoles=null;let compatProtocol=null;let compatDropPaths=[];const{upstreamUrl,headers,proxyUrl,skippedProxy}=buildForwardTarget(req,opts,route,affinity,prepared!==null?instanceId:void 0);const v1Active=v1Meta!==void 0&&prepared!==null;const v1Wrap=b2=>{if(!v1Active||typeof b2!=="string")return b2;try{return JSON.stringify(wrapV1Internal(JSON.parse(b2),v1Meta))}catch{return b2}};const resignCtx=inboundResignCredential(req.headers,opts,upstreamUrl);if(resignCtx!==void 0){log2("info",`[${prepared?.session.id??"passthrough"}] [resign] re-sign arm active (${APIG_RESIGN_SCHEME}) \u2014 every egress body is re-signed (#1884)`)}if(resignCtx===void 0){const laneCred=laneCredential(opts.routes,upstreamUrl,message=>log2("warn",`[${prepared?.session.id??"passthrough"}] ${message}`));if(laneCred!==void 0){applyLaneCredential(headers,laneCred,message=>log2("warn",`[${prepared?.session.id??"passthrough"}] ${message}`));log2("debug",`[${prepared?.session.id??"passthrough"}] [lane-credential] applied ${laneCred.reference} for ${maskUrlForLog(upstreamUrl)} (#2336)`)}}const applyResign=(hdrs,bodyStr)=>{if(resignCtx===void 0||req.method==="GET"||req.method==="HEAD")return;try{resignApig(hdrs,resignCtx,req.method??"POST",upstreamUrl,bodyStr,findRoute(opts.routes,upstreamUrl))}catch(err2){log2("warn",`[${prepared?.session.id??"passthrough"}] [resign] re-sign failed; sending the previous signature: ${String(err2)}`)}};const steerRaw=resolveCompress(opts.routes,upstreamUrl,void 0,opts.compress).outputSteering;const steerResolved=steerRaw!==void 0?resolveOutputSteeringConfig(steerRaw):null;const steerCfg=steerResolved?.config??null;for(const w2 of steerResolved?.warnings??[])log2("warn",`[${prepared?.session.id??"passthrough"}] [output-steering] ${w2}`);let steerProtocol=null;if(typeof body==="string"){const configured=resolveCompatRoles(opts.routes,upstreamUrl,opts.compat?.roles);const learned=prepared?.session.metadata.learnedCompatRoles??{};const roles={...configured,...learned};const protocol=prepared?.protocol??route?.explicitProtocol??resolveDeclaredProtocol(opts.routes,upstreamUrl)??inferWireProtocol(req.url??"");if(protocol==="openai"||protocol==="responses"){compatProtocol=protocol;if(Object.keys(roles).length>0){compatRoles=roles;const applied=applyCompatRoles(body,protocol,roles);if(applied.rewritten>0){wireBody=applied.body;log2("info",`[${prepared?.session.id??"passthrough"}] [compat] rewrote ${applied.rewritten} message role(s) per compat.roles (${Object.entries(roles).map(([f2,t])=>`${f2}\u2192${t}`).join(",")})`)}}}steerProtocol=protocol;if(steerCfg&&steerCfg.enabled&&typeof wireBody==="string"){const applied=applyOutputSteering(wireBody,protocol,steerCfg);if(applied.changed){wireBody=applied.body;log2("info",`[${prepared?.session.id??"passthrough"}] [output-steering] applied (${applied.labels.join(", ")})`)}}compatDropPaths=resolveCompatDropFields(opts.routes,upstreamUrl,opts.compat?.dropFields);if(compatDropPaths.length>0&&typeof wireBody==="string"){const applied=applyCompatDropFields(wireBody,compatDropPaths);if(applied.dropped>0){wireBody=applied.body;log2("info",`[${prepared?.session.id??"passthrough"}] [compat] dropped ${applied.dropped} field(s) per compat.dropFields (${compatDropPaths.join(", ")}) (#1757)`)}}}if(prepared&&!prepared.sidePassthrough&&prepared.processedMessages.length>0&&typeof wireBody==="string"&&opts.chainEgressStamp===true){try{const stamped=stampOutbound(JSON.parse(wireBody),prepared.protocol,instanceId);if(stamped!==null){wireBody=JSON.stringify(stamped);log2("debug",`[${prepared.session.id}] [stamp] outbound ${prepared.protocol} request carries checkpoint carrier`)}}catch(err2){log2("debug",`[${prepared.session.id}] [chain] outbound stamping failed (${String(err2)}); forwarding unstamped`)}}if(res.destroyed||res.writableEnded)return;const wireTransform=compatProtocol||steerCfg!==null&&steerCfg.enabled||compatDropPaths.length>0||v1Active?b2=>{if(compatProtocol&&compatRoles)applyCompatRolesJson(b2,compatProtocol,compatRoles);if(steerCfg&&steerCfg.enabled&&steerProtocol)applyOutputSteeringJson(b2,steerProtocol,steerCfg);if(compatDropPaths.length>0)dropCompatFieldsJson(b2,compatDropPaths);return v1Active?wrapV1Internal(b2,v1Meta):b2}:void 0;log2("info",currentFetchTransport()?`forward WS \u2192 ${maskUrlForLog(upstreamUrl.replace(/^http/,"ws"))}`:`forward ${req.method} \u2192 ${maskUrlForLog(upstreamUrl)}`);if(opts.debug&&prepared){const sid=prepared.session.id;const hdrKeys=Object.keys(req.headers);log2("info",`[${sid}] client headers: ${hdrKeys.join(",")}`);for(const k2 of["authorization","x-api-key","x-session-id","x-session-affinity","x-acp-session","x-opencode-session","prompt-cache-key","anthropic-beta"]){const v2=req.headers[k2]??req.headers[k2.toLowerCase()];if(v2){const s3=Array.isArray(v2)?v2.join(","):String(v2);const masked=CREDENTIAL_HEADER_RE.test(k2)?safePrefix(s3,8)+"..."+safeSuffix(s3,4)+` (${s3.length} chars)`:safePrefix(s3,60);log2("info",`[${sid}] client hdr ${k2}=${masked}`)}}}if(opts.debug||bodyDumpEnabled2()){const wireText=typeof wireBody==="string"?wireBody:wireBody.toString("utf8");try{const parsed=JSON.parse(wireText);if(opts.debug){const toolNames=(parsed.tools??[]).map(t=>{const fn=t.function;return fn?.name??t.name??"?"});log2("info",`[debug] tools=[${toolNames.join(",")}] msgs=${parsed.messages?.length??0} stream=${parsed.stream??false} system_len=${JSON.stringify(parsed.messages?.find(m2=>m2.role==="system")?.content??"").length}`)}if(bodyDumpEnabled2()&&dumpReqAllowed()){const dumpDir=dumpsDir();try{fs30.mkdirSync(dumpDir,{recursive:true})}catch{}const sid=prepared?.session.id??"unknown";const out=path52.join(dumpDir,`req-${Date.now()}-${safeSessionId(sid)}.json`);try{const pretty=JSON.stringify(JSON.parse(wireText),null,2);fs30.writeFileSync(out,`${DUMP_PLAINTEXT_BANNER}
|
|
7233
7233
|
${pretty}`)}catch{fs30.writeFileSync(out,`${DUMP_PLAINTEXT_BANNER}
|
|
7234
7234
|
${wireText}`)}log2("info",`[debug] forwarded body written to ${out}`);gcDumpDirIfConfigured(dumpDir)}}catch{}}if(opts.debug){const hdrLog={};for(const[hk,hv]of Object.entries(headers)){if(typeof hv==="string"){const masked=maskHeaderForLog(hk,hv);hdrLog[hk]=masked.length>200?masked.slice(0,200)+"...":masked}}log2("info",`[${prepared?.session.id??"unknown"}] \u2192 upstream headers: ${JSON.stringify(hdrLog)}`)}const rawBase=bodyDumpEnabled2()?(()=>{try{const rawDir=rawDumpDir();fs30.mkdirSync(rawDir,{recursive:true});return path52.join(rawDir,`${Date.now()}-${safeSessionId(prepared?.session.id)}`)}catch{return""}})():"";if(rawBase){try{const hdrText=Object.entries(maskHeadersForLog(headers)).map(([k2,v2])=>`${k2}: ${v2}`).join("\n");const bodyText=req.method==="GET"||req.method==="HEAD"?"":typeof wireBody==="string"?wireBody:Buffer.from(wireBody).toString("utf8");const reqPath=`${rawBase}-REQ.txt`;fs30.writeFileSync(reqPath,`${DUMP_PLAINTEXT_BANNER}
|
|
7235
7235
|
${req.method??"POST"} ${maskUrlForLog(upstreamUrl)}
|
|
@@ -7241,7 +7241,7 @@ ${hdrText}
|
|
|
7241
7241
|
|
|
7242
7242
|
${buildAbsorbSystemPrompt(absorbToolName(loopConfig))}`:"";const visibilityMarkers=resolveCompress(opts.routes,route?.rewrittenUrl,parsedReq.model??prepared.model,opts.compress).visibilityMarkers??true;const genBoundaryNote=detectGenerationBoundary(prepared.session,prepared.originalMessages,log2)?`
|
|
7243
7243
|
|
|
7244
|
-
${GENERATION_BOUNDARY_NOTE}`:"";const systemPrompt=withProjectAttribution(withMcpDialectNote(withMarkerIntegrityNote(withSummaryBudgetNote(textProtocol?buildCompressHybridSystemPrompt(prepared.prompts??defaultPrompts,messageTimestampSections(conversationPromptSections(prepared.surface?.promptSections,externalSummaryEnabled(config)),"hybrid")):buildCompressSystemPrompt(prepared.prompts??defaultPrompts,messageTimestampSections(conversationPromptSections(prepared.surface?.promptSections,externalSummaryEnabled(config)))),externalSummaryEnabled(config)),visibilityMarkers),prepared.mcpDialectNote===true))+genBoundaryNote+absorbSection;const adapter=pickAdapter(prepared.protocol,parsedReq,textProtocol,prepared.responsesProjection,prepared.anthropicSystem,prepared.openaiSystemText,absorbActive?absorbToolName(loopConfig):void 0,prepared.google,prepared.systemNotes,opts.streamErrorShape,prepared.anthropicCacheMarks,prepared.anthropicClientCacheControls,absorbActive);const refreshFolded=async current=>{return withSessionLock(prepared.session,async()=>{const turn=core.processTurn({messages:prepared.originalMessages,state:prepared.session.state,config:loopConfig,tokenCount:usageGradeInputBaseline(prepared.session),renderTags:prepared.renderTags??"text-only",contentStore:contentStoreOf(prepared.session)});prepared.session.state=turn.state;adoptContentStore(prepared.session,turn.contentStore);const viewed=applyAbsorbView(turn.messages,turn.state,loopConfig,effectiveTokenCount(prepared.session,turn.messages).tokens);const records=current.filter(m2=>typeof m2.id==="string"&&m2.id.startsWith("acp_loop_"));const out=[...stripKernelSummaries(viewed,turn.state),...records];const dropped=prepared.dropReasoning?prepared.dropReasoning(out):out;const ordered=prepared.protocol==="responses"?repairResponsesAssistantOrdering(dropped,prepared.originalMessages):dropped;return ordered})};const loopDumpDir=opts.dumpSse;const loopBillingUpstream=route?.rewrittenUrl??(/^https?:\/\//i.test(req.url??"")?req.url??void 0:opts.upstream);const loop=runCompressLoop(responseBody,{core,config,messages:prepared.processedMessages.length>0?prepared.processedMessages:prepared.originalMessages,compressMessages:prepared.originalMessages,session:prepared.session,reply,log:ctx.log,proxyUrl,skippedProxy,upstreamOrigin:targetOrigin,protocol:prepared.protocol,textProtocol,debug:opts.debug,refreshFolded,visibilityMarkers,dumpSse:loopDumpDir?(name,stream2)=>dumpStreamToFile(stream2,loopDumpDir,name):void 0,imageLearn:{host:upstreamHost(loopBillingUpstream),fp:`${imageBillingFor5(opts,loopBillingUpstream)}:${imageTokenCapFor5(opts,loopBillingUpstream)}`}},parsedReq,{url:upstreamUrl,headers:reqHeaders,wireTransform,resign:applyResign,responseStreamTransform:v1Active?v1UnwrapStream:void 0},adapter,systemPrompt,clientAbort.signal);let protocolFragmentWarned=false;for await(const chunk of loop){if(res.destroyed||res.writableEnded)break;{const s3=chunk.toString("utf8");if(s3.includes("<acp ")||s3.includes("</acp")){log2("warn",`[${prepared.session.id}] [tag-echo] detected: ${prepared.protocol} response stream contains <acp tag`)}else if(!protocolFragmentWarned&&containsToolCallXmlFragment(s3)){protocolFragmentWarned=true;log2("warn",`[${prepared.session.id}] [tag-echo] detected: ${prepared.protocol} response stream contains tool-call XML fragment (left untouched)`)}}res.write(chunk);if(res.writableNeedDrain){await awaitDrain(res)}if(res.destroyed||res.writableEnded)break}res.end()}catch(e){emitStreamError(res,prepared.protocol,e?.message??String(e),m2=>log2("error",`[${prepared.session.id}] ${m2}`),opts.streamErrorShape)}finally{clearUpstreamTimer();if(dumpRaw)await dumpRaw;markDirty(prepared.session)}}else{try{const buf=responseBody?Buffer.from(await new Response(responseBody).arrayBuffer()):Buffer.alloc(0);let text2=Buffer.from(buf).toString("utf8");try{let json=JSON.parse(text2);if(prepared.protocol==="responses"&&prepared.responsesTextProtocol){const requestBody=JSON.parse(typeof body==="string"?body:body.toString("utf8"));const requestHeaders=buildForwardHeaders(headers);const visibilityMarkers=resolveCompress(opts.routes,route?.rewrittenUrl,requestBody.model,opts.compress).visibilityMarkers??true;json=await compressLoopResponsesJson(json,{core,config,messages:prepared.originalMessages,session:prepared.session,log:ctx.log,proxyUrl,textProtocol:true,visibilityMarkers,signal:clientAbort.signal},requestBody,{url:upstreamUrl,headers:requestHeaders,wireTransform,resign:applyResign})}const rawUsage=prepared.protocol==="google"?json.usageMetadata??json.usage:json.usage;const u2=rawUsage??{};const{total,cached,creation}=usageTotals(prepared.protocol,u2);const out=usageOutputTotal(prepared.protocol,u2);const reportedCached=typeof cached==="number"?cached:null;const billed=typeof total==="number"?total:0;if(billed>0||reportedCached!==null){settleUsageReport(prepared.session,{total:billed,reportedCached,output:out,protocol:prepared.protocol,upstream:targetOrigin,creation});if(reportedCached!==null)warnCacheCollapse(prepared.session,billed,reportedCached);const hitPct2=reportedCached!==null&&billed>0?Math.round(100*reportedCached/billed):void 0;log("info",`[${prepared.session.id}] [acp-usage] input=${billed} ${hitPct2===void 0?"(no cache report)":`cached=${reportedCached} (cache hit ${hitPct2}%)`}${billed<=0?" (zero-total: lastInputTokens kept)":""}`)}else{diagnoseSuccessWithoutUsage(prepared.session,"proxy-json")}if(typeof out==="number"){prepared.session.stats.outputTokens+=out;billOutputUsage(prepared.session,out)}if(prepared.protocol==="openai"){await withSessionLock(prepared.session,()=>rewriteOpenaiJsonResponseAsync(json,ctx,clientAbort.signal))}else if(prepared.protocol==="responses"){await withSessionLock(prepared.session,()=>rewriteResponsesJsonResponseAsync(json,ctx,clientAbort.signal))}else if(prepared.protocol==="google"){await withSessionLock(prepared.session,()=>rewriteGoogleJsonResponseAsync(json,ctx,clientAbort.signal))}else{await withSessionLock(prepared.session,()=>rewriteJsonResponseAsync(json,ctx,clientAbort.signal))}captureHandoffJson(reply,prepared.protocol,json);reply?.save();res.end(JSON.stringify(json))}catch{res.end(text2)}}finally{clearUpstreamTimer();markDirty(prepared.session)}}}finally{clearUpstreamTimer();if(dumpRaw)await dumpRaw}}async function resolveFakeCompletion(stream2,opts){let buffer=await readStreamToBuffer(stream2,fakeBufCap());const max=maxFakeCompletionRetries();const sid=opts.session.id;const priorStreak=opts.session.metadata.fakeCompletionStreak??0;if(max>0&&priorStreak<max&&isFakeCompletion(opts.protocol,buffer.toString("utf8"))){for(let attempt=1;attempt<=max&&!opts.signal.aborted;attempt++){const hinted=injectFakeCompletionHint(opts.protocol,opts.wireBody);if(hinted===null)break;const wireHinted=opts.wrapBody?opts.wrapBody(hinted):hinted;opts.log("warn",`[${sid}] fake completion (tool-call XML, no tool block); retry ${attempt}/${max} with corrective hint`);let r;try{opts.resign?.(opts.reqHeaders,wireHinted);r=await fetchWithTimeout(opts.upstreamUrl,{method:"POST",headers:opts.reqHeaders,body:wireHinted,...opts.proxyUrl?{dispatcher:proxyDispatcher(opts.proxyUrl)}:{}},void 0,opts.signal)}catch(e){opts.log("warn",`[${sid}] fake-completion retry failed: ${String(e)}; presenting original`);break}try{if(!r.response.ok||!r.response.body){opts.log("warn",`[${sid}] fake-completion retry rejected (HTTP ${r.response.status}); presenting original`);break}buffer=await readStreamToBuffer(r.response.body,fakeBufCap())}finally{r.clearTimer()}if(!isFakeCompletion(opts.protocol,buffer.toString("utf8")))break}}const stillFake=isFakeCompletion(opts.protocol,buffer.toString("utf8"));opts.session.metadata.fakeCompletionStreak=stillFake?priorStreak+1:0;markDirty(opts.session);return buffer}var warnedWireDropKeys=new Set;var WARNED_WIREDROP_KEY_CAP=4096;function warnDroppedOpenaiParts(parsed,sessionId,log2){const report=droppedOpenaiParts(parsed);if(!report)return;const key2=`${sessionId}:${report.types.join(",")}`;if(warnedWireDropKeys.has(key2))return;warnedWireDropKeys.add(key2);if(warnedWireDropKeys.size>WARNED_WIREDROP_KEY_CAP){warnedWireDropKeys.delete(warnedWireDropKeys.values().next().value)}log2("warn",`[${sessionId}] wire codec will drop ${report.count} non-user content part(s) with unrecognized type(s) [${report.types.join(", ")}] (first at message #${report.firstIndex}) \u2014 kernel 0.0.85+ preserves all user-message parts (DeepSeek Files API refs included, #1205/#1188) and mid-conversation system/developer messages ride verbatim (#4166), but parts riding assistant/tool messages and the leading system/developer run still reduce to text-only`)}var NON_CONVERSATION_RELAY_WARN_CAP=4096;var nonConversationRelayWarned=new Set;function selfAddressedLocalPath(reqUrl,localPort){if(!reqUrl.startsWith("http://")&&!reqUrl.startsWith("https://"))return void 0;if(localPort===void 0)return void 0;try{const u2=new URL(reqUrl);const port=u2.port!==""?Number(u2.port):u2.protocol==="https:"?443:80;if(port!==localPort)return void 0;const host=u2.hostname.replace(/^\[|\]$/g,"").toLowerCase();const mine=host==="0.0.0.0"||host==="::"||host==="localhost"||localMachineIps().has(normalizeIpLiteral(host));if(!mine)return void 0;return u2.pathname+u2.search}catch{}return void 0}function resolveUpstream(_opts,reqUrl,req){const mitmUpstream=readMitmUpstream(req?.socket);if(mitmUpstream){const mitmKey=mitmUpstream.replace(/^https:\/\//,"mitm://");return{upstream:mitmUpstream,rewrittenUrl:mitmKey+(reqUrl??"")}}const KNOWN_PROTOCOLS=["responses","anthropic","openai","google"];if(reqUrl.startsWith("/bili/")){let rest=reqUrl.slice(6);let explicitProtocol;for(const p2 of KNOWN_PROTOCOLS){const prefix=`${p2}/`;if(rest.startsWith(prefix+"http://")||rest.startsWith(prefix+"https://")){explicitProtocol=p2;rest=rest.slice(prefix.length);break}}if(rest.startsWith("http://")||rest.startsWith("https://")){try{const u2=new URL(rest);return{upstream:`${u2.protocol}//${u2.host}`,rewrittenUrl:rest,explicitProtocol,tunnel:true}}catch{}}}if(reqUrl.startsWith("http://")||reqUrl.startsWith("https://")){try{const u2=new URL(reqUrl);return{upstream:`${u2.protocol}//${u2.host}`,rewrittenUrl:reqUrl,tunnel:true}}catch{}}return void 0}var requestAborts=new WeakMap;function registerRequestAbort(res,ac){if(requestAborts.get(res)?.signal.aborted||res.destroyed||res.writableEnded||res.socket?.destroyed)ac.abort();requestAborts.set(res,ac)}function googlePathKind(urlPath){if(urlPath.includes(":streamGenerateContent"))return"stream-generate";if(urlPath.includes(":generateContent"))return"generate";if(urlPath.includes(":countTokens"))return"count-tokens";return null}function googleModelFromPath(urlPath){const m2=/\/models\/([^/:?]+):(?:streamGenerateContent|generateContent|countTokens)\b/.exec(urlPath);if(!m2||!m2[1])return void 0;try{return decodeURIComponent(m2[1])}catch{return m2[1]}}function vertexAnthropicModelFromPath(urlPath){const m2=/\/publishers\/anthropic\/models\/([^/:?]+):(?:streamRawPredict|rawPredict)\b/.exec(urlPath);if(!m2||!m2[1])return void 0;try{return decodeURIComponent(m2[1])}catch{return m2[1]}}async function createEngineContext(opts){const filePath=configureLogger(opts.logFile??defaultLogFile());if(shouldMuteStderrLegAfterFileLive(Boolean(process.env.BILI_LAUNCH_TOKEN?.trim()),process.stderr.isTTY)){onFileLegLive(()=>muteStderrLeg())}const core=createCore(resolveMessageTimestamps(opts.compress)?{timestamps:true}:void 0);const config=opts.kernelConfig;const log2=(level,msg)=>logMsg(opts,level,msg);const instanceId=randomUUID12();const instanceStartedAt=Date.now();let bootReady=false;const parentWatchPid=Number.parseInt(process.env.BILI_PARENT_PID??"",10);const initialWatcherPid=Number.isInteger(parentWatchPid)&&parentWatchPid>0&&parentWatchPid!==process.pid?parentWatchPid:null;const proxyWatchers=new Set;if(initialWatcherPid!==null)proxyWatchers.add(initialWatcherPid);const watcherLastSeen=new Map;const lifecycleHooks={};await initSessions();try{await getStore().ready()}catch(e){log2("error",`[storage] refusing to start: ${String(e)}`);process.exit(1)}loadConversations();log2("info",`[persist] ${getStore().enabled?"enabled":"disabled"}`);try{const adopted=await reconcileDerivedLineage(listSessions(),{log:log2,adoptionEnabled:opts.resumeInheritance!==false});if(adopted>0)log2("info",`[lineage-reconcile] restored fold state for ${adopted} forked session(s)`)}catch(e){log2("warn",`[lineage-reconcile] sweep failed: ${String(e)}`)}const gcCfg=gcConfigFromEnv();if(gcCfg.enabled&&getStore().enabled){void gcSessionFiles().catch(err2=>log2("warn",`[gc] sweep failed: ${String(err2)}`));const gcTimer=setInterval(()=>{void gcSessionFiles().catch(err2=>log2("warn",`[gc] sweep failed: ${String(err2)}`))},gcCfg.intervalMs);gcTimer.unref?.()}const tunnelAllowlist=tunnelAllowlistFromEnv();if(tunnelAllowlist.length>0)log2("info",`[tunnel] remote-client allowlist: ${tunnelAllowlist.join(", ")}`);if(filePath){log2("info",`[log] writing to ${filePath}`)}void loadRegistry();const adminCtx={opts,core,config,log:log2,instanceId,instanceStartedAt,proxyWatchers,initialWatcherPid,watcherLastSeen,requestShutdown:reason=>{lifecycleHooks.requestShutdown?.(reason)},bootReady:()=>bootReady};return{opts,core,config,log:log2,instanceId,instanceStartedAt,proxyWatchers,watcherLastSeen,initialWatcherPid,lifecycleHooks,markBootReady:()=>{bootReady=true},bootReady:()=>bootReady,adminCtx}}function imageBillingFor5(opts,upstreamUrl){const env=process.env.BILI_IMAGE_BILLING;const configured=env==="pixels"||env==="bytes"?env:findRoute(opts.routes,upstreamUrl)?.imageBilling??opts.imageBilling??"auto";return resolveImageBilling(configured,upstreamUrl)}function imageTokenCapFor5(opts,upstreamUrl){return findRoute(opts.routes,upstreamUrl)?.imageTokenCap??opts.imageTokenCap??0}function resignSettingsFor(opts,upstreamUrl,scheme=APIG_RESIGN_SCHEME){return resolveResignSettings(process.env,findRoute(opts.routes,upstreamUrl)?.resign,scheme)}function inboundResignCredential(reqHeaders,opts,upstreamUrl){const marker=String(Array.isArray(reqHeaders[APIG_RESIGN_HEADER])?reqHeaders[APIG_RESIGN_HEADER][0]??"":reqHeaders[APIG_RESIGN_HEADER]??"");if(!resignSettingsFor(opts,upstreamUrl).enabled||marker!==APIG_RESIGN_SCHEME)return void 0;const encoded=Array.isArray(reqHeaders[APIG_RESIGN_CREDENTIAL_HEADER])?reqHeaders[APIG_RESIGN_CREDENTIAL_HEADER][0]:reqHeaders[APIG_RESIGN_CREDENTIAL_HEADER];return decodeApigCredential(encoded)}function imageReserveFor(session,protocol,body,opts,upstreamUrl){const billing=imageBillingFor5(opts,upstreamUrl);const cap=imageTokenCapFor5(opts,upstreamUrl);const raw=typeof body==="string"||Buffer.isBuffer(body);const prior=raw?imageTokensInRawBody(protocol,body,billing,cap):imageTokensInParsedBody(protocol,body,billing,cap);if(prior<=0)return prior;const nImages=raw?countImagesInRawBody(protocol,body):countImagesInParsedBody(protocol,body);if(nImages<=0)return prior;return learnedImageReserve(session,upstreamHost(upstreamUrl),nImages,`${billing}:${cap}`,cap,prior)??prior}var headroomFallbackLogged=new Set;var headroomEffectiveLogged=new Set;var armJudgingWallLogged=new Set;function resolveKnownOutputCeiling(headers,parsed,routes,upstreamUrl,sessionHeaderName,resolvedModel){const model=resolvedModel!==void 0&&resolvedModel.length>0?resolvedModel:typeof parsed.model==="string"&&parsed.model.length>0?parsed.model:void 0;if(!model)return void 0;const agent=pluginAgentHeader(headers);const runtimeMax=(pluginHeadersMatchModel(headers,model)?pluginReportedMaxOutput(headers):void 0)??(agent!==void 0?pluginRuntimeInfoFor(agent,model)?.maxOutput:pluginRuntimeInfoForConversation(runtimeConversationId(headers,parsed,sessionHeaderName),model)?.maxOutput);if(typeof runtimeMax==="number"&&runtimeMax>0)return runtimeMax;const launcherMax=launcherMaxOutput(model);if(typeof launcherMax==="number"&&launcherMax>0)return launcherMax;const cfgOut=resolveConfiguredOutputLimit(routes,upstreamUrl,model);if(cfgOut!==void 0&&cfgOut>0)return cfgOut;let host;try{host=upstreamUrl!==void 0?new URL(upstreamUrl).host:void 0}catch{host=void 0}return peekRegistryOutputLimit(model,host)}var ACP_TAG_MARK="<acp ";function hasSignedThinkingBlock(m2){if(m2.contentType==="reasoning")return typeof m2.thinkingSignature==="string"&&m2.thinkingSignature.length>0;const raw=m2.rawAnthropicBlock;return raw?.type==="redacted_thinking"}function planReasoningDrop(msgs,reasoning,strictEcho){if(strictEcho)return new Set;if(msgs.some(hasSignedThinkingBlock))return new Set;return dropCompressReasoningIds(msgs,reasoning)}function applyReasoningDrop(msgs,plan2,log2,sessionId){if(plan2.size===0)return msgs;const out=msgs.filter(m2=>!plan2.has(m2.id));if(out.length!==msgs.length){log2("info",`[${sessionId}] compress-reasoning: dropped ${msgs.length-out.length} reasoning message(s) from closed compress turns (#651)`)}return out}var reasoningViolationState=new Map;var REASONING_VIOLATION_KEY_CAP=512;var REASONING_VIOLATION_ENTRY_CAP=4096;function fnv1aHex(text2){let h=2166136261;for(let i=0;i<text2.length;i++){h^=text2.charCodeAt(i);h=Math.imul(h,16777619)}return(h>>>0).toString(16).padStart(8,"0")}function violationIdentity(wire,ids,fallback){const clean=[...new Set(ids.filter(i=>i.length>0))].sort();if(clean.length>0){const shown=clean.slice(0,3).join(", ")+(clean.length>3?` (+${clean.length-3})`:"");return{key:`${wire}|${clean.join("|")}`,display:shown}}const digest=fnv1aHex(JSON.stringify(fallback??null).slice(0,8192));return{key:`${wire}|~${digest}`,display:`~${digest}`}}function trackViolationEpisode(sessionKey,current){let state7=reasoningViolationState.get(sessionKey);if(!state7){state7={seq:0,entries:new Map};reasoningViolationState.set(sessionKey,state7);if(reasoningViolationState.size>REASONING_VIOLATION_KEY_CAP){const oldest=reasoningViolationState.keys().next().value;if(oldest!==void 0)reasoningViolationState.delete(oldest)}}state7.seq+=1;const fresh=[];let ongoing=0;let maxRepeat=0;for(const c of current){const e=state7.entries.get(c.key);if(e&&e.lastSeen===state7.seq-1){e.count+=1;e.lastSeen=state7.seq;ongoing+=1;if(e.count>maxRepeat)maxRepeat=e.count;continue}const revived=e!==void 0;if(revived){e.count=1;e.lastSeen=state7.seq}else{state7.entries.set(c.key,{count:1,lastSeen:state7.seq});if(state7.entries.size>REASONING_VIOLATION_ENTRY_CAP){const oldestEntry=state7.entries.keys().next().value;if(oldestEntry!==void 0)state7.entries.delete(oldestEntry)}}fresh.push({display:c.display,revived})}return{fresh,ongoing,maxRepeat}}function violationTail(ongoing,maxRepeat){return ongoing>0?`; ${ongoing} already reported (up to \xD7${maxRepeat} repeats)`:""}function violationNamed(fresh,ongoing,maxRepeat){const named=fresh.slice(0,3).map(f2=>f2.display).join(", ")+(fresh.length>3?`, \u2026+${fresh.length-3}`:"");return`${named}${fresh.some(f2=>f2.revived)?" (re-violating after recovery)":""}${violationTail(ongoing,maxRepeat)} (window: since this proxy started)`}function warnReasoningPairs(wireMessages,log2,sessionId){let withRc=0;const violators=[];for(const m2 of wireMessages){const msg=m2;if(msg?.role!=="assistant")continue;if(typeof msg.reasoning_content==="string"){withRc++;continue}const tcs=Array.isArray(msg.tool_calls)?msg.tool_calls:void 0;if(!tcs||tcs.length===0)continue;violators.push(violationIdentity("openai",tcs.map(t=>typeof t?.id==="string"?t.id:""),tcs))}if(withRc===0)return;const tracked=trackViolationEpisode(`${sessionId}|openai`,violators);if(tracked.fresh.length===0)return;log2("warn",`[${sessionId}] reasoning-pair-violated: ${violators.length} assistant tool-call message(s) lack reasoning_content while ${withRc} carry it \u2014 strict-echo upstreams (DeepSeek thinking mode) will reject the request; first seen: ${violationNamed(tracked.fresh,tracked.ongoing,tracked.maxRepeat)} (#684/#762/#2864)`)}function warnAnthropicThinkingPairs(inboundMessages,outboundMessages,log2,sessionId){const thinkingIds=new Set;for(const m2 of inboundMessages){const msg=m2;if(msg?.role!=="assistant"||!Array.isArray(msg.content))continue;if(!msg.content.some(b2=>b2?.type==="thinking"))continue;for(const b2 of msg.content){if(b2?.type==="tool_use"&&typeof b2.id==="string")thinkingIds.add(b2.id)}}if(thinkingIds.size===0)return;const lost=[];for(const m2 of outboundMessages){const msg=m2;if(msg?.role!=="assistant"||!Array.isArray(msg.content))continue;if(msg.content.some(b2=>b2?.type==="thinking"))continue;for(const b2 of msg.content){if(b2?.type==="tool_use"&&typeof b2.id==="string"&&thinkingIds.has(b2.id)){lost.push(violationIdentity("anthropic",[b2.id],b2))}}}const tracked=trackViolationEpisode(`${sessionId}|anthropic`,lost);if(tracked.fresh.length===0)return;log2("warn",`[${sessionId}] thinking-pair-violated: ${lost.length} tool_use block(s) lost their inbound thinking block in the outbound rebuild \u2014 a stripped signature pair is rejected by the API; first seen: ${violationNamed(tracked.fresh,tracked.ongoing,tracked.maxRepeat)} (#684/#1327/#2864)`)}function warnResponsesReasoningPairs(input,log2,sessionId){let withReasoning=0;let split=0;let runs=0;const orphans=[];let runCalls=0;let runReasoning=0;let runIdents=[];const closeRun=()=>{if(runCalls>0&&runReasoning===0){split+=runCalls;runs++;orphans.push(...runIdents)}runCalls=0;runReasoning=0;runIdents=[]};for(const item of input){const it2=item;const t=it2?.type;if(t==="reasoning"){withReasoning++;runReasoning++;continue}if(t==="function_call"||t==="custom_tool_call"){runCalls++;runIdents.push(violationIdentity("responses",typeof it2.call_id==="string"?[it2.call_id]:[],it2));continue}if(t==="function_call_output"||t==="custom_tool_call_output")continue;if(t==="message"&&it2.role==="assistant")continue;closeRun()}closeRun();if(withReasoning===0)return;const tracked=trackViolationEpisode(`${sessionId}|responses`,orphans);if(tracked.fresh.length===0)return;log2("warn",`[${sessionId}] reasoning-pair-violated: ${split} tool-call item(s) in ${runs} assistant run(s) lack any reasoning item while ${withReasoning} exist \u2014 strict-echo upstreams will reject the request; first seen: ${violationNamed(tracked.fresh,tracked.ongoing,tracked.maxRepeat)} (#684/#1479/#2864)`)}function buildCarrierIndex(messages){const callIds=new Set;const compressCalls=[];for(const m2 of messages){if(m2.contentType!=="tool-call")continue;if(m2.toolCallId)callIds.add(m2.toolCallId);if(m2.toolName===COMPRESS_TOOL_NAME)compressCalls.push(m2)}let rangePairs=null;const ensureRangePairs=()=>{if(!rangePairs){rangePairs=new Map;for(const c of compressCalls){let parsed;try{parsed=JSON.parse(c.text??"")}catch{continue}const obj=parsed;const ranges=Array.isArray(obj?.content)?obj.content:[obj];for(const r of ranges){if(typeof r?.startId!=="string"||!r.startId||typeof r?.endId!=="string"||!r.endId)continue;let ends=rangePairs.get(r.startId);if(!ends){ends=new Set;rangePairs.set(r.startId,ends)}ends.add(r.endId)}}}return rangePairs};return{callIds,compressCalls,ensureRangePairs}}function stripKernelSummaries(messages,state7){const{callIds,compressCalls,ensureRangePairs}=buildCarrierIndex(messages);const carried=new Set;for(const b2 of state7.blocks){if(!b2.active||!b2.compressCallId)continue;const present=isPluginFoldCallId(b2.compressCallId)?!b2.startRef||!b2.endRef?compressCalls.length>0:ensureRangePairs().get(b2.startRef)?.has(b2.endRef)??false:callIds.has(b2.compressCallId);if(present){carried.add(`acp_summary_${b2.blockId}`)}}return messages.filter(m2=>!(m2.id??"").startsWith("acp_summary_")||!carried.has(m2.id))}var RESPONSES_TURN_SEPARATOR="[The exchange between these two assistant turns was compressed.]";function repairResponsesAssistantOrdering(folded,original){const runOf=new Map;const runHasBody=new Map;let run=0;let inRun=false;for(const m2 of original){if(m2.role==="assistant"){if(!inRun){run++;inRun=true}runOf.set(m2.id,run);if(m2.contentType!=="reasoning")runHasBody.set(run,true)}else{inRun=false}}const survivorCount=new Map;for(const m2 of folded){const r=m2.role==="assistant"?runOf.get(m2.id):void 0;if(r!==void 0)survivorCount.set(r,(survivorCount.get(r)??0)+1)}const out=[];let phase=-1;let seenReasoning=false;let sepSeq=0;const pushSeparator=()=>{sepSeq++;out.push({id:`${RESPONSES_TURN_SEPARATOR_ID_PREFIX}${sepSeq}`,role:"user",contentType:"text",text:RESPONSES_TURN_SEPARATOR});phase=-1;seenReasoning=false};for(const m2 of folded){if(m2.role!=="assistant"){out.push(m2);phase=-1;seenReasoning=false;continue}const kind=m2.contentType==="reasoning"?"reasoning":m2.contentType==="tool-call"?"tool-call":"message";const r=runOf.get(m2.id);if(kind==="reasoning"&&r!==void 0&&runHasBody.get(r)&&survivorCount.get(r)===1)continue;if(kind==="reasoning"&&(phase>0||seenReasoning)||kind==="message"&&phase===2)pushSeparator();out.push(m2);if(kind==="reasoning"){phase=Math.max(phase,0);seenReasoning=true}else if(kind==="message")phase=Math.max(phase,1);else phase=Math.max(phase,2)}return out}function diagTagSummary(messages,sessionId,strategy){let textTagged=0;let toolTagged=0;for(const m2 of messages){const hasTag=(m2.text??"").includes(ACP_TAG_MARK);if(!hasTag)continue;if(m2.contentType==="tool-call"||m2.contentType==="tool-result")toolTagged++;else textTagged++}return`[${sessionId}] processTurn: ${messages.length} msgs, renderTags=${strategy}, ${textTagged} text tagged, ${toolTagged} tool tagged (should be 0 with text-only)`}function diagNudge(turn,sessionId,tokenCount,limit,model,willInject,decidePending=false,surfaceOff){const n=turn.nudge;if(!n)return`[${sessionId}] nudge: unavailable`;const b2=n.breakdown??{};const pct2=limit>0?`${Math.round(tokenCount/limit*100)}%`:"?";const growth=b2["growth"]??0;const floor=b2["growthFloor"]??0;const interval=b2["nudgeGrowthTokens"]??0;const pendingT1=b2["pendingT1"]??0;const ref=b2["growthReference"]??0;const inject=willInject?decidePending?`INJECT-PENDING T${n.tier??"?"}`:n.shouldInject?`INJECT T${n.tier??"?"}`:`INJECT-ESC T${n.tier??"?"}`:n.shouldInject?`ARMED-SUPPRESSED T${n.tier??"?"}`:"idle";const modelTag=model?` model=${model}`:"";const offTag=surfaceOff?`, ${surfaceOff}`:"";return`[${sessionId}] nudge ${inject}: usage=${pct2} (${tokenCount}/${limit}), growth=${growth}/${floor} (ref=${ref}, interval=${interval}), pendingT1=${pendingT1}/${interval}${modelTag}${offTag}, reason="${n.reason.slice(0,120)}"`}var SIDE_LANE_ANCHOR_MIN_ABS_DELTA=25e3;var SIDE_LANE_ANCHOR_IMPOSSIBLE_RATIO=8;function effectiveTokenCount(session,msgs,inboundImageTokens=0){const anchorStale=usageAnchorCycleStale(session.stats);const payloadUpperNow=estimateCoreMessagesUpper(msgs)+inboundImageTokens;const anchorImpossible=session.stats.lastInputTokens>0&&(session.stats.lastUsagePayloadUpper??0)>0&&payloadUpperNow>=session.stats.lastInputTokens*SIDE_LANE_ANCHOR_IMPOSSIBLE_RATIO&&payloadUpperNow>=session.stats.lastUsagePayloadUpper*SIDE_LANE_ANCHOR_IMPOSSIBLE_RATIO&&payloadUpperNow-session.stats.lastInputTokens>SIDE_LANE_ANCHOR_MIN_ABS_DELTA;if(!anchorStale&&session.stats.lastInputTokensSource==="usage"&&(session.stats.compressCreditTokens??0)>0&&session.stats.lastInputTokens>=0)return{tokens:session.stats.lastInputTokens,source:"usage"};if(!anchorStale&&!anchorImpossible&&session.stats.lastInputTokens>0&&(session.stats.lastInputTokensSource==="usage"||session.stats.lastInputTokensSource==="overflow-arm")&&staleSmallAnchorFallback(session.stats,session.stats.lastInputTokens)===null)return{tokens:session.stats.lastInputTokens,source:"usage"};const anchored=postRebuildAnchorTokens(session);if(anchored>0)return{tokens:anchored,source:"estimate"};const raw=payloadUpperNow;const grade=session.stats.lastUsageGradeTokens;if(!anchorStale&&grade!==void 0&&grade>0){const fallback=staleSmallAnchorFallback(session.stats,grade);if(fallback!==null)return{tokens:fallback,source:"estimate"};return{tokens:grade,source:"usage"}}if(session.metadata.anonymousPrefixAffinity)return{tokens:raw,source:"estimate"};const est=session.stats.localInputEstimate??0;if(est<=0)return{tokens:0,source:"estimate"};return{tokens:Math.min(est,raw),source:"estimate"}}function usageGradeInputBaseline(session){return session.stats.lastInputTokensSource==="usage"?session.stats.lastInputTokens:0}function scrubAnthropicPck(protocol,bodyBuffer,log2){if(protocol!=="anthropic"||bodyBuffer.length===0)return bodyBuffer;let parsed;try{parsed=JSON.parse(bodyBuffer.toString("utf8"))}catch{return bodyBuffer}if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed))return bodyBuffer;const p2=parsed;if(!Object.prototype.hasOwnProperty.call(p2,"prompt_cache_key"))return bodyBuffer;delete p2.prompt_cache_key;log2("debug",`stripped prompt_cache_key from verbatim anthropic forward (#1403)`);return Buffer.from(JSON.stringify(p2),"utf8")}function scrubCompatDrop(bodyBuffer,dropPaths,log2){if(dropPaths.length===0||bodyBuffer.length===0)return bodyBuffer;let parsed;try{parsed=JSON.parse(bodyBuffer.toString("utf8"))}catch{return bodyBuffer}if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed))return bodyBuffer;const dropped=dropCompatFieldsJson(parsed,dropPaths);if(dropped===0)return bodyBuffer;log2("info",`stripped ${dropped} field(s) per compat.dropFields (${dropPaths.join(", ")}) from verbatim forward (#1757)`);return Buffer.from(JSON.stringify(parsed),"utf8")}function isCountTokensRequest(method,urlPath,hasBody){return method==="POST"&&hasBody&&!countTokensPassthrough()&&(urlPath.endsWith("/messages/count_tokens")||googlePathKind(urlPath)==="count-tokens")}function prepareCountTokens(parsed,core,config,log2,session){const sessionId=session.id;try{const{msgs,cacheControls}=anthropicToCore(parsed);const turn=core.processTurn({messages:msgs,state:session.state,config:ccrLoopConfig(session,config),tokenCount:usageGradeInputBaseline(session),renderTags:renderNone()?"none":"text-only",contentStore:contentStoreOf(session)});const stripped=stripKernelSummaries(turn.messages,turn.state);const rebuiltMessages=coreToAnthropic(stripped,cacheControls);log2("info",`[${sessionId}] count_tokens pruned: ${msgs.length} \u2192 ${stripped.length} msgs`);const rebuilt={...parsed,messages:rebuiltMessages};delete rebuilt.prompt_cache_key;return{body:JSON.stringify(rebuilt),session,processedMessages:[],originalMessages:msgs,protocol:"anthropic",stream:false,compressInjected:false}}catch(err2){log2("warn",`[${sessionId}] count_tokens prune failed, forwarding unchanged: ${String(err2)}`);const fallback={...parsed};delete fallback.prompt_cache_key;return{body:JSON.stringify(fallback),session,processedMessages:[],originalMessages:[],protocol:"anthropic",stream:false,compressInjected:false}}}var loggedUpstreamProxyDecisions=new Set;function logUpstreamProxyDecision(opts,upstreamUrl,decision){if(!upstreamUrl)return;let host=upstreamUrl;try{host=new URL(upstreamUrl).host}catch{}const key2=`${host}|${decision.proxy??""}|${decision.source}`;if(loggedUpstreamProxyDecisions.has(key2))return;loggedUpstreamProxyDecisions.add(key2);const via=decision.proxy?`via ${maskUrlForLog(decision.proxy)}`:"direct";logMsg(opts,"info",`[upstream-proxy] ${maskHostPortForLog(host)} ${via} (source=${decision.source})`)}function forwardUpstreamUrl(req,opts,route){const reqUrl=req.url??"";const isAbsoluteUrl=/^https?:\/\//i.test(reqUrl);const rewritten=route?route.rewrittenUrl:isAbsoluteUrl?reqUrl:opts.upstream+reqUrl;return rewritten.replace(/^mitm:\/\//,"https://")}function buildForwardTarget(req,opts,route,affinity,hopMarker){const upstreamUrl=forwardUpstreamUrl(req,opts,route);const headers={};const reqConnNamed=connectionNamedHeaders(req.headers["connection"]);for(const[k2,v2]of Object.entries(req.headers)){const lower=k2.toLowerCase();if(UPSTREAM_HOP_HEADERS.has(lower)||reqConnNamed.has(lower)||v2===void 0)continue;if(lower===APIG_RESIGN_HEADER||lower===APIG_RESIGN_CREDENTIAL_HEADER)continue;headers[k2]=Array.isArray(v2)?v2.join(", "):v2}if(hopMarker!==void 0)headers[BILI_HOP_HEADER]=hopMarker;if(route?.tunnel){let destLoopback=false;let destAdminPath=false;try{const du=new URL(upstreamUrl);const lit=parseIpLiteral(du.hostname.replace(/^\[|\]$/g,""));destLoopback=lit!==null&&classifyIp(lit)==="loopback";const dp=du.pathname;destAdminPath=dp==="/__bili/"||dp.startsWith("/__bili/")||dp==="/__acp/"||dp.startsWith("/__acp/")}catch{}if(!(isLoopbackAddress(req.socket.remoteAddress)&&destLoopback&&destAdminPath))headers[BILI_TUNNEL_HEADER]="1"}headers["host"]=new URL(upstreamUrl).host;stripRemoteCompactionBetaFeature(headers);const convSource=conversationHeaderSource(req.headers);if(affinity&&(!convSource||convSource.name==="x-bili-plugin-conversation")){headers["x-session-id"]=affinity}const decision=resolveProxyDecision(opts.routes,opts.proxy,route?.rewrittenUrl??upstreamUrl,opts.proxyFallback);logUpstreamProxyDecision(opts,upstreamUrl,decision);return{upstreamUrl,headers,proxyUrl:decision.proxy,skippedProxy:decision.skippedProxy}}async function runNudgeDecision(args){const{req,opts,protocol,sideBody,session,log:log2}=args;let outcome;try{const route=resolveUpstream(opts,req.url??"",req);const target=buildForwardTarget(req,opts,route);let url=target.upstreamUrl;if(protocol==="google"&&url.includes(":streamGenerateContent")){url=url.replace(":streamGenerateContent",":generateContent")}const bodyStr=JSON.stringify(sideBody);const headers={"content-type":"application/json",...target.headers};const resignCtx=inboundResignCredential(req.headers,opts,target.upstreamUrl);if(resignCtx!==void 0){try{resignApig(headers,resignCtx,"POST",target.upstreamUrl,bodyStr,findRoute(opts.routes,target.upstreamUrl))}catch(err2){log2("warn",`[acp-decide] session=${session.id} re-sign failed; sending the previous signature: ${String(err2)}`)}}const{response,clearTimer}=await fetchWithTimeout(url,{method:"POST",headers,body:bodyStr,dispatcher:proxyDispatcher(target.proxyUrl)},DECIDE_TIMEOUT_MS);try{if(!response.ok){outcome={kind:"failed",detail:`HTTP ${response.status}`}}else{const text2=await response.text();let json=null;try{json=JSON.parse(text2)}catch{json=null}outcome=parseDecision(json!==null?extractDecisionText(protocol,json):extractSummaryFromSse(protocol,text2))}}finally{clearTimer()}}catch(e){outcome={kind:"failed",detail:String(e)}}recordDecision(session.metadata,outcome.kind!=="failed");markDirty(session);log2(outcome.kind==="failed"?"warn":"info",`[acp-decide] session=${session.id} ${protocol}: ${outcome.kind==="failed"?outcome.detail:outcome.kind==="yes"?`yes${outcome.range?` (${outcome.range})`:""}`:"no"}`);return outcome}function isPreflightFailFast(outcome){return"failFast"in outcome}var PREFLIGHT_KEEPALIVE_MS=15e3;var DOOMED_PROBE_BYTES_PER_TOKEN=7.5;var DOOMED_PROBE_ABSOLUTE_BYTES=2e6;function preflightHoldGraceMs2(){return preflightHoldGraceMs()}var LOCAL_REFUSAL_MAX_RECORDS=16;var LOCAL_REFUSAL_TTL_MS=10*6e4;function readLocalRefusals(metadata){const raw=metadata.localRefusals;if(!Array.isArray(raw))return[];const now=Date.now();return raw.filter(r=>!!r&&typeof r==="object"&&typeof r.origin==="string"&&typeof r.model==="string"&&typeof r.window==="number"&&typeof r.at==="number"&&r.at>now-LOCAL_REFUSAL_TTL_MS)}function noteLocalRefusal(session,origin,model,window2){if(!origin||!model||!Number.isFinite(window2)||window2<=0)return;const records=readLocalRefusals(session.metadata);const existing=records.find(r=>r.origin===origin&&r.model===model);if(existing!==void 0&&existing.window>=window2)return;session.metadata.localRefusals=[...records.filter(r=>!(r.origin===origin&&r.model===model)),{origin,model,window:Math.floor(window2),at:Date.now()}].slice(-LOCAL_REFUSAL_MAX_RECORDS);markDirty(session)}function localRefusalCovers(metadata,origin,model,window2){if(!origin||!model)return false;return readLocalRefusals(metadata).some(r=>r.origin===origin&&r.model===model&&r.window>=window2)}function beginPreflightHold(res,prepared,log2){if(res.headersSent||res.destroyed||res.writableEnded)return void 0;const sid=prepared.session.id;const keepAlive=prepared.stream?": bili-preflight\n\n":" ";try{if(prepared.stream){res.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache","x-accel-buffering":"no","x-bili-preflight":"compressing"})}else{res.writeHead(200,{"content-type":"application/json","x-bili-preflight":"compressing"})}}catch{return void 0}log2("info",`[${sid}] preflight still running after ${preflightHoldGraceMs2()}ms grace \u2014 committed early ${prepared.stream?"SSE":"JSON"} headers + keep-alive to hold the client (#568)`);try{res.write(keepAlive)}catch{}const iv=setInterval(()=>{try{res.write(keepAlive)}catch{clearInterval(iv)}},PREFLIGHT_KEEPALIVE_MS);return()=>clearInterval(iv)}function streamKeepaliveMs(){return streamKeepAliveMs()}function beginStreamKeepalive(res,sid,log2){const idleMs=streamKeepaliveMs();if(idleMs<=0||res.destroyed||res.writableEnded)return;const sock=res.socket;if(!sock)return;let baseline=sock.bytesWritten;let warned=false;let stopped=false;const anyRes=res;let origWrite;if(anyRes.__biliKeepaliveBoundary===void 0){origWrite=res.write.bind(res);anyRes.__biliKeepaliveBoundary=true;res.write=((...args)=>{const chunk=args[0];try{if(typeof chunk==="string"){if(chunk.length>0)anyRes.__biliKeepaliveBoundary=chunk.endsWith("\n")}else if(Buffer.isBuffer(chunk)||chunk instanceof Uint8Array){if(chunk.length>0)anyRes.__biliKeepaliveBoundary=chunk[chunk.length-1]===10}}catch{}return origWrite(...args)})}const stop=()=>{if(stopped)return;stopped=true;clearInterval(iv);res.removeListener("close",stop)};res.once("close",stop);const iv=setInterval(()=>{try{if(res.destroyed||res.writableEnded||!res.socket){stop();return}const written=res.socket.bytesWritten;if(written>baseline){baseline=written;return}if(anyRes.__biliKeepaliveBoundary===false)return;res.write(": bili-keepalive\n\n");if(!warned){warned=true;log2("info",`[${sid}] stream silent ${idleMs}ms \u2014 holding client with SSE keep-alive comments past its undici body timeout (#1647)`)}}catch{stop()}},Math.max(50,Math.floor(idleMs/3)))}function outboundPayloadBreakdown(prepared,opts,route,reqUrl){const billingUpstream=route?.rewrittenUrl??(/^https?:\/\//i.test(reqUrl)?reqUrl:opts.upstream);const imageTokens=imageReserveFor(prepared.session,prepared.protocol,prepared.parsedBody??prepared.body,opts,billingUpstream);const msgs=prepared.processedMessages.length>0?prepared.processedMessages:prepared.originalMessages;const textEstimate=estimateCoreMessages(msgs);const overheadEstimate=estimateWireOverhead(prepared.protocol,prepared.parsedBody??prepared.body);const armEstimate=Math.max(textEstimate,estimateCoreMessagesUpper(msgs))+overheadEstimate+imageTokens;return{textEstimate,overheadEstimate,imageTokens,payloadEstimate:textEstimate+overheadEstimate+imageTokens,armEstimate}}function outboundContextEstimates(prepared,wireBody,opts,upstream,parsed){let msgs=prepared.processedMessages.length>0?prepared.processedMessages:prepared.originalMessages;const project=value=>{switch(prepared.protocol){case"anthropic":msgs=anthropicToCore(value).msgs;break;case"openai":msgs=openaiToCore(value).msgs;break;case"responses":msgs=responsesToCoreWithToolImages(value).msgs;break;case"google":msgs=googleToCore(value).msgs;break}};let raw;if(parsed===void 0){try{project(JSON.parse(wireBody))}catch{}raw=wireBody}else if(parsed!==null){try{project(parsed)}catch{}raw=parsed}else{raw=""}const overhead=estimateWireOverhead(prepared.protocol,raw);const imageTokens=imageReserveFor(prepared.session,prepared.protocol,raw,opts,upstream);return{upperBound:estimateCoreMessagesUpper(msgs)+overhead+imageTokens,textOverhead:estimateCoreMessages(msgs)+overhead,imageTokens}}var routeMissWarned=new Set;function warnRouteMissIfNew(origin,model,knownKeys2,log2){if(!origin||!model||knownKeys2.length===0)return false;const key2=`${origin}\0${model}`;if(routeMissWarned.has(key2))return false;routeMissWarned.add(key2);const hosts2=knownKeys2.map(k2=>hostIdForLog(k2));let msg=`[route] no provider route matched ${hostIdForLog(origin)} (model=${model}) \u2014 its per-provider settings (context/compress/\u2026) are IGNORED; known providers keys: ${hosts2.join(", ")}. Add a matching key to the providers block in ~/.config/billion-context/billion-context.json.`;if(origin.startsWith("mitm://")){const host=origin.slice("mitm://".length);const siblings=[];let hasMitmTwin=false;for(const k2 of knownKeys2){let u2;try{u2=new URL(k2)}catch{continue}if(u2.protocol==="https:"&&u2.host===host)siblings.push(k2);else if(u2.protocol==="mitm:"&&u2.host===host)hasMitmTwin=true}if(siblings.length>0&&!hasMitmTwin){const twin=`mitm://${hostIdForLog(`https://${host}`)}`;msg+=` Scheme mismatch: your settings sit under ${siblings.map(s3=>hostIdForLog(s3)).join(", ")} but MITM-lane lookups use "${twin}" \u2014 add that key (the https:// entries keep serving /bili/-embedded requests).`}}log2("warn",msg);return true}function buildWindowShrinkNote(args){if(args.reason===void 0||args.nativeWindow===void 0||args.limit>=args.nativeWindow)return"";const head=` Note: bili's effective window ${args.limit} is below the model's full window ${args.nativeWindow} \u2014 `;if(args.reason==="operator"){return head+`your compress.modelContextLimit setting overrides it; if the upstream actually serves the larger window, raise or remove that setting (hot-reloaded, no session restart needed).`}if(args.routeMissedConfigured){const up=args.upstreamEndpoint?hostIdForLog(args.upstreamEndpoint):"this upstream";const keys=(args.knownKeys??[]).map(k2=>hostIdForLog(k2)).join(", ");return head+`it was aligned down to codex's own window perception, and your upstream (${up}) matched NO configured providers key${keys?` \u2014 your pinned context/modelContextLimit sit under: ${keys}`:""}. Add a providers entry for this upstream so the pinned window applies here.`}return head+`it was aligned down to codex's own window perception; set compress.modelContextLimit explicitly if your upstream serves the larger window.`}async function preflightCompressIfNeeded(prepared,runPrepare,req,inboundBody,res,opts,core,config,configuredWindow,model,resolvedNativeWindow,windowShrinkReason,route,affinity,anonymous,log2,instanceId){const session=prepared.session;const statedWall=typeof session.stats.overflowArmTokens==="number"&&session.stats.overflowArmTokens>0?session.stats.overflowArmTokens:0;const completionReserve=typeof session.stats.overflowArmCompletionReserve==="number"&&session.stats.overflowArmCompletionReserve>0?session.stats.overflowArmCompletionReserve:0;const limit=completionReserve>0&&statedWall>0?Math.max(0,Math.min(config.modelContextLimit,statedWall-completionReserve)):config.modelContextLimit;const headroomWindow=typeof session.metadata.reservedContextLimit==="number"&&session.metadata.reservedContextLimit>0?session.metadata.reservedContextLimit:config.modelContextLimit;if(limit<headroomWindow){const armKey=`${session.id}|${String(model??"?")}|${limit}|${headroomWindow}`;if(!armJudgingWallLogged.has(armKey)){armJudgingWallLogged.add(armKey);log2("info",`[arm-judge] upstream overflow proof (stated wall ${statedWall}, ${completionReserve} billed to completion): nudge/preflight judge input against ${limit} \u2014 BELOW the [headroom] window ${headroomWindow}; that line does not apply while this arm is live (#3450, #5191)`)}}const overflowTarget=prepared.protocol==="responses"&&codexHealthBarApplies(req.headers)?limit*CODEX_COMPACT_HEALTH_RATIO:limit;const autoFoldOn=autoFoldEngaged(config,session);const measuredFloor=autoFoldOn?autoFoldFloor(session):void 0;const autoFoldTarget=autoFoldOn?Math.min(Math.max(Math.max(AUTO_FOLD_TARGET_MIN,Math.min(config.externalSummary?.autoFoldTargetTokens??(overflowTarget>0?Math.round(overflowTarget/2):0),overflowTarget)),measuredFloor??0),overflowTarget):void 0;const growthArmed=autoFoldOn&&autoFoldTarget!==void 0&&autoFoldTarget>0&&autoFoldTarget<overflowTarget;const compressionTarget=growthArmed?autoFoldTarget:overflowTarget;const{textEstimate,overheadEstimate,imageTokens}=outboundPayloadBreakdown(prepared,opts,route,req.url??"");const unknownBaseline=anonymous&&session.stats.lastInputTokens<=0;const baselineFloorRaw=prepared.processedMessages.length>0?session.stats.lastInputTokensSource==="usage"||session.stats.lastInputTokensSource==="overflow-arm"?session.stats.lastInputTokens:0:session.stats.lastInputTokens;let baselineFloor=baselineFloorRaw;const currentOrigin=normalizeUpstreamOrigin(route?.upstream);const baselineOrigin=normalizeUpstreamOrigin(session.stats.lastInputTokensOrigin);if(baselineFloor>0&¤tOrigin!==void 0&&baselineOrigin!==void 0&&baselineOrigin!==currentOrigin){log2("info",`[${session.id}] preflight usage-baseline ~${baselineFloor} tok was measured on ${maskUrlForLog(baselineOrigin)}, request now routes to ${maskUrlForLog(currentOrigin)} \u2014 demoting to untrusted, judging by this payload's own estimate (#1933)`);baselineFloor=0}const kFactor=currentCalibrationFactor(session.stats,session.metadata?.lastModel);const kOrigin=session.stats.calibratedEstimateOrigin;const calibratedText=applyEstimateCalibration(textEstimate+overheadEstimate,kFactor,kOrigin,currentOrigin);const calibratedPayload=calibratedText+imageTokens;const tokenCount=unknownBaseline?estimateCoreMessagesUpper(prepared.processedMessages)+overheadEstimate+imageTokens:Math.max(baselineFloor,calibratedPayload);const textChannel=unknownBaseline?estimateCoreMessagesUpper(prepared.processedMessages)+overheadEstimate:calibratedText;const textBudget=Math.max(0,compressionTarget-imageTokens);const decisionTrigger=Math.max(Math.max(0,baselineFloor-imageTokens),textChannel);const growthWorthIt=!growthArmed||imageTokens>=compressionTarget||decisionTrigger-textBudget>=AUTO_FOLD_MIN_BENEFIT_TOKENS;const triggerFires=growthWorthIt&&(imageTokens>=compressionTarget||decisionTrigger>=textBudget);if(opts.debug){const billed=session.stats.lastInputTokens>0&&session.stats.lastInputTokensSource==="usage"?session.stats.lastInputTokens:"none";log2("debug",`[${session.id}] [usage-vs-est] upstream-billed=${billed} est=${Math.round(textEstimate)} k\u0302=${kFactor!==void 0?kFactor.toFixed(2):"n/a"} route=${currentOrigin===void 0?"?":maskUrlForLog(currentOrigin)} model=${model??"?"} baseline-grade=${session.stats.lastInputTokensSource??"none"} (#2283)`)}if(limit<=0||!model||!triggerFires)return prepared;const localRefusalHere=localRefusalCovers(session.metadata,currentOrigin,model,limit);const probeForEvidence=!growthArmed&&!unknownBaseline&&session.stats.lastInputTokens>0&&baselineFloor<=0&&prepared.processedMessages.length>0;if(probeForEvidence){const coreTextBytes=estimateCoreMessagesUpperBytes(prepared.processedMessages);if(coreTextBytes>Math.max(DOOMED_PROBE_ABSOLUTE_BYTES,limit*DOOMED_PROBE_BYTES_PER_TOKEN)){const byteFloorTokens=Math.ceil(coreTextBytes/DOOMED_PROBE_BYTES_PER_TOKEN);log2("error",`[${session.id}] preflight 413 core-text profile: ${describeCoreTextDuplication(prepared.processedMessages)}`);const doomedMessage=`payload core text alone is ~${coreTextBytes} bytes \u2014 even at the densest tokenizer density observed on a live route (~${DOOMED_PROBE_BYTES_PER_TOKEN} bytes/token, #2122) that is \u2265 ~${byteFloorTokens} tokens vs the model window ${limit} (model=${model}); no upstream can accept it, so it was NOT forwarded even for evidence. Remove or trim the oversized content (e.g. a giant paste or tool result) and retry.`;log2("error",`[${session.id}] preflight fail-fast 413 (retryable=false): ${doomedMessage}`);noteLocalRefusal(session,currentOrigin,model,limit);return{failFast:true,status:413,message:doomedMessage,retryable:false,respond:!res.writableEnded}}if(localRefusalHere){log2("warn",`[${session.id}] preflight trigger fired on estimate only (~${Math.round(textChannel)} text + ~${imageTokens} image vs window ${limit}) but this origin/model was locally refused (413) at an equal or wider window \u2014 NOT re-forwarding for evidence; falling through to fold/fail-fast (#3846)`)}else{log2("info",`[${session.id}] preflight trigger fired on estimate only (~${Math.round(textChannel)} text + ~${imageTokens} image vs window ${limit}); baseline ${session.stats.lastInputTokens} (${session.stats.lastInputTokensSource??"unprovenanced"}) carries no current-route upstream evidence \u2014 forwarding once to acquire usage/overflow evidence before compressing (#2313)`);return prepared}}const payloadFitsWindow=calibratedPayload<limit;const noOverflowEvidence=session.stats.lastInputTokens<limit||session.stats.lastInputTokensSource!=="usage"&&session.stats.lastInputTokensSource!=="overflow-arm";const imageArbitration=imageTokens>0&&textChannel<limit&&textChannel+imageTokens>=limit&&noOverflowEvidence;if(imageArbitration&&!localRefusalHere&&(prepared.nudge?.compressibleRanges??[]).length===0){log2("warn",`[${session.id}] image-dominated payload (~${textEstimate} text + ~${imageTokens} image tokens) exceeds window ${limit} by estimate only, nothing compressible, no upstream overflow evidence \u2014 forwarding for the upstream to arbitrate billing (#496/#1800)`);return prepared}const failFast=(status2,detail,retryable2,foldedTokens,rangesLeft)=>{const imageNote=imageTokens>=limit?` Images alone account for ~${imageTokens} tokens (\u2265 window ${limit}); compression cannot remove them \u2014 shrink or remove the images, or raise the window.`:"";const sizeClause=foldedTokens!==void 0&&foldedTokens<tokenCount?`context ~${foldedTokens} tokens (down from ~${tokenCount} before preflight) exceeds the model window ${limit}`:`context ~${tokenCount} tokens exceeds the model window ${limit}`;const rangesClause=rangesLeft!==void 0?`, with ${rangesLeft} compressible range(s) still visible`:"";const ffEmbeddedUrl=route?.rewrittenUrl;const ffProviderKeys=Object.keys(opts.routes);const shrinkNote=buildWindowShrinkNote({reason:windowShrinkReason,limit,nativeWindow:resolvedNativeWindow,routeMissedConfigured:ffProviderKeys.length>0&&findRouteKey(opts.routes,ffEmbeddedUrl)===void 0,upstreamEndpoint:ffEmbeddedUrl,knownKeys:ffProviderKeys});const estimateOnly=baselineFloor===0&&kFactor===void 0&&session.stats.lastInputTokensSource!=="usage"&&session.stats.lastInputTokensSource!=="overflow-arm";const estimateNote=estimateOnly?" (size judged by bili's local estimate, which can diverge from what the upstream actually bills)":"";const message=`${sizeClause} (model=${model})${rangesClause}${estimateNote} and preflight compression could not bring it under: ${detail.replace(/\.\s*$/,"")}.`+imageNote+shrinkNote+` The over-window payload was NOT forwarded.`;log2("error",`[${session.id}] preflight fail-fast ${status2} (retryable=${retryable2}): ${message}`);return{failFast:true,status:status2,message,retryable:retryable2,respond:!res.writableEnded}};if((prepared.nudge?.compressibleRanges??[]).length===0){if(payloadFitsWindow){log2("info",`[${session.id}] preflight target reached (~${tokenCount}) but the payload fits with no compressible ranges (~${Math.round(calibratedPayload)}/${limit}${kFactor!==void 0?`, k\u0302=${kFactor.toFixed(2)}`:""}); forwarding as-is`);return prepared}}log2("warn",`[${session.id}] context ${tokenCount} tokens reached preflight target ${compressionTarget}${growthArmed?" (auto-fold growth floor)":""}${completionReserve>0?` (window ${config.modelContextLimit} minus proven completion reservation ${completionReserve})`:""} (model window ${limit}, model=${model}; usage-baseline=${baselineFloor>0?baselineFloor:"none"} local-est=${Math.round(calibratedText)}${kFactor!==void 0?` raw=${Math.round(textEstimate+overheadEstimate)} k\u0302=${kFactor.toFixed(2)}`:""}); preflight compressing before forward`);const{upstreamUrl,headers,proxyUrl}=buildForwardTarget(req,opts,route,affinity,instanceId);const clientAbort=new AbortController;registerRequestAbort(res,clientAbort);res.on("close",()=>{if(!res.writableEnded){clientAbort.abort();noteClientAbort(session)}});const started=Date.now();let stopHold;const holdTimer=setTimeout(()=>{stopHold=beginPreflightHold(res,prepared,log2)},preflightHoldGraceMs2());holdTimer.unref();const forceStreamSummary=resolveCompress(opts.routes,route?.rewrittenUrl,model,opts.compress).streamSummary===true;const streamSummaryOff=resolveCompress(opts.routes,route?.rewrittenUrl,model,opts.compress).streamSummary===false;const preflightResignCtx=inboundResignCredential(req.headers,opts,upstreamUrl);let result;try{result=await preflightCompress({core,session,config,compressionTarget,compressReason:growthArmed?"growth":"overflow",prompts:prepared.prompts??defaultPrompts,surface:prepared.surface,protocol:prepared.protocol,billingBlock:prepared.anthropicBillingBlock,url:upstreamUrl,headers,resign:preflightResignCtx!==void 0?(hdrs,bodyStr)=>{try{resignApig(hdrs,preflightResignCtx,"POST",upstreamUrl,bodyStr,findRoute(opts.routes,upstreamUrl))}catch(err2){log2("warn",`[${session.id}] [preflight] re-sign failed; sending the previous signature: ${String(err2)}`)}}:void 0,model,proxyUrl,signal:clientAbort.signal,log:log2,imageReserve:imageTokens,wireOverhead:overheadEstimate,unknownBaseline,upstreamOrigin:currentOrigin,forceStreamSummary,streamSummaryOff},prepared.originalMessages)}finally{clearTimeout(holdTimer);stopHold?.()}if(!result.failure)delete session.metadata.preflightDeadEnd;const queueDroppedAll=externalQueueDroppedAll(result.externalDispatch);let outbound=prepared;let fits;let foldedCalibratedSize;if(result.compressedRanges>0){const rebuilt=await runPrepare();session.stats.requests-=1;outbound=rebuilt;const rebuiltMsgs=rebuilt.processedMessages.length>0?rebuilt.processedMessages:rebuilt.originalMessages;const rebuiltTextSize=estimateCoreMessages(rebuiltMsgs)+overheadEstimate;if(rebuiltTextSize>session.stats.lastInputTokens){session.stats.lastInputTokens=rebuiltTextSize;session.stats.lastInputTokensSource="estimate"}const rebuiltCalibrated=applyEstimateCalibration(rebuiltTextSize,kFactor,kOrigin,currentOrigin)+imageTokens;foldedCalibratedSize=rebuiltCalibrated;log2("info",`[${session.id}] preflight compressed ${result.compressedRanges} range(s), ~${result.savedTokens} tokens saved (${tokenCount} \u2192 ${foldedCalibratedSize}) in ${Date.now()-started}ms`);fits=unknownBaseline?result.fitsWindow:rebuiltCalibrated<limit;setPostRebuildAnchor(session,rebuiltTextSize+imageTokens);if(growthArmed&&result.failure===void 0&&rebuiltTextSize+imageTokens>=compressionTarget){session.metadata.autoFoldFloorTokens=rebuiltTextSize+imageTokens;markDirty(session);log2("warn",`[${session.id}] auto-fold target ${compressionTarget} unreachable \u2014 the session's irreducible baseline measures ~${rebuiltTextSize+imageTokens} tokens (system prompt + tools + live tail); effective target raised to the floor until the gap closes (#3444). Raise compress.externalSummary.autoFoldTargetTokens above ${rebuiltTextSize+imageTokens} for headroom`)}}else{fits=unknownBaseline?result.fitsWindow:estimateCoreMessages(prepared.processedMessages)+overheadEstimate+imageTokens<limit}const f2=result.failure;if(clientAbort.signal.aborted||f2?.kind==="aborted"){const detail=f2?.kind==="aborted"?f2.detail:"the client disconnected during preflight compression";log2("warn",`[${session.id}] preflight aborted (${detail}); not forwarding`);return{failFast:true,status:0,message:detail,retryable:false,respond:false}}if(fits){if(result.compressedRanges===0){if(growthArmed){if(queueDroppedAll){log2("warn",`[${session.id}] auto-fold made no progress (0 range(s) folded) \u2014 no summary attempt was ever dispatched (shared pool saturated / deadline expired before dispatch); congestion, not a chain failure \u2014 NOT backing off, auto-fold retries next turn (#2662); forwarding as-is (estimate fits the model window ${limit})`)}else if(result.hadFoldableCandidates){log2("warn",`[${session.id}] auto-fold made no progress (0 range(s) folded) \u2014 forwarding as-is (estimate fits the model window ${limit}); backing off auto-fold for ${Math.round(AUTO_FOLD_BACKOFF_MS/6e4)}m so classic nudges resume`);armAutoFoldBackoff(session);markDirty(session)}else{log2("info",`[${session.id}] auto-fold steady state: payload fits and no foldable candidates remained \u2014 forwarding as-is without backoff (#2638)`)}}else{log2("warn",`[${session.id}] preflight made no progress but the payload fits; forwarding as-is`)}}else if(growthArmed&&!queueDroppedAll&&result.savedTokens<AUTO_FOLD_MIN_BENEFIT_TOKENS){log2("warn",`[${session.id}] auto-fold saved only ~${result.savedTokens} tokens (< ${AUTO_FOLD_MIN_BENEFIT_TOKENS} worth) \u2014 forwarding as-is (estimate fits the model window ${limit}); backing off auto-fold for ${Math.round(AUTO_FOLD_BACKOFF_MS/6e4)}m so classic nudges resume (#3444)`);armAutoFoldBackoff(session);markDirty(session)}return outbound}if(result.compressedRanges>0&&!unknownBaseline&&result.payloadEstimate<limit&&!localRefusalHere){log2("warn",`[${session.id}] preflight view fits (~${result.payloadEstimate}/${limit}) but the rebuilt payload measures over \u2014 forwarding once for upstream arbitration (#1839)`);return outbound}if(growthArmed&&payloadFitsWindow){if(queueDroppedAll){log2("warn",`[${session.id}] auto-fold did not reach the growth target ${compressionTarget} (${result.compressedRanges} range(s) folded) \u2014 no summary attempt was ever dispatched (shared pool saturated / deadline expired before dispatch); congestion, not a chain failure \u2014 NOT backing off, auto-fold retries next turn (#2662); forwarding anyway (payload fits the model window ${limit})`)}else if(result.hadFoldableCandidates){log2("warn",`[${session.id}] auto-fold did not reach the growth target ${compressionTarget} (${result.compressedRanges} range(s) folded) \u2014 forwarding anyway (payload fits the model window ${limit}); backing off auto-fold for ${Math.round(AUTO_FOLD_BACKOFF_MS/6e4)}m so classic nudges resume`);armAutoFoldBackoff(session);markDirty(session)}else{log2("info",`[${session.id}] auto-fold steady state: growth target ${compressionTarget} unreachable while nothing foldable remained (${result.compressedRanges} range(s) folded) \u2014 forwarding anyway (payload fits the model window ${limit}) without backoff (#2638)`)}return outbound}if(imageArbitration&&!localRefusalHere){const outMsgs=outbound.processedMessages.length>0?outbound.processedMessages:outbound.originalMessages;const outText=estimateCoreMessages(outMsgs);if(outText+overheadEstimate<limit&&outText+overheadEstimate+imageTokens>=limit){log2("info",`[${session.id}] preflight folded ${result.compressedRanges} range(s) but images alone (~${imageTokens} tokens) keep the estimate over window ${limit} with no upstream overflow evidence \u2014 forwarding for the upstream to arbitrate billing (#496/#1800)`);return outbound}}const deterministicExhaustion=f2?.kind==="exhausted"&&f2.deterministic;const noUpstreamEvidence=session.stats.lastInputTokens<=0&&statedWall<=0&&deterministicExhaustion;let outboundBudgetTokens;try{const outBody=JSON.parse(typeof outbound.body==="string"?outbound.body:outbound.body.toString("utf8"));const outField=outputBudgetField(outBody);const rawBudget=outField!==null?readOutputBudget(outBody,outField):void 0;if(typeof rawBudget==="number"&&rawBudget>0)outboundBudgetTokens=rawBudget}catch{outboundBudgetTokens=void 0}const outboundCalibrated=foldedCalibratedSize??calibratedPayload;const nativeFitAfterClamp=statedWall<=0&&outboundBudgetTokens!==void 0&&typeof resolvedNativeWindow==="number"&&resolvedNativeWindow>0&&outboundCalibrated+outboundBudgetTokens<=resolvedNativeWindow;if((unknownBaseline||noUpstreamEvidence||nativeFitAfterClamp)&&!growthArmed){const outMsgs=outbound.processedMessages.length>0?outbound.processedMessages:outbound.originalMessages;const doomBytes=estimateCoreMessagesUpperBytes(outMsgs);if(doomBytes>Math.max(DOOMED_PROBE_ABSOLUTE_BYTES,limit*DOOMED_PROBE_BYTES_PER_TOKEN)){const byteFloorTokens=Math.ceil(doomBytes/DOOMED_PROBE_BYTES_PER_TOKEN);log2("error",`[${session.id}] preflight 413 core-text profile: ${describeCoreTextDuplication(outMsgs)}`);const doomedMessage=`payload core text alone is ~${doomBytes} bytes even after preflight compression \u2014 at the densest tokenizer density observed on a live route (~${DOOMED_PROBE_BYTES_PER_TOKEN} bytes/token, #2122) that is \u2265 ~${byteFloorTokens} tokens vs the model window ${limit} (model=${model}); no upstream can accept it. Remove or trim the oversized content (e.g. a giant paste or tool result) and retry.`;log2("error",`[${session.id}] preflight fail-fast 413 (retryable=false): ${doomedMessage}`);noteLocalRefusal(session,currentOrigin,model,limit);return{failFast:true,status:413,message:doomedMessage,retryable:false,respond:!res.writableEnded}}if(localRefusalHere){log2("warn",`[${session.id}] payload still over window ${limit} by local estimate (~${Math.round(result.payloadEstimate)} tok, ${result.compressedRanges} range(s) folded) but this origin/model was locally refused (413) at an equal or wider window \u2014 NOT re-forwarding for size arbitration (#3846/#4185)`)}else{const viaNativeFit=nativeFitAfterClamp&&!noUpstreamEvidence&&!unknownBaseline;log2("info",`[${session.id}] payload still over window ${limit} by local estimate (~${Math.round(result.payloadEstimate)} tok, ${result.compressedRanges} range(s) folded) ${viaNativeFit?`but the outbound view (~${Math.round(outboundCalibrated)} tok) + clamped output budget ${outboundBudgetTokens??0} fits the native window ${resolvedNativeWindow}`:"with no upstream evidence"} \u2014 forwarding once for the upstream to arbitrate size before failing fast (#3146/#4185)`);return outbound}}const status=f2?.kind==="upstream"&&f2.status===429?503:f2?.kind==="exhausted"&&f2.deterministic&&!payloadFitsWindow?413:502;const progressContinues=f2?.kind==="exhausted"&&!f2.deterministic&&result.compressedRanges>0;if(status===413)noteLocalRefusal(session,currentOrigin,model,limit);const retryable=progressContinues?true:f2?.retryable===false?false:f2?.retryable===true||f2?.kind==="upstream"&&f2.status!==void 0&&(f2.status===429||f2.status>=500);let ffDetail=f2?.detail??"the payload still exceeds the window after preflight compression";if(progressContinues){const shortfall=foldedCalibratedSize!==void 0?Math.max(0,limit-foldedCalibratedSize):void 0;ffDetail+=` ${result.compressedRanges} range(s) folded this turn persist in the session \u2014 the next attempt starts from a smaller baseline and continues the fold${shortfall!==void 0?` (~${shortfall.toLocaleString("en-US")} tokens short of the target)`:""}.`}const ff=failFast(status,ffDetail,retryable,result.compressedRanges>0?foldedCalibratedSize:void 0,result.rangesRemaining);return ff}var CONTEXTUAL_USER_FRAGMENT_MARKERS=[["# AGENTS.md instructions","</INSTRUCTIONS>"],["<environment_context>","</environment_context>"]];function asciiCI(hay,needle){if(hay.length!==needle.length)return false;for(let i=0;i<hay.length;i++){const h=hay.charCodeAt(i);const n=needle.charCodeAt(i);if(h===n)continue;const hl=h>=65&&h<=90?h+32:h;const nl=n>=65&&n<=90?n+32:n;if(hl!==nl)return false}return true}function isContextualUserFragment(text2){const t=text2.trim();if(!t)return false;return CONTEXTUAL_USER_FRAGMENT_MARKERS.some(([open,close])=>asciiCI(t.slice(0,open.length),open)&&asciiCI(t.slice(t.length-close.length),close))}var AUTO_INJECTED_NOTIFICATION_PREFIXES=["The approval policy changed from","Current runtime context","Time sampled while preparing turn"];function isAutoInjectedNotification(text2){const t=text2.trim();if(!t)return false;return AUTO_INJECTED_NOTIFICATION_PREFIXES.some(p2=>asciiCI(t.slice(0,p2.length),p2))}function deriveTitle(messages){for(const m2 of messages){if(m2.role!=="user"||m2.contentType!=="text")continue;const raw=m2.text??"";if(!raw.trim())continue;if(isContextualUserFragment(raw))continue;if(isAutoInjectedNotification(raw))continue;const clean=raw.replace(/\s+/g," ").trim();return clean.length>60?clean.slice(0,57)+"\u2026":clean}return void 0}function reapOrphansLogged(session,msgs,log2,sessionId){const{reaped}=reapOrphanBlocks(session,msgs,deactivateBlock);if(reaped.length===0)return;log2("warn",`[${sessionId}] orphan-gc deactivated ${reaped.length} block(s) whose source messages left the client history (${reaped.join(", ")}) \u2014 the client or another compression plugin deleted summarized content; those summaries can no longer be decompressed (#1206)`);recordConflict(session,"orphan-reap",`${reaped.length} block(s) deactivated: ${reaped.join(", ")}`)}function headerValue2(req,name){const lower=name.toLowerCase();for(const[k2,v2]of Object.entries(req.headers)){if(k2.toLowerCase()===lower)return Array.isArray(v2)?v2[0]:v2}return void 0}function formatBytes(n){if(n<1024)return`${n}B`;if(n<1024*1024)return`${(n/1024).toFixed(1)}KiB`;if(n<1024*1024*1024)return`${(n/(1024*1024)).toFixed(1)}MiB`;return`${(n/(1024*1024*1024)).toFixed(1)}GiB`}var SLOW_SESSION_MSG_WARN=1e3;function logRequestCost(log2,sessionId,msgs,inboundBytes,t0,outbound){const ms2=Math.max(0,Math.round(performance3.now()-t0));const outboundField=outbound!==void 0?`, outbound=${formatBytes(Buffer.byteLength(outbound))}`:"";const view=currentFetchTransport()?", view=ws-expanded":"";log2("info",`[${sessionId}] request: ${msgs??"?"} msgs, inbound=${formatBytes(inboundBytes)}${outboundField}, local=${ms2}ms${view}`);if(msgs!==null&&msgs>SLOW_SESSION_MSG_WARN){log2("warn",`[${sessionId}] slow-session: ${msgs} msgs / inbound=${formatBytes(inboundBytes)} took local=${ms2}ms \u2014 per-turn O(messages) synchronous scans are starving the event loop (#4528); consider closing/restarting the session or enabling compression`)}}var BodyTooLargeError=class extends Error{constructor(limit){super(`request body exceeds ${limit} bytes`);this.limit=limit;this.name="BodyTooLargeError"}limit};function readBody(req){return new Promise((resolve2,reject)=>{const chunks=[];let size=0;let aborted=false;req.on("data",c=>{if(aborted)return;size+=c.length;if(size>limitsReceiveBytes()){aborted=true;req.destroy();reject(new BodyTooLargeError(limitsReceiveBytes()));return}chunks.push(c)});req.on("end",()=>{if(!aborted)resolve2(Buffer.concat(chunks))});req.on("error",e=>{if(!aborted)reject(e)})})}function logMsg(opts,level,msg){if(!opts.log)return;log(level,msg)}init_fetch_transport();init_logger();init_upstream_fail();var INLINE_ORIGIN="http://billion-context.inline";var INLINE_HOSTNAME=new URL(INLINE_ORIGIN).hostname;function normalizeHeaderPairs(value){if(Array.isArray(value))return value.map(([k2,v2])=>[k2,String(v2)]);const out=[];for(const[k2,v2]of Object.entries(value)){if(v2===void 0)continue;out.push([k2,Array.isArray(v2)?v2.join(", "):String(v2)])}return out}var HOP_HEADERS=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","host","content-length"]);async function bodyToBuffer(body){if(body===null||body===void 0)return Buffer2.alloc(0);if(typeof body==="string")return Buffer2.from(body);if(body instanceof URLSearchParams)return Buffer2.from(body.toString());if(body instanceof Blob)return Buffer2.from(await body.arrayBuffer());if(body instanceof ArrayBuffer)return Buffer2.from(body);if(ArrayBuffer.isView(body))return Buffer2.from(body.buffer.slice(body.byteOffset,body.byteOffset+body.byteLength));const iterator=body[Symbol.asyncIterator];if(typeof iterator==="function"){const parts=[];for await(const chunk of body)parts.push(Buffer2.from(chunk));return Buffer2.concat(parts)}throw new Error(`inline engine: unsupported request body type ${Object.prototype.toString.call(body)}`)}var webPort=0;var webServer;var InlineReq=class extends EventEmitter{url;method;headers={};socket={get localPort(){return webPort},remoteAddress:"127.0.0.1"};chunks;deliveryScheduled=false;constructor(url,method,headers,body){super();this.url=url;this.method=method;this.headers=headers;this.chunks=body.length>0?[body]:[]}on(event,fn){super.on(event,fn);if(event==="data"||event==="end"||event==="error")this.scheduleDelivery();return this}destroy(){}scheduleDelivery(){if(this.deliveryScheduled)return;this.deliveryScheduled=true;queueMicrotask(()=>{for(const c of this.chunks)this.emit("data",c);this.emit("end")})}};var InlineRes=class extends EventEmitter{statusCode=200;statusMessage="";headersSent=false;writableEnded=false;destroyed=false;socket={get localPort(){return webPort},remoteAddress:"127.0.0.1",destroyed:false,bytesWritten:0};bodyStream;headHeaders=[];controller;committed=false;committedCb;constructor(){super();this.bodyStream=new ReadableStream({start:c=>{this.controller=c}})}onCommitted(cb){if(this.committed)cb();else this.committedCb=cb}markCommitted(){if(this.committed)return;this.committed=true;const cb=this.committedCb;this.committedCb=void 0;cb?.()}writeHead(status,reasonOrHeaders){if(this.headersSent)throw new Error("ERR_HTTP_HEADERS_SENT: Cannot change headers after they are sent to the client");this.statusCode=status;if(typeof reasonOrHeaders==="string")this.statusMessage=reasonOrHeaders;else if(reasonOrHeaders!==void 0)this.headHeaders.push(...normalizeHeaderPairs(reasonOrHeaders));this.headersSent=true;this.markCommitted();return this}write(chunk,cb){if(this.destroyed){cb?.();return false}const buf=typeof chunk==="string"?Buffer2.from(chunk):Buffer2.from(chunk);this.socket.bytesWritten+=buf.length;this.controller?.enqueue(buf);this.markCommitted();cb?.();return true}end(chunk,cb){if(this.destroyed){cb?.();return}if(chunk!==void 0)this.write(chunk);if(!this.writableEnded){this.writableEnded=true;this.markCommitted();try{this.controller?.close()}catch{}this.emit("finish");this.emit("close");cb?.()}}destroy(err2){if(this.destroyed)return;this.destroyed=true;this.socket.destroyed=true;try{this.controller?.error(err2??new Error("client aborted"))}catch{}if(!this.writableEnded)this.emit("close")}};async function toInlineReq(input,init){let url;let baseHeaders;let requestMethod;let requestBody;if(typeof input==="string")url=input;else if(input instanceof URL)url=input.href;else{url=input.url;baseHeaders=input.headers;requestMethod=input.method;requestBody=await input.arrayBuffer().catch(()=>null)}const headers=new Headers(baseHeaders);if(init?.headers!==void 0)new Headers(init.headers).forEach((v2,k2)=>headers.set(k2,v2));const headerMap={};headers.forEach((value,key2)=>{const existing=headerMap[key2];headerMap[key2]=existing===void 0?value:Array.isArray(existing)?[...existing,value]:[existing,value]});const method=(init?.method??requestMethod??"GET").toUpperCase();const bodySource=init?.body!==void 0?init.body:requestBody;const body=await bodyToBuffer(bodySource);const parsed=new URL(url);if(headerMap["host"]===void 0)headerMap["host"]=parsed.hostname===INLINE_HOSTNAME?"127.0.0.1":parsed.host;return new InlineReq(parsed.pathname+parsed.search,method,headerMap,body)}function responseFrom(res){const headers=new Headers;for(const[k2,v2]of res.headHeaders){if(HOP_HEADERS.has(k2.toLowerCase()))continue;headers.append(k2,v2)}return new Response(res.bodyStream,{status:res.statusCode,statusText:res.statusMessage||void 0,headers})}function makeDispatcher(ctx){return async(input,init,rawFetch)=>{const req=await toInlineReq(input,init);const res=new InlineRes;const signal=init?.signal;let onAbort;let abortPromise;if(signal!=null){abortPromise=new Promise((_2,reject)=>{onAbort=()=>{try{res.destroy(new Error("client aborted"))}catch{}reject(signal.reason??new DOMException("The operation was aborted.","AbortError"))};if(signal.aborted)onAbort();else signal.addEventListener("abort",onAbort,{once:true})});void abortPromise.catch(()=>{})}const committed=new Promise(resolveCommit=>res.onCommitted(resolveCommit));const transport=(url,options)=>(rawFetch??globalThis.fetch)(url,options);const pipeline=withFetchTransport(transport,()=>handle(req,res,ctx.opts,ctx.core,ctx.config,ctx.log,ctx.instanceId,ctx.instanceStartedAt,ctx.proxyWatchers,ctx.initialWatcherPid,ctx.adminCtx));let abortSurfaced=false;void pipeline.then(()=>{if(!res.writableEnded&&!res.destroyed)res.end()},err2=>{const msg=String(err2);const e=err2;const clientAbort=(e?.name==="AbortError"||/abort/i.test(String(e?.message??"")))&&(res.destroyed||res.writableEnded);if(clientAbort&&!abortSurfaced)ctx.log("info",`client aborted mid-stream: ${msg}`);else if(!isExpectedFailFast(err2)){if(err2 instanceof Error&&err2.stack)ctx.log("error",`${msg}
|
|
7244
|
+
${GENERATION_BOUNDARY_NOTE}`:"";const systemPrompt=withProjectAttribution(withMcpDialectNote(withMarkerIntegrityNote(withSummaryBudgetNote(textProtocol?buildCompressHybridSystemPrompt(prepared.prompts??defaultPrompts,messageTimestampSections(conversationPromptSections(prepared.surface?.promptSections,externalSummaryEnabled(config)),"hybrid")):buildCompressSystemPrompt(prepared.prompts??defaultPrompts,messageTimestampSections(conversationPromptSections(prepared.surface?.promptSections,externalSummaryEnabled(config)))),externalSummaryEnabled(config)),visibilityMarkers),prepared.mcpDialectNote===true))+genBoundaryNote+absorbSection;const adapter=pickAdapter(prepared.protocol,parsedReq,textProtocol,prepared.responsesProjection,prepared.anthropicSystem,prepared.openaiSystemText,absorbActive?absorbToolName(loopConfig):void 0,prepared.google,prepared.systemNotes,opts.streamErrorShape,prepared.anthropicCacheMarks,prepared.anthropicClientCacheControls,absorbActive);const refreshFolded=async current=>{return withSessionLock(prepared.session,async()=>{const turn=core.processTurn({messages:prepared.originalMessages,state:prepared.session.state,config:loopConfig,tokenCount:usageGradeInputBaseline(prepared.session),renderTags:prepared.renderTags??"text-only",contentStore:contentStoreOf(prepared.session)});prepared.session.state=turn.state;adoptContentStore(prepared.session,turn.contentStore);const viewed=applyAbsorbView(turn.messages,turn.state,loopConfig,effectiveTokenCount(prepared.session,turn.messages).tokens);const records=current.filter(m2=>typeof m2.id==="string"&&m2.id.startsWith("acp_loop_"));const out=[...stripKernelSummaries(viewed,turn.state),...records];const dropped=prepared.dropReasoning?prepared.dropReasoning(out):out;const ordered=prepared.protocol==="responses"?repairResponsesAssistantOrdering(dropped,prepared.originalMessages):dropped;return ordered})};const loopDumpDir=opts.dumpSse;const loopBillingUpstream=route?.rewrittenUrl??(/^https?:\/\//i.test(req.url??"")?req.url??void 0:opts.upstream);const loop=runCompressLoop(responseBody,{core,config,messages:prepared.processedMessages.length>0?prepared.processedMessages:prepared.originalMessages,compressMessages:prepared.originalMessages,session:prepared.session,reply,log:ctx.log,proxyUrl,skippedProxy,upstreamOrigin:targetOrigin,protocol:prepared.protocol,textProtocol,debug:opts.debug,refreshFolded,visibilityMarkers,dumpSse:loopDumpDir?(name,stream2)=>dumpStreamToFile(stream2,loopDumpDir,name):void 0,imageLearn:{host:upstreamHost(loopBillingUpstream),fp:`${imageBillingFor5(opts,loopBillingUpstream)}:${imageTokenCapFor5(opts,loopBillingUpstream)}`}},parsedReq,{url:upstreamUrl,headers:reqHeaders,wireTransform,resign:applyResign,responseStreamTransform:v1Active?v1UnwrapStream:void 0},adapter,systemPrompt,clientAbort.signal);let protocolFragmentWarned=false;for await(const chunk of loop){if(res.destroyed||res.writableEnded)break;{const s3=chunk.toString("utf8");if(s3.includes("<acp ")||s3.includes("</acp")){log2("warn",`[${prepared.session.id}] [tag-echo] detected: ${prepared.protocol} response stream contains <acp tag`)}else if(!protocolFragmentWarned&&containsToolCallXmlFragment(s3)){protocolFragmentWarned=true;log2("warn",`[${prepared.session.id}] [tag-echo] detected: ${prepared.protocol} response stream contains tool-call XML fragment (left untouched)`)}}res.write(chunk);if(res.writableNeedDrain){await awaitDrain(res)}if(res.destroyed||res.writableEnded)break}res.end()}catch(e){emitStreamError(res,prepared.protocol,e?.message??String(e),m2=>log2("error",`[${prepared.session.id}] ${m2}`),opts.streamErrorShape)}finally{clearUpstreamTimer();if(dumpRaw)await dumpRaw;markDirty(prepared.session)}}else{try{const buf=responseBody?Buffer.from(await new Response(responseBody).arrayBuffer()):Buffer.alloc(0);let text2=Buffer.from(buf).toString("utf8");try{let json=JSON.parse(text2);if(prepared.protocol==="responses"&&prepared.responsesTextProtocol){const requestBody=JSON.parse(typeof body==="string"?body:body.toString("utf8"));const requestHeaders=buildForwardHeaders(headers);const visibilityMarkers=resolveCompress(opts.routes,route?.rewrittenUrl,requestBody.model,opts.compress).visibilityMarkers??true;json=await compressLoopResponsesJson(json,{core,config,messages:prepared.originalMessages,session:prepared.session,log:ctx.log,proxyUrl,textProtocol:true,visibilityMarkers,signal:clientAbort.signal},requestBody,{url:upstreamUrl,headers:requestHeaders,wireTransform,resign:applyResign})}const rawUsage=prepared.protocol==="google"?json.usageMetadata??json.usage:json.usage;const u2=rawUsage??{};const{total,cached,creation}=usageTotals(prepared.protocol,u2);const out=usageOutputTotal(prepared.protocol,u2);const reportedCached=typeof cached==="number"?cached:null;const billed=typeof total==="number"?total:0;if(billed>0||reportedCached!==null){settleUsageReport(prepared.session,{total:billed,reportedCached,output:out,protocol:prepared.protocol,upstream:targetOrigin,creation});if(reportedCached!==null)warnCacheCollapse(prepared.session,billed,reportedCached);const hitPct2=reportedCached!==null&&billed>0?Math.round(100*reportedCached/billed):void 0;log("info",`[${prepared.session.id}] [acp-usage] input=${billed} ${hitPct2===void 0?"(no cache report)":`cached=${reportedCached} (cache hit ${hitPct2}%)`}${billed<=0?" (zero-total: lastInputTokens kept)":""}`)}else{diagnoseSuccessWithoutUsage(prepared.session,"proxy-json")}if(typeof out==="number"){prepared.session.stats.outputTokens+=out;billOutputUsage(prepared.session,out)}if(prepared.protocol==="openai"){await withSessionLock(prepared.session,()=>rewriteOpenaiJsonResponseAsync(json,ctx,clientAbort.signal))}else if(prepared.protocol==="responses"){await withSessionLock(prepared.session,()=>rewriteResponsesJsonResponseAsync(json,ctx,clientAbort.signal))}else if(prepared.protocol==="google"){await withSessionLock(prepared.session,()=>rewriteGoogleJsonResponseAsync(json,ctx,clientAbort.signal))}else{await withSessionLock(prepared.session,()=>rewriteJsonResponseAsync(json,ctx,clientAbort.signal))}captureHandoffJson(reply,prepared.protocol,json);reply?.save();res.end(JSON.stringify(json))}catch{res.end(text2)}}finally{clearUpstreamTimer();markDirty(prepared.session)}}}finally{clearUpstreamTimer();if(dumpRaw)await dumpRaw}}async function resolveFakeCompletion(stream2,opts){let buffer=await readStreamToBuffer(stream2,fakeBufCap());const max=maxFakeCompletionRetries();const sid=opts.session.id;const priorStreak=opts.session.metadata.fakeCompletionStreak??0;if(max>0&&priorStreak<max&&isFakeCompletion(opts.protocol,buffer.toString("utf8"))){for(let attempt=1;attempt<=max&&!opts.signal.aborted;attempt++){const hinted=injectFakeCompletionHint(opts.protocol,opts.wireBody);if(hinted===null)break;const wireHinted=opts.wrapBody?opts.wrapBody(hinted):hinted;opts.log("warn",`[${sid}] fake completion (tool-call XML, no tool block); retry ${attempt}/${max} with corrective hint`);let r;try{opts.resign?.(opts.reqHeaders,wireHinted);r=await fetchWithTimeout(opts.upstreamUrl,{method:"POST",headers:opts.reqHeaders,body:wireHinted,...opts.proxyUrl?{dispatcher:proxyDispatcher(opts.proxyUrl)}:{}},void 0,opts.signal)}catch(e){opts.log("warn",`[${sid}] fake-completion retry failed: ${String(e)}; presenting original`);break}try{if(!r.response.ok||!r.response.body){opts.log("warn",`[${sid}] fake-completion retry rejected (HTTP ${r.response.status}); presenting original`);break}buffer=await readStreamToBuffer(r.response.body,fakeBufCap())}finally{r.clearTimer()}if(!isFakeCompletion(opts.protocol,buffer.toString("utf8")))break}}const stillFake=isFakeCompletion(opts.protocol,buffer.toString("utf8"));opts.session.metadata.fakeCompletionStreak=stillFake?priorStreak+1:0;markDirty(opts.session);return buffer}var warnedWireDropKeys=new Set;var WARNED_WIREDROP_KEY_CAP=4096;function warnDroppedOpenaiParts(parsed,sessionId,log2){const report=droppedOpenaiParts(parsed);if(!report)return;const key2=`${sessionId}:${report.types.join(",")}`;if(warnedWireDropKeys.has(key2))return;warnedWireDropKeys.add(key2);if(warnedWireDropKeys.size>WARNED_WIREDROP_KEY_CAP){warnedWireDropKeys.delete(warnedWireDropKeys.values().next().value)}log2("warn",`[${sessionId}] wire codec will drop ${report.count} non-user content part(s) with unrecognized type(s) [${report.types.join(", ")}] (first at message #${report.firstIndex}) \u2014 kernel 0.0.85+ preserves all user-message parts (DeepSeek Files API refs included, #1205/#1188) and mid-conversation system/developer messages ride verbatim (#4166), but parts riding assistant/tool messages and the leading system/developer run still reduce to text-only`)}var NON_CONVERSATION_RELAY_WARN_CAP=4096;var nonConversationRelayWarned=new Set;function selfAddressedLocalPath(reqUrl,localPort){if(!reqUrl.startsWith("http://")&&!reqUrl.startsWith("https://"))return void 0;if(localPort===void 0)return void 0;try{const u2=new URL(reqUrl);const port=u2.port!==""?Number(u2.port):u2.protocol==="https:"?443:80;if(port!==localPort)return void 0;const host=u2.hostname.replace(/^\[|\]$/g,"").toLowerCase();const mine=host==="0.0.0.0"||host==="::"||host==="localhost"||localMachineIps().has(normalizeIpLiteral(host));if(!mine)return void 0;return u2.pathname+u2.search}catch{}return void 0}function resolveUpstream(_opts,reqUrl,req){const mitmUpstream=readMitmUpstream(req?.socket);if(mitmUpstream){const mitmKey=mitmUpstream.replace(/^https:\/\//,"mitm://");return{upstream:mitmUpstream,rewrittenUrl:mitmKey+(reqUrl??"")}}const KNOWN_PROTOCOLS=["responses","anthropic","openai","google"];if(reqUrl.startsWith("/bili/")){let rest=reqUrl.slice(6);let explicitProtocol;for(const p2 of KNOWN_PROTOCOLS){const prefix=`${p2}/`;if(rest.startsWith(prefix+"http://")||rest.startsWith(prefix+"https://")){explicitProtocol=p2;rest=rest.slice(prefix.length);break}}if(rest.startsWith("http://")||rest.startsWith("https://")){try{const u2=new URL(rest);return{upstream:`${u2.protocol}//${u2.host}`,rewrittenUrl:rest,explicitProtocol,tunnel:true}}catch{}}}if(reqUrl.startsWith("http://")||reqUrl.startsWith("https://")){try{const u2=new URL(reqUrl);return{upstream:`${u2.protocol}//${u2.host}`,rewrittenUrl:reqUrl,tunnel:true}}catch{}}return void 0}var requestAborts=new WeakMap;function registerRequestAbort(res,ac){if(requestAborts.get(res)?.signal.aborted||res.destroyed||res.writableEnded||res.socket?.destroyed)ac.abort();requestAborts.set(res,ac)}function googlePathKind(urlPath){if(urlPath.includes(":streamGenerateContent"))return"stream-generate";if(urlPath.includes(":generateContent"))return"generate";if(urlPath.includes(":countTokens"))return"count-tokens";return null}function googleModelFromPath(urlPath){const m2=/\/models\/([^/:?]+):(?:streamGenerateContent|generateContent|countTokens)\b/.exec(urlPath);if(!m2||!m2[1])return void 0;try{return decodeURIComponent(m2[1])}catch{return m2[1]}}function vertexAnthropicModelFromPath(urlPath){const m2=/\/publishers\/anthropic\/models\/([^/:?]+):(?:streamRawPredict|rawPredict)\b/.exec(urlPath);if(!m2||!m2[1])return void 0;try{return decodeURIComponent(m2[1])}catch{return m2[1]}}async function createEngineContext(opts){const filePath=configureLogger(opts.logFile??defaultLogFile());if(shouldMuteStderrLegAfterFileLive(Boolean(process.env.BILI_LAUNCH_TOKEN?.trim()),process.stderr.isTTY)){onFileLegLive(()=>muteStderrLeg())}const core=createCore(resolveMessageTimestamps(opts.compress)?{timestamps:true}:void 0);const config=opts.kernelConfig;const log2=(level,msg)=>logMsg(opts,level,msg);const instanceId=randomUUID12();const instanceStartedAt=Date.now();let bootReady=false;const parentWatchPid=Number.parseInt(process.env.BILI_PARENT_PID??"",10);const initialWatcherPid=Number.isInteger(parentWatchPid)&&parentWatchPid>0&&parentWatchPid!==process.pid?parentWatchPid:null;const proxyWatchers=new Set;if(initialWatcherPid!==null)proxyWatchers.add(initialWatcherPid);const watcherLastSeen=new Map;const lifecycleHooks={};await initSessions();try{await getStore().ready()}catch(e){log2("error",`[storage] refusing to start: ${String(e)}`);process.exit(1)}loadConversations();log2("info",`[persist] ${getStore().enabled?"enabled":"disabled"}`);try{const adopted=await reconcileDerivedLineage(listSessions(),{log:log2,adoptionEnabled:opts.resumeInheritance!==false});if(adopted>0)log2("info",`[lineage-reconcile] restored fold state for ${adopted} forked session(s)`)}catch(e){log2("warn",`[lineage-reconcile] sweep failed: ${String(e)}`)}const gcCfg=gcConfigFromEnv();if(gcCfg.enabled&&getStore().enabled){void gcSessionFiles().catch(err2=>log2("warn",`[gc] sweep failed: ${String(err2)}`));const gcTimer=setInterval(()=>{void gcSessionFiles().catch(err2=>log2("warn",`[gc] sweep failed: ${String(err2)}`))},gcCfg.intervalMs);gcTimer.unref?.()}const tunnelAllowlist=tunnelAllowlistFromEnv();if(tunnelAllowlist.length>0)log2("info",`[tunnel] remote-client allowlist: ${tunnelAllowlist.join(", ")}`);if(filePath){log2("info",`[log] writing to ${filePath}`)}void loadRegistry();const adminCtx={opts,core,config,log:log2,instanceId,instanceStartedAt,proxyWatchers,initialWatcherPid,watcherLastSeen,requestShutdown:reason=>{lifecycleHooks.requestShutdown?.(reason)},bootReady:()=>bootReady};return{opts,core,config,log:log2,instanceId,instanceStartedAt,proxyWatchers,watcherLastSeen,initialWatcherPid,lifecycleHooks,markBootReady:()=>{bootReady=true},bootReady:()=>bootReady,adminCtx}}function imageBillingFor5(opts,upstreamUrl){const env=process.env.BILI_IMAGE_BILLING;const configured=env==="pixels"||env==="bytes"?env:findRoute(opts.routes,upstreamUrl)?.imageBilling??opts.imageBilling??"auto";return resolveImageBilling(configured,upstreamUrl)}function imageTokenCapFor5(opts,upstreamUrl){return findRoute(opts.routes,upstreamUrl)?.imageTokenCap??opts.imageTokenCap??0}function resignSettingsFor(opts,upstreamUrl,scheme=APIG_RESIGN_SCHEME){return resolveResignSettings(process.env,findRoute(opts.routes,upstreamUrl)?.resign,scheme)}function inboundResignCredential(reqHeaders,opts,upstreamUrl){const marker=String(Array.isArray(reqHeaders[APIG_RESIGN_HEADER])?reqHeaders[APIG_RESIGN_HEADER][0]??"":reqHeaders[APIG_RESIGN_HEADER]??"");if(!resignSettingsFor(opts,upstreamUrl).enabled||marker!==APIG_RESIGN_SCHEME)return void 0;const encoded=Array.isArray(reqHeaders[APIG_RESIGN_CREDENTIAL_HEADER])?reqHeaders[APIG_RESIGN_CREDENTIAL_HEADER][0]:reqHeaders[APIG_RESIGN_CREDENTIAL_HEADER];return decodeApigCredential(encoded)}function imageReserveFor(session,protocol,body,opts,upstreamUrl){const billing=imageBillingFor5(opts,upstreamUrl);const cap=imageTokenCapFor5(opts,upstreamUrl);const raw=typeof body==="string"||Buffer.isBuffer(body);const prior=raw?imageTokensInRawBody(protocol,body,billing,cap):imageTokensInParsedBody(protocol,body,billing,cap);if(prior<=0)return prior;const nImages=raw?countImagesInRawBody(protocol,body):countImagesInParsedBody(protocol,body);if(nImages<=0)return prior;return learnedImageReserve(session,upstreamHost(upstreamUrl),nImages,`${billing}:${cap}`,cap,prior)??prior}var headroomFallbackLogged=new Set;var headroomEffectiveLogged=new Set;var armJudgingWallLogged=new Set;function resolveKnownOutputCeiling(headers,parsed,routes,upstreamUrl,sessionHeaderName,resolvedModel){const model=resolvedModel!==void 0&&resolvedModel.length>0?resolvedModel:typeof parsed.model==="string"&&parsed.model.length>0?parsed.model:void 0;if(!model)return void 0;const agent=pluginAgentHeader(headers);const runtimeMax=(pluginHeadersMatchModel(headers,model)?pluginReportedMaxOutput(headers):void 0)??(agent!==void 0?pluginRuntimeInfoFor(agent,model)?.maxOutput:pluginRuntimeInfoForConversation(runtimeConversationId(headers,parsed,sessionHeaderName),model)?.maxOutput);if(typeof runtimeMax==="number"&&runtimeMax>0)return runtimeMax;const launcherMax=launcherMaxOutput(model);if(typeof launcherMax==="number"&&launcherMax>0)return launcherMax;const cfgOut=resolveConfiguredOutputLimit(routes,upstreamUrl,model);if(cfgOut!==void 0&&cfgOut>0)return cfgOut;let host;try{host=upstreamUrl!==void 0?new URL(upstreamUrl).host:void 0}catch{host=void 0}return peekRegistryOutputLimit(model,host)}var ACP_TAG_MARK="<acp ";function hasSignedThinkingBlock(m2){if(m2.contentType==="reasoning")return typeof m2.thinkingSignature==="string"&&m2.thinkingSignature.length>0;const raw=m2.rawAnthropicBlock;return raw?.type==="redacted_thinking"}function planReasoningDrop(msgs,reasoning,strictEcho){if(strictEcho)return new Set;if(msgs.some(hasSignedThinkingBlock))return new Set;return dropCompressReasoningIds(msgs,reasoning)}function applyReasoningDrop(msgs,plan2,log2,sessionId){if(plan2.size===0)return msgs;const out=msgs.filter(m2=>!plan2.has(m2.id));if(out.length!==msgs.length){log2("info",`[${sessionId}] compress-reasoning: dropped ${msgs.length-out.length} reasoning message(s) from closed compress turns (#651)`)}return out}var reasoningViolationState=new Map;var REASONING_VIOLATION_KEY_CAP=512;var REASONING_VIOLATION_ENTRY_CAP=4096;function fnv1aHex(text2){let h=2166136261;for(let i=0;i<text2.length;i++){h^=text2.charCodeAt(i);h=Math.imul(h,16777619)}return(h>>>0).toString(16).padStart(8,"0")}function violationIdentity(wire,ids,fallback){const clean=[...new Set(ids.filter(i=>i.length>0))].sort();if(clean.length>0){const shown=clean.slice(0,3).join(", ")+(clean.length>3?` (+${clean.length-3})`:"");return{key:`${wire}|${clean.join("|")}`,display:shown}}const digest=fnv1aHex(JSON.stringify(fallback??null).slice(0,8192));return{key:`${wire}|~${digest}`,display:`~${digest}`}}function trackViolationEpisode(sessionKey,current){let state7=reasoningViolationState.get(sessionKey);if(!state7){state7={seq:0,entries:new Map};reasoningViolationState.set(sessionKey,state7);if(reasoningViolationState.size>REASONING_VIOLATION_KEY_CAP){const oldest=reasoningViolationState.keys().next().value;if(oldest!==void 0)reasoningViolationState.delete(oldest)}}state7.seq+=1;const fresh=[];let ongoing=0;let maxRepeat=0;for(const c of current){const e=state7.entries.get(c.key);if(e&&e.lastSeen===state7.seq-1){e.count+=1;e.lastSeen=state7.seq;ongoing+=1;if(e.count>maxRepeat)maxRepeat=e.count;continue}const revived=e!==void 0;if(revived){e.count=1;e.lastSeen=state7.seq}else{state7.entries.set(c.key,{count:1,lastSeen:state7.seq});if(state7.entries.size>REASONING_VIOLATION_ENTRY_CAP){const oldestEntry=state7.entries.keys().next().value;if(oldestEntry!==void 0)state7.entries.delete(oldestEntry)}}fresh.push({display:c.display,revived})}return{fresh,ongoing,maxRepeat}}function violationTail(ongoing,maxRepeat){return ongoing>0?`; ${ongoing} already reported (up to \xD7${maxRepeat} repeats)`:""}function violationNamed(fresh,ongoing,maxRepeat){const named=fresh.slice(0,3).map(f2=>f2.display).join(", ")+(fresh.length>3?`, \u2026+${fresh.length-3}`:"");return`${named}${fresh.some(f2=>f2.revived)?" (re-violating after recovery)":""}${violationTail(ongoing,maxRepeat)} (window: since this proxy started)`}function warnReasoningPairs(wireMessages,log2,sessionId){let withRc=0;const violators=[];for(const m2 of wireMessages){const msg=m2;if(msg?.role!=="assistant")continue;if(typeof msg.reasoning_content==="string"){withRc++;continue}const tcs=Array.isArray(msg.tool_calls)?msg.tool_calls:void 0;if(!tcs||tcs.length===0)continue;violators.push(violationIdentity("openai",tcs.map(t=>typeof t?.id==="string"?t.id:""),tcs))}if(withRc===0)return;const tracked=trackViolationEpisode(`${sessionId}|openai`,violators);if(tracked.fresh.length===0)return;log2("warn",`[${sessionId}] reasoning-pair-violated: ${violators.length} assistant tool-call message(s) lack reasoning_content while ${withRc} carry it \u2014 strict-echo upstreams (DeepSeek thinking mode) will reject the request; first seen: ${violationNamed(tracked.fresh,tracked.ongoing,tracked.maxRepeat)} (#684/#762/#2864)`)}function warnAnthropicThinkingPairs(inboundMessages,outboundMessages,log2,sessionId){const thinkingIds=new Set;for(const m2 of inboundMessages){const msg=m2;if(msg?.role!=="assistant"||!Array.isArray(msg.content))continue;if(!msg.content.some(b2=>b2?.type==="thinking"))continue;for(const b2 of msg.content){if(b2?.type==="tool_use"&&typeof b2.id==="string")thinkingIds.add(b2.id)}}if(thinkingIds.size===0)return;const lost=[];for(const m2 of outboundMessages){const msg=m2;if(msg?.role!=="assistant"||!Array.isArray(msg.content))continue;if(msg.content.some(b2=>b2?.type==="thinking"))continue;for(const b2 of msg.content){if(b2?.type==="tool_use"&&typeof b2.id==="string"&&thinkingIds.has(b2.id)){lost.push(violationIdentity("anthropic",[b2.id],b2))}}}const tracked=trackViolationEpisode(`${sessionId}|anthropic`,lost);if(tracked.fresh.length===0)return;log2("warn",`[${sessionId}] thinking-pair-violated: ${lost.length} tool_use block(s) lost their inbound thinking block in the outbound rebuild \u2014 a stripped signature pair is rejected by the API; first seen: ${violationNamed(tracked.fresh,tracked.ongoing,tracked.maxRepeat)} (#684/#1327/#2864)`)}function warnResponsesReasoningPairs(input,log2,sessionId){let withReasoning=0;let split=0;let runs=0;const orphans=[];let runCalls=0;let runReasoning=0;let runIdents=[];const closeRun=()=>{if(runCalls>0&&runReasoning===0){split+=runCalls;runs++;orphans.push(...runIdents)}runCalls=0;runReasoning=0;runIdents=[]};for(const item of input){const it2=item;const t=it2?.type;if(t==="reasoning"){withReasoning++;runReasoning++;continue}if(t==="function_call"||t==="custom_tool_call"){runCalls++;runIdents.push(violationIdentity("responses",typeof it2.call_id==="string"?[it2.call_id]:[],it2));continue}if(t==="function_call_output"||t==="custom_tool_call_output")continue;if(t==="message"&&it2.role==="assistant")continue;closeRun()}closeRun();if(withReasoning===0)return;const tracked=trackViolationEpisode(`${sessionId}|responses`,orphans);if(tracked.fresh.length===0)return;log2("warn",`[${sessionId}] reasoning-pair-violated: ${split} tool-call item(s) in ${runs} assistant run(s) lack any reasoning item while ${withReasoning} exist \u2014 strict-echo upstreams will reject the request; first seen: ${violationNamed(tracked.fresh,tracked.ongoing,tracked.maxRepeat)} (#684/#1479/#2864)`)}function buildCarrierIndex(messages){const callIds=new Set;const compressCalls=[];for(const m2 of messages){if(m2.contentType!=="tool-call")continue;if(m2.toolCallId)callIds.add(m2.toolCallId);if(m2.toolName===COMPRESS_TOOL_NAME)compressCalls.push(m2)}let rangePairs=null;const ensureRangePairs=()=>{if(!rangePairs){rangePairs=new Map;for(const c of compressCalls){let parsed;try{parsed=JSON.parse(c.text??"")}catch{continue}const obj=parsed;const ranges=Array.isArray(obj?.content)?obj.content:[obj];for(const r of ranges){if(typeof r?.startId!=="string"||!r.startId||typeof r?.endId!=="string"||!r.endId)continue;let ends=rangePairs.get(r.startId);if(!ends){ends=new Set;rangePairs.set(r.startId,ends)}ends.add(r.endId)}}}return rangePairs};return{callIds,compressCalls,ensureRangePairs}}function stripKernelSummaries(messages,state7){const{callIds,compressCalls,ensureRangePairs}=buildCarrierIndex(messages);const carried=new Set;for(const b2 of state7.blocks){if(!b2.active||!b2.compressCallId)continue;const present=isPluginFoldCallId(b2.compressCallId)?!b2.startRef||!b2.endRef?compressCalls.length>0:ensureRangePairs().get(b2.startRef)?.has(b2.endRef)??false:callIds.has(b2.compressCallId);if(present){carried.add(`acp_summary_${b2.blockId}`)}}return messages.filter(m2=>!(m2.id??"").startsWith("acp_summary_")||!carried.has(m2.id))}var RESPONSES_TURN_SEPARATOR="[The exchange between these two assistant turns was compressed.]";function repairResponsesAssistantOrdering(folded,original){const runOf=new Map;const runHasBody=new Map;let run=0;let inRun=false;for(const m2 of original){if(m2.role==="assistant"){if(!inRun){run++;inRun=true}runOf.set(m2.id,run);if(m2.contentType!=="reasoning")runHasBody.set(run,true)}else{inRun=false}}const survivorCount=new Map;for(const m2 of folded){const r=m2.role==="assistant"?runOf.get(m2.id):void 0;if(r!==void 0)survivorCount.set(r,(survivorCount.get(r)??0)+1)}const out=[];let phase=-1;let seenReasoning=false;let sepSeq=0;const pushSeparator=()=>{sepSeq++;out.push({id:`${RESPONSES_TURN_SEPARATOR_ID_PREFIX}${sepSeq}`,role:"user",contentType:"text",text:RESPONSES_TURN_SEPARATOR});phase=-1;seenReasoning=false};for(const m2 of folded){if(m2.role!=="assistant"){out.push(m2);phase=-1;seenReasoning=false;continue}const kind=m2.contentType==="reasoning"?"reasoning":m2.contentType==="tool-call"?"tool-call":"message";const r=runOf.get(m2.id);if(kind==="reasoning"&&r!==void 0&&runHasBody.get(r)&&survivorCount.get(r)===1)continue;if(kind==="reasoning"&&(phase>0||seenReasoning)||kind==="message"&&phase===2)pushSeparator();out.push(m2);if(kind==="reasoning"){phase=Math.max(phase,0);seenReasoning=true}else if(kind==="message")phase=Math.max(phase,1);else phase=Math.max(phase,2)}return out}function diagTagSummary(messages,sessionId,strategy){let textTagged=0;let toolTagged=0;for(const m2 of messages){const hasTag=(m2.text??"").includes(ACP_TAG_MARK);if(!hasTag)continue;if(m2.contentType==="tool-call"||m2.contentType==="tool-result")toolTagged++;else textTagged++}return`[${sessionId}] processTurn: ${messages.length} msgs, renderTags=${strategy}, ${textTagged} text tagged, ${toolTagged} tool tagged (should be 0 with text-only)`}function diagNudge(turn,sessionId,tokenCount,limit,model,willInject,decidePending=false,surfaceOff){const n=turn.nudge;if(!n)return`[${sessionId}] nudge: unavailable`;const b2=n.breakdown??{};const pct2=limit>0?`${Math.round(tokenCount/limit*100)}%`:"?";const growth=b2["growth"]??0;const floor=b2["growthFloor"]??0;const interval=b2["nudgeGrowthTokens"]??0;const pendingT1=b2["pendingT1"]??0;const ref=b2["growthReference"]??0;const inject=willInject?decidePending?`INJECT-PENDING T${n.tier??"?"}`:n.shouldInject?`INJECT T${n.tier??"?"}`:`INJECT-ESC T${n.tier??"?"}`:n.shouldInject?`ARMED-SUPPRESSED T${n.tier??"?"}`:"idle";const modelTag=model?` model=${model}`:"";const offTag=surfaceOff?`, ${surfaceOff}`:"";return`[${sessionId}] nudge ${inject}: usage=${pct2} (${tokenCount}/${limit}), growth=${growth}/${floor} (ref=${ref}, interval=${interval}), pendingT1=${pendingT1}/${interval}${modelTag}${offTag}, reason="${n.reason.slice(0,120)}"`}var SIDE_LANE_ANCHOR_MIN_ABS_DELTA=25e3;var SIDE_LANE_ANCHOR_IMPOSSIBLE_RATIO=8;function effectiveTokenCount(session,msgs,inboundImageTokens=0){const anchorStale=usageAnchorCycleStale(session.stats);const payloadUpperNow=estimateCoreMessagesUpper(msgs)+inboundImageTokens;const anchorImpossible=session.stats.lastInputTokens>0&&(session.stats.lastUsagePayloadUpper??0)>0&&payloadUpperNow>=session.stats.lastInputTokens*SIDE_LANE_ANCHOR_IMPOSSIBLE_RATIO&&payloadUpperNow>=session.stats.lastUsagePayloadUpper*SIDE_LANE_ANCHOR_IMPOSSIBLE_RATIO&&payloadUpperNow-session.stats.lastInputTokens>SIDE_LANE_ANCHOR_MIN_ABS_DELTA;if(!anchorStale&&session.stats.lastInputTokensSource==="usage"&&(session.stats.compressCreditTokens??0)>0&&session.stats.lastInputTokens>=0)return{tokens:session.stats.lastInputTokens,source:"usage"};if(!anchorStale&&!anchorImpossible&&session.stats.lastInputTokens>0&&(session.stats.lastInputTokensSource==="usage"||session.stats.lastInputTokensSource==="overflow-arm")&&staleSmallAnchorFallback(session.stats,session.stats.lastInputTokens)===null)return{tokens:session.stats.lastInputTokens,source:"usage"};const anchored=postRebuildAnchorTokens(session);if(anchored>0)return{tokens:anchored,source:"estimate"};const raw=payloadUpperNow;const grade=session.stats.lastUsageGradeTokens;if(!anchorStale&&grade!==void 0&&grade>0){const fallback=staleSmallAnchorFallback(session.stats,grade);if(fallback!==null)return{tokens:fallback,source:"estimate"};return{tokens:grade,source:"usage"}}if(session.metadata.anonymousPrefixAffinity)return{tokens:raw,source:"estimate"};const est=session.stats.localInputEstimate??0;if(est<=0)return{tokens:0,source:"estimate"};return{tokens:Math.min(est,raw),source:"estimate"}}function usageGradeInputBaseline(session){return session.stats.lastInputTokensSource==="usage"?session.stats.lastInputTokens:0}function scrubAnthropicPck(protocol,bodyBuffer,log2){if(protocol!=="anthropic"||bodyBuffer.length===0)return bodyBuffer;let parsed;try{parsed=JSON.parse(bodyBuffer.toString("utf8"))}catch{return bodyBuffer}if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed))return bodyBuffer;const p2=parsed;if(!Object.prototype.hasOwnProperty.call(p2,"prompt_cache_key"))return bodyBuffer;delete p2.prompt_cache_key;log2("debug",`stripped prompt_cache_key from verbatim anthropic forward (#1403)`);return Buffer.from(JSON.stringify(p2),"utf8")}function scrubCompatDrop(bodyBuffer,dropPaths,log2){if(dropPaths.length===0||bodyBuffer.length===0)return bodyBuffer;let parsed;try{parsed=JSON.parse(bodyBuffer.toString("utf8"))}catch{return bodyBuffer}if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed))return bodyBuffer;const dropped=dropCompatFieldsJson(parsed,dropPaths);if(dropped===0)return bodyBuffer;log2("info",`stripped ${dropped} field(s) per compat.dropFields (${dropPaths.join(", ")}) from verbatim forward (#1757)`);return Buffer.from(JSON.stringify(parsed),"utf8")}function isCountTokensRequest(method,urlPath,hasBody){return method==="POST"&&hasBody&&!countTokensPassthrough()&&(urlPath.endsWith("/messages/count_tokens")||googlePathKind(urlPath)==="count-tokens")}function prepareCountTokens(parsed,core,config,log2,session){const sessionId=session.id;try{const{msgs,cacheControls}=anthropicToCore(parsed);const turn=core.processTurn({messages:msgs,state:session.state,config:ccrLoopConfig(session,config),tokenCount:usageGradeInputBaseline(session),renderTags:renderNone()?"none":"text-only",contentStore:contentStoreOf(session)});const stripped=stripKernelSummaries(turn.messages,turn.state);const rebuiltMessages=coreToAnthropic(stripped,cacheControls);log2("info",`[${sessionId}] count_tokens pruned: ${msgs.length} \u2192 ${stripped.length} msgs`);const rebuilt={...parsed,messages:rebuiltMessages};delete rebuilt.prompt_cache_key;return{body:JSON.stringify(rebuilt),session,processedMessages:[],originalMessages:msgs,protocol:"anthropic",stream:false,compressInjected:false}}catch(err2){log2("warn",`[${sessionId}] count_tokens prune failed, forwarding unchanged: ${String(err2)}`);const fallback={...parsed};delete fallback.prompt_cache_key;return{body:JSON.stringify(fallback),session,processedMessages:[],originalMessages:[],protocol:"anthropic",stream:false,compressInjected:false}}}var loggedUpstreamProxyDecisions=new Set;function logUpstreamProxyDecision(opts,upstreamUrl,decision){if(!upstreamUrl)return;let host=upstreamUrl;try{host=new URL(upstreamUrl).host}catch{}const key2=`${host}|${decision.proxy??""}|${decision.source}`;if(loggedUpstreamProxyDecisions.has(key2))return;loggedUpstreamProxyDecisions.add(key2);const via=decision.proxy?`via ${maskUrlForLog(decision.proxy)}`:"direct";logMsg(opts,"info",`[upstream-proxy] ${maskHostPortForLog(host)} ${via} (source=${decision.source})`)}function forwardUpstreamUrl(req,opts,route){const reqUrl=req.url??"";const isAbsoluteUrl=/^https?:\/\//i.test(reqUrl);const rewritten=route?route.rewrittenUrl:isAbsoluteUrl?reqUrl:opts.upstream+reqUrl;return rewritten.replace(/^mitm:\/\//,"https://")}function buildForwardTarget(req,opts,route,affinity,hopMarker){const upstreamUrl=forwardUpstreamUrl(req,opts,route);const headers={};const reqConnNamed=connectionNamedHeaders(req.headers["connection"]);for(const[k2,v2]of Object.entries(req.headers)){const lower=k2.toLowerCase();if(UPSTREAM_HOP_HEADERS.has(lower)||reqConnNamed.has(lower)||v2===void 0)continue;if(lower===APIG_RESIGN_HEADER||lower===APIG_RESIGN_CREDENTIAL_HEADER)continue;headers[k2]=Array.isArray(v2)?v2.join(", "):v2}if(hopMarker!==void 0)headers[BILI_HOP_HEADER]=hopMarker;if(route?.tunnel){let destLoopback=false;let destAdminPath=false;try{const du=new URL(upstreamUrl);const lit=parseIpLiteral(du.hostname.replace(/^\[|\]$/g,""));destLoopback=lit!==null&&classifyIp(lit)==="loopback";const dp=du.pathname;destAdminPath=dp==="/__bili/"||dp.startsWith("/__bili/")||dp==="/__acp/"||dp.startsWith("/__acp/")}catch{}if(!(isLoopbackAddress(req.socket.remoteAddress)&&destLoopback&&destAdminPath))headers[BILI_TUNNEL_HEADER]="1"}headers["host"]=new URL(upstreamUrl).host;stripRemoteCompactionBetaFeature(headers);const convSource=conversationHeaderSource(req.headers);if(affinity&&(!convSource||convSource.name==="x-bili-plugin-conversation")){headers["x-session-id"]=affinity}const decision=resolveProxyDecision(opts.routes,opts.proxy,route?.rewrittenUrl??upstreamUrl,opts.proxyFallback);logUpstreamProxyDecision(opts,upstreamUrl,decision);return{upstreamUrl,headers,proxyUrl:decision.proxy,skippedProxy:decision.skippedProxy}}async function runNudgeDecision(args){const{req,opts,protocol,sideBody,session,log:log2}=args;let outcome;try{const route=resolveUpstream(opts,req.url??"",req);const target=buildForwardTarget(req,opts,route);let url=target.upstreamUrl;if(protocol==="google"&&url.includes(":streamGenerateContent")){url=url.replace(":streamGenerateContent",":generateContent")}const bodyStr=JSON.stringify(sideBody);const headers={"content-type":"application/json",...target.headers};const resignCtx=inboundResignCredential(req.headers,opts,target.upstreamUrl);if(resignCtx!==void 0){try{resignApig(headers,resignCtx,"POST",target.upstreamUrl,bodyStr,findRoute(opts.routes,target.upstreamUrl))}catch(err2){log2("warn",`[acp-decide] session=${session.id} re-sign failed; sending the previous signature: ${String(err2)}`)}}const{response,clearTimer}=await fetchWithTimeout(url,{method:"POST",headers,body:bodyStr,dispatcher:proxyDispatcher(target.proxyUrl)},DECIDE_TIMEOUT_MS);try{if(!response.ok){outcome={kind:"failed",detail:`HTTP ${response.status}`}}else{const text2=await response.text();let json=null;try{json=JSON.parse(text2)}catch{json=null}outcome=parseDecision(json!==null?extractDecisionText(protocol,json):extractSummaryFromSse(protocol,text2))}}finally{clearTimer()}}catch(e){outcome={kind:"failed",detail:String(e)}}recordDecision(session.metadata,outcome.kind!=="failed");markDirty(session);log2(outcome.kind==="failed"?"warn":"info",`[acp-decide] session=${session.id} ${protocol}: ${outcome.kind==="failed"?outcome.detail:outcome.kind==="yes"?`yes${outcome.range?` (${outcome.range})`:""}`:"no"}`);return outcome}function isPreflightFailFast(outcome){return"failFast"in outcome}var PREFLIGHT_KEEPALIVE_MS=15e3;var DOOMED_PROBE_BYTES_PER_TOKEN=7.5;var DOOMED_PROBE_ABSOLUTE_BYTES=2e6;function preflightHoldGraceMs2(){return preflightHoldGraceMs()}var LOCAL_REFUSAL_MAX_RECORDS=16;var LOCAL_REFUSAL_TTL_MS=10*6e4;function readLocalRefusals(metadata){const raw=metadata.localRefusals;if(!Array.isArray(raw))return[];const now=Date.now();return raw.filter(r=>!!r&&typeof r==="object"&&typeof r.origin==="string"&&typeof r.model==="string"&&typeof r.window==="number"&&typeof r.at==="number"&&r.at>now-LOCAL_REFUSAL_TTL_MS)}function noteLocalRefusal(session,origin,model,window2){if(!origin||!model||!Number.isFinite(window2)||window2<=0)return;const records=readLocalRefusals(session.metadata);const existing=records.find(r=>r.origin===origin&&r.model===model);if(existing!==void 0&&existing.window>=window2)return;session.metadata.localRefusals=[...records.filter(r=>!(r.origin===origin&&r.model===model)),{origin,model,window:Math.floor(window2),at:Date.now()}].slice(-LOCAL_REFUSAL_MAX_RECORDS);markDirty(session)}function localRefusalCovers(metadata,origin,model,window2){if(!origin||!model)return false;return readLocalRefusals(metadata).some(r=>r.origin===origin&&r.model===model&&r.window>=window2)}function beginPreflightHold(res,prepared,log2){if(res.headersSent||res.destroyed||res.writableEnded)return void 0;const sid=prepared.session.id;const keepAlive=prepared.stream?": bili-preflight\n\n":" ";try{if(prepared.stream){res.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache","x-accel-buffering":"no","x-bili-preflight":"compressing"})}else{res.writeHead(200,{"content-type":"application/json","x-bili-preflight":"compressing"})}}catch{return void 0}log2("info",`[${sid}] preflight still running after ${preflightHoldGraceMs2()}ms grace \u2014 committed early ${prepared.stream?"SSE":"JSON"} headers + keep-alive to hold the client (#568)`);try{res.write(keepAlive)}catch{}const iv=setInterval(()=>{try{res.write(keepAlive)}catch{clearInterval(iv)}},PREFLIGHT_KEEPALIVE_MS);return()=>clearInterval(iv)}function streamKeepaliveMs(){return streamKeepAliveMs()}function beginStreamKeepalive(res,sid,log2){const idleMs=streamKeepaliveMs();if(idleMs<=0||res.destroyed||res.writableEnded)return;const sock=res.socket;if(!sock)return;let baseline=sock.bytesWritten;let warned=false;let stopped=false;const anyRes=res;let origWrite;if(anyRes.__biliKeepaliveBoundary===void 0){origWrite=res.write.bind(res);anyRes.__biliKeepaliveBoundary=true;res.write=((...args)=>{const chunk=args[0];try{if(typeof chunk==="string"){if(chunk.length>0)anyRes.__biliKeepaliveBoundary=chunk.endsWith("\n")}else if(Buffer.isBuffer(chunk)||chunk instanceof Uint8Array){if(chunk.length>0)anyRes.__biliKeepaliveBoundary=chunk[chunk.length-1]===10}}catch{}return origWrite(...args)})}const stop=()=>{if(stopped)return;stopped=true;clearInterval(iv);res.removeListener("close",stop)};res.once("close",stop);const iv=setInterval(()=>{try{if(res.destroyed||res.writableEnded||!res.socket){stop();return}const written=res.socket.bytesWritten;if(written>baseline){baseline=written;return}if(anyRes.__biliKeepaliveBoundary===false)return;res.write(": bili-keepalive\n\n");if(!warned){warned=true;log2("info",`[${sid}] stream silent ${idleMs}ms \u2014 holding client with SSE keep-alive comments past its undici body timeout (#1647)`)}}catch{stop()}},Math.max(50,Math.floor(idleMs/3)))}function outboundPayloadBreakdown(prepared,opts,route,reqUrl){const billingUpstream=route?.rewrittenUrl??(/^https?:\/\//i.test(reqUrl)?reqUrl:opts.upstream);const imageTokens=imageReserveFor(prepared.session,prepared.protocol,prepared.parsedBody??prepared.body,opts,billingUpstream);const msgs=prepared.processedMessages.length>0?prepared.processedMessages:prepared.originalMessages;const textEstimate=estimateCoreMessages(msgs);const overheadEstimate=estimateWireOverhead(prepared.protocol,prepared.parsedBody??prepared.body);const armEstimate=Math.max(textEstimate,estimateCoreMessagesUpper(msgs))+overheadEstimate+imageTokens;return{textEstimate,overheadEstimate,imageTokens,payloadEstimate:textEstimate+overheadEstimate+imageTokens,armEstimate}}function outboundContextEstimates(prepared,wireBody,opts,upstream,parsed){let msgs=prepared.processedMessages.length>0?prepared.processedMessages:prepared.originalMessages;const project=value=>{switch(prepared.protocol){case"anthropic":msgs=anthropicToCore(value).msgs;break;case"openai":msgs=openaiToCore(value).msgs;break;case"responses":msgs=responsesToCoreWithToolImages(value).msgs;break;case"google":msgs=googleToCore(value).msgs;break}};let raw;if(parsed===void 0){try{project(JSON.parse(wireBody))}catch{}raw=wireBody}else if(parsed!==null){try{project(parsed)}catch{}raw=parsed}else{raw=""}const overhead=estimateWireOverhead(prepared.protocol,raw);const imageTokens=imageReserveFor(prepared.session,prepared.protocol,raw,opts,upstream);return{upperBound:estimateCoreMessagesUpper(msgs)+overhead+imageTokens,textOverhead:estimateCoreMessages(msgs)+overhead,imageTokens}}var routeMissWarned=new Set;function warnRouteMissIfNew(origin,model,knownKeys2,log2){if(!origin||!model||knownKeys2.length===0)return false;const key2=`${origin}\0${model}`;if(routeMissWarned.has(key2))return false;routeMissWarned.add(key2);const hosts2=knownKeys2.map(k2=>hostIdForLog(k2));let msg=`[route] no provider route matched ${hostIdForLog(origin)} (model=${model}) \u2014 its per-provider settings (context/compress/\u2026) are IGNORED; known providers keys: ${hosts2.join(", ")}. Add a matching key to the providers block in ~/.config/billion-context/billion-context.json.`;if(origin.startsWith("mitm://")){const host=origin.slice("mitm://".length);const siblings=[];let hasMitmTwin=false;for(const k2 of knownKeys2){let u2;try{u2=new URL(k2)}catch{continue}if(u2.protocol==="https:"&&u2.host===host)siblings.push(k2);else if(u2.protocol==="mitm:"&&u2.host===host)hasMitmTwin=true}if(siblings.length>0&&!hasMitmTwin){const twin=`mitm://${hostIdForLog(`https://${host}`)}`;msg+=` Scheme mismatch: your settings sit under ${siblings.map(s3=>hostIdForLog(s3)).join(", ")} but MITM-lane lookups use "${twin}" \u2014 add that key (the https:// entries keep serving /bili/-embedded requests).`}}log2("warn",msg);return true}function buildWindowShrinkNote(args){if(args.reason===void 0||args.nativeWindow===void 0||args.limit>=args.nativeWindow)return"";const head=` Note: bili's effective window ${args.limit} is below the model's full window ${args.nativeWindow} \u2014 `;if(args.reason==="operator"){return head+`your compress.modelContextLimit setting overrides it; if the upstream actually serves the larger window, raise or remove that setting (hot-reloaded, no session restart needed).`}if(args.routeMissedConfigured){const up=args.upstreamEndpoint?hostIdForLog(args.upstreamEndpoint):"this upstream";const keys=(args.knownKeys??[]).map(k2=>hostIdForLog(k2)).join(", ");return head+`it was aligned down to codex's own window perception, and your upstream (${up}) matched NO configured providers key${keys?` \u2014 your pinned context/modelContextLimit sit under: ${keys}`:""}. Add a providers entry for this upstream so the pinned window applies here.`}return head+`it was aligned down to codex's own window perception; set compress.modelContextLimit explicitly if your upstream serves the larger window.`}async function preflightCompressIfNeeded(prepared,runPrepare,req,inboundBody,res,opts,core,config,configuredWindow,model,resolvedNativeWindow,windowShrinkReason,route,affinity,anonymous,log2,instanceId){const session=prepared.session;const statedWall=typeof session.stats.overflowArmTokens==="number"&&session.stats.overflowArmTokens>0?session.stats.overflowArmTokens:0;const completionReserve=typeof session.stats.overflowArmCompletionReserve==="number"&&session.stats.overflowArmCompletionReserve>0?session.stats.overflowArmCompletionReserve:0;const limit=completionReserve>0&&statedWall>0?Math.max(0,Math.min(config.modelContextLimit,statedWall-completionReserve)):config.modelContextLimit;const headroomWindow=typeof session.metadata.reservedContextLimit==="number"&&session.metadata.reservedContextLimit>0?session.metadata.reservedContextLimit:config.modelContextLimit;if(limit<headroomWindow){const armKey=`${session.id}|${String(model??"?")}|${limit}|${headroomWindow}`;if(!armJudgingWallLogged.has(armKey)){armJudgingWallLogged.add(armKey);log2("info",`[arm-judge] upstream overflow proof (stated wall ${statedWall}, ${completionReserve} billed to completion): nudge/preflight judge input against ${limit} \u2014 BELOW the [headroom] window ${headroomWindow}; that line does not apply while this arm is live (#3450, #5191)`)}}const overflowTarget=prepared.protocol==="responses"&&codexHealthBarApplies(req.headers)?limit*CODEX_COMPACT_HEALTH_RATIO:limit;const autoFoldOn=autoFoldEngaged(config,session);const measuredFloor=autoFoldOn?autoFoldFloor(session):void 0;const autoFoldTarget=autoFoldOn?Math.min(Math.max(Math.max(AUTO_FOLD_TARGET_MIN,Math.min(config.externalSummary?.autoFoldTargetTokens??(overflowTarget>0?Math.round(overflowTarget/2):0),overflowTarget)),measuredFloor??0),overflowTarget):void 0;const growthArmed=autoFoldOn&&autoFoldTarget!==void 0&&autoFoldTarget>0&&autoFoldTarget<overflowTarget;const compressionTarget=growthArmed?autoFoldTarget:overflowTarget;const{textEstimate,overheadEstimate,imageTokens}=outboundPayloadBreakdown(prepared,opts,route,req.url??"");const unknownBaseline=anonymous&&session.stats.lastInputTokens<=0;const baselineFloorRaw=prepared.processedMessages.length>0?session.stats.lastInputTokensSource==="usage"||session.stats.lastInputTokensSource==="overflow-arm"?session.stats.lastInputTokens:0:session.stats.lastInputTokens;let baselineFloor=baselineFloorRaw;const currentOrigin=normalizeUpstreamOrigin(route?.upstream);const baselineOrigin=normalizeUpstreamOrigin(session.stats.lastInputTokensOrigin);if(baselineFloor>0&¤tOrigin!==void 0&&baselineOrigin!==void 0&&baselineOrigin!==currentOrigin){log2("info",`[${session.id}] preflight usage-baseline ~${baselineFloor} tok was measured on ${maskUrlForLog(baselineOrigin)}, request now routes to ${maskUrlForLog(currentOrigin)} \u2014 demoting to untrusted, judging by this payload's own estimate (#1933)`);baselineFloor=0}const kFactor=currentCalibrationFactor(session.stats,session.metadata?.lastModel);const kOrigin=session.stats.calibratedEstimateOrigin;const calibratedText=applyEstimateCalibration(textEstimate+overheadEstimate,kFactor,kOrigin,currentOrigin);const calibratedPayload=calibratedText+imageTokens;const tokenCount=unknownBaseline?estimateCoreMessagesUpper(prepared.processedMessages)+overheadEstimate+imageTokens:Math.max(baselineFloor,calibratedPayload);const textChannel=unknownBaseline?estimateCoreMessagesUpper(prepared.processedMessages)+overheadEstimate:calibratedText;const textBudget=Math.max(0,compressionTarget-imageTokens);const decisionTrigger=Math.max(Math.max(0,baselineFloor-imageTokens),textChannel);const growthWorthIt=!growthArmed||imageTokens>=compressionTarget||decisionTrigger-textBudget>=AUTO_FOLD_MIN_BENEFIT_TOKENS;const triggerFires=growthWorthIt&&(imageTokens>=compressionTarget||decisionTrigger>=textBudget);if(opts.debug){const billed=session.stats.lastInputTokens>0&&session.stats.lastInputTokensSource==="usage"?session.stats.lastInputTokens:"none";log2("debug",`[${session.id}] [usage-vs-est] upstream-billed=${billed} est=${Math.round(textEstimate)} k\u0302=${kFactor!==void 0?kFactor.toFixed(2):"n/a"} route=${currentOrigin===void 0?"?":maskUrlForLog(currentOrigin)} model=${model??"?"} baseline-grade=${session.stats.lastInputTokensSource??"none"} (#2283)`)}if(limit<=0||!model||!triggerFires)return prepared;const localRefusalHere=localRefusalCovers(session.metadata,currentOrigin,model,limit);const probeForEvidence=!growthArmed&&!unknownBaseline&&session.stats.lastInputTokens>0&&baselineFloor<=0&&prepared.processedMessages.length>0;if(probeForEvidence){const coreTextBytes=estimateCoreMessagesUpperBytes(prepared.processedMessages);if(coreTextBytes>Math.max(DOOMED_PROBE_ABSOLUTE_BYTES,limit*DOOMED_PROBE_BYTES_PER_TOKEN)){const byteFloorTokens=Math.ceil(coreTextBytes/DOOMED_PROBE_BYTES_PER_TOKEN);log2("error",`[${session.id}] preflight 413 core-text profile: ${describeCoreTextDuplication(prepared.processedMessages)}`);const doomedMessage=`payload core text alone is ~${coreTextBytes} bytes \u2014 even at the densest tokenizer density observed on a live route (~${DOOMED_PROBE_BYTES_PER_TOKEN} bytes/token, #2122) that is \u2265 ~${byteFloorTokens} tokens vs the model window ${limit} (model=${model}); no upstream can accept it, so it was NOT forwarded even for evidence. Remove or trim the oversized content (e.g. a giant paste or tool result) and retry.`;log2("error",`[${session.id}] preflight fail-fast 413 (retryable=false): ${doomedMessage}`);noteLocalRefusal(session,currentOrigin,model,limit);return{failFast:true,status:413,message:doomedMessage,retryable:false,respond:!res.writableEnded}}if(localRefusalHere){log2("warn",`[${session.id}] preflight trigger fired on estimate only (~${Math.round(textChannel)} text + ~${imageTokens} image vs window ${limit}) but this origin/model was locally refused (413) at an equal or wider window \u2014 NOT re-forwarding for evidence; falling through to fold/fail-fast (#3846)`)}else{log2("info",`[${session.id}] preflight trigger fired on estimate only (~${Math.round(textChannel)} text + ~${imageTokens} image vs window ${limit}); baseline ${session.stats.lastInputTokens} (${session.stats.lastInputTokensSource??"unprovenanced"}) carries no current-route upstream evidence \u2014 forwarding once to acquire usage/overflow evidence before compressing (#2313)`);return prepared}}const payloadFitsWindow=calibratedPayload<limit;const noOverflowEvidence=session.stats.lastInputTokens<limit||session.stats.lastInputTokensSource!=="usage"&&session.stats.lastInputTokensSource!=="overflow-arm";const imageArbitration=imageTokens>0&&textChannel<limit&&textChannel+imageTokens>=limit&&noOverflowEvidence;if(imageArbitration&&!localRefusalHere&&(prepared.nudge?.compressibleRanges??[]).length===0){log2("warn",`[${session.id}] image-dominated payload (~${textEstimate} text + ~${imageTokens} image tokens) exceeds window ${limit} by estimate only, nothing compressible, no upstream overflow evidence \u2014 forwarding for the upstream to arbitrate billing (#496/#1800)`);return prepared}const failFast=(status2,detail,retryable2,foldedTokens,rangesLeft)=>{const imageNote=imageTokens>=limit?` Images alone account for ~${imageTokens} tokens (\u2265 window ${limit}); compression cannot remove them \u2014 shrink or remove the images, or raise the window.`:"";const sizeClause=foldedTokens!==void 0&&foldedTokens<tokenCount?`context ~${foldedTokens} tokens (down from ~${tokenCount} before preflight) exceeds the model window ${limit}`:`context ~${tokenCount} tokens exceeds the model window ${limit}`;const rangesClause=rangesLeft!==void 0?`, with ${rangesLeft} compressible range(s) still visible`:"";const ffEmbeddedUrl=route?.rewrittenUrl;const ffProviderKeys=Object.keys(opts.routes);const shrinkNote=buildWindowShrinkNote({reason:windowShrinkReason,limit,nativeWindow:resolvedNativeWindow,routeMissedConfigured:ffProviderKeys.length>0&&findRouteKey(opts.routes,ffEmbeddedUrl)===void 0,upstreamEndpoint:ffEmbeddedUrl,knownKeys:ffProviderKeys});const estimateOnly=baselineFloor===0&&kFactor===void 0&&session.stats.lastInputTokensSource!=="usage"&&session.stats.lastInputTokensSource!=="overflow-arm";const estimateNote=estimateOnly?" (size judged by bili's local estimate, which can diverge from what the upstream actually bills)":"";const message=`${sizeClause} (model=${model})${rangesClause}${estimateNote} and preflight compression could not bring it under: ${detail.replace(/\.\s*$/,"")}.`+imageNote+shrinkNote+` The over-window payload was NOT forwarded.`;log2("error",`[${session.id}] preflight fail-fast ${status2} (retryable=${retryable2}): ${message}`);return{failFast:true,status:status2,message,retryable:retryable2,respond:!res.writableEnded}};if((prepared.nudge?.compressibleRanges??[]).length===0){if(payloadFitsWindow){log2("info",`[${session.id}] preflight target reached (~${tokenCount}) but the payload fits with no compressible ranges (~${Math.round(calibratedPayload)}/${limit}${kFactor!==void 0?`, k\u0302=${kFactor.toFixed(2)}`:""}); forwarding as-is`);return prepared}}log2("warn",`[${session.id}] context ${tokenCount} tokens reached preflight target ${compressionTarget}${growthArmed?" (auto-fold growth floor)":""}${completionReserve>0?` (window ${config.modelContextLimit} minus proven completion reservation ${completionReserve})`:""} (model window ${limit}, model=${model}; usage-baseline=${baselineFloor>0?baselineFloor:"none"} local-est=${Math.round(calibratedText)}${kFactor!==void 0?` raw=${Math.round(textEstimate+overheadEstimate)} k\u0302=${kFactor.toFixed(2)}`:""}); preflight compressing before forward`);const{upstreamUrl,headers,proxyUrl}=buildForwardTarget(req,opts,route,affinity,instanceId);const clientAbort=new AbortController;registerRequestAbort(res,clientAbort);res.on("close",()=>{if(!res.writableEnded){clientAbort.abort();noteClientAbort(session)}});const started=Date.now();let stopHold;const holdTimer=setTimeout(()=>{stopHold=beginPreflightHold(res,prepared,log2)},preflightHoldGraceMs2());holdTimer.unref();const forceStreamSummary=resolveCompress(opts.routes,route?.rewrittenUrl,model,opts.compress).streamSummary===true;const streamSummaryOff=resolveCompress(opts.routes,route?.rewrittenUrl,model,opts.compress).streamSummary===false;const preflightResignCtx=inboundResignCredential(req.headers,opts,upstreamUrl);let result;try{result=await preflightCompress({core,session,config,compressionTarget,compressReason:growthArmed?"growth":"overflow",prompts:prepared.prompts??defaultPrompts,surface:prepared.surface,protocol:prepared.protocol,billingBlock:prepared.anthropicBillingBlock,url:upstreamUrl,headers,resign:preflightResignCtx!==void 0?(hdrs,bodyStr)=>{try{resignApig(hdrs,preflightResignCtx,"POST",upstreamUrl,bodyStr,findRoute(opts.routes,upstreamUrl))}catch(err2){log2("warn",`[${session.id}] [preflight] re-sign failed; sending the previous signature: ${String(err2)}`)}}:void 0,model,proxyUrl,signal:clientAbort.signal,log:log2,imageReserve:imageTokens,wireOverhead:overheadEstimate,unknownBaseline,upstreamOrigin:currentOrigin,forceStreamSummary,streamSummaryOff},prepared.originalMessages)}finally{clearTimeout(holdTimer);stopHold?.()}if(!result.failure)delete session.metadata.preflightDeadEnd;const queueDroppedAll=externalQueueDroppedAll(result.externalDispatch);let outbound=prepared;let fits;let foldedCalibratedSize;if(result.compressedRanges>0){const rebuilt=await runPrepare();session.stats.requests-=1;outbound=rebuilt;const rebuiltMsgs=rebuilt.processedMessages.length>0?rebuilt.processedMessages:rebuilt.originalMessages;const rebuiltTextSize=estimateCoreMessages(rebuiltMsgs)+overheadEstimate;if(rebuiltTextSize>session.stats.lastInputTokens){session.stats.lastInputTokens=rebuiltTextSize;session.stats.lastInputTokensSource="estimate"}const rebuiltCalibrated=applyEstimateCalibration(rebuiltTextSize,kFactor,kOrigin,currentOrigin)+imageTokens;foldedCalibratedSize=rebuiltCalibrated;log2("info",`[${session.id}] preflight compressed ${result.compressedRanges} range(s), ~${result.savedTokens} tokens saved (${tokenCount} \u2192 ${foldedCalibratedSize}) in ${Date.now()-started}ms`);fits=unknownBaseline?result.fitsWindow:rebuiltCalibrated<limit;setPostRebuildAnchor(session,rebuiltTextSize+imageTokens);if(growthArmed&&result.failure===void 0&&rebuiltTextSize+imageTokens>=compressionTarget){session.metadata.autoFoldFloorTokens=rebuiltTextSize+imageTokens;markDirty(session);log2("warn",`[${session.id}] auto-fold target ${compressionTarget} unreachable \u2014 the session's irreducible baseline measures ~${rebuiltTextSize+imageTokens} tokens (system prompt + tools + live tail); effective target raised to the floor until the gap closes (#3444). Raise compress.externalSummary.autoFoldTargetTokens above ${rebuiltTextSize+imageTokens} for headroom`)}}else{fits=unknownBaseline?result.fitsWindow:estimateCoreMessages(prepared.processedMessages)+overheadEstimate+imageTokens<limit}const f2=result.failure;if(clientAbort.signal.aborted||f2?.kind==="aborted"){const detail=f2?.kind==="aborted"?f2.detail:"the client disconnected during preflight compression";log2("warn",`[${session.id}] preflight aborted (${detail}); not forwarding`);return{failFast:true,status:0,message:detail,retryable:false,respond:false}}if(fits){if(result.compressedRanges===0){if(growthArmed){if(queueDroppedAll){log2("warn",`[${session.id}] auto-fold made no progress (0 range(s) folded) \u2014 no summary attempt was ever dispatched (shared pool saturated / deadline expired before dispatch); congestion, not a chain failure \u2014 NOT backing off, auto-fold retries next turn (#2662); forwarding as-is (estimate fits the model window ${limit})`)}else if(result.hadFoldableCandidates){log2("warn",`[${session.id}] auto-fold made no progress (0 range(s) folded) \u2014 forwarding as-is (estimate fits the model window ${limit}); backing off auto-fold for ${Math.round(AUTO_FOLD_BACKOFF_MS/6e4)}m so classic nudges resume`);armAutoFoldBackoff(session);markDirty(session)}else{log2("info",`[${session.id}] auto-fold steady state: payload fits and no foldable candidates remained \u2014 forwarding as-is without backoff (#2638)`)}}else{log2("warn",`[${session.id}] preflight made no progress but the payload fits; forwarding as-is`)}}else if(growthArmed&&!queueDroppedAll&&result.savedTokens<AUTO_FOLD_MIN_BENEFIT_TOKENS){log2("warn",`[${session.id}] auto-fold saved only ~${result.savedTokens} tokens (< ${AUTO_FOLD_MIN_BENEFIT_TOKENS} worth) \u2014 forwarding as-is (estimate fits the model window ${limit}); backing off auto-fold for ${Math.round(AUTO_FOLD_BACKOFF_MS/6e4)}m so classic nudges resume (#3444)`);armAutoFoldBackoff(session);markDirty(session)}return outbound}if(result.compressedRanges>0&&!unknownBaseline&&result.payloadEstimate<limit&&!localRefusalHere){log2("warn",`[${session.id}] preflight view fits (~${result.payloadEstimate}/${limit}) but the rebuilt payload measures over \u2014 forwarding once for upstream arbitration (#1839)`);return outbound}if(growthArmed&&payloadFitsWindow){if(queueDroppedAll){log2("warn",`[${session.id}] auto-fold did not reach the growth target ${compressionTarget} (${result.compressedRanges} range(s) folded) \u2014 no summary attempt was ever dispatched (shared pool saturated / deadline expired before dispatch); congestion, not a chain failure \u2014 NOT backing off, auto-fold retries next turn (#2662); forwarding anyway (payload fits the model window ${limit})`)}else if(result.hadFoldableCandidates){log2("warn",`[${session.id}] auto-fold did not reach the growth target ${compressionTarget} (${result.compressedRanges} range(s) folded) \u2014 forwarding anyway (payload fits the model window ${limit}); backing off auto-fold for ${Math.round(AUTO_FOLD_BACKOFF_MS/6e4)}m so classic nudges resume`);armAutoFoldBackoff(session);markDirty(session)}else{log2("info",`[${session.id}] auto-fold steady state: growth target ${compressionTarget} unreachable while nothing foldable remained (${result.compressedRanges} range(s) folded) \u2014 forwarding anyway (payload fits the model window ${limit}) without backoff (#2638)`)}return outbound}if(imageArbitration&&!localRefusalHere){const outMsgs=outbound.processedMessages.length>0?outbound.processedMessages:outbound.originalMessages;const outText=estimateCoreMessages(outMsgs);if(outText+overheadEstimate<limit&&outText+overheadEstimate+imageTokens>=limit){log2("info",`[${session.id}] preflight folded ${result.compressedRanges} range(s) but images alone (~${imageTokens} tokens) keep the estimate over window ${limit} with no upstream overflow evidence \u2014 forwarding for the upstream to arbitrate billing (#496/#1800)`);return outbound}}const deterministicExhaustion=f2?.kind==="exhausted"&&f2.deterministic;const noUpstreamEvidence=session.stats.lastInputTokens<=0&&statedWall<=0&&deterministicExhaustion;let outboundBudgetTokens;try{const outBody=JSON.parse(typeof outbound.body==="string"?outbound.body:outbound.body.toString("utf8"));const outField=outputBudgetField(outBody);const rawBudget=outField!==null?readOutputBudget(outBody,outField):void 0;if(typeof rawBudget==="number"&&rawBudget>0)outboundBudgetTokens=rawBudget}catch{outboundBudgetTokens=void 0}const outboundCalibrated=foldedCalibratedSize??calibratedPayload;const nativeFitAfterClamp=statedWall<=0&&outboundBudgetTokens!==void 0&&typeof resolvedNativeWindow==="number"&&resolvedNativeWindow>0&&outboundCalibrated+outboundBudgetTokens<=resolvedNativeWindow;if((unknownBaseline||noUpstreamEvidence||nativeFitAfterClamp)&&!growthArmed){const outMsgs=outbound.processedMessages.length>0?outbound.processedMessages:outbound.originalMessages;const doomBytes=estimateCoreMessagesUpperBytes(outMsgs);if(doomBytes>Math.max(DOOMED_PROBE_ABSOLUTE_BYTES,limit*DOOMED_PROBE_BYTES_PER_TOKEN)){const byteFloorTokens=Math.ceil(doomBytes/DOOMED_PROBE_BYTES_PER_TOKEN);log2("error",`[${session.id}] preflight 413 core-text profile: ${describeCoreTextDuplication(outMsgs)}`);const doomedMessage=`payload core text alone is ~${doomBytes} bytes even after preflight compression \u2014 at the densest tokenizer density observed on a live route (~${DOOMED_PROBE_BYTES_PER_TOKEN} bytes/token, #2122) that is \u2265 ~${byteFloorTokens} tokens vs the model window ${limit} (model=${model}); no upstream can accept it. Remove or trim the oversized content (e.g. a giant paste or tool result) and retry.`;log2("error",`[${session.id}] preflight fail-fast 413 (retryable=false): ${doomedMessage}`);noteLocalRefusal(session,currentOrigin,model,limit);return{failFast:true,status:413,message:doomedMessage,retryable:false,respond:!res.writableEnded}}if(localRefusalHere){log2("warn",`[${session.id}] payload still over window ${limit} by local estimate (~${Math.round(result.payloadEstimate)} tok, ${result.compressedRanges} range(s) folded) but this origin/model was locally refused (413) at an equal or wider window \u2014 NOT re-forwarding for size arbitration (#3846/#4185)`)}else{const viaNativeFit=nativeFitAfterClamp&&!noUpstreamEvidence&&!unknownBaseline;log2("info",`[${session.id}] payload still over window ${limit} by local estimate (~${Math.round(result.payloadEstimate)} tok, ${result.compressedRanges} range(s) folded) ${viaNativeFit?`but the outbound view (~${Math.round(outboundCalibrated)} tok) + clamped output budget ${outboundBudgetTokens??0} fits the native window ${resolvedNativeWindow}`:"with no upstream evidence"} \u2014 forwarding once for the upstream to arbitrate size before failing fast (#3146/#4185)`);return outbound}}const status=f2?.kind==="upstream"&&f2.status===429?503:f2?.kind==="exhausted"&&f2.deterministic&&!payloadFitsWindow?413:502;const progressContinues=f2?.kind==="exhausted"&&!f2.deterministic&&result.compressedRanges>0;if(status===413)noteLocalRefusal(session,currentOrigin,model,limit);const retryable=progressContinues?true:f2?.retryable===false?false:f2?.retryable===true||f2?.kind==="upstream"&&f2.status!==void 0&&(f2.status===429||f2.status>=500);let ffDetail=f2?.detail??"the payload still exceeds the window after preflight compression";if(progressContinues){const shortfall=foldedCalibratedSize!==void 0?Math.max(0,limit-foldedCalibratedSize):void 0;ffDetail+=` ${result.compressedRanges} range(s) folded this turn persist in the session \u2014 the next attempt starts from a smaller baseline and continues the fold${shortfall!==void 0?` (~${shortfall.toLocaleString("en-US")} tokens short of the target)`:""}.`}const ff=failFast(status,ffDetail,retryable,result.compressedRanges>0?foldedCalibratedSize:void 0,result.rangesRemaining);return ff}var CONTEXTUAL_USER_FRAGMENT_MARKERS=[["# AGENTS.md instructions","</INSTRUCTIONS>"],["<environment_context>","</environment_context>"]];function asciiCI(hay,needle){if(hay.length!==needle.length)return false;for(let i=0;i<hay.length;i++){const h=hay.charCodeAt(i);const n=needle.charCodeAt(i);if(h===n)continue;const hl=h>=65&&h<=90?h+32:h;const nl=n>=65&&n<=90?n+32:n;if(hl!==nl)return false}return true}function isContextualUserFragment(text2){const t=text2.trim();if(!t)return false;return CONTEXTUAL_USER_FRAGMENT_MARKERS.some(([open,close])=>asciiCI(t.slice(0,open.length),open)&&asciiCI(t.slice(t.length-close.length),close))}var AUTO_INJECTED_NOTIFICATION_PREFIXES=["The approval policy changed from","Current runtime context","Time sampled while preparing turn"];function isAutoInjectedNotification(text2){const t=text2.trim();if(!t)return false;return AUTO_INJECTED_NOTIFICATION_PREFIXES.some(p2=>asciiCI(t.slice(0,p2.length),p2))}function deriveTitle(messages){for(const m2 of messages){if(m2.role!=="user"||m2.contentType!=="text")continue;const raw=m2.text??"";if(!raw.trim())continue;if(isContextualUserFragment(raw))continue;if(isAutoInjectedNotification(raw))continue;const clean=raw.replace(/\s+/g," ").trim();return clean.length>60?clean.slice(0,57)+"\u2026":clean}return void 0}function reapOrphansLogged(session,msgs,log2,sessionId){const{reaped}=reapOrphanBlocks(session,msgs,deactivateBlock);if(reaped.length===0)return;log2("warn",`[${sessionId}] orphan-gc deactivated ${reaped.length} block(s) whose source messages left the client history (${reaped.join(", ")}) \u2014 the client or another compression plugin deleted summarized content; those summaries can no longer be decompressed (#1206)`);recordConflict(session,"orphan-reap",`${reaped.length} block(s) deactivated: ${reaped.join(", ")}`)}function headerValue2(req,name){const lower=name.toLowerCase();for(const[k2,v2]of Object.entries(req.headers)){if(k2.toLowerCase()===lower)return Array.isArray(v2)?v2[0]:v2}return void 0}function formatBytes(n){if(n<1024)return`${n}B`;if(n<1024*1024)return`${(n/1024).toFixed(1)}KiB`;if(n<1024*1024*1024)return`${(n/(1024*1024)).toFixed(1)}MiB`;return`${(n/(1024*1024*1024)).toFixed(1)}GiB`}var SLOW_SESSION_MSG_WARN=1e3;function logRequestCost(log2,sessionId,msgs,inboundBytes,t0,outbound){const ms2=Math.max(0,Math.round(performance3.now()-t0));const outboundField=outbound!==void 0?`, outbound=${formatBytes(Buffer.byteLength(outbound))}`:"";const view=currentFetchTransport()?", view=ws-expanded":"";log2("info",`[${sessionId}] request: ${msgs??"?"} msgs, inbound=${formatBytes(inboundBytes)}${outboundField}, local=${ms2}ms${view}`);noteRequest(sessionId);if(msgs!==null&&msgs>SLOW_SESSION_MSG_WARN){log2("warn",`[${sessionId}] slow-session: ${msgs} msgs / inbound=${formatBytes(inboundBytes)} took local=${ms2}ms \u2014 per-turn O(messages) synchronous scans are starving the event loop (#4528); consider closing/restarting the session or enabling compression`)}}var BodyTooLargeError=class extends Error{constructor(limit){super(`request body exceeds ${limit} bytes`);this.limit=limit;this.name="BodyTooLargeError"}limit};function readBody(req){return new Promise((resolve2,reject)=>{const chunks=[];let size=0;let aborted=false;req.on("data",c=>{if(aborted)return;size+=c.length;if(size>limitsReceiveBytes()){aborted=true;req.destroy();reject(new BodyTooLargeError(limitsReceiveBytes()));return}chunks.push(c)});req.on("end",()=>{if(!aborted)resolve2(Buffer.concat(chunks))});req.on("error",e=>{if(!aborted)reject(e)})})}function logMsg(opts,level,msg){if(!opts.log)return;log(level,msg)}init_fetch_transport();init_logger();init_upstream_fail();var INLINE_ORIGIN="http://billion-context.inline";var INLINE_HOSTNAME=new URL(INLINE_ORIGIN).hostname;function normalizeHeaderPairs(value){if(Array.isArray(value))return value.map(([k2,v2])=>[k2,String(v2)]);const out=[];for(const[k2,v2]of Object.entries(value)){if(v2===void 0)continue;out.push([k2,Array.isArray(v2)?v2.join(", "):String(v2)])}return out}var HOP_HEADERS=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","host","content-length"]);async function bodyToBuffer(body){if(body===null||body===void 0)return Buffer2.alloc(0);if(typeof body==="string")return Buffer2.from(body);if(body instanceof URLSearchParams)return Buffer2.from(body.toString());if(body instanceof Blob)return Buffer2.from(await body.arrayBuffer());if(body instanceof ArrayBuffer)return Buffer2.from(body);if(ArrayBuffer.isView(body))return Buffer2.from(body.buffer.slice(body.byteOffset,body.byteOffset+body.byteLength));const iterator=body[Symbol.asyncIterator];if(typeof iterator==="function"){const parts=[];for await(const chunk of body)parts.push(Buffer2.from(chunk));return Buffer2.concat(parts)}throw new Error(`inline engine: unsupported request body type ${Object.prototype.toString.call(body)}`)}var webPort=0;var webServer;var InlineReq=class extends EventEmitter{url;method;headers={};socket={get localPort(){return webPort},remoteAddress:"127.0.0.1"};chunks;deliveryScheduled=false;constructor(url,method,headers,body){super();this.url=url;this.method=method;this.headers=headers;this.chunks=body.length>0?[body]:[]}on(event,fn){super.on(event,fn);if(event==="data"||event==="end"||event==="error")this.scheduleDelivery();return this}destroy(){}scheduleDelivery(){if(this.deliveryScheduled)return;this.deliveryScheduled=true;queueMicrotask(()=>{for(const c of this.chunks)this.emit("data",c);this.emit("end")})}};var InlineRes=class extends EventEmitter{statusCode=200;statusMessage="";headersSent=false;writableEnded=false;destroyed=false;socket={get localPort(){return webPort},remoteAddress:"127.0.0.1",destroyed:false,bytesWritten:0};bodyStream;headHeaders=[];controller;committed=false;committedCb;constructor(){super();this.bodyStream=new ReadableStream({start:c=>{this.controller=c}})}onCommitted(cb){if(this.committed)cb();else this.committedCb=cb}markCommitted(){if(this.committed)return;this.committed=true;const cb=this.committedCb;this.committedCb=void 0;cb?.()}writeHead(status,reasonOrHeaders){if(this.headersSent)throw new Error("ERR_HTTP_HEADERS_SENT: Cannot change headers after they are sent to the client");this.statusCode=status;if(typeof reasonOrHeaders==="string")this.statusMessage=reasonOrHeaders;else if(reasonOrHeaders!==void 0)this.headHeaders.push(...normalizeHeaderPairs(reasonOrHeaders));this.headersSent=true;this.markCommitted();return this}write(chunk,cb){if(this.destroyed){cb?.();return false}const buf=typeof chunk==="string"?Buffer2.from(chunk):Buffer2.from(chunk);this.socket.bytesWritten+=buf.length;this.controller?.enqueue(buf);this.markCommitted();cb?.();return true}end(chunk,cb){if(this.destroyed){cb?.();return}if(chunk!==void 0)this.write(chunk);if(!this.writableEnded){this.writableEnded=true;this.markCommitted();try{this.controller?.close()}catch{}this.emit("finish");this.emit("close");cb?.()}}destroy(err2){if(this.destroyed)return;this.destroyed=true;this.socket.destroyed=true;try{this.controller?.error(err2??new Error("client aborted"))}catch{}if(!this.writableEnded)this.emit("close")}};async function toInlineReq(input,init){let url;let baseHeaders;let requestMethod;let requestBody;if(typeof input==="string")url=input;else if(input instanceof URL)url=input.href;else{url=input.url;baseHeaders=input.headers;requestMethod=input.method;requestBody=await input.arrayBuffer().catch(()=>null)}const headers=new Headers(baseHeaders);if(init?.headers!==void 0)new Headers(init.headers).forEach((v2,k2)=>headers.set(k2,v2));const headerMap={};headers.forEach((value,key2)=>{const existing=headerMap[key2];headerMap[key2]=existing===void 0?value:Array.isArray(existing)?[...existing,value]:[existing,value]});const method=(init?.method??requestMethod??"GET").toUpperCase();const bodySource=init?.body!==void 0?init.body:requestBody;const body=await bodyToBuffer(bodySource);const parsed=new URL(url);if(headerMap["host"]===void 0)headerMap["host"]=parsed.hostname===INLINE_HOSTNAME?"127.0.0.1":parsed.host;return new InlineReq(parsed.pathname+parsed.search,method,headerMap,body)}function responseFrom(res){const headers=new Headers;for(const[k2,v2]of res.headHeaders){if(HOP_HEADERS.has(k2.toLowerCase()))continue;headers.append(k2,v2)}return new Response(res.bodyStream,{status:res.statusCode,statusText:res.statusMessage||void 0,headers})}function makeDispatcher(ctx){return async(input,init,rawFetch)=>{const req=await toInlineReq(input,init);const res=new InlineRes;const signal=init?.signal;let onAbort;let abortPromise;if(signal!=null){abortPromise=new Promise((_2,reject)=>{onAbort=()=>{try{res.destroy(new Error("client aborted"))}catch{}reject(signal.reason??new DOMException("The operation was aborted.","AbortError"))};if(signal.aborted)onAbort();else signal.addEventListener("abort",onAbort,{once:true})});void abortPromise.catch(()=>{})}const committed=new Promise(resolveCommit=>res.onCommitted(resolveCommit));const transport=(url,options)=>(rawFetch??globalThis.fetch)(url,options);const pipeline=withFetchTransport(transport,()=>handle(req,res,ctx.opts,ctx.core,ctx.config,ctx.log,ctx.instanceId,ctx.instanceStartedAt,ctx.proxyWatchers,ctx.initialWatcherPid,ctx.adminCtx));let abortSurfaced=false;void pipeline.then(()=>{if(!res.writableEnded&&!res.destroyed)res.end()},err2=>{const msg=String(err2);const e=err2;const clientAbort=(e?.name==="AbortError"||/abort/i.test(String(e?.message??"")))&&(res.destroyed||res.writableEnded);if(clientAbort&&!abortSurfaced)ctx.log("info",`client aborted mid-stream: ${msg}`);else if(!isExpectedFailFast(err2)){if(err2 instanceof Error&&err2.stack)ctx.log("error",`${msg}
|
|
7245
7245
|
${err2.stack.split("\n").slice(1,8).join("\n")}`);else ctx.log("error",msg)}if(res.destroyed)return;if(!res.headersSent){const{status,headers,body}=buildProxyFailureResponse(msg,err2);res.writeHead(status,headers);res.end(body)}else{res.end()}});try{if(abortPromise!==void 0)await Promise.race([committed,abortPromise]);else await committed}catch(err2){const e=err2;if((e?.name==="AbortError"||/abort/i.test(String(e?.message??"")))&&res.destroyed){abortSurfaced=true;ctx.log("info",`client aborted mid-stream: ${String(err2)}`)}throw err2}finally{if(signal!=null&&onAbort!=null){const detach=()=>signal.removeEventListener("abort",onAbort);res.once("finish",detach);res.once("close",detach)}}return responseFrom(res)}}function makeHttpDispatch(ctx){return async(req,res)=>{try{await handle(req,res,ctx.opts,ctx.core,ctx.config,ctx.log,ctx.instanceId,ctx.instanceStartedAt,ctx.proxyWatchers,ctx.initialWatcherPid,ctx.adminCtx)}catch(err2){const msg=String(err2);const e=err2;const clientAbort=(e?.name==="AbortError"||/abort/i.test(String(e?.message??"")))&&(res.destroyed||res.writableEnded);if(clientAbort)ctx.log("info",`client aborted mid-stream: ${msg}`);else if(err2 instanceof Error&&err2.stack)ctx.log("error",`${msg}
|
|
7246
7246
|
${err2.stack.split("\n").slice(1,8).join("\n")}`);else ctx.log("error",msg);if(res.destroyed)return;if(!res.headersSent){const status=msg.includes("exceeds")?413:502;res.writeHead(status,{"content-type":"application/json"});res.end(JSON.stringify({error:"acp-proxy failure",detail:msg}))}else{res.end()}}}}var engineFactory=startInlineEngine;var enginePromise;var failedAt=0;var RETRY_COOLDOWN_MS=3e4;function getInlineEngine(){if(enginePromise!==void 0){if(failedAt!==0&&Date.now()-failedAt>=RETRY_COOLDOWN_MS)enginePromise=void 0;else return enginePromise}enginePromise=engineFactory().catch(err2=>{failedAt=Date.now();log("error",`[inline] compression engine bootstrap failed (retry in ${RETRY_COOLDOWN_MS/1e3}s): ${String(err2)}`);throw err2});return enginePromise}function closeWebListener(){if(webServer!==void 0){webServer.close();webServer=void 0}webPort=0}async function startInlineEngine(){if(!process.env.BILI_INLINE_DEBUG)muteStderrLeg();ensureConfigTemplate();const opts=loadOptions();opts.inlineLane=true;const bootstrapOutcome=await ensureSqliteEngine({resolveProxy:url=>resolveProxy(opts.routes,opts.proxy,url,opts.proxyFallback)});recordEngineBootstrap(bootstrapOutcome);const ctx=await createEngineContext(opts);ctx.markBootReady();ctx.log("info",`[inline] compression engine running in-process (${INLINE_ORIGIN}) \u2014 no proxy spawned`);const dispatchHttp=makeHttpDispatch(ctx);const bridge=startInlineWsBridge({dispatchHttp,log:ctx.log,isEgressProxied:url=>resolveProxyDecision(opts.routes,opts.proxy,url,opts.proxyFallback).proxy!==void 0,instanceId:ctx.instanceId});const wsOrigin=bridge.then(b2=>b2.origin).catch(err2=>{ctx.log("warn",`[inline] WS bridge failed to start \u2014 codex WebSocket traffic goes DIRECT (uncompressed): ${String(err2)}`);return void 0});const webOrigin=new Promise(resolve2=>{closeWebListener();const web=http5.createServer((req,res)=>{const url=req.url??"/";if(url!=="/__bili/"&&!url.startsWith("/__bili/")&&url!=="/__acp/"&&!url.startsWith("/__acp/")){res.writeHead(404,{"content-type":"text/plain"});res.end("inline web listener serves /__bili/ only");return}void dispatchHttp(req,res)});web.once("error",err2=>{ctx.log("warn",`[inline] web listener failed to start \u2014 the Web UI link stays hidden: ${String(err2)}`);resolve2(void 0)});web.listen(0,"127.0.0.1",()=>{const addr=web.address();const port=typeof addr==="object"&&addr!==null?addr.port:0;if(typeof port==="number"&&port>0){webPort=port;webServer=web;web.unref();ctx.log("info",`[inline] web UI listening on http://127.0.0.1:${port} (loopback only)`);resolve2(`http://127.0.0.1:${port}`)}else{ctx.log("warn","[inline] web listener bound without a port \u2014 the Web UI link stays hidden");resolve2(void 0)}})});return{origin:INLINE_ORIGIN,dispatch:makeDispatcher(ctx),dispatchHttp,wsOrigin,webOrigin}}var MODEL_PREFIX=`${INLINE_ORIGIN}/bili/`;var rawSend;var installed=false;var degradeWarned=false;function urlOf2(input){try{if(typeof input==="string")return input;if(input instanceof URL)return input.href;return input.url}catch{return void 0}}function installInlineTransport(){if(installed)return true;installFetchChain(send=>{installed=true;rawSend=send;return async(input,init)=>{const url=urlOf2(input);if(url===void 0||!url.startsWith(INLINE_ORIGIN))return send(input,init);try{const engine=await getInlineEngine();return await engine.dispatch(input,init,rawSend)}catch(err2){if(err2 instanceof Error&&err2.name==="AbortError")throw err2;const msg=err2 instanceof Error?err2.message:String(err2);if(url.startsWith(MODEL_PREFIX)){if(!degradeWarned){degradeWarned=true;logHostEvent("error","[native-client]",`[bili-native] inline engine unavailable \u2014 model traffic goes direct (uncompressed): ${msg}`)}return await send(url.slice(MODEL_PREFIX.length),init)}throw err2}}});return true}function shouldBootstrapNativeOpencode(env){return nativeBootstrapGate(env,"BILI_NATIVE_OPENCODE")}function planNativeOpencode(env,fileInline=void 0){if(env.BILLION_CONTEXT_PLUGIN==="0"||env.BILI_NATIVE_OPENCODE==="0")return{mode:"off"};if(env.BILI_PROVIDER_REWRITES!==void 0)return{mode:"off"};const inlineEnv=env.BILI_OPENCODE_INLINE;const inlineEnvOff=inlineEnv!==void 0&&["","0","false","no","off"].includes(inlineEnv);const inlineEnvOn=inlineEnv!==void 0&&!inlineEnvOff;if(!inlineEnvOff&&(inlineEnvOn||fileInline===true))return{mode:"inline"};const attachOrigin=nativeAttachOrigin(env)??proxyEnvOrigin(env);if(attachOrigin!==void 0)return{mode:"attach",attachOrigin};return{mode:"spawn"}}function wireBodyMediaBytes(body,decode=b2=>new TextDecoder().decode(b2)){try{return mediaBytesOfWireBody(decode(body))}catch{return 0}}async function oversizeDirectRefusal(e,s3,reason){const model=e.model;if(model===void 0||typeof model.providerID!=="string"||typeof model.id!=="string")return void 0;const window2=s3.windows?.get(`${model.providerID}/${model.id}`);if(window2===void 0||!Number.isFinite(window2)||window2<=0)return void 0;const req=e.request;if(req===null||typeof req!=="object"||typeof req.clone!=="function")return void 0;let body;try{body=await req.clone().arrayBuffer()}catch{return void 0}const bytes=body.byteLength;if(Math.ceil(bytes/4)<=window2)return void 0;const coreBytes=Math.max(bytes-wireBodyMediaBytes(body),0);const floorTokens=Math.ceil(coreBytes/4);if(floorTokens<=window2)return void 0;if(reason==="busy-exhausted"){return new Error(`bili: proxy alive but unresponsive \u2014 it accepted connections but never answered its health probe within the wait budget (event loop saturated, typically a large compression in flight); this request cannot be sent uncompressed (body ~${floorTokens} tok (floor estimate ${coreBytes}B/4) exceeds the ${model.providerID}/${model.id} context window (${window2})), so it is refused locally instead of queued indefinitely. The proxy is likely to serve it once the fold finishes (#3654); retry shortly.`)}return new Error(`bili: proxy unavailable and this request cannot be sent uncompressed \u2014 body ~${floorTokens} tok (floor estimate ${coreBytes}B/4) exceeds the ${model.providerID}/${model.id} context window (${window2}); upstream would reject it. Recovery is automatic (#3308); retry shortly, or start a fresh session if the local history has outgrown the window.`)}function createNativeRoute(state7,deps={}){const resolveLive=createLiveOriginResolver(state7,deps);let warned=false;let refusedNoticed=false;const conflictWarned=new Set;return async(e,s3)=>{const url=typeof e.request?.url==="string"?e.request.url:void 0;if(url===void 0)return;if(routedBiliModelUrl(url)!==void 0){noteRoutedOrigin(state7,url);const baked=new URL(url).origin;const declaredRaw=process.env.BILLION_CONTEXT_PROXY;let declared;try{declared=declaredRaw!==void 0&&declaredRaw!==""?new URL(declaredRaw).origin:void 0}catch{declared=void 0}if(declared!==baked){const key2=`${String(e.sessionID??"_")}\0${baked}`;if(!conflictWarned.has(key2)){conflictWarned.add(key2);logHostEvent("error","[native-client]",`bili-native-opencode: conflicting configuration \u2014 model requests already carry a /bili/ prefix (origin ${baked}) while the native plugin is active. The plugin routes model requests itself; hand-written /bili/ prefixes belong to the no-plugin plain-proxy path. Pick ONE: (1) remove the /bili/ prefix from your opencode provider baseURL(s) so the plugin routes them, or (2) run \`bili plugin remove opencode\` and keep the pre-routed URLs. Until resolved, these requests continue to ${baked} in plain proxy mode WITHOUT the plugin session markers.`)}}}if(!isModelApiUrl(url))return;const target=await resolveLive();if(target===void 0){const refusal=await oversizeDirectRefusal(e,s3,state7.lastUnavailableReason);if(refusal!==void 0){if(!refusedNoticed){refusedNoticed=true;logHostEvent("error","[native-client]",state7.lastUnavailableReason==="busy-exhausted"?`bili-native-opencode: proxy alive but saturated past the wait budget \u2014 model request refused locally instead of queued indefinitely (#3654): ${refusal.message}`:`bili-native-opencode: proxy unavailable \u2014 model request refused locally instead of going direct into a guaranteed upstream 400 (#3308): ${refusal.message}`)}s3.proxyBase=void 0;throw refusal}if(!warned){warned=true;logHostEvent("error","[native-client]","bili-native-opencode: proxy unavailable \u2014 model requests go direct (uncompressed)")}s3.proxyBase=void 0;return}warned=false;s3.proxyBase=target;replaceRequestTarget(e,`${target}/bili/${url}`)}}var state6={origin:void 0,ready:Promise.resolve(void 0)};state6.prepareDirectSend=createPrepareDirectSend();async function bootstrap(){try{const handle2=await ensureProxyRunning({host:LAUNCHER_DEFAULT_HOST,port:0,passthrough:false,debug:false,lane:"opencode"},{scriptPath:nativeProxyScriptPath()});state6.origin=handle2.origin;process.env.BILLION_CONTEXT_PROXY=handle2.origin;return handle2.origin}catch(err2){logHostEvent("error","[native-client]",`bili-native-opencode: proxy bootstrap failed \u2014 model traffic goes direct (uncompressed): ${err2 instanceof Error?err2.message:String(err2)}`);return void 0}}var _spawnForTest;function _setSpawnForTest(fn){_spawnForTest=fn}async function verifyAttachAndRecover(attachOrigin){const explicitAttachOrigin=nativeAttachOrigin(process.env);const home=explicitAttachOrigin??state6.routedOrigin??attachOrigin;const version=await fetchProxyVersion(home).catch(()=>void 0);if(version!==void 0){state6.origin=home;process.env.BILLION_CONTEXT_PROXY=home;return home}const pinned=explicitAttachOrigin??state6.routedOrigin??await observeRoutedOrigin(state6);if(pinned!==void 0){const back=await waitForProxyVersion(pinned);if(back!==void 0){state6.origin=back;process.env.BILLION_CONTEXT_PROXY=back;logHostEvent("info","[native-client]",`bili-native-opencode: attach target ${pinned} is healthy again \u2014 attached, no second instance spawned`);return back}logHostEvent("error","[native-client]",explicitAttachOrigin!==void 0?`bili-native-opencode: explicit attach target ${pinned} unreachable within the health deadline \u2014 refusing to spawn a second instance (your declared endpoint stays authoritative). Start your proxy at ${pinned} or unset BILLION_CONTEXT_ATTACH; bili keeps re-checking and self-heals when it comes back.`:`bili-native-opencode: attach target ${pinned} is down and this process's model channel is pinned to it \u2014 refusing to spawn a second instance (bili tools would 404 against the other one). Start your proxy at ${pinned} or unset BILLION_CONTEXT_PROXY; bili keeps re-checking and self-heals when it comes back.`);state6.origin=void 0;return void 0}logHostEvent("error","[native-client]",`bili-native-opencode: attach target ${attachOrigin} is not healthy \u2014 falling back to a spawned proxy`);delete process.env.BILLION_CONTEXT_PROXY;state6.attach=false;state6.origin=void 0;const start=singleFlight(_spawnForTest??bootstrap);state6.respawn=start;const landed=start().then(o=>{if(o!==void 0){state6.origin=o;process.env.BILLION_CONTEXT_PROXY=o}return o});state6.ready=landed;return landed}var plan=planNativeOpencode(process.env,loadConfigFile().opencode?.inline);function armNativeOpencode(p2){if(p2.mode==="off")return;markNativeHost(process.env,"opencode");if(p2.mode==="attach"){state6.attach=true;const attachOrigin=p2.attachOrigin;if(attachOrigin!==void 0){process.env.BILLION_CONTEXT_PROXY=attachOrigin;const start=singleFlight(()=>verifyAttachAndRecover(attachOrigin));state6.respawn=start;state6.onGiveUp=()=>{delete process.env.BILLION_CONTEXT_PROXY};state6.onRoutedOriginObserved=origin=>{if(state6.origin===origin)return;void fetchProxyVersion(origin).catch(()=>void 0).then(version=>{if(version===void 0||state6.origin===origin)return;state6.origin=origin;process.env.BILLION_CONTEXT_PROXY=origin;logHostEvent("warn","[native-client]",`bili-native-opencode: model channel pinned to ${origin} \u2014 rebinding bili tools there`)})};state6.ready=start()}else{state6.ready=Promise.resolve(void 0)}}else if(p2.mode==="inline"){state6.attach=false;state6.origin=INLINE_ORIGIN;process.env.BILLION_CONTEXT_PROXY=INLINE_ORIGIN;logHostEvent("info","[native-client]","bili-native-opencode: inline mode \u2014 compression runs in-process, no proxy server will be started");const start=singleFlight(async()=>{await getInlineEngine();return INLINE_ORIGIN});state6.respawn=start;setNativeOriginWaiter({wait:()=>readyOrigin(state6)});state6.onGiveUp=()=>{delete process.env.BILLION_CONTEXT_PROXY;state6.origin=void 0};state6.ready=process.env.NODE_TEST_CONTEXT===void 0?start():Promise.resolve(void 0)}else if(process.env.NODE_TEST_CONTEXT===void 0){const start=singleFlight(bootstrap);state6.respawn=start;state6.onGiveUp=()=>{delete process.env.BILLION_CONTEXT_PROXY};state6.ready=start()}}if(plan.mode!=="off")armNativeOpencode(plan);if(process.env.NODE_TEST_CONTEXT===void 0&&plan.mode==="inline"){installInlineTransport();installNativeFetchIntercept(state6)}function _stateRespawnForTest(){return state6.respawn}function _noteRoutedForTest(url){noteRoutedOrigin(state6,url)}function _resetNativeStateForTest(){state6.attach=void 0;state6.origin=void 0;state6.routedOrigin=void 0;state6.onRoutedOriginObserved=void 0;state6.respawn=void 0;state6.onGiveUp=void 0;state6.ready=Promise.resolve(void 0);_spawnForTest=void 0;delete process.env.BILLION_CONTEXT_PROXY}function jsonSchemaToZodShape(schema,z2){if(schema===null||typeof schema!=="object"||Array.isArray(schema))return{};const props=schema.properties;if(props===null||typeof props!=="object"||Array.isArray(props))return{};const out={};for(const[key2,raw]of Object.entries(props)){out[key2]=jsonSchemaFieldToZod(raw,z2)}return out}function jsonSchemaFieldToZod(raw,z2){if(raw===null||typeof raw!=="object")return z2.any();const spec=raw;if(Array.isArray(spec.enum)&&spec.enum.length>0&&spec.enum.every(v2=>typeof v2==="string")){return z2.enum(spec.enum)}switch(spec.type){case"string":return typeof spec.description==="string"?z2.string().describe(spec.description):z2.string();case"number":return z2.number();case"boolean":return z2.boolean();case"array":{const item=jsonSchemaFieldToZod(spec.items,z2);return item===void 0?z2.array(z2.any()):z2.array(item)}default:return z2.any()}}function rewriteV1Providers(cfg,origin){const providers=cfg.provider;if(providers===null||typeof providers!=="object")return 0;let rewritten=0;for(const entry of Object.values(providers)){const options=entry?.options;if(options===null||typeof options!=="object")continue;const base=options.baseURL;if(typeof base!=="string"||base.trim().length===0)continue;if(!/^https?:\/\//i.test(base))continue;const next=wrapUpstream(origin,unwrapUpstream(base));if(next===base)continue;options.baseURL=next;rewritten++}const compaction=cfg.compaction;cfg.compaction={...compaction!==null&&typeof compaction==="object"&&!Array.isArray(compaction)?compaction:{},auto:false};return rewritten}function extractV1Windows(cfg){const map=new Map;const providers=cfg.provider;if(providers===null||typeof providers!=="object")return map;for(const[pid,entry]of Object.entries(providers)){const models=entry?.models;if(models===null||typeof models!=="object")continue;for(const[mid,model]of Object.entries(models)){const c=model?.limit?.context;if(typeof c==="number"&&Number.isFinite(c)&&c>0)map.set(`${pid}/${mid}`,Math.floor(c))}}return map}function extractV1Outputs(cfg){const map=new Map;const providers=cfg.provider;if(providers===null||typeof providers!=="object")return map;for(const[pid,entry]of Object.entries(providers)){const models=entry?.models;if(models===null||typeof models!=="object")continue;for(const[mid,model]of Object.entries(models)){const o=model?.limit?.output;if(typeof o==="number"&&Number.isFinite(o)&&o>0)map.set(`${pid}/${mid}`,Math.floor(o))}}return map}function lastSessionFromMessages(messages){if(!Array.isArray(messages))return void 0;for(let i=messages.length-1;i>=0;i--){const info=messages[i]?.info;if(typeof info?.sessionID==="string")return info.sessionID}return void 0}var harvestMsgIdsTransform=async(_input,output)=>{harvestOpencodeMsgIds(lastSessionFromMessages(output?.messages),output?.messages)};function createV1ServerHooks(getOrigin,ctx,deps={}){const acp=createAcpCommandHooks(getOrigin,ctx);const legacy=deps.legacy;const isLegacy=deps.isLegacy??isLegacyAcpSession;const log2=deps.log??(msg=>logHostEvent("info","[native-client]",msg));let windows=new Map;let outputs=new Map;const derivedReported=new Map;const derivedRetryAt=new Map;const derivedRetryMs=deps.derivedRetryMs??1e4;const maybeReportDerived=(base,sid)=>{const get=ctx.client?.session?.get;if(!sid||typeof get!=="function")return;if(derivedReported.has(sid))return;const retryAt=derivedRetryAt.get(sid);if(retryAt!==void 0&&Date.now()<retryAt)return;derivedReported.set(sid,"pending");void(async()=>{try{const res=await get({path:{id:sid}});const parent=res?.data?.parentID;if(typeof parent==="string"&&parent.length>0&&parent!==sid){await postIdentityRegister(base,sid,"opencode",parent);derivedReported.set(sid,"done")}else{derivedReported.set(sid,"none")}}catch{derivedReported.delete(sid);derivedRetryAt.set(sid,Date.now()+derivedRetryMs)}})()};const hooks={config:async cfg=>{if(legacy?.configHook!==void 0){await callLegacyAcpConfig(legacy.configHook,cfg)}await acp.config?.(cfg);const o=getOrigin();if(o!==void 0){const n=rewriteV1Providers(cfg,o);if(n>0)log2(`[bili-opencode-native] v1: rewrote ${n} provider baseURL(s) -> ${o}/bili/`)}windows=extractV1Windows(cfg);outputs=extractV1Outputs(cfg)},"command.execute.before":async(input,output)=>{if((input.command==="acp"||input.command==="dcp")&&legacy?.commandHook!==void 0&&isLegacy(input.sessionID)){await legacy.commandHook(input,output);return}if(input.command==="acp-cache"&&isLegacy(input.sessionID)){await showAcpText(ctx,input.sessionID,"bili: /acp-cache is unavailable for this legacy DCP session (#920) \u2014 its traffic bypasses this proxy's compression state; start a new session for the cache report");throw new Error("__BILI_ACP_HANDLED__")}await acp["command.execute.before"]?.(input)}};if(legacy!==void 0){const sys=legacy.hooks["experimental.chat.system.transform"];if(typeof sys==="function"){hooks["experimental.chat.system.transform"]=async(input,output)=>{if(!isLegacy(input.sessionID))return;await sys(input,output)}}const msgT=legacy.hooks["experimental.chat.messages.transform"];if(typeof msgT==="function"){hooks["experimental.chat.messages.transform"]=async(input,output)=>{if(isLegacy(lastSessionFromMessages(output?.messages))){await msgT(input,output);return}await harvestMsgIdsTransform(input,output)}}else{hooks["experimental.chat.messages.transform"]=harvestMsgIdsTransform}const textC=legacy.hooks["experimental.text.complete"];if(typeof textC==="function"){hooks["experimental.text.complete"]=async(input,output)=>{if(!isLegacy(input.sessionID))return;await textC(input,output)}}const evt=legacy.hooks.event;if(typeof evt==="function"){hooks.event=evt}}else{hooks["experimental.chat.messages.transform"]=harvestMsgIdsTransform}if(deps.z!==void 0||legacy!==void 0){hooks["chat.headers"]=async(input,output)=>{if(isLegacy(input.sessionID)){output.headers["x-bili-plugin-bypass"]="1";return}const base=getOrigin();if(base===void 0)return;output.headers["x-bili-plugin"]="opencode";output.headers["x-bili-plugin-conversation"]=input.sessionID;output.headers["x-bili-plugin-instructions-mutable"]="1";const model=input.model;if(model&&typeof model.providerID==="string"&&typeof model.id==="string"){const key2=`${model.providerID}/${model.id}`;const w2=windows.get(key2);if(w2!==void 0)output.headers["x-bili-plugin-context-window"]=String(w2);const o=outputs.get(key2);if(o!==void 0)output.headers["x-bili-plugin-max-output"]=String(o);const modelHeader=asciiHeaderValue(model.id);if(modelHeader!==void 0)output.headers["x-bili-plugin-model"]=modelHeader;reportRuntimeInfoOnChange(base,{agent:"opencode",model:model.id,contextWindow:w2,maxOutput:o,source:"client-config"})}maybeReportDerived(base,input.sessionID)};const forward2=deps.forward??((o,conversationId,tool,args,nativeCaller)=>Promise.resolve().then(()=>(init_shared(),shared_exports)).then(m2=>m2.forwardTool(o,conversationId,tool,args,void 0,nativeCaller===true)));if(legacy!==void 0){const tools={};for(const[name,def]of Object.entries(legacy.tools)){const exec=typeof def.execute==="function"?def.execute:void 0;tools[name]={description:typeof def.description==="string"?def.description:name,args:def.args??{},execute:async(args,v1ctx)=>{if(exec!==void 0&&isLegacy(v1ctx.sessionID)){return String(await exec(args,v1ctx)??"")}const base=getOrigin();if(base===void 0)return"bili: no live proxy yet \u2014 compression temporarily unavailable";const out=await forward2(base,v1ctx.sessionID,name,args,true);if(out.failed)throw new Error(out.text);return out.text}}}hooks.tool=tools}else{const tools={};if(deps.z!==void 0){for(const t of ACP_TOOLS_OPENAI){const fn=t.function;tools[fn.name]={description:fn.description??fn.name,args:jsonSchemaToZodShape(fn.parameters,deps.z),execute:async(args,v1ctx)=>{const base=getOrigin();if(base===void 0)return"bili: no live proxy yet \u2014 compression temporarily unavailable";const out=await forward2(base,v1ctx.sessionID,fn.name,args,true);if(out.failed)throw new Error(out.text);return out.text}}}}else{console.error("[bili-opencode-native] v1: zod unavailable \u2014 plugin tools skipped; sessions run in proxy mode (wire-injected compress)")}if(Object.keys(tools).length>0)hooks.tool=tools}}return hooks}async function resolveV1Origin(){try{return await readyOrigin(state6)}catch{return void 0}}var server=async ctx=>{if(plan.mode==="off")return{};const origin=await resolveV1Origin();if(installNativeFetchIntercept(state6)){console.log("[bili-opencode-native] v1: fetch patch installed (catches providers without an explicit baseURL)")}if(origin===void 0){console.error("[bili-opencode-native] v1: no live proxy at startup \u2014 traffic goes direct until runtime recovery lands one");return{}}console.log(`[bili-opencode-native] v1 active (proxy ${origin})`);let z2;try{const zodSpecifier="zod";z2=await import(zodSpecifier)}catch{z2=void 0}let legacy;try{legacy=await loadLegacyAcp(ctx,msg=>console.log(msg))}catch{legacy=void 0}return createV1ServerHooks(()=>state6.origin,ctx,{z:z2,legacy})};var opencode_native_default={id:"billion-context-opencode-native",setup:createOpencodeV2Setup({route:createNativeRoute(state6),incremental:maybeIncrementalOpencode}),server};async function maybeIncrementalOpencode(e,s3){try{const sid=typeof e.sessionID==="string"?e.sessionID:"";const base=s3.proxyBase;const req=e.request;if(!sid||!base||req===void 0||typeof req.clone!=="function")return;const url=req.url;sweepStale(incPendingOpencode,INC_PENDING_TTL_MS);let origText;try{origText=await req.clone().text()}catch{return}let body;try{body=JSON.parse(origText)}catch{return}if(body===null||typeof body!=="object")return;const b2=body;if(typeof b2.model!=="string"||!wireMessagesLookAnthropic(b2.messages))return;if(!await probeIncrementalTurns(base))return;let inflight4=false;for(const pending of incPendingOpencode.values()){if(pending.url===url&&Date.now()-pending.at<INC_PENDING_TTL_MS){inflight4=true;break}}if(inflight4)return;const plan2=planIncrementalTurn({conversationId:sid,path:"/v1/messages",messages:b2.messages,system:b2.system,request:b2,msgIds:alignedMsgIdsForWire(sid,b2.messages)});if(plan2.mode==="skip")return;const turnId=newIncrementalTurnId();rememberOriginalBody(turnId,origText);replaceRequestPayload(e,plan2.body,{[INCREMENTAL_TURN_MARKER_HEADER]:"1",[INCREMENTAL_TURN_ID_HEADER]:turnId});incPendingOpencode.set(turnId,{sid,url,messages:b2.messages,system:b2.system,base,at:Date.now()})}catch{}}var INC_PENDING_TTL_MS=3e4;var incPendingOpencode=new Map;function __resetOpencodeIncrementalForTests(){incPendingOpencode.clear()}function opencodeIncrementalOnResponse(_url,response,headers){const turnId=headers?.[INCREMENTAL_TURN_ID_HEADER];if(turnId===void 0)return;const pending=incPendingOpencode.get(turnId);if(pending===void 0)return;const seq=response.headers.get("x-bili-applied-seq");if(response.status===200&&(seq===null||!Number.isFinite(Number(seq)))){return}incPendingOpencode.delete(turnId);try{if(response.status===200){noteIncrementalAck(pending.sid,Number(seq),pending.messages,pending.system);return}if(response.status===409){const verdict=noteIncrementalRejection(pending.sid);logHostEvent("warn","[native-client]",`[opencode] incremental turn rejected (409) \u2014 conversation ${pending.sid} ${verdict==="dead"?"falls back to full resend (rejection circuit)":"re-seeds with a full resync next turn"} (#3369)`);return}if(response.status===503){clearIncrementalProbe(pending.base);logHostEvent("warn","[native-client]",`[opencode] incremental turns unavailable (503) \u2014 conversation ${pending.sid} state preserved, re-probing next turn (#3369)`)}}catch{}}state6.onResponse=opencodeIncrementalOnResponse;export{__resetOpencodeIncrementalForTests,_noteRoutedForTest,_resetNativeStateForTest,_setSpawnForTest,_stateRespawnForTest,armNativeOpencode,createNativeRoute,createV1ServerHooks,opencode_native_default as default,extractV1Outputs,extractV1Windows,jsonSchemaToZodShape,maybeIncrementalOpencode,opencodeIncrementalOnResponse,planNativeOpencode,rewriteV1Providers,shouldBootstrapNativeOpencode,verifyAttachAndRecover,wireBodyMediaBytes};
|
|
7247
7247
|
/*! Bundled license information:
|