billion-context 0.0.12330-pr.7928.7f35310 → 0.0.12332-pr.7934.f05a67f
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
CHANGED
|
@@ -1231,7 +1231,7 @@ ${partialOutcomeNote(blocksCreated)}`;const out={text:text2,failed:outcome==="fa
|
|
|
1231
1231
|
${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{mkdirSync7(dirname4(exported.path),{recursive:true});writeFileSync4(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:randomUUID3(),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_util();init_dist();init_logger();import{createHash as createHash13,randomUUID as randomUUID4}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 featureCount=Math.max(1,tokens.length-1);const stride=Math.max(1,Math.ceil(featureCount/MAX_FEATURES));const v2=new Int16Array(64);for(let f2=0;f2<featureCount;f2+=stride){const feature=tokens.length<2?tokens[0]??canonical2:`${tokens[f2]}${tokens[f2+1]}`;const h1=fnv1a32(feature,2166136261);const h2=fnv1a32(feature,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}var SYSTEM_REMINDER_FRAME="<system-reminder>";function opensSystemReminderFrame(text2){return text2.trimStart().startsWith(SYSTEM_REMINDER_FRAME)}function dshSkillCatalogPath(msg){return msg.role!=="assistant"&&msg.contentType==="text"&&typeof msg.text==="string"&&opensSystemReminderFrame(msg.text)&&msg.text.includes("<available_skills>")?"durable/skill-catalog":void 0}function agentsMdRevisionPath(text2){const m2=/^\s*\x3csystem-reminder\x3e\s*(?:(?:Updated|Additional)\s+instructions\s+from|Instructions\s+removed)\s*:[ \t]*([^\n]+)/.exec(text2);if(m2===null)return void 0;const path66=m2[1].trim();return path66.length>0?`durable/agents-md-update/${path66}`:void 0}function dshWorkspaceInstructionsPath(msg){if(msg.role==="assistant"||msg.contentType!=="text"||typeof msg.text!=="string")return void 0;if(!opensSystemReminderFrame(msg.text))return void 0;return agentsMdRevisionPath(msg.text)??(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")||msg.text.includes("The following information describes your current session"))?"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}var TOOL_JOB_NOTICE_RE=/^background job \S+(?: \(|$|\r?\n)/i;function dshToolJobNoticePath(msg){return msg.role!=="assistant"&&msg.contentType==="text"&&typeof msg.text==="string"&&TOOL_JOB_NOTICE_RE.test(msg.text.trim())?"oneshot/tool-job-notice":void 0}function dshMnemonPath(msg){return msg.role!=="assistant"&&msg.contentType==="text"&&typeof msg.text==="string"&&(startsWithAsciiCI(msg.text.trimStart(),"[MNEMON] ")||startsWithAsciiCI(msg.text.trimStart(),"[MNEMON RUNTIME MEMORY"))?"oneshot/mnemon":void 0}var SUBAGENT_SETTLED_RE=/^background subagent .+? (?:finished|was stopped|ran out of room|declined|failed|ended)\b/i;function dshSubagentSettledPath(msg){return msg.role!=="assistant"&&msg.contentType==="text"&&typeof msg.text==="string"&&SUBAGENT_SETTLED_RE.test(msg.text.trim())?"oneshot/subagent-settled":void 0}function dshAgentRelayPath(msg){return msg.role!=="assistant"&&msg.contentType==="text"&&typeof msg.text==="string"&&msg.text.startsWith("Agent ")&&msg.text.includes(" sent a message: ")?"oneshot/agent-relay":void 0}function dshImageHandlePath(msg){return msg.role!=="assistant"&&msg.contentType==="text"&&typeof msg.text==="string"&&msg.text.includes("; request preview ")?"oneshot/image-handle":void 0}function dshImageOffloadPlaceholderPath(msg){return msg.role!=="assistant"&&msg.contentType==="text"&&typeof msg.text==="string"&&(msg.text.includes("image omitted to fit request image limits;")||msg.text.includes("image omitted because this model accepts text only;"))?"oneshot/image-offload-placeholder":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)??dshPastedImagePath(msg)??dshToolJobNoticePath(msg)??dshMnemonPath(msg)??dshSubagentSettledPath(msg)??dshAgentRelayPath(msg)??dshImageHandlePath(msg)??dshImageOffloadPlaceholderPath(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)??dshMnemonPath(msg)??dshSubagentSettledPath(msg)??dshAgentRelayPath(msg)??dshImageHandlePath(msg)??dshImageOffloadPlaceholderPath(msg)};var dshCarrierRawMarkers=["<available_skills>","Instructions from:","Updated instructions from:","Additional instructions from:","Instructions removed:","Current runtime context","The following information describes your current session","<mcp_catalog>","Time sampled while preparing turn","<type>image</type>","background job","[MNEMON] ","[MNEMON RUNTIME MEMORY","Background subagent "," sent a message: ","; request preview ","image omitted to fit request image limits;","image omitted because this model accepts text only;"];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_MAJORITY_LOSS_NOTED="foldMajorityLossNoted";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 md2=session.metadata;if(!md2)return;delete md2[METADATA_DRIFT_STREAK];delete md2[METADATA_DRIFT_SINCE];delete md2[METADATA_DRIFT_ESCALATED];delete md2[METADATA_EPOCH_CONFIRM];delete md2[METADATA_SHAPE_NOTED];delete md2[METADATA_TRUNC_NOTED];delete md2[METADATA_TAIL_TRUNC_NOTED];delete md2[METADATA_MAJORITY_LOSS_NOTED];delete md2[METADATA_EPISODE_ORDER];delete md2[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}
|
|
1232
1232
|
${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 candidateWordEvidence(candidates){const canon2=new WeakMap;const bags=new WeakMap;const sketches=new WeakMap;const canonicalOf=m2=>{let text2=canon2.get(m2);if(text2===void 0)canon2.set(m2,text2=canonicalTextOf(m2.text??""));return text2};const wordBag=m2=>{let wh=bags.get(m2);if(wh===void 0)bags.set(m2,wh=wordBagDigest(canonicalOf(m2)));return wh};const sketch=m2=>{let sh=sketches.get(m2);if(sh===void 0)sketches.set(m2,sh=simhashHex(canonicalOf(m2)));return sh};const bucketBy=keyOf2=>{let buckets;return key2=>{if(buckets===void 0){buckets=new Map;for(const c of candidates){const k2=keyOf2(c);if(k2===void 0)continue;const bucket=buckets.get(k2);if(bucket===void 0)buckets.set(k2,[c]);else bucket.push(c)}}return buckets.get(key2)??[]}};const byWordBag=bucketBy(c=>wordBag(c.message));const byUnwrappedIdentity=bucketBy(c=>c.message.role==="user"&&c.message.contentType==="text"?normalizedIdentity({...c.message,text:(c.message.text??"").replace(/\r?\n/g," ")}):void 0);return{wordBag,sketch,withWordBag:wh=>byWordBag(wh),withUnwrappedIdentity:n=>n===void 0?[]:byUnwrappedIdentity(n)}}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 plan={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{plan.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))}plan.newOrder=newOrder;plan.nextCanon=canon2;const missing=[];const missingSet=new Set;const displaced=new Set;for(const id of covered){const present=byId2.get(id);if(present===void 0){if(!expectedAbsent?.has(id)){missing.push(id);missingSet.add(id)}continue}const t=anchors[id]?.t;if(t!==void 0&&present.toolCallId!==void 0&&present.toolCallId!==""&&present.toolCallId!==t){missing.push(id);missingSet.add(id);displaced.add(id)}}if(missing.length===0)return plan;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 evidence=candidateWordEvidence(candidates);const missingMiddle=[];for(let i=prefix;i<oldOrder.length-suffix;i++){const id=oldOrder[i];if(missingSet.has(id))missingMiddle.push(id)}const toolMissing=missingMiddle.concat([...displaced].filter(id=>!missingMiddle.includes(id)));const toolCandidates=candidates.concat(msgs.flatMap((message,pos)=>message.id!==void 0&&displaced.has(message.id)?[{id:message.id,message,pos}]:[]));const gapPairs=[];let minClaimed=Infinity;let maxClaimed=-Infinity;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;plan.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}plan.claims.set(oldId,[newId]);claimedCandidates.add(newId);plan.byPos++;minClaimed=Math.min(minClaimed,i);maxClaimed=Math.max(maxClaimed,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;plan.resyncs++;j2=r;continue}const oldId=oldOrder[iOld];const newId=newOrder[iNew];if(oldId===newId||!missingSet.has(oldId)||covered.has(newId)||claimedCandidates.has(newId)||plan.claims.has(oldId)){j2++;continue}plan.claims.set(oldId,[newId]);claimedCandidates.add(newId);plan.byPos++;minClaimed=Math.min(minClaimed,iOld);maxClaimed=Math.max(maxClaimed,iOld);j2++}}if(toolMissing.length>0&&toolCandidates.length>0){const byToolCallId=new Map;for(const cand of toolCandidates){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 toolMissing){if(plan.claims.has(oldId))continue;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;plan.claims.set(oldId,[usable[0].id]);claimedCandidates.add(usable[0].id);plan.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(plan.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;plan.claims.set(oldId,[b2.ids[b2.k]]);claimedCandidates.add(b2.ids[b2.k]);b2.k++;plan.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(plan.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);plan.claims.set(oldId,[newId]);claimedCandidates.add(newId);plan.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(plan.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)||plan.claims.has(anchor.x))return;plan.claims.set(anchor.x,targets)};if(singles.length===1){plan.claims.set(oldId,[singles[0]]);claimedCandidates.add(singles[0]);claimSibling([singles[0]])}else{const[a,b2]=pairs[0];plan.claims.set(oldId,[a,b2]);claimedCandidates.add(a);claimedCandidates.add(b2);claimSibling([a,b2])}plan.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=`
|
|
1233
1233
|
${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(plan.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;plan.claims.set(oldId,[target]);claimedCandidates.add(target);plan.byImage++}const familyClaim=map=>{const byNorm=new Map;for(const oldId of missingMiddle){if(plan.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;plan.claims.set(oldIds[k2],[usable[k2]]);claimedCandidates.add(usable[k2]);plan.byImage++}}};familyClaim(stripVariants);familyClaim(appendVariants)}}if(gapPairs.length>0){const fenced=plan.byPos>0||plan.resyncs>0;for(const gap of gapPairs){if(plan.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==="user")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??""))){plan.claims.set(gap.oldId,[gap.newId]);claimedCandidates.add(gap.newId);plan.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;plan.claims.set(gap.oldId,[gap.newId]);claimedCandidates.add(gap.newId);plan.byOrder++}}}for(const id of missing){if(!plan.claims.has(id))plan.unmatched.push(id)}const residualMiddle=missingMiddle.filter(id=>!plan.claims.has(id));if(residualMiddle.length>=SHAPE_MASS_MIN){const looseProse=(anchor,m2)=>{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;if(anchor.r==="user"){if(anchor.c!=="text"||m2.contentType!=="text")return false;const unwrapped={...m2,text:(m2.text??"").replace(/\r?\n/g," ")};return normalizedIdentity(unwrapped)===anchor.n}if(anchor.wh===void 0||anchor.sh===void 0)return false;if(evidence.wordBag(m2)!==anchor.wh)return false;const dist=hammingHex(anchor.sh,evidence.sketch(m2));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 pool=anchor.r==="user"?evidence.withUnwrappedIdentity(anchor.n):evidence.withWordBag(anchor.wh);const cand=pool.find(c=>!claimedCandidates.has(c.id)&&looseProse(anchor,c.message));if(cand===void 0)continue;plan.claims.set(oldId,[cand.id]);claimedCandidates.add(cand.id);plan.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;plan.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=plan.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=plan.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++){plan.claims.set(run[k2].id,[familyCands[k2].id]);claimedCandidates.add(familyCands[k2].id);plan.byShape++}}}}{const residualClasses=new Set(["text","tool-call","tool-result","image","reasoning","code"]);const classCarrying=plan.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 sh=anchor.sh;const loose=anchor.wh!==void 0&&sh!==void 0&&evidence.withWordBag(anchor.wh).some(c=>!claimedCandidates.has(c.id)&&(anchor.r===void 0||anchor.r===c.message.role)&&(()=>{const d=hammingHex(sh,evidence.sketch(c.message));return d>=0&&d<=GAP_SIMHASH_MAX_HAMMING})());if(loose)plan.nearDupResidual.push(id);else plan.absentEverywhere.push(id)}}if(plan.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 plan.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))plan.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??"")}plan.churnTokens=churnTokens;plan.claimedChurnTokens=claimedChurnTokens;return plan}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||!list.some(id=>(claims.get(id)?.length??0)>0))continue;const present=new Map;for(const id of list)present.set(id,(present.get(id)??0)+1);const rewritten=[];for(const id of list){const replacement=claims.get(id);if(replacement===void 0||replacement.length===0){rewritten.push(id);continue}const keep=replacement.filter(target=>!present.has(target)||claims.has(target));const remaining=present.get(id)-1;if(remaining===0)present.delete(id);else present.set(id,remaining);for(const target of keep){rewritten.push(target);present.set(target,(present.get(target)??0)+1)}}list.length=rewritten.length;for(let i=0;i<rewritten.length;i++)list[i]=rewritten[i];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 activeCovered=coveredIdsOf(blocks);const covered=new Set(activeCovered);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 path66=classifyCarrier(m2);if(path66!==void 0)expected[id]=path66}}let expectedSize=Object.keys(expected).length;const plan=planReconciliation(oldOrder,anchors,msgs,covered,positions,new Set(Object.keys(expected)));if(plan.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=${plan.unmatched.length+plan.claims.size} claims=${plan.claims.size} expected=${expectedSize} byPos=${plan.byPos} resyncs=${plan.resyncs} byTool=${plan.byTool} byTwin=${plan.byTwin} bySim=${plan.bySim} byOrder=${plan.byOrder} byNorm=${plan.byNorm} byTurn=${plan.byTurn} byImage=${plan.byImage} unmatched=${plan.unmatched.length} | msgs[0..5]=${sample.join(" | ")}
|
|
1234
|
-
`)}let offloadPending=session.metadata[METADATA_OFFLOAD_PENDING]??{};if(plan.unmatched.length>0&&opts.storedRowLookup!==void 0){const needed=[];for(const id of plan.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 path66=classifyCarrier(parsed);if(path66!==void 0){expected[id]=path66;continue}}}if(hasImageMarker)offloadPending[id]=1}}}}const pendingIds=Object.keys(offloadPending);if(pendingIds.length>0){const claimedTargets=new Set;for(const targets of plan.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=plan.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=plan.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=plan.newOrder.slice(-MAX_ORDER);if(plan.nextCanon!==void 0){session.metadata[METADATA_POSITIONS]={ids:nextOrder,canon:plan.nextCanon.slice(-MAX_ORDER)}}const absentSet=new Set(plan.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(plan.newOrder);const witnessSet=new Set(witness2);const commonWitness=witness2.filter(id=>inboundSet.has(id));const commonInbound=plan.newOrder.filter(id=>witnessSet.has(id));wireContinuity=commonWitness.length>0&&witness2.slice(witness2.length-commonWitness.length).every(id=>inboundSet.has(id))&&plan.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))&&plan.newOrder.slice(0,commonPrefix.length).every(id=>witnessSet.has(id))}const markerChurnExplained=(opts.markerStripped??0)>0;const realUnmatched=plan.unmatched.filter(id=>expected[id]===void 0);const accountedHere=plan.unmatched.length-realUnmatched.length;const expectedNote=accountedHere>0?`; ${accountedHere} more covered id(s) accounted as expected host behavior (#5142)`:"";const reasoningOnlyDrop=plan.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=plan.byShape>0||classCarryingResidual.length>0&&plan.nearDupResidual.length>=.6*classCarryingResidual.length;const truncationExplained=classCarryingResidual.length>0&&plan.nearDupResidual.length===0&&classCarryingResidual.every(id=>absentSet.has(id))&&wireContinuity;const tailTruncationExplained=classCarryingResidual.length>0&&plan.nearDupResidual.length===0&&classCarryingResidual.every(id=>absentSet.has(id))&&tailTruncated;let coveredHard=0;let presentHard=0;for(const id of activeCovered){if(isResponsesTurnSeparatorId(id)||expected[id]!==void 0||anchors[id]?.c==="reasoning")continue;coveredHard++;if(byId2.has(id))presentHard++}const hardDirectMajority=presentHard>=MIN_RESYNC_RUN&&2*presentHard>coveredHard;if(hardDirectMajority&&epochConfirmPending(session))resetFoldDriftState(session);const totalDrift=plan.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(plan.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)&&!plan.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];const storedPositions=session.metadata[METADATA_POSITIONS];const positionIds=storedPositions?.ids;const positionCanon=storedPositions?.canon;for(let i=nextOrder.length-1;i>=0;i--){if(deadIds.has(nextOrder[i])){nextOrder.splice(i,1);if(positionIds===nextOrder&&Array.isArray(positionCanon))positionCanon.splice(i,1)}}if(Array.isArray(positionIds)&&positionIds!==nextOrder){for(let i=positionIds.length-1;i>=0;i--){if(deadIds.has(positionIds[i])){positionIds.splice(i,1);if(Array.isArray(positionCanon))positionCanon.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(plan.claims.size>0&&mode==="repair"){rewriteBlocks(blocks,plan.claims);const prior=new Set(session.state?.lastPassIds??[]);for(const targets of plan.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,(plan.churnTokens??0)-(plan.claimedChurnTokens??0)):plan.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 ${plan.byShape}, ${plan.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(!hardDirectMajority&&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(session.stats)delete session.stats.preflightRuns;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&&plan.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(plan.claims.size>0&&mode==="repair"){opts.log(realUnmatched.length>0?"warn":"info",`${tag}[fold-reconcile] resent history drifted: ${plan.claims.size+realUnmatched.length} covered id(s) missing${expectedNote} \u2014 reanchored ${plan.claims.size} (${plan.byPos} positional${plan.resyncs>0?`, ${plan.resyncs} order break(s) resynced`:""}, ${plan.byTool} by toolCallId${plan.byTwin>0?`, ${plan.byTwin} by toolCallId twin`:""}${plan.bySim>0?`, ${plan.bySim} by simhash corroboration`:""}${plan.byOrder>0?`, ${plan.byOrder} by order bracket`:""}, ${plan.byNorm} by normalized identity${plan.byTurn>0?`, ${plan.byTurn} by assistant-turn key`:""}${plan.byImage>0?`, ${plan.byImage} by image-capability variant`:""}${plan.byShape>0?`, ${plan.byShape} by shape census`:""}) onto churned bytes, ${realUnmatched.length} unmatched re-enter the wire unfolded${plan.idRewriteSuspects>0?`; ${plan.idRewriteSuspects} suspected host-rewritten tool-call ids (identical content under a different toolCallId \u2014 #2396)`:""} (#1921)${driftTok}`)}else if(plan.claims.size>0){opts.log("warn",`${tag}[fold-reconcile] resent history drifted: ${plan.claims.size+realUnmatched.length} covered id(s) missing${expectedNote}, ${plan.claims.size} matchable by anchor (${plan.byPos} positional${plan.resyncs>0?`, ${plan.resyncs} resynced`:""}, ${plan.byTool} toolCallId${plan.byTwin>0?`, ${plan.byTwin} twin`:""}${plan.bySim>0?`, ${plan.bySim} simhash`:""}${plan.byOrder>0?`, ${plan.byOrder} order-bracket`:""}, ${plan.byNorm} normalized${plan.byTurn>0?`, ${plan.byTurn} turn key`:""}${plan.byImage>0?`, ${plan.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(hardDirectMajority&&nonReasoningUnmatched>=FOLD_DRIFT_ESCALATE_MIN_UNMATCHED&&!shapeExplained&&!truncationExplained&&!tailTruncationExplained){if(session.metadata[METADATA_MAJORITY_LOSS_NOTED]!==true){session.metadata[METADATA_MAJORITY_LOSS_NOTED]=true;opts.log("info",`${tag}[fold-reconcile] ${realUnmatched.length} covered id(s) missing but ${presentHard}/${coveredHard} hard-covered id(s) still ride verbatim on the wire \u2014 partial interior loss, fold substrate healthy, no epoch confirmation (#5715)`)}}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)${plan.idRewriteSuspects>0?`; ${plan.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:plan.claims.size>0?mode==="repair"?"reanchored":"unmatched":"unmatched",missing:plan.claims.size+realUnmatched.length,claims:plan.claims.size,byPos:plan.byPos,byTool:plan.byTool,byTwin:plan.byTwin,bySim:plan.bySim,byOrder:plan.byOrder,byNorm:plan.byNorm,byTurn:plan.byTurn,byImage:plan.byImage,byShape:plan.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 prev=session.metadata[METADATA_SYSTEM_FP];const fp2=system===void 0||system===null?"-":prev!==void 0&&prev.fp!=="-"&&prev.size===text2.length&&prev.head!==void 0&&prev.head===text2.slice(0,256)?prev.fp:createHash12("sha256").update(text2).digest("hex").slice(0,16);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,head:text2.slice(0,256)}}function noteCanonicalSystemFingerprint(session,canonical2){if(!session.metadata)return;const text2=canonical2===void 0||canonical2===null?"":JSON.stringify(canonical2)??"";const prev=session.metadata[METADATA_CANONICAL_SYS_FP];const fp2=canonical2===void 0||canonical2===null?"-":prev!==void 0&&prev.fp!=="-"&&prev.size===text2.length&&prev.head!==void 0&&prev.head===text2.slice(0,256)?prev.fp:createHash12("sha256").update(text2).digest("hex").slice(0,16);session.metadata[METADATA_CANONICAL_SYS_FP]={fp:fp2,size:text2.length,head:text2.slice(0,256)}}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();var FULL_DETAIL_LINES=512;var BOOT_ID=randomUUID4();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 RECOVERY_BURST_MS=10*6e4;var RECOVERY_STALE_MS=30*6e4;var RECOVERY_CAP=500;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:randomUUID4(),round:0},async()=>{try{return await fn()}finally{const capture2=captures.getStore();if(capture2){delete capture2.sentBody;delete capture2.inBody;delete capture2.imageFacts;delete capture2.calibration}}})}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:randomUUID4()}}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())}var CREDENTIAL_HEADER_NAMES=["authorization","x-api-key","api-key","x-goog-api-key"];function credentialFingerprint(headers){if(!headers)return void 0;const values=new Set;const fields=new Set;for(const[name2,value]of Object.entries(headers)){const n=name2.toLowerCase();if(CREDENTIAL_HEADER_NAMES.includes(n)){const v2=value.trim().replace(/^Bearer\s+/i,"").trim();if(v2!==""){const m2=/^SDK-HMAC-SHA256\s+Access=([^\s,]+)/i.exec(v2);const credential=m2!==null?`sdk-hmac:${m2[1]}`:v2;values.add(credential);fields.add(JSON.stringify([n,credential]))}}}if(values.size===0)return void 0;const cred=values.size===1?values.values().next().value:`credential-set:${JSON.stringify([...fields].sort())}`;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 transient2=pendingCapture(session);const prior=transient2.sentBody;const sameBytes=prior!==void 0&&prior.bytes===buf.byteLength&&prior.full!==null&&prior.full.equals(buf);const digest=sameBytes?prior.digest:createHash13("sha256").update(buf).digest("hex");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),ownedSeparatorCores:samePayload?prior.ownedSeparatorCores: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 noteCalibrationPair(session,pair){const capture2=captures.getStore();if(capture2?.session===session){capture2.calibration=pair;return}}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,cap2,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=cap2>0?Math.min(entry.cost,cap2):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}i++;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}i++}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 cacheLedgerIsEmpty(session){const led=(session.metadata??{})[LEDGER_KEY];return!led||led.lines.length===0&&led.folds.length===0}var usageSink=null;var usageStatsSink=null;var usageSinkWarned=false;function setEgressUsageSink(fn){usageSink=fn}function setEgressUsageStatsSink(fn){usageStatsSink=fn}function emitUsageEvents(session,events){if(!usageSink||events.length===0)return;try{usageSink(session.id,events)}catch(err2){if(!usageSinkWarned){usageSinkWarned=true;log("warn",`[${session.id}] [cache-ledger] egress usage sink failed (${err2 instanceof Error?err2.message:String(err2)}) \u2014 the in-memory ledger keeps the truth; the stream lags until the sink recovers`)}}}function usageStatsJson(led){if(led.lines.length===0&&led.folds.length===0)return null;const last=led.lines[led.lines.length-1];const obj={requests:led.agg.requests,input:Math.round(led.agg.input),cached:Math.round(led.agg.cached),output:Math.round(led.agg.output),nc:Math.round(led.agg.nc),cr:Math.round(led.agg.cr),tr:Math.round(led.agg.tr),folds:led.folds.length};if(last!==void 0){obj.lastAt=last.at;if(last.hitPct!==null)obj.hitPct=last.hitPct;if(typeof last.input==="number"&&last.input>0)obj.finalContext=Math.round(last.input)}return JSON.stringify(obj)}function pushFold(led,f2,closeFrom){for(let i=closeFrom;i<led.folds.length;i++){const open=led.folds[i];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});recordFoldRecovery(led,f2.at,f2.S,led.foldSeqCounter)}function recordNudgeInject(session,nudge){if(!nudge)return;const led=getCacheLedger(session);const evs=led.recovery??(led.recovery=[]);if(evs.length===0){for(const f2 of led.folds){evs.push({kind:"f",at:f2.at,S:f2.S,seq:f2.seq,p:0,mode:"a"})}}evs.push({kind:"n",at:Date.now(),p:nudge.breakdown?.["pendingT1"]??0,tier:typeof nudge.tier==="number"?nudge.tier:null});if(evs.length>RECOVERY_CAP)evs.splice(0,evs.length-RECOVERY_CAP);markDirty(session)}function recordFoldRecovery(led,at2,S2,seq){if(led.recovery===void 0)return;const evs=led.recovery;let lastF;let lastN;for(const ev of evs){if(ev.kind==="f")lastF=ev;else if(ev.at<=at2)lastN=ev}const gapArmed=lastN!==void 0&&lastN.at>(lastF?.at??0);const chainArmed=lastF!==void 0&&at2-lastF.at<=RECOVERY_BURST_MS;const nudgeFresh=lastN!==void 0&&at2-lastN.at<=RECOVERY_STALE_MS;const mode=lastN&&nudgeFresh&&(gapArmed||chainArmed)?"n":"a";const p2=lastN&&nudgeFresh?lastN.p:0;evs.push({kind:"f",at:at2,S:S2,seq,p:p2,mode,pct:mode==="n"&&p2>0?Math.round(S2/p2*1e3)/10:void 0});if(evs.length>RECOVERY_CAP)evs.splice(0,evs.length-RECOVERY_CAP)}function recordCacheFoldsFromBlocks(session,blocks,geo){if(blocks.length===0)return[];const led=getCacheLedger(session);let closeFrom=0;const emitted=[];for(const b2 of blocks){const id=refNum3(b2.blockId);if(id<=led.lastBlockId)continue;const foldRow={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};pushFold(led,foldRow,closeFrom);emitted.push({type:"F",at:foldRow.at,payload:foldRow});closeFrom=led.folds.length-1;led.lastBlockId=Math.max(led.lastBlockId,id)}if(emitted.length>0)emitUsageEvents(session,emitted);return emitted}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 capture2=captures.getStore();const capturePair=capture2?.session===session?capture2.calibration:void 0;if(capture2?.session===session)delete capture2.calibration;if(capturePair!==void 0&&capturePair.imageTokens>0)return;const pendingEst=capturePair!==void 0?capturePair.estimate:session.stats.lastLocalTextEstimate;const pendingOrigin=capturePair!==void 0?normalizeUpstreamOrigin(capturePair.origin):normalizeUpstreamOrigin(session.stats.lastLocalTextEstimateOrigin);if(pendingEst!==void 0&&pendingEst>=CALIBRATION_MIN_ESTIMATE&&settleOrigin!==void 0&&pendingOrigin===settleOrigin){const rawSample=billed/pendingEst;const sampleProvenance=capturePair!==void 0?CALIBRATION_PROVENANCE_TEXT_ONLY:void 0;const settleModel=capturePair?.model!==void 0?capturePair.model: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.provenances===void 0)ring.provenances=[];while(ring.provenances.length<ring.values.length-1)ring.provenances.push(void 0);ring.provenances.push(sampleProvenance);if(ring.values.length>CALIBRATION_SAMPLE_WINDOW){ring.values.shift();ring.provenances.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;delete session.stats.calibratedEstimateProvenance}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;const ringProvenance=ring.provenances!==void 0&&ring.provenances.length===ring.values.length&&ring.provenances.every(p2=>p2===CALIBRATION_PROVENANCE_TEXT_ONLY)?CALIBRATION_PROVENANCE_TEXT_ONLY:void 0;if(ringProvenance!==void 0)session.stats.calibratedEstimateProvenance=ringProvenance;else delete session.stats.calibratedEstimateProvenance}}else{delete session.stats.calibratedEstimate;delete session.stats.calibratedEstimateOrigin;delete session.stats.calibratedEstimateModel;delete session.stats.calibratedEstimateProvenance}}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){if(session.transient?.nudgeHeldAfterReject)delete session.transient.nudgeHeldAfterReject;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{const contextTotal=s3.context!==void 0&&s3.context>0?s3.context:s3.total;session.stats.lastInputTokens=Math.max(0,contextTotal-(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;const stampedModel=typeof s3.model==="string"&&s3.model!==""?s3.model:typeof session.metadata?.lastModel==="string"&&session.metadata.lastModel!==""?session.metadata.lastModel:void 0;if(stampedModel!==void 0)session.stats.lastInputTokensModel=stampedModel;if(stampedModel!==void 0){const fallbackWindows=session.metadata.windowFallbackModels??{};const judged=fallbackWindows[stampedModel];if(typeof judged==="number"&&Number.isFinite(judged)&&session.stats.lastInputTokens>judged){const ratchet=session.metadata.windowRatchet??{};const current=Math.max(ratchet[stampedModel]??judged,judged);const trustedCeiling=4*judged;let raised=Math.max(2*session.stats.lastInputTokens,ratchet[stampedModel]??0);if(session.stats.lastInputTokens>trustedCeiling)raised=Math.min(raised,trustedCeiling);if(raised>current){ratchet[stampedModel]=raised;session.metadata.windowRatchet=ratchet;log("info",`[${session.id}] [window-ratchet] model=${stampedModel} billed ${session.stats.lastInputTokens} input beyond the judged window ${judged} \u2014 session window raised to ${raised} (${session.stats.lastInputTokens>trustedCeiling?`clamped to the ${4}\xD7-judged bound ${trustedCeiling} against one anomalous bill`:"2\xD7 the observation"}; monotonic, session-local)`)}}}ingestCalibrationPair(session,contextTotal,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);const usageSample={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};recordCacheSample(session,usageSample);{const usageLine=led.lines[led.lines.length-1];const usageEvents=[];if(usageLine!==void 0&&usageLine.rs===1)usageEvents.push({type:"M",at:usageLine.at});if(usageLine!==void 0){usageEvents.push({type:"S",at:usageLine.at,payload:{s:usageSample,model:typeof session.metadata?.lastModel==="string"&&session.metadata.lastModel!==""?session.metadata.lastModel:void 0}});const stats2=usageStatsJson(led);if(stats2!==null&&usageStatsSink){try{usageStatsSink(session.id,stats2)}catch{}}}emitUsageEvents(session,usageEvents)}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;if(lcp>=shorterFull.length-64)curLine.bs="append";else if(lcp<1024)curLine.bs="head";else{const arrClose=messagesArrayCloseOffset(shorterFull);curLine.bs=arrClose!==null&&lcp>=arrClose?"tail":isMidInsertionAppend(prevSlot.full,curSlot.full,lcp)?"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:hits.reduce((min,hit)=>Math.min(min,hit),Infinity)})}}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)}};let recovery;const recSource=led.recovery&&led.recovery.length>0?led.recovery:led.folds.map(f2=>({kind:"f",at:f2.at,S:f2.S,seq:f2.seq,p:0,mode:"a"}));if(recSource.length>0){const paired2=new Set;const recEvents=recSource.map((ev,i)=>({at:ev.at,kind:ev.kind,...ev.kind==="n"?{tier:ev.tier}:{},pending:ev.p,folded:ev.kind==="f"?ev.S:null,foldSeq:ev.kind==="f"?ev.seq:null,mode:ev.kind==="f"?ev.mode:null,pct:ev.kind==="f"?ev.pct??null:null,paired:false,i}));for(let i=0;i<recEvents.length;i++){if(recEvents[i].kind!=="n")continue;for(let j2=i+1;j2<recEvents.length;j2++){const f2=recEvents[j2];if(f2.kind==="n")break;if(f2.mode!=="n")continue;if(paired2.has(j2))continue;paired2.add(j2);recEvents[i].paired=true;break}}let nudges=0;let folds2=0;let nudgeFolds=0;let activeFolds=0;let totalPending=0;let totalFolded=0;for(const[j2,f2]of recEvents.entries()){if(f2.kind==="n"){nudges+=1;totalPending+=f2.pending}else{folds2+=1;if(f2.mode==="n"){nudgeFolds+=1;totalFolded+=f2.folded??0}else{activeFolds+=1}}}const episodes=[];let recPool=0;for(let j2=0;j2<recEvents.length;j2++){const ev=recEvents[j2];if(ev.kind==="n"){recPool+=ev.pending;let epFolded=0;let epActive=0;for(let k2=j2+1;k2<recEvents.length&&recEvents[k2].kind!=="n";k2++){const f2=recEvents[k2];if(f2.mode==="n")epFolded+=f2.folded??0;else epActive+=1}const credited=Math.min(epFolded,recPool);recPool=Math.max(0,recPool-epFolded);episodes.push({at:ev.at,tier:ev.tier??null,pending:ev.pending,folded:epFolded,pct:ev.pending>0?Math.round(epFolded/ev.pending*1e3)/10:null,credited,extra:epFolded-credited,activeFolds:epActive})}}recovery={events:recEvents.map(({i:_i2,...ev})=>ev),summary:{nudges,folds:folds2,nudgeFolds,activeFolds,totalPending,totalFolded,pct:totalPending>0?Math.round(totalFolded/totalPending*1e3)/10:null},episodes}}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,recovery,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 REPLAY_PRE_BOOT="egress-usage-replay";function rebuildCacheLedgerFromUsageEvents(session,events){const meta=session.metadata??(session.metadata={});const led={v:1,lastBlockId:0,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;for(const ev of events){if(ev.type==="F"){const bid=ev.payload?.bid;if(typeof bid==="string")led.lastBlockId=Math.max(led.lastBlockId,refNum3(bid))}}let appliedS=0;for(const ev of events){if(ev.type==="M"){led.lastBoot=REPLAY_PRE_BOOT;continue}if(ev.type==="F"){const p3=ev.payload;if(!p3||typeof p3.S!=="number"||typeof p3.bid!=="string")continue;pushFold(led,{at:typeof p3.at==="number"?p3.at:ev.at,S:p3.S,sigma:typeof p3.sigma==="number"?p3.sigma:0,X:typeof p3.X==="number"?p3.X:void 0,V:typeof p3.V==="number"?p3.V:void 0,Vp:typeof p3.Vp==="number"?p3.Vp:void 0,bid:p3.bid},0);led.lastBlockId=Math.max(led.lastBlockId,refNum3(p3.bid));continue}if(ev.type!=="S")continue;const p2=ev.payload;if(!p2||!p2.s||typeof p2.s.input!=="number"||typeof p2.s.at!=="number")continue;const prevModel=meta.lastModel;if(typeof p2.model==="string"&&p2.model!=="")meta.lastModel=p2.model;try{recordCacheSample(session,p2.s);appliedS+=1}finally{if(typeof prevModel==="string"&&prevModel!=="")meta.lastModel=prevModel;else delete meta.lastModel}}if(appliedS>0)led.lastBoot=BOOT_ID;return{lines:led.lines.length,folds:led.folds.length}}var{join:join7}=path28;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;var BOOT_WINDOW_DECODES_PER_SESSION=16;var BOOT_WINDOW_MIN_DECODES=64;var BOOT_WINDOW_MAX_DECODES=2048;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 path28.join(proto,`${host}${createHash14("sha256").update(id,"utf8").digest("hex").slice(0,24)}.json`)}function durableWriteFile(file,data,mode){const fd=openSync5(file,"w",mode);try{writeFileSync5(fd,data);fsyncSync2(fd)}finally{closeSync5(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=path28.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 CORRUPT_SIBLING_CAP=1;function pruneCorruptSiblings(baseFile,keepPath){const dir=path28.dirname(baseFile);const prefix=`${path28.basename(baseFile)}.corrupt-`;const keepName=keepPath?path28.basename(keepPath):void 0;let names;try{names=readdirSync4(dir)}catch{return{removed:0,locked:0}}const stampOf=name2=>{const n=Number(name2.slice(prefix.length));return Number.isFinite(n)?n:0};const others=names.filter(n=>n.startsWith(prefix)&&n!==keepName).sort((a,b2)=>stampOf(b2)-stampOf(a));let removed=0;let locked=0;for(const name2 of others.slice(Math.max(0,CORRUPT_SIBLING_CAP-1))){try{unlinkSync3(path28.join(dir,name2));removed++}catch{locked++}}return{removed,locked}}function isAllocationFailureError(error){return error instanceof RangeError&&/allocation failed|heap out of memory/i.test(error.message)}function errText2(error){return error instanceof Error?error.message:String(error)}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;preoomPending=new Set;shadow;residentFieldsForBuild;forkBaseCut=new Set;storageMode;jsonWriterOff;mysqlReady=Promise.resolve();networkFullExpected=false;ready(){return this.mysqlReady}writerOffPending=new Map;durabilityArms=new Map;frozenNoticeAt=new Map;saveTimers=new Map;saveBuilders=new Map;flushWaiters=new Map;lastSaveLanded=new Map;saveWritesInFlight=new Set;durableRevision=new Map;committedMetaFp=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 jsonWriterOffChoice=resolveJsonWriterChoice(process.env,fileStorageJsonWriter());const writerBackendIsSqlite=opts?.shadow!==void 0?!opts.shadow.isAsyncBackend:resolveBackendName(process.env,fileStorageBackend())==="sqlite";this.jsonWriterOff=effectiveJsonWriterOff(process.env,fileStorageJsonWriter(),fileStorageUnified())&&storageMode==="full"&&!unifiedBlockedByEncryption&&writerBackendIsSqlite;if(this.jsonWriterOff&&jsonWriterOffChoice==="unset"){baseLog("info","[storage] json envelope writer off (pure-sqlite default \u2014 index.db is the only persistent copy; restore dual-write with storage.jsonWriter=on)")}if(jsonWriterOffRequested(process.env,fileStorageJsonWriter())&&!this.jsonWriterOff){baseLog("warn","[storage] storage.jsonWriter=off ignored \u2014 requires the unified full/sqlite posture on the sqlite backend (shadow/legacy keep the JSON envelope as sole source of truth; network backends keep it 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(),fileStorageJsonWriter()).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(),fileStorageJsonWriter())??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=>path28.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=>path28.join(this.sessionsDir,rel2)),...this.diskFiles.filter(file=>fileNameMatchesId(path28.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=readFileSync11(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=path28.join(this.sessionsDir,rel2);const tmp=path28.join(path28.dirname(abs),`.tmp-${path28.basename(abs,".json")}-${process.pid}-${this.tmpSeq++}`);try{mkdirSync8(path28.dirname(abs),{recursive:true});const text2=JSON.stringify(store2);durableWriteFile(tmp,this.codec?this.codec.encode(text2):text2);renameSync3(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=path28.join(this.sessionsDir,rel2);const tmp=path28.join(path28.dirname(abs),`.tmp-${path28.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}if(this.writerOffActive()){session.contentStoreDirty=false;return true}mkdirSync8(path28.dirname(abs),{recursive:true});const text2=JSON.stringify(session.contentStore);durableWriteFile(tmp,this.codec?this.codec.encode(text2):text2,384);renameSync3(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;const warmRec={v:null};await this.withPreoomSnapshot(id,session.meta,()=>this.store.writeNow(id,()=>{const r=this.buildRecordForSave(session);warmRec.v=r;return r}));if(warmRec.v)this.noteMetaFp(id,warmRec.v.metadata??{});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(existsSync9(path28.join(root,relPathFor(id))))return true;if(existsSync9(path28.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;mkdirSync8(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=existsSync9(root)?await walkJsonFiles(root):[];const rootFiles=[];filesByRoot.set(root,rootFiles);for(const file of files){if(path28.basename(file).endsWith(".content-store.json"))continue;this.diskFiles.push(file);rootFiles.push(file)}}if(this.replicasAvailable()){this.seedIndexedAliases(canonical2);const hot=(filesByRoot.get(this.sessionsDir)??[]).map(file=>{try{const st2=statSync9(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;const decodeCap=limits.maxSessions===0?0:Math.min(BOOT_WINDOW_MAX_DECODES,Math.max(BOOT_WINDOW_MIN_DECODES,limits.maxSessions*BOOT_WINDOW_DECODES_PER_SESSION));let decoded=0;for(const cand of hot){if(decoded>=decodeCap)break;if(parsedCands.length>=limits.maxSessions&&windowBytes>=limits.maxBytes)break;if(cand.size>limits.maxBytes)continue;const parsed=await this.readRawFileWithBytes(cand.file);decoded++;parsedFiles.add(cand.file);if(!parsed)continue;const rec=this.parseBootPayload(parsed.value);if(!rec||!fileNameMatchesId(path28.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(path28.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=path28.join(root,rel2);try{if(statSync9(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(path28.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(resolve3=>setImmediate(resolve3))}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=readFileSync11(file)}catch(err2){if(err2.code==="ENOENT")return null;throw err2}let raw;try{raw=JSON.parse(bytes.toString("utf8"))}catch(plainTextError){try{raw=JSON.parse(this.readCodec.decode(bytes))}catch(decodeError){if(isAllocationFailureError(plainTextError)||isAllocationFailureError(decodeError)){this.log("error",`[persist] session state ${path28.basename(file)} unreadable this round \u2014 decode ran out of memory, NOT corruption; file left in place for retry (${errText2(plainTextError)} / ${errText2(decodeError)})`);this.preoomPending.add(file);return null}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;this.preoomPending.delete(file);return{id,payload,version:payload.version,savedAt:payload.savedAt}}quarantineCorruptState(file,id,cause){const causeText=errText2(cause);const quarantinePath=`${file}.corrupt-${Date.now()}`;try{renameSync3(file,quarantinePath);const pruned=pruneCorruptSiblings(file,quarantinePath);const capNote=pruned.removed>0?`; removed ${pruned.removed} older forensic cop${pruned.removed===1?"y":"ies"} (cap ${CORRUPT_SIBLING_CAP})`:"";this.log("warn",`[persist] quarantined undecodable session state ${path28.basename(file)} \u2192 ${path28.basename(quarantinePath)}; starting ${id} fresh (${causeText})${capNote}`)}catch(renameErr){this.log("error",`[persist] failed to quarantine corrupt session state ${path28.basename(file)}; resuming ${id} empty this load (${causeText}; rename: ${errText2(renameErr)})`)}}withPreoomSnapshot(id,meta,write){const file=path28.join(this.sessionsDir,relPathFor(id,meta?.protocol,meta?.upstreamOrigin));if(!this.preoomPending.has(file))return write();this.preoomPending.delete(file);let snapshotPath=null;try{if(existsSync9(file)){snapshotPath=`${file}.corrupt-preoom-${Date.now()}`;renameSync3(file,snapshotPath);const pruned=pruneCorruptSiblings(file,snapshotPath);const capNote=pruned.removed>0?`; removed ${pruned.removed} older forensic cop${pruned.removed===1?"y":"ies"} (cap ${CORRUPT_SIBLING_CAP})`:"";this.log("warn",`[persist] preserved pre-OOM session state ${path28.basename(file)} \u2192 ${path28.basename(snapshotPath)} before overwriting it with fresh state (the old envelope was healthy but unreadable under memory pressure)${capNote}`)}}catch(err2){this.log("error",`[persist] failed to preserve pre-OOM session state ${path28.basename(file)} before overwrite; proceeding as pre-fix (${errText2(err2)})`);snapshotPath=null}if(!snapshotPath)return write();const restore=()=>{try{if(existsSync9(snapshotPath)&&!existsSync9(file))renameSync3(snapshotPath,file)}catch{}};try{const result=write();const asPromise=result;if(result&&typeof asPromise?.then==="function"){return asPromise.then(value=>value,error=>{restore();throw error})}if(typeof result==="boolean"&&!result)restore();return result}catch(err2){restore();throw err2}}buildForLoadAll(id,payload){if(this.shadow?.readsUnified){const dbAt=this.shadow.sessionUpdatedAt(id);let importedNewer=false;if(dbAt===null)this.shadow.importRecord(payload);else if(payload.savedAt>dbAt)importedNewer=this.shadow.importRecord(payload)!==null;const view=this.shadow.viewFor(id);if(view){if(!importedNewer&&dbAt!==null&&payload.savedAt>dbAt){this.log("warn",`[persist] newer envelope for ${id} (savedAt ${payload.savedAt}) could not be imported \u2014 serving the envelope view, unified row kept at ${dbAt}`);return this.withEgressUsageReplay(buildSession(payload))}return this.withEgressUsageReplay(buildSession(viewToRecord(view)))}return this.withEgressUsageReplay(buildSession(payload))}return buildSession(payload)}async sweepStaleTemps(){let files;try{files=await walkJsonFiles(this.sessionsDir)}catch{return}for(const file of files){if(isStaleTempName(path28.basename(file))){await rm3(file,{force:true}).catch(()=>{})}}}async migrateLegacyIds(){if(!this.enabled)return;if(existsSync9(this.markerPath()))return;const loaded=await this.store.loadAll();await this.applyLegacyMigration(loaded)}markerPath(){return path28.join(this.sessionsDir,MIGRATION_MARKER)}async applyLegacyMigration(loaded){if(existsSync9(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;const rekeyRec={v:null};await this.withPreoomSnapshot(label,session.meta,()=>this.store.writeNow(label,()=>{const r=this.buildRecordForSave(session);rekeyRec.v=r;return r}));if(rekeyRec.v)this.noteMetaFp(label,rekeyRec.v.metadata??{});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{mkdirSync8(this.sessionsDir,{recursive:true});writeFileSync5(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(existsSync9(path28.join(this.sessionsDir,rel2)))rels.add(rel2)}const expected=path28.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(path28.join(this.sessionsDir,entry.name),{withFileTypes:true})){if(f2.isFile()&&matches(f2.name))rels.add(path28.join(entry.name,f2.name))}}catch{}}}catch{}return[...rels]}async removeSessionFiles(id,meta){for(const rel2 of await this.findSessionFiles(id,meta)){await rm3(path28.join(this.sessionsDir,rel2),{force:true}).catch(()=>{});if(rel2.endsWith(".json")&&!rel2.endsWith(".fb.json")){await rm3(path28.join(this.sessionsDir,`${rel2.slice(0,-".json".length)}.content-store.json`),{force:true}).catch(()=>{})}}}async removeSession(id){this.durabilityArms.delete(id);let meta;const unifiedAvailable=this.replicasAvailable();if(unifiedAvailable){try{const row=this.liveShadow().sessionIdentity(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([path28.join(this.sessionsDir,relPathFor(id,meta?.protocol,meta?.upstreamOrigin)),path28.join(this.sessionsDir,relPathFor(id)),path28.join(this.sessionsDir,flatFileNameFor(id))]);for(const file of livePaths){if(!existsSync9(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),...existsSync9(`${this.sessionsDir}-cold`)?walkJsonFilesSync(`${this.sessionsDir}-cold`):[]].filter(f2=>!path28.basename(f2).endsWith(".content-store.json"));this.diskFilesSeeded=true}const expected=path28.basename(relPathFor(id,meta?.protocol,meta?.upstreamOrigin));const candidates=this.diskFiles.filter(file=>fileNameMatchesId(path28.basename(file),id,meta?.protocol,meta?.upstreamOrigin)||!meta?.protocol&&path28.basename(file).endsWith(`_${expected}`));for(const file of candidates){if(!existsSync9(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=path28.join(this.sessionsDir,proto);const logicalFor=file=>file.endsWith(".fb.json")?`${file.slice(0,-".fb.json".length)}.json`:file;const candidates=new Set([path28.join(dir,path28.basename(relPathFor(id,proto,meta.upstreamOrigin)))]);const suffix=`_${path28.basename(relPathFor(id))}`;for(const file of this.diskFiles){const base=path28.basename(file);if(base.endsWith(".content-store.json"))continue;if(path28.dirname(file)!==dir||!logicalFor(base).endsWith(suffix))continue;candidates.add(file)}const valid=new Map;for(const file of candidates){if(!existsSync9(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=path28.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 (${path28.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===path28.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 ${path28.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 record3=viewToRecord(view);const session=buildSession(record3);this.noteDurable(id,session.revisionEpoch);if(hasNegativePersistedTokens(record3)){this.scheduleSave(session);this.log("info",`[persist] clamped negative token stats on reload for ${id} (#408)`)}this.logColdLoad(id,"unified store",session,record3.savedAt);return this.withEgressUsageReplay(session)}withEgressUsageReplay(session){if(session.metadata?.["egressAuthority"]!==true)return session;if(!cacheLedgerIsEmpty(session))return session;const st2=this.egressOpLogStore();if(!st2)return session;try{const rows=st2.egressUsageRows(session.id);if(rows.length===0)return session;const events=[];for(const r of rows){let payload;try{payload=r.rowType==="M"?void 0:JSON.parse(r.payloadText)}catch{continue}events.push({type:r.rowType,at:r.at,payload})}const n=rebuildCacheLedgerFromUsageEvents(session,events);this.log("info",`[persist] rebuilt the cache ledger for ${session.id} from the egress_usage stream (${n.lines} line(s), ${n.folds} fold(s))`)}catch(err2){this.log("warn",`[persist] egress usage replay failed for ${session.id} (${err2 instanceof Error?err2.message:String(err2)}) \u2014 serving an empty ledger; new samples book fresh from this load`)}return session}maybeRestampToLedger(session){const state8=session.state;if(state8.refLedgerAligned===true)return;if(!state8.messageRefs||Object.keys(state8.messageRefs.byRaw).length===0)return;try{const seqByRawId=this.unifiedSeqByRaw(session.id);if(seqByRawId===null||seqByRawId.size===0)return;const outcome=restampRefsToLedger(state8,seqByRawId);if(session.contentStore){const store2=contentStoreOf(session);const restampedStore=restampContentStore(store2,state8.messageRefs.byRaw);if(restampedStore!==store2)session.contentStore=restampedStore}if(outcome.superseded.size>0){session.restampSuperseded=outcome.superseded}else{delete session.restampSuperseded}const snap=state8.tokenSnapshot;if(snap&&outcome.superseded.size>0){const byRawNow=state8.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)`)}}state8.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)}`)}}consumePendingLedgerAlign(session){if(!session.pendingLedgerAlign)return;delete session.pendingLedgerAlign;this.durabilityArms.delete(session.id);this.maybeRestampToLedger(session)}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,archiveDir2){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.restoreArchived(sessionId,{archiveDir:archiveDir2??join7(this.sessionsDir,"archive")})}catch(err2){this.log("warn",`[persist] unified restore failed: ${String(err2)}`);return null}}unifiedArchiveSession(sessionId,archiveDir2){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.archiveSession(sessionId,{archiveDir:archiveDir2??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,archiveDir2){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.archiveBlock(sessionId,blockId,{archiveDir:archiveDir2??join7(this.sessionsDir,"archive")})}catch(err2){this.log("warn",`[persist] unified block archive failed: ${String(err2)}`);return null}}unifiedRestoreBlock(sessionId,blockId,archiveDir2){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.restoreBlock(sessionId,blockId,{archiveDir:archiveDir2??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}}snapStage0(sessionId,incoming,opts){if(!this.replicasAvailable())return null;return this.liveShadow().snapStage0(sessionId,incoming,opts)}snapStage0Reset(sessionId){if(!this.replicasAvailable())return;this.liveShadow().snapStage0Reset(sessionId)}snapConvBound(sessionId){if(!this.replicasAvailable())return false;return this.liveShadow().snapConvBound(sessionId)}snapMsgIdLiveIds(sessionId){if(!this.replicasAvailable())return[];return this.liveShadow().snapMsgIdLiveIds(sessionId)}snapPinLiveIds(sessionId){if(!this.replicasAvailable())return[];return this.liveShadow().snapPinLiveIds(sessionId)}egressOpLogStore(){return this.replicasAvailable()?this.liveShadow().egressOpLogSync():null}snapR3Latched(sessionId){if(!this.replicasAvailable())return false;return this.liveShadow().snapR3Latched(sessionId)}snapR3Latch(sessionId){if(!this.replicasAvailable())return;this.liveShadow().snapR3Latch(sessionId)}snapR3LatchClear(sessRaw){if(!this.replicasAvailable())return null;return this.liveShadow().snapR3LatchClear(sessRaw)}snapR3LatchedList(){if(!this.replicasAvailable())return[];return this.liveShadow().snapR3LatchedList()}snapSidOfRaw(sessRaw){if(!this.replicasAvailable())return null;return this.liveShadow().snapSidOfRaw(sessRaw)}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}}unifiedMessageContentByIds(sessionId,msgIds){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.messageContentByMsgIds(sessionId,msgIds)}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(e){log("warn",`[persist] unifiedWebSummaries: ${String(e)} \u2014 falling back to the disk-index walk`);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)}setKvAsync(namespace,key2,value){return this.liveShadow().setKvAsync(namespace,key2,value)}getKvAsync(namespace,key2){return this.liveShadow().getKvAsync(namespace,key2)}listKvAsync(namespace,keyPrefix){return this.liveShadow().listKvAsync(namespace,keyPrefix)}deleteKvAsync(namespace,key2){return this.liveShadow().deleteKvAsync(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;if(session.metadata["egressAuthority"]===true)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 record3=this.buildRecordForSave(session);const activeBlockIds2=session.state.blocks.filter(b2=>b2.active!==false).map(b2=>b2.blockId).sort();await this.shadow.insertCheckpointAsync({cpId:`cp-${randomUUID5()}`,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(record3)});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();let record3;if(opts.resident){record3=this.buildRecordForSave(opts.resident)}else{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)`);record3=viewToRecord(view)}if(record3.metadata?.["egressAuthority"]===true){throw new Error(`[storage] createReplica: session ${sessionId} is egress-on \u2014 use the point-fork path instead`)}const ccr=this.contentStoreById(sessionId,record3.meta);if(ccr)record3.forkContentStore=ccr;const cpId=`cp-${randomUUID5()}`;const activeBlockIds2=record3.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(record3)});const row=await shadow.getCheckpointAsync(cpId);if(!row)throw new Error(`[storage] checkpoint ${cpId} missing right after insert (index inconsistency)`);return row}async forkEgressSnapshot(sessionId,childId){await this.ready();const parent=peekSession(sessionId)??await this.loadAsync(sessionId);if(!parent)throw new Error(`[storage] forkEgressSnapshot: session ${sessionId} does not exist`);if(parent.metadata["egressAuthority"]!==true)throw new Error(`[storage] forkEgressSnapshot: session ${sessionId} is not an egress-on session`);const cid=childId??`fork-${randomUUID5()}`;if(peekSession(cid)!==void 0||await this.loadAsync(cid))throw new Error(`[storage] forkEgressSnapshot: child ${cid} already exists`);const child2={...parent,id:cid,meta:structuredClone(parent.meta),stats:structuredClone(parent.stats),metadata:(()=>{const{egressFlowUnreadable:_dropped,...rest}=parent.metadata;void _dropped;return{...rest,derivedFromSessionId:sessionId}})(),state:structuredClone(parent.state),blockContents:new Map([...(parent.blockContents??new Map).entries()].map(([k2,v2])=>[k2,structuredClone(v2)])),lastMessages:parent.lastMessages?structuredClone(parent.lastMessages):void 0,pluginSnapshot:parent.pluginSnapshot?structuredClone(parent.pluginSnapshot):void 0,decompositionLog:parent.decompositionLog?structuredClone(parent.decompositionLog):void 0,transient:void 0,lockChain:void 0,persisted:false,inFlight:0,pendingRetrievals:[]};await this.persistForkSession(sessionId,child2);const opSeq=this.egressOpLogStore()?.egressStateMaxSeq(cid)??0;return{childId:cid,opSeq}}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 record3=JSON.parse(stateJson);const newId=opts.sessionId??`restore-${randomUUID5().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`)}record3.id=newId;record3.savedAt=Date.now();record3.meta={...record3.meta,restoredFrom:cp2.session_id,restoredCheckpoint:cp2.cp_id};await this.withPreoomSnapshot(newId,record3.meta,()=>this.store.writeNow(newId,()=>record3));this.noteMetaFp(newId,record3.metadata??{});shadow.record(record3);this.ownCommit.set(newId,{requests:record3.stats?.requests??record3.requests??0,nextBlockId:record3.state?.nextBlockId??0,builtAtMs:Date.now()});if(record3.forkContentStore){this.writeContentStoreSidecar(newId,record3.meta,record3.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 readFile6(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 incRequests=incoming.stats?.requests??incoming.requests??0;const incBlocks=incoming.state?.nextBlockId??0;if(incRequests<own.requests||incBlocks<own.nextBlockId)return false;const shadow=this.shadow;if(shadow&&!shadow.stats.disabled){let row=null;try{row=shadow.sessionCounters(incoming.id)}catch{return false}if(!row||row.requests!==own.requests||row.nextBlockId!==own.nextBlockId)return false}if(this.writerOffActive()||this.envelopeFrozen(incoming.id)){return this.envelopeFileKey(incoming.id,incoming.meta)===own.writerOffFile}const stat6=this.statEnvelope(incoming.id,incoming.meta);if(!stat6)return false;if(!own.written)return false;if(stat6.size!==own.written.size)return false;if(stat6.mtimeMs>own.written.mtimeMs+OWN_WRITE_STAMP_EPSILON_MS)return false;return true}envelopeFileKey(id,meta){const stat6=this.statEnvelope(id,meta);return stat6?`${stat6.size}:${stat6.mtimeMs}`:"absent"}statEnvelope(id,meta){const candidates=[];const known=this.sourceFiles.get(id);if(known)candidates.push(known);candidates.push(path28.join(this.sessionsDir,relPathFor(id,meta?.protocol,meta?.upstreamOrigin)),path28.join(this.sessionsDir,relPathFor(id)),path28.join(this.sessionsDir,flatFileNameFor(id)));for(const file of candidates){try{const st2=statSync9(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 record3=this.buildRecordForSave(session,stamp2);const disk=this.staleDiskPayload(record3);if(disk===null){const payload=session.decompositionLog;if(payload!==void 0)session.decompositionLog=void 0;const tail=session.lastMessagesFolded!==true?session.lastMessages:void 0;if(!this.egressProjectionFrozen(session)){this.shadow?.record(payload!==void 0?{...record3,decompositionLog:payload}:record3,tail&&tail.length>0?{lastMessages:tail,lastMessagesFolded:session.lastMessagesFolded}:void 0,session.contentStore??void 0)}this.noteOwnCommit(session.id,record3);return record3}const now=Date.now();const last=this.staleWarnAt.get(record3.id)??0;if(now-last>=STALE_WARN_THROTTLE_MS){this.staleWarnAt.set(record3.id,now);this.log("warn",`[persist] rejected stale snapshot for session ${record3.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);if(!this.egressProjectionFrozen(session))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,writerOffFile:this.writerOffActive()||this.envelopeFrozen(id)?this.envelopeFileKey(id,committed.meta??prev?.meta):void 0,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 stat6=this.statEnvelope(id,token.meta);if(!stat6)return;token.written=stat6}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)`)}egressProjectionFrozen(session){return session.metadata?.["egressAuthority"]===true&&egressPlaneGateOn()}ingestRowsNow(session){if(!this.shadow)return;if(this.egressProjectionFrozen(session))return;try{const stamp2=this.liveStorageStamp;const record3=this.buildRecordForSave(session,stamp2);const disk=this.staleDiskPayload(record3);if(disk!==null){const now=Date.now();const last=this.staleWarnAt.get(record3.id)??0;if(now-last>=STALE_WARN_THROTTLE_MS){this.staleWarnAt.set(record3.id,now);this.log("warn",`[persist] rejected stale snapshot for session ${record3.id} (durability-before-render): 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);this.armDurabilitySkip(session,disk);return}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?{...record3,decompositionLog:payload}:record3,tail&&tail.length>0?{lastMessages:tail,lastMessagesFolded:session.lastMessagesFolded}:void 0,session.contentStore??void 0);this.noteOwnCommit(session.id,record3);this.armDurabilitySkip(session,record3)}catch(err2){this.log("warn",`[persist] ingestRowsNow failed for ${session.id}: ${String(err2)} \u2014 the debounced save retries the full path`)}}armDurabilitySkip(session,record3){this.durabilityArms.set(session.id,{epoch:session.revisionEpoch??0,messagesRef:session.lastMessages,metadata:record3.metadata??{},metadataFp:JSON.stringify(session.metadata)})}scheduleSave(session){this.consumePendingLedgerAlign(session);if(!this.saveContentStore(session)){this.durabilityArms.delete(session.id);return}const frozen=this.envelopeFrozen(session.id);if(this.writerOffActive()||frozen||this.egressProjectionFrozen(session)){if(frozen)this.noteFrozenSkip(session.id,"scheduled");if(this.writerOffPending.has(session.id))return;const run=()=>{this.writerOffPending.delete(session.id);const proofRevision=session.revisionEpoch;const armed4=this.durabilityArms.get(session.id);const durabilitySkip=armed4!==void 0&&(session.revisionEpoch??0)===armed4.epoch+1&&session.lastMessages===armed4.messagesRef&&session.decompositionLog===void 0&&!session.contentStoreDirty&&session.pendingLedgerAlign===void 0&&JSON.stringify(session.metadata)===armed4.metadataFp;this.durabilityArms.delete(session.id);let settledOk=false;try{const recMeta=durabilitySkip&&armed4?armed4.metadata:this.guardedBuild(session)().metadata??{};this.maybeCutForkBase(session);this.noteMetaFp(session.id,recMeta);if(this.egressProjectionFrozen(session)){this.lastSaveLanded.set(session.id,true)}else{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}this.durabilityArms.delete(session.id);if(!this.enabled)return;this.tryRecoverSidecar();const id=session.id;const guarded=this.guardedBuild(session);const armed3={build:()=>{const r=guarded();armed3.rec=r;return r},rec:null};this.saveBuilders.set(id,armed3);const existing=this.saveTimers.get(id);if(existing)return;const timer2=setTimeout(()=>{this.saveTimers.delete(id);const armed4=this.saveBuilders.get(id);this.saveBuilders.delete(id);if(!armed4)return;const proofRevision=peekSession(id)?.revisionEpoch;this.saveWritesInFlight.add(id);void this.withPreoomSnapshot(id,peekSession(id)?.meta,()=>this.store.writeNow(id,armed4.build)).then(()=>{this.stampOwnWrite(id);if(armed4.rec)this.noteMetaFp(id,armed4.rec.metadata??{});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))timer2.unref?.();this.saveTimers.set(id,timer2)}async afterNextFlush(sessionId){if(!this.saveTimers.has(sessionId)&&!this.writerOffPending.has(sessionId)&&!this.saveWritesInFlight.has(sessionId)){return true}return await new Promise(resolve3=>{const ws2=this.flushWaiters.get(sessionId)??[];ws2.push(ok=>{resolve3(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 cap2=sessionResidentHardMaxBytes();if(cap2>0&&sessionWeight(session)>cap2){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 ${cap2} 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){this.consumePendingLedgerAlign(session);if(!this.saveContentStore(session)){this.durabilityArms.delete(session.id);throw new Error(`Originals were not saved for ${session.id}`)}const frozen=this.envelopeFrozen(session.id);if(this.writerOffActive()||frozen||this.egressProjectionFrozen(session)){if(frozen)this.noteFrozenSkip(session.id,"writeNow");this.writerOffPending.delete(session.id);const proofRevision2=session.revisionEpoch;const rec2=this.guardedBuild(session)();this.maybeCutForkBase(session);this.noteMetaFp(session.id,rec2.metadata??{});if(!this.egressProjectionFrozen(session)){this.noteDurable(session.id,proofRevision2);this.lastSaveLanded.set(session.id,true);this.foldResidentTail(session);this.dropResidentBlockContents(session);this.dropResidentMetadata(session);this.dropResidentContentStore(session)}else{this.lastSaveLanded.set(session.id,true)}return}this.durabilityArms.delete(session.id);const proofRevision=session.revisionEpoch;this.saveWritesInFlight.add(session.id);const rec={v:null};try{await this.withPreoomSnapshot(session.id,session.meta,()=>this.store.writeNow(session.id,()=>{const r=this.guardedBuild(session)();rec.v=r;return r}))}catch(err2){this.saveWritesInFlight.delete(session.id);throw err2}this.stampOwnWrite(session.id);if(rec.v)this.noteMetaFp(session.id,rec.v.metadata??{});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)}async flushSessionNow(session){const epoch=session.revisionEpoch;try{await this.writeNow(session)}catch(err2){this.log("warn",`[persist] ${session.id}: in-request snapshot flush failed (round stays on the legacy egress path): ${String(err2).slice(0,200)}`);return{ok:false,epoch}}if((session.revisionEpoch??0)!==(epoch??0)){this.scheduleSave(session)}else{const t=this.saveTimers.get(session.id);if(t){clearTimeout(t);this.saveTimers.delete(session.id)}this.saveBuilders.delete(session.id);this.writerOffPending.delete(session.id);this.runIdleSpillIfIdle(session.id)}return{ok:true,epoch}}static async flushOrSkip(session){const st2=getStore();if(!st2||typeof st2.flushSessionNow!=="function")return{ok:false,epoch:session.revisionEpoch};return st2.flushSessionNow(session)}foldResidentTail(session){if(session.inFlight>0)return;const raw=session.lastMessages;if(!raw||raw.length===0)return;session.lastMessages=boundedFoldedSnapshot(session);session.lastMessagesFolded=true}persistedMetadataView(session){return{...session.metadata,biliVersion:VERSION,storageMode:this.liveStorageStamp}}noteMetaFp(id,metadata){if(this.writerOffActive())return;this.committedMetaFp.set(id,this.metaFingerprint(metadata))}metaFingerprint(view){try{return createHash14("sha256").update(canonicalJson2(JSON.parse(JSON.stringify(view))),"utf8").digest("hex")}catch{return"\0unhashable-"+Math.random().toString(36).slice(2)}}dropResidentMetadata(session){if(this.writerOffActive()||session.inFlight>0||!this.enabled)return;if(isDroppedMetadata(session.metadata))return;if(Object.keys(session.metadata).length===0)return;const proven=this.committedMetaFp.get(session.id);if(proven===void 0||proven!==this.metaFingerprint(this.persistedMetadataView(session)))return;const meta=session.meta??void 0;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(this.writerOffActive()||session.inFlight>0||!this.enabled)return;const existing=session.blockContents;if(existing instanceof LazyBlockContents){existing.drop();return}if(existing.size===0)return;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(this.writerOffActive()||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(existsSync9(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(),fileStorageJsonWriter())??void 0}catch(err2){this.log("error",hadIntegrityQuickCheckFailure()?`[storage] sidecar reopen attempt REFUSED \u2014 the index is proven corrupt (${String(err2)}); no further in-process retries (2026-11-21 refusal policy; operator hand-fix or BILI_STORAGE_ALLOW_LEGACY_DEGRADE=1)`:`[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){this.consumePendingLedgerAlign(session);if(!this.saveContentStore(session))return false;this.tryRecoverSidecar();const frozen=this.envelopeFrozen(session.id);if(this.writerOffActive()||frozen||this.egressProjectionFrozen(session)){if(frozen)this.noteFrozenSkip(session.id,"flushSync");this.writerOffPending.delete(session.id);const proofRevision2=session.revisionEpoch;let rec=null;try{rec=this.guardedBuild(session)()}catch(err2){this.log("error",`[persist] writerOff flushSync build failed for ${session.id}: ${String(err2)}`);return false}this.maybeCutForkBase(session);if(rec)this.noteMetaFp(session.id,rec.metadata??{});if(!this.egressProjectionFrozen(session)){this.noteDurable(session.id,proofRevision2);this.lastSaveLanded.set(session.id,true);this.foldResidentTail(session);this.dropResidentBlockContents(session);this.dropResidentMetadata(session);this.dropResidentContentStore(session)}else{this.lastSaveLanded.set(session.id,true)}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 syncRec={v:null};const ok=this.withPreoomSnapshot(session.id,session.meta,()=>this.store.flushSync(session.id,()=>{const r=this.guardedBuild(session)();syncRec.v=r;return r}));if(ok){this.stampOwnWrite(session.id);if(syncRec.v)this.noteMetaFp(session.id,syncRec.v.metadata??{});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 record3=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,record3);if(!this.writerOffActive()){if(!this.withPreoomSnapshot(session.id,session.meta,()=>this.store.flushSync(session.id,()=>record3)))throw new Error("fork envelope persistence failed; retry the same request");this.stampOwnWrite(session.id)}this.noteMetaFp(session.id,record3.metadata??{});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 record3=viewToRecord(view);const receipt=record3.metadata?.publicForkReceipt;if(typeof receipt?.requestHash!=="string"||receipt.response?.ok!==true||receipt.response.sessionId!==id||receipt.response.childConversationId!==id)return;const session=buildSession(record3);if(!this.saveContentStore(session))throw new Error("fork content recovery failed");this.noteOwnCommit(id,record3);if(!this.writerOffActive()){if(!this.withPreoomSnapshot(id,session.meta,()=>this.store.flushSync(id,()=>record3)))throw new Error("fork envelope recovery failed");this.stampOwnWrite(id)}this.noteMetaFp(id,record3.metadata??{});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 timer2 of this.saveTimers.values())clearTimeout(timer2);this.saveTimers.clear();const armed3=new Map;for(const id of ids){const slot=this.saveBuilders.get(id);if(slot)armed3.set(id,slot);this.saveBuilders.delete(id)}await Promise.all([...armed3.entries()].map(([id,slot])=>this.withPreoomSnapshot(id,peekSession(id)?.meta,()=>this.store.writeNow(id,slot.build)).then(()=>{this.stampOwnWrite(id);if(slot.rec)this.noteMetaFp(id,slot.rec.metadata??{})}).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 timer2 of this.saveTimers.values())clearTimeout(timer2);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 storedProvenances=Array.isArray(ring.provenances)?ring.provenances:void 0;const kept=ring.values.map((x,i)=>({value:x,provenance:storedProvenances?.[i]})).filter(e=>typeof e.value==="number"&&Number.isFinite(e.value)&&e.value>=CALIBRATION_SAMPLE_MIN&&e.value<=CALIBRATION_SAMPLE_MAX);const recent=kept.slice(-CALIBRATION_SAMPLE_WINDOW);if(recent.length===0)return void 0;const provenances=recent.map(e=>e.provenance===CALIBRATION_PROVENANCE_TEXT_ONLY?CALIBRATION_PROVENANCE_TEXT_ONLY:void 0);const model=typeof ring.model==="string"&&ring.model.trim().length>0?ring.model:void 0;return{origin:ring.origin,...model===void 0?{}:{model},values:recent.map(e=>e.value),...provenances.some(p2=>p2!==void 0)?{provenances}:{}}}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(record3){const s3=buildSession(record3);return toLegacyLike(s3)}function buildSession(parsed){const blockContents=restoreBlockContents(Object.entries(parsed.blockContents??{}));const meta=parsed.meta??{};const stats2=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:stats2.requests??parsed.requests??0,tokensSaved:stats2.tokensSaved??parsed.tokensSaved??0,inputTokens:stats2.inputTokens??parsed.inputTokens??0,cachedTokens:stats2.cachedTokens??parsed.cachedTokens??0,outputTokens:stats2.outputTokens??parsed.outputTokens??0,cacheSamples:stats2.cacheSamples??parsed.cacheSamples??0,lastInputTokens:Math.max(0,stats2.lastInputTokens??parsed.lastInputTokens??0),lastInputTokensSource:stats2.lastInputTokensSource==="usage"||stats2.lastInputTokensSource==="estimate"||stats2.lastInputTokensSource==="overflow-arm"?stats2.lastInputTokensSource:void 0,emergencyShrinkAt:typeof stats2.emergencyShrinkAt==="number"&&Number.isFinite(stats2.emergencyShrinkAt)&&stats2.emergencyShrinkAt>=0?stats2.emergencyShrinkAt:void 0,emergencyShrinkEstimate:typeof stats2.emergencyShrinkEstimate==="number"&&Number.isFinite(stats2.emergencyShrinkEstimate)&&stats2.emergencyShrinkEstimate>0?stats2.emergencyShrinkEstimate:void 0,overflowArmTokens:typeof stats2.overflowArmTokens==="number"&&Number.isFinite(stats2.overflowArmTokens)&&stats2.overflowArmTokens>0?stats2.overflowArmTokens:void 0,preflightRuns:typeof stats2.preflightRuns==="number"&&Number.isFinite(stats2.preflightRuns)&&stats2.preflightRuns>=0?stats2.preflightRuns:void 0,overflowArmCompletionReserve:typeof stats2.overflowArmCompletionReserve==="number"&&Number.isFinite(stats2.overflowArmCompletionReserve)&&stats2.overflowArmCompletionReserve>0?stats2.overflowArmCompletionReserve:void 0,overflowArmMismatchWarned:stats2.overflowArmMismatchWarned===true?true:void 0,provenCompletionWall:typeof stats2.provenCompletionWall==="number"&&Number.isFinite(stats2.provenCompletionWall)&&stats2.provenCompletionWall>0?stats2.provenCompletionWall:void 0,provenCompletionWallOrigin:typeof stats2.provenCompletionWallOrigin==="string"&&stats2.provenCompletionWallOrigin.length>0?stats2.provenCompletionWallOrigin:void 0,provenCompletionWallModel:typeof stats2.provenCompletionWallModel==="string"&&stats2.provenCompletionWallModel.length>0?stats2.provenCompletionWallModel:void 0,compressCreditTokens:0,contextTokens:Math.max(0,stats2.contextTokens??parsed.contextTokens??0),contextTokensSource:stats2.contextTokensSource==="usage"||stats2.contextTokensSource==="estimate"?stats2.contextTokensSource:void 0,localInputEstimate:typeof stats2.localInputEstimate==="number"&&Number.isFinite(stats2.localInputEstimate)&&stats2.localInputEstimate>0?stats2.localInputEstimate:void 0,lastUsageGradeTokens:typeof stats2.lastUsageGradeTokens==="number"&&Number.isFinite(stats2.lastUsageGradeTokens)&&stats2.lastUsageGradeTokens>=0?stats2.lastUsageGradeTokens:void 0,lastInputTokensOrigin:typeof stats2.lastInputTokensOrigin==="string"&&stats2.lastInputTokensOrigin.trim().length>0?stats2.lastInputTokensOrigin:void 0,calibratedEstimate:restoreCalibratedEstimate(stats2.calibratedEstimate),calibratedEstimateOrigin:typeof stats2.calibratedEstimateOrigin==="string"&&stats2.calibratedEstimateOrigin.trim().length>0?stats2.calibratedEstimateOrigin:void 0,calibratedEstimateModel:typeof stats2.calibratedEstimateModel==="string"&&stats2.calibratedEstimateModel.trim().length>0?stats2.calibratedEstimateModel:void 0,calibratedEstimateProvenance:stats2.calibratedEstimateProvenance===CALIBRATION_PROVENANCE_TEXT_ONLY?CALIBRATION_PROVENANCE_TEXT_ONLY:void 0,calibrationRing:restoreCalibrationRing(stats2.calibrationRing),retrieveCalls:stats2.retrieveCalls??0,retrieveHits:stats2.retrieveHits??0,retrieveMisses:stats2.retrieveMisses??0,retrieveDropped:stats2.retrieveDropped??0,retrieveDelivered:stats2.retrieveDelivered??0,storedBytes:stats2.storedBytes??0,storeBytesSaved:stats2.storeBytesSaved??0,rangeRestores:stats2.rangeRestores??0,wholeBlockRestores:stats2.wholeBlockRestores??0,wholeBlockRestoresPreciseAvailable:stats2.wholeBlockRestoresPreciseAvailable??0,costUsd:validCostUsd(stats2.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 stats2=parsed.stats??{};const last=stats2.lastInputTokens??parsed.lastInputTokens;const ctx=stats2.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 record3={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){record3.messages=view.lastMessages;record3.messagesFolded=view.lastMessagesFolded===true}if(view.pluginSnapshot!==void 0)record3.pluginSnapshot=view.pluginSnapshot;if(view.contentStore!==void 0)record3.forkContentStore=view.contentStore;return record3}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 effectiveJsonWriterOff(process.env,fileStorageJsonWriter(),fileStorageUnified())&&!encrypted?"storage: sqlite (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(name2){return name2.startsWith(".tmp-")||/\.tmp-enc-\d+-\d+$/.test(name2)}function walkJsonFilesSync(dir,out=[]){let entries2;try{entries2=readdirSync4(dir,{withFileTypes:true})}catch{return out}for(const e of entries2){const full=path28.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=path28.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}function unifiedKvActive(){try{if(_store===null)return false;return _store.liveStorageStamp!=="legacy"}catch{return false}}function kvStore(){try{const s3=_store;if(!s3||s3.liveStorageStamp==="legacy")return null;if(typeof s3.getKvAsync!=="function"||typeof s3.setKvAsync!=="function"||typeof s3.listKvAsync!=="function")return null;return s3}catch{return null}}init_version();init_knobs();init_config();init_dist();init_config();init_paths();init_logger();init_external_summary_settings();import*as path29 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
|
|
1234
|
+
`)}let offloadPending=session.metadata[METADATA_OFFLOAD_PENDING]??{};if(plan.unmatched.length>0&&opts.storedRowLookup!==void 0){const needed=[];for(const id of plan.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 path66=classifyCarrier(parsed);if(path66!==void 0){expected[id]=path66;continue}}}if(hasImageMarker)offloadPending[id]=1}}}}const pendingIds=Object.keys(offloadPending);if(pendingIds.length>0){const claimedTargets=new Set;for(const targets of plan.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=plan.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=plan.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=plan.newOrder.slice(-MAX_ORDER);if(plan.nextCanon!==void 0){session.metadata[METADATA_POSITIONS]={ids:nextOrder,canon:plan.nextCanon.slice(-MAX_ORDER)}}const absentSet=new Set(plan.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(plan.newOrder);const witnessSet=new Set(witness2);const commonWitness=witness2.filter(id=>inboundSet.has(id));const commonInbound=plan.newOrder.filter(id=>witnessSet.has(id));wireContinuity=commonWitness.length>0&&witness2.slice(witness2.length-commonWitness.length).every(id=>inboundSet.has(id))&&plan.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))&&plan.newOrder.slice(0,commonPrefix.length).every(id=>witnessSet.has(id))}const markerChurnExplained=(opts.markerStripped??0)>0;const realUnmatched=plan.unmatched.filter(id=>expected[id]===void 0);const accountedHere=plan.unmatched.length-realUnmatched.length;const expectedNote=accountedHere>0?`; ${accountedHere} more covered id(s) accounted as expected host behavior (#5142)`:"";const reasoningOnlyDrop=plan.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=plan.byShape>0||classCarryingResidual.length>0&&plan.nearDupResidual.length>=.6*classCarryingResidual.length;const truncationExplained=classCarryingResidual.length>0&&plan.nearDupResidual.length===0&&classCarryingResidual.every(id=>absentSet.has(id))&&wireContinuity;const tailTruncationExplained=classCarryingResidual.length>0&&plan.nearDupResidual.length===0&&classCarryingResidual.every(id=>absentSet.has(id))&&tailTruncated;let coveredHard=0;let presentHard=0;for(const id of activeCovered){if(isResponsesTurnSeparatorId(id)||expected[id]!==void 0||anchors[id]?.c==="reasoning")continue;coveredHard++;if(byId2.has(id))presentHard++}const hardDirectMajority=presentHard>=MIN_RESYNC_RUN&&2*presentHard>coveredHard;if(hardDirectMajority&&epochConfirmPending(session))resetFoldDriftState(session);const totalDrift=plan.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(plan.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)&&!plan.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];const storedPositions=session.metadata[METADATA_POSITIONS];const positionIds=storedPositions?.ids;const positionCanon=storedPositions?.canon;for(let i=nextOrder.length-1;i>=0;i--){if(deadIds.has(nextOrder[i])){nextOrder.splice(i,1);if(positionIds===nextOrder&&Array.isArray(positionCanon))positionCanon.splice(i,1)}}if(Array.isArray(positionIds)&&positionIds!==nextOrder){for(let i=positionIds.length-1;i>=0;i--){if(deadIds.has(positionIds[i])){positionIds.splice(i,1);if(Array.isArray(positionCanon))positionCanon.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(plan.claims.size>0&&mode==="repair"){rewriteBlocks(blocks,plan.claims);const prior=new Set(session.state?.lastPassIds??[]);for(const targets of plan.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,(plan.churnTokens??0)-(plan.claimedChurnTokens??0)):plan.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 ${plan.byShape}, ${plan.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(!hardDirectMajority&&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(session.stats)delete session.stats.preflightRuns;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&&plan.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(plan.claims.size>0&&mode==="repair"){opts.log(realUnmatched.length>0?"warn":"info",`${tag}[fold-reconcile] resent history drifted: ${plan.claims.size+realUnmatched.length} covered id(s) missing${expectedNote} \u2014 reanchored ${plan.claims.size} (${plan.byPos} positional${plan.resyncs>0?`, ${plan.resyncs} order break(s) resynced`:""}, ${plan.byTool} by toolCallId${plan.byTwin>0?`, ${plan.byTwin} by toolCallId twin`:""}${plan.bySim>0?`, ${plan.bySim} by simhash corroboration`:""}${plan.byOrder>0?`, ${plan.byOrder} by order bracket`:""}, ${plan.byNorm} by normalized identity${plan.byTurn>0?`, ${plan.byTurn} by assistant-turn key`:""}${plan.byImage>0?`, ${plan.byImage} by image-capability variant`:""}${plan.byShape>0?`, ${plan.byShape} by shape census`:""}) onto churned bytes, ${realUnmatched.length} unmatched re-enter the wire unfolded${plan.idRewriteSuspects>0?`; ${plan.idRewriteSuspects} suspected host-rewritten tool-call ids (identical content under a different toolCallId \u2014 #2396)`:""} (#1921)${driftTok}`)}else if(plan.claims.size>0){opts.log("warn",`${tag}[fold-reconcile] resent history drifted: ${plan.claims.size+realUnmatched.length} covered id(s) missing${expectedNote}, ${plan.claims.size} matchable by anchor (${plan.byPos} positional${plan.resyncs>0?`, ${plan.resyncs} resynced`:""}, ${plan.byTool} toolCallId${plan.byTwin>0?`, ${plan.byTwin} twin`:""}${plan.bySim>0?`, ${plan.bySim} simhash`:""}${plan.byOrder>0?`, ${plan.byOrder} order-bracket`:""}, ${plan.byNorm} normalized${plan.byTurn>0?`, ${plan.byTurn} turn key`:""}${plan.byImage>0?`, ${plan.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(hardDirectMajority&&nonReasoningUnmatched>=FOLD_DRIFT_ESCALATE_MIN_UNMATCHED&&!shapeExplained&&!truncationExplained&&!tailTruncationExplained){if(session.metadata[METADATA_MAJORITY_LOSS_NOTED]!==true){session.metadata[METADATA_MAJORITY_LOSS_NOTED]=true;opts.log("info",`${tag}[fold-reconcile] ${realUnmatched.length} covered id(s) missing but ${presentHard}/${coveredHard} hard-covered id(s) still ride verbatim on the wire \u2014 partial interior loss, fold substrate healthy, no epoch confirmation (#5715)`)}}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)${plan.idRewriteSuspects>0?`; ${plan.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:plan.claims.size>0?mode==="repair"?"reanchored":"unmatched":"unmatched",missing:plan.claims.size+realUnmatched.length,claims:plan.claims.size,byPos:plan.byPos,byTool:plan.byTool,byTwin:plan.byTwin,bySim:plan.bySim,byOrder:plan.byOrder,byNorm:plan.byNorm,byTurn:plan.byTurn,byImage:plan.byImage,byShape:plan.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 prev=session.metadata[METADATA_SYSTEM_FP];const fp2=system===void 0||system===null?"-":prev!==void 0&&prev.fp!=="-"&&prev.size===text2.length&&prev.head!==void 0&&prev.head===text2.slice(0,256)?prev.fp:createHash12("sha256").update(text2).digest("hex").slice(0,16);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,head:text2.slice(0,256)}}function noteCanonicalSystemFingerprint(session,canonical2){if(!session.metadata)return;const text2=canonical2===void 0||canonical2===null?"":JSON.stringify(canonical2)??"";const prev=session.metadata[METADATA_CANONICAL_SYS_FP];const fp2=canonical2===void 0||canonical2===null?"-":prev!==void 0&&prev.fp!=="-"&&prev.size===text2.length&&prev.head!==void 0&&prev.head===text2.slice(0,256)?prev.fp:createHash12("sha256").update(text2).digest("hex").slice(0,16);session.metadata[METADATA_CANONICAL_SYS_FP]={fp:fp2,size:text2.length,head:text2.slice(0,256)}}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();var FULL_DETAIL_LINES=512;var BOOT_ID=randomUUID4();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 RECOVERY_BURST_MS=10*6e4;var RECOVERY_STALE_MS=30*6e4;var RECOVERY_CAP=500;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:randomUUID4(),round:0},async()=>{try{return await fn()}finally{const capture2=captures.getStore();if(capture2){delete capture2.sentBody;delete capture2.inBody;delete capture2.imageFacts;delete capture2.calibration}}})}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:randomUUID4()}}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())}var CREDENTIAL_HEADER_NAMES=["authorization","x-api-key","api-key","x-goog-api-key"];function credentialFingerprint(headers){if(!headers)return void 0;const values=new Set;const fields=new Set;for(const[name2,value]of Object.entries(headers)){const n=name2.toLowerCase();if(CREDENTIAL_HEADER_NAMES.includes(n)){const v2=value.trim().replace(/^Bearer\s+/i,"").trim();if(v2!==""){const m2=/^SDK-HMAC-SHA256\s+Access=([^\s,]+)/i.exec(v2);const credential=m2!==null?`sdk-hmac:${m2[1]}`:v2;values.add(credential);fields.add(JSON.stringify([n,credential]))}}}if(values.size===0)return void 0;const cred=values.size===1?values.values().next().value:`credential-set:${JSON.stringify([...fields].sort())}`;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 transient2=pendingCapture(session);const prior=transient2.sentBody;const sameBytes=prior!==void 0&&prior.bytes===buf.byteLength&&prior.full!==null&&prior.full.equals(buf);const digest=sameBytes?prior.digest:createHash13("sha256").update(buf).digest("hex");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),ownedSeparatorCores:samePayload?prior.ownedSeparatorCores: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 noteCalibrationPair(session,pair){const capture2=captures.getStore();if(capture2?.session===session){capture2.calibration=pair;return}}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,cap2,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=cap2>0?Math.min(entry.cost,cap2):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}i++;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}i++}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 cacheLedgerIsEmpty(session){const led=(session.metadata??{})[LEDGER_KEY];return!led||led.lines.length===0&&led.folds.length===0}var usageSink=null;var usageStatsSink=null;var usageSinkWarned=false;function setEgressUsageSink(fn){usageSink=fn}function setEgressUsageStatsSink(fn){usageStatsSink=fn}function emitUsageEvents(session,events){if(!usageSink||events.length===0)return;try{usageSink(session.id,events)}catch(err2){if(!usageSinkWarned){usageSinkWarned=true;log("warn",`[${session.id}] [cache-ledger] egress usage sink failed (${err2 instanceof Error?err2.message:String(err2)}) \u2014 the in-memory ledger keeps the truth; the stream lags until the sink recovers`)}}}function usageStatsJson(led){if(led.lines.length===0&&led.folds.length===0)return null;const last=led.lines[led.lines.length-1];const obj={requests:led.agg.requests,input:Math.round(led.agg.input),cached:Math.round(led.agg.cached),output:Math.round(led.agg.output),nc:Math.round(led.agg.nc),cr:Math.round(led.agg.cr),tr:Math.round(led.agg.tr),folds:led.folds.length};if(last!==void 0){obj.lastAt=last.at;if(last.hitPct!==null)obj.hitPct=last.hitPct;if(typeof last.input==="number"&&last.input>0)obj.finalContext=Math.round(last.input)}return JSON.stringify(obj)}function pushFold(led,f2,closeFrom){for(let i=closeFrom;i<led.folds.length;i++){const open=led.folds[i];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});recordFoldRecovery(led,f2.at,f2.S,led.foldSeqCounter)}function recordNudgeInject(session,nudge){if(!nudge)return;const led=getCacheLedger(session);const evs=led.recovery??(led.recovery=[]);if(evs.length===0){for(const f2 of led.folds){evs.push({kind:"f",at:f2.at,S:f2.S,seq:f2.seq,p:0,mode:"a"})}}evs.push({kind:"n",at:Date.now(),p:nudge.breakdown?.["pendingT1"]??0,tier:typeof nudge.tier==="number"?nudge.tier:null});if(evs.length>RECOVERY_CAP)evs.splice(0,evs.length-RECOVERY_CAP);markDirty(session)}function recordFoldRecovery(led,at2,S2,seq){if(led.recovery===void 0)return;const evs=led.recovery;let lastF;let lastN;for(const ev of evs){if(ev.kind==="f")lastF=ev;else if(ev.at<=at2)lastN=ev}const gapArmed=lastN!==void 0&&lastN.at>(lastF?.at??0);const chainArmed=lastF!==void 0&&at2-lastF.at<=RECOVERY_BURST_MS;const nudgeFresh=lastN!==void 0&&at2-lastN.at<=RECOVERY_STALE_MS;const mode=lastN&&nudgeFresh&&(gapArmed||chainArmed)?"n":"a";const p2=lastN&&nudgeFresh?lastN.p:0;evs.push({kind:"f",at:at2,S:S2,seq,p:p2,mode,pct:mode==="n"&&p2>0?Math.round(S2/p2*1e3)/10:void 0});if(evs.length>RECOVERY_CAP)evs.splice(0,evs.length-RECOVERY_CAP)}function recordCacheFoldsFromBlocks(session,blocks,geo){if(blocks.length===0)return[];const led=getCacheLedger(session);let closeFrom=0;const emitted=[];for(const b2 of blocks){const id=refNum3(b2.blockId);if(id<=led.lastBlockId)continue;const foldRow={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};pushFold(led,foldRow,closeFrom);emitted.push({type:"F",at:foldRow.at,payload:foldRow});closeFrom=led.folds.length-1;led.lastBlockId=Math.max(led.lastBlockId,id)}if(emitted.length>0)emitUsageEvents(session,emitted);return emitted}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 capture2=captures.getStore();const capturePair=capture2?.session===session?capture2.calibration:void 0;if(capture2?.session===session)delete capture2.calibration;if(capturePair!==void 0&&capturePair.imageTokens>0)return;const pendingEst=capturePair!==void 0?capturePair.estimate:session.stats.lastLocalTextEstimate;const pendingOrigin=capturePair!==void 0?normalizeUpstreamOrigin(capturePair.origin):normalizeUpstreamOrigin(session.stats.lastLocalTextEstimateOrigin);if(pendingEst!==void 0&&pendingEst>=CALIBRATION_MIN_ESTIMATE&&settleOrigin!==void 0&&pendingOrigin===settleOrigin){const rawSample=billed/pendingEst;const sampleProvenance=capturePair!==void 0?CALIBRATION_PROVENANCE_TEXT_ONLY:void 0;const settleModel=capturePair?.model!==void 0?capturePair.model: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.provenances===void 0)ring.provenances=[];while(ring.provenances.length<ring.values.length-1)ring.provenances.push(void 0);ring.provenances.push(sampleProvenance);if(ring.values.length>CALIBRATION_SAMPLE_WINDOW){ring.values.shift();ring.provenances.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;delete session.stats.calibratedEstimateProvenance}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;const ringProvenance=ring.provenances!==void 0&&ring.provenances.length===ring.values.length&&ring.provenances.every(p2=>p2===CALIBRATION_PROVENANCE_TEXT_ONLY)?CALIBRATION_PROVENANCE_TEXT_ONLY:void 0;if(ringProvenance!==void 0)session.stats.calibratedEstimateProvenance=ringProvenance;else delete session.stats.calibratedEstimateProvenance}}else{delete session.stats.calibratedEstimate;delete session.stats.calibratedEstimateOrigin;delete session.stats.calibratedEstimateModel;delete session.stats.calibratedEstimateProvenance}}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){if(session.transient?.nudgeHeldAfterReject)delete session.transient.nudgeHeldAfterReject;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{const contextTotal=s3.context!==void 0&&s3.context>0?s3.context:s3.total;session.stats.lastInputTokens=Math.max(0,contextTotal-(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;const stampedModel=typeof s3.model==="string"&&s3.model!==""?s3.model:typeof session.metadata?.lastModel==="string"&&session.metadata.lastModel!==""?session.metadata.lastModel:void 0;if(stampedModel!==void 0)session.stats.lastInputTokensModel=stampedModel;if(stampedModel!==void 0){const fallbackWindows=session.metadata.windowFallbackModels??{};const judged=fallbackWindows[stampedModel];if(typeof judged==="number"&&Number.isFinite(judged)&&session.stats.lastInputTokens>judged){const ratchet=session.metadata.windowRatchet??{};const current=Math.max(ratchet[stampedModel]??judged,judged);const trustedCeiling=4*judged;let raised=Math.max(2*session.stats.lastInputTokens,ratchet[stampedModel]??0);if(session.stats.lastInputTokens>trustedCeiling)raised=Math.min(raised,trustedCeiling);if(raised>current){ratchet[stampedModel]=raised;session.metadata.windowRatchet=ratchet;log("info",`[${session.id}] [window-ratchet] model=${stampedModel} billed ${session.stats.lastInputTokens} input beyond the judged window ${judged} \u2014 session window raised to ${raised} (${session.stats.lastInputTokens>trustedCeiling?`clamped to the ${4}\xD7-judged bound ${trustedCeiling} against one anomalous bill`:"2\xD7 the observation"}; monotonic, session-local)`)}}}ingestCalibrationPair(session,contextTotal,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);const usageSample={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};recordCacheSample(session,usageSample);{const usageLine=led.lines[led.lines.length-1];const usageEvents=[];if(usageLine!==void 0&&usageLine.rs===1)usageEvents.push({type:"M",at:usageLine.at});if(usageLine!==void 0){usageEvents.push({type:"S",at:usageLine.at,payload:{s:usageSample,model:typeof session.metadata?.lastModel==="string"&&session.metadata.lastModel!==""?session.metadata.lastModel:void 0}});const stats2=usageStatsJson(led);if(stats2!==null&&usageStatsSink){try{usageStatsSink(session.id,stats2)}catch{}}}emitUsageEvents(session,usageEvents)}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;if(lcp>=shorterFull.length-64)curLine.bs="append";else if(lcp<1024)curLine.bs="head";else{const arrClose=messagesArrayCloseOffset(shorterFull);curLine.bs=arrClose!==null&&lcp>=arrClose?"tail":isMidInsertionAppend(prevSlot.full,curSlot.full,lcp)?"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:hits.reduce((min,hit)=>Math.min(min,hit),Infinity)})}}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)}};let recovery;const recSource=led.recovery&&led.recovery.length>0?led.recovery:led.folds.map(f2=>({kind:"f",at:f2.at,S:f2.S,seq:f2.seq,p:0,mode:"a"}));if(recSource.length>0){const paired2=new Set;const recEvents=recSource.map((ev,i)=>({at:ev.at,kind:ev.kind,...ev.kind==="n"?{tier:ev.tier}:{},pending:ev.p,folded:ev.kind==="f"?ev.S:null,foldSeq:ev.kind==="f"?ev.seq:null,mode:ev.kind==="f"?ev.mode:null,pct:ev.kind==="f"?ev.pct??null:null,paired:false,i}));for(let i=0;i<recEvents.length;i++){if(recEvents[i].kind!=="n")continue;for(let j2=i+1;j2<recEvents.length;j2++){const f2=recEvents[j2];if(f2.kind==="n")break;if(f2.mode!=="n")continue;if(paired2.has(j2))continue;paired2.add(j2);recEvents[i].paired=true;break}}let nudges=0;let folds2=0;let nudgeFolds=0;let activeFolds=0;let totalPending=0;let totalFolded=0;for(const[j2,f2]of recEvents.entries()){if(f2.kind==="n"){nudges+=1;totalPending+=f2.pending}else{folds2+=1;if(f2.mode==="n"){nudgeFolds+=1;totalFolded+=f2.folded??0}else{activeFolds+=1}}}const episodes=[];let recPool=0;for(let j2=0;j2<recEvents.length;j2++){const ev=recEvents[j2];if(ev.kind==="n"){recPool+=ev.pending;let epFolded=0;let epActive=0;for(let k2=j2+1;k2<recEvents.length&&recEvents[k2].kind!=="n";k2++){const f2=recEvents[k2];if(f2.mode==="n")epFolded+=f2.folded??0;else epActive+=1}const credited=Math.min(epFolded,recPool);recPool=Math.max(0,recPool-epFolded);episodes.push({at:ev.at,tier:ev.tier??null,pending:ev.pending,folded:epFolded,pct:ev.pending>0?Math.round(epFolded/ev.pending*1e3)/10:null,credited,extra:epFolded-credited,activeFolds:epActive})}}recovery={events:recEvents.map(({i:_i2,...ev})=>ev),summary:{nudges,folds:folds2,nudgeFolds,activeFolds,totalPending,totalFolded,pct:totalPending>0?Math.round(totalFolded/totalPending*1e3)/10:null},episodes}}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,recovery,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 REPLAY_PRE_BOOT="egress-usage-replay";function rebuildCacheLedgerFromUsageEvents(session,events){const meta=session.metadata??(session.metadata={});const led={v:1,lastBlockId:0,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;for(const ev of events){if(ev.type==="F"){const bid=ev.payload?.bid;if(typeof bid==="string")led.lastBlockId=Math.max(led.lastBlockId,refNum3(bid))}}let appliedS=0;for(const ev of events){if(ev.type==="M"){led.lastBoot=REPLAY_PRE_BOOT;continue}if(ev.type==="F"){const p3=ev.payload;if(!p3||typeof p3.S!=="number"||typeof p3.bid!=="string")continue;pushFold(led,{at:typeof p3.at==="number"?p3.at:ev.at,S:p3.S,sigma:typeof p3.sigma==="number"?p3.sigma:0,X:typeof p3.X==="number"?p3.X:void 0,V:typeof p3.V==="number"?p3.V:void 0,Vp:typeof p3.Vp==="number"?p3.Vp:void 0,bid:p3.bid},0);led.lastBlockId=Math.max(led.lastBlockId,refNum3(p3.bid));continue}if(ev.type!=="S")continue;const p2=ev.payload;if(!p2||!p2.s||typeof p2.s.input!=="number"||typeof p2.s.at!=="number")continue;const prevModel=meta.lastModel;if(typeof p2.model==="string"&&p2.model!=="")meta.lastModel=p2.model;try{recordCacheSample(session,p2.s);appliedS+=1}finally{if(typeof prevModel==="string"&&prevModel!=="")meta.lastModel=prevModel;else delete meta.lastModel}}if(appliedS>0)led.lastBoot=BOOT_ID;return{lines:led.lines.length,folds:led.folds.length}}var{join:join7}=path28;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;var BOOT_WINDOW_DECODES_PER_SESSION=16;var BOOT_WINDOW_MIN_DECODES=64;var BOOT_WINDOW_MAX_DECODES=2048;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 path28.join(proto,`${host}${createHash14("sha256").update(id,"utf8").digest("hex").slice(0,24)}.json`)}function durableWriteFile(file,data,mode){const fd=openSync5(file,"w",mode);try{writeFileSync5(fd,data);fsyncSync2(fd)}finally{closeSync5(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=path28.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 CORRUPT_SIBLING_CAP=1;function pruneCorruptSiblings(baseFile,keepPath){const dir=path28.dirname(baseFile);const prefix=`${path28.basename(baseFile)}.corrupt-`;const keepName=keepPath?path28.basename(keepPath):void 0;let names;try{names=readdirSync4(dir)}catch{return{removed:0,locked:0}}const stampOf=name2=>{const n=Number(name2.slice(prefix.length));return Number.isFinite(n)?n:0};const others=names.filter(n=>n.startsWith(prefix)&&n!==keepName).sort((a,b2)=>stampOf(b2)-stampOf(a));let removed=0;let locked=0;for(const name2 of others.slice(Math.max(0,CORRUPT_SIBLING_CAP-1))){try{unlinkSync3(path28.join(dir,name2));removed++}catch{locked++}}return{removed,locked}}function isAllocationFailureError(error){return error instanceof RangeError&&/allocation failed|heap out of memory/i.test(error.message)}function errText2(error){return error instanceof Error?error.message:String(error)}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;preoomPending=new Set;shadow;residentFieldsForBuild;forkBaseCut=new Set;storageMode;jsonWriterOff;mysqlReady=Promise.resolve();networkFullExpected=false;ready(){return this.mysqlReady}writerOffPending=new Map;durabilityArms=new Map;frozenNoticeAt=new Map;saveTimers=new Map;saveBuilders=new Map;flushWaiters=new Map;lastSaveLanded=new Map;saveWritesInFlight=new Set;durableRevision=new Map;committedMetaFp=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 jsonWriterOffChoice=resolveJsonWriterChoice(process.env,fileStorageJsonWriter());const writerBackendIsSqlite=opts?.shadow!==void 0?!opts.shadow.isAsyncBackend:resolveBackendName(process.env,fileStorageBackend())==="sqlite";this.jsonWriterOff=effectiveJsonWriterOff(process.env,fileStorageJsonWriter(),fileStorageUnified())&&storageMode==="full"&&!unifiedBlockedByEncryption&&writerBackendIsSqlite;if(this.jsonWriterOff&&jsonWriterOffChoice==="unset"){baseLog("info","[storage] json envelope writer off (pure-sqlite default \u2014 index.db is the only persistent copy; restore dual-write with storage.jsonWriter=on)")}if(jsonWriterOffRequested(process.env,fileStorageJsonWriter())&&!this.jsonWriterOff){baseLog("warn","[storage] storage.jsonWriter=off ignored \u2014 requires the unified full/sqlite posture on the sqlite backend (shadow/legacy keep the JSON envelope as sole source of truth; network backends keep it 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(),fileStorageJsonWriter()).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(),fileStorageJsonWriter())??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=>path28.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=>path28.join(this.sessionsDir,rel2)),...this.diskFiles.filter(file=>fileNameMatchesId(path28.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=readFileSync11(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=path28.join(this.sessionsDir,rel2);const tmp=path28.join(path28.dirname(abs),`.tmp-${path28.basename(abs,".json")}-${process.pid}-${this.tmpSeq++}`);try{mkdirSync8(path28.dirname(abs),{recursive:true});const text2=JSON.stringify(store2);durableWriteFile(tmp,this.codec?this.codec.encode(text2):text2);renameSync3(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=path28.join(this.sessionsDir,rel2);const tmp=path28.join(path28.dirname(abs),`.tmp-${path28.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}if(this.writerOffActive()){session.contentStoreDirty=false;return true}mkdirSync8(path28.dirname(abs),{recursive:true});const text2=JSON.stringify(session.contentStore);durableWriteFile(tmp,this.codec?this.codec.encode(text2):text2,384);renameSync3(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;const warmRec={v:null};await this.withPreoomSnapshot(id,session.meta,()=>this.store.writeNow(id,()=>{const r=this.buildRecordForSave(session);warmRec.v=r;return r}));if(warmRec.v)this.noteMetaFp(id,warmRec.v.metadata??{});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(existsSync9(path28.join(root,relPathFor(id))))return true;if(existsSync9(path28.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;mkdirSync8(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=existsSync9(root)?await walkJsonFiles(root):[];const rootFiles=[];filesByRoot.set(root,rootFiles);for(const file of files){if(path28.basename(file).endsWith(".content-store.json"))continue;this.diskFiles.push(file);rootFiles.push(file)}}if(this.replicasAvailable()){this.seedIndexedAliases(canonical2);const hot=(filesByRoot.get(this.sessionsDir)??[]).map(file=>{try{const st2=statSync9(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;const decodeCap=limits.maxSessions===0?0:Math.min(BOOT_WINDOW_MAX_DECODES,Math.max(BOOT_WINDOW_MIN_DECODES,limits.maxSessions*BOOT_WINDOW_DECODES_PER_SESSION));let decoded=0;for(const cand of hot){if(decoded>=decodeCap)break;if(parsedCands.length>=limits.maxSessions&&windowBytes>=limits.maxBytes)break;if(cand.size>limits.maxBytes)continue;const parsed=await this.readRawFileWithBytes(cand.file);decoded++;parsedFiles.add(cand.file);if(!parsed)continue;const rec=this.parseBootPayload(parsed.value);if(!rec||!fileNameMatchesId(path28.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(path28.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=path28.join(root,rel2);try{if(statSync9(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(path28.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(resolve3=>setImmediate(resolve3))}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=readFileSync11(file)}catch(err2){if(err2.code==="ENOENT")return null;throw err2}let raw;try{raw=JSON.parse(bytes.toString("utf8"))}catch(plainTextError){try{raw=JSON.parse(this.readCodec.decode(bytes))}catch(decodeError){if(isAllocationFailureError(plainTextError)||isAllocationFailureError(decodeError)){this.log("error",`[persist] session state ${path28.basename(file)} unreadable this round \u2014 decode ran out of memory, NOT corruption; file left in place for retry (${errText2(plainTextError)} / ${errText2(decodeError)})`);this.preoomPending.add(file);return null}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;this.preoomPending.delete(file);return{id,payload,version:payload.version,savedAt:payload.savedAt}}quarantineCorruptState(file,id,cause){const causeText=errText2(cause);const quarantinePath=`${file}.corrupt-${Date.now()}`;try{renameSync3(file,quarantinePath);const pruned=pruneCorruptSiblings(file,quarantinePath);const capNote=pruned.removed>0?`; removed ${pruned.removed} older forensic cop${pruned.removed===1?"y":"ies"} (cap ${CORRUPT_SIBLING_CAP})`:"";this.log("warn",`[persist] quarantined undecodable session state ${path28.basename(file)} \u2192 ${path28.basename(quarantinePath)}; starting ${id} fresh (${causeText})${capNote}`)}catch(renameErr){this.log("error",`[persist] failed to quarantine corrupt session state ${path28.basename(file)}; resuming ${id} empty this load (${causeText}; rename: ${errText2(renameErr)})`)}}withPreoomSnapshot(id,meta,write){const file=path28.join(this.sessionsDir,relPathFor(id,meta?.protocol,meta?.upstreamOrigin));if(!this.preoomPending.has(file))return write();this.preoomPending.delete(file);let snapshotPath=null;try{if(existsSync9(file)){snapshotPath=`${file}.corrupt-preoom-${Date.now()}`;renameSync3(file,snapshotPath);const pruned=pruneCorruptSiblings(file,snapshotPath);const capNote=pruned.removed>0?`; removed ${pruned.removed} older forensic cop${pruned.removed===1?"y":"ies"} (cap ${CORRUPT_SIBLING_CAP})`:"";this.log("warn",`[persist] preserved pre-OOM session state ${path28.basename(file)} \u2192 ${path28.basename(snapshotPath)} before overwriting it with fresh state (the old envelope was healthy but unreadable under memory pressure)${capNote}`)}}catch(err2){this.log("error",`[persist] failed to preserve pre-OOM session state ${path28.basename(file)} before overwrite; proceeding as pre-fix (${errText2(err2)})`);snapshotPath=null}if(!snapshotPath)return write();const restore=()=>{try{if(existsSync9(snapshotPath)&&!existsSync9(file))renameSync3(snapshotPath,file)}catch{}};try{const result=write();const asPromise=result;if(result&&typeof asPromise?.then==="function"){return asPromise.then(value=>value,error=>{restore();throw error})}if(typeof result==="boolean"&&!result)restore();return result}catch(err2){restore();throw err2}}buildForLoadAll(id,payload){if(this.shadow?.readsUnified){const dbAt=this.shadow.sessionUpdatedAt(id);let importedNewer=false;if(dbAt===null)this.shadow.importRecord(payload);else if(payload.savedAt>dbAt)importedNewer=this.shadow.importRecord(payload)!==null;const view=this.shadow.viewFor(id);if(view){if(!importedNewer&&dbAt!==null&&payload.savedAt>dbAt){this.log("warn",`[persist] newer envelope for ${id} (savedAt ${payload.savedAt}) could not be imported \u2014 serving the envelope view, unified row kept at ${dbAt}`);return this.withEgressUsageReplay(buildSession(payload))}return this.withEgressUsageReplay(buildSession(viewToRecord(view)))}return this.withEgressUsageReplay(buildSession(payload))}return buildSession(payload)}async sweepStaleTemps(){let files;try{files=await walkJsonFiles(this.sessionsDir)}catch{return}for(const file of files){if(isStaleTempName(path28.basename(file))){await rm3(file,{force:true}).catch(()=>{})}}}async migrateLegacyIds(){if(!this.enabled)return;if(existsSync9(this.markerPath()))return;const loaded=await this.store.loadAll();await this.applyLegacyMigration(loaded)}markerPath(){return path28.join(this.sessionsDir,MIGRATION_MARKER)}async applyLegacyMigration(loaded){if(existsSync9(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;const rekeyRec={v:null};await this.withPreoomSnapshot(label,session.meta,()=>this.store.writeNow(label,()=>{const r=this.buildRecordForSave(session);rekeyRec.v=r;return r}));if(rekeyRec.v)this.noteMetaFp(label,rekeyRec.v.metadata??{});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{mkdirSync8(this.sessionsDir,{recursive:true});writeFileSync5(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(existsSync9(path28.join(this.sessionsDir,rel2)))rels.add(rel2)}const expected=path28.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(path28.join(this.sessionsDir,entry.name),{withFileTypes:true})){if(f2.isFile()&&matches(f2.name))rels.add(path28.join(entry.name,f2.name))}}catch{}}}catch{}return[...rels]}async removeSessionFiles(id,meta){for(const rel2 of await this.findSessionFiles(id,meta)){await rm3(path28.join(this.sessionsDir,rel2),{force:true}).catch(()=>{});if(rel2.endsWith(".json")&&!rel2.endsWith(".fb.json")){await rm3(path28.join(this.sessionsDir,`${rel2.slice(0,-".json".length)}.content-store.json`),{force:true}).catch(()=>{})}}}async removeSession(id){this.durabilityArms.delete(id);let meta;const unifiedAvailable=this.replicasAvailable();if(unifiedAvailable){try{const row=this.liveShadow().sessionIdentity(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([path28.join(this.sessionsDir,relPathFor(id,meta?.protocol,meta?.upstreamOrigin)),path28.join(this.sessionsDir,relPathFor(id)),path28.join(this.sessionsDir,flatFileNameFor(id))]);for(const file of livePaths){if(!existsSync9(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),...existsSync9(`${this.sessionsDir}-cold`)?walkJsonFilesSync(`${this.sessionsDir}-cold`):[]].filter(f2=>!path28.basename(f2).endsWith(".content-store.json"));this.diskFilesSeeded=true}const expected=path28.basename(relPathFor(id,meta?.protocol,meta?.upstreamOrigin));const candidates=this.diskFiles.filter(file=>fileNameMatchesId(path28.basename(file),id,meta?.protocol,meta?.upstreamOrigin)||!meta?.protocol&&path28.basename(file).endsWith(`_${expected}`));for(const file of candidates){if(!existsSync9(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=path28.join(this.sessionsDir,proto);const logicalFor=file=>file.endsWith(".fb.json")?`${file.slice(0,-".fb.json".length)}.json`:file;const candidates=new Set([path28.join(dir,path28.basename(relPathFor(id,proto,meta.upstreamOrigin)))]);const suffix=`_${path28.basename(relPathFor(id))}`;for(const file of this.diskFiles){const base=path28.basename(file);if(base.endsWith(".content-store.json"))continue;if(path28.dirname(file)!==dir||!logicalFor(base).endsWith(suffix))continue;candidates.add(file)}const valid=new Map;for(const file of candidates){if(!existsSync9(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=path28.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 (${path28.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===path28.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 ${path28.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 record3=viewToRecord(view);const session=buildSession(record3);this.noteDurable(id,session.revisionEpoch);if(hasNegativePersistedTokens(record3)){this.scheduleSave(session);this.log("info",`[persist] clamped negative token stats on reload for ${id} (#408)`)}this.logColdLoad(id,"unified store",session,record3.savedAt);return this.withEgressUsageReplay(session)}withEgressUsageReplay(session){if(session.metadata?.["egressAuthority"]!==true)return session;if(!cacheLedgerIsEmpty(session))return session;const st2=this.egressOpLogStore();if(!st2)return session;try{const rows=st2.egressUsageRows(session.id);if(rows.length===0)return session;const events=[];for(const r of rows){let payload;try{payload=r.rowType==="M"?void 0:JSON.parse(r.payloadText)}catch{continue}events.push({type:r.rowType,at:r.at,payload})}const n=rebuildCacheLedgerFromUsageEvents(session,events);this.log("info",`[persist] rebuilt the cache ledger for ${session.id} from the egress_usage stream (${n.lines} line(s), ${n.folds} fold(s))`)}catch(err2){this.log("warn",`[persist] egress usage replay failed for ${session.id} (${err2 instanceof Error?err2.message:String(err2)}) \u2014 serving an empty ledger; new samples book fresh from this load`)}return session}maybeRestampToLedger(session){const state8=session.state;if(state8.refLedgerAligned===true)return;if(!state8.messageRefs||Object.keys(state8.messageRefs.byRaw).length===0)return;try{const seqByRawId=this.unifiedSeqByRaw(session.id);if(seqByRawId===null||seqByRawId.size===0)return;const outcome=restampRefsToLedger(state8,seqByRawId);if(session.contentStore){const store2=contentStoreOf(session);const restampedStore=restampContentStore(store2,state8.messageRefs.byRaw);if(restampedStore!==store2)session.contentStore=restampedStore}if(outcome.superseded.size>0){session.restampSuperseded=outcome.superseded}else{delete session.restampSuperseded}const snap=state8.tokenSnapshot;if(snap&&outcome.superseded.size>0){const byRawNow=state8.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)`)}}state8.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)}`)}}consumePendingLedgerAlign(session){if(!session.pendingLedgerAlign)return;delete session.pendingLedgerAlign;this.durabilityArms.delete(session.id);this.maybeRestampToLedger(session)}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,archiveDir2){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.restoreArchived(sessionId,{archiveDir:archiveDir2??join7(this.sessionsDir,"archive")})}catch(err2){this.log("warn",`[persist] unified restore failed: ${String(err2)}`);return null}}unifiedArchiveSession(sessionId,archiveDir2){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.archiveSession(sessionId,{archiveDir:archiveDir2??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,archiveDir2){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.archiveBlock(sessionId,blockId,{archiveDir:archiveDir2??join7(this.sessionsDir,"archive")})}catch(err2){this.log("warn",`[persist] unified block archive failed: ${String(err2)}`);return null}}unifiedRestoreBlock(sessionId,blockId,archiveDir2){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.restoreBlock(sessionId,blockId,{archiveDir:archiveDir2??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}}snapStage0(sessionId,incoming,opts){if(!this.replicasAvailable())return null;return this.liveShadow().snapStage0(sessionId,incoming,opts)}snapStage0Reset(sessionId){if(!this.replicasAvailable())return;this.liveShadow().snapStage0Reset(sessionId)}snapConvBound(sessionId){if(!this.replicasAvailable())return false;return this.liveShadow().snapConvBound(sessionId)}snapMsgIdLiveIds(sessionId){if(!this.replicasAvailable())return[];return this.liveShadow().snapMsgIdLiveIds(sessionId)}snapPinLiveIds(sessionId){if(!this.replicasAvailable())return[];return this.liveShadow().snapPinLiveIds(sessionId)}egressOpLogStore(){return this.replicasAvailable()?this.liveShadow().egressOpLogSync():null}snapR3Latched(sessionId){if(!this.replicasAvailable())return false;return this.liveShadow().snapR3Latched(sessionId)}snapR3Latch(sessionId){if(!this.replicasAvailable())return;this.liveShadow().snapR3Latch(sessionId)}snapR3LatchClear(sessRaw){if(!this.replicasAvailable())return null;return this.liveShadow().snapR3LatchClear(sessRaw)}snapR3LatchedList(){if(!this.replicasAvailable())return[];return this.liveShadow().snapR3LatchedList()}snapSidOfRaw(sessRaw){if(!this.replicasAvailable())return null;return this.liveShadow().snapSidOfRaw(sessRaw)}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}}unifiedMessageContentByIds(sessionId,msgIds){if(!this.shadow||this.shadow.stats.disabled)return null;try{return this.shadow.messageContentByMsgIds(sessionId,msgIds)}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(e){log("warn",`[persist] unifiedWebSummaries: ${String(e)} \u2014 falling back to the disk-index walk`);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)}setKvAsync(namespace,key2,value){return this.liveShadow().setKvAsync(namespace,key2,value)}getKvAsync(namespace,key2){return this.liveShadow().getKvAsync(namespace,key2)}listKvAsync(namespace,keyPrefix){return this.liveShadow().listKvAsync(namespace,keyPrefix)}deleteKvAsync(namespace,key2){return this.liveShadow().deleteKvAsync(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;if(session.metadata["egressAuthority"]===true)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 record3=this.buildRecordForSave(session);const activeBlockIds2=session.state.blocks.filter(b2=>b2.active!==false).map(b2=>b2.blockId).sort();await this.shadow.insertCheckpointAsync({cpId:`cp-${randomUUID5()}`,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(record3)});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();let record3;if(opts.resident){record3=this.buildRecordForSave(opts.resident)}else{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)`);record3=viewToRecord(view)}if(record3.metadata?.["egressAuthority"]===true){throw new Error(`[storage] createReplica: session ${sessionId} is egress-on \u2014 use the point-fork path instead`)}const ccr=this.contentStoreById(sessionId,record3.meta);if(ccr)record3.forkContentStore=ccr;const cpId=`cp-${randomUUID5()}`;const activeBlockIds2=record3.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(record3)});const row=await shadow.getCheckpointAsync(cpId);if(!row)throw new Error(`[storage] checkpoint ${cpId} missing right after insert (index inconsistency)`);return row}async forkEgressSnapshot(sessionId,childId){await this.ready();const parent=peekSession(sessionId)??await this.loadAsync(sessionId);if(!parent)throw new Error(`[storage] forkEgressSnapshot: session ${sessionId} does not exist`);if(parent.metadata["egressAuthority"]!==true)throw new Error(`[storage] forkEgressSnapshot: session ${sessionId} is not an egress-on session`);const cid=childId??`fork-${randomUUID5()}`;if(peekSession(cid)!==void 0||await this.loadAsync(cid))throw new Error(`[storage] forkEgressSnapshot: child ${cid} already exists`);const child2={...parent,id:cid,meta:structuredClone(parent.meta),stats:structuredClone(parent.stats),metadata:(()=>{const{egressFlowUnreadable:_dropped,...rest}=parent.metadata;void _dropped;return{...rest,derivedFromSessionId:sessionId}})(),state:structuredClone(parent.state),blockContents:new Map([...(parent.blockContents??new Map).entries()].map(([k2,v2])=>[k2,structuredClone(v2)])),lastMessages:parent.lastMessages?structuredClone(parent.lastMessages):void 0,pluginSnapshot:parent.pluginSnapshot?structuredClone(parent.pluginSnapshot):void 0,decompositionLog:parent.decompositionLog?structuredClone(parent.decompositionLog):void 0,transient:void 0,lockChain:void 0,persisted:false,inFlight:0,pendingRetrievals:[]};await this.persistForkSession(sessionId,child2);const opSeq=this.egressOpLogStore()?.egressStateMaxSeq(cid)??0;return{childId:cid,opSeq}}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 record3=JSON.parse(stateJson);const newId=opts.sessionId??`restore-${randomUUID5().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`)}record3.id=newId;record3.savedAt=Date.now();record3.meta={...record3.meta,restoredFrom:cp2.session_id,restoredCheckpoint:cp2.cp_id};await this.withPreoomSnapshot(newId,record3.meta,()=>this.store.writeNow(newId,()=>record3));this.noteMetaFp(newId,record3.metadata??{});shadow.record(record3);this.ownCommit.set(newId,{requests:record3.stats?.requests??record3.requests??0,nextBlockId:record3.state?.nextBlockId??0,builtAtMs:Date.now()});if(record3.forkContentStore){this.writeContentStoreSidecar(newId,record3.meta,record3.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 readFile6(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;if(this.writerOffActive()||this.envelopeFrozen(incoming.id)){return this.envelopeFileKey(incoming.id,incoming.meta)===own.writerOffFile}const stat6=this.statEnvelope(incoming.id,incoming.meta);if(!stat6)return false;if(!own.written)return false;if(stat6.size!==own.written.size)return false;if(stat6.mtimeMs>own.written.mtimeMs+OWN_WRITE_STAMP_EPSILON_MS)return false;return true}envelopeFileKey(id,meta){const stat6=this.statEnvelope(id,meta);return stat6?`${stat6.size}:${stat6.mtimeMs}`:"absent"}statEnvelope(id,meta){const candidates=[];const known=this.sourceFiles.get(id);if(known)candidates.push(known);candidates.push(path28.join(this.sessionsDir,relPathFor(id,meta?.protocol,meta?.upstreamOrigin)),path28.join(this.sessionsDir,relPathFor(id)),path28.join(this.sessionsDir,flatFileNameFor(id)));for(const file of candidates){try{const st2=statSync9(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 record3=this.buildRecordForSave(session,stamp2);const disk=this.staleDiskPayload(record3);if(disk===null){const payload=session.decompositionLog;if(payload!==void 0)session.decompositionLog=void 0;const tail=session.lastMessagesFolded!==true?session.lastMessages:void 0;if(!this.egressProjectionFrozen(session)){this.shadow?.record(payload!==void 0?{...record3,decompositionLog:payload}:record3,tail&&tail.length>0?{lastMessages:tail,lastMessagesFolded:session.lastMessagesFolded}:void 0,session.contentStore??void 0)}this.noteOwnCommit(session.id,record3);return record3}const now=Date.now();const last=this.staleWarnAt.get(record3.id)??0;if(now-last>=STALE_WARN_THROTTLE_MS){this.staleWarnAt.set(record3.id,now);this.log("warn",`[persist] rejected stale snapshot for session ${record3.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);if(!this.egressProjectionFrozen(session))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,writerOffFile:this.writerOffActive()||this.envelopeFrozen(id)?this.envelopeFileKey(id,committed.meta??prev?.meta):void 0,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 stat6=this.statEnvelope(id,token.meta);if(!stat6)return;token.written=stat6}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)`)}egressProjectionFrozen(session){return session.metadata?.["egressAuthority"]===true&&egressPlaneGateOn()}ingestRowsNow(session){if(!this.shadow)return;if(this.egressProjectionFrozen(session))return;try{const stamp2=this.liveStorageStamp;const record3=this.buildRecordForSave(session,stamp2);const disk=this.staleDiskPayload(record3);if(disk!==null){const now=Date.now();const last=this.staleWarnAt.get(record3.id)??0;if(now-last>=STALE_WARN_THROTTLE_MS){this.staleWarnAt.set(record3.id,now);this.log("warn",`[persist] rejected stale snapshot for session ${record3.id} (durability-before-render): 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);this.armDurabilitySkip(session,disk);return}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?{...record3,decompositionLog:payload}:record3,tail&&tail.length>0?{lastMessages:tail,lastMessagesFolded:session.lastMessagesFolded}:void 0,session.contentStore??void 0);this.noteOwnCommit(session.id,record3);this.armDurabilitySkip(session,record3)}catch(err2){this.log("warn",`[persist] ingestRowsNow failed for ${session.id}: ${String(err2)} \u2014 the debounced save retries the full path`)}}armDurabilitySkip(session,record3){this.durabilityArms.set(session.id,{epoch:session.revisionEpoch??0,messagesRef:session.lastMessages,metadata:record3.metadata??{},metadataFp:JSON.stringify(session.metadata)})}scheduleSave(session){this.consumePendingLedgerAlign(session);if(!this.saveContentStore(session)){this.durabilityArms.delete(session.id);return}const frozen=this.envelopeFrozen(session.id);if(this.writerOffActive()||frozen||this.egressProjectionFrozen(session)){if(frozen)this.noteFrozenSkip(session.id,"scheduled");if(this.writerOffPending.has(session.id))return;const run=()=>{this.writerOffPending.delete(session.id);const proofRevision=session.revisionEpoch;const armed4=this.durabilityArms.get(session.id);const durabilitySkip=armed4!==void 0&&(session.revisionEpoch??0)===armed4.epoch+1&&session.lastMessages===armed4.messagesRef&&session.decompositionLog===void 0&&!session.contentStoreDirty&&session.pendingLedgerAlign===void 0&&JSON.stringify(session.metadata)===armed4.metadataFp;this.durabilityArms.delete(session.id);let settledOk=false;try{const recMeta=durabilitySkip&&armed4?armed4.metadata:this.guardedBuild(session)().metadata??{};this.maybeCutForkBase(session);this.noteMetaFp(session.id,recMeta);if(this.egressProjectionFrozen(session)){this.lastSaveLanded.set(session.id,true)}else{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}this.durabilityArms.delete(session.id);if(!this.enabled)return;this.tryRecoverSidecar();const id=session.id;const guarded=this.guardedBuild(session);const armed3={build:()=>{const r=guarded();armed3.rec=r;return r},rec:null};this.saveBuilders.set(id,armed3);const existing=this.saveTimers.get(id);if(existing)return;const timer2=setTimeout(()=>{this.saveTimers.delete(id);const armed4=this.saveBuilders.get(id);this.saveBuilders.delete(id);if(!armed4)return;const proofRevision=peekSession(id)?.revisionEpoch;this.saveWritesInFlight.add(id);void this.withPreoomSnapshot(id,peekSession(id)?.meta,()=>this.store.writeNow(id,armed4.build)).then(()=>{this.stampOwnWrite(id);if(armed4.rec)this.noteMetaFp(id,armed4.rec.metadata??{});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))timer2.unref?.();this.saveTimers.set(id,timer2)}async afterNextFlush(sessionId){if(!this.saveTimers.has(sessionId)&&!this.writerOffPending.has(sessionId)&&!this.saveWritesInFlight.has(sessionId)){return true}return await new Promise(resolve3=>{const ws2=this.flushWaiters.get(sessionId)??[];ws2.push(ok=>{resolve3(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 cap2=sessionResidentHardMaxBytes();if(cap2>0&&sessionWeight(session)>cap2){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 ${cap2} 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){this.consumePendingLedgerAlign(session);if(!this.saveContentStore(session)){this.durabilityArms.delete(session.id);throw new Error(`Originals were not saved for ${session.id}`)}const frozen=this.envelopeFrozen(session.id);if(this.writerOffActive()||frozen||this.egressProjectionFrozen(session)){if(frozen)this.noteFrozenSkip(session.id,"writeNow");this.writerOffPending.delete(session.id);const proofRevision2=session.revisionEpoch;const rec2=this.guardedBuild(session)();this.maybeCutForkBase(session);this.noteMetaFp(session.id,rec2.metadata??{});if(!this.egressProjectionFrozen(session)){this.noteDurable(session.id,proofRevision2);this.lastSaveLanded.set(session.id,true);this.foldResidentTail(session);this.dropResidentBlockContents(session);this.dropResidentMetadata(session);this.dropResidentContentStore(session)}else{this.lastSaveLanded.set(session.id,true)}return}this.durabilityArms.delete(session.id);const proofRevision=session.revisionEpoch;this.saveWritesInFlight.add(session.id);const rec={v:null};try{await this.withPreoomSnapshot(session.id,session.meta,()=>this.store.writeNow(session.id,()=>{const r=this.guardedBuild(session)();rec.v=r;return r}))}catch(err2){this.saveWritesInFlight.delete(session.id);throw err2}this.stampOwnWrite(session.id);if(rec.v)this.noteMetaFp(session.id,rec.v.metadata??{});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)}async flushSessionNow(session){const epoch=session.revisionEpoch;try{await this.writeNow(session)}catch(err2){this.log("warn",`[persist] ${session.id}: in-request snapshot flush failed (round stays on the legacy egress path): ${String(err2).slice(0,200)}`);return{ok:false,epoch}}if((session.revisionEpoch??0)!==(epoch??0)){this.scheduleSave(session)}else{const t=this.saveTimers.get(session.id);if(t){clearTimeout(t);this.saveTimers.delete(session.id)}this.saveBuilders.delete(session.id);this.writerOffPending.delete(session.id);this.runIdleSpillIfIdle(session.id)}return{ok:true,epoch}}static async flushOrSkip(session){const st2=getStore();if(!st2||typeof st2.flushSessionNow!=="function")return{ok:false,epoch:session.revisionEpoch};return st2.flushSessionNow(session)}foldResidentTail(session){if(session.inFlight>0)return;const raw=session.lastMessages;if(!raw||raw.length===0)return;session.lastMessages=boundedFoldedSnapshot(session);session.lastMessagesFolded=true}persistedMetadataView(session){return{...session.metadata,biliVersion:VERSION,storageMode:this.liveStorageStamp}}noteMetaFp(id,metadata){if(this.writerOffActive())return;this.committedMetaFp.set(id,this.metaFingerprint(metadata))}metaFingerprint(view){try{return createHash14("sha256").update(canonicalJson2(JSON.parse(JSON.stringify(view))),"utf8").digest("hex")}catch{return"\0unhashable-"+Math.random().toString(36).slice(2)}}dropResidentMetadata(session){if(this.writerOffActive()||session.inFlight>0||!this.enabled)return;if(isDroppedMetadata(session.metadata))return;if(Object.keys(session.metadata).length===0)return;const proven=this.committedMetaFp.get(session.id);if(proven===void 0||proven!==this.metaFingerprint(this.persistedMetadataView(session)))return;const meta=session.meta??void 0;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(this.writerOffActive()||session.inFlight>0||!this.enabled)return;const existing=session.blockContents;if(existing instanceof LazyBlockContents){existing.drop();return}if(existing.size===0)return;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(this.writerOffActive()||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(existsSync9(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(),fileStorageJsonWriter())??void 0}catch(err2){this.log("error",hadIntegrityQuickCheckFailure()?`[storage] sidecar reopen attempt REFUSED \u2014 the index is proven corrupt (${String(err2)}); no further in-process retries (2026-11-21 refusal policy; operator hand-fix or BILI_STORAGE_ALLOW_LEGACY_DEGRADE=1)`:`[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){this.consumePendingLedgerAlign(session);if(!this.saveContentStore(session))return false;this.tryRecoverSidecar();const frozen=this.envelopeFrozen(session.id);if(this.writerOffActive()||frozen||this.egressProjectionFrozen(session)){if(frozen)this.noteFrozenSkip(session.id,"flushSync");this.writerOffPending.delete(session.id);const proofRevision2=session.revisionEpoch;let rec=null;try{rec=this.guardedBuild(session)()}catch(err2){this.log("error",`[persist] writerOff flushSync build failed for ${session.id}: ${String(err2)}`);return false}this.maybeCutForkBase(session);if(rec)this.noteMetaFp(session.id,rec.metadata??{});if(!this.egressProjectionFrozen(session)){this.noteDurable(session.id,proofRevision2);this.lastSaveLanded.set(session.id,true);this.foldResidentTail(session);this.dropResidentBlockContents(session);this.dropResidentMetadata(session);this.dropResidentContentStore(session)}else{this.lastSaveLanded.set(session.id,true)}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 syncRec={v:null};const ok=this.withPreoomSnapshot(session.id,session.meta,()=>this.store.flushSync(session.id,()=>{const r=this.guardedBuild(session)();syncRec.v=r;return r}));if(ok){this.stampOwnWrite(session.id);if(syncRec.v)this.noteMetaFp(session.id,syncRec.v.metadata??{});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 record3=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,record3);if(!this.writerOffActive()){if(!this.withPreoomSnapshot(session.id,session.meta,()=>this.store.flushSync(session.id,()=>record3)))throw new Error("fork envelope persistence failed; retry the same request");this.stampOwnWrite(session.id)}this.noteMetaFp(session.id,record3.metadata??{});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 record3=viewToRecord(view);const receipt=record3.metadata?.publicForkReceipt;if(typeof receipt?.requestHash!=="string"||receipt.response?.ok!==true||receipt.response.sessionId!==id||receipt.response.childConversationId!==id)return;const session=buildSession(record3);if(!this.saveContentStore(session))throw new Error("fork content recovery failed");this.noteOwnCommit(id,record3);if(!this.writerOffActive()){if(!this.withPreoomSnapshot(id,session.meta,()=>this.store.flushSync(id,()=>record3)))throw new Error("fork envelope recovery failed");this.stampOwnWrite(id)}this.noteMetaFp(id,record3.metadata??{});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 timer2 of this.saveTimers.values())clearTimeout(timer2);this.saveTimers.clear();const armed3=new Map;for(const id of ids){const slot=this.saveBuilders.get(id);if(slot)armed3.set(id,slot);this.saveBuilders.delete(id)}await Promise.all([...armed3.entries()].map(([id,slot])=>this.withPreoomSnapshot(id,peekSession(id)?.meta,()=>this.store.writeNow(id,slot.build)).then(()=>{this.stampOwnWrite(id);if(slot.rec)this.noteMetaFp(id,slot.rec.metadata??{})}).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 timer2 of this.saveTimers.values())clearTimeout(timer2);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 storedProvenances=Array.isArray(ring.provenances)?ring.provenances:void 0;const kept=ring.values.map((x,i)=>({value:x,provenance:storedProvenances?.[i]})).filter(e=>typeof e.value==="number"&&Number.isFinite(e.value)&&e.value>=CALIBRATION_SAMPLE_MIN&&e.value<=CALIBRATION_SAMPLE_MAX);const recent=kept.slice(-CALIBRATION_SAMPLE_WINDOW);if(recent.length===0)return void 0;const provenances=recent.map(e=>e.provenance===CALIBRATION_PROVENANCE_TEXT_ONLY?CALIBRATION_PROVENANCE_TEXT_ONLY:void 0);const model=typeof ring.model==="string"&&ring.model.trim().length>0?ring.model:void 0;return{origin:ring.origin,...model===void 0?{}:{model},values:recent.map(e=>e.value),...provenances.some(p2=>p2!==void 0)?{provenances}:{}}}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(record3){const s3=buildSession(record3);return toLegacyLike(s3)}function buildSession(parsed){const blockContents=restoreBlockContents(Object.entries(parsed.blockContents??{}));const meta=parsed.meta??{};const stats2=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:stats2.requests??parsed.requests??0,tokensSaved:stats2.tokensSaved??parsed.tokensSaved??0,inputTokens:stats2.inputTokens??parsed.inputTokens??0,cachedTokens:stats2.cachedTokens??parsed.cachedTokens??0,outputTokens:stats2.outputTokens??parsed.outputTokens??0,cacheSamples:stats2.cacheSamples??parsed.cacheSamples??0,lastInputTokens:Math.max(0,stats2.lastInputTokens??parsed.lastInputTokens??0),lastInputTokensSource:stats2.lastInputTokensSource==="usage"||stats2.lastInputTokensSource==="estimate"||stats2.lastInputTokensSource==="overflow-arm"?stats2.lastInputTokensSource:void 0,emergencyShrinkAt:typeof stats2.emergencyShrinkAt==="number"&&Number.isFinite(stats2.emergencyShrinkAt)&&stats2.emergencyShrinkAt>=0?stats2.emergencyShrinkAt:void 0,emergencyShrinkEstimate:typeof stats2.emergencyShrinkEstimate==="number"&&Number.isFinite(stats2.emergencyShrinkEstimate)&&stats2.emergencyShrinkEstimate>0?stats2.emergencyShrinkEstimate:void 0,overflowArmTokens:typeof stats2.overflowArmTokens==="number"&&Number.isFinite(stats2.overflowArmTokens)&&stats2.overflowArmTokens>0?stats2.overflowArmTokens:void 0,preflightRuns:typeof stats2.preflightRuns==="number"&&Number.isFinite(stats2.preflightRuns)&&stats2.preflightRuns>=0?stats2.preflightRuns:void 0,overflowArmCompletionReserve:typeof stats2.overflowArmCompletionReserve==="number"&&Number.isFinite(stats2.overflowArmCompletionReserve)&&stats2.overflowArmCompletionReserve>0?stats2.overflowArmCompletionReserve:void 0,overflowArmMismatchWarned:stats2.overflowArmMismatchWarned===true?true:void 0,provenCompletionWall:typeof stats2.provenCompletionWall==="number"&&Number.isFinite(stats2.provenCompletionWall)&&stats2.provenCompletionWall>0?stats2.provenCompletionWall:void 0,provenCompletionWallOrigin:typeof stats2.provenCompletionWallOrigin==="string"&&stats2.provenCompletionWallOrigin.length>0?stats2.provenCompletionWallOrigin:void 0,provenCompletionWallModel:typeof stats2.provenCompletionWallModel==="string"&&stats2.provenCompletionWallModel.length>0?stats2.provenCompletionWallModel:void 0,compressCreditTokens:0,contextTokens:Math.max(0,stats2.contextTokens??parsed.contextTokens??0),contextTokensSource:stats2.contextTokensSource==="usage"||stats2.contextTokensSource==="estimate"?stats2.contextTokensSource:void 0,localInputEstimate:typeof stats2.localInputEstimate==="number"&&Number.isFinite(stats2.localInputEstimate)&&stats2.localInputEstimate>0?stats2.localInputEstimate:void 0,lastUsageGradeTokens:typeof stats2.lastUsageGradeTokens==="number"&&Number.isFinite(stats2.lastUsageGradeTokens)&&stats2.lastUsageGradeTokens>=0?stats2.lastUsageGradeTokens:void 0,lastInputTokensOrigin:typeof stats2.lastInputTokensOrigin==="string"&&stats2.lastInputTokensOrigin.trim().length>0?stats2.lastInputTokensOrigin:void 0,calibratedEstimate:restoreCalibratedEstimate(stats2.calibratedEstimate),calibratedEstimateOrigin:typeof stats2.calibratedEstimateOrigin==="string"&&stats2.calibratedEstimateOrigin.trim().length>0?stats2.calibratedEstimateOrigin:void 0,calibratedEstimateModel:typeof stats2.calibratedEstimateModel==="string"&&stats2.calibratedEstimateModel.trim().length>0?stats2.calibratedEstimateModel:void 0,calibratedEstimateProvenance:stats2.calibratedEstimateProvenance===CALIBRATION_PROVENANCE_TEXT_ONLY?CALIBRATION_PROVENANCE_TEXT_ONLY:void 0,calibrationRing:restoreCalibrationRing(stats2.calibrationRing),retrieveCalls:stats2.retrieveCalls??0,retrieveHits:stats2.retrieveHits??0,retrieveMisses:stats2.retrieveMisses??0,retrieveDropped:stats2.retrieveDropped??0,retrieveDelivered:stats2.retrieveDelivered??0,storedBytes:stats2.storedBytes??0,storeBytesSaved:stats2.storeBytesSaved??0,rangeRestores:stats2.rangeRestores??0,wholeBlockRestores:stats2.wholeBlockRestores??0,wholeBlockRestoresPreciseAvailable:stats2.wholeBlockRestoresPreciseAvailable??0,costUsd:validCostUsd(stats2.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 stats2=parsed.stats??{};const last=stats2.lastInputTokens??parsed.lastInputTokens;const ctx=stats2.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 record3={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){record3.messages=view.lastMessages;record3.messagesFolded=view.lastMessagesFolded===true}if(view.pluginSnapshot!==void 0)record3.pluginSnapshot=view.pluginSnapshot;if(view.contentStore!==void 0)record3.forkContentStore=view.contentStore;return record3}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 effectiveJsonWriterOff(process.env,fileStorageJsonWriter(),fileStorageUnified())&&!encrypted?"storage: sqlite (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(name2){return name2.startsWith(".tmp-")||/\.tmp-enc-\d+-\d+$/.test(name2)}function walkJsonFilesSync(dir,out=[]){let entries2;try{entries2=readdirSync4(dir,{withFileTypes:true})}catch{return out}for(const e of entries2){const full=path28.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=path28.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}function unifiedKvActive(){try{if(_store===null)return false;return _store.liveStorageStamp!=="legacy"}catch{return false}}function kvStore(){try{const s3=_store;if(!s3||s3.liveStorageStamp==="legacy")return null;if(typeof s3.getKvAsync!=="function"||typeof s3.setKvAsync!=="function"||typeof s3.listKvAsync!=="function")return null;return s3}catch{return null}}init_version();init_knobs();init_config();init_dist();init_config();init_paths();init_logger();init_external_summary_settings();import*as path29 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
|
|
1235
1235
|
|
|
1236
1236
|
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.
|
|
1237
1237
|
|
|
@@ -1304,7 +1304,7 @@ ${home}`).digest("hex").slice(0,32)}function featureEnabled(feature){return reso
|
|
|
1304
1304
|
|
|
1305
1305
|
---
|
|
1306
1306
|
|
|
1307
|
-
${extra}`:extra;return[{...head,content:merged},...messages.slice(1)]}return[{role:"system",content:extra},...messages]}function conversationSignalOpenai(body,headerValue3){if(headerValue3&&headerValue3.trim())return headerValue3.trim();const msgs=Array.isArray(body?.messages)?body.messages:[];const firstUser=msgs.find(m2=>m2?.role==="user");const seed=firstUser?stringContent(firstUser.content):"default";return hashId2(seed)}function isPlainStringOrTextParts(content){if(content==null||typeof content==="string")return true;return Array.isArray(content)&&content.length>0&&content.every(p2=>typeof p2==="object"&&p2!==null&&p2.type==="text")}function stringContent(content){if(content==null)return"";if(typeof content==="string")return content;if(Array.isArray(content)){return content.map(p2=>typeof p2==="string"?p2:p2.type==="text"?p2.text??"":"").join("\n")}return""}var OPAQUE_ITEM_TYPES=new Set(["additional_tools","mcp_list_tools"]);function isOpaqueItem(item){return OPAQUE_ITEM_TYPES.has(item.type)}var EASY_INPUT_ROLES=new Set(["user","assistant","system","developer"]);function normalizeEasyInputItem(item){if(typeof item.type==="string")return item;if(EASY_INPUT_ROLES.has(String(item.role))){return{...item,type:"message"}}return item}function shouldDropAllReasoning(){return(process.env.ACP_REASONING_KEEP??"").trim().toLowerCase()==="none"}function partText(part){if(part.type==="input_text"||part.type==="output_text"){return typeof part.text==="string"?part.text:""}return""}function responsesTextOf(content){if(typeof content==="string")return content;if(!Array.isArray(content))return"";return content.map(part=>part&&typeof part==="object"&&typeof part.text==="string"?part.text:"").join("\n")}function isPlainResponsesContent(content){if(content==null||typeof content==="string")return true;return Array.isArray(content)&&content.length>0&&content.every(p2=>p2&&typeof p2==="object"&&(p2.type==="input_text"||p2.type==="output_text")&&typeof p2.text==="string")}function messageContent(content){return typeof content==="string"?content:content.map(partText).join("\n")}function userDisplayText(content,text2){if(typeof content==="string")return text2;const hasImage=content.some(part=>part.type==="input_image");const hasTextPart=content.some(part=>part.type==="input_text"||part.type==="output_text");return!text2||hasImage&&!hasTextPart?"[image]":text2}function reasoningText(item){const fromParts=(parts,type)=>{if(!Array.isArray(parts))return"";const texts=[];for(const part of parts){if(part&&typeof part==="object"&&"type"in part&&"text"in part){const rec=part;if(rec.type===type&&typeof rec.text==="string")texts.push(rec.text)}}return texts.join("\n")};const content="content"in item?item.content:void 0;const summary="summary"in item?item.summary:void 0;return fromParts(content,"reasoning_text")||fromParts(summary,"summary_text")}function responsesToCore(body){const msgs=[];const systemParts=[];const preamble=[];const customToolCallIds=new Set;const layout=[];let droppedReasoning=0;const clusters=new ClusterCounter;const toolNames=new Map;let idx=0;if(typeof body.instructions==="string"&&body.instructions.trim())systemParts.push(body.instructions);if(typeof body.input==="string"){const id=clusters.next(deriveCanonicalMessageId("user","text",body.input));msgs.push({id,role:"user",contentType:"text",text:body.input});return{msgs,systemParts,preamble,customToolCallIds,layout,droppedReasoning,stringInput:{original:body.input,coreId:id}}}let sysDevHead=true;let headRole;for(const[wireIndex,raw]of body.input.entries()){const item=normalizeEasyInputItem(raw);let coreId;const before=msgs.length;if(isOpaqueItem(item))preamble.push(item);switch(item.type){case"reasoning":{if(shouldDropAllReasoning()){droppedReasoning++;continue}const text2=reasoningText(item);const rid=text2.length>0?text2:canonicalOpaqueSeed(item);coreId=clusters.next(deriveCanonicalMessageId("assistant","reasoning",rid));msgs.push({id:coreId,role:"assistant",contentType:"reasoning",text:rid,rawResponsesItem:item});break}case"message":{const message=item;const text2=messageContent(message.content);if(message.role==="system"||message.role==="developer"){if(sysDevHead){headRole??=message.role;systemParts.push(text2);idx++;continue}const midBase=deriveCanonicalMessageId(message.role,"text",text2);msgs.push({id:clusters.next(midBase),role:"system",contentType:"text",text:text2,originalRole:message.role,rawResponsesItem:item});break}else if(message.role==="user"||message.role==="assistant"&&text2){const role2=message.role;const splittable=role2==="user"&&Array.isArray(message.content)&&message.content.length>1&&message.content.every(part=>typeof part==="object"&&part!==null&&(part.type==="input_text"||part.type==="output_text"||part.type==="input_image"));if(splittable){for(const rawPart of message.content){const part=typeof rawPart==="object"&&rawPart!==null?rawPart:void 0;if(!part)continue;if((part.type==="input_text"||part.type==="output_text")&&typeof part.text==="string"&&part.text.length>0){const base=deriveCanonicalMessageId("user","text",part.text);msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:part.text})}else if(part.type==="input_image"&&typeof part.image_url==="string"){const image=parseDataUrl(part.image_url);const base=deriveCanonicalMessageId("user","text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:imageMediaFingerprint(image?image.base64:part.image_url)});msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawResponsesItem:item,rawResponseImagePart:{...part,type:"input_image",image_url:part.image_url},...image?{imageMediaType:image.mediaType,imageBase64:image.base64}:{}})}}break}let effText=text2;if(role2==="assistant"){const split=splitDemotedThinking(text2);if(split){msgs.push({id:clusters.next(deriveCanonicalMessageId("assistant","reasoning",split.reasoning)),role:"assistant",contentType:"reasoning",text:split.reasoning,rawResponsesItem:item});effText=split.text}}const hasImage=Array.isArray(message.content)&&message.content.some(part=>part.type==="input_image");if(effText||role2==="user"&&hasImage){const displayText=role2==="user"?userDisplayText(message.content,effText):effText;const mediaFingerprint=Array.isArray(message.content)?message.content.flatMap(part=>{if(part?.type==="input_image"&&typeof part.image_url==="string"){const raw2=part.image_url;const decoded=parseDataUrl(raw2);return[imageMediaFingerprint(decoded?decoded.base64:raw2)]}return[]}).join(",")||void 0:void 0;coreId=clusters.next(deriveCanonicalMessageId(role2,"text",displayText,{mediaFingerprint}));const imageUrl=Array.isArray(message.content)?message.content.find(part=>part.type==="input_image"&&typeof part.image_url==="string")?.image_url:void 0;const image=typeof imageUrl==="string"?parseDataUrl(imageUrl):void 0;msgs.push({id:coreId,role:role2,contentType:"text",text:displayText,rawResponsesItem:item,...image?{imageMediaType:image.mediaType,imageBase64:image.base64}:{}})}}break}case"function_call":{const call=item;coreId=clusters.next(deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(call.arguments??""),{toolName:call.name}));msgs.push({id:coreId,role:"assistant",contentType:"tool-call",toolName:call.name,toolCallId:call.call_id,text:call.arguments??"",rawResponsesItem:item});toolNames.set(call.call_id,call.name);break}case"function_call_output":{const output=item;const text2=typeof output.output==="string"?output.output:JSON.stringify(output.output);coreId=clusters.next(deriveCanonicalMessageId("tool","tool-result",text2,{toolName:toolNames.get(output.call_id)}));const name2=toolNames.get(output.call_id);msgs.push({id:coreId,role:"tool",contentType:"tool-result",toolCallId:output.call_id,text:text2,...name2?{toolName:name2}:{},rawResponsesItem:item});break}case"computer_call":case"computer_call_output":case"file_search_call":case"web_search_call":case"image_generation_call":case"code_interpreter_call":case"mcp_call":{const rid=canonicalOpaqueSeed(item);coreId=clusters.next(deriveCanonicalMessageId("assistant","responses-call",rid));msgs.push({id:coreId,role:"assistant",contentType:"reasoning",text:rid,rawResponsesItem:item});break}case"custom_tool_call":{const ctc=item;const callId=ctc.call_id??`call_${idx}`;customToolCallIds.add(callId);const argText=ctc.input??ctc.arguments??"";coreId=clusters.next(deriveCanonicalMessageId("assistant","tool-call",argText,{toolName:ctc.name??"custom"}));msgs.push({id:coreId,role:"assistant",contentType:"tool-call",toolName:ctc.name??"custom",toolCallId:callId,text:argText,rawResponsesItem:item});toolNames.set(callId,ctc.name??"custom");break}case"custom_tool_call_output":{const ctco=item;const callId=ctco.call_id??`call_${idx}`;customToolCallIds.add(callId);const outText=typeof ctco.output==="string"?ctco.output:JSON.stringify(ctco.output??"");coreId=clusters.next(deriveCanonicalMessageId("tool","tool-result",outText,{toolName:toolNames.get(callId)}));const name2=toolNames.get(callId);msgs.push({id:coreId,role:"tool",contentType:"tool-result",toolCallId:callId,text:outText,...name2?{toolName:name2}:{},rawResponsesItem:item});break}default:if(!isOpaqueItem(item))preamble.push(item);break}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}const role=item.role;const isSysDevMsgItem=(item.type===void 0||item.type==="message")&&(role==="system"||role==="developer");if(!isSysDevMsgItem&&item.type!=="additional_tools"&&item.type!=="mcp_list_tools")sysDevHead=false;const produced=msgs.slice(before).map(m2=>m2.id);layout.push({original:item,...produced.length>0?{coreId:produced[0]}:{},...produced.length>1?{coreIds:produced}:{}});idx++}return{msgs,systemParts,preamble,customToolCallIds,layout,droppedReasoning,...headRole?{headRole}:{}}}function patchTextParts(parts,text2){const textIndexes=parts.flatMap((part,index)=>part.type==="input_text"||part.type==="output_text"?[index]:[]);if(textIndexes.length===0)return[{type:"input_text",text:text2},...parts];const first=textIndexes[0];const remaining=new Set(textIndexes.slice(1));const out=[];for(let index=0;index<parts.length;index++){const part=parts[index];if(!part||remaining.has(index))continue;out.push(index===first?{...part,text:text2}:part)}return out}function patchOriginalItem(original,source,next){if(source.text===next.text&&source.toolName===next.toolName&&source.toolCallId===next.toolCallId&&source.role===next.role&&source.contentType===next.contentType)return original;if(original.type==="message"){const message=original;const content=typeof message.content==="string"?next.text??"":patchTextParts(message.content,next.text??"");return{...message,content}}if(original.type==="function_call"){return{...original,name:next.toolName??String(original.name??"unknown"),call_id:next.toolCallId??String(original.call_id??""),arguments:next.text??""}}if(original.type==="function_call_output"){return{...original,call_id:next.toolCallId??String(original.call_id??""),output:next.text??""}}return original}function patchResponsesInput(projection,messages){if(projection.stringInput){const original=projection.msgs.find(message=>message.id===projection.stringInput?.coreId);const next=messages.find(message=>message.id===projection.stringInput?.coreId);if(original&&next&&messages.length===1&&next.role==="user"&&next.contentType==="text"){return next.text===original.text?projection.stringInput.original:next.text??""}return coreToResponses(messages,projection.customToolCallIds)}const sourceById=new Map(projection.msgs.map(message=>[message.id,message]));const nextById=new Map(messages.map(message=>[message.id,message]));const slotById=new Map;projection.layout.forEach((slot,index)=>{if(slot.coreId)slotById.set(slot.coreId,index)});const insertions=new Map;for(let index=0;index<messages.length;index++){const message=messages[index];if(sourceById.has(message.id))continue;let target=projection.layout.length;for(let nextIndex=index+1;nextIndex<messages.length;nextIndex++){const slot=slotById.get(messages[nextIndex].id);if(slot!==void 0){target=slot;break}}const generated=coreToResponses([message],projection.customToolCallIds);if(generated.length>0)insertions.set(target,[...insertions.get(target)??[],...generated])}const out=[];projection.layout.forEach((slot,index)=>{out.push(...insertions.get(index)??[]);if(slot.coreIds&&slot.coreIds.length>1){const entries2=slot.coreIds.map(id=>({core:sourceById.get(id),next:nextById.get(id)}));if(entries2.every(entry=>entry.next===void 0))return;const original=slot.original;const allSurvive=entries2.every(entry=>entry.next!==void 0);const changed=entries2.some(entry=>entry.core&&entry.next&&(entry.core.text??"")!==(entry.next.text??""));if(allSurvive&&!changed){out.push(slot.original);return}const imageParts=Array.isArray(original.content)?original.content.filter(part=>part.type==="input_image"):[];let img=0;const parts=[];for(const entry of entries2){if(!entry.next)continue;const bili=entry.next;if(entry.core?.imagePart||bili.text===CANONICAL_IMAGE_TEXT){const part=entry.core?.rawResponseImagePart??imageParts[img++];if(!part)throw new Error("coreToResponses: image core without a source part \u2014 refusing to drop content (#7824)");parts.push(part)}else if(bili.text){parts.push({type:"input_text",text:bili.text})}}if(parts.length>0)out.push({...original,content:parts});return}if(!slot.coreId){out.push(slot.original);return}const source=sourceById.get(slot.coreId);const next=nextById.get(slot.coreId);if(source&&next)out.push(patchOriginalItem(slot.original,source,next))});out.push(...insertions.get(projection.layout.length)??[]);return out}function coreToResponses(messages,customToolCallIds=new Set){const out=[];const flushUserRun=run=>{if(run.length===0)return;if(run.length===1){const message=run[0];const raw=message.rawResponsesItem;const rawMessage2=raw?.type==="message"?raw:void 0;if(rawMessage2&&userDisplayText(rawMessage2.content,messageContent(rawMessage2.content))===(message.text??""))out.push(rawMessage2);else if((message.imagePart||message.text===CANONICAL_IMAGE_TEXT)&&rawMessage2&&Array.isArray(rawMessage2.content))out.push({type:"message",role:"user",content:rawMessage2.content.filter(part=>part.type==="input_image")});else if((message.imagePart||message.text===CANONICAL_IMAGE_TEXT)&&message.imageBase64&&message.imageMediaType)out.push({type:"message",role:"user",content:[{type:"input_image",image_url:`data:${message.imageMediaType};base64,${message.imageBase64}`}]});else out.push({type:"message",role:"user",content:message.text??""});return}const rawCarrier=run.find(m2=>m2.rawResponsesItem!==void 0);const rawItem=rawCarrier?.rawResponsesItem;const rawMessage=rawItem?.type==="message"?rawItem:void 0;if(run.every(m2=>m2.rawResponsesItem!==void 0)){const seen=new Set;const distinctItems=[];for(const m2 of run){const it2=m2.rawResponsesItem;if(it2.type==="message"&&!seen.has(it2)){seen.add(it2);distinctItems.push(it2)}}if(distinctItems.length>1){out.push(...distinctItems);return}}const fullCover=rawMessage&&Array.isArray(rawMessage.content)&&rawMessage.content.length===run.length;if(fullCover&&rawMessage){out.push(rawMessage);return}const imageParts=rawMessage&&Array.isArray(rawMessage.content)?rawMessage.content.filter(part=>part.type==="input_image"):[];let img=0;const parts=[];for(const message of run){const bili=message;if(bili.imagePart&&bili.rawResponsesItem){const part=bili.rawResponseImagePart??imageParts[img++];if(!part)throw new Error("coreToResponses: image core without a source part \u2014 refusing to drop content (#7824)");parts.push(part)}else if(bili.imagePart&&bili.imageBase64&&bili.imageMediaType){parts.push({type:"input_image",image_url:`data:${bili.imageMediaType};base64,${bili.imageBase64}`})}else if(bili.text){parts.push({type:"input_text",text:bili.text})}}out.push({type:"message",role:"user",content:parts.length>0?parts:""})};let userRun=[];for(const message of messages){if(message.role==="user"){userRun.push(message);continue}flushUserRun(userRun);userRun=[];const biliMessage=message;const raw=biliMessage.rawResponsesItem;if(message.role==="system"){const rawMsg=raw;const isSysDevRaw=rawMsg!=null&&(rawMsg.type===void 0||rawMsg.type==="message")&&(rawMsg.role==="system"||rawMsg.role==="developer");if(isSysDevRaw){const text2=message.text??"";if(text2!==responsesTextOf(rawMsg.content)&&isPlainResponsesContent(rawMsg.content)){out.push({type:"message",role:rawMsg.role,content:typeof rawMsg.content==="string"?text2:[{type:"input_text",text:text2}]})}else{out.push(raw)}}else{out.push({type:"message",role:"developer",content:message.text??""})}}else if(message.role==="assistant"){if(message.contentType==="text"){out.push({type:"message",role:"assistant",content:message.text??""})}else if(message.contentType==="tool-call"){const callId=message.toolCallId??`call_${message.id}`;if(customToolCallIds.has(callId)){out.push({type:"custom_tool_call",call_id:callId,name:message.toolName??"unknown",input:message.text??"",status:"completed"})}else{out.push({type:"function_call",call_id:callId,name:message.toolName??"unknown",arguments:message.text??""})}}else if(message.contentType==="reasoning"){if(raw)out.push(raw);else if((message.text??"").trim().length>0){out.push({type:"message",role:"assistant",content:message.text??""})}}}else if(message.role==="tool"){const callId=message.toolCallId??"";if(customToolCallIds.has(callId)){out.push({type:"custom_tool_call_output",call_id:callId,output:message.text??""})}else{out.push({type:"function_call_output",call_id:callId,output:message.text??""})}}}flushUserRun(userRun);return out}function injectResponsesDeveloperMessage(input,content,role="developer"){const items=typeof input==="string"?[{type:"message",role:"user",content:input}]:[...input];let index=0;while(items[index]?.type==="additional_tools")index++;items.splice(index,0,{type:"message",role,content});return items}function conversationIdentityResponses(body,headerValue3){if(headerValue3?.trim())return{value:headerValue3.trim(),source:"header",clientProvided:true};if(typeof body.session_id==="string"&&body.session_id.trim()){return{value:body.session_id.trim(),source:"body-session",clientProvided:true}}const metadataSession=body.metadata?.session_id;if(typeof metadataSession==="string"&&metadataSession.trim()){return{value:metadataSession.trim(),source:"metadata-session",clientProvided:true}}if(typeof body.previous_response_id==="string"&&body.previous_response_id.trim()){return{value:body.previous_response_id.trim(),source:"previous-response",clientProvided:false}}return{value:hashId2(JSON.stringify(body.input??[])),source:"content-fingerprint",clientProvided:false}}function conversationSignalResponses(body,headerValue3){return conversationIdentityResponses(body,headerValue3).value}function createSubagentNamespaces(){const anchors=new Map;return{namespaceFor(identityValue,instructions){if(typeof instructions!=="string"||instructions.trim().length===0)return identityValue;const fp2=hashId2(instructions);const anchor=anchors.get(identityValue);if(anchor===void 0){anchors.set(identityValue,fp2);return identityValue}return anchor===fp2?identityValue:`${identityValue}|sub:${fp2}`}}}var defaultNamespaces=createSubagentNamespaces();function googleSystemText(body){const parts=body.systemInstruction?.parts;if(!Array.isArray(parts))return"";const texts=[];for(const part of parts){if(typeof part.text==="string"&&part.text.length>0)texts.push(part.text)}return texts.join("\n\n")}function googleToCore(body){const msgs=[];const clusters=new ClusterCounter;const unmatchedCalls=new Map;const contents=Array.isArray(body.contents)?body.contents:[];for(const[contentIndex,content]of contents.entries()){const before=msgs.length;const parts=Array.isArray(content.parts)?content.parts:[];const isModel=content.role==="model";for(const part of parts){const fr2=part.functionResponse;if(!fr2||typeof fr2.name!=="string")continue;const response=fr2.response??{};const text2=response&&typeof response==="object"&&!Array.isArray(response)&&Object.keys(response).length===1&&typeof response.output==="string"?response.output:jsonText(response);const wireId=typeof fr2.id==="string"?fr2.id:void 0;const queue=unmatchedCalls.get(fr2.name);let paired;if(wireId){const i=queue?queue.indexOf(wireId):-1;if(queue&&i>=0)queue.splice(i,1)}else if(queue&&queue.length>0){paired=queue.shift()}const base=deriveCanonicalMessageId("tool","tool-result",text2,{toolName:fr2.name});const id=clusters.next(base);msgs.push({id,role:"tool",contentType:"tool-result",toolName:fr2.name,toolCallId:wireId??paired??id,text:text2,rawGoogleParts:[part]})}for(const part of parts){if(part.thought!==true||typeof part.text!=="string")continue;const base=deriveCanonicalMessageId("assistant","reasoning",part.text);msgs.push({id:clusters.next(base),role:"assistant",contentType:"reasoning",text:part.text,rawGoogleParts:[part],...signatureField("googleThoughtSignature",part.thoughtSignature)})}const rest=parts.filter(isContentPart);let lastTextCore=null;let leftover=[];for(const part of rest){if(typeof part.text==="string"&&part.thought!==true){const base=deriveCanonicalMessageId(isModel?"assistant":"user","text",part.text);lastTextCore={id:clusters.next(base),role:isModel?"assistant":"user",contentType:"text",text:part.text,rawGoogleParts:[part],...signatureField("googleThoughtSignature",part.thoughtSignature)};msgs.push(lastTextCore);continue}const inline=part.inlineData;if(inline&&typeof inline.mimeType==="string"&&typeof inline.data==="string"){const base=deriveCanonicalMessageId(isModel?"assistant":"user","text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:imageMediaFingerprint(inline.data)});msgs.push({id:clusters.next(base),role:isModel?"assistant":"user",contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,imageMediaType:inline.mimeType,imageBase64:inline.data,rawGoogleParts:[part]});continue}if(lastTextCore){lastTextCore.rawGoogleParts=[...lastTextCore.rawGoogleParts??[],part]}else{leftover=[...leftover,part]}}if(leftover.length>0){const text2=textPartsOf(leftover).map(p2=>p2.text??"").join("\n");const base=deriveCanonicalMessageId(isModel?"assistant":"user","text",text2);msgs.push({id:clusters.next(base),role:isModel?"assistant":"user",contentType:"text",text:text2,rawGoogleParts:leftover})}for(const part of parts){const fc=part.functionCall;if(!fc||typeof fc.name!=="string")continue;const text2=jsonText(fc.args??{});const wireId=typeof fc.id==="string"?fc.id:void 0;const base=deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(text2),{toolName:fc.name});const id=clusters.next(base);const toolCallId=wireId??id;const queue=unmatchedCalls.get(fc.name);if(queue)queue.push(toolCallId);else unmatchedCalls.set(fc.name,[toolCallId]);msgs.push({id,role:"assistant",contentType:"tool-call",toolName:fc.name,toolCallId,text:text2,rawGoogleParts:[part],...signatureField("googleThoughtSignature",part.thoughtSignature)})}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=contentIndex}}return{msgs,systemText:googleSystemText(body)}}var CLAUDE_WIRE_MODEL=/claude/i;function normalizeGoogleUserPartOrder(parts,opts){if(opts&&typeof opts.model==="string"&&CLAUDE_WIRE_MODEL.test(opts.model))return parts;const firstFr=parts.findIndex(p2=>p2.functionResponse!==void 0);if(firstFr===-1)return parts;const movable=p2=>typeof p2.text==="string"&&p2.thought!==true&&typeof p2.thoughtSignature!=="string";let reorder=false;for(let i=firstFr;i<parts.length;i++){if(movable(parts[i])){reorder=true;break}}if(!reorder)return parts;const moved=[];const rest=[];for(const p2 of parts)(movable(p2)?moved:rest).push(p2);return[...moved,...rest]}function coreToGoogle(messages,opts){const out=[];let model=null;let user=null;const flushModel=()=>{if(!model)return;const parts=[...model.reasoning,...model.text,...model.calls];model=null;if(parts.length>0)out.push({role:"model",parts})};const flushUser=()=>{if(!user)return;const parts=normalizeGoogleUserPartOrder([...user.responses,...user.content],{model:opts?.model});user=null;if(parts.length>0)out.push({role:"user",parts})};for(const m2 of messages){if(m2.role==="assistant"){flushUser();if(!model)model={reasoning:[],text:[],calls:[]};if(m2.contentType==="reasoning"){const rp=reasoningPart(m2);if(rp)model.reasoning.push(rp)}else if(m2.contentType==="tool-call")model.calls.push(toolCallPart(m2));else model.text.push(...contentParts(m2))}else{flushModel();if(!user)user={responses:[],content:[]};if(m2.role==="tool"||m2.contentType==="tool-result")user.responses.push(...toolResultParts(m2));else user.content.push(...contentParts(m2))}}flushModel();flushUser();return out}function conversationSignalGoogle(body,headerValue3){if(headerValue3&&headerValue3.trim())return headerValue3.trim();const contents=Array.isArray(body.contents)?body.contents:[];const firstUser=contents.find(c=>c.role!=="model");const parts=firstUser&&Array.isArray(firstUser.parts)?firstUser.parts:[];const seed=firstUser?parts.map(p2=>typeof p2.text==="string"?p2.text:"").join("\n"):"default";return hashId2(seed)}function reasoningPart(m2){const text2=m2.text??"";const head=rawParts(m2)[0];if(head)return{...head,text:text2,thought:true};if(m2.googleThoughtSignature)return{text:text2,thought:true,...signatureField("thoughtSignature",m2.googleThoughtSignature)};return text2?{text:text2}:void 0}function toolCallPart(m2){const head=rawParts(m2)[0];if(head&&head.functionCall)return head;return{functionCall:{name:m2.toolName??"unknown",args:jsonValue(m2.text),...m2.toolCallId?{id:m2.toolCallId}:{}},...signatureField("thoughtSignature",m2.googleThoughtSignature)}}function toolResultParts(m2){const raw=rawParts(m2);if(raw.length>0&&raw.every(p2=>p2.functionResponse))return raw;return[{functionResponse:{name:m2.toolName??"unknown",response:jsonValue(m2.text),...m2.toolCallId?{id:m2.toolCallId}:{}}}]}function contentParts(m2){const text2=m2.text??"";const raw=rawParts(m2);if(raw.length===0){const parts2=text2&&text2!==CANONICAL_IMAGE_TEXT&&!m2.imagePart?[{text:text2,...signatureField("thoughtSignature",m2.googleThoughtSignature)}]:[];if(m2.imageBase64&&m2.imageMediaType)parts2.push({inlineData:{mimeType:m2.imageMediaType,data:m2.imageBase64}});return parts2}const rawTexts=textPartsOf(raw);if(rawTexts.map(p2=>p2.text??"").join("\n")===text2)return raw;const parts=text2&&text2!==CANONICAL_IMAGE_TEXT&&!m2.imagePart?[{text:text2,...signatureField("thoughtSignature",m2.googleThoughtSignature)}]:[];for(const part of raw){if(!rawTexts.includes(part))parts.push(part)}return parts}function rawParts(m2){const raw=m2.rawGoogleParts;if(!Array.isArray(raw))return[];const out=[];for(const item of raw){if(typeof item==="object"&&item!==null)out.push(item)}return out}function textPartsOf(parts){return parts.filter(p2=>typeof p2.text==="string"&&p2.thought!==true)}function isContentPart(part){if(part.functionCall!==void 0||part.functionResponse!==void 0)return false;if(part.thought===true&&typeof part.text==="string")return false;return true}function signatureField(key2,signature){return typeof signature==="string"?{[key2]:signature}:{}}function jsonText(value){try{return JSON.stringify(value)??""}catch{return""}}function jsonValue(text2){if(!text2)return{};try{const value=JSON.parse(text2);return value===null?{}:value}catch{return{output:text2}}}function detectWireFormat(payload){if(payload===null||typeof payload!=="object")return void 0;const p2=payload;if(Array.isArray(p2.contents))return"google";if(Array.isArray(p2.input))return"responses";const messages=p2.messages;if(!Array.isArray(messages))return void 0;if("system"in p2||"anthropic_version"in p2)return"anthropic";for(const m2 of messages){if(m2===null||typeof m2!=="object")continue;const c=m2.content;if(Array.isArray(c)){for(const b2 of c){if(b2&&typeof b2==="object"&&typeof b2.type==="string"){if(b2.type==="tool_use"||b2.type==="tool_result"||b2.type==="thinking")return"anthropic";if(b2.type==="text"&&"cache_control"in b2)return"anthropic"}}}if(Array.isArray(m2.tool_calls))return"openai";if(m2.role==="tool"&&typeof m2.tool_call_id==="string")return"openai";if(m2.role==="system"||m2.role==="developer")return"openai"}return"openai"}init_dist();init_util();var responsesPartBinding=Symbol("responsesPartBinding");function responsesToolImageParts(item){if(typeof item!=="object"||item===null)return void 0;const raw=item;if(raw.type!=="function_call_output"&&raw.type!=="custom_tool_call_output")return void 0;if(!Array.isArray(raw.output))return void 0;let hasImage=false;for(const part of raw.output){if(typeof part!=="object"||part===null)return void 0;if(part.type==="input_text"&&typeof part.text==="string")continue;if(part.type==="input_image"&&typeof part.image_url==="string"){hasImage=true;continue}return void 0}return hasImage?raw.output:void 0}function outputText(parts){return parts.filter(part=>part.type==="input_text").map(part=>part.text).join("\n")}function responsesToCoreWithToolImages(body){const projection=responsesToCore(body);const byId2=new Map(projection.msgs.map(message=>[message.id,message]));for(const slot of projection.layout){const source=slot.original;if(source.role!=="user"||!Array.isArray(source.content))continue;const parts=source.content;if(!parts.every(part=>part.type==="input_image"||part.type==="input_text"||part.type==="output_text"))continue;const emitted=parts.filter(part=>part.type==="input_image"||typeof part.text==="string"&&part.text.length>0);const ids=slot.coreIds??(slot.coreId?[slot.coreId]:[]);if(ids.length!==emitted.length)continue;ids.forEach((id,index)=>{const message=byId2.get(id);if(message)message[responsesPartBinding]={source,part:emitted[index],sourceId:id}})}for(const message of projection.msgs){const parts=responsesToolImageParts(message.rawResponsesItem);if(parts)message.text=outputText(parts)}return projection}function rebuildToolImages(message){if(message.role!=="tool"||message.contentType!=="tool-result")return void 0;const raw=message.rawResponsesItem;const parts=responsesToolImageParts(raw);if(!raw||!parts)return void 0;const text2=message.text??"";if(text2===outputText(parts)&&message.toolCallId===raw.call_id)return raw;let written=false;const output=parts.map(part=>{if(part.type!=="input_text")return part;const next={...part,text:written?"":text2};written=true;return next});if(!written&&text2)output.unshift({type:"input_text",text:text2});return{...raw,call_id:message.toolCallId??raw.call_id,output}}function isPlainRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function foldConfigurationFields(base,overlay){const out={...base};for(const[key2,value]of Object.entries(overlay)){if(isPlainRecord(out[key2])&&isPlainRecord(value))out[key2]=foldConfigurationFields(out[key2],value);else out[key2]=value}return out}function mergeAdjacentConfigurationUpdates(items){const out=[];for(const item of items){const prev=out[out.length-1];if(item.type==="configuration_update"&&prev!==void 0&&prev.type==="configuration_update"){const base={};for(const[key2,value]of Object.entries(prev))base[key2]=value;out[out.length-1]=foldConfigurationFields(base,item)}else{out.push(item)}}return out}function boundCarrier(messages){const source=messages[0][responsesPartBinding].source;const parts=messages.map(message=>{const part=message[responsesPartBinding].part;return part.type==="input_image"||part.text===message.text?part:{...part,text:message.text??""}});const original=source.content;const unchanged=Array.isArray(original)&&original.length===parts.length&&parts.every((part,index)=>part===original[index]);return unchanged?source:{type:"message",role:"user",content:parts}}function boundProjection(projection,messages){const runs=new Map;let previous;for(const message of messages){const bound2=message;const binding=bound2[responsesPartBinding];if(!binding||message.role!=="user"||isRenderedSummaryMessage(message)){previous=void 0;continue}const groups=runs.get(binding.source)??[];if(previous?.[responsesPartBinding]?.source===binding.source)groups.at(-1).push(bound2);else groups.push([bound2]);runs.set(binding.source,groups);previous=bound2}const sources2=new Map(projection.msgs.map(message=>[message.id,message]));const replaced=new Set;const rebound=[];const layout=projection.layout.flatMap(slot=>{const groups=runs.get(slot.original);if(!groups)return[slot];for(const id of slot.coreIds??(slot.coreId?[slot.coreId]:[]))replaced.add(id);return groups.map(group=>{for(const message of group){const source=sources2.get(message[responsesPartBinding].sourceId);if(source)rebound.push({...source,id:message.id,text:message.text})}const ids=group.map(message=>message.id);return{original:boundCarrier(group),coreId:ids[0],...ids.length>1?{coreIds:ids}:{}}})});return{...projection,layout,msgs:[...projection.msgs.filter(message=>!replaced.has(message.id)),...rebound]}}function patchResponsesInputWithToolImages(projection,messages){const voiced=systemToUser(messages,m2=>isRenderedSummaryMessage(m2));const input=patchResponsesInput(boundProjection(projection,voiced),voiced);if(typeof input==="string")return input;const byOriginal=new Map;const byCall=new Map;for(const message of voiced){const rebuilt=rebuildToolImages(message);if(!rebuilt)continue;byOriginal.set(message.rawResponsesItem,rebuilt);byCall.set(`${rebuilt.type}:${message.toolCallId??""}`,rebuilt)}return mergeAdjacentConfigurationUpdates(input.map(item=>byOriginal.get(item)??byCall.get(`${item.type}:${item.call_id??""}`)??item))}function coreToResponsesWithToolImages(messages,customToolCallIds=new Set){const out=[];let pending=[];const flush=()=>{if(pending.length===0)return;out.push(boundCarrier(pending));pending=[]};for(const message of systemToUser(messages,m2=>isRenderedSummaryMessage(m2))){const bound2=message;if(bound2[responsesPartBinding]&&message.role==="user"&&!isRenderedSummaryMessage(message)){if(pending.length&&pending[0][responsesPartBinding].source!==bound2[responsesPartBinding].source)flush();pending.push(bound2);continue}flush();const rebuilt=rebuildToolImages(message);out.push(...rebuilt?[rebuilt]:coreToResponses([message],customToolCallIds))}flush();return out}init_config();init_knobs();init_store();import{createHash as createHash21}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:${imageSigPart(m2.imageBase64)}`:"";return`${m2.role}|${m2.contentType}|${m2.toolName??""}|${text2}${img}`}function imageSigPart(v2){if(typeof v2==="string")return v2.length>0?sha256Hex2(v2).slice(0,24):"none";if(typeof v2==="object"&&v2!==null){const h=v2.$media;if(typeof h==="string"&&h.length>=24)return h.slice(0,24);try{return`s${sha256Hex2(JSON.stringify(v2)??"").slice(0,24)}`}catch{return"unserializable"}}return"none"}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=[];let bySeq=new Map;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"};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,retired:block.retired===true})}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 bySeq2=new Map;for(const row of contentRows){const msg=parseRow(row.content,row.seq,row.ts);if(!msg)return{reason:"row-unparsable"};bySeq2.set(row.seq,{seq:row.seq,msgId:row.msgId,msg})}let coveredSeen=0;for(const r of rows){const v2=bySeq2.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,retired}of blockSeeds){if(retired)continue;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=>createHash21("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();init_util();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",BILI_HOST_RECOVERY_OWNER_HEADER,"x-bili-pf-count","x-bili-pf-seq","x-bili-pf-tail-ids","x-bili-pf-delta","x-bili-turn-id","x-bili-msg-ids","x-bili-zed-lane","te","trailer","upgrade","expect"]);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 name2 of part.split(",")){const t=name2.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"||k2.toLowerCase()==="expect"||k2.toLowerCase()===BILI_HOST_RECOVERY_OWNER_HEADER)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 createSseFramer(){let pendingCr="";let lineParts=[];let frameParts=[];function*push(chunk){let text2=normalizeSseLineEndings(pendingCr+chunk);pendingCr=text2.endsWith("\r")?"\r":"";if(pendingCr)text2=text2.slice(0,-1);let start=0;let end;while((end=text2.indexOf("\n",start))!==-1){if(end>start)lineParts.push(text2.slice(start,end));if(lineParts.length===0&&frameParts.length>0){frameParts.pop();const frame=frameParts.join("");frameParts=[];yield frame}else{if(lineParts.length>0)frameParts.push(lineParts.join(""));frameParts.push("\n")}lineParts=[];start=end+1}if(start<text2.length)lineParts.push(text2.slice(start))}function*finish2(){if(pendingCr)yield*push("\n");const tail=[...frameParts,...lineParts].join("");frameParts=[];lineParts=[];if(tail.length>0)yield tail}return{push,finish:finish2}}function sseEventData(frame){const parts=[];for(const line of frame.split("\n")){if(line==="data")parts.push("");else if(line.startsWith("data:"))parts.push(line.slice(5).replace(/^ /,""))}return parts.length>0?parts.join("\n"):null}function replaceSseEventData(frame,data){const out=[];let replaced=false;for(const line of frame.split("\n")){if(line==="data"||line.startsWith("data:")){if(!replaced)for(const part of data.split("\n"))out.push(`data: ${part}`);replaced=true}else out.push(line)}return out.join("\n")}function*bufferedSseEvents(text2){let event="";let data=[];for(const line of finalizeSseLineEndings(text2).split("\n")){if(line===""){if(data.length)yield{event,data:data.join("\n")};event="";data=[]}else{const colon=line.indexOf(":");const field=colon<0?line:line.slice(0,colon);const value=colon<0?"":line.slice(colon+1).replace(/^ /,"");if(field==="event")event=value;else if(field==="data")data.push(value)}}if(data.length)yield{event,data:data.join("\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)}var XAI_RESPONSE_MISSING=/Response with id=\S+ not found/;function continuationRejected(error,status){if(error.code==="previous_response_not_found")return true;if(status===400&&(error.code===void 0||error.code==="invalid_request_error"))return true;const message=error.message;return error.type==="api_error"&&typeof message==="string"&&XAI_RESPONSE_MISSING.test(message)}function untypedErrorEnvelope(frame){if(!object2(frame)||typeof frame.type==="string"||!object2(frame.error))return void 0;return{frame,error:frame.error}}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.push(cursor);cursor=cursor.base}const base=levels[levels.length-1];if(!base||!Array.isArray(base.request.input))throw new Error("previous_response_not_found");const input=[];for(let i=levels.length-1;i>=0;i--){const level=levels[i];const added=i===levels.length-1?level.request.input:level.tail;if(Array.isArray(added))for(const item of added)input.push(item);for(const item of level.output)input.push(item)}for(const item of request.input)input.push(item);const{generate:_priorGenerate,...topRequest}=levels[0].request;return{...topRequest,...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}function cacheDiagnosticHash(text2){return createHash22("sha256").update(text2).digest("hex")}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;connectionGeneration=0;sendSequence=0;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.connectionGeneration++;this.key=key2;await new Promise((resolve3,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");resolve3()};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);const connection=this.connectionGeneration;const{input:_diagnosticInput,...settings}=body;const settingsHash=cacheDiagnosticHash(canonical({...settings,...egressTransportFields}));this.log("debug",`upstream request mode=${request.previous_response_id===void 0?"full":"delta"}`);return new Promise((resolve3,reject)=>{const output=new ResponsesWsOutput;let controller;let settled=false;let ended=false;let retryFull=request.previous_response_id!==void 0;let receivedEvents=0;let send=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)}`);send=++this.sendSequence;this.log("debug",`upstream cache-diagnostic ${JSON.stringify({phase:"send",connection,send,mode:payload.previous_response_id===void 0?"full":"delta",frame_sha256:cacheDiagnosticHash(frameText),settings_sha256:settingsHash,previous_response_id_sha256:typeof payload.previous_response_id==="string"?cacheDiagnosticHash(payload.previous_response_id):null})}`);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);const bare=untypedErrorEnvelope(frame);if(bare&&!settled){if(retryFull&&continuationRejected(bare.error,bare.frame.status)){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 bare.frame.status==="number"&&bare.frame.status>=400&&bare.frame.status<=599?bare.frame.status:400;this.log("warn",`upstream rejected phase=await-first-event status=${status}`);resolve3(new Response(JSON.stringify(bare.frame),{status,headers:{"content-type":"application/json"}}));return}if(!object2(frame)||typeof frame.type!=="string")throw new Error("Invalid Responses WebSocket event");receivedEvents++;if(["response.completed","response.failed","response.incomplete","error"].includes(frame.type)){const response=object2(frame.response)?frame.response:{};const usage=object2(response.usage)?response.usage:{};const details=object2(usage.input_tokens_details)?usage.input_tokens_details:{};const tokens=value=>typeof value==="number"&&Number.isFinite(value)?value:null;this.log("debug",`upstream cache-diagnostic ${JSON.stringify({phase:"terminal",connection,send,event:frame.type,response_id_sha256:typeof response.id==="string"?cacheDiagnosticHash(response.id):null,usage_present:Object.hasOwn(response,"usage"),input_tokens_details_present:Object.hasOwn(usage,"input_tokens_details"),input_tokens_present:Object.hasOwn(usage,"input_tokens"),input_tokens:tokens(usage.input_tokens),output_tokens_present:Object.hasOwn(usage,"output_tokens"),output_tokens:tokens(usage.output_tokens),cached_tokens_present:Object.hasOwn(details,"cached_tokens"),cached_tokens:tokens(details.cached_tokens)})}`)}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");resolve3(this.fetch(url,options,false));return}if(retryFull&&continuationRejected(error,frame.status)){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}`);resolve3(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);resolve3(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});resolve3(new Response(readable,{headers:{"content-type":"text/event-stream"}}))}const block=`event: ${frame.type}
|
|
1307
|
+
${extra}`:extra;return[{...head,content:merged},...messages.slice(1)]}return[{role:"system",content:extra},...messages]}function conversationSignalOpenai(body,headerValue3){if(headerValue3&&headerValue3.trim())return headerValue3.trim();const msgs=Array.isArray(body?.messages)?body.messages:[];const firstUser=msgs.find(m2=>m2?.role==="user");const seed=firstUser?stringContent(firstUser.content):"default";return hashId2(seed)}function isPlainStringOrTextParts(content){if(content==null||typeof content==="string")return true;return Array.isArray(content)&&content.length>0&&content.every(p2=>typeof p2==="object"&&p2!==null&&p2.type==="text")}function stringContent(content){if(content==null)return"";if(typeof content==="string")return content;if(Array.isArray(content)){return content.map(p2=>typeof p2==="string"?p2:p2.type==="text"?p2.text??"":"").join("\n")}return""}var OPAQUE_ITEM_TYPES=new Set(["additional_tools","mcp_list_tools"]);function isOpaqueItem(item){return OPAQUE_ITEM_TYPES.has(item.type)}var EASY_INPUT_ROLES=new Set(["user","assistant","system","developer"]);function normalizeEasyInputItem(item){if(typeof item.type==="string")return item;if(EASY_INPUT_ROLES.has(String(item.role))){return{...item,type:"message"}}return item}function shouldDropAllReasoning(){return(process.env.ACP_REASONING_KEEP??"").trim().toLowerCase()==="none"}function partText(part){if(part.type==="input_text"||part.type==="output_text"){return typeof part.text==="string"?part.text:""}return""}function responsesTextOf(content){if(typeof content==="string")return content;if(!Array.isArray(content))return"";return content.map(part=>part&&typeof part==="object"&&typeof part.text==="string"?part.text:"").join("\n")}function isPlainResponsesContent(content){if(content==null||typeof content==="string")return true;return Array.isArray(content)&&content.length>0&&content.every(p2=>p2&&typeof p2==="object"&&(p2.type==="input_text"||p2.type==="output_text")&&typeof p2.text==="string")}function messageContent(content){return typeof content==="string"?content:content.map(partText).join("\n")}function userDisplayText(content,text2){if(typeof content==="string")return text2;const hasImage=content.some(part=>part.type==="input_image");const hasTextPart=content.some(part=>part.type==="input_text"||part.type==="output_text");return!text2||hasImage&&!hasTextPart?"[image]":text2}function reasoningText(item){const fromParts=(parts,type)=>{if(!Array.isArray(parts))return"";const texts=[];for(const part of parts){if(part&&typeof part==="object"&&"type"in part&&"text"in part){const rec=part;if(rec.type===type&&typeof rec.text==="string")texts.push(rec.text)}}return texts.join("\n")};const content="content"in item?item.content:void 0;const summary="summary"in item?item.summary:void 0;return fromParts(content,"reasoning_text")||fromParts(summary,"summary_text")}function responsesToCore(body){const msgs=[];const systemParts=[];const preamble=[];const customToolCallIds=new Set;const layout=[];let droppedReasoning=0;const clusters=new ClusterCounter;const toolNames=new Map;let idx=0;if(typeof body.instructions==="string"&&body.instructions.trim())systemParts.push(body.instructions);if(typeof body.input==="string"){const id=clusters.next(deriveCanonicalMessageId("user","text",body.input));msgs.push({id,role:"user",contentType:"text",text:body.input});return{msgs,systemParts,preamble,customToolCallIds,layout,droppedReasoning,stringInput:{original:body.input,coreId:id}}}let sysDevHead=true;let headRole;for(const[wireIndex,raw]of body.input.entries()){const item=normalizeEasyInputItem(raw);let coreId;const before=msgs.length;if(isOpaqueItem(item))preamble.push(item);switch(item.type){case"reasoning":{if(shouldDropAllReasoning()){droppedReasoning++;continue}const text2=reasoningText(item);const rid=text2.length>0?text2:canonicalOpaqueSeed(item);coreId=clusters.next(deriveCanonicalMessageId("assistant","reasoning",rid));msgs.push({id:coreId,role:"assistant",contentType:"reasoning",text:rid,rawResponsesItem:item});break}case"message":{const message=item;const text2=messageContent(message.content);if(message.role==="system"||message.role==="developer"){if(sysDevHead){headRole??=message.role;systemParts.push(text2);idx++;continue}const midBase=deriveCanonicalMessageId(message.role,"text",text2);msgs.push({id:clusters.next(midBase),role:"system",contentType:"text",text:text2,originalRole:message.role,rawResponsesItem:item});break}else if(message.role==="user"||message.role==="assistant"&&text2){const role2=message.role;const splittable=role2==="user"&&Array.isArray(message.content)&&message.content.length>1&&message.content.every(part=>typeof part==="object"&&part!==null&&(part.type==="input_text"||part.type==="output_text"||part.type==="input_image"));if(splittable){for(const rawPart of message.content){const part=typeof rawPart==="object"&&rawPart!==null?rawPart:void 0;if(!part)continue;if((part.type==="input_text"||part.type==="output_text")&&typeof part.text==="string"&&part.text.length>0){const base=deriveCanonicalMessageId("user","text",part.text);msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:part.text})}else if(part.type==="input_image"&&typeof part.image_url==="string"){const image=parseDataUrl(part.image_url);const base=deriveCanonicalMessageId("user","text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:imageMediaFingerprint(image?image.base64:part.image_url)});msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawResponsesItem:item,rawResponseImagePart:{...part,type:"input_image",image_url:part.image_url},...image?{imageMediaType:image.mediaType,imageBase64:image.base64}:{}})}}break}let effText=text2;if(role2==="assistant"){const split=splitDemotedThinking(text2);if(split){msgs.push({id:clusters.next(deriveCanonicalMessageId("assistant","reasoning",split.reasoning)),role:"assistant",contentType:"reasoning",text:split.reasoning,rawResponsesItem:item});effText=split.text}}const hasImage=Array.isArray(message.content)&&message.content.some(part=>part.type==="input_image");if(effText||role2==="user"&&hasImage){const displayText=role2==="user"?userDisplayText(message.content,effText):effText;const mediaFingerprint=Array.isArray(message.content)?message.content.flatMap(part=>{if(part?.type==="input_image"&&typeof part.image_url==="string"){const raw2=part.image_url;const decoded=parseDataUrl(raw2);return[imageMediaFingerprint(decoded?decoded.base64:raw2)]}return[]}).join(",")||void 0:void 0;coreId=clusters.next(deriveCanonicalMessageId(role2,"text",displayText,{mediaFingerprint}));const imageUrl=Array.isArray(message.content)?message.content.find(part=>part.type==="input_image"&&typeof part.image_url==="string")?.image_url:void 0;const image=typeof imageUrl==="string"?parseDataUrl(imageUrl):void 0;msgs.push({id:coreId,role:role2,contentType:"text",text:displayText,rawResponsesItem:item,...image?{imageMediaType:image.mediaType,imageBase64:image.base64}:{}})}}break}case"function_call":{const call=item;coreId=clusters.next(deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(call.arguments??""),{toolName:call.name}));msgs.push({id:coreId,role:"assistant",contentType:"tool-call",toolName:call.name,toolCallId:call.call_id,text:call.arguments??"",rawResponsesItem:item});toolNames.set(call.call_id,call.name);break}case"function_call_output":{const output=item;const text2=typeof output.output==="string"?output.output:JSON.stringify(output.output);coreId=clusters.next(deriveCanonicalMessageId("tool","tool-result",text2,{toolName:toolNames.get(output.call_id)}));const name2=toolNames.get(output.call_id);msgs.push({id:coreId,role:"tool",contentType:"tool-result",toolCallId:output.call_id,text:text2,...name2?{toolName:name2}:{},rawResponsesItem:item});break}case"computer_call":case"computer_call_output":case"file_search_call":case"web_search_call":case"image_generation_call":case"code_interpreter_call":case"mcp_call":{const rid=canonicalOpaqueSeed(item);coreId=clusters.next(deriveCanonicalMessageId("assistant","responses-call",rid));msgs.push({id:coreId,role:"assistant",contentType:"reasoning",text:rid,rawResponsesItem:item});break}case"custom_tool_call":{const ctc=item;const callId=ctc.call_id??`call_${idx}`;customToolCallIds.add(callId);const argText=ctc.input??ctc.arguments??"";coreId=clusters.next(deriveCanonicalMessageId("assistant","tool-call",argText,{toolName:ctc.name??"custom"}));msgs.push({id:coreId,role:"assistant",contentType:"tool-call",toolName:ctc.name??"custom",toolCallId:callId,text:argText,rawResponsesItem:item});toolNames.set(callId,ctc.name??"custom");break}case"custom_tool_call_output":{const ctco=item;const callId=ctco.call_id??`call_${idx}`;customToolCallIds.add(callId);const outText=typeof ctco.output==="string"?ctco.output:JSON.stringify(ctco.output??"");coreId=clusters.next(deriveCanonicalMessageId("tool","tool-result",outText,{toolName:toolNames.get(callId)}));const name2=toolNames.get(callId);msgs.push({id:coreId,role:"tool",contentType:"tool-result",toolCallId:callId,text:outText,...name2?{toolName:name2}:{},rawResponsesItem:item});break}default:if(!isOpaqueItem(item))preamble.push(item);break}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}const role=item.role;const isSysDevMsgItem=(item.type===void 0||item.type==="message")&&(role==="system"||role==="developer");if(!isSysDevMsgItem&&item.type!=="additional_tools"&&item.type!=="mcp_list_tools")sysDevHead=false;const produced=msgs.slice(before).map(m2=>m2.id);layout.push({original:item,...produced.length>0?{coreId:produced[0]}:{},...produced.length>1?{coreIds:produced}:{}});idx++}return{msgs,systemParts,preamble,customToolCallIds,layout,droppedReasoning,...headRole?{headRole}:{}}}function patchTextParts(parts,text2){const textIndexes=parts.flatMap((part,index)=>part.type==="input_text"||part.type==="output_text"?[index]:[]);if(textIndexes.length===0)return[{type:"input_text",text:text2},...parts];const first=textIndexes[0];const remaining=new Set(textIndexes.slice(1));const out=[];for(let index=0;index<parts.length;index++){const part=parts[index];if(!part||remaining.has(index))continue;out.push(index===first?{...part,text:text2}:part)}return out}function patchOriginalItem(original,source,next){if(source.text===next.text&&source.toolName===next.toolName&&source.toolCallId===next.toolCallId&&source.role===next.role&&source.contentType===next.contentType)return original;if(original.type==="message"){const message=original;const content=typeof message.content==="string"?next.text??"":patchTextParts(message.content,next.text??"");return{...message,content}}if(original.type==="function_call"){return{...original,name:next.toolName??String(original.name??"unknown"),call_id:next.toolCallId??String(original.call_id??""),arguments:next.text??""}}if(original.type==="function_call_output"){return{...original,call_id:next.toolCallId??String(original.call_id??""),output:next.text??""}}return original}function patchResponsesInput(projection,messages){if(projection.stringInput){const original=projection.msgs.find(message=>message.id===projection.stringInput?.coreId);const next=messages.find(message=>message.id===projection.stringInput?.coreId);if(original&&next&&messages.length===1&&next.role==="user"&&next.contentType==="text"){return next.text===original.text?projection.stringInput.original:next.text??""}return coreToResponses(messages,projection.customToolCallIds)}const sourceById=new Map(projection.msgs.map(message=>[message.id,message]));const nextById=new Map(messages.map(message=>[message.id,message]));const slotById=new Map;projection.layout.forEach((slot,index)=>{if(slot.coreId)slotById.set(slot.coreId,index)});const insertions=new Map;for(let index=0;index<messages.length;index++){const message=messages[index];if(sourceById.has(message.id))continue;let target=projection.layout.length;for(let nextIndex=index+1;nextIndex<messages.length;nextIndex++){const slot=slotById.get(messages[nextIndex].id);if(slot!==void 0){target=slot;break}}const generated=coreToResponses([message],projection.customToolCallIds);if(generated.length>0)insertions.set(target,[...insertions.get(target)??[],...generated])}const out=[];projection.layout.forEach((slot,index)=>{out.push(...insertions.get(index)??[]);if(slot.coreIds&&slot.coreIds.length>1){const entries2=slot.coreIds.map(id=>({core:sourceById.get(id),next:nextById.get(id)}));if(entries2.every(entry=>entry.next===void 0))return;const original=slot.original;const allSurvive=entries2.every(entry=>entry.next!==void 0);const changed=entries2.some(entry=>entry.core&&entry.next&&(entry.core.text??"")!==(entry.next.text??""));if(allSurvive&&!changed){out.push(slot.original);return}const imageParts=Array.isArray(original.content)?original.content.filter(part=>part.type==="input_image"):[];let img=0;const parts=[];for(const entry of entries2){if(!entry.next)continue;const bili=entry.next;if(entry.core?.imagePart||bili.text===CANONICAL_IMAGE_TEXT){const part=entry.core?.rawResponseImagePart??imageParts[img++];if(!part)throw new Error("coreToResponses: image core without a source part \u2014 refusing to drop content (#7824)");parts.push(part)}else if(bili.text){parts.push({type:"input_text",text:bili.text})}}if(parts.length>0)out.push({...original,content:parts});return}if(!slot.coreId){out.push(slot.original);return}const source=sourceById.get(slot.coreId);const next=nextById.get(slot.coreId);if(source&&next)out.push(patchOriginalItem(slot.original,source,next))});out.push(...insertions.get(projection.layout.length)??[]);return out}function coreToResponses(messages,customToolCallIds=new Set){const out=[];const flushUserRun=run=>{if(run.length===0)return;if(run.length===1){const message=run[0];const raw=message.rawResponsesItem;const rawMessage2=raw?.type==="message"?raw:void 0;if(rawMessage2&&userDisplayText(rawMessage2.content,messageContent(rawMessage2.content))===(message.text??""))out.push(rawMessage2);else if((message.imagePart||message.text===CANONICAL_IMAGE_TEXT)&&rawMessage2&&Array.isArray(rawMessage2.content))out.push({type:"message",role:"user",content:rawMessage2.content.filter(part=>part.type==="input_image")});else if((message.imagePart||message.text===CANONICAL_IMAGE_TEXT)&&message.imageBase64&&message.imageMediaType)out.push({type:"message",role:"user",content:[{type:"input_image",image_url:`data:${message.imageMediaType};base64,${message.imageBase64}`}]});else out.push({type:"message",role:"user",content:message.text??""});return}const rawCarrier=run.find(m2=>m2.rawResponsesItem!==void 0);const rawItem=rawCarrier?.rawResponsesItem;const rawMessage=rawItem?.type==="message"?rawItem:void 0;if(run.every(m2=>m2.rawResponsesItem!==void 0)){const seen=new Set;const distinctItems=[];for(const m2 of run){const it2=m2.rawResponsesItem;if(it2.type==="message"&&!seen.has(it2)){seen.add(it2);distinctItems.push(it2)}}if(distinctItems.length>1){out.push(...distinctItems);return}}const fullCover=rawMessage&&Array.isArray(rawMessage.content)&&rawMessage.content.length===run.length;if(fullCover&&rawMessage){out.push(rawMessage);return}const imageParts=rawMessage&&Array.isArray(rawMessage.content)?rawMessage.content.filter(part=>part.type==="input_image"):[];let img=0;const parts=[];for(const message of run){const bili=message;if(bili.imagePart&&bili.rawResponsesItem){const part=bili.rawResponseImagePart??imageParts[img++];if(!part)throw new Error("coreToResponses: image core without a source part \u2014 refusing to drop content (#7824)");parts.push(part)}else if(bili.imagePart&&bili.imageBase64&&bili.imageMediaType){parts.push({type:"input_image",image_url:`data:${bili.imageMediaType};base64,${bili.imageBase64}`})}else if(bili.text){parts.push({type:"input_text",text:bili.text})}}out.push({type:"message",role:"user",content:parts.length>0?parts:""})};let userRun=[];for(const message of messages){if(message.role==="user"){userRun.push(message);continue}flushUserRun(userRun);userRun=[];const biliMessage=message;const raw=biliMessage.rawResponsesItem;if(message.role==="system"){const rawMsg=raw;const isSysDevRaw=rawMsg!=null&&(rawMsg.type===void 0||rawMsg.type==="message")&&(rawMsg.role==="system"||rawMsg.role==="developer");if(isSysDevRaw){const text2=message.text??"";if(text2!==responsesTextOf(rawMsg.content)&&isPlainResponsesContent(rawMsg.content)){out.push({type:"message",role:rawMsg.role,content:typeof rawMsg.content==="string"?text2:[{type:"input_text",text:text2}]})}else{out.push(raw)}}else{out.push({type:"message",role:"developer",content:message.text??""})}}else if(message.role==="assistant"){if(message.contentType==="text"){out.push({type:"message",role:"assistant",content:message.text??""})}else if(message.contentType==="tool-call"){const callId=message.toolCallId??`call_${message.id}`;if(customToolCallIds.has(callId)){out.push({type:"custom_tool_call",call_id:callId,name:message.toolName??"unknown",input:message.text??"",status:"completed"})}else{out.push({type:"function_call",call_id:callId,name:message.toolName??"unknown",arguments:message.text??""})}}else if(message.contentType==="reasoning"){if(raw)out.push(raw);else if((message.text??"").trim().length>0){out.push({type:"message",role:"assistant",content:message.text??""})}}}else if(message.role==="tool"){const callId=message.toolCallId??"";if(customToolCallIds.has(callId)){out.push({type:"custom_tool_call_output",call_id:callId,output:message.text??""})}else{out.push({type:"function_call_output",call_id:callId,output:message.text??""})}}}flushUserRun(userRun);return out}function injectResponsesDeveloperMessage(input,content,role="developer"){const items=typeof input==="string"?[{type:"message",role:"user",content:input}]:[...input];let index=0;while(items[index]?.type==="additional_tools")index++;items.splice(index,0,{type:"message",role,content});return items}function conversationIdentityResponses(body,headerValue3){if(headerValue3?.trim())return{value:headerValue3.trim(),source:"header",clientProvided:true};if(typeof body.session_id==="string"&&body.session_id.trim()){return{value:body.session_id.trim(),source:"body-session",clientProvided:true}}const metadataSession=body.metadata?.session_id;if(typeof metadataSession==="string"&&metadataSession.trim()){return{value:metadataSession.trim(),source:"metadata-session",clientProvided:true}}if(typeof body.previous_response_id==="string"&&body.previous_response_id.trim()){return{value:body.previous_response_id.trim(),source:"previous-response",clientProvided:false}}return{value:hashId2(JSON.stringify(body.input??[])),source:"content-fingerprint",clientProvided:false}}function conversationSignalResponses(body,headerValue3){return conversationIdentityResponses(body,headerValue3).value}function createSubagentNamespaces(){const anchors=new Map;return{namespaceFor(identityValue,instructions){if(typeof instructions!=="string"||instructions.trim().length===0)return identityValue;const fp2=hashId2(instructions);const anchor=anchors.get(identityValue);if(anchor===void 0){anchors.set(identityValue,fp2);return identityValue}return anchor===fp2?identityValue:`${identityValue}|sub:${fp2}`}}}var defaultNamespaces=createSubagentNamespaces();function googleSystemText(body){const parts=body.systemInstruction?.parts;if(!Array.isArray(parts))return"";const texts=[];for(const part of parts){if(typeof part.text==="string"&&part.text.length>0)texts.push(part.text)}return texts.join("\n\n")}function googleToCore(body){const msgs=[];const clusters=new ClusterCounter;const unmatchedCalls=new Map;const contents=Array.isArray(body.contents)?body.contents:[];for(const[contentIndex,content]of contents.entries()){const before=msgs.length;const parts=Array.isArray(content.parts)?content.parts:[];const isModel=content.role==="model";for(const part of parts){const fr2=part.functionResponse;if(!fr2||typeof fr2.name!=="string")continue;const response=fr2.response??{};const text2=response&&typeof response==="object"&&!Array.isArray(response)&&Object.keys(response).length===1&&typeof response.output==="string"?response.output:jsonText(response);const wireId=typeof fr2.id==="string"?fr2.id:void 0;const queue=unmatchedCalls.get(fr2.name);let paired;if(wireId){const i=queue?queue.indexOf(wireId):-1;if(queue&&i>=0)queue.splice(i,1)}else if(queue&&queue.length>0){paired=queue.shift()}const base=deriveCanonicalMessageId("tool","tool-result",text2,{toolName:fr2.name});const id=clusters.next(base);msgs.push({id,role:"tool",contentType:"tool-result",toolName:fr2.name,toolCallId:wireId??paired??id,text:text2,rawGoogleParts:[part]})}for(const part of parts){if(part.thought!==true||typeof part.text!=="string")continue;const base=deriveCanonicalMessageId("assistant","reasoning",part.text);msgs.push({id:clusters.next(base),role:"assistant",contentType:"reasoning",text:part.text,rawGoogleParts:[part],...signatureField("googleThoughtSignature",part.thoughtSignature)})}const rest=parts.filter(isContentPart);let lastTextCore=null;let leftover=[];for(const part of rest){if(typeof part.text==="string"&&part.thought!==true){const base=deriveCanonicalMessageId(isModel?"assistant":"user","text",part.text);lastTextCore={id:clusters.next(base),role:isModel?"assistant":"user",contentType:"text",text:part.text,rawGoogleParts:[part],...signatureField("googleThoughtSignature",part.thoughtSignature)};msgs.push(lastTextCore);continue}const inline=part.inlineData;if(inline&&typeof inline.mimeType==="string"&&typeof inline.data==="string"){const base=deriveCanonicalMessageId(isModel?"assistant":"user","text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:imageMediaFingerprint(inline.data)});msgs.push({id:clusters.next(base),role:isModel?"assistant":"user",contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,imageMediaType:inline.mimeType,imageBase64:inline.data,rawGoogleParts:[part]});continue}if(lastTextCore){lastTextCore.rawGoogleParts=[...lastTextCore.rawGoogleParts??[],part]}else{leftover=[...leftover,part]}}if(leftover.length>0){const text2=textPartsOf(leftover).map(p2=>p2.text??"").join("\n");const base=deriveCanonicalMessageId(isModel?"assistant":"user","text",text2);msgs.push({id:clusters.next(base),role:isModel?"assistant":"user",contentType:"text",text:text2,rawGoogleParts:leftover})}for(const part of parts){const fc=part.functionCall;if(!fc||typeof fc.name!=="string")continue;const text2=jsonText(fc.args??{});const wireId=typeof fc.id==="string"?fc.id:void 0;const base=deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(text2),{toolName:fc.name});const id=clusters.next(base);const toolCallId=wireId??id;const queue=unmatchedCalls.get(fc.name);if(queue)queue.push(toolCallId);else unmatchedCalls.set(fc.name,[toolCallId]);msgs.push({id,role:"assistant",contentType:"tool-call",toolName:fc.name,toolCallId,text:text2,rawGoogleParts:[part],...signatureField("googleThoughtSignature",part.thoughtSignature)})}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=contentIndex}}return{msgs,systemText:googleSystemText(body)}}var CLAUDE_WIRE_MODEL=/claude/i;function normalizeGoogleUserPartOrder(parts,opts){if(opts&&typeof opts.model==="string"&&CLAUDE_WIRE_MODEL.test(opts.model))return parts;const firstFr=parts.findIndex(p2=>p2.functionResponse!==void 0);if(firstFr===-1)return parts;const movable=p2=>typeof p2.text==="string"&&p2.thought!==true&&typeof p2.thoughtSignature!=="string";let reorder=false;for(let i=firstFr;i<parts.length;i++){if(movable(parts[i])){reorder=true;break}}if(!reorder)return parts;const moved=[];const rest=[];for(const p2 of parts)(movable(p2)?moved:rest).push(p2);return[...moved,...rest]}function coreToGoogle(messages,opts){const out=[];let model=null;let user=null;const flushModel=()=>{if(!model)return;const parts=[...model.reasoning,...model.text,...model.calls];model=null;if(parts.length>0)out.push({role:"model",parts})};const flushUser=()=>{if(!user)return;const parts=normalizeGoogleUserPartOrder([...user.responses,...user.content],{model:opts?.model});user=null;if(parts.length>0)out.push({role:"user",parts})};for(const m2 of messages){if(m2.role==="assistant"){flushUser();if(!model)model={reasoning:[],text:[],calls:[]};if(m2.contentType==="reasoning"){const rp=reasoningPart(m2);if(rp)model.reasoning.push(rp)}else if(m2.contentType==="tool-call")model.calls.push(toolCallPart(m2));else model.text.push(...contentParts(m2))}else{flushModel();if(!user)user={responses:[],content:[]};if(m2.role==="tool"||m2.contentType==="tool-result")user.responses.push(...toolResultParts(m2));else user.content.push(...contentParts(m2))}}flushModel();flushUser();return out}function conversationSignalGoogle(body,headerValue3){if(headerValue3&&headerValue3.trim())return headerValue3.trim();const contents=Array.isArray(body.contents)?body.contents:[];const firstUser=contents.find(c=>c.role!=="model");const parts=firstUser&&Array.isArray(firstUser.parts)?firstUser.parts:[];const seed=firstUser?parts.map(p2=>typeof p2.text==="string"?p2.text:"").join("\n"):"default";return hashId2(seed)}function reasoningPart(m2){const text2=m2.text??"";const head=rawParts(m2)[0];if(head)return{...head,text:text2,thought:true};if(m2.googleThoughtSignature)return{text:text2,thought:true,...signatureField("thoughtSignature",m2.googleThoughtSignature)};return text2?{text:text2}:void 0}function toolCallPart(m2){const head=rawParts(m2)[0];if(head&&head.functionCall)return head;return{functionCall:{name:m2.toolName??"unknown",args:jsonValue(m2.text),...m2.toolCallId?{id:m2.toolCallId}:{}},...signatureField("thoughtSignature",m2.googleThoughtSignature)}}function toolResultParts(m2){const raw=rawParts(m2);if(raw.length>0&&raw.every(p2=>p2.functionResponse))return raw;return[{functionResponse:{name:m2.toolName??"unknown",response:jsonValue(m2.text),...m2.toolCallId?{id:m2.toolCallId}:{}}}]}function contentParts(m2){const text2=m2.text??"";const raw=rawParts(m2);if(raw.length===0){const parts2=text2&&text2!==CANONICAL_IMAGE_TEXT&&!m2.imagePart?[{text:text2,...signatureField("thoughtSignature",m2.googleThoughtSignature)}]:[];if(m2.imageBase64&&m2.imageMediaType)parts2.push({inlineData:{mimeType:m2.imageMediaType,data:m2.imageBase64}});return parts2}const rawTexts=textPartsOf(raw);if(rawTexts.map(p2=>p2.text??"").join("\n")===text2)return raw;const parts=text2&&text2!==CANONICAL_IMAGE_TEXT&&!m2.imagePart?[{text:text2,...signatureField("thoughtSignature",m2.googleThoughtSignature)}]:[];for(const part of raw){if(!rawTexts.includes(part))parts.push(part)}return parts}function rawParts(m2){const raw=m2.rawGoogleParts;if(!Array.isArray(raw))return[];const out=[];for(const item of raw){if(typeof item==="object"&&item!==null)out.push(item)}return out}function textPartsOf(parts){return parts.filter(p2=>typeof p2.text==="string"&&p2.thought!==true)}function isContentPart(part){if(part.functionCall!==void 0||part.functionResponse!==void 0)return false;if(part.thought===true&&typeof part.text==="string")return false;return true}function signatureField(key2,signature){return typeof signature==="string"?{[key2]:signature}:{}}function jsonText(value){try{return JSON.stringify(value)??""}catch{return""}}function jsonValue(text2){if(!text2)return{};try{const value=JSON.parse(text2);return value===null?{}:value}catch{return{output:text2}}}function detectWireFormat(payload){if(payload===null||typeof payload!=="object")return void 0;const p2=payload;if(Array.isArray(p2.contents))return"google";if(Array.isArray(p2.input))return"responses";const messages=p2.messages;if(!Array.isArray(messages))return void 0;if("system"in p2||"anthropic_version"in p2)return"anthropic";for(const m2 of messages){if(m2===null||typeof m2!=="object")continue;const c=m2.content;if(Array.isArray(c)){for(const b2 of c){if(b2&&typeof b2==="object"&&typeof b2.type==="string"){if(b2.type==="tool_use"||b2.type==="tool_result"||b2.type==="thinking")return"anthropic";if(b2.type==="text"&&"cache_control"in b2)return"anthropic"}}}if(Array.isArray(m2.tool_calls))return"openai";if(m2.role==="tool"&&typeof m2.tool_call_id==="string")return"openai";if(m2.role==="system"||m2.role==="developer")return"openai"}return"openai"}init_dist();init_util();var responsesPartBinding=Symbol("responsesPartBinding");function responsesToolImageParts(item){if(typeof item!=="object"||item===null)return void 0;const raw=item;if(raw.type!=="function_call_output"&&raw.type!=="custom_tool_call_output")return void 0;if(!Array.isArray(raw.output))return void 0;let hasImage=false;for(const part of raw.output){if(typeof part!=="object"||part===null)return void 0;if(part.type==="input_text"&&typeof part.text==="string")continue;if(part.type==="input_image"&&typeof part.image_url==="string"){hasImage=true;continue}return void 0}return hasImage?raw.output:void 0}function outputText(parts){return parts.filter(part=>part.type==="input_text").map(part=>part.text).join("\n")}function responsesToCoreWithToolImages(body){const projection=responsesToCore(body);const byId2=new Map(projection.msgs.map(message=>[message.id,message]));for(const slot of projection.layout){const source=slot.original;if(source.role!=="user"||!Array.isArray(source.content))continue;const parts=source.content;if(!parts.every(part=>part.type==="input_image"||part.type==="input_text"||part.type==="output_text"))continue;const emitted=parts.filter(part=>part.type==="input_image"||typeof part.text==="string"&&part.text.length>0);const ids=slot.coreIds??(slot.coreId?[slot.coreId]:[]);if(ids.length!==emitted.length)continue;ids.forEach((id,index)=>{const message=byId2.get(id);if(message)message[responsesPartBinding]={source,part:emitted[index],sourceId:id}})}for(const message of projection.msgs){const parts=responsesToolImageParts(message.rawResponsesItem);if(parts)message.text=outputText(parts)}return projection}function rebuildToolImages(message){if(message.role!=="tool"||message.contentType!=="tool-result")return void 0;const raw=message.rawResponsesItem;const parts=responsesToolImageParts(raw);if(!raw||!parts)return void 0;const text2=message.text??"";if(text2===outputText(parts)&&message.toolCallId===raw.call_id)return raw;let written=false;const output=parts.map(part=>{if(part.type!=="input_text")return part;const next={...part,text:written?"":text2};written=true;return next});if(!written&&text2)output.unshift({type:"input_text",text:text2});return{...raw,call_id:message.toolCallId??raw.call_id,output}}function isPlainRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function foldConfigurationFields(base,overlay){const out={...base};for(const[key2,value]of Object.entries(overlay)){if(isPlainRecord(out[key2])&&isPlainRecord(value))out[key2]=foldConfigurationFields(out[key2],value);else out[key2]=value}return out}function mergeAdjacentConfigurationUpdates(items){const out=[];for(const item of items){const prev=out[out.length-1];if(item.type==="configuration_update"&&prev!==void 0&&prev.type==="configuration_update"){const base={};for(const[key2,value]of Object.entries(prev))base[key2]=value;out[out.length-1]=foldConfigurationFields(base,item)}else{out.push(item)}}return out}function boundCarrier(messages){const source=messages[0][responsesPartBinding].source;const parts=messages.map(message=>{const part=message[responsesPartBinding].part;return part.type==="input_image"||part.text===message.text?part:{...part,text:message.text??""}});const original=source.content;const unchanged=Array.isArray(original)&&original.length===parts.length&&parts.every((part,index)=>part===original[index]);return unchanged?source:{type:"message",role:"user",content:parts}}function boundProjection(projection,messages){const runs=new Map;let previous;for(const message of messages){const bound2=message;const binding=bound2[responsesPartBinding];if(!binding||message.role!=="user"||isRenderedSummaryMessage(message)){previous=void 0;continue}const groups=runs.get(binding.source)??[];if(previous?.[responsesPartBinding]?.source===binding.source)groups.at(-1).push(bound2);else groups.push([bound2]);runs.set(binding.source,groups);previous=bound2}const sources2=new Map(projection.msgs.map(message=>[message.id,message]));const replaced=new Set;const rebound=[];const layout=projection.layout.flatMap(slot=>{const groups=runs.get(slot.original);if(!groups)return[slot];for(const id of slot.coreIds??(slot.coreId?[slot.coreId]:[]))replaced.add(id);return groups.map(group=>{for(const message of group){const source=sources2.get(message[responsesPartBinding].sourceId);if(source)rebound.push({...source,id:message.id,text:message.text})}const ids=group.map(message=>message.id);return{original:boundCarrier(group),coreId:ids[0],...ids.length>1?{coreIds:ids}:{}}})});return{...projection,layout,msgs:[...projection.msgs.filter(message=>!replaced.has(message.id)),...rebound]}}function patchResponsesInputWithToolImages(projection,messages){const voiced=systemToUser(messages,m2=>isRenderedSummaryMessage(m2));const input=patchResponsesInput(boundProjection(projection,voiced),voiced);if(typeof input==="string")return input;const byOriginal=new Map;const byCall=new Map;for(const message of voiced){const rebuilt=rebuildToolImages(message);if(!rebuilt)continue;byOriginal.set(message.rawResponsesItem,rebuilt);byCall.set(`${rebuilt.type}:${message.toolCallId??""}`,rebuilt)}return mergeAdjacentConfigurationUpdates(input.map(item=>byOriginal.get(item)??byCall.get(`${item.type}:${item.call_id??""}`)??item))}function coreToResponsesWithToolImages(messages,customToolCallIds=new Set){const out=[];let pending=[];const flush=()=>{if(pending.length===0)return;out.push(boundCarrier(pending));pending=[]};for(const message of systemToUser(messages,m2=>isRenderedSummaryMessage(m2))){const bound2=message;if(bound2[responsesPartBinding]&&message.role==="user"&&!isRenderedSummaryMessage(message)){if(pending.length&&pending[0][responsesPartBinding].source!==bound2[responsesPartBinding].source)flush();pending.push(bound2);continue}flush();const rebuilt=rebuildToolImages(message);out.push(...rebuilt?[rebuilt]:coreToResponses([message],customToolCallIds))}flush();return out}init_config();init_knobs();init_store();import{createHash as createHash21}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:${imageSigPart(m2.imageBase64)}`:"";return`${m2.role}|${m2.contentType}|${m2.toolName??""}|${text2}${img}`}function imageSigPart(v2){if(typeof v2==="string")return v2.length>0?sha256Hex2(v2).slice(0,24):"none";if(typeof v2==="object"&&v2!==null){const h=v2.$media;if(typeof h==="string"&&h.length>=24)return h.slice(0,24);try{return`s${sha256Hex2(JSON.stringify(v2)??"").slice(0,24)}`}catch{return"unserializable"}}return"none"}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=[];let bySeq=new Map;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"};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,retired:block.retired===true})}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 bySeq2=new Map;for(const row of contentRows){const msg=parseRow(row.content,row.seq,row.ts);if(!msg)return{reason:"row-unparsable"};bySeq2.set(row.seq,{seq:row.seq,msgId:row.msgId,msg})}let coveredSeen=0;for(const r of rows){const v2=bySeq2.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,retired}of blockSeeds){if(retired)continue;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 attachHandoffReplyTimestamps(session,msgs){const stash=session.metadata["handoffReply"];const rows=stash?.rows;if(!rows||rows.length===0)return;const tsById=new Map;for(const row of rows)if(typeof row.ts==="number")tsById.set(row.msgId,row.ts);if(tsById.size===0)return;for(const m2 of msgs){if(m2.ts===void 0&&tsById.has(m2.id))m2.ts=tsById.get(m2.id)}}function maybeSnapshotView(session,clientMsgs,deps){const view=maybeSnapshotViewInner(session,clientMsgs,deps);attachHandoffReplyTimestamps(session,view);return view}function maybeSnapshotViewInner(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=>createHash21("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();init_util();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",BILI_HOST_RECOVERY_OWNER_HEADER,"x-bili-pf-count","x-bili-pf-seq","x-bili-pf-tail-ids","x-bili-pf-delta","x-bili-turn-id","x-bili-msg-ids","x-bili-zed-lane","te","trailer","upgrade","expect"]);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 name2 of part.split(",")){const t=name2.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"||k2.toLowerCase()==="expect"||k2.toLowerCase()===BILI_HOST_RECOVERY_OWNER_HEADER)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 createSseFramer(){let pendingCr="";let lineParts=[];let frameParts=[];function*push(chunk){let text2=normalizeSseLineEndings(pendingCr+chunk);pendingCr=text2.endsWith("\r")?"\r":"";if(pendingCr)text2=text2.slice(0,-1);let start=0;let end;while((end=text2.indexOf("\n",start))!==-1){if(end>start)lineParts.push(text2.slice(start,end));if(lineParts.length===0&&frameParts.length>0){frameParts.pop();const frame=frameParts.join("");frameParts=[];yield frame}else{if(lineParts.length>0)frameParts.push(lineParts.join(""));frameParts.push("\n")}lineParts=[];start=end+1}if(start<text2.length)lineParts.push(text2.slice(start))}function*finish2(){if(pendingCr)yield*push("\n");const tail=[...frameParts,...lineParts].join("");frameParts=[];lineParts=[];if(tail.length>0)yield tail}return{push,finish:finish2}}function sseEventData(frame){const parts=[];for(const line of frame.split("\n")){if(line==="data")parts.push("");else if(line.startsWith("data:"))parts.push(line.slice(5).replace(/^ /,""))}return parts.length>0?parts.join("\n"):null}function replaceSseEventData(frame,data){const out=[];let replaced=false;for(const line of frame.split("\n")){if(line==="data"||line.startsWith("data:")){if(!replaced)for(const part of data.split("\n"))out.push(`data: ${part}`);replaced=true}else out.push(line)}return out.join("\n")}function*bufferedSseEvents(text2){let event="";let data=[];for(const line of finalizeSseLineEndings(text2).split("\n")){if(line===""){if(data.length)yield{event,data:data.join("\n")};event="";data=[]}else{const colon=line.indexOf(":");const field=colon<0?line:line.slice(0,colon);const value=colon<0?"":line.slice(colon+1).replace(/^ /,"");if(field==="event")event=value;else if(field==="data")data.push(value)}}if(data.length)yield{event,data:data.join("\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)}var XAI_RESPONSE_MISSING=/Response with id=\S+ not found/;function continuationRejected(error,status){if(error.code==="previous_response_not_found")return true;if(status===400&&(error.code===void 0||error.code==="invalid_request_error"))return true;const message=error.message;return error.type==="api_error"&&typeof message==="string"&&XAI_RESPONSE_MISSING.test(message)}function untypedErrorEnvelope(frame){if(!object2(frame)||typeof frame.type==="string"||!object2(frame.error))return void 0;return{frame,error:frame.error}}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.push(cursor);cursor=cursor.base}const base=levels[levels.length-1];if(!base||!Array.isArray(base.request.input))throw new Error("previous_response_not_found");const input=[];for(let i=levels.length-1;i>=0;i--){const level=levels[i];const added=i===levels.length-1?level.request.input:level.tail;if(Array.isArray(added))for(const item of added)input.push(item);for(const item of level.output)input.push(item)}for(const item of request.input)input.push(item);const{generate:_priorGenerate,...topRequest}=levels[0].request;return{...topRequest,...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}function cacheDiagnosticHash(text2){return createHash22("sha256").update(text2).digest("hex")}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;connectionGeneration=0;sendSequence=0;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.connectionGeneration++;this.key=key2;await new Promise((resolve3,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");resolve3()};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);const connection=this.connectionGeneration;const{input:_diagnosticInput,...settings}=body;const settingsHash=cacheDiagnosticHash(canonical({...settings,...egressTransportFields}));this.log("debug",`upstream request mode=${request.previous_response_id===void 0?"full":"delta"}`);return new Promise((resolve3,reject)=>{const output=new ResponsesWsOutput;let controller;let settled=false;let ended=false;let retryFull=request.previous_response_id!==void 0;let receivedEvents=0;let send=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)}`);send=++this.sendSequence;this.log("debug",`upstream cache-diagnostic ${JSON.stringify({phase:"send",connection,send,mode:payload.previous_response_id===void 0?"full":"delta",frame_sha256:cacheDiagnosticHash(frameText),settings_sha256:settingsHash,previous_response_id_sha256:typeof payload.previous_response_id==="string"?cacheDiagnosticHash(payload.previous_response_id):null})}`);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);const bare=untypedErrorEnvelope(frame);if(bare&&!settled){if(retryFull&&continuationRejected(bare.error,bare.frame.status)){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 bare.frame.status==="number"&&bare.frame.status>=400&&bare.frame.status<=599?bare.frame.status:400;this.log("warn",`upstream rejected phase=await-first-event status=${status}`);resolve3(new Response(JSON.stringify(bare.frame),{status,headers:{"content-type":"application/json"}}));return}if(!object2(frame)||typeof frame.type!=="string")throw new Error("Invalid Responses WebSocket event");receivedEvents++;if(["response.completed","response.failed","response.incomplete","error"].includes(frame.type)){const response=object2(frame.response)?frame.response:{};const usage=object2(response.usage)?response.usage:{};const details=object2(usage.input_tokens_details)?usage.input_tokens_details:{};const tokens=value=>typeof value==="number"&&Number.isFinite(value)?value:null;this.log("debug",`upstream cache-diagnostic ${JSON.stringify({phase:"terminal",connection,send,event:frame.type,response_id_sha256:typeof response.id==="string"?cacheDiagnosticHash(response.id):null,usage_present:Object.hasOwn(response,"usage"),input_tokens_details_present:Object.hasOwn(usage,"input_tokens_details"),input_tokens_present:Object.hasOwn(usage,"input_tokens"),input_tokens:tokens(usage.input_tokens),output_tokens_present:Object.hasOwn(usage,"output_tokens"),output_tokens:tokens(usage.output_tokens),cached_tokens_present:Object.hasOwn(details,"cached_tokens"),cached_tokens:tokens(details.cached_tokens)})}`)}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");resolve3(this.fetch(url,options,false));return}if(retryFull&&continuationRejected(error,frame.status)){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}`);resolve3(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);resolve3(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});resolve3(new Response(readable,{headers:{"content-type":"text/event-stream"}}))}const block=`event: ${frame.type}
|
|
1308
1308
|
data: ${event.data}
|
|
1309
1309
|
|
|
1310
1310
|
`;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;destroy(error){if(this.destroyed)return this;super.destroy(error);if(!this.ended)this.emit("close");return this}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}const status=this.statusCode>=400?this.statusCode:502;if(!object2(details)){this.peer.send(errorFrame("incomplete_response","Responses exchange ended without a terminal event",status))}else{const rawError=details.error;const detailText=typeof details.detail==="string"?details.detail:"";const error=object2(rawError)?rawError:typeof rawError==="string"?{code:"proxy_failure",message:detailText!==""&&detailText!==rawError?`${rawError}: ${detailText}`:rawError}:{code:"incomplete_response",message:"Responses exchange ended without a terminal event"};this.peer.send(JSON.stringify({...details,error,type:"error",status}))}}this.ended=true;this.emit("finish");if(!this.destroyed)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();buffer+=done?decoder.decode():decoder.decode(value,{stream:true});if(buffer.length>this.budget)throw new Error("Warmup output buffer limit exceeded");buffer=done?finalizeSseLineEndings(buffer):normalizeSseLineEndings(buffer);for(;;){const index=buffer.indexOf("\n\n");if(index<0)break;const block=buffer.slice(0,index);buffer=buffer.slice(index+2);const payload=sseEventData(block);if(payload===null)continue;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(done)break}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 server=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(server,options.dispatchHttp,options.log,[responsesCodec,codexResponsesCodec],options.isEgressProxied,options.instanceId);server.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((resolve3,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",()=>resolve3())});server.unref();const{port}=server.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(resolve3=>{server.close(()=>resolve3())})}}init_dist();import http4 from"http";import fs37 from"fs";import net4 from"net";import tls5 from"tls";import{randomUUID as randomUUID15}from"crypto";import{performance as performance3}from"perf_hooks";init_config();var DEFAULT_COMPRESS_REASONING={drop:true,threshold:2048,tail:false};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,tail:cfg?.tail===true}}function dropCompressReasoningIds(messages,cfg){const{drop,threshold,tail}=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)}}const runBefore=i=>{if(i===0||messages[i-1].contentType!=="reasoning")return null;const idx=[];let j2=i-1;while(j2>=0&&messages[j2].contentType==="reasoning"){idx.push(j2);j2--}return idx};const harvest=i=>{const idx=runBefore(i);if(idx===null)return;let total=0;for(const k2 of idx)total+=(messages[k2].text??"").length;if(total>threshold)for(const k2 of idx)ids.add(messages[k2].id)};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;harvest(i)}if(tail){for(let i=0;i<=last;i++){const m2=messages[i];if(m2.contentType==="tool-call"){const ri2=typeof m2.toolCallId==="string"?resultAt.get(m2.toolCallId):void 0;if(ri2===void 0||ri2<=i||ri2>=last)continue}else if(m2.contentType==="text"){if(i>=last)continue}else{continue}harvest(i)}}}catch{}return ids}init_logger();init_config();init_registry();init_fetch_util();init_upstream_proxy();init_upstream_fail();init_log_mask();var SUBAGENT_PROMPT_PREFIX="You are a subagent spawned by another session.";var SUBAGENT_PROMPT_PREFIX_CI=SUBAGENT_PROMPT_PREFIX.toLowerCase();function isSubagentPrompt(text2){const t=(text2??"").trim();if(!t)return false;return t.length>=SUBAGENT_PROMPT_PREFIX.length&&t.slice(0,SUBAGENT_PROMPT_PREFIX.length).toLowerCase()===SUBAGENT_PROMPT_PREFIX_CI}function subagentPromptTask(text2){const t=(text2??"").trim();if(!isSubagentPrompt(t))return void 0;return t.slice(SUBAGENT_PROMPT_PREFIX.length).trim()}function displaySessionTitle(hostTitle,title,firstBlockTopic){const stored=hostTitle||title;if(!stored)return void 0;if(hostTitle)return stored;if(firstBlockTopic&&isSubagentPrompt(stored))return firstBlockTopic;return stored}function topicLeadFrom(topic,summary){const raw=topic||summary;if(!raw)return void 0;let hint=String(raw).replace(/\s+/g," ").trim();if(!hint)return void 0;if(hint.length>48)hint=hint.slice(0,48)+"\u2026";return hint}function firstBlockTopicLead(blocks){const fb=blocks.find(b2=>b2.topic||b2.summary);if(!fb)return void 0;return topicLeadFrom(fb.topic,fb.summary)}init_msgid_pin();init_dist();init_config();init_util();init_turn_separator();var RESPONSES_TURN_SEPARATOR="[The exchange between these two assistant turns was compressed.]";function isSeparatorCarrier(item,text2=RESPONSES_TURN_SEPARATOR){if(item===null||typeof item!=="object"||Array.isArray(item))return false;const record3=item;if(Object.keys(record3).length!==3)return false;return record3["type"]==="message"&&record3["role"]==="user"&&record3["content"]===text2}function isSeparatorCoreShaped(core,text2=RESPONSES_TURN_SEPARATOR){return core.role==="user"&&core.contentType==="text"&&core.text===text2}function separatorCoreProvenance(ownedWireIndexes,cores){const owned=new Set;if(ownedWireIndexes.size===0||!Array.isArray(cores))return owned;for(let index=0;index<cores.length;index++){const wireIndex=cores[index].wireIndex;if(wireIndex!==void 0&&ownedWireIndexes.has(wireIndex))owned.add(index)}return owned}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=[];const slots=[];let phase=-1;let seenReasoning=false;let sepSeq=0;const pushSeparator=()=>{sepSeq++;const id=`${RESPONSES_TURN_SEPARATOR_ID_PREFIX}${sepSeq}`;const carrier={type:"message",role:"user",content:RESPONSES_TURN_SEPARATOR};const marker={id,role:"user",contentType:"text",text:RESPONSES_TURN_SEPARATOR,rawResponsesItem:carrier};out.push(marker);slots.push({id,core:marker,carrier});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{messages:out,slots}}function carrierOwners(slots){const owners=new Map;if(!Array.isArray(slots))return owners;for(const slot of slots)owners.set(slot.carrier,slot);return owners}function resolveSeparatorIndexes(finalWire,slots){if(!Array.isArray(finalWire)||!Array.isArray(slots)||slots.length===0)return[];const owners=carrierOwners(slots);if(owners.size===0)return[];const claims=[];for(let index=0;index<finalWire.length;index++){const slot=owners.get(finalWire[index]);if(slot===void 0||!isSeparatorCarrier(finalWire[index]))continue;claims.push({id:slot.id,index,carrier:slot.carrier});owners.delete(slot.carrier)}return claims}function separatorManifestAnchored(manifest,wire,body){if(manifest===void 0||typeof body!=="string"||body.length===0)return false;if(manifest.body!==body)return false;if(!Array.isArray(wire))return false;for(const claim of manifest.claims){const item=wire[claim.index];if(item!==claim.carrier||!isSeparatorCarrier(item,manifest.text))return false}return true}function collectSeparatorManifest(finalWire,slots,body){if(!Array.isArray(finalWire)||!Array.isArray(slots)||slots.length===0)return void 0;if(typeof body!=="string"||body.length===0)return void 0;const claims=resolveSeparatorIndexes(finalWire,slots);if(claims.length===0)return void 0;return{text:RESPONSES_TURN_SEPARATOR,claims,length:finalWire.length,body}}function reanchorSeparatorManifest(manifest,finalWire,finalBody,origin){if(!manifest||!Array.isArray(finalWire))return void 0;if(typeof finalBody!=="string"||finalBody.length===0)return void 0;if(manifest.claims.length===0)return void 0;if(origin!==void 0&&!separatorManifestAnchored(manifest,origin.wire,origin.body))return void 0;const expected=new Map;for(const claim of manifest.claims)expected.set(claim.carrier,claim);if(expected.size===0)return void 0;const claims=[];for(let index=0;index<finalWire.length;index++){const item=finalWire[index];const claim=expected.get(item);if(claim===void 0)continue;if(!isSeparatorCarrier(item,manifest.text))continue;claims.push({id:claim.id,index,carrier:claim.carrier});expected.delete(item)}if(claims.length===0)return void 0;return{text:manifest.text,claims,length:finalWire.length,body:finalBody}}function separatorProvenanceSet(manifest,wire,body){const owned=new Set;if(!manifest||!Array.isArray(wire))return owned;if(typeof body!=="string"||body.length===0)return owned;if(body!==manifest.body)return owned;for(const claim of manifest.claims){if(claim.index>=wire.length)continue;if(!isSeparatorCarrier(wire[claim.index],manifest.text))continue;owned.add(claim.index)}return owned}init_dist();var SESSIONS_CAP=256;var INJECTS_CAP=500;var HARVESTS_CAP=200;var COMMITS_CAP=500;var USAGE_CAP=1200;var INIT_PER_MSG_CAP=100;var HARVEST_WINDOW_MS=12e4;var analyses=new Map;function touch(id){let a=analyses.get(id);if(!a){a={sessionId:id,firstSeen:Date.now(),lastSeen:Date.now(),requests:0,injects:[],injectTotal:0,idleGates:{mass:0,growth:0,cadence:0,other:0},harvests:[],commits:[],compressCommits:0,compressedTotal:0,usage:[]};analyses.set(id,a);if(analyses.size>SESSIONS_CAP){const oldest=analyses.keys().next().value;if(oldest!==void 0)analyses.delete(oldest)}}else{analyses.delete(id);analyses.set(id,a)}return a}function snapshotInit(messages){const entries2=[];let totalChars=0;let estTokens=0;for(const m2 of messages){const chars=(m2.text??"").length+(m2.toolName?m2.toolName.length:0);totalChars+=chars;const tok=countMessageTokens(m2,defaultCountTokens);estTokens+=tok;if(entries2.length===INIT_PER_MSG_CAP&&tok<=entries2[entries2.length-1].estTokens)continue;let lo2=0;let hi2=entries2.length;while(lo2<hi2){const mid=lo2+hi2>>>1;if(tok>entries2[mid].estTokens)hi2=mid;else lo2=mid+1}entries2.splice(lo2,0,{role:m2.role,contentType:m2.contentType,toolName:m2.toolName,estTokens:tok});if(entries2.length>INIT_PER_MSG_CAP)entries2.pop()}return{ts:Date.now(),messageCount:messages.length,totalChars,estTokens,perMessage:entries2}}function fmtKiB(chars){const k2=chars/1024;return k2>=1024?`${(k2/1024).toFixed(1)}MiB`:`${k2.toFixed(1)}KiB`}function fmtKtok(n){return n>=1e4?`${(n/1e3).toFixed(0)}K`:`${n}`}function fmtHM(ms2){const h=ms2/36e5;return h>=10?`${h.toFixed(0)}h`:h>=1?`${h.toFixed(1)}h`:`${(ms2/6e4).toFixed(0)}m`}function clock(ts2){const d=new Date(ts2);const p2=x=>String(x).padStart(2,"0");return`${p2(d.getHours())}:${p2(d.getMinutes())}`}function ringSlopePerHour(ring,now){const cutoff=now-36e5;let first=null;let last=null;for(const s3 of ring){if(s3.ts<cutoff)continue;if(first===null)first=s3;last=s3}if(first===null||last===null||first===last)return null;const spanH=(last.ts-first.ts)/36e5;if(spanH<5/60)return null;return(last.v-first.v)/spanH}function buildVerdict(a,now=Date.now()){const out=[];const spanMs=a.lastSeen-a.firstSeen;if(spanMs<6e4)return out;const inflow=ringSlopePerHour(a.usage.map(u2=>({ts:u2.ts,v:u2.tokenCount})),now);const cumCommits=[];let cumTokens=0;for(const c of a.commits){cumTokens+=c.tokens;cumCommits.push({ts:c.ts,v:cumTokens})}const drain=ringSlopePerHour(cumCommits,now);const limit=a.usage.length>0?a.usage[a.usage.length-1].limit:0;if(a.init&&limit>0&&a.init.estTokens>=.15*limit){out.push(`session started heavy: the first observed request already carried ~${fmtKtok(a.init.estTokens)} tok (${a.init.messageCount} msgs, ${fmtKiB(a.init.totalChars)}) \u2014 the context floor was high before any compression ran`)}if(inflow!==null&&drain!==null){if(inflow>drain*1.15){out.push(`usage climbing: new content \u2248${fmtKtok(inflow)} tok/h outpaces T1 compression \u2248${fmtKtok(drain)} tok/h \u2014 the band drifts up until a distillation reset lands`)}else if(inflow<drain*.85){out.push(`usage falling: T1 compression \u2248${fmtKtok(drain)} tok/h exceeds new content \u2248${fmtKtok(inflow)} tok/h`)}else{out.push(`usage plateau: inflow \u2248${fmtKtok(inflow)} tok/h balances T1 drain \u2248${fmtKtok(drain)} tok/h \u2014 the band is pinned where they meet, not stuck`)}}const under=a.harvests.filter(h=>h.ratio<.5);if(a.injectTotal>=3&&a.harvests.length>=3&&under.length>=1){const worst=a.harvests.reduce((w2,h)=>h.ratio<w2.ratio?h:w2,a.harvests[0]);out.push(`${under.length}/${a.harvests.length} recent nudges under-harvested (worst ${Math.round(worst.ratio*100)}% at ${clock(worst.ts)}) \u2014 the model folded less than the offered pending; nudges are advisory, the kernel never forces a range`)}const r=a.lastReadiness;if(r&&r.interval>0){const t2Thr=Math.round(1.5*r.interval);if(r.t2>=t2Thr){out.push(`T2 distillation is mass-ready (summary pool ${fmtKtok(r.t2)} tok \u2265 ${fmtKtok(t2Thr)}) \u2014 a block-merge reset can fire and drop the band sharply`)}else if(r.t2>.5*t2Thr){out.push(`T2 distillation not ready: summary pool ${fmtKtok(r.t2)} tok < ${fmtKtok(t2Thr)} threshold \u2014 it refills slowly (each T1 fold contributes only its ~1-3K summary)`)}}return out.slice(0,4)}function formatContextAnalysis(sessionId,now=Date.now()){const a=analyses.get(sessionId);if(!a||a.requests<2)return null;const spanMs=a.lastSeen-a.firstSeen;const lines=[];if(a.init){const top=a.init.perMessage[0];lines.push(`init: ${clock(a.init.ts)} \u2014 ${a.init.messageCount} msgs / ${fmtKiB(a.init.totalChars)} inbound \u2248 ${fmtKtok(a.init.estTokens)} tok`+(top?` \xB7 largest: ${top.role}/${top.contentType}${top.toolName?` ${top.toolName}`:""} \u2248${fmtKtok(top.estTokens)} tok`:""))}const g2=a.idleGates;const gateTotal=g2.mass+g2.growth+g2.cadence+g2.other;const gateStr=gateTotal>0?` \xB7 idle gates: mass ${g2.mass}\xD7 / growth ${g2.growth}\xD7 / cadence ${g2.cadence}\xD7 / other ${g2.other}\xD7`:"";lines.push(`injects: ${a.injectTotal} in ${fmtHM(spanMs)}${gateStr}`);if(a.harvests.length>0){const under=a.harvests.filter(h=>h.ratio<.5).length;const sorted=[...a.harvests].sort((x,y)=>x.ratio-y.ratio);const worst=sorted[0];const best=sorted[sorted.length-1];lines.push(`harvest: ${a.harvests.length-under}/${a.harvests.length} nudges \u226550% of offered (range ${Math.round(worst.ratio*100)}%\u2013${Math.round(best.ratio*100)}%)${under>0?`, ${under} under-harvested`:""}`)}if(a.compressCommits>0){lines.push(`compression: ${a.compressCommits} commit(s), ~${fmtKtok(a.compressedTotal)} tok total`)}for(const v2 of buildVerdict(a,now))lines.push(`verdict: ${v2}`);return lines}function recordNudgeObservation(sessionId,turn,tokenCount,limit,willInject,decidePending=false,surfaceOff){const now=Date.now();const a=touch(sessionId);a.requests++;a.lastSeen=now;if(!a.init&&Array.isArray(turn.messages)&&turn.messages.length>0){a.init=snapshotInit(turn.messages)}a.usage.push({ts:now,tokenCount,limit});if(a.usage.length>USAGE_CAP)a.usage.splice(0,a.usage.length-USAGE_CAP);const n=turn.nudge;if(!n)return null;const b2=n.breakdown??{};const interval=b2["nudgeGrowthTokens"]??0;const pendingT1=b2["pendingT1"]??0;const pendingT2=b2["pendingT2"]??0;const pendingT3=b2["pendingT3"]??0;a.lastReadiness={ts:now,t1:pendingT1,t2:pendingT2,t3:pendingT3,interval};const label=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 pct2=limit>0?Math.round(tokenCount/limit*100):0;if(willInject){a.injectTotal++;a.injects.push({ts:now,label,tier:n.tier,usagePct:pct2,tokenCount,limit,growth:b2["growth"]??0,floor:b2["growthFloor"]??0,interval,pendingT1,pendingT2,pendingT3});if(a.injects.length>INJECTS_CAP)a.injects.splice(0,a.injects.length-INJECTS_CAP);const fmt=formatContextAnalysis(sessionId,now);return fmt?`[context-analysis] ${sessionId} ${label} @${pct2}% \u2014 `+fmt.join(" \xB7 "):null}const reason=n.reason??"";if(/cadence/i.test(reason))a.idleGates.cadence++;else if(/< threshold/i.test(reason))a.idleGates.mass++;else if(/< floor/i.test(reason))a.idleGates.growth++;else a.idleGates.other++;const gateTotal=a.idleGates.mass+a.idleGates.growth+a.idleGates.cadence+a.idleGates.other;if(gateTotal>0&&gateTotal%60===0){const fmt=formatContextAnalysis(sessionId,now);return fmt?`[context-analysis] ${sessionId} ${label} @${pct2}% (${reason.slice(0,80)}) \u2014 `+fmt.join(" \xB7 "):null}return null}function recordCompressCommit(sessionId,tokensCompressed,blocksCreated){const now=Date.now();const a=touch(sessionId);a.lastSeen=now;a.compressCommits++;a.compressedTotal+=tokensCompressed;a.commits.push({ts:now,tokens:tokensCompressed});if(a.commits.length>COMMITS_CAP)a.commits.splice(0,a.commits.length-COMMITS_CAP);if(blocksCreated<=0||tokensCompressed<=0)return;for(let i=a.injects.length-1;i>=0;i--){const ev=a.injects[i];if(ev.matched)continue;const age=now-ev.ts;if(age>HARVEST_WINDOW_MS)break;const tierMass=ev.tier===2?ev.pendingT2:ev.tier===3?ev.pendingT3:ev.pendingT1;const offered=tierMass>0?tierMass:ev.tokenCount;ev.matched=true;a.harvests.push({ts:now,offered,got:tokensCompressed,ratio:offered>0?Math.min(2,tokensCompressed/offered):1});if(a.harvests.length>HARVESTS_CAP)a.harvests.splice(0,a.harvests.length-HARVESTS_CAP);return}}function contextAnalysisView(sessionId,now=Date.now()){const a=analyses.get(sessionId);if(!a||a.requests<2)return null;const lines=formatContextAnalysis(sessionId,now);return{firstSeen:a.firstSeen,lastSeen:a.lastSeen,requests:a.requests,init:a.init,injectTotal:a.injectTotal,injects:a.injects.slice(-50),idleGates:a.idleGates,harvests:a.harvests.slice(-50),compressCommits:a.compressCommits,compressedTotal:a.compressedTotal,lastReadiness:a.lastReadiness,verdict:buildVerdict(a,now),text:(lines??[]).join("\n")}}function yieldToEventLoop(){return new Promise(resolve3=>setImmediate(resolve3))}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 formatK2(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 ${formatK2(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(name2){const raw=process.env[name2];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(name2){const raw=process.env[name2];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=resolveModelEntryOnRoute(route,model).entry?.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}found="5m"}for(const[key2,value]of Object.entries(o)){if(key2==="input_schema")continue;if(key2==="input"&&(o.type==="tool_use"||o.type==="server_tool_use"))continue;walk(value)}};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;function realSchedule(fn,ms2){const t=setTimeout(fn,ms2);t.unref?.();return t}var clock2=()=>Date.now();var scheduleFn=realSchedule;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=clock2();const credFp=credentialFingerprint(inp.headers);const prev=registry3.get(inp.sessionId);if(prev&&prev.credFp!==credFp)disarm2(inp.sessionId,"credential-rotated");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);prev?.pingController?.abort();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=clock2();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;const controller=new AbortController;entry.pingController=controller;const timeout=AbortSignal.timeout(PING_TIMEOUT_MS);const onTimeout=()=>controller.abort(timeout.reason);timeout.addEventListener("abort",onTimeout,{once:true});entry.lastPingAt=clock2();try{let resp;try{resp=await sendPing(entry,controller.signal)}catch(err2){handleFailure(entry,`network: ${err2 instanceof Error?err2.message:String(err2)}`);return}if(registry3.get(entry.sessionId)!==entry)return;let text2;try{text2=await resp.text()}catch(err2){if(resp.status!==429){handleFailure(entry,`response body: ${err2 instanceof Error?err2.message:String(err2)}`);return}text2=""}if(registry3.get(entry.sessionId)!==entry)return;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=clock2();log("info",`[${entry.sessionId}] [keepalive] ping#${entry.pingCount} hit=${cached}tok`);reschedule(entry)}else{disarm2(entry.sessionId,"prefix-dead(cache_read=0)")}}finally{timeout.removeEventListener("abort",onTimeout);entry.pingInFlight=false;entry.pingController=void 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,signal){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};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);entry.pingController?.abort();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","upstream-unreachable","connect-refused","proxy-reset","upstream-reset","dns","tls"]);var MAX_ALERTS=32;var ALERT_STALE_MS=5*6e4;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 pruneStaleAlerts(now){if(alerts.size===0)return;const cutoff=now-ALERT_STALE_MS;for(const[key2,a]of alerts){if(a.lastSeen<cutoff)alerts.delete(key2)}}function errnoCode(error){for(let depth=0;typeof error==="object"&&error!==null&&depth<8;depth++){const current=error;if(typeof current.code==="string"&¤t.code.length>0)return current.code;error=current.cause}return 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;delete existing.skippedProxy;delete existing.skippedSource;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(now=Date.now()){pruneStaleAlerts(now);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&&now-entry.probeAt<circuitProbeCooldownMs)return blockReasonText(c,now);entry.probeInFlight=true;entry.probeAt=now;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,probeAt:0,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 isOpenCircuitStale(e,now){const c=e.state;if(c.openedAt===null)return false;const anchor=c.nextProbeAt??c.lastFailure?.at??c.openedAt;return now-anchor>ALERT_STALE_MS}function getOpenUpstreamCircuits(now=Date.now()){return[...circuits.values()].filter(e=>e.state.openedAt!==null&&!isOpenCircuitStale(e,now)).map(e=>({...e.state})).sort((a,b2)=>(b2.openedAt??0)-(a.openedAt??0))}function getUpstreamHealthReport(now=Date.now()){pruneStaleAlerts(now);const byHost=new Map;const touch2=host=>{let acc=byHost.get(host);if(!acc){acc={alerts:[],circuit:null};byHost.set(host,acc)}return acc};for(const a of alerts.values())touch2(a.host).alerts.push(a);for(const e of circuits.values()){if(e.state.openedAt!==null&&!isOpenCircuitStale(e,now))touch2(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 MAX_KEYRING_ERROR_BODY_BYTES=16*1024;var KEYRING_MODEL_LIMIT_CODE="keyring_model_temporarily_unavailable";function recordOf(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)?value:void 0}function parseSmallJsonRecord(body){if(body.length>MAX_KEYRING_ERROR_BODY_BYTES)return void 0;try{const text2=typeof body==="string"?body:new TextDecoder().decode(body);return recordOf(JSON.parse(text2))}catch{return void 0}}function jsonCodeAt(body,index){if(typeof body==="string")return index<body.length?body.charCodeAt(index):-1;return index<body.length?body[index]??-1:-1}function skipJsonWhitespace(body,start){let index=start;while(index<body.length){const code=jsonCodeAt(body,index);if(code!==32&&code!==9&&code!==10&&code!==13)break;index+=1}return index}function skipJsonString(body,start){if(jsonCodeAt(body,start)!==34)return void 0;let index=start+1;while(index<body.length){const code=jsonCodeAt(body,index);if(code===34)return index+1;if(code<32)return void 0;if(code===92){index+=1;if(index>=body.length)return void 0;const escaped=jsonCodeAt(body,index);if(escaped===117){for(let digit=index+1;digit<=index+4;digit+=1){const value=jsonCodeAt(body,digit);if(!(value>=48&&value<=57||value>=65&&value<=70||value>=97&&value<=102))return void 0}index+=5;continue}if(escaped!==34&&escaped!==92&&escaped!==47&&escaped!==98&&escaped!==102&&escaped!==110&&escaped!==114&&escaped!==116)return void 0}index+=1}return void 0}function readJsonString(body,start,end){try{const source=typeof body==="string"?body.slice(start,end):new TextDecoder().decode(body.subarray(start,end));const value=JSON.parse(source);return typeof value==="string"?value:void 0}catch{return void 0}}function skipJsonNumber(body,start){let index=start;if(jsonCodeAt(body,index)===45)index+=1;const integer2=jsonCodeAt(body,index);if(integer2===48){index+=1}else if(integer2>=49&&integer2<=57){index+=1;while(jsonCodeAt(body,index)>=48&&jsonCodeAt(body,index)<=57)index+=1}else{return void 0}if(jsonCodeAt(body,index)===46){index+=1;const fraction=index;while(jsonCodeAt(body,index)>=48&&jsonCodeAt(body,index)<=57)index+=1;if(index===fraction)return void 0}const exponent=jsonCodeAt(body,index);if(exponent===101||exponent===69){index+=1;const sign=jsonCodeAt(body,index);if(sign===43||sign===45)index+=1;const digits=index;while(jsonCodeAt(body,index)>=48&&jsonCodeAt(body,index)<=57)index+=1;if(index===digits)return void 0}return index}function skipJsonValue(body,start,depth=0){if(depth>256)return void 0;const index=skipJsonWhitespace(body,start);const code=jsonCodeAt(body,index);if(code===34)return skipJsonString(body,index);if(code===91||code===123){const object3=code===123;const close=object3?125:93;let cursor=skipJsonWhitespace(body,index+1);if(jsonCodeAt(body,cursor)===close)return cursor+1;while(cursor<body.length){if(object3){const keyEnd=skipJsonString(body,cursor);if(keyEnd===void 0)return void 0;cursor=skipJsonWhitespace(body,keyEnd);if(jsonCodeAt(body,cursor)!==58)return void 0;cursor+=1}const valueEnd=skipJsonValue(body,cursor,depth+1);if(valueEnd===void 0)return void 0;cursor=skipJsonWhitespace(body,valueEnd);const separator=jsonCodeAt(body,cursor);if(separator===close)return cursor+1;if(separator!==44)return void 0;cursor=skipJsonWhitespace(body,cursor+1)}return void 0}if(code===116&&jsonCodeAt(body,index+1)===114&&jsonCodeAt(body,index+2)===117&&jsonCodeAt(body,index+3)===101)return index+4;if(code===102&&jsonCodeAt(body,index+1)===97&&jsonCodeAt(body,index+2)===108&&jsonCodeAt(body,index+3)===115&&jsonCodeAt(body,index+4)===101)return index+5;if(code===110&&jsonCodeAt(body,index+1)===117&&jsonCodeAt(body,index+2)===108&&jsonCodeAt(body,index+3)===108)return index+4;return skipJsonNumber(body,index)}function scanRequestModel(body){let index=skipJsonWhitespace(body,0);if(jsonCodeAt(body,index)!==123)return void 0;index=skipJsonWhitespace(body,index+1);let model;if(jsonCodeAt(body,index)===125)return void 0;while(index<body.length){const keyStart=index;const keyEnd=skipJsonString(body,keyStart);if(keyEnd===void 0)return void 0;const key2=keyEnd-keyStart<=32?readJsonString(body,keyStart,keyEnd):void 0;index=skipJsonWhitespace(body,keyEnd);if(jsonCodeAt(body,index)!==58)return void 0;const valueStart=skipJsonWhitespace(body,index+1);let valueEnd;if(key2==="model"&&jsonCodeAt(body,valueStart)===34){valueEnd=skipJsonString(body,valueStart);if(valueEnd===void 0)return void 0;model=readJsonString(body,valueStart,valueEnd)}else{if(key2==="model")model=void 0;valueEnd=skipJsonValue(body,valueStart);if(valueEnd===void 0)return void 0}index=skipJsonWhitespace(body,valueEnd);const separator=jsonCodeAt(body,index);if(separator===125)return skipJsonWhitespace(body,index+1)===body.length?model:void 0;if(separator!==44)return void 0;index=skipJsonWhitespace(body,index+1)}return void 0}var bodyModelMemo=new WeakMap;var requestModelScanCount=0;function requestModelFromBody(body,cacheHost){if(cacheHost!==void 0){const memo=bodyModelMemo.get(cacheHost);if(memo!==void 0&&memo.body===body)return memo.model}requestModelScanCount++;const model=scanRequestModel(body);const out=typeof model==="string"&&model.length>0?model:void 0;if(cacheHost!==void 0)bodyModelMemo.set(cacheHost,{body,model:out});return out}function keyringModel429Scope(status,requestModel,responseBody){if(status!==429||!requestModel||responseBody==null)return void 0;const error=recordOf(parseSmallJsonRecord(responseBody)?.error);if(error?.model!==requestModel)return void 0;if(error.code===KEYRING_MODEL_LIMIT_CODE)return requestModel;if(error.code==="bili_throttle_hold"&&error.scope==="model")return requestModel;return void 0}function throttle429ModelScope(status,requestModel,responseBody){const recognized=keyringModel429Scope(status,requestModel,responseBody);if(recognized!==void 0)return recognized;if(status!==429||throttle429Scope()!=="model")return void 0;return requestModel!==void 0&&requestModel.length>0?requestModel:void 0}function modelHoldKey(key2,model){return`${key2}\0model\0${model}`}var holds=new Map;var provisionalGroups=new Map;var MAX_CLASSIFICATIONS_PER_ACCOUNT=64;var MAX_CLASSIFICATION_ACCOUNTS=64;var activeClassificationCounts=new Map;var classificationReservations=new Map;var NOOP_CLASSIFICATION_RESERVATION={release(){}};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;let cred=credentialFingerprint(headers);try{const parsed=new URL(url);host=parsed.host;if(cred===void 0&&/\/models\/[^/]+:(?:generateContent|streamGenerateContent|countTokens)$/.test(parsed.pathname)){const values=[...parsed.searchParams.getAll("key"),...parsed.searchParams.getAll("$key")];const queryKey=values[0];if(queryKey!==void 0&&values.every(value=>value===queryKey)){cred=credentialFingerprint({"x-goog-api-key":queryKey})}}}catch{}return{key:cred===void 0?host:`${host}\0${cred}`,host,cred}}function releaseClassificationReservation(reservation,state8){if(!state8.active)return;state8.active=false;classificationReservations.delete(reservation);const activeCount=activeClassificationCounts.get(state8.accountKey);if(activeCount===void 0||activeCount<=1){activeClassificationCounts.delete(state8.accountKey)}else{activeClassificationCounts.set(state8.accountKey,activeCount-1)}const onRelease=state8.onRelease;state8.onRelease=void 0;onRelease?.()}function reserveUpstreamThrottleClassification(url,headers){if(!throttle429Enabled())return NOOP_CLASSIFICATION_RESERVATION;const{key:key2}=holdKey(url,headers);const activeCount=activeClassificationCounts.get(key2)??0;if(activeCount>=MAX_CLASSIFICATIONS_PER_ACCOUNT||activeCount===0&&activeClassificationCounts.size>=MAX_CLASSIFICATION_ACCOUNTS)return void 0;activeClassificationCounts.set(key2,activeCount+1);const state8={accountKey:key2,active:true,claimed:false};let reservation;reservation={release(){releaseClassificationReservation(reservation,state8)}};classificationReservations.set(reservation,state8);return reservation}function evictOldestModel(){for(const[slotKey,state8]of holds){if(state8.model===void 0||state8.provisional)continue;holds.delete(slotKey);return true}return false}function evictOldestAccountWide(){for(const[slotKey,state8]of holds){if(state8.model!==void 0||state8.provisional)continue;holds.delete(slotKey);return true}return false}function storeHold(slotKey,state8,preserveAccountWide){if(!holds.has(slotKey)&&holds.size>=MAX_HOLDS){if(state8.model!==void 0||state8.provisional||preserveAccountWide){if(!evictOldestModel())return false}else if(!evictOldestModel()&&!evictOldestAccountWide()){return false}}holds.set(slotKey,state8);return true}function makeReject(st2,now){const maxC=throttle429MaxConsecutive();const terminal=st2.streak>=maxC;const secsLeft=Math.max(1,Math.ceil((st2.nextAttemptAt-now)/1e3));const modelText=st2.model===void 0?"":` for model "${st2.model}"`;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}${modelText}; 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,...st2.model===void 0?{}:{model:st2.model}}}return{status:429,code:"bili_throttle_hold",message:`upstream rate-limited ${st2.streak} consecutive request(s) to ${st2.host}${modelText}; 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,...st2.model===void 0?{}:{model:st2.model}}}function createHoldState(accountKey,host,cred,retryAfterHeader,now,previous,model,provisional,provisionalRequestModel){const streak=(previous?.streak??0)+1;const base=throttle429BaseDelayMs();const cap2=throttle429MaxDelayMs();const exp=Math.min(cap2,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);return{streak,nextAttemptAt:now+delay,probeAt:previous?.probeAt,probeToken:previous?.probeToken,host,cred,accountKey,...model===void 0?{}:{model},provisional,...provisionalRequestModel===void 0?{}:{provisionalRequestModel}}}function logThrottle429Passthrough(host,model,retryAfterHeader,now){const raMs=parseRetryAfterMs(retryAfterHeader,now);const raNote=raMs!==null?`, upstream Retry-After ~${Math.round(raMs/1e3)}s (passed through, client decides)`:"";const modelNote=model===void 0||model.length===0?"":` for model "${model}"`;log("warn",`[acp-proxy] [429-passthrough] ${host}${modelNote}: upstream 429 forwarded to the client unchanged (429 governor disabled \u2014 no local hold, no 424)${raNote} (#4204/#6639)`)}function logThrottle429(state8,retryAfterHeader,now){const streak=state8.streak;const maxC=throttle429MaxConsecutive();const delay=state8.nextAttemptAt-now;const raMs=parseRetryAfterMs(retryAfterHeader,now);const raNote=raMs!==null&&raMs>=delay?", upstream Retry-After honored":"";const modelNote=state8.model===void 0?"":` for model "${state8.model}"`;const delaySec=Math.round(delay/1e3);if(streak===1){log("warn",`[acp-proxy] [429-hold] ${state8.host}${modelNote}: 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] ${state8.host}${modelNote}: ${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] ${state8.host}${modelNote}: consecutive 429 #${streak} \u2014 hold extended to ~${delaySec}s${raNote} (#4204)`)}}function expireProbeToken(state8,now){if(state8.probeToken===void 0||state8.probeAt===void 0||now-state8.probeAt<PROBE_INFLIGHT_TTL_MS)return;state8.probeToken=void 0;state8.probeAt=void 0}function releaseProbeToken(probeToken,now,accountKey){for(const state8 of holds.values()){if(accountKey!==void 0&&state8.accountKey!==accountKey)continue;expireProbeToken(state8,now);if(probeToken===void 0||state8.probeToken!==probeToken)continue;state8.probeToken=void 0;state8.probeAt=void 0}for(const group of provisionalGroups.values()){const state8=group.state;if(accountKey!==void 0&&state8.accountKey!==accountKey)continue;expireProbeToken(state8,now);if(probeToken===void 0||state8.probeToken!==probeToken)continue;state8.probeToken=void 0;state8.probeAt=void 0}}function releaseUpstreamThrottleProbe(probeToken){if(probeToken===void 0)return;releaseProbeToken(probeToken,Date.now())}function slotBlocked(state8,now){expireProbeToken(state8,now);return now<state8.nextAttemptAt||state8.probeToken!==void 0}function strongerReject(current,candidate){if(current===void 0)return candidate;const maxC=throttle429MaxConsecutive();const candidateTerminal=candidate.streak>=maxC;const currentTerminal=current.streak>=maxC;if(candidateTerminal&&!currentTerminal)return candidate;if(candidateTerminal===currentTerminal&&candidate.nextAttemptAt>current.nextAttemptAt)return candidate;return current}function refreshProvisionalGroup(group){const first=group.observations.values().next().value;if(first===void 0)return;let strongest=first;for(const observation of group.observations){strongest=strongerReject(strongest,observation)}const probeToken=group.state.probeToken;const probeAt=group.state.probeAt;group.state={...strongest,probeToken,probeAt,model:void 0,provisional:true,provisionalRequestModel:void 0}}function settleProvisionalObservation(key2,state8,requestModel,modelScope){const exactModel=modelScope!==void 0&&modelScope.length>0&&requestModel!==void 0&&modelScope===requestModel?modelScope:void 0;const preserveAccountWide=exactModel!==void 0;const targetKey=exactModel===void 0?key2:modelHoldKey(key2,exactModel);const target=holds.get(targetKey);state8.provisional=false;state8.provisionalRequestModel=void 0;if(exactModel===void 0){delete state8.model}else{state8.model=exactModel}if(target===void 0){if(exactModel!==void 0)state8.streak=1;storeHold(targetKey,state8,preserveAccountWide)}else if(target.probeToken!==state8.probeToken){state8.streak=target.streak+1;state8.nextAttemptAt=Math.max(state8.nextAttemptAt,target.nextAttemptAt);storeHold(Symbol("settled upstream throttle observation"),state8,preserveAccountWide)}else{target.streak+=1;target.nextAttemptAt=Math.max(target.nextAttemptAt,state8.nextAttemptAt)}}function upstreamThrottleGate(url,headers,now=Date.now(),requestModel){if(!throttle429Enabled())return{};const{key:key2}=holdKey(url,headers);let hasApplicable=false;let rejectState;for(const state8 of holds.values()){if(state8.accountKey!==key2)continue;if(!state8.provisional&&state8.model!==void 0&&state8.model!==requestModel)continue;hasApplicable=true;if(slotBlocked(state8,now))rejectState=strongerReject(rejectState,state8)}for(const group of provisionalGroups.values()){const state8=group.state;if(state8.accountKey!==key2)continue;hasApplicable=true;if(slotBlocked(state8,now))rejectState=strongerReject(rejectState,state8)}if(rejectState!==void 0)return{reject:makeReject(rejectState,now)};if(!hasApplicable)return{};const probeToken=Symbol("upstream throttle probe");for(const state8 of holds.values()){if(state8.accountKey!==key2)continue;if(!state8.provisional&&state8.model!==void 0&&state8.model!==requestModel)continue;state8.probeToken=probeToken;state8.probeAt=now}for(const group of provisionalGroups.values()){const state8=group.state;if(state8.accountKey!==key2)continue;state8.probeToken=probeToken;state8.probeAt=now}return{probeToken}}function upstreamThrottlePeekReject(url,headers,now=Date.now(),requestModel){if(!throttle429Enabled())return void 0;const{key:key2}=holdKey(url,headers);let rejectState;for(const state8 of holds.values()){if(state8.accountKey!==key2)continue;if(!state8.provisional&&state8.model!==void 0&&state8.model!==requestModel)continue;if(slotBlocked(state8,now))rejectState=strongerReject(rejectState,state8)}for(const group of provisionalGroups.values()){const state8=group.state;if(state8.accountKey!==key2)continue;if(slotBlocked(state8,now))rejectState=strongerReject(rejectState,state8)}return rejectState===void 0?void 0:makeReject(rejectState,now)}function noteUpstreamThrottle429(url,headers,retryAfterHeader,now=Date.now(),modelScope,probeToken){const{key:key2,host,cred}=holdKey(url,headers);if(!throttle429Enabled()){logThrottle429Passthrough(host,modelScope,retryAfterHeader,now);releaseProbeToken(probeToken,now,key2);return}releaseProbeToken(probeToken,now,key2);const scopeModel=modelScope===void 0||modelScope.length===0?void 0:modelScope;const stateKey=scopeModel===void 0?key2:modelHoldKey(key2,scopeModel);const previous=holds.get(stateKey);const observedState=createHoldState(key2,host,cred,retryAfterHeader,now,previous,scopeModel,false);if(previous)observedState.nextAttemptAt=Math.max(observedState.nextAttemptAt,previous.nextAttemptAt);if(previous===void 0){if(!storeHold(stateKey,observedState,scopeModel!==void 0)){log("warn",`[acp-proxy] [429-hold] ${host}${scopeModel!==void 0?` model "${scopeModel}"`:""}: 429 hold NOT stored \u2014 hold map saturated at ${MAX_HOLDS} with no evictable model-scoped hold; this 429 is ungoverned and requests pass through (#5199)`);return}}else{holds.set(stateKey,observedState)}logThrottle429(observedState,retryAfterHeader,now)}function beginProvisionalUpstreamThrottle429(url,headers,retryAfterHeader,now,requestModel,probeToken,reservation){if(!throttle429Enabled()){reservation?.release();const{host:host2}=holdKey(url,headers);logThrottle429Passthrough(host2,requestModel,retryAfterHeader,now);return()=>void 0}const{key:key2,host,cred}=holdKey(url,headers);releaseProbeToken(probeToken,now,key2);const classificationReservation=reservation??reserveUpstreamThrottleClassification(url,headers);if(classificationReservation===void 0)return()=>void 0;const classificationState=classificationReservations.get(classificationReservation);if(classificationState===void 0||!classificationState.active||classificationState.claimed){return()=>void 0}if(classificationState.accountKey!==key2){classificationReservation.release();return()=>void 0}classificationState.claimed=true;const previousAccount=holds.get(key2);const state8=createHoldState(key2,host,cred,retryAfterHeader,now,previousAccount,void 0,true,requestModel);state8.probeToken=void 0;state8.probeAt=void 0;const existingGroup=provisionalGroups.get(key2);if(existingGroup===void 0&&provisionalGroups.size>=MAX_CLASSIFICATION_ACCOUNTS){classificationReservation.release();return()=>void 0}const group=existingGroup??{state:{...state8,provisionalRequestModel:void 0},observations:new Set};if(existingGroup===void 0)provisionalGroups.set(key2,group);if(group.observations.size>=MAX_CLASSIFICATIONS_PER_ACCOUNT){classificationReservation.release();return()=>void 0}group.observations.add(state8);refreshProvisionalGroup(group);logThrottle429(state8,retryAfterHeader,now);classificationState.onRelease=()=>{if(provisionalGroups.get(key2)!==group||!group.observations.delete(state8))return;if(group.observations.size===0){provisionalGroups.delete(key2)}else{refreshProvisionalGroup(group)}};let settled=false;return modelScope=>{if(settled)return;settled=true;const pendingGroup=provisionalGroups.get(key2);if(pendingGroup!==group||!group.observations.delete(state8)){classificationReservation.release();return}classificationState.onRelease=void 0;settleProvisionalObservation(key2,state8,requestModel,modelScope);if(group.observations.size===0){provisionalGroups.delete(key2)}else{refreshProvisionalGroup(group)}classificationReservation.release()}}function noteUpstreamThrottleResolved(url,headers,status,now=Date.now(),requestModel,probeToken){if(!throttle429Enabled())return;const{key:key2,host}=holdKey(url,headers);for(const[slotKey,state8]of holds){if(state8.accountKey!==key2)continue;expireProbeToken(state8,now);const ownsProbe=probeToken!==void 0&&state8.probeToken===probeToken;const inResolvedScope=state8.model===void 0||state8.model===requestModel;if(state8.provisional){if(ownsProbe){state8.probeToken=void 0;state8.probeAt=void 0}continue}if(!inResolvedScope){if(ownsProbe){state8.probeToken=void 0;state8.probeAt=void 0}continue}if(state8.probeToken!==void 0&&!ownsProbe)continue;holds.delete(slotKey);const modelNote=state8.model===void 0?"":` for model "${state8.model}"`;log("info",`[acp-proxy] [429-hold] ${host}${modelNote}: cleared after HTTP ${status} (was ${state8.streak} consecutive 429s) (#4204)`)}for(const group of provisionalGroups.values()){const state8=group.state;if(state8.accountKey!==key2)continue;expireProbeToken(state8,now);if(probeToken!==void 0&&state8.probeToken===probeToken){state8.probeToken=void 0;state8.probeAt=void 0}}}function activeThrottleHolds(){const maxC=throttle429MaxConsecutive();const states=[...holds.values(),...Array.from(provisionalGroups.values(),group=>group.state)];return states.map(state8=>({host:state8.host,streak:state8.streak,nextAttemptAt:state8.nextAttemptAt,terminal:state8.streak>=maxC,...state8.model===void 0?{}:{model:state8.model}}))}init_dist();init_dist();import{createHash as createHash27}from"crypto";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. Pass ONE 'content' string JSON-encoding an array of {startId, endId, topic?} objects (the string parameter accepts a JSON-encoded array; do not send a raw JSON array argument). 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,child2]of Object.entries(value)){result[key2]=key2==="required"&&Array.isArray(child2)?child2.filter(name2=>name2!=="summary"):adaptSchema(child2)}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")}
|
|
@@ -1579,7 +1579,7 @@ data: ${JSON.stringify({type:"error",code:err2.code,message:err2.message})}
|
|
|
1579
1579
|
`)}else{safeWrite(res,`event: error
|
|
1580
1580
|
data: ${JSON.stringify({type:"error",error:{type:"server_error",code:err2.code,message:err2.message}})}
|
|
1581
1581
|
|
|
1582
|
-
`)}}catch{}finally{try{res.end()}catch{}}}var reports=new Map;function recordAttributionReport(agent,report){reports.set(agent,{state:report.state,refusals:report.refusals,since:report.since,...report.error!==void 0?{error:report.error}:{},...report.endpoint!==void 0?{endpoint:report.endpoint}:{}})}function attributionStatusWire(){const out={};for(const[agent,r]of reports)out[agent]={state:r.state,refusals:r.refusals,since:r.since,...r.error!==void 0?{error:r.error}:{},...r.endpoint!==void 0?{endpoint:r.endpoint}:{}};return out}init_logger();init_ingest();var HANDOFF_REPLY_MAX_BYTES=15e5;function baseIdOfCore(m2){const text2=m2.text??"";switch(m2.contentType){case"text":if(m2.imagePart)return null;return deriveCanonicalMessageId(m2.originalRole??m2.role,"text",text2);case"reasoning":return deriveCanonicalMessageId("assistant","reasoning",text2);case"tool-call":return deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(text2),{toolName:m2.toolName});case"tool-result":return deriveCanonicalMessageId("tool","tool-result",text2,{toolName:m2.toolName});default:return null}}function restampForJoin(protocol,m2){const b2=m2;const text2=b2.text??"";if(b2.contentType==="reasoning"&&protocol==="openai"){const stamped={...b2,reasoningContent:text2};return stamped}if(b2.contentType==="tool-call"&&(protocol==="openai"||protocol==="anthropic")){try{const parsed=JSON.parse(text2);if(parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed))return{...m2,text:JSON.stringify(parsed)}}catch{}}return m2}function createHandoffReply(session,canSave=()=>true,protocol){const request=session.stats.requests;const snapshot=session.lastMessages;const messages=new Map;let bytes=0;let discarded=false;const discard=()=>{discarded=true;messages.clear()};const put=(key2,message,textBytes2,lastCodeUnit)=>{if(discarded)return;const previous=messages.get(key2);const text2=message.text??"";const measuredTextBytes=textBytes2??Buffer.byteLength(text2);const size=measuredTextBytes+Buffer.byteLength(message.toolName??"")+Buffer.byteLength(message.toolCallId??"")+128;bytes+=size-(previous?.bytes??0);if(bytes>HANDOFF_REPLY_MAX_BYTES){discard();return}messages.set(key2,{message,bytes:size,textBytes:measuredTextBytes,lastCodeUnit:lastCodeUnit??text2.charCodeAt(text2.length-1)})};return{append(key2,contentType,text2){if(!text2||discarded)return;const previous=messages.get(key2);const last=previous?.lastCodeUnit??0;const first=text2.charCodeAt(0);const joinsPair=last>=55296&&last<=56319&&first>=56320&&first<=57343;const textBytes2=(previous?.textBytes??0)+Buffer.byteLength(text2)-(joinsPair?2:0);put(key2,{id:`reply_${key2}`,role:"assistant",contentType,text:(previous?.message.text??"")+text2},textBytes2,text2.charCodeAt(text2.length-1))},tool(key2,toolName,toolCallId,text2){put(key2,{id:`reply_${key2}`,role:"assistant",contentType:"tool-call",toolName,toolCallId,text:text2})},replace(next){messages.clear();bytes=0;for(const[i,m2]of next.entries())put(String(i),{id:`reply_${i}`,role:"assistant",contentType:m2.contentType,text:m2.text,toolName:m2.toolName,toolCallId:m2.toolCallId})},discard,save(){if(discarded||!messages.size||session.stats.requests!==request||session.lastMessages!==snapshot||!canSave())return;if(session.lastMessagesFolded!==true&&Array.isArray(snapshot)){const clusters=new ClusterCounter;for(const m2 of snapshot){const b2=baseIdOfCore(m2);if(b2!==null)clusters.next(b2)}const rows=[];for(const entry of messages.values()){const m2=restampForJoin(protocol,entry.message);const b2=baseIdOfCore(m2);if(b2===null)continue;rows.push(planStoredMessageRow({...m2,id:clusters.next(b2)}))}if(rows.length>0)session.metadata["handoffReply"]={request,rows}}session.metadata.handoffResponse={request,messages:[...messages.values()].map(entry=>entry.message)};markDirty(session)}}}function captureHandoffJson(reply,protocol,json){if(!reply)return;try{if(json.error||protocol==="responses"&&json.status&&json.status!=="completed"){reply.discard();return}let messages;if(protocol==="openai"){const message=json.choices?.[0]?.message;messages=openaiToCore({messages:[message]}).msgs}else if(protocol==="anthropic"){messages=anthropicToCore({messages:[json]}).msgs}else if(protocol==="responses"){messages=responsesToCore({input:json.output}).msgs}else if(protocol==="google"){const content=json.candidates?.[0]?.content;messages=googleToCore({contents:[content]}).msgs}else return;reply.replace(messages.filter(m2=>m2.role==="assistant"))}catch(err2){log("debug",`[handoff] JSON reply capture skipped (codec failed for protocol ${protocol??"unknown"}): ${err2 instanceof Error?err2.message:String(err2)}`);reply.discard()}}init_fetch_util();init_logger();var GITHUB_RELEASES_URL="https://api.github.com/repos/ranxianglei/billion-context/releases?per_page=20";var THROTTLE_MS=10*60*1e3;var MAX_ENTRIES=20;var FETCH_TIMEOUT_MS=5e3;var state4={releases:[],lastCheckAt:0};var inflight2;var warmAttempted=false;function latestChangelog(){return state4.releases[0]}function parseRelease(raw){if(typeof raw!=="object"||raw===null)return void 0;const e=raw;const tag=typeof e.tag_name==="string"?e.tag_name.trim():"";const url=typeof e.html_url==="string"?e.html_url.trim():"";if(!tag||!url)return void 0;const name2=typeof e.name==="string"?e.name.trim():"";const publishedAt=typeof e.published_at==="string"?e.published_at.trim():"";const body=typeof e.body==="string"?e.body:void 0;return{tag,url,...name2!==""&&name2!==tag?{name:name2}:{},...publishedAt!==""?{publishedAt}:{},...body!==void 0?{body}:{}}}async function runCheck(){try{const result=await fetchWithTimeout(GITHUB_RELEASES_URL,{method:"GET",headers:{Accept:"application/json","user-agent":"billion-context-changelog"}},FETCH_TIMEOUT_MS);try{if(!result.response.ok)throw new Error(`GitHub Releases returned HTTP ${result.response.status}`);const raw=await result.response.json();if(!Array.isArray(raw))throw new Error("response is not a JSON array");const releases=[];for(const item of raw){const rel2=parseRelease(item);if(rel2!==void 0)releases.push(rel2);if(releases.length>=MAX_ENTRIES)break}state4={releases,lastCheckAt:Date.now()}}finally{if(!result.response.bodyUsed){void result.response.body?.cancel().catch(()=>{})}result.stopIdleTimer()}}catch(e){state4={...state4,lastError:"offline",lastCheckAt:Date.now()};log("warn",`[changelog] GitHub Releases check failed (${String(e)}) \u2014 serving cached view`)}}function warmChangelogOnce(){if(warmAttempted||latestChangelog()!==void 0)return;warmAttempted=true;void getChangelog()}async function getChangelog(opts){const stale=Date.now()-state4.lastCheckAt>=THROTTLE_MS;if((opts?.force??false)||stale){if(inflight2===void 0){inflight2=runCheck().finally(()=>{inflight2=void 0})}await inflight2}return{releases:state4.releases,...state4.lastError!==void 0?{error:state4.lastError}:{}}}async function handleChangelogGet(res){const data=await getChangelog();res.writeHead(200,{"content-type":"application/json"});res.end(JSON.stringify(data))}init_fetch_util();init_logger();import{readFileSync as readFileSync14,readdirSync as readdirSync7,statSync as statSync12}from"fs";import{dirname as dirname8,join as join11,resolve as resolve2,sep}from"path";import{fileURLToPath as fileURLToPath6}from"url";function makeMdRender(){function escape2(s3){return s3.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function inlineLinks(s3,image){const marker=image?"![":"[";const parts=[];let copied=0;let search=0;let urlEnd=0;while(search<s3.length){const start=s3.indexOf(marker,search);if(start<0)break;const labelStart=start+marker.length;const labelEnd=s3.indexOf("]",labelStart);if(labelEnd<0)break;search=labelEnd+1;if(s3[labelEnd+1]!=="("||!image&&labelEnd===labelStart)continue;const urlStart=labelEnd+2;search=urlStart;if(urlEnd<urlStart){urlEnd=urlStart;while(urlEnd<s3.length&&s3[urlEnd]!==")"&&!/\s/.test(s3[urlEnd]))urlEnd+=1}if(urlEnd===s3.length)break;if(urlEnd===urlStart||s3[urlEnd]!==")")continue;const label=s3.slice(labelStart,labelEnd);const url=s3.slice(urlStart,urlEnd);parts.push(s3.slice(copied,start));if(image){parts.push(/^(?:https?:\/\/|\/__bili\/blog-assets\/)/i.test(url)?`<img class="md-img" src="${url}" alt="${label}" />`:"")}else{parts.push(/^(https?:\/\/|\/)/i.test(url)?`<a href="${url}" target="_blank" rel="noopener noreferrer">${label}</a>`:label)}copied=search=urlEnd+1}parts.push(s3.slice(copied));return parts.join("")}function inlineMd(s3){let out=escape2(s3);out=out.replace(/`([^`]+)`/g,(_m,code)=>`<code>${code.replace(/[*[\]]/g,c=>`&#${c.charCodeAt(0)};`)}</code>`);out=inlineLinks(out,true);out=out.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>");out=out.replace(/(^|[^*])\*([^*\n]+)\*/g,"$1<em>$2</em>");out=inlineLinks(out,false);return out}function scan(code,re2,cls){let out="";let last=0;re2.lastIndex=0;let m2;while((m2=re2.exec(code))!==null){if(m2.index>last)out+=escape2(code.slice(last,m2.index));const c=cls(m2,code);out+=c?`<span class="${c}">${escape2(m2[0])}</span>`:escape2(m2[0]);last=m2.index+m2[0].length;if(m2[0].length===0)re2.lastIndex+=1}if(last<code.length)out+=escape2(code.slice(last));return out}const JSON_RE=/"(?:\\.|[^"\\\n])*"|\b(?:true|false|null)\b|-?\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b/g;function highlightJson(code){return scan(code,JSON_RE,m2=>{const t=m2[0];if(t[0]==='"'){const rest=code.slice(m2.index+t.length);return/^\s*:/.test(rest)?"hl-key":"hl-str"}if(t[0]==="-"||t[0]>="0"&&t[0]<="9")return"hl-num";return"hl-bool"})}const C_RE=/\/\/[^\n]*|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`\\])*`|\b\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?\b|\b(?:const|let|var|function|return|if|else|for|while|do|switch|case|break|continue|import|from|export|default|class|extends|new|delete|typeof|instanceof|in|of|void|this|super|static|async|await|try|catch|finally|throw|yield|public|private|protected|readonly|interface|type|enum|namespace|declare|implements|keyof|satisfies|as|is|fn|mut|impl|trait|struct|use|mod|pub|where|func|package|chan|map|range|defer|select|fallthrough|goto|end|begin|rescue|ensure|module|require|include)\b/g;function highlightC(code){return scan(code,C_RE,m2=>{const t=m2[0];if(t[0]==="/")return"hl-c";if(t[0]==='"'||t[0]==="'"||t[0]==="`")return"hl-str";if(t[0]>="0"&&t[0]<="9")return"hl-num";return"hl-k"})}const PY_RE=/#[^\n]*|"""[\s\S]*?"""|'''[\s\S]*?'''|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|\b\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?[jJ]?\b|\b(?:def|class|return|if|elif|else|for|while|import|from|as|with|try|except|finally|raise|pass|break|continue|lambda|yield|async|await|in|not|and|or|is|None|True|False|global|nonlocal|del|assert|match|case)\b/g;function highlightPy(code){return scan(code,PY_RE,m2=>{const t=m2[0];if(t[0]==="#")return"hl-c";if(t[0]==='"'||t[0]==="'")return"hl-str";if(t[0]>="0"&&t[0]<="9")return"hl-num";return"hl-k"})}const SH_RE=/#[^\n]*|"(?:\\.|[^"\\\n])*"|'(?:[^'\\\n]|\\.)*'|`(?:\\.|[^`\\\n])*`|\b\d+(?:\.\d+)?\b|\b(?:if|then|else|elif|fi|for|in|do|done|while|case|esac|function|local|export|return|echo|set|unset|shift|source|readonly|cd|exit|trap|select|time|eval|exec|test|declare|type|alias|unalias|read|printf)\b/g;function highlightSh(code){return scan(code,SH_RE,m2=>{const t=m2[0];if(t[0]==="#")return"hl-c";if(t[0]==='"'||t[0]==="'"||t[0]==="`")return"hl-str";if(t[0]>="0"&&t[0]<="9")return"hl-num";return"hl-k"})}function highlightDiff(code){return code.split("\n").map(ln2=>{let c="";if(ln2.startsWith("@@"))c="hl-hunk";else if(ln2.startsWith("\\")||ln2.startsWith("diff ")||ln2.startsWith("index ")||ln2.startsWith("From "))c="hl-hunk";else if(ln2.startsWith("+")&&!ln2.startsWith("+++"))c="hl-add";else if(ln2.startsWith("-")&&!ln2.startsWith("---"))c="hl-del";return c?`<span class="${c}">${escape2(ln2)}</span>`:escape2(ln2)}).join("\n")}function highlight(code,lang){const l=(lang||"").trim().toLowerCase().split(/\s+/)[0]||"";if(l==="json"||l==="json5")return highlightJson(code);if(l==="diff"||l==="patch"||l==="git")return highlightDiff(code);if(l==="py"||l==="python"||l==="ruby"||l==="rb")return highlightPy(code);if(l==="sh"||l==="bash"||l==="zsh"||l==="shell"||l==="fish"||l==="console")return highlightSh(code);if(["js","javascript","mjs","cjs","ts","typescript","jsx","tsx","go","c","cpp","cc","cxx","h","hpp","cs","java","rust","rs","kt","kts","swift","scala","dart","groovy"].indexOf(l)>-1)return highlightC(code);return escape2(code)}function render(md2){const lines=md2.split("\n");const html=[];let i=0;while(i<lines.length){const line=lines[i];if(line.startsWith("```")){const tag=line.slice(3).trim().split(/\s+/)[0]||"";const buf=[];i+=1;while(i<lines.length&&!lines[i].startsWith("```")){buf.push(lines[i]);i+=1}i+=1;const body=buf.join("\n");html.push(tag?`<pre><code class="hl-${escape2(tag)}">${highlight(body,tag)}</code></pre>`:`<pre><code>${escape2(body)}</code></pre>`);continue}const h=line.match(/^(#{1,6})\s+(.*)$/);if(h){const level=h[1].length;const inner=h[2].trim();const role=level===3&&/^(user|assistant|tool)$/i.test(inner)?inner.toLowerCase():null;html.push(role?`<h3 class="msg-role ${role}">${inlineMd(inner)}</h3>`:`<h${level}>${inlineMd(h[2])}</h${level}>`);i+=1;continue}if(/^\s*(---+|\*\*\*+)\s*$/.test(line)){html.push("<hr/>");i+=1;continue}if(/^\s*\|.*\|\s*$/.test(line)&&i+1<lines.length&&/^\s*\|[\s:|-]+\|\s*$/.test(lines[i+1])){const cells=row=>row.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(c=>inlineMd(c.trim()));const head=cells(line);i+=2;const rows=[];while(i<lines.length&&/^\s*\|.*\|\s*$/.test(lines[i])){rows.push(cells(lines[i]));i+=1}html.push(`<table class="data"><thead><tr>${head.map(c=>`<th>${c}</th>`).join("")}</tr></thead><tbody>${rows.map(r=>`<tr>${r.map(c=>`<td>${c}</td>`).join("")}</tr>`).join("")}</tbody></table>`);continue}if(/^\s{2,}\S/.test(line)){const buf=[];let indent=Infinity;while(i<lines.length&&/^\s{2,}\S/.test(lines[i])){buf.push(lines[i]);const m2=lines[i].match(/^\s*/);if(m2&&m2[0].length<indent)indent=m2[0].length;i+=1}const cut=Math.min(indent,4);html.push(`<pre><code>${escape2(buf.map(l=>l.slice(cut)).join("\n"))}</code></pre>`);continue}if(/^\s*>\s?/.test(line)){const buf=[];while(i<lines.length&&/^\s*>\s?/.test(lines[i])){buf.push(lines[i].replace(/^\s*>\s?/,""));i+=1}html.push(`<blockquote><p>${inlineMd(buf.join(" "))}</p></blockquote>`);continue}if(/^\s*[-*]\s+/.test(line)){const items=[];while(i<lines.length&&/^\s*[-*]\s+/.test(lines[i])){const rest=lines[i].replace(/^\s*[-*]\s+/,"");const task=rest.match(/^\[([ xX])\]\s+(.*)$/);items.push(task?`<li><input type="checkbox" disabled${task[1]===" "?"":" checked"}> ${inlineMd(task[2])}</li>`:`<li>${inlineMd(rest)}</li>`);i+=1}html.push(`<ul>${items.join("")}</ul>`);continue}if(/^\s*\d+[.)]\s+/.test(line)){const items=[];while(i<lines.length&&/^\s*\d+[.)]\s+/.test(lines[i])){items.push(`<li>${inlineMd(lines[i].replace(/^\s*\d+[.)]\s+/,""))}</li>`);i+=1}html.push(`<ol>${items.join("")}</ol>`);continue}if(line.trim()===""){i+=1;continue}const para=[line];i+=1;while(i<lines.length&&lines[i].trim()!==""&&!/^(#{1,6}\s|```|\s*[-*]\s|\s*\d+[.)]\s|\s*>)/.test(lines[i])){para.push(lines[i]);i+=1}html.push(`<p>${para.map(inlineMd).join("<br/>")}</p>`)}return html.join("\n")}return{escape:escape2,render,highlight}}var md=makeMdRender();function markdownToHtml(mdSource){return md.render(mdSource)}var BLOG_ASSET_PREFIX="/__bili/blog-assets";var ASSET_TYPES={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp"};var rootOverride;var probedRoot;var state5;var ASSET_SECURITY_HEADERS={"content-security-policy":"sandbox","x-content-type-options":"nosniff"};var remote;function probeRoot(){const here=dirname8(fileURLToPath6(import.meta.url));for(const cand of[join11(here,".."),join11(here,"..",".."),join11(here,"..","..","..")]){try{if(statSync12(join11(cand,"package.json")).isFile())return cand}catch{}}return void 0}function pkgRoot(){if(rootOverride!==void 0)return rootOverride;if(probedRoot===void 0)probedRoot=probeRoot();return probedRoot}function parseFrontmatter(text2){text2=text2.replace(/\r\n/g,"\n");const fm={};const src=text2.replace(/\r\n/g,"\n");let body=src;if(src.startsWith("---\n")){const end=src.indexOf("\n---\n",4);if(end!==-1){for(const line of src.slice(4,end).split("\n")){const j2=line.indexOf(":");if(j2>0)fm[line.slice(0,j2).trim()]=line.slice(j2+1).trim().replace(/^["']|["']$/g,"")}body=src.slice(end+5)}}return{fm,body}}var validDate=s3=>/^\d{4}-\d{2}-\d{2}$/.test(s3);function rewriteImages(md2,srcDirAbs,root){return md2.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(_m,_alt,target)=>{if(/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(target))return``;let abs;try{abs=resolve2(srcDirAbs,decodeURIComponent(target))}catch{return""}if(!abs.startsWith(root+sep))return"";const ext=abs.slice(abs.lastIndexOf(".")).toLowerCase();if(ASSET_TYPES[ext]===void 0||!statSyncSafe(abs))return"";const rel2=abs.slice(root.length+sep.length).split(sep).join("/");return``})}function statSyncSafe(p2){try{return statSync12(p2).isFile()}catch{return false}}var SCHEME_OR_PROTO_REL_RE=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;function resolveRepoRel(base,targetRaw){let target;try{target=decodeURIComponent(targetRaw)}catch{return void 0}if(target===""||target.includes("\0")||target.startsWith("/"))return void 0;const keep=s3=>s3!==""&&s3!==".";const out=base.split("/").filter(keep);for(const seg of target.split("/")){if(!keep(seg))continue;if(seg===".."){if(out.length===0)return void 0;out.pop();continue}out.push(seg)}return out.length>0?out.join("/"):void 0}function collectImageTargets(md2,base){const found=new Set;for(const m2 of md2.matchAll(/!\[[^\]]*\]\(([^)\s]+)\)/g)){const target=m2[1];if(SCHEME_OR_PROTO_REL_RE.test(target))continue;const rel2=resolveRepoRel(base,target);if(rel2!==void 0)found.add(rel2)}return[...found]}function rewriteImagesFromAssets(md2,assetKeys,base="website/blog/posts"){return md2.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(_m,_alt,target)=>{if(SCHEME_OR_PROTO_REL_RE.test(target))return``;const rel2=resolveRepoRel(base,target);if(rel2===void 0)return"";const ext=rel2.slice(rel2.lastIndexOf(".")).toLowerCase();if(ASSET_TYPES[ext]===void 0||!assetKeys.has(rel2))return"";return``})}function splitH1(body){const m2=body.match(/^#[ \t]+([^ \t\n][^\n]*)\r?\n?/);if(!m2)return["",body];return[m2[1].replace(/[*_`]/g,"").trim(),body.slice(m2[0].length)]}function collectPosts(root){const postsDir=join11(root,"website","blog","posts");let names=[];try{names=readdirSync7(postsDir).filter(f2=>f2.endsWith(".md")).sort()}catch{return[]}const pairs=new Map;for(const f2 of names){const base=f2.endsWith(".zh.md")?f2.slice(0,-".zh.md".length):f2.slice(0,-".md".length);if(!pairs.has(base))pairs.set(base,{});pairs.get(base)[f2.endsWith(".zh.md")?"zh":"en"]=f2}const items=postsFromPairs(pairs,name2=>{if(name2===void 0)return void 0;let raw;try{raw=readFileSync14(join11(postsDir,name2),"utf8")}catch{return void 0}const{fm,body}=parseFrontmatter(raw);const[h1,rest]=splitH1(body);return{html:markdownToHtml(rewriteImages(rest,postsDir,root)),h1,fm}});return items}function postsFromPairs(pairs,renderOne){const items=[];for(const[base,pair]of pairs){const slug=base.replace(/^\d{4}-\d{2}-\d{2}_/,"")||base;const en2=renderOne(pair.en);const zh2=renderOne(pair.zh);if(!en2&&!zh2)continue;items.push({id:slug,kind:"post",date:validDate(en2?.fm.date||"")?en2.fm.date:validDate(zh2?.fm.date||"")?zh2.fm.date:validDate(base.slice(0,10))?base.slice(0,10):"",title:en2?.fm.title||en2?.h1||slug,titleZh:zh2?.fm.title_zh||zh2?.fm.title||zh2?.h1||"",excerpt:en2?.fm.excerpt||"",excerptZh:zh2?.fm.excerpt_zh||"",html:en2?.html||"",htmlZh:zh2?.html||""})}return items}function collectArticles(root){const manifestPath=join11(root,"website","articles.json");if(!statSyncSafe(manifestPath))return[];let manifest;try{manifest=JSON.parse(readFileSync14(manifestPath,"utf8"))}catch{return[]}const list=Array.isArray(manifest?.articles)?manifest.articles:[];const items=[];for(const entryRaw of list){const entry=entryRaw;const file=typeof entry.file==="string"?entry.file:"";if(!file||file.includes("\0"))continue;let abs;try{abs=resolve2(root,decodeURIComponent(file))}catch{continue}if(!abs.startsWith(root+sep)||!statSyncSafe(abs))continue;let raw;try{raw=readFileSync14(abs,"utf8")}catch{continue}const{fm,body}=parseFrontmatter(raw);const[h1,rest]=splitH1(body);const slugIn=typeof entry.slug==="string"&&entry.slug?entry.slug:file.replace(/\.md$/,"").split("/").pop();let zhHtml="";let zhTitle="";if(typeof entry.zh_file==="string"){const zhAbs=resolve2(root,entry.zh_file);if(zhAbs.startsWith(root+sep)&&statSyncSafe(zhAbs)){try{const zparsed=parseFrontmatter(readFileSync14(zhAbs,"utf8"));const[zhH1,zhRest]=splitH1(zparsed.body);zhHtml=markdownToHtml(rewriteImages(zhRest,dirname8(zhAbs),root));zhTitle=(typeof entry.title_zh==="string"&&entry.title_zh?entry.title_zh:"")||zparsed.fm.title_zh||zparsed.fm.title||zhH1||""}catch{zhHtml=""}}}const date=(typeof entry.date==="string"?entry.date:"")||fm.date||"";items.push({id:`${slugIn}`,kind:"article",date:validDate(date)?date:"",title:(typeof entry.title==="string"&&entry.title?entry.title:"")||fm.title||h1||slugIn,titleZh:zhTitle,excerpt:fm.excerpt||"",excerptZh:fm.excerpt_zh||"",html:markdownToHtml(rewriteImages(rest,dirname8(abs),root)),htmlZh:zhHtml})}return items}function collect(){const root=pkgRoot();if(!root)return[];const articles=collectArticles(root);const articleIds=new Set(articles.map(a=>a.id));return sortItems([...collectPosts(root).filter(p2=>!articleIds.has(p2.id)),...articles])}function getBlogFeed(){if(state5===void 0){try{state5={items:collect()}}catch{state5={items:[]}}}if(remote===void 0)return{items:state5.items};const byId2=new Map;for(const item of state5.items)byId2.set(item.id,item);for(const item of remote.items)byId2.set(item.id,item);return{items:sortItems([...byId2.values()]),...remote.error!==void 0?{error:remote.error}:{}}}function sortItems(items){items.sort((a,b2)=>{if(a.date&&b2.date)return a.date===b2.date?a.id.localeCompare(b2.id):a.date<b2.date?1:-1;if(a.date!==b2.date)return a.date?-1:1;return a.id.localeCompare(b2.id)});return items}function getRemoteBlogAsset(rel2){return remote?.assets.get(rel2)}function registerRemoteBlogFeed(round){if(round.error!==void 0){remote=remote===void 0?{items:[],assets:new Map,error:round.error}:{items:remote.items,assets:remote.assets,error:round.error};return}remote={items:round.items,assets:round.assets}}var REMOTE_POST_DIR="website/blog/posts";function buildRemoteBlogPosts(files,assetKeys){const renderText=(relPath,text2)=>{try{const{fm,body}=parseFrontmatter(text2);const[h1,rest]=splitH1(body);const baseDir=relPath.includes("/")?relPath.slice(0,relPath.lastIndexOf("/")):"";return{html:markdownToHtml(rewriteImagesFromAssets(rest,assetKeys,baseDir)),h1,fm}}catch{return void 0}};const items=[];const pairs=new Map;for(const key2 of[...files.keys()].sort()){if(!key2.startsWith(REMOTE_POST_DIR+"/")||!key2.endsWith(".md"))continue;const name2=key2.slice(REMOTE_POST_DIR.length+1);if(name2.includes("/"))continue;const base=name2.endsWith(".zh.md")?name2.slice(0,-".zh.md".length):name2.slice(0,-".md".length);if(!pairs.has(base))pairs.set(base,{});pairs.get(base)[name2.endsWith(".zh.md")?"zh":"en"]=key2}items.push(...postsFromPairs(pairs,key2=>{if(key2===void 0)return void 0;const text2=files.get(key2);return text2===void 0?void 0:renderText(key2,text2)}));const manifestRaw=files.get("website/articles.json");if(manifestRaw!==void 0){let list=[];try{const parsed=JSON.parse(manifestRaw);if(Array.isArray(parsed.articles))list=parsed.articles}catch{list=[]}for(const entryRaw of list){const entry=entryRaw;const file=typeof entry.file==="string"?entry.file:"";const raw=files.get(file);if(!file||raw===void 0)continue;const en2=renderText(file,raw);const slugIn=typeof entry.slug==="string"&&entry.slug?entry.slug:file.replace(/\.md$/,"").split("/").pop();let zhHtml="";let zhTitle="";if(typeof entry.zh_file==="string"&&entry.zh_file){const zhRaw=files.get(entry.zh_file);if(zhRaw!==void 0){const zh2=renderText(entry.zh_file,zhRaw);if(zh2!==void 0){zhHtml=zh2.html;zhTitle=(typeof entry.title_zh==="string"&&entry.title_zh?entry.title_zh:"")||zh2.fm.title_zh||zh2.fm.title||zh2.h1||""}}}if(!en2)continue;const date=en2.fm.date||"";const discussion=typeof entry.discussion==="number"&&Number.isInteger(entry.discussion)&&entry.discussion>0?entry.discussion:void 0;items.push({id:slugIn,kind:"article",discussion,date:validDate(date)?date:"",title:(typeof entry.title==="string"&&entry.title?entry.title:"")||en2.fm.title||en2.h1||slugIn,titleZh:zhTitle,excerpt:en2.fm.excerpt||"",excerptZh:en2.fm.excerpt_zh||"",html:en2.html,htmlZh:zhHtml})}}return sortItems(items)}function handleBlogGet(res){const data=getBlogFeed();res.writeHead(200,{"content-type":"application/json; charset=utf-8","cache-control":"no-cache"});res.end(JSON.stringify(data))}function safeSegments(urlPath){const raw=urlPath.slice(BLOG_ASSET_PREFIX.length+1);const parts=raw===""?[]:raw.split("/");const out=[];for(const segRaw of parts){if(segRaw==="")continue;let seg;try{seg=decodeURIComponent(segRaw)}catch{return void 0}if(seg===""||seg==="."||seg===".."||seg.includes("\0"))return void 0;out.push(seg)}return out}function handleBlogAssetGet(res,urlPath){const notFound=()=>{res.writeHead(404,{"content-type":"text/plain; charset=utf-8","cache-control":"no-cache",...ASSET_SECURITY_HEADERS});res.end(`404 Not Found: ${urlPath}
|
|
1582
|
+
`)}}catch{}finally{try{res.end()}catch{}}}var reports=new Map;function recordAttributionReport(agent,report){reports.set(agent,{state:report.state,refusals:report.refusals,since:report.since,...report.error!==void 0?{error:report.error}:{},...report.endpoint!==void 0?{endpoint:report.endpoint}:{}})}function attributionStatusWire(){const out={};for(const[agent,r]of reports)out[agent]={state:r.state,refusals:r.refusals,since:r.since,...r.error!==void 0?{error:r.error}:{},...r.endpoint!==void 0?{endpoint:r.endpoint}:{}};return out}init_logger();init_ingest();var HANDOFF_REPLY_MAX_BYTES=15e5;function baseIdOfCore(m2){const text2=m2.text??"";switch(m2.contentType){case"text":if(m2.imagePart)return null;return deriveCanonicalMessageId(m2.originalRole??m2.role,"text",text2);case"reasoning":return deriveCanonicalMessageId("assistant","reasoning",text2);case"tool-call":return deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(text2),{toolName:m2.toolName});case"tool-result":return deriveCanonicalMessageId("tool","tool-result",text2,{toolName:m2.toolName});default:return null}}function restampForJoin(protocol,m2){const b2=m2;const text2=b2.text??"";if(b2.contentType==="reasoning"&&protocol==="openai"){const stamped={...b2,reasoningContent:text2};return stamped}if(b2.contentType==="tool-call"&&(protocol==="openai"||protocol==="anthropic")){try{const parsed=JSON.parse(text2);if(parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed))return{...m2,text:JSON.stringify(parsed)}}catch{}}return m2}function createHandoffReply(session,canSave=()=>true,protocol){const request=session.stats.requests;const snapshot=session.lastMessages;const messages=new Map;let bytes=0;let discarded=false;const discard=()=>{discarded=true;messages.clear()};const put=(key2,message,textBytes2,lastCodeUnit)=>{if(discarded)return;const previous=messages.get(key2);const text2=message.text??"";const measuredTextBytes=textBytes2??Buffer.byteLength(text2);const size=measuredTextBytes+Buffer.byteLength(message.toolName??"")+Buffer.byteLength(message.toolCallId??"")+128;bytes+=size-(previous?.bytes??0);if(bytes>HANDOFF_REPLY_MAX_BYTES){discard();return}messages.set(key2,{message,bytes:size,textBytes:measuredTextBytes,lastCodeUnit:lastCodeUnit??text2.charCodeAt(text2.length-1)})};return{append(key2,contentType,text2){if(!text2||discarded)return;const previous=messages.get(key2);const last=previous?.lastCodeUnit??0;const first=text2.charCodeAt(0);const joinsPair=last>=55296&&last<=56319&&first>=56320&&first<=57343;const textBytes2=(previous?.textBytes??0)+Buffer.byteLength(text2)-(joinsPair?2:0);put(key2,{id:`reply_${key2}`,role:"assistant",contentType,text:(previous?.message.text??"")+text2},textBytes2,text2.charCodeAt(text2.length-1))},tool(key2,toolName,toolCallId,text2){put(key2,{id:`reply_${key2}`,role:"assistant",contentType:"tool-call",toolName,toolCallId,text:text2})},replace(next){messages.clear();bytes=0;for(const[i,m2]of next.entries())put(String(i),{id:`reply_${i}`,role:"assistant",contentType:m2.contentType,text:m2.text,toolName:m2.toolName,toolCallId:m2.toolCallId})},discard,save(){if(discarded||!messages.size||session.stats.requests!==request||session.lastMessages!==snapshot||!canSave())return;if(session.lastMessagesFolded!==true&&Array.isArray(snapshot)){const clusters=new ClusterCounter;for(const m2 of snapshot){const b2=baseIdOfCore(m2);if(b2!==null)clusters.next(b2)}const now=Date.now();const rows=[];for(const entry of messages.values()){const m2=restampForJoin(protocol,entry.message);const b2=baseIdOfCore(m2);if(b2===null)continue;rows.push(planStoredMessageRow({...m2,id:clusters.next(b2),ts:now}))}if(rows.length>0)session.metadata["handoffReply"]={request,rows}}session.metadata.handoffResponse={request,messages:[...messages.values()].map(entry=>entry.message)};markDirty(session)}}}function captureHandoffJson(reply,protocol,json){if(!reply)return;try{if(json.error||protocol==="responses"&&json.status&&json.status!=="completed"){reply.discard();return}let messages;if(protocol==="openai"){const message=json.choices?.[0]?.message;messages=openaiToCore({messages:[message]}).msgs}else if(protocol==="anthropic"){messages=anthropicToCore({messages:[json]}).msgs}else if(protocol==="responses"){messages=responsesToCore({input:json.output}).msgs}else if(protocol==="google"){const content=json.candidates?.[0]?.content;messages=googleToCore({contents:[content]}).msgs}else return;reply.replace(messages.filter(m2=>m2.role==="assistant"))}catch(err2){log("debug",`[handoff] JSON reply capture skipped (codec failed for protocol ${protocol??"unknown"}): ${err2 instanceof Error?err2.message:String(err2)}`);reply.discard()}}init_fetch_util();init_logger();var GITHUB_RELEASES_URL="https://api.github.com/repos/ranxianglei/billion-context/releases?per_page=20";var THROTTLE_MS=10*60*1e3;var MAX_ENTRIES=20;var FETCH_TIMEOUT_MS=5e3;var state4={releases:[],lastCheckAt:0};var inflight2;var warmAttempted=false;function latestChangelog(){return state4.releases[0]}function parseRelease(raw){if(typeof raw!=="object"||raw===null)return void 0;const e=raw;const tag=typeof e.tag_name==="string"?e.tag_name.trim():"";const url=typeof e.html_url==="string"?e.html_url.trim():"";if(!tag||!url)return void 0;const name2=typeof e.name==="string"?e.name.trim():"";const publishedAt=typeof e.published_at==="string"?e.published_at.trim():"";const body=typeof e.body==="string"?e.body:void 0;return{tag,url,...name2!==""&&name2!==tag?{name:name2}:{},...publishedAt!==""?{publishedAt}:{},...body!==void 0?{body}:{}}}async function runCheck(){try{const result=await fetchWithTimeout(GITHUB_RELEASES_URL,{method:"GET",headers:{Accept:"application/json","user-agent":"billion-context-changelog"}},FETCH_TIMEOUT_MS);try{if(!result.response.ok)throw new Error(`GitHub Releases returned HTTP ${result.response.status}`);const raw=await result.response.json();if(!Array.isArray(raw))throw new Error("response is not a JSON array");const releases=[];for(const item of raw){const rel2=parseRelease(item);if(rel2!==void 0)releases.push(rel2);if(releases.length>=MAX_ENTRIES)break}state4={releases,lastCheckAt:Date.now()}}finally{if(!result.response.bodyUsed){void result.response.body?.cancel().catch(()=>{})}result.stopIdleTimer()}}catch(e){state4={...state4,lastError:"offline",lastCheckAt:Date.now()};log("warn",`[changelog] GitHub Releases check failed (${String(e)}) \u2014 serving cached view`)}}function warmChangelogOnce(){if(warmAttempted||latestChangelog()!==void 0)return;warmAttempted=true;void getChangelog()}async function getChangelog(opts){const stale=Date.now()-state4.lastCheckAt>=THROTTLE_MS;if((opts?.force??false)||stale){if(inflight2===void 0){inflight2=runCheck().finally(()=>{inflight2=void 0})}await inflight2}return{releases:state4.releases,...state4.lastError!==void 0?{error:state4.lastError}:{}}}async function handleChangelogGet(res){const data=await getChangelog();res.writeHead(200,{"content-type":"application/json"});res.end(JSON.stringify(data))}init_fetch_util();init_logger();import{readFileSync as readFileSync14,readdirSync as readdirSync7,statSync as statSync12}from"fs";import{dirname as dirname8,join as join11,resolve as resolve2,sep}from"path";import{fileURLToPath as fileURLToPath6}from"url";function makeMdRender(){function escape2(s3){return s3.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function inlineLinks(s3,image){const marker=image?"![":"[";const parts=[];let copied=0;let search=0;let urlEnd=0;while(search<s3.length){const start=s3.indexOf(marker,search);if(start<0)break;const labelStart=start+marker.length;const labelEnd=s3.indexOf("]",labelStart);if(labelEnd<0)break;search=labelEnd+1;if(s3[labelEnd+1]!=="("||!image&&labelEnd===labelStart)continue;const urlStart=labelEnd+2;search=urlStart;if(urlEnd<urlStart){urlEnd=urlStart;while(urlEnd<s3.length&&s3[urlEnd]!==")"&&!/\s/.test(s3[urlEnd]))urlEnd+=1}if(urlEnd===s3.length)break;if(urlEnd===urlStart||s3[urlEnd]!==")")continue;const label=s3.slice(labelStart,labelEnd);const url=s3.slice(urlStart,urlEnd);parts.push(s3.slice(copied,start));if(image){parts.push(/^(?:https?:\/\/|\/__bili\/blog-assets\/)/i.test(url)?`<img class="md-img" src="${url}" alt="${label}" />`:"")}else{parts.push(/^(https?:\/\/|\/)/i.test(url)?`<a href="${url}" target="_blank" rel="noopener noreferrer">${label}</a>`:label)}copied=search=urlEnd+1}parts.push(s3.slice(copied));return parts.join("")}function inlineMd(s3){let out=escape2(s3);out=out.replace(/`([^`]+)`/g,(_m,code)=>`<code>${code.replace(/[*[\]]/g,c=>`&#${c.charCodeAt(0)};`)}</code>`);out=inlineLinks(out,true);out=out.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>");out=out.replace(/(^|[^*])\*([^*\n]+)\*/g,"$1<em>$2</em>");out=inlineLinks(out,false);return out}function scan(code,re2,cls){let out="";let last=0;re2.lastIndex=0;let m2;while((m2=re2.exec(code))!==null){if(m2.index>last)out+=escape2(code.slice(last,m2.index));const c=cls(m2,code);out+=c?`<span class="${c}">${escape2(m2[0])}</span>`:escape2(m2[0]);last=m2.index+m2[0].length;if(m2[0].length===0)re2.lastIndex+=1}if(last<code.length)out+=escape2(code.slice(last));return out}const JSON_RE=/"(?:\\.|[^"\\\n])*"|\b(?:true|false|null)\b|-?\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b/g;function highlightJson(code){return scan(code,JSON_RE,m2=>{const t=m2[0];if(t[0]==='"'){const rest=code.slice(m2.index+t.length);return/^\s*:/.test(rest)?"hl-key":"hl-str"}if(t[0]==="-"||t[0]>="0"&&t[0]<="9")return"hl-num";return"hl-bool"})}const C_RE=/\/\/[^\n]*|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`\\])*`|\b\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?\b|\b(?:const|let|var|function|return|if|else|for|while|do|switch|case|break|continue|import|from|export|default|class|extends|new|delete|typeof|instanceof|in|of|void|this|super|static|async|await|try|catch|finally|throw|yield|public|private|protected|readonly|interface|type|enum|namespace|declare|implements|keyof|satisfies|as|is|fn|mut|impl|trait|struct|use|mod|pub|where|func|package|chan|map|range|defer|select|fallthrough|goto|end|begin|rescue|ensure|module|require|include)\b/g;function highlightC(code){return scan(code,C_RE,m2=>{const t=m2[0];if(t[0]==="/")return"hl-c";if(t[0]==='"'||t[0]==="'"||t[0]==="`")return"hl-str";if(t[0]>="0"&&t[0]<="9")return"hl-num";return"hl-k"})}const PY_RE=/#[^\n]*|"""[\s\S]*?"""|'''[\s\S]*?'''|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|\b\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?[jJ]?\b|\b(?:def|class|return|if|elif|else|for|while|import|from|as|with|try|except|finally|raise|pass|break|continue|lambda|yield|async|await|in|not|and|or|is|None|True|False|global|nonlocal|del|assert|match|case)\b/g;function highlightPy(code){return scan(code,PY_RE,m2=>{const t=m2[0];if(t[0]==="#")return"hl-c";if(t[0]==='"'||t[0]==="'")return"hl-str";if(t[0]>="0"&&t[0]<="9")return"hl-num";return"hl-k"})}const SH_RE=/#[^\n]*|"(?:\\.|[^"\\\n])*"|'(?:[^'\\\n]|\\.)*'|`(?:\\.|[^`\\\n])*`|\b\d+(?:\.\d+)?\b|\b(?:if|then|else|elif|fi|for|in|do|done|while|case|esac|function|local|export|return|echo|set|unset|shift|source|readonly|cd|exit|trap|select|time|eval|exec|test|declare|type|alias|unalias|read|printf)\b/g;function highlightSh(code){return scan(code,SH_RE,m2=>{const t=m2[0];if(t[0]==="#")return"hl-c";if(t[0]==='"'||t[0]==="'"||t[0]==="`")return"hl-str";if(t[0]>="0"&&t[0]<="9")return"hl-num";return"hl-k"})}function highlightDiff(code){return code.split("\n").map(ln2=>{let c="";if(ln2.startsWith("@@"))c="hl-hunk";else if(ln2.startsWith("\\")||ln2.startsWith("diff ")||ln2.startsWith("index ")||ln2.startsWith("From "))c="hl-hunk";else if(ln2.startsWith("+")&&!ln2.startsWith("+++"))c="hl-add";else if(ln2.startsWith("-")&&!ln2.startsWith("---"))c="hl-del";return c?`<span class="${c}">${escape2(ln2)}</span>`:escape2(ln2)}).join("\n")}function highlight(code,lang){const l=(lang||"").trim().toLowerCase().split(/\s+/)[0]||"";if(l==="json"||l==="json5")return highlightJson(code);if(l==="diff"||l==="patch"||l==="git")return highlightDiff(code);if(l==="py"||l==="python"||l==="ruby"||l==="rb")return highlightPy(code);if(l==="sh"||l==="bash"||l==="zsh"||l==="shell"||l==="fish"||l==="console")return highlightSh(code);if(["js","javascript","mjs","cjs","ts","typescript","jsx","tsx","go","c","cpp","cc","cxx","h","hpp","cs","java","rust","rs","kt","kts","swift","scala","dart","groovy"].indexOf(l)>-1)return highlightC(code);return escape2(code)}function render(md2){const lines=md2.split("\n");const html=[];let i=0;while(i<lines.length){const line=lines[i];if(line.startsWith("```")){const tag=line.slice(3).trim().split(/\s+/)[0]||"";const buf=[];i+=1;while(i<lines.length&&!lines[i].startsWith("```")){buf.push(lines[i]);i+=1}i+=1;const body=buf.join("\n");html.push(tag?`<pre><code class="hl-${escape2(tag)}">${highlight(body,tag)}</code></pre>`:`<pre><code>${escape2(body)}</code></pre>`);continue}const h=line.match(/^(#{1,6})\s+(.*)$/);if(h){const level=h[1].length;const inner=h[2].trim();const role=level===3&&/^(user|assistant|tool)$/i.test(inner)?inner.toLowerCase():null;html.push(role?`<h3 class="msg-role ${role}">${inlineMd(inner)}</h3>`:`<h${level}>${inlineMd(h[2])}</h${level}>`);i+=1;continue}if(/^\s*(---+|\*\*\*+)\s*$/.test(line)){html.push("<hr/>");i+=1;continue}if(/^\s*\|.*\|\s*$/.test(line)&&i+1<lines.length&&/^\s*\|[\s:|-]+\|\s*$/.test(lines[i+1])){const cells=row=>row.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(c=>inlineMd(c.trim()));const head=cells(line);i+=2;const rows=[];while(i<lines.length&&/^\s*\|.*\|\s*$/.test(lines[i])){rows.push(cells(lines[i]));i+=1}html.push(`<table class="data"><thead><tr>${head.map(c=>`<th>${c}</th>`).join("")}</tr></thead><tbody>${rows.map(r=>`<tr>${r.map(c=>`<td>${c}</td>`).join("")}</tr>`).join("")}</tbody></table>`);continue}if(/^\s{2,}\S/.test(line)){const buf=[];let indent=Infinity;while(i<lines.length&&/^\s{2,}\S/.test(lines[i])){buf.push(lines[i]);const m2=lines[i].match(/^\s*/);if(m2&&m2[0].length<indent)indent=m2[0].length;i+=1}const cut=Math.min(indent,4);html.push(`<pre><code>${escape2(buf.map(l=>l.slice(cut)).join("\n"))}</code></pre>`);continue}if(/^\s*>\s?/.test(line)){const buf=[];while(i<lines.length&&/^\s*>\s?/.test(lines[i])){buf.push(lines[i].replace(/^\s*>\s?/,""));i+=1}html.push(`<blockquote><p>${inlineMd(buf.join(" "))}</p></blockquote>`);continue}if(/^\s*[-*]\s+/.test(line)){const items=[];while(i<lines.length&&/^\s*[-*]\s+/.test(lines[i])){const rest=lines[i].replace(/^\s*[-*]\s+/,"");const task=rest.match(/^\[([ xX])\]\s+(.*)$/);items.push(task?`<li><input type="checkbox" disabled${task[1]===" "?"":" checked"}> ${inlineMd(task[2])}</li>`:`<li>${inlineMd(rest)}</li>`);i+=1}html.push(`<ul>${items.join("")}</ul>`);continue}if(/^\s*\d+[.)]\s+/.test(line)){const items=[];while(i<lines.length&&/^\s*\d+[.)]\s+/.test(lines[i])){items.push(`<li>${inlineMd(lines[i].replace(/^\s*\d+[.)]\s+/,""))}</li>`);i+=1}html.push(`<ol>${items.join("")}</ol>`);continue}if(line.trim()===""){i+=1;continue}const para=[line];i+=1;while(i<lines.length&&lines[i].trim()!==""&&!/^(#{1,6}\s|```|\s*[-*]\s|\s*\d+[.)]\s|\s*>)/.test(lines[i])){para.push(lines[i]);i+=1}html.push(`<p>${para.map(inlineMd).join("<br/>")}</p>`)}return html.join("\n")}return{escape:escape2,render,highlight}}var md=makeMdRender();function markdownToHtml(mdSource){return md.render(mdSource)}var BLOG_ASSET_PREFIX="/__bili/blog-assets";var ASSET_TYPES={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp"};var rootOverride;var probedRoot;var state5;var ASSET_SECURITY_HEADERS={"content-security-policy":"sandbox","x-content-type-options":"nosniff"};var remote;function probeRoot(){const here=dirname8(fileURLToPath6(import.meta.url));for(const cand of[join11(here,".."),join11(here,"..",".."),join11(here,"..","..","..")]){try{if(statSync12(join11(cand,"package.json")).isFile())return cand}catch{}}return void 0}function pkgRoot(){if(rootOverride!==void 0)return rootOverride;if(probedRoot===void 0)probedRoot=probeRoot();return probedRoot}function parseFrontmatter(text2){text2=text2.replace(/\r\n/g,"\n");const fm={};const src=text2.replace(/\r\n/g,"\n");let body=src;if(src.startsWith("---\n")){const end=src.indexOf("\n---\n",4);if(end!==-1){for(const line of src.slice(4,end).split("\n")){const j2=line.indexOf(":");if(j2>0)fm[line.slice(0,j2).trim()]=line.slice(j2+1).trim().replace(/^["']|["']$/g,"")}body=src.slice(end+5)}}return{fm,body}}var validDate=s3=>/^\d{4}-\d{2}-\d{2}$/.test(s3);function rewriteImages(md2,srcDirAbs,root){return md2.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(_m,_alt,target)=>{if(/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(target))return``;let abs;try{abs=resolve2(srcDirAbs,decodeURIComponent(target))}catch{return""}if(!abs.startsWith(root+sep))return"";const ext=abs.slice(abs.lastIndexOf(".")).toLowerCase();if(ASSET_TYPES[ext]===void 0||!statSyncSafe(abs))return"";const rel2=abs.slice(root.length+sep.length).split(sep).join("/");return``})}function statSyncSafe(p2){try{return statSync12(p2).isFile()}catch{return false}}var SCHEME_OR_PROTO_REL_RE=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;function resolveRepoRel(base,targetRaw){let target;try{target=decodeURIComponent(targetRaw)}catch{return void 0}if(target===""||target.includes("\0")||target.startsWith("/"))return void 0;const keep=s3=>s3!==""&&s3!==".";const out=base.split("/").filter(keep);for(const seg of target.split("/")){if(!keep(seg))continue;if(seg===".."){if(out.length===0)return void 0;out.pop();continue}out.push(seg)}return out.length>0?out.join("/"):void 0}function collectImageTargets(md2,base){const found=new Set;for(const m2 of md2.matchAll(/!\[[^\]]*\]\(([^)\s]+)\)/g)){const target=m2[1];if(SCHEME_OR_PROTO_REL_RE.test(target))continue;const rel2=resolveRepoRel(base,target);if(rel2!==void 0)found.add(rel2)}return[...found]}function rewriteImagesFromAssets(md2,assetKeys,base="website/blog/posts"){return md2.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(_m,_alt,target)=>{if(SCHEME_OR_PROTO_REL_RE.test(target))return``;const rel2=resolveRepoRel(base,target);if(rel2===void 0)return"";const ext=rel2.slice(rel2.lastIndexOf(".")).toLowerCase();if(ASSET_TYPES[ext]===void 0||!assetKeys.has(rel2))return"";return``})}function splitH1(body){const m2=body.match(/^#[ \t]+([^ \t\n][^\n]*)\r?\n?/);if(!m2)return["",body];return[m2[1].replace(/[*_`]/g,"").trim(),body.slice(m2[0].length)]}function collectPosts(root){const postsDir=join11(root,"website","blog","posts");let names=[];try{names=readdirSync7(postsDir).filter(f2=>f2.endsWith(".md")).sort()}catch{return[]}const pairs=new Map;for(const f2 of names){const base=f2.endsWith(".zh.md")?f2.slice(0,-".zh.md".length):f2.slice(0,-".md".length);if(!pairs.has(base))pairs.set(base,{});pairs.get(base)[f2.endsWith(".zh.md")?"zh":"en"]=f2}const items=postsFromPairs(pairs,name2=>{if(name2===void 0)return void 0;let raw;try{raw=readFileSync14(join11(postsDir,name2),"utf8")}catch{return void 0}const{fm,body}=parseFrontmatter(raw);const[h1,rest]=splitH1(body);return{html:markdownToHtml(rewriteImages(rest,postsDir,root)),h1,fm}});return items}function postsFromPairs(pairs,renderOne){const items=[];for(const[base,pair]of pairs){const slug=base.replace(/^\d{4}-\d{2}-\d{2}_/,"")||base;const en2=renderOne(pair.en);const zh2=renderOne(pair.zh);if(!en2&&!zh2)continue;items.push({id:slug,kind:"post",date:validDate(en2?.fm.date||"")?en2.fm.date:validDate(zh2?.fm.date||"")?zh2.fm.date:validDate(base.slice(0,10))?base.slice(0,10):"",title:en2?.fm.title||en2?.h1||slug,titleZh:zh2?.fm.title_zh||zh2?.fm.title||zh2?.h1||"",excerpt:en2?.fm.excerpt||"",excerptZh:zh2?.fm.excerpt_zh||"",html:en2?.html||"",htmlZh:zh2?.html||""})}return items}function collectArticles(root){const manifestPath=join11(root,"website","articles.json");if(!statSyncSafe(manifestPath))return[];let manifest;try{manifest=JSON.parse(readFileSync14(manifestPath,"utf8"))}catch{return[]}const list=Array.isArray(manifest?.articles)?manifest.articles:[];const items=[];for(const entryRaw of list){const entry=entryRaw;const file=typeof entry.file==="string"?entry.file:"";if(!file||file.includes("\0"))continue;let abs;try{abs=resolve2(root,decodeURIComponent(file))}catch{continue}if(!abs.startsWith(root+sep)||!statSyncSafe(abs))continue;let raw;try{raw=readFileSync14(abs,"utf8")}catch{continue}const{fm,body}=parseFrontmatter(raw);const[h1,rest]=splitH1(body);const slugIn=typeof entry.slug==="string"&&entry.slug?entry.slug:file.replace(/\.md$/,"").split("/").pop();let zhHtml="";let zhTitle="";if(typeof entry.zh_file==="string"){const zhAbs=resolve2(root,entry.zh_file);if(zhAbs.startsWith(root+sep)&&statSyncSafe(zhAbs)){try{const zparsed=parseFrontmatter(readFileSync14(zhAbs,"utf8"));const[zhH1,zhRest]=splitH1(zparsed.body);zhHtml=markdownToHtml(rewriteImages(zhRest,dirname8(zhAbs),root));zhTitle=(typeof entry.title_zh==="string"&&entry.title_zh?entry.title_zh:"")||zparsed.fm.title_zh||zparsed.fm.title||zhH1||""}catch{zhHtml=""}}}const date=(typeof entry.date==="string"?entry.date:"")||fm.date||"";items.push({id:`${slugIn}`,kind:"article",date:validDate(date)?date:"",title:(typeof entry.title==="string"&&entry.title?entry.title:"")||fm.title||h1||slugIn,titleZh:zhTitle,excerpt:fm.excerpt||"",excerptZh:fm.excerpt_zh||"",html:markdownToHtml(rewriteImages(rest,dirname8(abs),root)),htmlZh:zhHtml})}return items}function collect(){const root=pkgRoot();if(!root)return[];const articles=collectArticles(root);const articleIds=new Set(articles.map(a=>a.id));return sortItems([...collectPosts(root).filter(p2=>!articleIds.has(p2.id)),...articles])}function getBlogFeed(){if(state5===void 0){try{state5={items:collect()}}catch{state5={items:[]}}}if(remote===void 0)return{items:state5.items};const byId2=new Map;for(const item of state5.items)byId2.set(item.id,item);for(const item of remote.items)byId2.set(item.id,item);return{items:sortItems([...byId2.values()]),...remote.error!==void 0?{error:remote.error}:{}}}function sortItems(items){items.sort((a,b2)=>{if(a.date&&b2.date)return a.date===b2.date?a.id.localeCompare(b2.id):a.date<b2.date?1:-1;if(a.date!==b2.date)return a.date?-1:1;return a.id.localeCompare(b2.id)});return items}function getRemoteBlogAsset(rel2){return remote?.assets.get(rel2)}function registerRemoteBlogFeed(round){if(round.error!==void 0){remote=remote===void 0?{items:[],assets:new Map,error:round.error}:{items:remote.items,assets:remote.assets,error:round.error};return}remote={items:round.items,assets:round.assets}}var REMOTE_POST_DIR="website/blog/posts";function buildRemoteBlogPosts(files,assetKeys){const renderText=(relPath,text2)=>{try{const{fm,body}=parseFrontmatter(text2);const[h1,rest]=splitH1(body);const baseDir=relPath.includes("/")?relPath.slice(0,relPath.lastIndexOf("/")):"";return{html:markdownToHtml(rewriteImagesFromAssets(rest,assetKeys,baseDir)),h1,fm}}catch{return void 0}};const items=[];const pairs=new Map;for(const key2 of[...files.keys()].sort()){if(!key2.startsWith(REMOTE_POST_DIR+"/")||!key2.endsWith(".md"))continue;const name2=key2.slice(REMOTE_POST_DIR.length+1);if(name2.includes("/"))continue;const base=name2.endsWith(".zh.md")?name2.slice(0,-".zh.md".length):name2.slice(0,-".md".length);if(!pairs.has(base))pairs.set(base,{});pairs.get(base)[name2.endsWith(".zh.md")?"zh":"en"]=key2}items.push(...postsFromPairs(pairs,key2=>{if(key2===void 0)return void 0;const text2=files.get(key2);return text2===void 0?void 0:renderText(key2,text2)}));const manifestRaw=files.get("website/articles.json");if(manifestRaw!==void 0){let list=[];try{const parsed=JSON.parse(manifestRaw);if(Array.isArray(parsed.articles))list=parsed.articles}catch{list=[]}for(const entryRaw of list){const entry=entryRaw;const file=typeof entry.file==="string"?entry.file:"";const raw=files.get(file);if(!file||raw===void 0)continue;const en2=renderText(file,raw);const slugIn=typeof entry.slug==="string"&&entry.slug?entry.slug:file.replace(/\.md$/,"").split("/").pop();let zhHtml="";let zhTitle="";if(typeof entry.zh_file==="string"&&entry.zh_file){const zhRaw=files.get(entry.zh_file);if(zhRaw!==void 0){const zh2=renderText(entry.zh_file,zhRaw);if(zh2!==void 0){zhHtml=zh2.html;zhTitle=(typeof entry.title_zh==="string"&&entry.title_zh?entry.title_zh:"")||zh2.fm.title_zh||zh2.fm.title||zh2.h1||""}}}if(!en2)continue;const date=en2.fm.date||"";const discussion=typeof entry.discussion==="number"&&Number.isInteger(entry.discussion)&&entry.discussion>0?entry.discussion:void 0;items.push({id:slugIn,kind:"article",discussion,date:validDate(date)?date:"",title:(typeof entry.title==="string"&&entry.title?entry.title:"")||en2.fm.title||en2.h1||slugIn,titleZh:zhTitle,excerpt:en2.fm.excerpt||"",excerptZh:en2.fm.excerpt_zh||"",html:en2.html,htmlZh:zhHtml})}}return sortItems(items)}function handleBlogGet(res){const data=getBlogFeed();res.writeHead(200,{"content-type":"application/json; charset=utf-8","cache-control":"no-cache"});res.end(JSON.stringify(data))}function safeSegments(urlPath){const raw=urlPath.slice(BLOG_ASSET_PREFIX.length+1);const parts=raw===""?[]:raw.split("/");const out=[];for(const segRaw of parts){if(segRaw==="")continue;let seg;try{seg=decodeURIComponent(segRaw)}catch{return void 0}if(seg===""||seg==="."||seg===".."||seg.includes("\0"))return void 0;out.push(seg)}return out}function handleBlogAssetGet(res,urlPath){const notFound=()=>{res.writeHead(404,{"content-type":"text/plain; charset=utf-8","cache-control":"no-cache",...ASSET_SECURITY_HEADERS});res.end(`404 Not Found: ${urlPath}
|
|
1583
1583
|
`)};const clean=urlPath.split(/[?#]/)[0];if(!clean.startsWith(BLOG_ASSET_PREFIX+"/")){notFound();return}const root=pkgRoot();const segments=safeSegments(clean);if(!root||segments===void 0){notFound();return}const overlaid=getRemoteBlogAsset(segments.join("/"));if(overlaid!==void 0){res.writeHead(200,{"content-type":overlaid.type,"cache-control":"no-cache",...ASSET_SECURITY_HEADERS});res.end(overlaid.buf);return}const file=resolve2(root,...segments);if(!file.startsWith(root+sep)){notFound();return}const ext=file.slice(file.lastIndexOf(".")).toLowerCase();const type=ASSET_TYPES[ext];if(type===void 0||!statSyncSafe(file)){notFound();return}res.writeHead(200,{"content-type":type,"cache-control":"no-cache",...ASSET_SECURITY_HEADERS});res.end(readFileSync14(file))}var GITHUB_CONTENTS_URL="https://api.github.com/repos/ranxianglei/billion-context/contents";var GITHUB_RAW_BASE="https://raw.githubusercontent.com/ranxianglei/billion-context";var BRANCH="master";var POST_DIR="website/blog/posts";var MANIFEST_REL="website/articles.json";var FETCH_TIMEOUT_MS2=5e3;var ROUND_TTL_MS=60*60*1e3;var CONCURRENCY=4;var MAX_TEXT_BYTES=512*1024;var MAX_IMAGE_BYTES=2*1024*1024;var MAX_TOTAL_DOWNLOAD_BYTES=8*1024*1024;var MAX_TOTAL_FILES=200;var MAX_IMAGE_CANDIDATES=50;var TextFileNotFound=class extends Error{};var lastRoundStartedAt=0;var inflight3;var warmAttempted2=false;var remoteSnapshotPresent=false;var scheduleHandle;var disabled=false;function warmBlogRefreshOnce(){if(warmAttempted2||remoteSnapshotPresent)return;warmAttempted2=true;kickBlogRefresh({force:true})}function armSchedule(){if(scheduleHandle!==void 0||disabled)return;const t=setTimeout(()=>{scheduleHandle=void 0;kickBlogRefresh({force:true})},ROUND_TTL_MS);t.unref?.();scheduleHandle=t}function kickBlogRefresh(opts){armSchedule();if(disabled||inflight3!==void 0)return;const due=(opts?.force??false)||Date.now()-lastRoundStartedAt>=ROUND_TTL_MS;if(!due)return;lastRoundStartedAt=Date.now();const base=runRound();const gate=settleRoundImmune(base,()=>{if(inflight3===gate)inflight3=void 0});inflight3=gate}async function runRound(){const files=new Map;const assets=new Map;let downloadedBytes=0;const account=n=>{downloadedBytes+=n;if(downloadedBytes>MAX_TOTAL_DOWNLOAD_BYTES)throw new Error(`round downloads exceed ${MAX_TOTAL_DOWNLOAD_BYTES} bytes`)};const chain={start:0,used:new Set};try{const listing=await getJsonList(`${GITHUB_CONTENTS_URL}/${POST_DIR}?ref=${BRANCH}`);const names=listing.filter(e=>e.type==="file"&&typeof e.name==="string"&&e.name.endsWith(".md")).map(e=>e.name).sort();await fetchAllText(names.map(n=>({rel:`${POST_DIR}/${n}`})),files,chain,account);if(files.size===0)throw new Error("no post files returned");let entries2=[];let manifestText;try{manifestText=await getTextChain(MANIFEST_REL,chain,account)}catch(error){if(!(error instanceof TextFileNotFound))throw error}if(manifestText!==void 0){files.set(MANIFEST_REL,manifestText);try{const parsed=JSON.parse(manifestText);if(Array.isArray(parsed.articles))entries2=parsed.articles.filter(isArticleEntry)}catch{}}const wanted=[];for(const e of entries2){for(const rel2 of[e.file,...e.zh_file!==void 0?[e.zh_file]:[]]){if(isSafeRelPath(rel2)&&!wanted.includes(rel2)&&!files.has(rel2))wanted.push(rel2)}}await fetchAllText(wanted.map(rel2=>({rel:rel2})),files,chain,account);const targets=new Set;for(const[rel2,text2]of files){if(!rel2.endsWith(".md"))continue;const baseDir=rel2.includes("/")?rel2.slice(0,rel2.lastIndexOf("/")):"";for(const t of collectImageTargets(text2,baseDir)){if(ASSET_TYPES[t.slice(t.lastIndexOf(".")).toLowerCase()]!==void 0)targets.add(t)}}const targetList=[...targets].sort().slice(0,MAX_IMAGE_CANDIDATES);if(files.size+targetList.length>MAX_TOTAL_FILES){throw new Error(`round file count exceeds ${MAX_TOTAL_FILES}`)}await fetchAllBinary(targetList.map(rel2=>({rel:rel2})),assets,chain,account);registerRemoteBlogFeed({items:buildRemoteBlogPosts(files,new Set(assets.keys())),assets});remoteSnapshotPresent=true;log("info",`[blog-refresh] GitHub master round ok: ${files.size} documents, ${assets.size} images (via ${[...chain.used].join("+")})`)}catch(e){registerRemoteBlogFeed({items:[],assets:new Map,error:"offline"});log("warn",`[blog-refresh] GitHub master round failed (${String(e)}) \u2014 serving bundled/fallback content`)}}function isArticleEntry(x){const e=x;return typeof e.file==="string"&&e.file.length>0&&!e.file.includes("\0")&&(e.zh_file===void 0||typeof e.zh_file==="string")&&(e.discussion===void 0||typeof e.discussion==="number"&&Number.isInteger(e.discussion)&&e.discussion>0)}function isSafeRelPath(p2){if(p2.startsWith("/")||p2.includes("\0"))return false;return p2.split("/").every(seg=>seg!==""&&seg!=="."&&seg!=="..")}function encRelPath(rel2){return rel2.split("/").map(encodeURIComponent).join("/")}function rawUrl(rel2){return`${GITHUB_RAW_BASE}/${BRANCH}/${encRelPath(rel2)}`}function sourceChainFor(rel2){const enc=encRelPath(rel2);return[{name:"raw",url:rawUrl(rel2)},{name:"github-api",url:`${GITHUB_CONTENTS_URL}/${enc}?ref=${BRANCH}`}]}async function getJsonList(url){const result=await fetchWithTimeout(url,ghHeaders("application/json"),FETCH_TIMEOUT_MS2);try{if(!result.response.ok)throw new Error(`GitHub contents API returned HTTP ${result.response.status}`);const raw=await result.response.json();if(!Array.isArray(raw))throw new Error("contents listing is not a JSON array");return raw}finally{await releaseUnreadBody(result.response);result.stopIdleTimer()}}async function fetchPlainText(url,account){const result=await fetchWithTimeout(url,ghHeaders(),FETCH_TIMEOUT_MS2);try{if(result.response.status===404)throw new TextFileNotFound(`plain GET ${url} \u2192 HTTP 404`);if(!result.response.ok)throw new Error(`plain GET ${url} \u2192 HTTP ${result.response.status}`);const declared=contentLengthOf(result.response.headers);if(declared!==void 0&&declared>MAX_TEXT_BYTES){throw new Error(`text document exceeds ${MAX_TEXT_BYTES} bytes (content-length ${declared}): ${url}`)}const buf=await readCappedBytes(result.response.body,MAX_TEXT_BYTES);if(buf===void 0)throw new Error(`text document exceeds ${MAX_TEXT_BYTES} bytes: ${url}`);account?.(buf.byteLength);return buf.toString("utf8")}finally{await releaseUnreadBody(result.response);result.stopIdleTimer()}}async function fetchApiText(rel2,account){const url=`${GITHUB_CONTENTS_URL}/${encRelPath(rel2)}?ref=${BRANCH}`;const result=await fetchWithTimeout(url,ghHeaders("application/json"),FETCH_TIMEOUT_MS2);try{if(result.response.status===404)throw new TextFileNotFound(`contents GET ${url} \u2192 HTTP 404`);if(!result.response.ok)throw new Error(`contents GET ${url} \u2192 HTTP ${result.response.status}`);const data=await result.response.json();if(typeof data.content!=="string"){throw new Error(`contents API omitted the body (>1 MiB cap): ${rel2}`)}const buf=decodeCappedBase64(data.content,MAX_TEXT_BYTES);if(buf===void 0)throw new Error(`text document exceeds ${MAX_TEXT_BYTES} bytes: ${rel2}`);account?.(buf.byteLength);return buf.toString("utf8")}finally{await releaseUnreadBody(result.response);result.stopIdleTimer()}}async function getTextChain(rel2,chain,account){const sources2=sourceChainFor(rel2);let lastError=new Error(`all sources failed for ${rel2}`);let lastHardError;let hadHardError=false;for(let i=Math.min(chain.start,sources2.length-1);i<sources2.length;i++){try{const text2=i===1?await fetchApiText(rel2,account):await fetchPlainText(sources2[i].url,account);chain.start=Math.max(chain.start,i);chain.used.add(sources2[i].name);return text2}catch(e){lastError=e;if(!(e instanceof TextFileNotFound)){lastHardError=e;hadHardError=true}}}throw hadHardError?lastHardError:lastError}async function fetchPlainImage(url,account){let ext="";const dot=url.lastIndexOf(".");if(dot!==-1)ext=url.slice(dot).toLowerCase();const type=ASSET_TYPES[ext];if(type===void 0)return void 0;const result=await fetchWithTimeout(url,ghHeaders(),FETCH_TIMEOUT_MS2);try{if(result.response.status===404)return void 0;if(!result.response.ok)throw new Error(`image GET ${url} \u2192 HTTP ${result.response.status}`);const declared=contentLengthOf(result.response.headers);if(declared!==void 0&&declared>MAX_IMAGE_BYTES)return void 0;const buf=await readCappedBytes(result.response.body,MAX_IMAGE_BYTES);if(buf===void 0||buf.byteLength===0)return void 0;account?.(buf.byteLength);return{buf,type}}finally{await releaseUnreadBody(result.response);result.stopIdleTimer()}}async function fetchApiImage(rel2,account){const ext=rel2.slice(rel2.lastIndexOf("."));const type=ASSET_TYPES[ext.toLowerCase()];if(type===void 0)return void 0;const url=`${GITHUB_CONTENTS_URL}/${encRelPath(rel2)}?ref=${BRANCH}`;const result=await fetchWithTimeout(url,ghHeaders("application/json"),FETCH_TIMEOUT_MS2);try{if(result.response.status===404)return void 0;if(!result.response.ok)throw new Error(`contents image GET ${url} \u2192 HTTP ${result.response.status}`);const data=await result.response.json();if(typeof data.content!=="string")return void 0;const buf=decodeCappedBase64(data.content,MAX_IMAGE_BYTES);if(buf===void 0||buf.byteLength===0)return void 0;account?.(buf.byteLength);return{buf,type}}finally{await releaseUnreadBody(result.response);result.stopIdleTimer()}}async function releaseUnreadBody(response){if(!response.bodyUsed)await response.body?.cancel().catch(()=>{})}function decodeCappedBase64(content,maxBytes){const compact2=content.replace(/\s/g,"");if(Buffer.byteLength(compact2,"base64")>maxBytes)return void 0;const buf=Buffer.from(compact2,"base64");return buf.byteLength>maxBytes?void 0:buf}async function readCappedBytes(body,maxBytes){if(body===null)return Buffer.alloc(0);const reader=body.getReader();const chunks=[];let total=0;try{for(;;){const{done,value}=await reader.read();if(done)break;if(value.byteLength===0)continue;if(value.byteLength>maxBytes-total){await reader.cancel().catch(()=>{});return void 0}total+=value.byteLength;chunks.push(value)}}finally{reader.releaseLock()}return Buffer.concat(chunks,total)}async function getImageChain(rel2,chain,account){const sources2=sourceChainFor(rel2);let lastHardError;let sawCleanMiss=false;for(let i=Math.min(chain.start,sources2.length-1);i<sources2.length;i++){try{const got=i===1?await fetchApiImage(rel2,account):await fetchPlainImage(sources2[i].url,account);if(got!==void 0){chain.start=Math.max(chain.start,i);chain.used.add(sources2[i].name);return got}sawCleanMiss=true}catch(e){lastHardError=e}}if(!sawCleanMiss&&lastHardError!==void 0)throw lastHardError;return void 0}function ghHeaders(accept){const h={"user-agent":"billion-context-blog-refresh"};if(accept!==void 0)h.Accept=accept;return h}function settleRoundImmune(base,onSettle){return base.then(()=>void 0,()=>void 0).finally(onSettle)}function contentLengthOf(headers){const v2=headers.get("content-length");if(v2===null||!/^\d+$/.test(v2))return void 0;return Number(v2)}async function mapPool(items,fn){let next=0;const workers=Array.from({length:Math.min(CONCURRENCY,items.length)},async()=>{while(next<items.length){const i=next++;await fn(items[i])}});await Promise.all(workers)}async function fetchAllText(targets,sink2,chain,account){await mapPool(targets,async t=>{sink2.set(t.rel,await getTextChain(t.rel,chain,account))})}async function fetchAllBinary(targets,sink2,chain,account){await mapPool(targets,async t=>{const got=await getImageChain(t.rel,chain,account);if(got!==void 0)sink2.set(t.rel,got)})}init_billing();init_util();init_paths();import{createHash as createHash31}from"crypto";import{createHash as createHash30}from"crypto";import{createHash as createHash29}from"crypto";var MAX_TURN_FRAGS=64;function fragmentHash(kind,text2,calls){return createHash29("sha256").update(`v2f\0${canon({calls,kind,text:text2})}`).digest("hex")}var CLIENT_MARKER_RE=/^\[model changed: [^\]]*\]$/;function stripLeadingSystemRun(messages){let i=0;while(i<messages.length){const m2=messages[i];if(!m2||typeof m2!=="object")break;const role=m2.role;if(role!=="system"&&role!=="developer")break;i++}return i===0?messages:messages.slice(i)}function canon(value){return JSON.stringify(sortKeys(value))}function sortKeys(value){if(Array.isArray(value))return value.map(sortKeys);if(value!==null&&typeof value==="object"){const record3=value;const out=Object.create(null);for(const key2 of Object.keys(record3).sort())out[key2]=sortKeys(record3[key2]);return out}return value}function canonicalCallArgs(args){if(typeof args==="string"){try{return canon(JSON.parse(args))}catch{return canon(args)}}return canon(args??{})}function blockText2(block){if(!block||typeof block!=="object")return null;const b2=block;if(b2.type==="text"||b2.type==="input_text"||b2.type==="output_text"){return typeof b2.text==="string"?b2.text:""}if(b2.type==="thinking"||b2.type==="redacted_thinking"){return typeof b2.thinking==="string"?b2.thinking:""}return null}function toolResultText(content){if(typeof content==="string")return content;if(Array.isArray(content)){const parts=[];for(const b2 of content){const t=blockText2(b2);parts.push(t!==null?t:canon(b2))}return parts.join("")}return content===void 0?"":canon(content)}function neutralTurns(messages){const list=stripLeadingSystemRun(messages);const turns=[];let asst=null;let asstFrags=[];const flushAssistant=()=>{if(asst===null)return;if(asst.calls!==void 0&&asst.calls.length===0){asst={kind:"assistant",text:asst.text??"",frags:asstFrags.slice(0,MAX_TURN_FRAGS)}}else if(asst.calls!==void 0){delete asst.text;asst.frags=asstFrags.slice(0,MAX_TURN_FRAGS)}turns.push(asst);asst=null;asstFrags=[]};const pushTextTurn=(kind,text2,frags)=>{if(kind==="user"&&CLIENT_MARKER_RE.test(text2))return;turns.push({kind,text:text2,...frags?{frags}:{}})};for(const message of list){if(!message||typeof message!=="object"){turns.push({kind:"raw",text:canon(message),frags:[fragmentHash("raw",canon(message),[])]});continue}const m2=message;if(Array.isArray(m2.parts)){const role2=m2.role==="model"?"assistant":typeof m2.role==="string"?m2.role:"user";const texts=[];const calls=[];const toolBodies=[];for(const part of m2.parts){if(!part||typeof part!=="object")continue;const p2=part;if(typeof p2.text==="string"&&p2.text!==USER_IMAGE_PLACEHOLDER)texts.push(p2.text);if(p2.functionCall&&typeof p2.functionCall==="object"){const fc=p2.functionCall;calls.push(`${String(fc.name??"")}\0${canon(fc.args??{})}`)}if(p2.functionResponse&&typeof p2.functionResponse==="object"){const resp=p2.functionResponse.response;if(typeof resp==="string")toolBodies.push(resp);else if(resp&&typeof resp==="object"&&!Array.isArray(resp)){const entries2=Object.entries(resp);toolBodies.push(entries2.length===1&&typeof entries2[0][1]==="string"?entries2[0][1]:canon(resp))}else toolBodies.push(canon(resp??p2.functionResponse))}}if(role2==="assistant"){asst=asst??{kind:"assistant",text:"",calls:[]};const joined=texts.join("");asst.text=(asst.text??"")+joined;asst.calls=[...asst.calls??[],...calls];asstFrags.push(fragmentHash("assistant",joined,calls));continue}flushAssistant();for(const toolBody of toolBodies)turns.push({kind:"tool",text:toolBody,frags:[fragmentHash("tool",toolBody,[])]});if(calls.length>0&&toolBodies.length===0)turns.push({kind:"assistant",calls,frags:[fragmentHash("assistant","",calls)]});else if(texts.length>0)pushTextTurn(role2,texts.join(""),[fragmentHash(role2,texts.join(""),[])]);continue}if(typeof m2.type==="string"&&m2.type==="function_call"&&typeof m2.name==="string"){const call=`${m2.name}\0${canonicalCallArgs(m2.arguments)}`;asst=asst??{kind:"assistant",text:"",calls:[]};asst.calls=[...asst.calls??[],call];asstFrags.push(fragmentHash("assistant","",[call]));continue}if(typeof m2.type==="string"&&(m2.type==="function_call_output"||m2.type==="local_shell_call_output")){flushAssistant();const body=typeof m2.output==="string"?m2.output:canon(m2.output??"");turns.push({kind:"tool",text:body,frags:[fragmentHash("tool",body,[])]});continue}const role=typeof m2.role==="string"?m2.role:"?";if(role==="tool"){flushAssistant();const body=typeof m2.content==="string"?m2.content:Array.isArray(m2.content)?m2.content.map(b2=>{const t=blockText2(b2);return t!==null?t:canon(b2)}).join(""):m2.content===void 0||m2.content===null?"":canon(m2.content);turns.push({kind:"tool",text:body,frags:[fragmentHash("tool",body,[])]});continue}if((typeof m2.content==="string"||m2.content===void 0||m2.content===null)&&!Array.isArray(m2.tool_calls)){const text2=m2.content??"";if(role==="assistant"){asst=asst??{kind:"assistant",text:"",calls:[]};const own=text2+(typeof m2.reasoning_content==="string"?m2.reasoning_content:"");asst.text=(asst.text??"")+own;asstFrags.push(fragmentHash("assistant",own,[]));continue}flushAssistant();pushTextTurn(role,text2,[fragmentHash(role,text2,[])]);continue}if(Array.isArray(m2.content)){const texts=[];const calls=[];const results=[];let foreign=false;for(const block of m2.content){if(!block||typeof block!=="object"){foreign=true;continue}const b2=block;if(b2.type==="tool_use"){calls.push(`${String(b2.name??"")}\0${canonicalCallArgs(b2.input)}`)}else if(b2.type==="tool_result"){results.push(toolResultText(b2.content))}else{const t=blockText2(b2);if(t===USER_IMAGE_PLACEHOLDER)continue;if(t!==null)texts.push(t);else foreign=true}}if(role==="assistant"){asst=asst??{kind:"assistant",text:"",calls:[]};const ownText=texts.join("")+(foreign?"\0foreign:"+canon(m2.content):"");asst.text=(asst.text??"")+ownText;asst.calls=[...asst.calls??[],...calls];asstFrags.push(fragmentHash("assistant",ownText,calls));continue}flushAssistant();for(const r of results)turns.push({kind:"tool",text:r,frags:[fragmentHash("tool",r,[])]});if(results.length>0&&texts.length>0&&role==="user")pushTextTurn("user",texts.join(""),[fragmentHash("user",texts.join(""),[])]);else if(results.length===0&&texts.length>0)pushTextTurn(role,texts.join(""),[fragmentHash(role,texts.join(""),[])]);else if(results.length===0&&texts.length===0&&role==="user"&&foreign)pushTextTurn("user",canon(m2.content),[fragmentHash("user",canon(m2.content),[])]);continue}if(Array.isArray(m2.tool_calls)){if(role==="assistant"){asst=asst??{kind:"assistant",text:"",calls:[]};const calls=m2.tool_calls.filter(tc=>!!tc&&typeof tc==="object").map(tc=>`${String(tc.function?.name??"")}\0${canonicalCallArgs(tc.function?.arguments)}`);asst.calls=[...asst.calls??[],...calls];asstFrags.push(fragmentHash("assistant","",calls));continue}}flushAssistant();turns.push({kind:role,text:canon(m2),frags:[fragmentHash(role,canon(m2),[])]})}flushAssistant();return turns}function neutralTurnCanonical(turn){if(turn.calls!==void 0)return canon({calls:turn.calls,role:turn.kind});return canon({content:turn.text??"",role:turn.kind})}var MIN_CANONICAL_BYTES=24;var MAX_TRACKED_SESSIONS2=1024;var TRUNCATION_LINEAGE_WINDOW=8;var MAX_STORED_ITEMS=128;var MIN_FORK_PREFIX=3;var MIN_RESUME_PREFIX=8;var ALIGN_SIMILAR_HAMMING=10;var ALIGN_DIVERGENT_HAMMING=32;var ALIGN_COVERAGE_MIN=.9;var ALIGN_PERVASIVE_MIN_FRACTION=.2;var ALIGN_PERVASIVE_MIN_POSITIONS=2;var ALIGN_EXACT_ANCHOR_MIN=1;var ALIGN_MIN_DEPTH=8;var ALIGN_TAIL_APPEND_MAX=64;var SKETCH_MAX_CHAINS=64;var SKETCH_MAX_DEPTH=2048;var SKETCH_TTL_MS=24*60*60*1e3;var simhashAdoptionEnabled=true;function stableStringify(value){return JSON.stringify(sortKeys2(value))}function sortKeys2(value){if(Array.isArray(value))return value.map(sortKeys2);if(value&&typeof value==="object"){const record3=value;const out=Object.create(null);for(const key2 of Object.keys(record3).sort())out[key2]=sortKeys2(record3[key2]);return out}return value}function canonicalForHash(value){return JSON.stringify(canonicalize4(value))}function canonicalize4(value){if(Array.isArray(value))return value.map(canonicalize4);if(value&&typeof value==="object"){const record3=value;const out=Object.create(null);for(const key2 of Object.keys(record3).sort()){if(key2==="cache_control")continue;out[key2]=canonicalize4(record3[key2])}return out}return value}function sha2562(text2){return createHash30("sha256").update(text2,"utf8").digest("hex")}function hasUserMessage(messages){return messages.some(m2=>!!m2&&typeof m2==="object"&&m2.role==="user")}function chainHashes(messages){const hashes=[];let prev="";let bytes=0;for(const message of messages){const canonical2=canonicalForHash(message);bytes+=canonical2.length;prev=sha2562(`${prev}\0${canonical2}`);hashes.push(prev)}return bytes>=MIN_CANONICAL_BYTES?hashes:[]}function perItemHashes(messages){return messages.map(m2=>sha2562(canonicalForHash(m2)))}function neutralFingerprints(turns,sketchCap=0){const hashes=[];const itemHashes=[];const sketches=[];const userFlags=[];let prev="v2";let bytes=0;for(const turn of turns){const canonical2=neutralTurnCanonical(turn);bytes+=canonical2.length;const h=sha2562(`v2i\0${canonical2}`);prev=sha2562(`${prev}\0${canonical2}`);hashes.push(prev);itemHashes.push(h);if(sketches.length<sketchCap)sketches.push(sketchForCanonical(canonical2,h));userFlags.push(turn.kind==="user")}return{hashes:bytes>=MIN_CANONICAL_BYTES?hashes:[],itemHashes,sketches,userFlags}}function neutralTailHashOf(turns,depth=turns.length){const tail=depth>=1?turns[depth-1]:void 0;if(!tail)return void 0;if(tail.calls!==void 0){if(tail.calls.length===0)return void 0;const text3=normalizeMessageText(tail.calls.join("\n"));return text3?sha2562(`chain-norm2\0${text3}`):void 0}if(typeof tail.text!=="string"||tail.text==="")return void 0;const lines=tail.text.split("\n").filter(l=>l!==USER_IMAGE_PLACEHOLDER);const text2=normalizeMessageText(lines.join("\n"));if(!text2)return void 0;return sha2562(`chain-norm2\0${tail.kind}\0${text2}`)}function lcpLength(a,b2){const n=Math.min(a.length,b2.length);let i=0;while(i<n&&a[i]===b2[i])i++;return i}function normalizeAffinityMessages(messages){let i=0;while(i<messages.length){const m2=messages[i];if(!m2||typeof m2!=="object")break;const role=m2.role;if(role!=="system"&&role!=="developer")break;i++}return i===0?messages:messages.slice(i)}var NORM_CHURN_KEYS=new Set(["signature","id","cache_control","tool_use_id","server_tool_use_id","web_search_tool_result_id"]);var MIN_NORM_LEAF_LEN=32;function normalizedTailHashOf(messages,depth=messages.length){const tail=depth>=1?messages[depth-1]:void 0;if(!tail||typeof tail!=="object")return void 0;const leaves=[];const walk=(v2,key2)=>{if(typeof v2==="string"){if(key2==="role"){leaves.push(`role\0${v2}`);return}if(key2===void 0||NORM_CHURN_KEYS.has(key2))return;if(v2.length>=MIN_NORM_LEAF_LEN)leaves.push(v2);return}if(v2===null||typeof v2!=="object")return;if(Array.isArray(v2)){for(const item of v2)walk(item);return}for(const k2 of Object.keys(v2).sort())walk(v2[k2],k2)};walk(tail);if(leaves.length===0)return void 0;leaves.sort();const lines=leaves.join("\n").split("\n").filter(l=>l!==USER_IMAGE_PLACEHOLDER);const text2=normalizeMessageText(lines.join("\n"));if(!text2)return void 0;return sha2562(`chain-norm\0${text2}`)}function containsRun(haystack,needle){const w2=needle.length;if(w2===0||haystack.length<w2+1)return false;for(let j2=1;j2+w2<=haystack.length;j2++){let hit=true;for(let i=0;i<w2;i++){if(haystack[j2+i]!==needle[i]){hit=false;break}}if(hit)return true}return false}function describeResumeMiss(report){const b2=report.best;if(!b2){const scope=report.declaredParentState!==void 0?`; declared parent chain ${report.declaredParentState}`:"";return`no eligible tracked chain (floor ${MIN_RESUME_PREFIX}${scope})`}switch(b2.kind){case"equal-depth":return`no byte-exact resume among ${report.eligible} eligible chain(s); closest ${b2.sessionId} is a byte-exact EQUAL-DEPTH replay (${b2.chainDepth} cells == incoming ${b2.incomingDepth}) \u2014 rejected by design; either a duplicate conversation or a branch taken at the parent's last-request depth \u2014 content cannot distinguish`;case"truncated":return`no byte-exact resume among ${report.eligible} eligible chain(s); closest ${b2.sessionId} (chain ${b2.chainDepth}) is LONGER than the incoming history (${b2.incomingDepth} cells)${b2.tailWindowIntact?`, visible cells ${b2.windowStart}..${b2.incomingDepth-1} intact \u2014 truncated replay`:""}`;case"prefix-break":{let detail;if(b2.firstDivergence!==null){detail=b2.windowStart>0?`first divergence found at cell ${b2.firstDivergence} (stored ${b2.storedCell} vs incoming ${b2.incomingCell}; cells 0..${b2.windowStart-1} uninspectable \u2014 chain deeper than the ${MAX_STORED_ITEMS}-cell window)`:`first divergence at cell ${b2.firstDivergence} (stored ${b2.storedCell} vs incoming ${b2.incomingCell})`}else if(b2.tailWindowIntact){detail=`tail window (cells ${b2.windowStart}..${Math.min(b2.chainDepth,b2.incomingDepth)-1}) byte-intact \u2014 break sits BEFORE cell ${b2.windowStart}`}else{detail="head-anchored prefix broken (no inspectable overlap)"}return`no byte-exact resume among ${report.eligible} eligible chain(s); closest ${b2.sessionId} (chain ${b2.chainDepth}, incoming ${b2.incomingDepth}): ${detail}`}}}var PrefixAffinityResolver=class{trackedChains=new Map;resolve(input){if(!hasUserMessage(input))return null;const turns=neutralTurns(input);const fingerprints=neutralFingerprints(turns,SKETCH_MAX_DEPTH);const hashes=fingerprints.hashes;const incomingDepth=hashes.length;const messages=normalizeAffinityMessages(input);let hasHv1=false;for(const entry of this.trackedChains.values()){if(entry.hv===1){hasHv1=true;break}}const v1Hashes=hasHv1||incomingDepth===0?chainHashes(messages):[];const v1Depth=v1Hashes.length;if(incomingDepth===0&&v1Depth===0)return null;const tailHash=incomingDepth>0?hashes[incomingDepth-1]:v1Hashes[v1Depth-1];const incItemHashes=fingerprints.itemHashes;const incSketches=fingerprints.sketches;const incUserFlags=fingerprints.userFlags;const storedItemHashes=incItemHashes.slice(-MAX_STORED_ITEMS);const tracked2=this.trackedChains;const tailFragments=turns.length>0?turns[turns.length-1].frags:void 0;let best;for(const entry of tracked2.values()){if(entry.identified)continue;if(entry.hv===2){if(incomingDepth===0||entry.depth>incomingDepth)continue;if(hashes[entry.depth-1]!==entry.tailHash)continue}else{if(v1Depth===0||entry.depth>v1Depth)continue;if(v1Hashes[entry.depth-1]!==entry.tailHash)continue}const better=!best||entry.hv===2&&best.hv===1||entry.hv===best.hv&&(entry.depth>best.depth||entry.depth===best.depth&&entry.lastSeen>best.lastSeen);if(better)best=entry}if(best){return{sessionId:best.sessionId,matchedDepth:best.depth,storedDepth:best.depth,incomingDepth,tailHash,via:"prefix",itemHashes:storedItemHashes,sketches:incSketches,userFlags:incUserFlags.slice(-MAX_STORED_ITEMS),...tailFragments?{tailFragments}:{}}}if(incomingDepth>=2){let cont;for(const entry of tracked2.values()){if(entry.identified||entry.hv!==2)continue;const storedFrags=entry.tailFrags;if(storedFrags===void 0||storedFrags.length===0)continue;const depth=entry.depth;if(depth<2||depth>MAX_STORED_ITEMS||incomingDepth<depth+1)continue;let eq=true;for(let i=0;i<depth-1;i++){if(incItemHashes[i]!==entry.itemHashes[i]){eq=false;break}}if(!eq)continue;const incFrags=turns[depth-1]?.frags;if(incFrags===void 0||incFrags.length<=storedFrags.length)continue;let prefix=true;for(let i=0;i<storedFrags.length;i++){if(incFrags[i]!==storedFrags[i]){prefix=false;break}}if(!prefix)continue;if(!cont||depth>cont.depth||depth===cont.depth&&entry.lastSeen>cont.lastSeen)cont=entry}if(cont){return{sessionId:cont.sessionId,matchedDepth:cont.depth-1,storedDepth:cont.depth,incomingDepth,tailHash,via:"prefix",itemHashes:storedItemHashes,sketches:incSketches,userFlags:incUserFlags.slice(-MAX_STORED_ITEMS),...tailFragments?{tailFragments}:{}}}}if(simhashAdoptionEnabled&&incomingDepth>0){const adopted=this.simhashAdopt(incomingDepth,incSketches,incItemHashes,incUserFlags);if(adopted){return{sessionId:adopted.sessionId,matchedDepth:adopted.depth,storedDepth:adopted.depth,incomingDepth,tailHash,via:"simhash",itemHashes:storedItemHashes,sketches:incSketches,userFlags:incUserFlags.slice(-MAX_STORED_ITEMS),adoption:{coverage:adopted.coverage,meanHamming:adopted.meanHamming},...tailFragments?{tailFragments}:{}}}}let lineage=this.lineageOf(storedItemHashes,incomingDepth);if(lineage===void 0&&v1Depth>0){lineage=this.lineageOf(perItemHashes(messages).slice(-MAX_STORED_ITEMS),v1Depth)}let orphanSuspect;for(const entry of tracked2.values()){if(!entry.identified||entry.depth<MIN_RESUME_PREFIX)continue;const domainHashes=entry.hv===2?hashes:v1Hashes;if(domainHashes.length<entry.depth||domainHashes.length>entry.depth+ALIGN_TAIL_APPEND_MAX)continue;if(domainHashes[entry.depth-1]!==entry.tailHash)continue;if(orphanSuspect){orphanSuspect=void 0;break}orphanSuspect=[entry.sessionId]}const sessionId=`pfa-${sha2562(`${tailHash}\0${incomingDepth}`).slice(0,16)}`;return{sessionId,matchedDepth:0,storedDepth:0,incomingDepth,tailHash,via:"new",itemHashes:storedItemHashes,sketches:incSketches,userFlags:incUserFlags.slice(-MAX_STORED_ITEMS),...tailFragments?{tailFragments}:{},...lineage?{lineage}:{},...orphanSuspect?{orphanSuspect}:{}}}lineageOf(incItemHashes,incomingDepth){let forkParent;let forkLcp=0;for(const entry of this.trackedChains.values()){if(entry.depth>MAX_STORED_ITEMS)continue;const lcp=lcpLength(incItemHashes,entry.itemHashes);if(lcp>=MIN_FORK_PREFIX&&lcp>forkLcp){forkLcp=lcp;forkParent=entry}}if(forkParent)return{parents:[forkParent.sessionId],reason:"forked",sharedPrefix:forkLcp};const w2=Math.min(TRUNCATION_LINEAGE_WINDOW,incomingDepth);if(w2>=MIN_FORK_PREFIX){const needle=incItemHashes.slice(0,w2);const parents=[];for(const entry of this.trackedChains.values()){if(containsRun(entry.itemHashes,needle))parents.push(entry.sessionId)}if(parents.length>0)return{parents,reason:"truncated"}}return void 0}simhashAdopt(incomingDepth,incSketches,itemHashes,incUserFlags){if(incSketches.length<ALIGN_MIN_DEPTH)return null;const now=Date.now();let winner=null;let passing=0;for(const entry of this.trackedChains.values()){if(entry.identified)continue;if(entry.hv!==2)continue;if(!entry.sketches||entry.sketches.length<ALIGN_MIN_DEPTH)continue;if(now-entry.lastSeen>SKETCH_TTL_MS)continue;if(incomingDepth<entry.depth)continue;if(incomingDepth-entry.depth>ALIGN_TAIL_APPEND_MAX)continue;const alignLen=Math.min(entry.depth,entry.sketches.length,incSketches.length);if(alignLen<ALIGN_MIN_DEPTH)continue;let similar=0;let mutated=0;let total=0;for(let i=0;i<alignLen;i++){const d=hammingHex(incSketches[i],entry.sketches[i]);if(d<0||d>ALIGN_DIVERGENT_HAMMING){similar=-1;break}total+=d;if(d<=ALIGN_SIMILAR_HAMMING){similar++;if(d>0)mutated++}}if(similar<0)continue;const coverage=similar/alignLen;if(coverage<ALIGN_COVERAGE_MIN)continue;if(mutated<Math.max(ALIGN_PERVASIVE_MIN_POSITIONS,alignLen*ALIGN_PERVASIVE_MIN_FRACTION))continue;const entryHashes=entry.itemHashes;const entryUsers=entry.userFlags;if(!entryUsers)continue;let exactUser=0;for(let i=0;i<entryHashes.length&&i<entryUsers.length;i++){if(!entryUsers[i])continue;const rawPos=entry.depth-entryHashes.length+i;if(rawPos<0||rawPos>=itemHashes.length||rawPos>=incUserFlags.length)continue;if(incUserFlags[rawPos]&&itemHashes[rawPos]===entryHashes[i])exactUser++}if(exactUser<ALIGN_EXACT_ANCHOR_MIN)continue;passing++;if(passing>1)return null;winner={entry,coverage,meanHamming:total/alignLen}}return winner?{sessionId:winner.entry.sessionId,depth:winner.entry.depth,coverage:winner.coverage,meanHamming:winner.meanHamming}:null}note(sessionId,depth,tailHash,itemHashes,identified=false,sketches,userFlags,normTailHash,tailFrags){const tracked2=this.trackedChains;tracked2.delete(sessionId);const storedSketches=!identified&&sketches&&sketches.length>0?sketches.slice(0,SKETCH_MAX_DEPTH):void 0;const storedUsers=storedSketches!==void 0&&userFlags&&userFlags.length>0?userFlags.slice(-MAX_STORED_ITEMS):void 0;tracked2.set(sessionId,{sessionId,hv:2,depth,tailHash,itemHashes,lastSeen:Date.now(),identified,sketches:storedSketches,userFlags:storedUsers,...normTailHash?{normTailHash}:{},...tailFrags&&tailFrags.length>0?{tailFrags:tailFrags.slice(0,MAX_TURN_FRAGS)}:{}});if(storedSketches!==void 0){const withSketches=[...tracked2.values()].filter(e=>e.sketches!==void 0);if(withSketches.length>SKETCH_MAX_CHAINS){const drop=new Set(withSketches.sort((a,b2)=>a.lastSeen-b2.lastSeen).slice(0,withSketches.length-SKETCH_MAX_CHAINS).map(e=>e.sessionId));for(const id of drop){const e=tracked2.get(id);if(e){delete e.sketches;delete e.userFlags}}}}while(tracked2.size>MAX_TRACKED_SESSIONS2){const oldest=[...tracked2.values()].sort((a,b2)=>a.lastSeen-b2.lastSeen)[0];if(!oldest)break;tracked2.delete(oldest.sessionId)}}peekChain(sessionId){return this.trackedChains.get(sessionId)}chainFingerprint(messages){if(!hasUserMessage(normalizeAffinityMessages(messages)))return null;const turns=neutralTurns(messages);const fingerprints=neutralFingerprints(turns,0);if(fingerprints.hashes.length===0)return null;return{depth:turns.length,tailHash:fingerprints.hashes[fingerprints.hashes.length-1],itemHashes:fingerprints.itemHashes.slice(-MAX_STORED_ITEMS),normTailHash:neutralTailHashOf(turns),...turns[turns.length-1]?.frags?{tailFrags:turns[turns.length-1].frags}:{}}}findResumeParent(messages,selfSessionId){const msgs=normalizeAffinityMessages(messages);if(!hasUserMessage(msgs))return null;const turns=neutralTurns(messages);const hashesV2=neutralFingerprints(turns,0).hashes;const hashesV1=chainHashes(msgs);if(hashesV2.length<MIN_RESUME_PREFIX&&hashesV1.length<MIN_RESUME_PREFIX)return null;let best=null;for(const[id,entry]of this.trackedChains){if(id===selfSessionId)continue;if(entry.depth<MIN_RESUME_PREFIX)continue;const hashes=entry.hv===2?hashesV2:hashesV1;const len=entry.hv===2?turns.length:msgs.length;if(hashes.length<MIN_RESUME_PREFIX||len<=entry.depth)continue;if(hashes[entry.depth-1]!==entry.tailHash)continue;if(!best||entry.depth>best.sharedDepth||entry.depth===best.sharedDepth&&entry.lastSeen>best.lastSeen){best={sessionId:id,sharedDepth:entry.depth,lastSeen:entry.lastSeen}}}return best?{sessionId:best.sessionId,sharedDepth:best.sharedDepth}:null}findResumeParentWithin(parentId,messages,selfSessionId){if(parentId===selfSessionId)return null;const entry=this.trackedChains.get(parentId);if(entry===void 0||entry.depth<MIN_RESUME_PREFIX)return null;const msgs=normalizeAffinityMessages(messages);if(!hasUserMessage(msgs))return null;const turns=neutralTurns(messages);const hashes=entry.hv===2?neutralFingerprints(turns,0).hashes:chainHashes(msgs);const len=entry.hv===2?turns.length:msgs.length;if(hashes.length<MIN_RESUME_PREFIX)return null;if(len<=entry.depth)return null;if(hashes[entry.depth-1]!==entry.tailHash)return null;return{sessionId:parentId,sharedDepth:entry.depth}}diagnoseResumeMiss(messages,selfSessionId,declaredParent){const msgs=normalizeAffinityMessages(messages);if(!hasUserMessage(msgs))return{eligible:0};const turns=neutralTurns(messages);const fp2=neutralFingerprints(turns,0);const hashesV2=fp2.hashes;const hashesV1=chainHashes(msgs);if(hashesV2.length===0&&hashesV1.length===0)return{eligible:0};const cands=[];let declaredParentState;const consider=(id,entry)=>{if(id===selfSessionId)return;if(entry.depth<MIN_RESUME_PREFIX)return;const hv22=entry.hv===2;const hashes=hv22?hashesV2:hashesV1;const len2=hv22?turns.length:msgs.length;if(hashes.length<MIN_RESUME_PREFIX)return;let kind;if(len2<entry.depth)kind="truncated";else if(len2===entry.depth&&hashes[entry.depth-1]===entry.tailHash)kind="equal-depth";else kind="prefix-break";cands.push({id,entry,kind,rank:kind==="equal-depth"?0:kind==="prefix-break"?1:2})};if(declaredParent!==void 0&&declaredParent!==selfSessionId){const entry=this.trackedChains.get(declaredParent);if(entry===void 0)declaredParentState="untracked";else if(entry.depth<MIN_RESUME_PREFIX)declaredParentState="too-shallow";else consider(declaredParent,entry)}else if(declaredParent===void 0){for(const[id,entry]of this.trackedChains)consider(id,entry)}if(cands.length===0)return{eligible:0,...declaredParentState!==void 0?{declaredParentState}:{}};cands.sort((a,b2)=>a.rank-b2.rank||b2.entry.depth-a.entry.depth||b2.entry.lastSeen-a.entry.lastSeen);const top=cands[0];const hv2=top.entry.hv===2;const depth=top.entry.depth;const len=hv2?turns.length:msgs.length;const itemIncoming=hv2?fp2.itemHashes:perItemHashes(msgs);const windowStart=Math.max(0,depth-top.entry.itemHashes.length);const end=Math.min(depth,len);let firstDivergence=null;let tailWindowIntact=false;if(windowStart<end){tailWindowIntact=true;for(let i=windowStart;i<end;i++){if(itemIncoming[i]!==top.entry.itemHashes[i-windowStart]){firstDivergence=i;tailWindowIntact=false;break}}}const best={sessionId:top.id,chainDepth:depth,incomingDepth:len,hashDomain:hv2?2:1,kind:top.kind,firstDivergence,windowStart,tailWindowIntact,...firstDivergence!==null?{incomingCell:itemIncoming[firstDivergence]?.slice(0,8),storedCell:top.entry.itemHashes[firstDivergence-windowStart]?.slice(0,8)}:{}};return{eligible:cands.length,...declaredParentState!==void 0?{declaredParentState}:{},best}}chainContinues(messages,sessionId){const entry=this.trackedChains.get(sessionId);if(!entry)return false;const msgs=normalizeAffinityMessages(messages);if(!hasUserMessage(msgs))return false;if(entry.hv===2){const turns=neutralTurns(messages);const hashes2=neutralFingerprints(turns,0).hashes;if(hashes2.length===0||turns.length<entry.depth)return false;if(hashes2[entry.depth-1]===entry.tailHash)return true;return entry.normTailHash!==void 0&&neutralTailHashOf(turns,entry.depth)===entry.normTailHash}const hashes=chainHashes(msgs);if(hashes.length===0||msgs.length<entry.depth)return false;if(hashes[entry.depth-1]===entry.tailHash)return true;return entry.normTailHash!==void 0&&normalizedTailHashOf(msgs,entry.depth)===entry.normTailHash}forget(sessionId){this.trackedChains.delete(sessionId)}trackedSessionIds(){return[...this.trackedChains.keys()]}exportSnapshot(){return[...this.trackedChains.values()].map(e=>({sessionId:e.sessionId,...e.hv===2?{hv:2}:{},depth:e.depth,tailHash:e.tailHash,itemHashes:e.itemHashes,lastSeen:e.lastSeen,identified:e.identified,...e.normTailHash?{normTailHash:e.normTailHash}:{},...e.tailFrags&&e.tailFrags.length>0?{tailFrags:e.tailFrags}:{},...e.sketches?{sketches:e.sketches,...e.userFlags?{userFlags:e.userFlags}:{}}:{}}))}importSnapshot(entries2){if(!Array.isArray(entries2))return 0;let imported=0;for(const raw of entries2){if(!raw||typeof raw!=="object")continue;const e=raw;if(typeof e.sessionId!=="string"||typeof e.depth!=="number"||typeof e.tailHash!=="string")continue;if(!Array.isArray(e.itemHashes)||e.itemHashes.some(h=>typeof h!=="string"))continue;if(typeof e.lastSeen!=="number")continue;const hv=e.hv===2?2:1;let sketches;if(hv===2&&Array.isArray(e.sketches)){const slots=Array.from(e.sketches);if(slots.every(s3=>typeof s3==="string"&&/^[0-9a-f]{16}$/.test(s3))&&slots.length>=ALIGN_MIN_DEPTH)sketches=slots.slice(0,SKETCH_MAX_DEPTH)}let userFlags;if(sketches!==void 0&&Array.isArray(e.userFlags)){const flags=Array.from(e.userFlags);if(flags.every(u2=>typeof u2==="boolean")&&flags.length>0)userFlags=flags.slice(-MAX_STORED_ITEMS)}const entry={sessionId:e.sessionId,hv,depth:e.depth,tailHash:e.tailHash,itemHashes:e.itemHashes.slice(-MAX_STORED_ITEMS),lastSeen:e.lastSeen,identified:e.identified===true,sketches,...typeof e.normTailHash==="string"&&/^[0-9a-f]{64}$/.test(e.normTailHash)?{normTailHash:e.normTailHash}:{},...userFlags?{userFlags}:{}};if(hv===2&&Array.isArray(e.tailFrags)){const frags=Array.from(e.tailFrags);if(frags.every(f2=>typeof f2==="string"&&/^[0-9a-f]{64}$/.test(f2))&&frags.length>0)entry.tailFrags=frags.slice(0,MAX_TURN_FRAGS)}this.trackedChains.delete(entry.sessionId);this.trackedChains.set(entry.sessionId,entry);imported++}while(this.trackedChains.size>MAX_TRACKED_SESSIONS2){const oldest=[...this.trackedChains.values()].sort((a,b2)=>a.lastSeen-b2.lastSeen)[0];if(!oldest)break;this.trackedChains.delete(oldest.sessionId)}return imported}};var prefixAffinity=new PrefixAffinityResolver;var RING_CAPACITY=32;var WITNESS_TTL_MS=10*60*1e3;var rings=new Map;var hashIndex=new Map;var lastRecordSweepAt;var clockForTest;function nowMs(){return clockForTest?clockForTest():Date.now()}function sha2563(text2){return createHash31("sha256").update(text2,"utf8").digest("hex")}function normalizeToolName(name2){const idx=name2.lastIndexOf("__");return idx>=0?name2.slice(idx+2):name2}function witnessHash(name2,args){let canonicalArgs="{}";if(typeof args==="string"){const trimmed=args.trim();if(trimmed.length>0){try{canonicalArgs=stableStringify(JSON.parse(trimmed))}catch{return""}}}else if(args!==null&&args!==void 0){canonicalArgs=stableStringify(args)}const parsed=JSON.parse(canonicalArgs);if(parsed===null||typeof parsed!=="object")return"";const obj=parsed;if("conversation_id"in obj){delete obj.conversation_id;canonicalArgs=stableStringify(obj)}return sha2563(`${normalizeToolName(name2)}\0${canonicalArgs}`)}function dropFromIndex(hash,sessionId){const sessions2=hashIndex.get(hash);if(!sessions2)return;sessions2.delete(sessionId);if(sessions2.size===0)hashIndex.delete(hash)}function dropFromIndexIfAbsent(ring,hash,sessionId){if(ring.some(e=>e.hash===hash))return;dropFromIndex(hash,sessionId)}function sweep(sessionId,now){const ring=rings.get(sessionId);if(!ring)return;while(ring.length>0&&now-ring[0].at>WITNESS_TTL_MS){const dead=ring.shift();if(!dead)break;dropFromIndexIfAbsent(ring,dead.hash,sessionId)}if(ring.length===0)rings.delete(sessionId)}function recordToolWitness(sessionId,name2,args){if(name2.length===0)return;const hash=witnessHash(name2,args);if(!hash)return;const now=nowMs();if(lastRecordSweepAt===void 0||now-lastRecordSweepAt>WITNESS_TTL_MS||now<lastRecordSweepAt){for(const id of rings.keys())sweep(id,now);lastRecordSweepAt=now}sweep(sessionId,now);const ring=rings.get(sessionId)??[];if(ring.length>0&&ring[ring.length-1].hash===hash){ring[ring.length-1].at=now}else{ring.push({hash,at:now});while(ring.length>RING_CAPACITY){const evicted=ring.shift();if(!evicted)break;dropFromIndexIfAbsent(ring,evicted.hash,sessionId)}}rings.set(sessionId,ring);const sessions2=hashIndex.get(hash)??new Set;sessions2.add(sessionId);hashIndex.set(hash,sessions2)}function lookupToolWitness(name2,args){const hash=witnessHash(name2,args);if(!hash)return new Set;const now=nowMs();for(const sessionId of[...rings.keys()])sweep(sessionId,now);const sessions2=hashIndex.get(hash);return sessions2?new Set(sessions2):new Set}var TOOL_USE_ID_TTL_MS=10*60*1e3;var TOOL_USE_ID_CAPACITY=1024;var toolUseIds=new Map;function recordToolUseId(toolUseId,sessionId){if(toolUseId.length===0||toolUseId.length>512)return;toolUseIds.delete(toolUseId);toolUseIds.set(toolUseId,{sessionId,at:nowMs()});while(toolUseIds.size>TOOL_USE_ID_CAPACITY){const oldestKey=toolUseIds.keys().next().value;if(oldestKey===void 0)break;toolUseIds.delete(oldestKey)}}function lookupToolUseIdSession(toolUseId){if(toolUseId.length===0||toolUseId.length>512)return void 0;const hit=toolUseIds.get(toolUseId);if(!hit)return void 0;if(nowMs()-hit.at>TOOL_USE_ID_TTL_MS){toolUseIds.delete(toolUseId);return void 0}return hit.sessionId}async function readStreamToBuffer(stream2,maxBytes=1<<20){const reader=stream2.getReader();const chunks=[];let kept=0;try{for(;;){const{done,value}=await reader.read();if(done)break;if(value&&kept<maxBytes){const take=Math.min(value.length,maxBytes-kept);chunks.push(Buffer.from(value.subarray(0,take)));kept+=take}}}finally{reader.releaseLock()}return Buffer.concat(chunks)}async function bufferStreamIfFits(stream2,maxBytes){const reader=stream2.getReader();const chunks=[];let kept=0;let handedOff=false;try{for(;;){const{done,value}=await reader.read();if(done)return Buffer.concat(chunks,kept);if(value.byteLength===0)continue;if(kept+value.byteLength<=maxBytes){chunks.push(Buffer.from(value));kept+=value.byteLength;continue}let ended=false;const replay=new ReadableStream({start(controller){for(const chunk of chunks)controller.enqueue(chunk);chunks.length=0;controller.enqueue(value)},async pull(controller){try{const next=await reader.read();if(ended)return;if(next.done){ended=true;reader.releaseLock();controller.close()}else{controller.enqueue(next.value)}}catch(error){if(!ended){ended=true;reader.releaseLock();controller.error(error)}}},async cancel(reason){ended=true;try{await reader.cancel(reason)}finally{reader.releaseLock()}}});handedOff=true;return replay}}finally{if(!handedOff)reader.releaseLock()}}function bufferToStream(buf){return new ReadableStream({start(controller){controller.enqueue(new Uint8Array(buf));controller.close()}})}function awaitDrain(res){if(res.destroyed||res.writableEnded)return Promise.resolve();return new Promise(resolve3=>{const done=()=>{res.removeListener?.("drain",done);res.removeListener?.("close",done);res.removeListener?.("error",done);resolve3()};res.once("drain",done);res.once("close",done);res.once("error",done)})}async function pipeThrough(stream2,res){const reader=stream2.getReader();let completed2=false;const cancel=()=>{void reader.cancel().catch(()=>{})};res.once("close",cancel);res.once("error",cancel);try{if(res.destroyed||res.writableEnded)return;for(;;){const{done,value}=await reader.read();if(done){completed2=true;break}if(res.destroyed||res.writableEnded)break;if(!res.write(Buffer.from(value))){await awaitDrain(res)}}}finally{res.removeListener("close",cancel);res.removeListener("error",cancel);if(!completed2)cancel();reader.releaseLock();res.end()}}async function dumpStreamToFile(stream2,dir,name2){const{mkdirSync:mkdirSync15,createWriteStream:createWriteStream2}=await import("fs");const{join:join15}=await import("path");const{pipeline:pipeline2}=await import("stream/promises");try{mkdirSync15(dir,{recursive:true});const ws2=createWriteStream2(join15(dir,name2));await pipeline2(stream2,ws2);gcDumpDirIfConfigured(dir)}catch(err2){logDumpFailure("SSE stream dump",err2)}}init_version();function tailLooksTerminal(tail,protocol){if(/^data: \[DO/.test(tail))return true;if(protocol==="anthropic")return/event: message_stop/.test(tail.slice(0,64))||/"type"\s*:\s*"message_stop"/.test(tail);if(protocol==="openai"){return/"finish_reason"\s*:\s*"/.test(tail)}if(protocol==="google"){return/"finishReason"\s*:\s*"/.test(tail)}return/event: response\.(?:completed|failed|incomplete)/.test(tail.slice(0,64))||/"type"\s*:\s*"response\.(?:completed|failed|incomplete)"/.test(tail)}var PROXY_VERSION=(()=>{try{const here=fileURLToPath7(import.meta.url);const pkg=path40.join(path40.dirname(here),"..","package.json");return JSON.parse(fs20.readFileSync(pkg,"utf8")).version??"dev"}catch{return"dev"}})();var PLUGIN_AGENT_HEADER="x-bili-plugin";var PLUGIN_CONVERSATION_HEADER="x-bili-plugin-conversation";var PLUGIN_CONTEXT_WINDOW_HEADER="x-bili-plugin-context-window";var PLUGIN_MAX_OUTPUT_HEADER="x-bili-plugin-max-output";var PLUGIN_MODEL_HEADER="x-bili-plugin-model";var PLUGIN_COMPRESSION_HEADER="x-bili-plugin-compression";var PLUGIN_INSTRUCTIONS_MUTABLE_HEADER="x-bili-plugin-instructions-mutable";var PLUGIN_REQUEST_AGENT_HEADER="x-bili-plugin-agent";var PLUGIN_PURPOSE_HEADER="x-bili-plugin-purpose";var PLUGIN_PURPOSE_CONVERSATION="conversation";var PLUGIN_PROTOCOL_VERSION=1;var PLUGIN_FOLD_CALLID_PREFIX="plugin_";function isPluginFoldCallId(callId){return typeof callId==="string"&&callId.startsWith(PLUGIN_FOLD_CALLID_PREFIX)}function reconcilePluginFoldCallIds(session,messages){const blocks=new Map;for(const block of session.state.blocks){if(!block.active||!block.startRef||!block.endRef)continue;const key2=JSON.stringify([block.startRef,block.endRef]);const sameRange=blocks.get(key2)??[];sameRange.push(block);blocks.set(key2,sameRange)}const calls=new Map;const results=new Map(messages.filter(m2=>m2.contentType==="tool-result"&&m2.toolCallId).map(m2=>[m2.toolCallId,m2.text??""]));for(const message of messages){if(message.contentType!=="tool-call"||message.toolName!=="compress"||!message.toolCallId)continue;try{const args=JSON.parse(message.text??"");for(const range of Array.isArray(args?.content)?args.content:[args]){if(!range||typeof range.startId!=="string"||typeof range.endId!=="string")continue;const key2=JSON.stringify([range.startId,range.endId]);if(!blocks.has(key2))continue;const ids=calls.get(key2)??new Set;ids.add(message.toolCallId);calls.set(key2,ids)}}catch{}}let changed=0;for(const[key2,sameRange]of blocks){const block=sameRange[0];const ids=calls.get(key2);if(sameRange.length!==1||!isPluginFoldCallId(block.compressCallId)||ids?.size!==1)continue;const id=ids.values().next().value;const receipt=results.get(id);if(!receipt?.startsWith("[Compressed ")||!receipt.split("\n").some(line=>line.startsWith(` \xB7 ${block.blockId} full summary `)))continue;block.compressCallId=id;changed++}if(changed>0)markDirty(session);return changed}var VERSION2=(()=>{try{const here=fileURLToPath7(import.meta.url);const pkg=path40.join(path40.dirname(here),"..","package.json");return JSON.parse(fs20.readFileSync(pkg,"utf8")).version??"dev"}catch{return"dev"}})();function headerValue(headers,name2){const v2=headers[name2];const s3=typeof v2==="string"?v2:Array.isArray(v2)?v2[0]:void 0;const t=s3?.trim();return t&&t.length>0?t:void 0}function pluginPurposeHeader(headers){return pluginAgentHeader(headers)!==void 0?headerValue(headers,PLUGIN_PURPOSE_HEADER):void 0}function pluginAgentHeader(headers){return headerValue(headers,PLUGIN_AGENT_HEADER)}function pluginConversationHeader(headers){return headerValue(headers,PLUGIN_CONVERSATION_HEADER)}function pluginContextWindowHeader(headers){const raw=headerValue(headers,PLUGIN_CONTEXT_WINDOW_HEADER);if(raw===void 0)return void 0;const n=Number.parseInt(raw,10);return Number.isFinite(n)&&n>0?n:void 0}function pluginReportedContextWindow(headers){return pluginAgentHeader(headers)!==void 0?pluginContextWindowHeader(headers):void 0}function pluginReportedMaxOutput(headers){const raw=pluginAgentHeader(headers)===void 0?void 0:headerValue(headers,PLUGIN_MAX_OUTPUT_HEADER);if(raw===void 0)return void 0;const n=Number.parseInt(raw,10);return Number.isFinite(n)&&n>0?n:void 0}function pluginReportedModel(headers){if(pluginAgentHeader(headers)===void 0)return void 0;const raw=headerValue(headers,PLUGIN_MODEL_HEADER);return raw!==void 0&&/^\S{1,256}$/.test(raw)?raw:void 0}function pluginRequestAgentHeader(headers){if(pluginAgentHeader(headers)===void 0)return void 0;return headerValue(headers,PLUGIN_REQUEST_AGENT_HEADER)}function pluginCompressionProxyHeader(headers){if(pluginAgentHeader(headers)===void 0)return false;return headerValue(headers,PLUGIN_COMPRESSION_HEADER)==="proxy"}function pluginHeadersMatchModel(headers,bodyModel){const reported=pluginReportedModel(headers);if(reported===void 0||bodyModel===void 0)return true;if(reported===bodyModel)return true;return bodyModel.split("/").pop()===reported}var MAX_PLUGIN_CONVERSATIONS=1024;var CONV_NS="plugin-conversations";var CONV_KEY="table";var convKvReady=false;var convChain=Promise.resolve();var convWarned=false;function convWarnOnce(tag,err2){if(convWarned)return;convWarned=true;log("warn",`[plugin] ${tag} failed \u2014 the conversation table stays on the legacy file for this process (${err2 instanceof Error?err2.message:String(err2)})`)}function parseConvTable(value){if(!value||typeof value!=="object"||Array.isArray(value))return null;const out={};for(const[k2,v2]of Object.entries(value)){if(!v2||typeof v2!=="object")continue;const e=v2;if(typeof e.sessionId!=="string"||e.sessionId.length===0)continue;if(typeof e.lastSeen!=="number")continue;out[k2]={sessionId:e.sessionId,lastSeen:e.lastSeen}}return out}var conversations=new Map;var snapshotRefsEvaluatedStore=new WeakMap;var warnedNoModelRequests=new Set;var WARNED_NO_MODEL_REQUESTS_CAP=4096;var WITNESS_TTL_MS_PLUGIN=10*60*1e3;var conversationsFile=()=>path40.join(stateDir(),"plugin-conversations.json");var conversationsSaveTimer;var conversationsDirty=false;function writeConversationsFile(){if(!conversationsDirty)return;if(egressPlaneGateOn())return;try{const obj={};for(const[k2,v2]of conversations)obj[k2]=v2;const store2=kvStore();if(convKvReady&&store2!==null){convChain=convChain.then(()=>store2.setKvAsync(CONV_NS,CONV_KEY,obj)).catch(err2=>{convWarnOnce("persist",err2);convKvReady=false;conversationsDirty=true;scheduleSaveConversations()});conversationsDirty=false;return}fs20.mkdirSync(stateDir(),{recursive:true});const filePath=conversationsFile();const draft=`${filePath}.${process.pid}.bili-tmp`;const fd=fs20.openSync(draft,"w");try{fs20.writeFileSync(fd,JSON.stringify(obj));fs20.fsyncSync(fd)}finally{fs20.closeSync(fd)}fs20.renameSync(draft,filePath);conversationsDirty=false}catch{}}function scheduleSaveConversations(){if(conversationsSaveTimer)clearTimeout(conversationsSaveTimer);conversationsSaveTimer=setTimeout(()=>{conversationsSaveTimer=void 0;writeConversationsFile()},300)}function loadConversations(){let raw;try{raw=fs20.readFileSync(conversationsFile(),"utf8")}catch{return}try{const obj=JSON.parse(raw);for(const[k2,v2]of Object.entries(obj)){if(v2&&typeof v2.sessionId==="string"&&v2.sessionId.length>0){conversations.set(k2,{sessionId:v2.sessionId,lastSeen:typeof v2.lastSeen==="number"?v2.lastSeen:Date.now()})}}}catch{let removedCopies=0;try{const backup=`${conversationsFile()}.corrupt-${Date.now()}`;fs20.renameSync(conversationsFile(),backup);removedCopies=pruneCorruptSiblings(conversationsFile(),backup).removed}catch{}const capNote=removedCopies>0?`; removed ${removedCopies} older forensic cop${removedCopies===1?"y":"ies"} (cap ${CORRUPT_SIBLING_CAP})`:"";log("warn",`[plugin] plugin-conversations.json is corrupt \u2014 backed up beside the original, starting an empty routing table${capNote}`)}conversationsDirty=false}async function hydratePluginConversationsUnified(){const store2=kvStore();if(convKvReady||!store2)return;if(egressPlaneGateOn())return;try{let raw;try{raw=await store2.getKvAsync(CONV_NS,CONV_KEY)}catch{raw=void 0}const hadRow=raw!==void 0&&raw!==null;const kvTable=hadRow?parseConvTable(raw)??{}:{};const byKey=new Map([...conversations]);for(const[k2,v2]of Object.entries(kvTable)){const cur=byKey.get(k2);byKey.set(k2,!cur||v2.lastSeen>=cur.lastSeen?v2:cur)}const merged=[...byKey.entries()].sort((a,b2)=>a[1].lastSeen-b2[1].lastSeen);conversations.clear();for(const[k2,v2]of merged)conversations.set(k2,v2);while(conversations.size>MAX_PLUGIN_CONVERSATIONS){const oldest=conversations.keys().next().value;if(oldest===void 0)break;conversations.delete(oldest)}const missing=[...conversations.keys()].filter(k2=>!(k2 in kvTable));if(!hadRow||missing.length>0){const payload={};for(const[k2,v2]of conversations)payload[k2]=v2;await store2.setKvAsync(CONV_NS,CONV_KEY,payload);if(missing.length>0)log("info",`[plugin] migrated ${missing.length} conversation route(s) from the legacy JSON file into unified storage (#5753)`)}convKvReady=true;conversationsDirty=false}catch(err2){convWarnOnce("hydrate",err2)}}function recordPluginSession(conversationId,sessionId){if(conversationId!==sessionId&&(peekSession(conversationId)||conversations.get(conversationId)?.sessionId===conversationId)){sessionId=conversationId}conversations.delete(conversationId);conversations.set(conversationId,{sessionId,lastSeen:Date.now()});conversationsDirty=true;if(conversations.size>MAX_PLUGIN_CONVERSATIONS){const oldest=conversations.keys().next().value;if(oldest!==void 0)conversations.delete(oldest)}scheduleSaveConversations()}function preparePluginWireMetadata(rawWire,parsedWire){let textComparable=false;try{if(parsedWire!==null&&typeof parsedWire==="object"){const wire=parsedWire;textComparable=comparableHistory(wire.messages??wire.input??wire.contents)}}catch{textComparable=false}return{wireHash:createHash32("sha256").update(rawWire).digest("hex"),textComparable}}function rememberPluginMessages(sessionId,processed,original,nudge,rawWire){const incoming=processed.length>0?processed:original;const session=peekSession(sessionId);if(!session)return;const transient2=session.transient??={};const previous=transient2.pluginMessages;if(previous){const previousView=previous.processed.length>0?previous.processed:previous.original;if(previousView.length>incoming.length){const knownIds=new Set(previousView.map(m2=>m2.id));if(!incoming.some(m2=>knownIds.has(m2.id)))return}}transient2.pluginMessages={processed,original,nudge};if(typeof session.metadata.pluginAgent==="string"&&original.length>0){const cap2=publicSnapshotCapBytes();const dropOverCap=()=>{session.pluginSnapshot=void 0;session.metadata.publicSnapshotCapped=true;delete session.metadata.publicSnapshotBytes};let changed=false;const prev=session.pluginSnapshot;if(!prev||session.metadata.publicSnapshotCapped===true){const bytes=stableJson(original).length;if(cap2>0&&bytes>cap2)dropOverCap();else{session.pluginSnapshot=structuredClone(original);session.metadata.publicSnapshotBytes=bytes;delete session.metadata.publicSnapshotCapped}changed=true}else{const n=original.length;let k2=0;while(k2<prev.length&&k2<n&&sameSnapshotView(prev[k2],original[k2]))k2++;if(k2===n&&n===prev.length){const trackedBytes=typeof session.metadata.publicSnapshotBytes==="number"?session.metadata.publicSnapshotBytes:void 0;const bytes=trackedBytes??stableJson(prev).length;if(trackedBytes===void 0)session.metadata.publicSnapshotBytes=bytes;if(cap2>0&&bytes>cap2)dropOverCap();if(trackedBytes===void 0||cap2>0&&bytes>cap2)changed=true}else if(k2===prev.length){let bytes=typeof session.metadata.publicSnapshotBytes==="number"?session.metadata.publicSnapshotBytes:stableJson(prev).length;for(let i=k2;i<n;i++)bytes+=stableJson(original[i]).length+1;if(cap2>0&&bytes>cap2)dropOverCap();else{for(let i=k2;i<n;i++)prev.push(structuredClone(original[i]));session.metadata.publicSnapshotBytes=bytes;delete session.metadata.publicSnapshotCapped}changed=true}else{const bytes=stableJson(original).length;if(cap2>0&&bytes>cap2)dropOverCap();else{session.pluginSnapshot=structuredClone(original);session.metadata.publicSnapshotBytes=bytes;delete session.metadata.publicSnapshotCapped}changed=true}}const storeChanged=snapshotRefsEvaluatedStore.get(session)!==session.contentStore;if(changed||storeChanged){const previousRefs=session.metadata.publicSnapshotStoredRefs;session.metadata.publicSnapshotStoredRefs=[...new Set([...Array.isArray(previousRefs)?previousRefs:[],...(session.pluginSnapshot??[]).flatMap(m2=>{const ref=session.state.messageRefs.byRaw[m2.id];return ref&&session.contentStore?.byRef[ref]?[ref]:[]})])];snapshotRefsEvaluatedStore.set(session,session.contentStore)}if(rawWire!==void 0){const wireHash2=Buffer.isBuffer(rawWire)?createHash32("sha256").update(rawWire).digest("hex"):rawWire.wireHash;if(session.metadata.publicSnapshotWireHash!==wireHash2){let comparable2;if(Buffer.isBuffer(rawWire)){try{const wire=JSON.parse(rawWire.toString("utf8"));comparable2=comparableHistory(wire.messages??wire.input??wire.contents)}catch{comparable2=false}}else{comparable2=rawWire.textComparable}session.metadata.publicSnapshotWireHash=wireHash2;if(session.metadata.publicSnapshotTextComparable!==comparable2){session.metadata.publicSnapshotTextComparable=comparable2;changed=true}}}if(changed||storeChanged)markDirty(session)}}var pluginRuntimeTable=new Map;var pluginRuntimeByConversation=new Map;var MAX_PLUGIN_RUNTIME_ENTRIES=32;function evictOldestRuntimeEntries(map){while(map.size>MAX_PLUGIN_RUNTIME_ENTRIES){const oldest=map.keys().next().value;if(oldest===void 0)break;map.delete(oldest)}}function recordPluginRuntimeInfo(entry){const conv=entry.conversationId!==void 0&&entry.conversationId.length>0?entry.conversationId:void 0;const table=conv!==void 0?pluginRuntimeByConversation:pluginRuntimeTable;table.delete(conv??entry.agent);table.set(conv??entry.agent,entry);evictOldestRuntimeEntries(table)}function pluginRuntimeInfoFor(agent,model){if(agent===void 0||model===void 0)return void 0;const entry=pluginRuntimeTable.get(agent);if(entry===void 0||entry.model!==model)return void 0;return entry}var CHILD_CONVERSATION_SUFFIX=/:(?:side(?::conversation)?|sub):[^:]+$/;var MAX_CHILD_CONVERSATION_DEPTH=4;function parentConversationId(conversationId){const parent=conversationId.replace(CHILD_CONVERSATION_SUFFIX,"");return parent!==conversationId&&parent.length>0?parent:void 0}function pluginRuntimeInfoForConversation(conversationId,model){if(conversationId===void 0||model===void 0)return void 0;const exact=pluginRuntimeByConversation.get(conversationId);if(exact!==void 0)return exact.model===model?exact:void 0;let parent=parentConversationId(conversationId);for(let depth=0;parent!==void 0&&depth<MAX_CHILD_CONVERSATION_DEPTH;depth++){const entry=pluginRuntimeByConversation.get(parent);if(entry!==void 0)return entry.model===model?entry:void 0;parent=parentConversationId(parent)}return void 0}function runtimeConversationId(headers,parsed,sessionHeaderName){const fromClient=clientConversationHeader(headers);if(fromClient!==void 0&&fromClient.length>0)return fromClient;const custom=sessionHeaderName!==void 0?headerValue(headers,sessionHeaderName):void 0;if(custom!==void 0)return custom;const pck=typeof parsed==="object"&&parsed!==null?parsed.prompt_cache_key:void 0;return typeof pck==="string"&&pck.trim().length>0?pck.trim():void 0}function handlePluginRuntimeInfo(payload,res){let parsed;try{parsed=JSON.parse(payload)}catch{res.writeHead(400,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:"invalid JSON"}));return}const body=parsed;const str3=(v2,max)=>typeof v2==="string"&&v2.length>0&&v2.length<=max?v2:void 0;const num7=v2=>typeof v2==="number"&&Number.isFinite(v2)&&v2>0?Math.floor(v2):void 0;const agent=str3(body.agent,64);const model=str3(body.model,256);if(agent===void 0||model===void 0){res.writeHead(400,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:"agent and model are required"}));return}const conversationId=str3(body.conversationId,256);recordPluginRuntimeInfo({agent,model,contextWindow:num7(body.contextWindow),maxOutput:num7(body.maxOutput),baseURL:str3(body.baseURL,2048),...conversationId!==void 0?{conversationId}:{},source:str3(body.source,64)??"client-config",ts:Date.now()});res.writeHead(200,{"content-type":"application/json"});res.end(JSON.stringify({ok:true}))}function handlePluginAttribution(payload,res){let parsed;try{parsed=JSON.parse(payload)}catch{res.writeHead(400,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:"invalid JSON"}));return}const body=parsed;const str3=(v2,max)=>typeof v2==="string"&&v2.length>0&&v2.length<=max?v2:void 0;const nonNeg=v2=>typeof v2==="number"&&Number.isFinite(v2)&&v2>=0?Math.floor(v2):void 0;const agent=str3(body.agent,64);if(agent===void 0||body.state!=="ok"&&body.state!=="none"&&body.state!=="threw"){res.writeHead(400,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:"agent and state (ok|none|threw) are required"}));return}const error=str3(body.error,300);const endpoint=str3(body.endpoint,200);recordAttributionReport(agent,{state:body.state,refusals:nonNeg(body.refusals)??0,since:nonNeg(body.since)??0,...error!==void 0?{error}:{},...endpoint!==void 0?{endpoint}:{}});res.writeHead(200,{"content-type":"application/json"});res.end(JSON.stringify({ok:true}))}var MAX_PENDING_REGISTERS=64;var pendingRegisters=[];function queuePluginRegister(conversationId,agent,identity,parentConversationId2){if(!identity){for(let i=0;i<pendingRegisters.length;i++){if(pendingRegisters[i].conversationId===conversationId){pendingRegisters.splice(i,1);break}}pendingRegisters.push({conversationId,agent,ts:Date.now(),...parentConversationId2?{parentConversationId:parentConversationId2}:{}});while(pendingRegisters.length>MAX_PENDING_REGISTERS)pendingRegisters.shift()}else{const parent=parentConversationId2??registeredIds.get(conversationId)?.parentConversationId;registeredIds.set(conversationId,{agent,...parent?{parentConversationId:parent}:{}});while(registeredIds.size>MAX_PENDING_REGISTERS){const oldest=registeredIds.keys().next().value;if(oldest!==void 0)registeredIds.delete(oldest)}}}var PENDING_REGISTER_TTL_MS=10*60*1e3;function takePendingPluginRegister(eligible=()=>true){const now=Date.now();while(pendingRegisters.length>0&&now-pendingRegisters[0].ts>PENDING_REGISTER_TTL_MS){pendingRegisters.shift()}const index=pendingRegisters.findIndex(eligible);return index<0?void 0:pendingRegisters.splice(index,1)[0]}var registeredIds=new Map;function consumePluginRegisterFor(conversationId){const entry=registeredIds.get(conversationId);if(entry!==void 0){registeredIds.delete(conversationId);registeredIds.set(conversationId,entry)}return entry}function handlePluginRegister(payload,res){let parsed;try{parsed=JSON.parse(payload)}catch{res.writeHead(400,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:"invalid JSON body"}));return}const conversationId=typeof parsed.conversationId==="string"?parsed.conversationId.trim():"";if(!conversationId){res.writeHead(400,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:"conversationId is required"}));return}const agent=typeof parsed.agent==="string"&&parsed.agent.trim()?parsed.agent.trim():"launcher";let parentConversationId2=typeof parsed.parentConversationId==="string"?parsed.parentConversationId.trim():"";if(parentConversationId2===conversationId)parentConversationId2="";queuePluginRegister(conversationId,agent,parsed.identity===true,parentConversationId2||void 0);res.end(JSON.stringify({ok:true,conversationId,agent}))}function handlePluginCompact(payload,res){let parsed;try{parsed=JSON.parse(payload)}catch{res.writeHead(400,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:"invalid JSON body"}));return}const conversationId=typeof parsed.conversationId==="string"?parsed.conversationId.trim():"";if(!conversationId){res.writeHead(400,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:"conversationId is required"}));return}const{session,entry}=resolveConversation(conversationId);if(!session){res.writeHead(404,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:entry?`unknown plugin conversation id "${conversationId}" (id registered but session not resident)`:`unknown plugin conversation id "${conversationId}" (no model request has arrived with this conversation id yet)`}));return}markCompactionBoundary(session);if(entry)entry.lastSeen=Date.now();res.end(JSON.stringify({ok:true,conversationId}))}var HOST_TITLE_MAX=200;function handlePluginSessionName(payload,res){let parsed;try{parsed=JSON.parse(payload)}catch{res.writeHead(400,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:"invalid JSON body"}));return}const conversationId=typeof parsed.conversationId==="string"?parsed.conversationId.trim():"";if(!conversationId){res.writeHead(400,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:"conversationId is required"}));return}if(typeof parsed.name!=="string"){res.writeHead(400,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:"name must be a string (empty clears)"}));return}const{session,entry}=resolveConversation(conversationId);if(!session){res.writeHead(404,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:entry?`unknown plugin conversation id "${conversationId}" (id registered but session not resident)`:`unknown plugin conversation id "${conversationId}" (no model request has arrived with this conversation id yet)`}));return}let name2=parsed.name.replace(/\s+/g," ").trim();if(name2.length>HOST_TITLE_MAX)name2=name2.slice(0,HOST_TITLE_MAX);if(name2)session.meta.hostTitle=name2;else delete session.meta.hostTitle;markDirty(session);if(entry)entry.lastSeen=Date.now();res.end(JSON.stringify({ok:true,conversationId}))}function handlePluginManifest(res,config,toolPrompts){const absorbOn=absorbEnabled(config);const absorbName=config.absorb?.toolName??ABSORB_TOOL_NAME;const absorbTools=absorbOn?absorbToolsFor(absorbName):void 0;const blockOpsOn=blockOpsEnabled(config);const blockOps=blockOpsOn?blockOpsTools():void 0;const rulesOn=rulesEnabled(config);const ccrOn=config.ccr?.enabled===true;const ccrName=config.ccr?.toolName??RETRIEVE_TOOL_NAME;const ccrTools=ccrOn?retrieveToolsFor(ccrName):void 0;const rescaleOn=imageRescaleEnabled();const externalSummary=externalSummaryEnabled(config);const acpAnthropic=withAcpNotes(withExternalSummaryTools(applyAcpToolOverrides(ccrOn?BILI_ACP_TOOLS_ANTHROPIC:BILI_ACP_TOOLS_ANTHROPIC_NO_RANGE,toolPrompts),externalSummary),"binding");const acpOpenai=withAcpNotesOpenAI(withExternalSummaryTools(applyAcpToolOverrides(ccrOn?BILI_ACP_TOOLS_OPENAI:BILI_ACP_TOOLS_OPENAI_NO_RANGE,toolPrompts),externalSummary),"binding");const acpResponses=withAcpNotes(withExternalSummaryTools(applyAcpToolOverrides(BILI_ACP_TOOLS_RESPONSES_NO_RANGE,toolPrompts),externalSummary),"binding");res.writeHead(200,{"content-type":"application/json"});res.end(JSON.stringify({ok:true,protocolVersion:PLUGIN_PROTOCOL_VERSION,proxy:"billion-context",version:VERSION2,commit:BUILD_COMMIT,toolNames:[...ACP_TOOL_NAMES,...absorbTools?[absorbName]:[],...rulesOn?[RULE_TOOL_NAME]:[],...ccrOn?[ccrName]:[],...rescaleOn?[READ_ORIGINAL_IMAGE_TOOL_NAME]:[],...blockOpsOn?[ACP_RETIRE_TOOL_NAME,ACP_RESTORE_TOOL_NAME,ACP_REWRITE_TOOL_NAME]:[]],tools:{anthropic:[...acpAnthropic,...absorbTools?[absorbTools.anthropic]:[],...rulesOn?[RULE_TOOL]:[],...ccrTools?[ccrTools.anthropic]:[],...rescaleOn?[READ_ORIGINAL_IMAGE_TOOL]:[],...blockOps?blockOps.anthropic:[]],openai:[...acpOpenai,...absorbTools?[absorbTools.openai]:[],...rulesOn?[RULE_TOOL_OPENAI]:[],...ccrTools?[ccrTools.openai]:[],...rescaleOn?[READ_ORIGINAL_IMAGE_TOOL_OPENAI]:[],...blockOps?blockOps.openai:[]],responses:[...acpResponses,...absorbTools?[absorbTools.responses]:[],...rulesOn?[RULE_TOOL_RESPONSES]:[],...rescaleOn?[READ_ORIGINAL_IMAGE_TOOL_RESPONSES]:[],...blockOps?blockOps.responses:[]]},headers:{agent:PLUGIN_AGENT_HEADER,conversation:PLUGIN_CONVERSATION_HEADER,contextWindow:PLUGIN_CONTEXT_WINDOW_HEADER,maxOutput:PLUGIN_MAX_OUTPUT_HEADER,model:PLUGIN_MODEL_HEADER,instructionsMutable:PLUGIN_INSTRUCTIONS_MUTABLE_HEADER,compression:PLUGIN_COMPRESSION_HEADER},toolEndpoint:"/__bili/plugin/tool",statusEndpoint:"/__bili/plugin/status",runtimeInfoEndpoint:"/__bili/plugin/runtime-info",capabilities:{...externalSummary?{externalSummary:{enabled:true,summaryOptional:true,submittedSummary:"hint",maxToolDurationMs:externalSummaryMaxToolDurationMs(config)}}:{},fork:{protocolVersion:2,acceptsProtocolVersions:[1,2],endpoint:"/__bili/plugin/fork",snapshotEndpoint:"/__bili/plugin/snapshot"}}}))}function conversationIdForSession(sessionId){let bestId;let bestSeen=-Infinity;for(const[cid,entry]of conversations){if(entry.sessionId===sessionId&&entry.lastSeen>bestSeen){bestId=cid;bestSeen=entry.lastSeen}}return bestId}function resolveConversation(conversationId){let entry=conversations.get(conversationId);let session=peekSession(conversationId)??(entry?peekSession(entry.sessionId):void 0);if(!session){session=findSessionByCanonicalId(conversationId)}if(session&&entry?.sessionId!==session.id){recordPluginSession(conversationId,session.id);entry=conversations.get(conversationId)}return{session,entry}}function comparableHistory(value){if(value===null||typeof value==="string")return true;if(Array.isArray(value))return value.every(comparableHistory);if(!value||typeof value!=="object")return false;const part=value;if(part.type!==void 0&&!["message","text","input_text","output_text","thinking","redacted_thinking","reasoning","tool_use","tool_result","function_call","function_call_output"].includes(String(part.type)))return false;if(part.type==="tool_use"||part.type==="function_call")return true;if(part.type==="thinking")return typeof part.thinking==="string"||typeof part.signature==="string";if(part.type==="redacted_thinking")return typeof part.data==="string";if(part.type==="reasoning")return true;if(part.audio!==void 0&&part.audio!==null)return false;if(part.content!==void 0)return comparableHistory(part.content);if(part.output!==void 0)return comparableHistory(part.output);if(part.parts!==void 0)return comparableHistory(part.parts);return typeof part.text==="string"||Array.isArray(part.tool_calls)}function stableJson(value){if(Array.isArray(value))return`[${value.map(stableJson).join(",")}]`;if(value!==null&&typeof value==="object"){const obj=value;return`{${Object.keys(obj).filter(k2=>obj[k2]!==void 0).sort().map(k2=>`${JSON.stringify(k2)}:${stableJson(obj[k2])}`).join(",")}}`}return JSON.stringify(value)??"null"}function forkHash(value){return createHash32("sha256").update(stableJson(value),"utf8").digest("hex")}function forkOrderHash(messages){return createHash32("sha256").update(JSON.stringify(messages),"utf8").digest("hex")}function forkToolIsError(message){return message.toolIsError===true}function redactedPayloadDigest(message){const block=message.rawAnthropicBlock;if(!block||block.type!=="redacted_thinking"||typeof block.data!=="string")return null;return createHash32("sha256").update(block.data,"utf8").digest("hex").slice(0,16)}function forkMessageIdentityHash(message){const m2=message;return forkHash([m2.role,m2.contentType,m2.text??null,m2.toolName??null,m2.toolCallId??null,m2.thinkingSignature??null,m2.googleThoughtSignature??null,m2.summaryOfBlockId??null,forkToolIsError(m2),redactedPayloadDigest(m2)])}function sameSnapshotView(a,b2){const am=a;const bm=b2;return a.id===b2.id&&a.role===b2.role&&a.contentType===b2.contentType&&a.text===b2.text&&a.toolName===b2.toolName&&a.toolCallId===b2.toolCallId&&am.thinkingSignature===bm.thinkingSignature&&am.googleThoughtSignature===bm.googleThoughtSignature&&typeof a.thinkingTokens==="number"===(typeof b2.thinkingTokens==="number")&&a.summaryOfBlockId===b2.summaryOfBlockId&&forkToolIsError(a)===forkToolIsError(b2)}var FORK_PREFIX_ID_PREVIEW=16;var FORK_PREFIX_HASH_PREVIEW=12;function forkPrefixPreview(value){return value.length>0?value.slice(0,FORK_PREFIX_ID_PREVIEW):"-"}function publicForkInputCheck(session,protocol,parsed){const prefix=session.pluginSnapshot;if(session.metadata.publicForkReceipt===void 0)return{ok:false,reason:"receipt-missing"};if(!prefix)return{ok:false,reason:"snapshot-missing"};try{const incoming=incomingCoreMessages(protocol,parsed);if(incoming===null)return{ok:false,reason:`incoming-unmappable (protocol=${protocol})`};if(incoming.length<prefix.length)return{ok:false,reason:`prefix-longer-than-incoming (expected=${prefix.length} incoming=${incoming.length})`};for(let index=0;index<prefix.length;index+=1){const expected=prefix[index];const candidate=incoming[index];const ref=session.state.messageRefs.byRaw[expected.id];const refOk=ref!==void 0&&(ref===BLOCKED_REF||session.state.messageRefs.byRef[ref]===expected.id);const idOk=candidate.id===expected.id;const expectedHash=forkMessageIdentityHash(expected);const candidateHash=forkMessageIdentityHash(candidate);if(!refOk||!idOk||candidateHash!==expectedHash){const parts=[`cell-mismatch@${index}`];if(!refOk)parts.push(`ref-broken (rawId=${forkPrefixPreview(expected.id)} ref=${ref??"MISSING"})`);if(!idOk)parts.push(`id-drift expected=${forkPrefixPreview(expected.id)} got=${forkPrefixPreview(candidate.id)}`);else if(candidateHash!==expectedHash)parts.push(`hash-drift-under-same-id role=${candidate.role} expected-hash=${expectedHash.slice(0,FORK_PREFIX_HASH_PREVIEW)} got-hash=${candidateHash.slice(0,FORK_PREFIX_HASH_PREVIEW)}`);return{ok:false,reason:parts.join(" ")}}}return{ok:true}}catch(err2){return{ok:false,reason:`projection-error (${err2 instanceof Error?err2.message:String(err2)})`}}}function sessionRevisionOf(session){const epoch=session.revisionEpoch??0;const cache7=session.pluginRevisionCache;if(cache7&&cache7.epoch===epoch)return cache7.revision;const revision=forkSnapshot(session).parentRevision;session.pluginRevisionCache={epoch,revision};return revision}var reconMissGate=new Map;var reconMissLastLogMs=new Map;function reconMiss(session,gate,detail){const why=detail?`${gate} ${detail}`:gate;const key2=`${session.id}:${gate}`;const now=Date.now();if(now-(reconMissLastLogMs.get(key2)??0)>=1e4){reconMissLastLogMs.set(key2,now);log("warn",`[plugin] raw-tail reconstruction unavailable for ${session.id} (${why}) \u2014 snapshot/fork falls back to the legacy path`)}reconMissGate.set(session.id,{gate:why,at:now});return null}function reconMissReason(sessionId){const hit=reconMissGate.get(sessionId);return hit&&Date.now()-hit.at<3e4?hit.gate:void 0}async function waitForReconstructionReplicas(session){if(session.pluginSnapshot!==void 0)return;const expected=session.state.lastPassIds;if(!expected||expected.length===0)return;const store2=getStore();if(store2.replicasAvailable())return;if(store2.sidecarDownReason()!=="sidecar-missing")return;await store2.waitForReplicas()}function reconstructRawTailForFork(session){const expected=session.state.lastPassIds;if(!expected||expected.length===0)return reconMiss(session,"empty-lastPassIds");const store2=getStore();if(!store2.replicasAvailable())return reconMiss(session,"replicasUnavailable",store2.sidecarDownReason());const seqs=store2.unifiedTailSeqs(session.id);if(!seqs||seqs.length===0)return reconMiss(session,"empty-tailSeqs",`expected=${expected.length}`);const rows=store2.unifiedTailViewRows(session.id);if(!rows)return reconMiss(session,"null-tailViewRows",`seqs=${seqs.length}`);const bySeq=new Map;for(const row of rows)bySeq.set(row.seq,row.content);const out=[];for(const seq of seqs){const content=bySeq.get(seq);if(content===void 0)return reconMiss(session,"gap-tailRow",`seq=${seq}/${seqs.length} rows=${rows.length}`);let msg;try{msg=JSON.parse(content)}catch{return reconMiss(session,"unparseable-row",`seq=${seq}`)}if(typeof msg.id!=="string"||typeof msg.role!=="string")return reconMiss(session,"bad-row-shape",`seq=${seq}`);out.push(msg)}if(out.length!==expected.length)return reconMiss(session,"length-mismatch",`rows=${out.length} expected=${expected.length}`);for(let i=0;i<out.length;i+=1)if(out[i].id!==expected[i])return reconMiss(session,"id-mismatch",`index=${i}`);const cap2=publicSnapshotCapBytes();if(Buffer.byteLength(stableJson(out),"utf8")>cap2)return reconMiss(session,"cap-exceeded");reconMissGate.delete(session.id);return out}function egressOpLogSource(session){if(session.metadata.egressAuthority!==true)return null;const st2=getStore().egressOpLogStore();if(!st2)return null;let view;try{view=st2.egressStateView(session.id)}catch(err2){log("warn",`[plugin] egress op-log fork source unreadable for ${session.id} \u2014 fork falls through to the next source: ${String(err2)}`);return null}return view.length>0?rebuildCoreFromLog(view):null}function forkSourceOf(session,source){return source??session.pluginSnapshot??reconstructRawTailForFork(session)??egressOpLogSource(session)}function forkSnapshot(session,source){const messages=forkSourceOf(session,source);if(!messages){const capped=session.metadata.publicSnapshotCapped===true;const base=capped?"raw snapshot exceeded the retention cap (BILI_PUBLIC_SNAPSHOT_CAP_BYTES); fork is refused rather than retaining an unbounded raw copy":"raw snapshot unavailable; send a fresh plugin model request";const why=capped?void 0:reconMissReason(session.id);throw new Error(why?`${base} [reconstruction: ${why}]`:base)}if(session.metadata.publicSnapshotTextComparable===false)throw new Error("multimodal or opaque content cannot be compared by text");const store2=contentStoreOf(session);const expectedStoredRefs=session.metadata.publicSnapshotStoredRefs;if(Array.isArray(expectedStoredRefs)&&expectedStoredRefs.some(ref=>typeof ref!=="string"||!store2.byRef[ref]))throw new Error("CCR original index unavailable");const indexedHashes=new Set(Object.values(store2.byRef).map(entry=>entry.hash));if(Object.entries(store2.byHash).some(([hash,text2])=>!indexedHashes.has(hash)||typeof text2!=="string"||createHash32("sha256").update(text2,"utf8").digest("hex")!==hash))throw new Error("CCR original payload/index inconsistent");if(Object.entries(store2.byRef).some(([ref,entry])=>typeof store2.byHash[entry.hash]!=="string"||session.state.messageRefs.byRaw[entry.rawId]!==void 0&&(session.state.messageRefs.byRaw[entry.rawId]!==ref||session.state.messageRefs.byRef[ref]!==entry.rawId)))throw new Error("CCR original alias inconsistent");const orderedMessages=messages.map((m2,i)=>{const ref=session.state.messageRefs.byRaw[m2.id];if(!ref||ref!==BLOCKED_REF&&session.state.messageRefs.byRef[ref]!==m2.id)throw new Error(`raw/ref mapping inconsistent (msg ${i+1}/${messages.length} role=${m2.role} tool=${m2.toolName??"-"} ref=${ref??"MISSING"} rawId=${m2.id.slice(0,16)})`);const entry=store2.byRef[ref];const placeholder=m2.text?parseStoredPlaceholder(m2.text):null;if(entry&&(entry.rawId!==m2.id||typeof store2.byHash[entry.hash]!=="string")||placeholder&&(placeholder.ref!==ref||!entry))throw new Error("CCR original unavailable or alias inconsistent");return{rawId:m2.id,ref:ref===BLOCKED_REF?null:ref,identityHash:forkMessageIdentityHash(m2)}});const activeBlockSet=session.state.blocks.filter(b2=>b2.active).map(b2=>b2.blockId).sort();const parentRevision=forkHash({sessionId:session.id,seq:orderedMessages.length,blockSet:activeBlockSet});return{protocolVersion:2,status:"exact",sessionId:session.id,parentRevision,orderHash:forkOrderHash(orderedMessages),orderedMessages,messages:messages.map((m2,i)=>({rawId:m2.id,ref:orderedMessages[i].ref,role:m2.role,text:m2.text,toolName:m2.toolName,toolCallId:m2.toolCallId,contentType:m2.contentType,toolIsError:forkToolIsError(m2)}))}}function forkParentRevisionLegacy(session){const messages=session.pluginSnapshot;if(!messages)throw new Error("raw snapshot unavailable");const store2=contentStoreOf(session);const state8={...session.state};return forkHash({sessionId:session.id,messages,state:state8,blockContents:Object.fromEntries(session.blockContents),contentStore:store2})}async function resolveForkConversation(id){if(peekSession(id))return peekSession(id);if(await getStore().loadAsync(id))return getSessionAsync(id);const{session,entry}=resolveConversation(id);if(session)return session;const persistedId=entry?.sessionId??id;if(!await getStore().loadAsync(persistedId))return void 0;return getSessionAsync(persistedId)}var PERSONA_LINEAGE_FRESH_MS=10*60*1e3;function holdsRefs(s3){return Object.keys(s3.state.messageRefs?.byRef??{}).length>0}function personaDescendantsOf(baseId){if(baseId.includes("|sub:"))return[];const prefix=`${baseId}|sub:`;const now=Date.now();return listSessions().filter(s3=>s3.id.startsWith(prefix)&&(s3.stats?.requests??0)>0&&now-(s3.lastSeen??0)<=PERSONA_LINEAGE_FRESH_MS&&holdsRefs(s3))}function maxCitedRefNum(args){let max=0;const visit2=v2=>{if(typeof v2==="string"){for(const m2 of v2.matchAll(/\bm(\d{5,})\b/g))max=Math.max(max,Number(m2[1]))}else if(Array.isArray(v2)){for(const item of v2)visit2(item)}else if(v2!==null&&typeof v2==="object"){for(const item of Object.values(v2))visit2(item)}};visit2(args);return max}function highestMintedRefNum(s3){let max=0;for(const ref of Object.keys(s3.state.messageRefs?.byRef??{})){const m2=/^m(\d{5,})$/.exec(ref);if(m2)max=Math.max(max,Number(m2[1]))}return max}function livePersonaDescendant(parent,maxCited){if(parent.id.includes("|sub:"))return void 0;const cands=personaDescendantsOf(parent.id).filter(s3=>(s3.createdAt??0)>(parent.lastSeen??0));if(cands.length===0)return void 0;const cited=maxCited??0;if(cited>0){const fits=cands.filter(s3=>highestMintedRefNum(s3)>=cited);if(fits.length>0)return fits[0]}return cands[0]}function personaLineageWitness(witnessIds,resolvedId){const base=resolvedId.split("|sub:")[0];for(const w2 of witnessIds){if(w2===resolvedId)continue;if(!w2.includes("|sub:")&&w2!==base)continue;if(w2.includes("|sub:")&&w2.split("|sub:")[0]!==base)continue;const s3=peekSession(w2);if(s3&&(s3.stats?.requests??0)>0&&Date.now()-(s3.lastSeen??0)<=PERSONA_LINEAGE_FRESH_MS)return s3}return void 0}function forkReply(res,status,body){res.writeHead(status,{"content-type":"application/json"});res.end(JSON.stringify(body))}async function handlePluginSnapshot(conversationId,res){if(!conversationId)return forkReply(res,400,{ok:false,code:"INVALID_REQUEST",error:"conversationId is required"});const session=await resolveForkConversation(conversationId);if(!session)return forkReply(res,404,{ok:false,code:"PARENT_NOT_FOUND",error:"unknown plugin conversation"});acquireInFlight(session);try{await waitForReconstructionReplicas(session);await withSessionLock(session,()=>forkReply(res,200,{ok:true,conversationId,...forkSnapshot(session)}))}catch(err2){forkReply(res,409,{ok:false,status:"unavailable",code:"SNAPSHOT_UNAVAILABLE",error:String(err2)})}finally{releaseInFlight(session)}}function parseForkRequest(payload){const value=JSON.parse(payload);if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("expected fork object");const b2=value;const identifier=v2=>typeof v2==="string"&&v2.length>0&&v2.length<=256&&v2.trim()===v2&&!/[\x00-\x1f\x7f]/.test(v2);const hash=v2=>typeof v2==="string"&&/^[a-f0-9]{64}$/.test(v2);if(b2.protocolVersion!==1&&b2.protocolVersion!==2)throw new Error("unsupported fork protocolVersion (expected 1 or 2)");if(!identifier(b2.parentConversationId)||!identifier(b2.childConversationId)||!identifier(b2.idempotencyKey)||!hash(b2.parentRevision))throw new Error("invalid fork identity/revision");if(b2.parentConversationId===b2.childConversationId)throw new Error("parent and child must differ");const point=b2.branchPoint;if(!point||!Number.isSafeInteger(point.messageCount)||point.messageCount<0||!hash(point.orderHash)||!Array.isArray(b2.orderedMessages)||b2.orderedMessages.length!==point.messageCount)throw new Error("invalid branchPoint/orderedMessages");const orderedMessages=b2.orderedMessages.map(v2=>{if(!v2||typeof v2!=="object")throw new Error("invalid ordered identity");const item=v2;if(!identifier(item.rawId)||!(item.ref===null||typeof item.ref==="string"&&/^m\d{5,}$/.test(item.ref))||!hash(item.identityHash))throw new Error("invalid raw/ref identity");return{rawId:item.rawId,ref:item.ref,identityHash:item.identityHash}});let prefixMsgIds;if(b2.prefixMsgIds!==void 0){if(!Array.isArray(b2.prefixMsgIds)||b2.prefixMsgIds.length!==point.messageCount||b2.prefixMsgIds.some(v2=>!identifier(v2)))throw new Error("invalid prefixMsgIds");prefixMsgIds=b2.prefixMsgIds}let driftFrom;if(b2.driftFrom!==void 0){if(prefixMsgIds===void 0||!Number.isSafeInteger(b2.driftFrom)||b2.driftFrom<0||b2.driftFrom>point.messageCount)throw new Error("invalid driftFrom");driftFrom=b2.driftFrom<point.messageCount?b2.driftFrom:void 0}return{protocolVersion:b2.protocolVersion,parentConversationId:b2.parentConversationId,childConversationId:b2.childConversationId,parentRevision:b2.parentRevision,branchPoint:{messageCount:point.messageCount,orderHash:point.orderHash},orderedMessages,idempotencyKey:b2.idempotencyKey,...prefixMsgIds!==void 0?{prefixMsgIds}:{},...driftFrom!==void 0?{driftFrom}:{}}}function forkChildHeldBySameParent(child2,parent){return registeredIds.get(child2)?.parentConversationId===parent}async function handlePluginFork(payload,res){let request;try{request=parseForkRequest(payload)}catch(err2){return forkReply(res,400,{ok:false,code:"INVALID_REQUEST",error:String(err2)})}const requestHash=forkHash(request);const replay=async()=>{await getStore().recoverCompletedFork(request.childConversationId);const existing=await resolveForkConversation(request.childConversationId);if(!existing)return false;const receipt=existing.metadata.publicForkReceipt;if(receipt?.requestHash===requestHash)forkReply(res,200,{...receipt.response,replayed:true});else forkReply(res,409,{ok:false,code:"CHILD_CONFLICT",error:"child conversation already exists or idempotency payload differs"});return true};try{if(await replay())return}catch(err2){return forkReply(res,503,{ok:false,status:"unavailable",code:"FORK_FAILED",error:String(err2)})}if(conversations.has(request.childConversationId)||pendingRegisters.some(r=>r.conversationId===request.childConversationId)||registeredIds.has(request.childConversationId)&&!forkChildHeldBySameParent(request.childConversationId,request.parentConversationId))return forkReply(res,409,{ok:false,code:"CHILD_CONFLICT",error:"child conversation already registered"});const parent=await resolveForkConversation(request.parentConversationId);if(!parent)return forkReply(res,404,{ok:false,code:"PARENT_NOT_FOUND",error:"parent conversation not found"});acquireInFlight(parent);try{await waitForReconstructionReplicas(parent);await withSessionLock(parent,async()=>{if(await replay())return;if(conversations.has(request.childConversationId)||pendingRegisters.some(r=>r.conversationId===request.childConversationId)||registeredIds.has(request.childConversationId)&&!forkChildHeldBySameParent(request.childConversationId,request.parentConversationId))return forkReply(res,409,{ok:false,code:"CHILD_CONFLICT",error:"child conversation already registered"});const source=forkSourceOf(parent);let snapshot;try{snapshot=forkSnapshot(parent,source)}catch(err2){return forkReply(res,409,{ok:false,status:"unavailable",code:"SNAPSHOT_UNAVAILABLE",error:String(err2)})}if(snapshot.parentRevision!==request.parentRevision){let legacy=null;try{legacy=forkParentRevisionLegacy(parent)}catch{legacy=null}if(legacy!==request.parentRevision)return forkReply(res,409,{ok:false,code:"PARENT_REVISION_CONFLICT",error:"parent revision changed"})}const prefix=snapshot.orderedMessages.slice(0,request.branchPoint.messageCount);if(prefix.length!==request.branchPoint.messageCount||forkOrderHash(request.orderedMessages)!==request.branchPoint.orderHash||stableJson(prefix)!==stableJson(request.orderedMessages))return forkReply(res,409,{ok:false,code:"BRANCH_POINT_CONFLICT",error:"ordered prefix/hash does not match parent"});let forkDriftFrom;if(request.prefixMsgIds!==void 0&&request.prefixMsgIds.length===prefix.length&&request.prefixMsgIds.every((id,k2)=>id===prefix[k2].rawId)){forkDriftFrom=request.driftFrom}const rawIds=new Set(prefix.map(m2=>m2.rawId));const child2=createSession(request.childConversationId,{...parent.meta,label:request.childConversationId});const crossing=parent.state.blocks.filter(b2=>b2.effectiveMessageIds.some(id=>rawIds.has(id))&&!b2.effectiveMessageIds.every(id=>rawIds.has(id)));const blocks=parent.state.blocks.filter(b2=>b2.effectiveMessageIds.length>0&&b2.effectiveMessageIds.every(id=>rawIds.has(id)));const blockIds=new Set(blocks.map(b2=>b2.blockId));const expandedChildren=new Set(crossing.flatMap(b2=>b2.directBlockIds));for(const b2 of[...blocks,...crossing]){const content=parent.blockContents.get(b2.blockId);if(!content||!content.full||typeof content.full.text!=="string"||!content.full.text||b2.directBlockIds.some(id=>!parent.state.blocks.some(childBlock=>childBlock.blockId===id)))return forkReply(res,409,{ok:false,status:"unavailable",code:"PARENT_STATE_INCOMPLETE",error:"nested block/original content unavailable"})}for(const b2 of blocks){if(b2.directBlockIds.some(id=>!blockIds.has(id)))return forkReply(res,409,{ok:false,status:"unavailable",code:"PARENT_STATE_INCOMPLETE",error:"nested block outside matched prefix"});child2.state.blocks.push({...structuredClone(b2),...expandedChildren.has(b2.blockId)?{active:false,expanded:true}:{}});child2.blockContents.set(b2.blockId,structuredClone(parent.blockContents.get(b2.blockId)))}child2.state.messageRefs=structuredClone(parent.state.messageRefs);for(const{rawId,ref}of prefix){child2.state.messageRefs.byRaw[rawId]=ref??BLOCKED_REF;if(ref!==null){child2.state.messageRefs.byRef[ref]=rawId;if(parent.state.tokenSnapshot[ref]!==void 0)child2.state.tokenSnapshot[ref]=parent.state.tokenSnapshot[ref]}}child2.state.nextBlockId=parent.state.nextBlockId;child2.state.nextRunId=parent.state.nextRunId;child2.state.lastPassIds=prefix.map(m2=>m2.rawId);child2.state.rules=structuredClone(parent.state.rules);child2.state.nextRuleId=parent.state.nextRuleId;const forkRefs=new Set(prefix.map(m2=>m2.ref));child2.state.hiddenOrphanRefs=parent.state.hiddenOrphanRefs?.filter(ref=>forkRefs.has(ref));child2.state.emergencyTruncateLatch=parent.state.emergencyTruncateLatch?.filter(e=>forkRefs.has(e.ref));child2.state.renderDeferredRefs=parent.state.renderDeferredRefs?.filter(r=>forkRefs.has(r));if(parent.state.viewLatches){child2.state.viewLatches=Object.fromEntries(Object.entries(parent.state.viewLatches).filter(([r])=>forkRefs.has(r)))}if(parent.state.viewLatchConfigDigest){child2.state.viewLatchConfigDigest=parent.state.viewLatchConfigDigest}seedTimestampsFromParent(child2,parent);child2.state.suppressMintingOnce=true;if(parent.state.timestampsHighWaterRefSeq!==void 0)child2.state.timestampsHighWaterRefSeq=parent.state.timestampsHighWaterRefSeq;child2.state.deadRefs=parent.state.deadRefs?.filter(ref=>!forkRefs.has(ref));child2.state.stats.tokensCompressed=child2.state.blocks.filter(b2=>b2.active).reduce((sum,b2)=>sum+b2.compressedTokens,0);child2.state.stats.compressionCount=blocks.length;if(prefix.length===snapshot.orderedMessages.length)child2.state.nudge=structuredClone(parent.state.nudge);child2.pluginSnapshot=structuredClone(source.slice(0,request.branchPoint.messageCount));const forkView=prune(child2.pluginSnapshot,child2.state);child2.state.absorbed=structuredClone(parent.state.absorbed?.filter(a=>rawIds.has(a.callMessageId)&&rawIds.has(a.resultMessageId)&&(a.absorbCallId!==void 0&&forkView.some(m2=>m2.contentType==="tool-call"&&m2.toolCallId===a.absorbCallId)||child2.state.blocks.some(b2=>b2.active&&!b2.expanded&&a.summary.length>0&&b2.summary.includes(a.summary))))??[]);child2.lastMessages=structuredClone(child2.pluginSnapshot);child2.lastMessagesFolded=false;const parentStore=contentStoreOf(parent);for(const{ref,rawId}of prefix){if(ref===null)continue;const entry=parentStore.byRef[ref];if(entry&&(entry.rawId!==rawId||typeof parentStore.byHash[entry.hash]!=="string"))return forkReply(res,409,{ok:false,status:"unavailable",code:"PARENT_STATE_INCOMPLETE",error:"CCR original unavailable or alias inconsistent"})}child2.contentStore=cloneStoreForRefs(parentStore,new Set(prefix.filter(m2=>m2.ref!==null).map(m2=>m2.ref)))??void 0;child2.metadata.publicSnapshotTextComparable=true;child2.metadata.publicSnapshotStoredRefs=Object.keys(child2.contentStore?.byRef??{});for(const key2 of["pluginAgent","lastModel","effectiveConfig","effectiveConfigEpoch","effectiveCcr","effectiveContextLimit","reservedContextLimit","lastWindowSource","systemPromptTokens","egressAuthority"])if(parent.metadata[key2]!==void 0)child2.metadata[key2]=structuredClone(parent.metadata[key2]);child2.metadata.parentConversationId=request.parentConversationId;child2.metadata.parentRevision=request.parentRevision;child2.stats.contextTokens=prune(child2.pluginSnapshot,child2.state).reduce((sum,m2)=>sum+countMessageTokens(m2),0)+(typeof child2.metadata.systemPromptTokens==="number"?child2.metadata.systemPromptTokens:0);child2.stats.contextTokensSource="estimate";recordContextObservation(child2,child2.stats.contextTokens,"estimate");child2.stats.localInputEstimate=child2.stats.contextTokens;if(parent.transient?.latestKnownMsgId){(child2.transient??={}).latestKnownMsgId=parent.transient.latestKnownMsgId;child2.transient.needlePayloadUpper=parent.transient.needlePayloadUpper}const response={ok:true,status:forkDriftFrom!==void 0?crossing.length>0?"expanded+drifted":"drifted":crossing.length>0?"expanded":"exact",protocolVersion:2,parentConversationId:request.parentConversationId,childConversationId:request.childConversationId,sessionId:child2.id,parentRevision:request.parentRevision,childRevision:forkSnapshot(child2).parentRevision,branchPoint:request.branchPoint,...forkDriftFrom!==void 0?{driftFrom:forkDriftFrom}:{},expandedBlocks:crossing.map(b2=>b2.blockId),inheritedBlocks:child2.state.blocks.map(b2=>({id:b2.blockId,tier:b2.tier,active:b2.active,expanded:b2.expanded===true})),replayed:false};child2.metadata.publicForkReceipt={requestHash,response};await publishForkSession(child2,parent.id);recordPluginSession(request.childConversationId,child2.id);registeredIds.delete(request.childConversationId);(child2.transient??={}).pluginMessages={processed:structuredClone(child2.pluginSnapshot),original:structuredClone(child2.pluginSnapshot)};if(source&&source!==parent.pluginSnapshot)parent.pluginSnapshot=structuredClone(source);parent.metadata.publicSnapshotRetained=true;if(!getStore().flushSync(parent))log("warn",`fork ${request.childConversationId}: parent snapshot flush failed (${parent.id}); the debounced save will retry`);forkReply(res,201,response)})}catch(err2){forkReply(res,503,{ok:false,status:"unavailable",code:"FORK_FAILED",error:String(err2)})}finally{releaseInFlight(parent)}}function disabledOptionalToolNote(tool,session,config){const absorbName=effectiveAbsorbConfig(session,config)?.toolName??ABSORB_TOOL_NAME;if(tool===absorbName)return`${tool} is not enabled on this bili proxy (compress.absorb.enabled is not true) \u2014 nothing was absorbed.`;if(tool===RULE_TOOL_NAME)return`${tool} is not enabled on this bili proxy (compress.rules.enabled is not true) \u2014 nothing was recorded.`;if(!ccrEnabled(session)&&tool===retrieveToolName(session))return`${tool} is not enabled on this bili proxy (compress.ccr.enabled is not true) \u2014 nothing was retrieved.`;if(BLOCK_OP_TOOL_NAMES.has(tool)&&effectiveBlockOpsConfig(session,config)?.enabled!==true){const verb=tool===ACP_RETIRE_TOOL_NAME?"no blocks were retired":tool===ACP_RESTORE_TOOL_NAME?"no blocks were restored":"no summary was rewritten";return`${tool} is not enabled on this bili proxy (compress.blockOps.enabled is not true) \u2014 ${verb}.`}return void 0}var chainVerdicts=new Map;var WARNED_CHAIN_SESSION_CAP=4096;function recordChainVerdict(sessionId,kind,protocol){const first=!chainVerdicts.has(sessionId);chainVerdicts.set(sessionId,{at:Date.now(),kind,protocol});if(chainVerdicts.size>WARNED_CHAIN_SESSION_CAP){chainVerdicts.delete(chainVerdicts.keys().next().value)}return first}function chainVerdictFor(conversationId){return chainVerdicts.get(conversationId)}function chainAdvisoryPanel(v2){return`\u2139\uFE0F billion-context: this conversation carried ACP-shaped content (evidence: ${v2.kind}, protocol ${v2.protocol}) with no prior local compression state. Historical ACP content is advisory-only (#1357) \u2014 it was NOT treated as a foreign bili chain, so the request was processed normally and this conversation owns its own compression session. Last observation: ${new Date(v2.at).toISOString()}. See the [chain] warn in the bili log.`}function webSessionUrl(origin,sessionId){const o=typeof origin==="string"?origin.trim().replace(/\/+$/,""):"";if(o.length===0||o.endsWith(":0")||sessionId.length===0)return void 0;return`${o}/__bili/#/session/${encodeURIComponent(sessionId)}`}async function handlePluginStatus(conversationId,res,deps,fallbackLatest=false,trustedOrigin){const jsonHeaders=()=>{const h={"content-type":"application/json"};if(trustedOrigin!==void 0&&trustedOrigin.length>0)h["access-control-allow-origin"]=trustedOrigin;return h};let session=await resolveForkConversation(conversationId);const entry=conversations.get(conversationId);let viaFallback=false;let resolvedConversationId=conversationId;if(!session&&fallbackLatest){const latest=listSessions().filter(s3=>s3.restored!==true).sort((a,b2)=>(b2.lastSeen??0)-(a.lastSeen??0))[0];if(latest){session=latest;viaFallback=true;resolvedConversationId=conversationIdForSession(latest.id)??conversationId}}if(!session){const verdict=chainVerdictFor(conversationId);if(verdict!==void 0){res.writeHead(200,jsonHeaders());res.end(JSON.stringify({ok:true,conversationId,phase:"chain-advisory",chain:verdict,panel:chainAdvisoryPanel(verdict),sessionId:null,sessionRevision:null,model:null,contextLimit:null,contextTokens:null,contextTokensSource:"unavailable",contextTokensAt:null,contextGeneration:null}));return}const pre=pluginRuntimeTable.get(conversationId)??pluginRuntimeByConversation.get(conversationId);if(pre!==void 0){res.writeHead(200,jsonHeaders());res.end(JSON.stringify({ok:true,conversationId,phase:"pre-first-request",model:pre.model,contextLimit:pre.contextWindow??null,runtimeInfo:pre,panel:null,sessionId:null,sessionRevision:null,contextTokens:null,contextTokensSource:"unavailable",contextTokensAt:null,contextGeneration:null}));return}res.writeHead(404,jsonHeaders());res.end(JSON.stringify({ok:false,error:fallbackLatest?"no session with activity since boot \u2014 issue a model request or pass the conversation id":"unknown plugin conversation"}));return}if(entry)entry.lastSeen=Date.now();const limit=session.metadata.effectiveContextLimit;const observation=currentContextObservation(session);const contextTokensSource=observation?.source??"unavailable";const contextTokens=observation?.tokens??null;let sessionRevision=null;try{sessionRevision=sessionRevisionOf(session)}catch{}const mem=session.transient?.pluginMessages;const modelContextLimit=typeof limit==="number"&&limit>0?limit:0;let nudge;const messages=mem?mem.processed.length>0?mem.processed:mem.original:session.pluginSnapshot??[];const pluginCfg=effectiveConfig(session,deps.config);if(messages.length>0){try{nudge=deps.core.processTurn({messages,state:session.state,config:ccrLoopConfig(session,pluginCfg),tokenCount:statusInputBaseline(session),renderTags:"none",contentStore:contentStoreOf(session),applyView:mem&&mem.original.length>0?mem.original:void 0}).nudge}catch{nudge=void 0}}if(nudge){nudge={...nudge,compressibleRanges:excludeDeadRefRanges(nudge.compressibleRanges??[],session.state.deadRefs)}}let protectedMass;let protectedMassLine;if(messages.length>0){try{const audit=uncoveredAudit({core:deps.core,messages,state:session.state,config:ccrLoopConfig(session,pluginCfg),tokenCount:statusInputBaseline(session),contentStore:contentStoreOf(session),applyView:mem&&mem.original.length>0?mem.original:void 0,normalRanges:nudge?.compressibleRanges});const pmLine=formatProtectedMass(audit.mass);if(pmLine!==null){protectedMass=audit.mass;protectedMassLine=pmLine}}catch{}}const sysTokRaw=session.metadata.systemPromptTokens;const systemPromptTokens=typeof sysTokRaw==="number"&&Number.isFinite(sysTokRaw)&&sysTokRaw>0?sysTokRaw:0;const contextView=buildContextView({nudge,systemPromptTokens,limit:modelContextLimit,session,protectedMass});let panel;try{panel=buildStatusPanel({version:`billion-context@${PROXY_VERSION}${BUILD_COMMIT&&BUILD_COMMIT!=="unknown"?` (${BUILD_COMMIT})`:""} \xB7 pack: ${session.meta.activePack??"default"}${deps.inlineLane?" \xB7 inline":""}${deps.webOrigin?` \xB7 via ${deps.webOrigin}`:""}`,storage:storageStatusLabel(),externalBlockIds:new Set(session.state.blocks.filter(isExternalSummaryBlock).map(b2=>b2.blockId)),tokenCount:statusInputBaseline(session),systemPromptTokens,state:session.state,nudge,modelContextLimit,unprunedTokens:mem&&mem.original.length>0?mem.original.reduce((sum,m2)=>sum+countMessageTokens(m2),0)+systemPromptTokens:void 0})}catch{panel=void 0}const preFooter=[];if(protectedMassLine!==void 0){preFooter.push(protectedMassLine)}const adv=getAdvisoryState();if(adv.active){preFooter.push(`\u26A0\uFE0F CRITICAL ADVISORY: ${describeAdvisory(adv.active,adv.lastError)}`)}const obd=session.metadata.outputBudgetDegraded;const lastModel=typeof session.metadata.lastModel==="string"?session.metadata.lastModel:void 0;if(obd!==void 0&&obd.model!==void 0&&obd.value!==void 0&&obd.model===lastModel){preFooter.push(`\u26A0\uFE0F OUTPUT BUDGET: model "${obd.model}" has NO known output ceiling \u2014 outgoing max_tokens restored to ${obd.value} tokens from the client's own estimate (no ceiling to back it); longer replies may cut off at the output limit. Declare an output limit in bili config or set maxTokens on the host model item (#2904).`)}const upd=getUpdateVisibility(VERSION2);if(upd.visible){preFooter.push(describeUpdateReady(upd))}const webUrl=webSessionUrl(deps.webOrigin,session.id);if(webUrl!==void 0){preFooter.push(`Web UI: ${webUrl}`)}const clLatest=latestChangelog();if(clLatest!==void 0){preFooter.push(`changelog: ${clLatest.tag} ${clLatest.url}`)}else{warmChangelogOnce()}warmBlogRefreshOnce();if(panel!==void 0&&preFooter.length>0){panel=panel.replace(PANEL_BOX_FOOTER,`
|
|
1584
1584
|
${preFooter.join("\n")}
|
|
1585
1585
|
${PANEL_BOX_FOOTER}`.replace(/\$/g,"$$$$"))}res.writeHead(200,jsonHeaders());res.end(JSON.stringify({ok:true,conversationId:resolvedConversationId,sessionId:session.id,sessionRevision,fallback:viaFallback||void 0,label:session.meta.label??null,pluginAgent:session.metadata.pluginAgent??null,model:session.metadata.lastModel??null,windowSource:session.metadata.lastWindowSource??null,runtimeInfo:pluginRuntimeInfoFor(typeof session.metadata.pluginAgent==="string"?session.metadata.pluginAgent:void 0,typeof session.metadata.lastModel==="string"?session.metadata.lastModel:void 0)??pluginRuntimeInfoForConversation(conversationIdForSession(session.id),typeof session.metadata.lastModel==="string"?session.metadata.lastModel:void 0)??null,contextLimit:typeof limit==="number"?limit:null,contextTokens,contextTokensSource,contextTokensAt:observation?.at??null,contextGeneration:observation?forkHash({sessionId:session.id,sessionRevision,generation:observation.generation,contextTokens,contextTokensSource,limit,model:session.metadata.lastModel}):null,contextView,compressCreditTokens:session.stats.compressCreditTokens??0,inputTokens:session.stats.inputTokens,outputTokens:session.stats.outputTokens,cachedTokens:session.stats.cachedTokens,requests:session.stats.requests,blocks:session.state.blocks.map(b2=>({id:b2.blockId,tier:b2.tier,active:b2.active})),compressibleRanges:nudge?.compressibleRanges??null,outputBudgetDegraded:obd??null,panel,webUrl:webUrl??null,lastSeen:session.lastSeen}))}async function handlePluginTool(payload,res,deps){let parsed;try{parsed=JSON.parse(payload);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))throw new Error("expected tool object")}catch{res.writeHead(400,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:"invalid JSON body"}));return}const conversationId=typeof parsed.conversationId==="string"?parsed.conversationId.trim():"";const tool=typeof parsed.tool==="string"?parsed.tool:"";if(parsed.toolCallId!==void 0&&(typeof parsed.toolCallId!=="string"||!parsed.toolCallId.trim()||parsed.toolCallId.length>512))return forkReply(res,400,{ok:false,code:"INVALID_REQUEST",error:"toolCallId must be a non-empty string of at most 512 characters"});if(parsed.expectedRevision!==void 0&&(typeof parsed.expectedRevision!=="string"||!/^[a-f0-9]{64}$/.test(parsed.expectedRevision)))return forkReply(res,400,{ok:false,code:"INVALID_REQUEST",error:"expectedRevision must be a snapshot revision"});if(parsed.expectedRevision!==void 0&&!conversationId)return forkReply(res,400,{ok:false,code:"INVALID_REQUEST",error:"expectedRevision requires conversationId"});const bodyArgs=parsed.args&&typeof parsed.args==="object"?parsed.args:{};const routedCallId=typeof parsed.toolCallId==="string"?parsed.toolCallId:"";const toolUseLaneId=routedCallId?lookupToolUseIdSession(routedCallId):void 0;const toolUseSession=toolUseLaneId?peekSession(toolUseLaneId):void 0;const nativeCaller=parsed.nativeCaller===true;const witnessIds=tool?lookupToolWitness(tool,bodyArgs):new Set;let session;let entry;let routedBy="body";if(toolUseSession){session=toolUseSession;const cid=conversationIdForSession(session.id);entry=cid?conversations.get(cid):void 0;routedBy="native";deps.log("info",`[plugin] tool "${tool}": routed by host call id (#4580) to "${session.id}"`)}else if(conversationId){session=await resolveForkConversation(conversationId);entry=conversations.get(conversationId);if(session&&witnessIds.size>0&&!witnessIds.has(session.id)){const lineage=nativeCaller?personaLineageWitness(witnessIds,session.id):void 0;if(lineage){session=lineage;routedBy="witness";deps.log("info",`[plugin] tool "${tool}": host-stamped native caller "${conversationId}" resolves to a stale persona parent \u2014 following live lineage witness "${lineage.id}" (#2601)`)}else if(!nativeCaller){const witnesses=[...witnessIds];let witnessLastSeen=0;for(const wid of witnesses){const ws2=peekSession(wid);if(ws2&&ws2.lastSeen>witnessLastSeen)witnessLastSeen=ws2.lastSeen}const single=witnesses.length===1&&witnesses[0]!==session.id?witnesses[0]:void 0;return forkReply(res,409,{ok:false,code:"TOOL_CONVERSATION_CONFLICT",error:single?`outbound tool witness does not match conversationId \u2014 your captured conversation id "${conversationId}" is stale: the identical call lives in conversation "${single}". Re-send with conversation_id="${single}", or restart the client to re-bind.`:`outbound tool witness does not match conversationId \u2014 your captured conversation id "${conversationId}" is stale and ${witnesses.length} sessions hold the matching outbound witness; refuse to guess. Start a fresh conversation or restart the client to re-bind.`,conversationId,namedSessionId:session.id,witnessSessions:witnesses,namedSessionLastSeen:session.lastSeen,witnessLastSeen})}else{routedBy="native";deps.log("warn",`[plugin] tool "${tool}": host-stamped native caller "${conversationId}" conflicts with outbound witness \u2014 honoring the native caller, refusing the witness (#2024)`)}}else if(session&&nativeCaller){const live=livePersonaDescendant(session,maxCitedRefNum(bodyArgs));if(live){session=live;routedBy="native";deps.log("info",`[plugin] tool "${tool}": host-stamped native caller "${conversationId}" resolves to a stale persona parent \u2014 following live fork "${live.id}" (#2601)`)}}}else if(witnessIds.size===1){const[wit]=[...witnessIds];session=peekSession(wit);if(session){const cid=conversationIdForSession(session.id);entry=cid?conversations.get(cid):void 0;routedBy="witness"}}else if(witnessIds.size>1&&!conversationId){res.writeHead(400,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:`cannot route tool "${tool}": its (name, arguments) was witnessed in ${witnessIds.size} sessions and the request carries no conversationId \u2014 refuse to guess. Re-send with a conversationId, or bind the MCP shim (CLAUDE_CODE_SESSION_ID / BILI_CONVERSATION_ID).`}));return}if(!session&&!conversationId){const now=Date.now();let fresh=0;let bestCid;let bestSeen=-Infinity;for(const[cid,e]of conversations){if(now-e.lastSeen>WITNESS_TTL_MS_PLUGIN)continue;fresh++;if(e.lastSeen>bestSeen){bestSeen=e.lastSeen;bestCid=cid}}if(bestCid&&fresh===1){entry=conversations.get(bestCid);session=entry?peekSession(entry.sessionId):void 0;if(session)routedBy="arb"}else{res.writeHead(400,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:`cannot route tool "${tool}": no conversationId, no outbound witness match, and ${fresh} conversation${fresh===1?"":"s"} active on this proxy \u2014 refuse to guess. Send a model message first, or bind the MCP shim (CLAUDE_CODE_SESSION_ID / BILI_CONVERSATION_ID).`}));return}}if(!session){session=await resolveForkConversation(conversationId);entry=conversations.get(conversationId)}if(!session){if(!entry){if(!warnedNoModelRequests.has(conversationId)){if(warnedNoModelRequests.size>=WARNED_NO_MODEL_REQUESTS_CAP)warnedNoModelRequests.clear();warnedNoModelRequests.add(conversationId);deps.log("warn",`[plugin] NO MODEL REQUESTS seen for conversation ${conversationId} (tool "${tool}"): the model answered without any of its requests reaching this proxy \u2014 candidates: its LLM transport bypasses the intercepted fetch (SDK-injected fetch or non-global dispatcher), the host's attribution left this traffic unclaimed by the proxy, or the conversation id is stale after a host resume. Verify: send a message and look for processTurn lines in bili.log \u2014 none appearing means the traffic never reaches the proxy; routing through the client's bili launcher (baseURL rewrite) reaches it regardless of which fetch the transport uses.`)}}else{deps.log("warn",`[plugin] tool "${tool}" rejected for conversation ${conversationId}: id registered but session not resident in this proxy instance`)}res.writeHead(404,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:!entry?"unknown plugin conversation (no model request has arrived with this conversation id yet \u2014 if your messages ARE still reaching the model, its LLM transport may be bypassing this proxy's fetch interception (SDK-injected fetch / non-global dispatcher), the host's attribution may have left this traffic unclaimed by the proxy, or the id may be stale after a host resume; check bili.log for processTurn lines)":"unknown plugin conversation (id registered but its session is not resident in this proxy instance \u2014 a fresh model request re-binds it)"}));return}if(!isProxyToolFor(tool,session,deps.config)){const note=disabledOptionalToolNote(tool,session,deps.config);if(note!==void 0){deps.log("info",`[${session.id}] [plugin] ${tool} called but disabled \u2014 replied with explanation`);res.writeHead(200,{"content-type":"application/json"});res.end(JSON.stringify({ok:true,result:note}));return}const allowed=[...ACP_TOOL_NAMES];const absorb=effectiveAbsorbConfig(session,deps.config);if(absorb?.enabled===true)allowed.push(absorb.toolName??ABSORB_TOOL_NAME);if(effectiveRulesEnabled(session,deps.config))allowed.push(RULE_TOOL_NAME);if(effectiveBlockOpsConfig(session,deps.config)?.enabled===true)allowed.push(ACP_RETIRE_TOOL_NAME,ACP_RESTORE_TOOL_NAME,ACP_REWRITE_TOOL_NAME);res.writeHead(400,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:`unknown tool "${tool}" (expected one of: ${allowed.join(", ")})`}));return}if(entry)entry.lastSeen=Date.now();const args=parsed.args&&typeof parsed.args==="object"?{...parsed.args}:{};delete args.conversation_id;const callId=typeof parsed.toolCallId==="string"?parsed.toolCallId:`${PLUGIN_FOLD_CALLID_PREFIX}${Date.now().toString(36)}`;acquireInFlight(session);let result;let retrievalExport;try{result=await withSessionLock(session,async()=>{if(parsed.expectedRevision!==void 0){try{if(sessionRevisionOf(session)!==parsed.expectedRevision){forkReply(res,409,{ok:false,code:"PARENT_REVISION_CONFLICT",error:"session revision changed"});return void 0}}catch(err2){forkReply(res,409,{ok:false,status:"unavailable",code:"SNAPSHOT_UNAVAILABLE",error:String(err2)});return void 0}}const mem=session.transient?.pluginMessages;const rawMessages=mem?mem.processed.length>0?mem.processed:mem.original:session.pluginSnapshot??[];const messages=stampEgressSeqs(getStore()?.egressOpLogStore(),session.id,rawMessages);const before=currentContextObservation(session);const creditBefore=session.stats.compressCreditTokens??0;const compressBefore=session.lastCompress;const pendingBefore=new Set(session.pendingRetrievals.map(p2=>p2.ref));const toolResult=await executeProxyToolAsync(tool,args,{core:deps.core,config:effectiveConfig(session,deps.config),messages,compressMessages:mem&&mem.original.length>0?stampEgressSeqs(getStore()?.egressOpLogStore(),session.id,mem.original):void 0,session,log:m2=>deps.log("info",`[${session.id}] [plugin] ${m2}`)},callId,void 0,deps.signal);if(nativeCaller&&tool===retrieveToolName(session)&&typeof args.ref==="string"){const retrieved=applyRetrieve({store:contentStoreOf(session),ref:args.ref,exportDir:path40.join(stateDir(),"retrieve")});if(retrieved.ok&&retrieved.toolResultText===toolResult.text)retrievalExport=retrieved.export}const creditDelta=(session.stats.compressCreditTokens??0)-creditBefore;const restoredInjections=session.pendingRetrievals.filter(p2=>!pendingBefore.has(p2.ref));const restored=tool==="decompress"&&(/^\[Block [^\n]+ content /.test(toolResult.text)||/^\[decompress [^\n]+: restored \d+ item\(s\)/.test(toolResult.text));if(before&&(creditDelta!==0||session.lastCompress!==compressBefore||restored)){const restoredTokens=restored?countMessageTokens({text:toolResult.text})+restoredInjections.reduce((sum,p2)=>sum+countMessageTokens(p2.injection),0):0;recordContextObservation(session,Math.max(0,before.tokens-creditDelta)+restoredTokens,"estimate")}return toolResult})}catch(err2){releaseInFlight(session);deps.log("warn",`[${session.id}] [plugin] tool ${tool} threw: ${String(err2)}`);res.writeHead(500,{"content-type":"application/json"});res.end(JSON.stringify({ok:false,error:String(err2)}));return}releaseInFlight(session);if(result===void 0)return;if(typeof session.metadata.pluginAgent!=="string"&&tool!==retrieveToolName(session)){session.metadata.pluginAgent="mcp"}markDirty(session);deps.log("info",`[${session.id}] [plugin] tool ${tool} executed via plugin (routed by ${routedBy}, #1685) (${result.text.length} chars, outcome=${result.outcome??"n/a"}${result.reason?`, reason=${result.reason}`:""})`);let sentResult=result.text;if(tool==="acp_cache"){const wu=webSessionUrl(deps.webOrigin,session.id);if(wu!==void 0)sentResult=`Web UI: ${wu}
|