billion-context 0.1.207 → 0.1.208

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.
@@ -361,7 +361,7 @@ Summaries are model-generated, fallible historical metadata \u2014 NOT current u
361
361
  ${added}`:added}function hasSeparateOutputBudgetEvidence(origin,modelId){if(origin!==void 0){try{if(new URL(origin).hostname.toLowerCase()===ANTHROPIC_API_HOST)return true}catch{}}if(typeof modelId==="string"&&modelId.length>CLAUDE_MODEL_ID_PREFIX.length&&modelId.toLowerCase().startsWith(CLAUDE_MODEL_ID_PREFIX))return true;return false}function shouldReserveOutputHeadroom(protocol,origin,modelId){if(protocol==="anthropic")return!hasSeparateOutputBudgetEvidence(origin,modelId);return true}function systemCarrierTexts(parsed){const out=[];const sys=parsed.system;if(typeof sys==="string")out.push(sys);else if(Array.isArray(sys))pushBlockTexts(out,sys);const inst=parsed.instructions;if(typeof inst==="string")out.push(inst);const si2=parsed.systemInstruction;if(typeof si2==="object"&&si2!==null){const parts=si2.parts;if(Array.isArray(parts))pushBlockTexts(out,parts)}for(const key2 of["messages","input"]){const arr=parsed[key2];if(!Array.isArray(arr))continue;for(const entry of arr){if(typeof entry!=="object"||entry===null)continue;const rec=entry;if(rec.role!=="system"&&rec.role!=="developer")continue;const c=rec.content;if(typeof c==="string")out.push(c);else if(Array.isArray(c))pushBlockTexts(out,c)}}return out}function pushBlockTexts(out,blocks){for(const b3 of blocks){const t=blockText(b3);if(t!==void 0)out.push(t)}}function blockText(v3){if(typeof v3==="string")return v3;if(typeof v3==="object"&&v3!==null){const t=v3.text;if(typeof t==="string")return t}return void 0}var BILI_PLUGIN_BYPASS_HEADER,BILI_PASSTHROUGH_HEADER,MIN_ASSUMED_WINDOW_TOKENS,CONTEXT_OVERFLOW_PATTERNS,DEFAULT_OUTPUT_HEADROOM_MAX_PCT,ANTHROPIC_API_HOST,CLAUDE_MODEL_ID_PREFIX;var init_util=__esm({"src/util.ts"(){"use strict";BILI_PLUGIN_BYPASS_HEADER="x-bili-plugin-bypass";BILI_PASSTHROUGH_HEADER="x-bili-passthrough";MIN_ASSUMED_WINDOW_TOKENS=1e6;CONTEXT_OVERFLOW_PATTERNS=[/context_length_exceeded/i,/context_window_exceeded/i,/context length exceeded/i,/maximum context length/i,/max context length/i,/maximum context size/i,/longer than the model'?s context length/i,/exceeds the context window/i,/out of room in the model/i,/exceeded model token limit/i,/prompt is too long/i,/prompt_too_long/i,/prompt_is_too_long/i,/request_too_large/i,/token limit exceeded/i,/exceed[_\s]?context[_\s]?size/i,/exceeds the maximum number of tokens/i,/context_limit/i,/上下文.{0,8}(?:超出|超过|超限)/,/(?:超出|超过|超限).{0,8}上下文/,/上下文.{0,8}(?:已满|过长|超长|太大)/,/(?:超出|超过|超限).{0,12}(?:模型上限|上下文窗口)/,/(?:输入|请求|提示词|对话|消息)[^。;;!!\n]{0,10}(?:过长|太长|超长)/,/tokens?[^。;;!!\n]{0,10}(?:超出|超过|超限)/i,/输入[^。;;!!\n]{0,12}(?:超出|超过|超限)/,/prompt[^。;;!!\n]{0,6}(?:过长|太长|超长)/i];DEFAULT_OUTPUT_HEADROOM_MAX_PCT=.25;ANTHROPIC_API_HOST="api.anthropic.com";CLAUDE_MODEL_ID_PREFIX="claude-"}});function matchesAnyMitmDomain(host,domains){const h=host.toLowerCase();return domains.some(d2=>{const dl=d2.toLowerCase();return h===dl||h.endsWith("."+dl)})}var DEFAULT_MITM_DOMAINS;var init_mitm_domains=__esm({"src/mitm-domains.ts"(){"use strict";DEFAULT_MITM_DOMAINS=["api.anthropic.com","api.openai.com","chatgpt.com"]}});function parseCompatRoles(v3){if(!v3||typeof v3!=="object"||Array.isArray(v3))return void 0;const obj=v3;let out;for(const[k2,val]of Object.entries(obj)){if(typeof val!=="string"||val.length===0)continue;out??={};out[k2]=val}return out}function resolveCompatRoles(routes,upstreamUrl,globalRoles){const providerRoles=findRoute(routes,upstreamUrl)?.compat?.roles;if(!globalRoles&&!providerRoles)return{};return{...globalRoles,...providerRoles}}function applyCompatRolesJson(parsed,protocol,roles){if(Object.keys(roles).length===0)return 0;const items=protocol==="openai"?parsed.messages:parsed.input;if(!Array.isArray(items))return 0;let rewritten=0;for(const item of items){if(!item||typeof item!=="object"||Array.isArray(item))continue;const msg=item;if(protocol==="responses"&&msg.type!==void 0&&msg.type!=="message")continue;const role=msg.role;if(typeof role!=="string")continue;const mapped=roles[role];if(mapped===void 0||mapped===role)continue;msg.role=mapped;rewritten++}return rewritten}function detectRoleRejection(status,bodyText){if(status!==400)return null;const head=bodyText.slice(0,4096);for(const re2 of ROLE_REJECTION_PATTERNS){const m3=re2.exec(head);if(!m3)continue;const role=m3[1].toLowerCase();if(ROLE_CAPTURE_STOPWORDS.has(role))continue;return{role}}return null}function detectSystemPlacementError(status,bodyText){if(status!==400)return false;const head=bodyText.slice(0,4096);if(!/system/i.test(head))return false;const norm=head.replace(/['"`[\](){}]/g," ");const PLACEMENT_MARKERS=[/\b(multiple|more\s+than\s+one|exactly\s+one|only\s+one|single|another|second|third)\s+system/i,/\b[2-9]\d*\s+system\s+messages?\b/i,/system\s+messages?\b[^.\n]{0,50}\bindex\s*\d+\b/i,/(system\s+messages?|system\s+roles?)\b[^.\n]{0,50}\b(beginning|start|front|first\s+message|must\s+be\s+first)/i];return PLACEMENT_MARKERS.some(re2=>re2.test(norm))}function hasOffHeadSystem(body,protocol){let parsed;try{parsed=JSON.parse(body)}catch{return false}const items=protocol==="openai"?parsed.messages:parsed.input;if(!Array.isArray(items))return false;const virtualLeading=protocol==="responses"&&typeof parsed.instructions==="string"&&parsed.instructions.length>0;let systems=0;let firstSlotIdx=-1;let firstSystemIdx=-1;items.forEach((item,i)=>{if(!item||typeof item!=="object"||Array.isArray(item))return;const msg=item;const t=msg.type;const isMessage=t===void 0||t==="message";if(protocol==="responses"&&!isMessage&&!ROLE_PRODUCING_TYPES.has(t))return;if(firstSlotIdx<0)firstSlotIdx=i;if(isMessage&&msg.role==="system"){systems++;if(firstSystemIdx<0)firstSystemIdx=i}});if(systems===0)return false;if(systems>1)return true;if(virtualLeading)return true;return firstSystemIdx!==firstSlotIdx}function applyCompatRoles(body,protocol,roles){if(Object.keys(roles).length===0)return{body,rewritten:0};let parsed;try{parsed=JSON.parse(body)}catch{return{body,rewritten:0}}const rewritten=applyCompatRolesJson(parsed,protocol,roles);if(rewritten===0)return{body,rewritten:0};return{body:JSON.stringify(parsed),rewritten}}var ROLE_CAPTURE_STOPWORDS,ROLE_REJECTION_PATTERNS,ROLE_PRODUCING_TYPES;var init_compat_roles=__esm({"src/compat-roles.ts"(){"use strict";init_config();ROLE_CAPTURE_STOPWORDS=new Set(["must","should","be","is","one","of","the","a","an","in","for","not","was","and","or","to","only","allowed","supported","valid","value","message","messages"]);ROLE_REJECTION_PATTERNS=[/(?:invalid|unknown|unsupported|unrecognized|unexpected)[a-z ]{0,24}?role\s*[:=]?\s*["'`]?([a-z][a-z0-9_-]{1,31})["'`]?/i,/role\s*[:=]?\s*["'`]?([a-z][a-z0-9_-]{1,31})["'`]?\s+(?:is\s+)?not\s+(?:supported|allowed|recognized|valid|accepted)/i];ROLE_PRODUCING_TYPES=new Set(["function_call","function_call_output","custom_tool_call","custom_tool_call_output","reasoning"])}});function isPlainObj(v3){return typeof v3==="object"&&v3!==null&&!Array.isArray(v3)}function parsePath(p2){for(const s3 of p2.split("."))if(!SEGMENT_RE.test(s3))return false;return true}function parseCompatDropFields(v3){if(!Array.isArray(v3))return void 0;let out;for(const entry of v3){if(typeof entry!=="string")continue;const p2=entry.trim();if(!parsePath(p2))continue;if(!out)out=[];if(!out.includes(p2))out.push(p2)}return out}function resolveCompatDropFields(routes,upstreamUrl,globalPaths){const providerPaths=findRoute(routes,upstreamUrl)?.compat?.dropFields;const g3=globalPaths??[];if(g3.length===0&&!providerPaths?.length)return[];const out=[...g3];for(const p2 of providerPaths??[])if(!out.includes(p2))out.push(p2);return out}function dropCompatFieldsJson(parsed,paths){if(paths.length===0)return 0;let dropped=0;for(const raw of paths){const segs=raw.split(".");let node=parsed;for(let i=0;i<segs.length-1;i++){node=isPlainObj(node)?node[segs[i]]:void 0}const leaf=segs[segs.length-1];if(isPlainObj(node)&&Object.prototype.hasOwnProperty.call(node,leaf)){delete node[leaf];dropped++}}return dropped}function applyCompatDropFields(body,paths){if(paths.length===0||body.length===0)return{body,dropped:0};let parsed;try{parsed=JSON.parse(body)}catch{return{body,dropped:0}}if(!isPlainObj(parsed))return{body,dropped:0};const dropped=dropCompatFieldsJson(parsed,paths);if(dropped===0)return{body,dropped:0};return{body:JSON.stringify(parsed),dropped}}var SEGMENT_RE;var init_compat_drop=__esm({"src/compat-drop.ts"(){"use strict";init_config();SEGMENT_RE=/^[A-Za-z0-9_-]+$/}});function isPrivateIPv4(host){const a=Number.parseInt(host.split(".")[0]??"",10);const b3=Number.parseInt(host.split(".")[1]??"",10);if(a===127||a===10||a===0)return true;if(a===172&&b3>=16&&b3<=31)return true;if(a===192&&b3===168)return true;if(a===169&&b3===254)return true;return false}function isPrivateHostname(hostname){let host=hostname.toLowerCase();if(host==="localhost"||host.endsWith(".local")||host.endsWith(".lan")||host.endsWith(".internal"))return true;if(host.startsWith("["))host=host.slice(1,-1);if(host.includes(":")){if(host==="::1"||host==="::")return true;const first=host.split(":")[0]??"";if(/^f[cd]/.test(first))return true;if(/^fe[89ab]/.test(first))return true;const dotted=/::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(host);if(dotted&&isPrivateIPv4(dotted[1]))return true;const hex=/::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(host);if(hex){const w1=Number.parseInt(hex[1],16);const w22=Number.parseInt(hex[2],16);if(isPrivateIPv4(`${w1>>8}.${w1&255}.${w22>>8}.${w22&255}`))return true}return false}if(/^\d+\.\d+\.\d+\.\d+$/.test(host))return isPrivateIPv4(host);return false}function plainHttpTrusted(url,allowPrivate){if(LOOPBACK_HOSTNAMES.includes(url.hostname))return true;return allowPrivate&&isPrivateHostname(url.hostname)}var LOOPBACK_HOSTNAMES;var init_private_host=__esm({"src/private-host.ts"(){"use strict";LOOPBACK_HOSTNAMES=["localhost","127.0.0.1","[::1]"]}});function validSummaryCredentialName(value){return/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(value)}function object(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Expected an external summary object");return value}function knownKeys(value,allowed){if(Object.keys(value).some(key2=>!allowed.includes(key2)))throw new Error("Unknown external summary setting; credentials must use credentialRef")}function integer(value,fallback,min,max){const result=value===void 0?fallback:value;if(typeof result!=="number"||!Number.isSafeInteger(result)||result<min||result>max)throw new Error("Invalid external summary budget");return result}function text(value,limit){if(typeof value!=="string"||!value.trim()||value.length>limit||/[\x00-\x1f\x7f]/.test(value))throw new Error("Invalid external summary target");return value.trim()}function parseAutoFold(settings2){let autoFold;if(settings2.autoFold!==void 0){if(typeof settings2.autoFold!=="boolean")throw new Error("External summary autoFold must be boolean");autoFold=settings2.autoFold}let autoFoldTargetTokens;if(settings2.autoFoldTargetTokens!==void 0){if(typeof settings2.autoFoldTargetTokens!=="number"||!Number.isSafeInteger(settings2.autoFoldTargetTokens)||settings2.autoFoldTargetTokens<AUTO_FOLD_TARGET_MIN||settings2.autoFoldTargetTokens>AUTO_FOLD_TARGET_MAX){throw new Error(`External summary autoFoldTargetTokens must be an integer between ${AUTO_FOLD_TARGET_MIN} and ${AUTO_FOLD_TARGET_MAX}`)}autoFoldTargetTokens=settings2.autoFoldTargetTokens}if(autoFold!==true)return{};return{autoFold,...autoFoldTargetTokens!==void 0?{autoFoldTargetTokens}:{}}}function parseConcurrency(settings2){if(settings2.concurrency===void 0)return{};const value=settings2.concurrency;if(typeof value!=="number"||!Number.isSafeInteger(value)||value<SUMMARY_CONCURRENCY_MIN||value>SUMMARY_CONCURRENCY_MAX){throw new Error(`External summary concurrency must be an integer between ${SUMMARY_CONCURRENCY_MIN} and ${SUMMARY_CONCURRENCY_MAX}`)}return{concurrency:value}}function parseBudget(raw){const rawBudget=raw===void 0?{}:object(raw);knownKeys(rawBudget,["totalTimeoutMs","targetTimeoutMs","maxSummaryBytes"]);const totalTimeoutMs=integer(rawBudget.totalTimeoutMs,SUMMARY_DEFAULT_BUDGET.totalTimeoutMs,100,6e5);const targetTimeoutMs=integer(rawBudget.targetTimeoutMs,Math.min(SUMMARY_DEFAULT_BUDGET.targetTimeoutMs,totalTimeoutMs),100,totalTimeoutMs);const maxSummaryBytes=integer(rawBudget.maxSummaryBytes,SUMMARY_DEFAULT_BUDGET.maxSummaryBytes,128,1024*1024);return{totalTimeoutMs,targetTimeoutMs,maxSummaryBytes}}function noteAutoFoldIgnored(settings2){const wantsAutoFold=settings2.autoFold===true;const hasTarget=settings2.autoFoldTargetTokens!==void 0;if(!wantsAutoFold&&!hasTarget)return;const sig=`${wantsAutoFold?"f":"-"}:${hasTarget?"t":"-"}`;if(seenAutoFoldInertWarnings.has(sig))return;seenAutoFoldInertWarnings.add(sig);const knobs=`${wantsAutoFold?"autoFold":""}${wantsAutoFold&&hasTarget?" + ":""}${hasTarget?"autoFoldTargetTokens":""}`;log("warn",`[external-summary] ${knobs} set but "enabled" is not true \u2014 the chain is off, so it has no effect. Set "enabled": true to activate auto-fold.`)}function parseExternalSummaryChain(value){const settings2=object(value);knownKeys(settings2,["enabled","targets","budget","concurrency","autoFold","autoFoldTargetTokens"]);if(settings2.enabled!==void 0&&typeof settings2.enabled!=="boolean")throw new Error("External summary enabled must be boolean");const enabled=settings2.enabled===true;if(!enabled){noteAutoFoldIgnored(settings2);return{enabled:false,targets:[],budget:SUMMARY_DEFAULT_BUDGET}}if(settings2.targets!==void 0&&!Array.isArray(settings2.targets))throw new Error('External summary targets must be an array of "provider/model" references');const refs=settings2.targets??[];if(refs.length>16||refs.length===0)throw new Error("External summary requires 1 to 16 targets when enabled");const targets=refs.map(ref=>{const target=text(ref,256);const slash=target.indexOf("/");if(slash<=0||slash===target.length-1)throw new Error(`External summary target "${target}" must reference a provider and model as "provider/model"`);return target});return{enabled,targets,budget:parseBudget(settings2.budget),...parseConcurrency(settings2),...parseAutoFold(settings2)}}function expandExternalSummaryChain(chain,recipes){if(!chain.enabled)return{enabled:false,targets:[],budget:chain.budget??SUMMARY_DEFAULT_BUDGET};const names=new Set;const targets=chain.targets.map(ref=>{const slash=ref.indexOf("/");const providerName=ref.slice(0,slash);const model=ref.slice(slash+1);const recipe=recipes[providerName];if(!recipe)throw new Error(`External summary target "${ref}" references unknown provider "${providerName}" (known: ${Object.keys(recipes).sort().join(", ")||"none"})`);const knobs=recipe.models[model];if(!knobs)throw new Error(`External summary target "${ref}" references unknown model "${model}" on provider "${providerName}" (known: ${Object.keys(recipe.models).sort().join(", ")})`);let name=`${providerName}--${model}`.replace(/[^A-Za-z0-9_-]/g,"-").replace(/^[^A-Za-z0-9]+/,"").slice(0,64);if(!validSummaryCredentialName(name)||names.has(name))name=`${providerName}-${names.size}`;names.add(name);const contextWindow=integer(knobs.contextWindow,128e3,2048,1e7);const outputTokens=integer(knobs.outputTokens,Math.min(8192,Math.floor(contextWindow/4)),128,contextWindow-1);if(knobs.stream!==void 0&&typeof knobs.stream!=="boolean")throw new Error("External summary stream must be boolean");const stream2=knobs.stream===true;const inlineKey=recipe.apiKey;const credentialRef=recipe.apiKeyEnv?`env:${recipe.apiKeyEnv}`:`secret:${recipe.credentialRef}`;return{name,protocol:recipe.api,url:derivedSummaryEndpoint(recipe,model,stream2),model,...inlineKey!==void 0?{apiKey:inlineKey}:{credentialRef},contextWindow,outputTokens,stream:stream2}});return{enabled:true,targets,budget:chain.budget??SUMMARY_DEFAULT_BUDGET,...chain.concurrency!==void 0?{concurrency:chain.concurrency}:{},...parseAutoFold(chain)}}function derivedSummaryEndpoint(recipe,model,stream2){const base=recipe.baseUrl.replace(/\/+$/,"");let path54;if(recipe.api==="google"){path54=`/models/${encodeURIComponent(model.replace(/^models\//,""))}:${stream2?"streamGenerateContent":"generateContent"}`}else{const suffix=recipe.api==="anthropic"?"/messages":recipe.api==="openai"?"/chat/completions":"/responses";path54=/\/+v\d+[a-z]*$/.test(base)?suffix:`/v1${suffix}`}const url=new URL(`${base}${path54}`);if(url.protocol!=="https:"&&!(url.protocol==="http:"&&plainHttpTrusted(url,allowPrivateHttpProviders()))||url.username||url.password||url.hash||[...url.searchParams.keys()].some(key2=>key2!=="alt")||url.pathname.includes("/bili/")||url.pathname.startsWith("/__bili/"))throw new Error(`External summary endpoint derived from "${recipe.baseUrl}" is not usable; use HTTPS and no embedded credentials or proxy recursion`);return url.href}function parseExternalSummarySettings(value,options={}){const inlineKeys=options.inlineKeys===true;const settings2=object(value);knownKeys(settings2,["enabled","targets","budget","concurrency","autoFold","autoFoldTargetTokens"]);if(settings2.enabled!==void 0&&typeof settings2.enabled!=="boolean")throw new Error("External summary enabled must be boolean");const enabled=settings2.enabled===true;if(!enabled){noteAutoFoldIgnored(settings2);return{enabled:false,targets:[],budget:SUMMARY_DEFAULT_BUDGET}}if(settings2.targets!==void 0&&!Array.isArray(settings2.targets))throw new Error("External summary targets must be an array");const values=settings2.targets??[];if(values.length>16||values.length===0)throw new Error("External summary requires 1 to 16 targets when enabled");const names=new Set;const targets=values.map(value2=>{const target=object(value2);knownKeys(target,inlineKeys?["name","protocol","url","model","credentialRef","apiKey","contextWindow","outputTokens","stream"]:["name","protocol","url","model","credentialRef","contextWindow","outputTokens","stream"]);const name=text(target.name,64);if(!validSummaryCredentialName(name)||names.has(name))throw new Error("External summary target names must be unique identifiers");names.add(name);const protocol=target.protocol;if(protocol!=="anthropic"&&protocol!=="openai"&&protocol!=="responses"&&protocol!=="google")throw new Error("Invalid external summary protocol");const endpoint=text(target.url,2048);let url;try{url=new URL(endpoint)}catch{throw new Error("Invalid external summary endpoint")}if(url.protocol!=="https:"&&!(url.protocol==="http:"&&plainHttpTrusted(url,allowPrivateHttpProviders()))||url.username||url.password||url.hash||[...url.searchParams.keys()].some(key2=>key2!=="alt")||url.pathname.includes("/bili/")||url.pathname.startsWith("/__bili/"))throw new Error("Invalid external summary endpoint; use HTTPS and no embedded credentials or proxy recursion");const inlineKey=inlineKeys?target.apiKey:void 0;if(inlineKey!==void 0&&(typeof inlineKey!=="string"||inlineKey.length===0||inlineKey.length>8192||/[\x00-\x20\x7f]/.test(inlineKey)))throw new Error("Invalid external summary api key");if(inlineKey!==void 0&&target.credentialRef!==void 0)throw new Error("External summary target carries both apiKey and credentialRef \u2014 exactly one credential is allowed");let credentialRef;if(inlineKey===void 0){credentialRef=text(target.credentialRef,128);if(!/^env:[A-Za-z_][A-Za-z0-9_]*$/.test(credentialRef)&&!(credentialRef.startsWith("secret:")&&validSummaryCredentialName(credentialRef.slice(7))))throw new Error("Invalid external summary credential reference")}const contextWindow=integer(target.contextWindow,128e3,2048,1e7);const outputTokens=integer(target.outputTokens,Math.min(8192,Math.floor(contextWindow/4)),128,contextWindow-1);if(target.stream!==void 0&&typeof target.stream!=="boolean")throw new Error("External summary stream must be boolean");const model=text(target.model,200);if(protocol==="google"){const suffix=target.stream===true?"streamGenerateContent":"generateContent";if(!url.pathname.endsWith(`/models/${encodeURIComponent(model.replace(/^models\//,""))}:${suffix}`))throw new Error("Google summary endpoint must match the model and stream mode")}return{name,protocol,url:url.href,model,...inlineKey!==void 0?{apiKey:inlineKey}:{credentialRef},contextWindow,outputTokens,stream:target.stream===true}});return{enabled:true,targets,budget:parseBudget(settings2.budget),...parseConcurrency(settings2),...parseAutoFold(settings2)}}function expandExternalSummaryChainTolerant(chain,recipes){try{return expandExternalSummaryChain(chain,recipes)}catch(error){const message=error instanceof Error?error.message:String(error);if(!seenExpansionWarnings.has(message)){seenExpansionWarnings.add(message);log("warn",`[external-summary] ${message} \u2014 the chain is disabled until the reference is fixed`)}return{enabled:false,targets:[],budget:SUMMARY_DEFAULT_BUDGET}}}var SUMMARY_DEFAULT_BUDGET,SUMMARY_CONCURRENCY_MIN,SUMMARY_CONCURRENCY_MAX,SUMMARY_CONCURRENCY_DEFAULT,AUTO_FOLD_TARGET_MIN,AUTO_FOLD_TARGET_MAX,seenAutoFoldInertWarnings,seenExpansionWarnings;var init_external_summary_settings=__esm({"src/external-summary-settings.ts"(){"use strict";init_logger();init_private_host();init_knobs();SUMMARY_DEFAULT_BUDGET={totalTimeoutMs:5e4,targetTimeoutMs:25e3,maxSummaryBytes:64*1024};SUMMARY_CONCURRENCY_MIN=1;SUMMARY_CONCURRENCY_MAX=32;SUMMARY_CONCURRENCY_DEFAULT=4;AUTO_FOLD_TARGET_MIN=8192;AUTO_FOLD_TARGET_MAX=1e7;seenAutoFoldInertWarnings=new Set;seenExpansionWarnings=new Set}});import{readFileSync as readFileSync3,existsSync,mkdirSync as mkdirSync2,writeFileSync}from"fs";import{createHash as createHash4}from"crypto";import{dirname}from"path";function safeReadJson(path54){try{const raw=readFileSync3(path54,"utf8").replace(/^\uFEFF/,"");return JSON.parse(raw)}catch(e){if(e.code!=="ENOENT"){log("error",`[acp-config] failed to parse ${path54}: ${String(e)}`)}return void 0}}function modelRoots(model){const slash=model.lastIndexOf("/");if(slash>0&&slash<model.length-1)return[model.slice(slash+1),model];return[model]}function lookupContextLimit(model){if(!model)return void 0;for(const root of modelRoots(model)){for(const entry of CONTEXT_LIMIT_TABLE){if(entry.match.test(root))return entry.limit}}return void 0}function tierGatedStandardWindow(model){if(!model)return void 0;for(const root of modelRoots(model)){if(!TIER_GATED_FAMILIES.some(fam=>fam.match.test(root)))continue;for(const entry of CONTEXT_LIMIT_TABLE){if(entry.match.test(root))return entry.limit}}return void 0}function findRouteKey(routes,upstreamUrl){if(!upstreamUrl)return void 0;let bestKey="";for(const key2 of Object.keys(routes)){if(upstreamUrl===key2||upstreamUrl.startsWith(key2+"/")){if(key2.length>bestKey.length)bestKey=key2}}return bestKey||void 0}function findRoute(routes,upstreamUrl){const key2=findRouteKey(routes,upstreamUrl);return key2?routes[key2]:void 0}function resolveConfiguredContextLimit(routes,upstreamUrl,model){if(!model||!upstreamUrl)return void 0;const m3=findRoute(routes,upstreamUrl)?.models?.[model];if(m3?.context&&m3.context>0)return m3.context;return void 0}function resolveConfiguredOutputLimit(routes,upstreamUrl,model){if(!model||!upstreamUrl)return void 0;const m3=findRoute(routes,upstreamUrl)?.models?.[model];if(m3?.output&&m3.output>0)return m3.output;return void 0}function resolveCompressProtocol(routes,upstreamUrl){return findRoute(routes,upstreamUrl)?.compressProtocol}function resolveDeclaredProtocol(routes,url){if(!url)return void 0;const path54=url.split("?",2)[0];let best;let bestLen=-1;for(const key2 of Object.keys(routes)){if(routes[key2].protocol===void 0)continue;if(path54===key2||path54.startsWith(key2+"/")){if(key2.length>bestLen){bestLen=key2.length;best=routes[key2].protocol}}}return best}function warnNamedProviderOnce(signature,message){if(seenNamedProviderWarnings.has(signature))return;seenNamedProviderWarnings.add(signature);log("warn",`[acp-config] ${message}`)}function warnInertRoutingFields(key2,obj){if(!obj)return;const recipe=obj.baseUrl!==void 0||obj.api!==void 0;const inert=NAMED_PROVIDER_ROUTING_FIELDS.filter(f2=>f2 in obj&&obj[f2]!==void 0&&!(recipe&&f2==="models"));if(inert.length===0)return;warnNamedProviderOnce(`inert:${key2}:${inert.join(",")}`,`providers."${key2}" carries routing fields without "bind" [${inert.join(", ")}] \u2014 they are inert (add "bind": "<upstream base URL>" to apply them, or move them under the URL entry)`)}function routeCarriesFields(route){if(!route)return false;return Object.values(route).some(v3=>v3!==void 0)}function mitmTwinCovers(routes,target){for(const key2 of Object.keys(routes)){if(!key2.startsWith("mitm://"))continue;let twin;try{twin=new URL(key2)}catch{continue}if(twin.host!==target.host)continue;const tp=twin.pathname;if(tp===""||tp==="/")return true;const pp=target.pathname;if(pp===tp||pp.startsWith(tp+"/"))return true}return false}function warnInertMitmLaneKeys(routes,env){const fileConfig=loadConfigFile();const mitmEnabled=(env.BILI_MITM??(fileConfig.mitm?.enabled===false?"0":"1"))!=="0";if(!mitmEnabled)return;const whitelist=[...DEFAULT_MITM_DOMAINS,...resolveMitmDomains(env)];for(const key2 of Object.keys(routes)){let u2;try{u2=new URL(key2)}catch{continue}if(u2.protocol!=="https:")continue;if(!matchesAnyMitmDomain(u2.hostname,whitelist))continue;if(!routeCarriesFields(routes[key2]))continue;if(mitmTwinCovers(routes,u2))continue;const twin="mitm://"+key2.slice("https://".length);warnNamedProviderOnce(`mitm-inert:${key2}`,`providers."${key2}" is inert for MITM-lane traffic to ${u2.host} \u2014 CONNECT traffic looks up "${twin}", which has no entry, so these settings never apply to proxy-routed clients. Add a "${twin}" entry to cover them (the https:// entry still serves /bili/-embedded requests).`)}}function isUrlLikeKey(key2){return/^(https?|mitm):\/\//i.test(key2.trim())}function normalizeBindTarget(raw){try{const u2=new URL(raw.trim());if(u2.protocol!=="http:"&&u2.protocol!=="https:")return void 0;return normalizeUrlKey(u2.href)}catch{return void 0}}function cloneJsonValue(value){if(!value||typeof value!=="object")return value;if(Array.isArray(value))return value.map(cloneJsonValue);const out={};for(const[k2,v3]of Object.entries(value))out[k2]=cloneJsonValue(v3);return out}function fillRouteGaps(winner,filler){const isObj6=v3=>!!v3&&typeof v3==="object"&&!Array.isArray(v3);const fillerObj=isObj6(filler)?filler:null;if(!fillerObj)return cloneJsonValue(winner);const winnerObj=isObj6(winner)?winner:null;if(!winnerObj)return cloneJsonValue(filler);const out={};for(const[k2,fv]of Object.entries(fillerObj))out[k2]=cloneJsonValue(fv);for(const[k2,wv]of Object.entries(winnerObj)){const fv=k2 in out?out[k2]:void 0;out[k2]=isObj6(wv)&&isObj6(fv)?fillRouteGaps(wv,fv):cloneJsonValue(wv)}return out}function parseNamedProviderRecipe(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("a named provider recipe must be an object");const obj=value;const unknownKeys=Object.keys(obj).filter(key2=>![...NAMED_PROVIDER_RECIPE_FIELDS,"bind","compactionOptIn"].includes(key2));if(unknownKeys.length>0)throw new Error(`unknown recipe fields on named provider entry [${unknownKeys.join(", ")}] \u2014 routing fields need "bind"; credentials must use apiKeyEnv/credentialRef`);if(typeof obj.baseUrl!=="string"||!obj.baseUrl.trim()||obj.baseUrl.length>2048)throw new Error("recipe baseUrl must be a non-empty string");if(obj.api!=="anthropic"&&obj.api!=="openai"&&obj.api!=="responses"&&obj.api!=="google")throw new Error(`recipe api must be one of: anthropic, openai, responses, google (got ${JSON.stringify(obj.api)})`);if(obj.apiKeyEnv!==void 0&&(typeof obj.apiKeyEnv!=="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(obj.apiKeyEnv)))throw new Error("recipe apiKeyEnv must be an environment variable name");if(obj.credentialRef!==void 0&&(typeof obj.credentialRef!=="string"||!validSummaryCredentialName(obj.credentialRef)))throw new Error("recipe credentialRef must be a secret-store credential name");if(obj.apiKeyEnv!==void 0&&obj.credentialRef!==void 0)throw new Error("recipe carries both apiKeyEnv and credentialRef \u2014 pick one");if(obj.apiKeyEnv===void 0&&obj.credentialRef===void 0)throw new Error("recipe needs a credential reference (apiKeyEnv or credentialRef)");if(!obj.models||typeof obj.models!=="object"||Array.isArray(obj.models)||Object.keys(obj.models).length===0)throw new Error("recipe models must be a non-empty object of model entries");const models={};for(const[id,raw]of Object.entries(obj.models)){const knobs=raw&&typeof raw==="object"&&!Array.isArray(raw)?raw:{};const unknown=Object.keys(knobs).filter(key2=>!["contextWindow","outputTokens","stream"].includes(key2));if(unknown.length>0)throw new Error(`unknown fields on recipe model "${id}" [${unknown.join(", ")}]`);if(knobs.contextWindow!==void 0&&(typeof knobs.contextWindow!=="number"||!Number.isSafeInteger(knobs.contextWindow)||knobs.contextWindow<2048||knobs.contextWindow>1e7))throw new Error(`recipe model "${id}" contextWindow must be an integer in [2048, 10000000]`);if(knobs.outputTokens!==void 0&&(typeof knobs.outputTokens!=="number"||!Number.isSafeInteger(knobs.outputTokens)||knobs.outputTokens<128))throw new Error(`recipe model "${id}" outputTokens must be an integer >= 128`);if(knobs.stream!==void 0&&typeof knobs.stream!=="boolean")throw new Error(`recipe model "${id}" stream must be a boolean`);models[id]={...knobs.contextWindow!==void 0?{contextWindow:knobs.contextWindow}:{},...knobs.outputTokens!==void 0?{outputTokens:knobs.outputTokens}:{},...knobs.stream!==void 0?{stream:knobs.stream}:{}}}return{baseUrl:obj.baseUrl.trim().replace(/\/+$/,""),api:obj.api,...obj.apiKeyEnv!==void 0?{apiKeyEnv:obj.apiKeyEnv}:{},...obj.credentialRef!==void 0?{credentialRef:obj.credentialRef}:{},models}}function isNamedProviderRecipeShape(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const obj=value;return obj.baseUrl!==void 0||obj.api!==void 0}function collectNamedProviders(providers){const out={};for(const[key2,value]of Object.entries(providers)){if(isUrlLikeKey(key2)||value===null||typeof value!=="object"||Array.isArray(value))continue;if(!isNamedProviderRecipeShape(value))continue;if(!validSummaryCredentialName(key2)){warnNamedProviderOnce(`recipe-name:${key2}`,`providers."${key2}" is not a valid recipe name ([A-Za-z0-9][A-Za-z0-9_-]{0,63}) \u2014 the entry is ignored`);continue}try{out[key2]=parseNamedProviderRecipe(value)}catch(error){warnNamedProviderOnce(`recipe:${key2}`,`providers."${key2}" has an invalid recipe (${error instanceof Error?error.message:String(error)}) \u2014 chains referencing it are disabled`)}}return out}function loadNamedProviders(env=process.env){const fileConfig=loadConfigFile();const out={};const routesPath=env.ACP_PROVIDERS??fileConfig.providersPath??"";if(routesPath){const parsed=safeReadJson(routesPath);if(parsed&&typeof parsed==="object"&&!Array.isArray(parsed))Object.assign(out,collectNamedProviders(parsed))}if(fileConfig.providers){const inline=collectNamedProviders(fileConfig.providers);for(const[name,recipe]of Object.entries(inline))if(out[name]===void 0)out[name]=recipe}return out}function loadRoutes(env=process.env){const fileConfig=loadConfigFile();const routes={};const aliases=[];const ingest=(key2,value,urlWins)=>{rejectLegacyRoute(key2,value);const route=parseRouteEntry(value);if(!route)return;const obj=value&&typeof value==="object"&&!Array.isArray(value)?value:null;const urlLike=isUrlLikeKey(key2);if(obj&&"bind"in obj){const bind=obj.bind;if(typeof bind!=="string"){warnNamedProviderOnce(`bad-bind:${key2}`,`providers."${key2}".bind must be a string http(s) base URL \u2014 the entry stays routing-inert`)}else if(urlLike){warnNamedProviderOnce(`bind-on-url:${key2}`,`providers."${key2}" has "bind" \u2014 ignored: URL keys are already lanes (remove "bind", or rename the key to make it a named entry)`)}else if(bind.trim().length>0){const target=normalizeBindTarget(bind);if(target){aliases.push({target,route});return}warnNamedProviderOnce(`bad-bind:${key2}`,`providers."${key2}".bind is not a valid http(s) base URL ("${bind}") \u2014 the entry stays routing-inert`)}}if(!urlLike)warnInertRoutingFields(key2,obj);const normKey=normalizeUrlKey(key2);if(urlWins||!routes[normKey])routes[normKey]=route};const routesPath=env.ACP_PROVIDERS??fileConfig.providersPath??"";if(routesPath){const parsed=safeReadJson(routesPath);if(parsed&&typeof parsed==="object"&&!Array.isArray(parsed)){for(const[k2,v3]of Object.entries(parsed))ingest(k2,v3,true)}}if(fileConfig.providers){for(const[k2,v3]of Object.entries(fileConfig.providers))ingest(k2,v3,false)}for(const{target,route}of aliases){routes[target]=fillRouteGaps(routes[target],route)}warnInertMitmLaneKeys(routes,env);return routes}function passthroughState(env){const filePassthrough=loadConfigFile().passthrough===true;if(env.ACP_PASSTHROUGH!==void 0)return{enabled:env.ACP_PASSTHROUGH==="1",source:"env"};return{enabled:filePassthrough,source:filePassthrough?"file":null}}function normAbsorbValue(field,v3){if(field==="contextThresholdPct"&&typeof v3==="string"){const m3=v3.match(/^(-?\d+(?:\.\d+)?)\s*%$/);if(m3)return Number(m3[1])/100}return v3}function findAbsorbPluginDivergences(routes,baseAbsorb){const out=[];const check=(scope,level)=>{if(!level)return;for(const field of ABSORB_DIVERGENCE_FIELDS){if(level[field]===void 0)continue;if(JSON.stringify(normAbsorbValue(field,level[field]))!==JSON.stringify(normAbsorbValue(field,baseAbsorb?.[field]))){out.push(`${scope}.absorb.${field}=${JSON.stringify(level[field])} (base=${JSON.stringify(baseAbsorb?.[field])})`)}}};for(const[url,route]of Object.entries(routes)){check(url,route.compress?.absorb);for(const[model,entry]of Object.entries(route.models??{}))check(`${url}/${model}`,entry.compress?.absorb)}return out}function warnAbsorbPluginDivergences(routes,baseAbsorb){const divs=findAbsorbPluginDivergences(routes,baseAbsorb);if(divs.length===0)return;const sig=divs.join("\0");if(seenAbsorbDivergenceWarnings.has(sig))return;seenAbsorbDivergenceWarnings.add(sig);log("warn",`[acp-config] provider/model absorb override diverges from base [${divs.join("; ")}] \u2014 plugin-mode sessions follow the base value, proxy-mode sessions honor the override (#1359)`)}function findCcrPluginDivergences(routes,globalCompress){const base=globalCompress?.ccr;if(base?.enabled!==true)return[];const out=[];const report=(level,ccr)=>{if(!ccr)return;for(const f2 of CCR_FIELDS){if(!(f2 in ccr))continue;const value=ccr[f2];const effective=base[f2]??DEFAULT_CCR_CONFIG[f2];const differs=Array.isArray(value)&&Array.isArray(effective)?JSON.stringify(value)!==JSON.stringify(effective):value!==effective;if(differs)out.push({level,field:f2,value,effective})}};for(const[url,route]of Object.entries(routes)){report(`provider ${url}`,route.compress?.ccr);for(const[model,entry]of Object.entries(route.models??{})){report(`provider ${url} model ${model}`,entry.compress?.ccr)}}return out}function formatCcrValue(v3){return typeof v3==="string"?`"${v3}"`:JSON.stringify(v3)}function warnCcrPluginDivergences(routes,globalCompress){for(const dv of findCcrPluginDivergences(routes,globalCompress)){log("warn",`[acp-config] ccr override ignored in plugin sessions: ${dv.level} ccr.${dv.field}=${formatCcrValue(dv.value)} \u2014 plugin sessions use ${formatCcrValue(dv.effective)} (base config governs the plugin manifest surface, #1345); proxy-mode sessions honor the override`)}}function isMcpBiliHardProtected(toolName){return toolName.startsWith(MCP_BILI_TOOL_PREFIX)&&MCP_HARD_PROTECTED_BARE_NAMES.includes(toolName.slice(MCP_BILI_TOOL_PREFIX.length))}function isMcpBiliCompress(toolName){return toolName==="compress"||toolName.startsWith(MCP_BILI_TOOL_PREFIX)&&toolName.slice(MCP_BILI_TOOL_PREFIX.length)==="compress"}function loadOptions(env=process.env){const fileConfig=loadConfigFile();if(env.BILI_ALLOW_DSH_COMPACTION!==void 0&&!removedDshEnvWarned){removedDshEnvWarned=true;log("warn","[acp-config] env BILI_ALLOW_DSH_COMPACTION was removed (#3651, superseding #2028) \u2014 ignored; dsh native compaction is now refused unconditionally by the wire guard")}const port=parseInt(env.ACP_PORT??env.PORT??`${fileConfig.port??8787}`,10);if(!Number.isInteger(port)||port<1||port>65535){throw new Error(`Invalid port ${Number.isNaN(port)?"(not a number)":port}; must be 1-65535`)}const rawHost=env.ACP_HOST??fileConfig.host??"127.0.0.1";const host=rawHost==="localhost"?"127.0.0.1":rawHost;const upstream=(env.ACP_UPSTREAM??fileConfig.upstream??"https://api.anthropic.com").replace(/\/$/,"");const routes=loadRoutes(env);const namedProviders=loadNamedProviders(env);warnAbsorbPluginDivergences(routes,fileConfig.compress?.absorb);warnCcrPluginDivergences(routes,fileConfig.compress);const passthrough=passthroughState(env);const modelContextLimit=parseInt(env.ACP_MODEL_CONTEXT_LIMIT??`${fileConfig.modelContextLimit??2e5}`,10);const biliProxy=nonEmpty(env.BILI_UPSTREAM_PROXY);const webProxy=nonEmpty(fileConfig.upstreamProxy);const configProxy=nonEmpty(fileConfig.proxy);const rawProxyMode=env.BILI_UPSTREAM_PROXY_MODE??fileConfig.upstreamProxyMode??(webProxy?"manual":void 0);const effectiveMode=rawProxyMode??"direct";const proxyMode=parseUpstreamProxyMode(effectiveMode);const explicitDirect=proxyMode==="direct"&&!biliProxy;const defaultDirect=rawProxyMode===void 0&&!biliProxy;const proxy=biliProxy??(proxyMode==="direct"?"":proxyMode==="manual"?webProxy??configProxy:configProxy);const proxySource=biliProxy?"bili-env":proxyMode==="direct"?"direct":proxyMode==="manual"&&webProxy?"web-manual":configProxy?"config":"auto";const httpProxy=nonEmpty(env.HTTP_PROXY??env.http_proxy);const httpsProxy=nonEmpty(env.HTTPS_PROXY??env.https_proxy);const allProxy=nonEmpty(env.ALL_PROXY??env.all_proxy);const noProxy=nonEmpty(env.NO_PROXY??env.no_proxy);const proxyFallback={...httpProxy?{httpProxy}:{},...httpsProxy?{httpsProxy}:{},...allProxy?{allProxy}:{},...noProxy?{noProxy}:{},biliPort:port,globalSource:proxySource,explicitDirect,defaultDirect};const inheritedHttpProxy=nonEmpty(env.BILI_INHERITED_HTTP_PROXY);const inheritedHttpsProxy=nonEmpty(env.BILI_INHERITED_HTTPS_PROXY);const inheritedAllProxy=nonEmpty(env.BILI_INHERITED_ALL_PROXY);const inheritedNoProxy=nonEmpty(env.BILI_INHERITED_NO_PROXY);const auxProxyFallback={...proxyFallback,explicitDirect:rawProxyMode==="direct"&&!biliProxy,...httpProxy?{}:inheritedHttpProxy?{httpProxy:inheritedHttpProxy}:{},...httpsProxy?{}:inheritedHttpsProxy?{httpsProxy:inheritedHttpsProxy}:{},...allProxy?{}:inheritedAllProxy?{allProxy:inheritedAllProxy}:{},...noProxy?{}:inheritedNoProxy?{noProxy:inheritedNoProxy}:{}};validateHttpProxy(proxy,proxyFallback.biliPort);for(const[url,route]of Object.entries(routes)){try{validateHttpProxy(route.proxy,proxyFallback.biliPort)}catch(error){throw new Error(`[acp-config] invalid upstream proxy for ${url}: ${String(error)}`)}}return{port,host,upstream,auxProxyFallback,routes,namedProviders,proxy,proxyMode,proxySource,proxyFallback,modelContextLimit,kernelConfig:{...defaultConfig(modelContextLimit),isToolProtected:isMcpBiliHardProtected,isCompressTool:isMcpBiliCompress},compress:{...fileConfig.compress??{},injectTool:(env.ACP_COMPRESS_TOOL??(fileConfig.compress?.injectTool===false?"0":"1"))!=="0",injectNudge:(env.ACP_COMPRESS_NUDGE??(fileConfig.compress?.injectNudge===false?"0":"1"))!=="0"},promptCache:{routing:parsePromptCacheRouting(env.ACP_PROMPT_CACHE_ROUTING??fileConfig.promptCache?.routing)},compat:{roles:parseCompatRoles(fileConfig.compat?.roles)??{},dropFields:parseCompatDropFields(fileConfig.compat?.dropFields)??[]},streamErrorShape:parseStreamErrorShape(env.BILI_STREAM_ERROR_SHAPE??fileConfig.compat?.streamErrorShape),imageBilling:parseImageBilling(fileConfig.imageBilling),imageTokenCap:parseImageTokenCap(fileConfig.imageTokenCap),sessionHeader:env.ACP_SESSION_HEADER??fileConfig.sessionHeader??"x-acp-session",log:env.ACP_LOG!=="0"&&fileConfig.log!==false,debug:(env.ACP_DEBUG??(fileConfig.debug?"1":"0"))==="1",dumpSse:env.ACP_DUMP_SSE||fileConfig.dumpSse||void 0,passthrough:passthrough.enabled,passthroughSource:passthrough.source,autoUpdate:(env.ACP_AUTO_UPDATE??(fileConfig.autoUpdate===false?"0":"1"))!=="0",autoRestartOnUpdate:(env.ACP_AUTO_RESTART_ON_UPDATE??(fileConfig.autoRestartOnUpdate===true?"1":"0"))!=="0",updateTag:(env.ACP_UPDATE_TAG??fileConfig.updateTag??"latest").trim()||"latest",advisoryCheck:(env.BILI_ADVISORY_CHECK??(fileConfig.advisoryCheck===false?"0":"1"))!=="0",releaseNotesCheck:(env.BILI_RELEASE_NOTES_CHECK??(fileConfig.releaseNotesCheck===false?"0":"1"))!=="0",advisoryUrl:env.BILI_ADVISORY_URL||fileConfig.advisoryUrl||void 0,releaseNotesUrl:env.BILI_RELEASE_NOTES_URL||fileConfig.releaseNotesUrl||void 0,logFile:env.ACP_LOG_FILE!==void 0?env.ACP_LOG_FILE||void 0:fileConfig.logFile,mitm:{enabled:(env.BILI_MITM??(fileConfig.mitm?.enabled===false?"0":"1"))!=="0",domains:dedupeDomains([...fileConfig.mitm?.domains??[],...splitCsv(env.BILI_MITM_DOMAINS)])},maskHosts:(env.BILI_LOG_MASK_HOSTS??(fileConfig.maskHosts===false?"0":"1"))!=="0",subagentSplit:(env.BILI_SUBAGENT_SPLIT??(fileConfig.subagentSplit===false?"0":"1"))!=="0",forkAdoption:(env.BILI_FORK_ADOPTION??(fileConfig.forkAdoption===true?"1":"0"))!=="0",affinitySimhash:(env.BILI_AFFINITY_SIMHASH??(fileConfig.affinitySimhash===false?"0":"1"))!=="0",resumeInheritance:(env.BILI_RESUME_INHERITANCE??(fileConfig.resumeInheritance===false?"0":"1"))!=="0",chainContentDetection:(env.BILI_CHAIN_CONTENT??(fileConfig.chainContentDetection===true?"1":"0"))!=="0",chainEgressStamp:(env.BILI_CHAIN_STAMP??(fileConfig.chainEgressStamp===true?"1":"0"))!=="0",stableSystemAnchor:(env.BILI_STABLE_SYSTEM_ANCHOR??(fileConfig.stableSystemAnchor===true?"1":"0"))!=="0"}}function resolveMitmDomains(env){return dedupeDomains([...loadConfigFile().mitm?.domains??[],...splitCsv(env.BILI_MITM_DOMAINS)])}function resolveRecordedMitmDomains(passed,env=process.env){const fileConfig=loadConfigFile();const enabled=(env.BILI_MITM??(fileConfig.mitm?.enabled===false?"0":"1"))!=="0";if(!enabled)return[];const effective=passed&&passed.length>0?passed.join(","):env.BILI_MITM_DOMAINS;return dedupeDomains([...fileConfig.mitm?.domains??[],...splitCsv(effective)])}function nonEmpty(value){const trimmed=value?.trim();return trimmed?trimmed:void 0}function splitCsv(value){if(!value)return[];return value.split(",").map(s3=>s3.trim()).filter(s3=>s3.length>0)}function dedupeDomains(list){const seen=new Set;const out=[];for(const d2 of list){if(!seen.has(d2)){seen.add(d2);out.push(d2)}}return out}function warnUnknownTopLevelKeys(obj){const unknown=Object.keys(obj).filter(key2=>!KNOWN_TOP_LEVEL_KEYS.has(key2)&&key2!=="allowDshCompaction");if(unknown.length===0)return;const signature=[...unknown].sort().join("\0");if(seenUnknownTopLevelKeySignatures.has(signature))return;seenUnknownTopLevelKeySignatures.add(signature);const misplaced=unknown.filter(key2=>COMPRESS_SETTING_FIELDS.has(key2));const hint=misplaced.length>0?` \u2014 ${misplaced.map(k2=>`"${k2}" belongs under "compress" (did you mean "compress.${k2}"?)`).join("; ")}`:"";log("warn",`[acp-config] ignoring unknown top-level config key(s): ${unknown.join(", ")}${hint}`)}function parseBiliConfig(raw){try{return JSON.parse(raw)}catch{const errors=[];const value=parse2(raw,errors,{allowTrailingComma:true});if(errors.length===0)return value;const first=errors[0];throw new SyntaxError(`invalid JSON/JSONC at ${lineColumnOf(raw,first.offset)}: ${printParseErrorCode(first.error)}`)}}function lineColumnOf(text2,offset){let line=1;let column=1;for(let i=0;i<offset&&i<text2.length;i++){if(text2.charAt(i)==="\n"){line++;column=1}else column++}return`line ${line} column ${column}`}function loadConfigFile(){const path54=configFile();let raw;let value;try{raw=readFileSync3(path54,"utf8").replace(/^\uFEFF/,"");const cached=configFileCache;if(cached&&cached.raw===raw)return cached.value;const parsed=parseBiliConfig(raw);if(parsed&&typeof parsed==="object"&&!Array.isArray(parsed)){const obj=parsed;warnRemovedDshAllowKey(obj);warnUnknownTopLevelKeys(obj);warnInertResignPassthrough(obj);warnInertStripImages(obj);warnInertRemovedCompressKeys(obj);value=obj}else{value={}}}catch(e){if(e.code!=="ENOENT"){log("error",`[acp-config] failed to parse ${path54}: ${String(e)}`)}if(raw!==void 0)value={}}if(raw===void 0||value===void 0)return{};configFileCache={raw,value};return value}function configFileEpoch(){let raw;try{raw=readFileSync3(configFile(),"utf8").replace(/^\uFEFF/,"")}catch{raw=""}return createHash4("sha256").update(raw).digest("hex")}function warnRemovedDshAllowKey(obj){const hits=[];if(Object.prototype.hasOwnProperty.call(obj,"allowDshCompaction")&&obj.allowDshCompaction!==null&&obj.allowDshCompaction!==void 0){hits.push('top-level "allowDshCompaction"')}const d2=obj.dsh;if(d2!==null&&typeof d2==="object"&&!Array.isArray(d2)){const live=new Set(["authoredCompaction","contextTab","contextTabLabel"]);for(const key2 of Object.keys(d2))if(!live.has(key2))hits.push(`dsh.${key2}`)}hits.sort();const sig=hits.join(",");if(sig===""||sig===removedDshAllowKeySignature)return;removedDshAllowKeySignature=sig;log("warn",`[acp-config] ${hits.join(", ")} was removed (#3651, superseding #2028) \u2014 value(s) ignored: dsh native compaction is now refused unconditionally by the wire guard on every lane. Delete it from your config to silence this.`)}function resolveResignSettings(env=process.env,provider={},scheme=RESIGN_BUILTIN_SCHEME){const key2=scheme.trim().toLowerCase();const file=loadConfigFile().resign?.[key2]??{};const providerBlock=provider?.[key2]??{};const enabled=env.BILI_RESIGN!==void 0?env.BILI_RESIGN!=="0":providerBlock.enabled!==void 0?providerBlock.enabled:file.enabled!==false;const passthrough=env.BILI_RESIGN_PASSTHROUGH!==void 0?env.BILI_RESIGN_PASSTHROUGH==="1"||env.BILI_RESIGN_PASSTHROUGH==="true":providerBlock.passthrough!==void 0?providerBlock.passthrough:file.passthrough===true;const credentialRef=env.BILI_CODEARTS_REF?.trim()||providerBlock.credentialRef||file.credentialRef||void 0;return{enabled,passthrough,credentialRef}}function warnInertStripImages(obj){const compress=obj.compress;if(!compress||typeof compress!=="object"||Array.isArray(compress))return;const hit=["stripImages","stripImagesKeepRecent"].filter(k2=>compress[k2]!==void 0);const sig=hit.join(",");if(sig===""||sig===seenInertStripImagesSignature)return;seenInertStripImagesSignature=sig;log("warn",`[acp-config] compress.${hit.join("/compress.")} is INERT \u2014 compress.stripImages was removed: media now folds by default (#2640) and decompress({ imageRef }) recovers folded pixels; nothing is stripped from the wire anymore. Remove the key(s) from the config.`)}function warnInertRemovedCompressKeys(obj){const hits=[];const scanBlock=(block,pathPrefix)=>{if(!block||typeof block!=="object"||Array.isArray(block))return;for(const key2 of INERT_REMOVED_COMPRESS_KEYS){if(block[key2]!==void 0)hits.push(`${pathPrefix}.${key2}`)}};scanBlock(obj.compress,"compress");const providers=obj.providers;if(providers&&typeof providers==="object"&&!Array.isArray(providers)){for(const[url,entry]of Object.entries(providers)){if(!entry||typeof entry!=="object"||Array.isArray(entry))continue;const p2=entry;scanBlock(p2.compress,`providers["${url}"].compress`);const models=p2.models;if(models&&typeof models==="object"&&!Array.isArray(models)){for(const[model,mEntry]of Object.entries(models)){if(!mEntry||typeof mEntry!=="object"||Array.isArray(mEntry))continue;scanBlock(mEntry.compress,`providers["${url}"].models["${model}"].compress`)}}}}hits.sort();const sig=hits.join(",");if(sig===""||sig===seenInertRemovedCompressKeysSignature)return;seenInertRemovedCompressKeysSignature=sig;log("warn",`[acp-config] ${hits.join(", ")} is INERT \u2014 compress.imageCompression was removed and no longer does anything at any level (image pre-compression + image_full restore channel, #3266). Remove it from the config; images pass through byte-identical.`)}function warnInertResignPassthrough(obj){const inert=[];const consider=(map,providerBlockFor)=>{if(!map||typeof map!=="object"||Array.isArray(map))return;for(const[key2,val]of Object.entries(map)){if(key2===RESIGN_BUILTIN_SCHEME)continue;const block=val!==null&&typeof val==="object"&&!Array.isArray(val)?val:{};if(block["passthrough"]!==true)continue;const fileBlock=(obj.resign??{})[key2];const providerBlock=providerBlockFor(key2);const enabled=process.env.BILI_RESIGN!==void 0?process.env.BILI_RESIGN!=="0":providerBlock?.enabled!==void 0?providerBlock.enabled:fileBlock?.enabled!==false;if(enabled)inert.push(key2)}};consider(obj.resign,()=>void 0);const providers=obj.providers;if(providers&&typeof providers==="object"&&!Array.isArray(providers)){for(const entry of Object.values(providers)){if(!entry||typeof entry!=="object"||Array.isArray(entry))continue;const pmap=entry.resign;if(pmap===void 0)continue;consider(pmap,key2=>(pmap??{})[key2])}}inert.sort();const sig=inert.join(",");if(sig===""||sig===inertResignPassthroughSignature)return;inertResignPassthroughSignature=sig;const list=inert.map(k2=>`resign["${k2}"].passthrough`).join(", ");log("warn",`[acp-config] ${list}=true is INERT \u2014 since the #2090 compress-or-refuse contract, unsigned pass-through exists ONLY for the built-in scheme "${RESIGN_BUILTIN_SCHEME}"; those signed requests stay REFUSED until bili ships a re-signer for them. Restore pre-resign handling with resign["<scheme>"].enabled=false or BILI_RESIGN=0 (the upstream will then reject the rewritten bodies).`)}function resolveZonePortBase(env=process.env){const fromEnv=Number.parseInt(env.BILI_ZONE_PORT??"",10);if(Number.isInteger(fromEnv)&&fromEnv>0&&fromEnv<65536)return fromEnv;return ZONE_PORT_BASE}function resolveNativeAttachExternal(env=process.env){const fromEnv=(env.BILI_NATIVE_ATTACH_EXTERNAL??"").trim().toLowerCase();if(fromEnv==="1"||fromEnv==="true")return true;if(fromEnv==="0"||fromEnv==="false")return false;return loadConfigFile().native?.attachExternal===true}function resolveNativeAttachLanePriority(){const raw=loadConfigFile().native?.attachLanePriority;if(!Array.isArray(raw))return[];const out=[];for(const item of raw){if(typeof item!=="string")continue;const t=item.trim();if(t.length>0&&!out.includes(t))out.push(t)}return out}function resolveNativeAttachPolicy(env=process.env){const norm=v3=>(v3??"").trim().toLowerCase();const fromEnv=norm(env.BILI_NATIVE_ATTACH_POLICY);if(fromEnv==="global-fallback"||fromEnv==="global")return"global-fallback";if(fromEnv==="own-lane"||fromEnv==="ownlane"||fromEnv==="strict")return"own-lane";const file=norm(loadConfigFile().native?.attachPolicy);if(file==="global-fallback"||file==="global")return"global-fallback";return"own-lane"}function resolveNativeAttachUrl(env=process.env){const fromEnv=(env.BILI_MCP_PROXY??"").trim();if(fromEnv.length>0)return fromEnv;const file=(loadConfigFile().native?.attachUrl??"").trim();return file.length>0?file:void 0}function ensureConfigTemplate(){const p2=configFile();if(existsSync(p2))return false;try{mkdirSync2(dirname(p2),{recursive:true});writeFileSync(p2,TEMPLATE_CONFIG+"\n","utf8");log("info",`[acp-config] created empty config at ${p2} \u2014 add your providers (see README Quickstart), then restart`);return true}catch{return false}}function normalizeUrlKey(key2){return key2.replace(/\/+$/,"")}function parseRouteEntry(v3){if(v3&&typeof v3==="object"&&!Array.isArray(v3)){const obj=v3;const route={models:obj.models};if(typeof obj.proxy==="string")route.proxy=obj.proxy;if(obj.compressProtocol==="marker"||obj.compressProtocol==="tools")route.compressProtocol=obj.compressProtocol;const declaredProtocol=parseDeclaredWireProtocol(obj.protocol);if(declaredProtocol!==void 0)route.protocol=declaredProtocol;if(obj.compress)route.compress=obj.compress;const cacheKeepalive=parseCacheKeepaliveSettings(obj.cacheKeepalive);if(cacheKeepalive)route.cacheKeepalive=cacheKeepalive;for(const raw of Object.values(obj.models??{})){if(raw&&typeof raw==="object"&&!Array.isArray(raw)&&Object.prototype.hasOwnProperty.call(raw,"cacheKeepalive")){parseCacheKeepaliveSettings(raw.cacheKeepalive)}}const compat={};const compatRoles=parseCompatRoles(obj.compat?.roles);if(compatRoles)compat.roles=compatRoles;const compatDrops=parseCompatDropFields(obj.compat?.dropFields);if(compatDrops)compat.dropFields=compatDrops;if(Object.keys(compat).length>0)route.compat=compat;if(typeof obj.passthrough==="boolean")route.passthrough=obj.passthrough;if(typeof obj.direct==="boolean")route.direct=obj.direct;const imageBilling=parseImageBilling(obj.imageBilling);if(imageBilling)route.imageBilling=imageBilling;const imageTokenCap=parseImageTokenCap(obj.imageTokenCap);if(imageTokenCap!==void 0)route.imageTokenCap=imageTokenCap;const calibration=parseCalibrationPolicy(obj.calibration);if(calibration)route.calibration=calibration;if(obj.baseUrl===void 0&&obj.api===void 0){if(obj.apiKeyEnv!==void 0||obj.credentialRef!==void 0){if(obj.apiKeyEnv!==void 0&&obj.credentialRef!==void 0)throw new Error("[acp-config] providers entry carries both apiKeyEnv and credentialRef \u2014 exactly one lane credential is allowed");if(obj.apiKeyEnv!==void 0){if(typeof obj.apiKeyEnv!=="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(obj.apiKeyEnv))throw new Error(`[acp-config] providers entry apiKeyEnv must be an environment variable name (got ${JSON.stringify(obj.apiKeyEnv)})`);route.apiKeyEnv=obj.apiKeyEnv}else{if(typeof obj.credentialRef!=="string"||!validSummaryCredentialName(obj.credentialRef))throw new Error(`[acp-config] providers entry credentialRef must be a name in the summary-credential store (got ${JSON.stringify(obj.credentialRef)})`);route.credentialRef=obj.credentialRef}}}return route}if(v3===null)return{};return void 0}function parseImageBilling(value){return value==="auto"||value==="pixels"||value==="bytes"?value:void 0}function parseDeclaredWireProtocol(v3){if(v3===void 0)return void 0;if(v3==="anthropic"||v3==="openai"||v3==="responses"||v3==="google")return v3;throw new Error(`[acp-config] providers.protocol must be one of: anthropic, openai, responses, google (got ${JSON.stringify(v3)})`)}function parseImageTokenCap(value){return typeof value==="number"&&Number.isInteger(value)&&value>0?value:void 0}function parseCalibrationPolicy(value){if(value===void 0)return void 0;if(!value||typeof value!=="object"||Array.isArray(value))throw new Error(`[acp-config] providers entry calibration must be an object with "disabled" and/or "max" (got ${JSON.stringify(value)})`);const vo=value;for(const key2 of Object.keys(vo)){if(key2!=="disabled"&&key2!=="max")throw new Error(`[acp-config] providers entry calibration has unknown key "${key2}" (allowed: disabled, max)`)}const out={};if("disabled"in vo){if(typeof vo.disabled!=="boolean")throw new Error(`[acp-config] providers entry calibration.disabled must be a boolean (got ${JSON.stringify(vo.disabled)})`);out.disabled=vo.disabled}if("max"in vo){const m3=vo.max;if(typeof m3!=="number"||!Number.isFinite(m3)||m3<=0||m3>4)throw new Error(`[acp-config] providers entry calibration.max must be a number > 0 and <= 4 (got ${JSON.stringify(m3)})`);out.max=m3}if(out.disabled===void 0&&out.max===void 0)throw new Error('[acp-config] providers entry calibration requires at least one of "disabled" or "max"');return out}function parseCacheKeepaliveSettings(v3){if(v3===void 0)return void 0;if(!v3||typeof v3!=="object"||Array.isArray(v3))throw new Error(`[acp-config] cacheKeepalive must be an object of optional fields (got ${JSON.stringify(v3)})`);const obj=v3;for(const key2 of Object.keys(obj)){if(!CACHE_KEEPALIVE_FIELDS.includes(key2))throw new Error(`[acp-config] cacheKeepalive has unknown key "${key2}" (allowed: ${CACHE_KEEPALIVE_FIELDS.join(", ")})`)}const out={};if("enabled"in obj){if(typeof obj.enabled!=="boolean")throw new Error(`[acp-config] cacheKeepalive.enabled must be a boolean (got ${JSON.stringify(obj.enabled)})`);out.enabled=obj.enabled}if("ttlFactor"in obj){const n=obj.ttlFactor;if(typeof n!=="number"||!Number.isFinite(n)||!(n>0&&n<=1))throw new Error(`[acp-config] cacheKeepalive.ttlFactor must be a number in (0, 1] (got ${JSON.stringify(n)})`);out.ttlFactor=n}for(const key2 of["maxDurationMs","maxConcurrentPings","intervalMs"]){if(key2 in obj){const n=obj[key2];if(typeof n!=="number"||!Number.isInteger(n)||n<=0)throw new Error(`[acp-config] cacheKeepalive.${key2} must be a positive integer ms/count (got ${JSON.stringify(n)})`);out[key2]=n}}if("assumeTtl"in obj){if(obj.assumeTtl!=="5m"&&obj.assumeTtl!=="1h")throw new Error(`[acp-config] cacheKeepalive.assumeTtl must be "5m" or "1h" (got ${JSON.stringify(obj.assumeTtl)})`);out.assumeTtl=obj.assumeTtl}if("armWithoutBreakpoints"in obj){if(typeof obj.armWithoutBreakpoints!=="boolean")throw new Error(`[acp-config] cacheKeepalive.armWithoutBreakpoints must be a boolean (got ${JSON.stringify(obj.armWithoutBreakpoints)})`);out.armWithoutBreakpoints=obj.armWithoutBreakpoints}return Object.keys(out).length>0?out:void 0}function parseStreamErrorShape(value){return value==="completion"?"completion":"protocol"}function parsePromptCacheRouting(value){return value==="enabled"||value==="disabled"?value:"auto"}function parseUpstreamProxyMode(value){return value==="manual"||value==="auto"?value:"direct"}function parseCompressSettings(v3){if(!v3||typeof v3!=="object"||Array.isArray(v3))return void 0;const obj=v3;const out={};if(obj.externalSummary!==void 0){try{out.externalSummary=parseExternalSummaryChain(obj.externalSummary)}catch(error){log("warn",`[config] compress.externalSummary is invalid (${error instanceof Error?error.message:String(error)}); ignoring the whole compress section`);return void 0}}const numberOrPercent=value=>typeof value==="number"&&Number.isFinite(value)||typeof value==="string"&&/^\d+(\.\d+)?%$/.test(value.trim());let ok=true;const takeNumber=key2=>{if(!(key2 in obj))return;if(typeof obj[key2]!=="number"||!Number.isFinite(obj[key2]))ok=false;else out[key2]=obj[key2]};for(const key2 of["modelContextLimit","maxContextLimit","emergencyThresholdPercent"]){if(!(key2 in obj))continue;if(!numberOrPercent(obj[key2])){ok=false;continue}out[key2]=typeof obj[key2]==="string"?obj[key2].trim():obj[key2]}for(const key2 of["nudgeGrowthTokens","preserveRecentMessages","preserveRecentTokens","minCompressRange","minCompressRangeChars"]){takeNumber(key2)}if("nudgeDecisionMaxTokens"in obj){const v4=obj.nudgeDecisionMaxTokens;if(typeof v4!=="number"||!Number.isFinite(v4)||v4<=0){ok=false}else{out.nudgeDecisionMaxTokens=Math.floor(v4)}}if("outputHeadroomMaxPct"in obj){const v4=obj.outputHeadroomMaxPct;if(typeof v4!=="number"&&typeof v4!=="string")ok=false;else{const pct2=resolveOutputHeadroomCap(v4);if(!Number.isFinite(pct2)||pct2<0)ok=false;else out.outputHeadroomMaxPct=v4}}if("tiers"in obj){if(typeof obj.tiers!=="boolean")ok=false;else out.tiers=obj.tiers}if("tierNudgeTokens"in obj&&obj.tierNudgeTokens!==void 0){const v4=obj.tierNudgeTokens;if(!v4||typeof v4!=="object"||Array.isArray(v4)){ok=false}else{const vo=v4;const cleaned={};for(const key2 of["t1","t2","t3"]){if(!(key2 in vo))continue;const x2=vo[key2];if(typeof x2!=="number"||!Number.isFinite(x2)||x2<1){ok=false;continue}cleaned[key2]=x2}if(ok&&Object.keys(cleaned).length>0)out.tierNudgeTokens=cleaned}}if("nudgeModelDecided"in obj){if(typeof obj.nudgeModelDecided!=="boolean")ok=false;else out.nudgeModelDecided=obj.nudgeModelDecided}if("minPressureBenefitTokens"in obj){const v4=obj.minPressureBenefitTokens;if(typeof v4!=="number"||!Number.isFinite(v4)||v4<0)ok=false;else out.minPressureBenefitTokens=Math.floor(v4)}for(const key2 of["protectedLatestTools","protectedTools"]){if(!(key2 in obj)||obj[key2]===void 0)continue;const v4=obj[key2];if(!Array.isArray(v4)||v4.length===0||v4.some(x2=>typeof x2!=="string"||x2.trim().length===0))ok=false;else out[key2]=v4.map(x2=>x2.trim())}if("neverPreserveRecentTools"in obj&&obj.neverPreserveRecentTools!==void 0){const v4=obj.neverPreserveRecentTools;if(!Array.isArray(v4)||v4.some(x2=>typeof x2!=="string"||x2.trim().length===0))ok=false;else out.neverPreserveRecentTools=v4.map(x2=>x2.trim())}if("preserveRecentTools"in obj&&obj.preserveRecentTools!==void 0){const v4=obj.preserveRecentTools;if(!Array.isArray(v4)||v4.length===0||v4.some(x2=>typeof x2!=="string"||x2.trim().length===0))ok=false;else out.preserveRecentTools=v4.map(x2=>x2.trim())}if("visibilityMarkers"in obj){if(typeof obj.visibilityMarkers!=="boolean")ok=false;else out.visibilityMarkers=obj.visibilityMarkers}if("streamSummary"in obj){if(typeof obj.streamSummary!=="boolean")ok=false;else out.streamSummary=obj.streamSummary}if("rules"in obj){if(typeof obj.rules!=="boolean")ok=false;else out.rules=obj.rules}for(const key2 of["injectTool","injectNudge"]){if(key2 in obj){if(typeof obj[key2]!=="boolean")ok=false;else out[key2]=obj[key2]}}if("acknowledgePromptsRisk"in obj){if(typeof obj.acknowledgePromptsRisk!=="boolean")ok=false;else out.acknowledgePromptsRisk=obj.acknowledgePromptsRisk}if("absorb"in obj&&obj.absorb!==void 0){const a=obj.absorb;if(!a||typeof a!=="object"||Array.isArray(a)){ok=false}else{const ao2=a;const cleaned={};for(const key2 of["enabled","minToolTokens","contextThresholdPct","excludeTools","toolName","mediaOnly"]){if(!(key2 in ao2))continue;const v4=ao2[key2];if(key2==="enabled"||key2==="mediaOnly"){if(typeof v4!=="boolean"){ok=false;continue}if(key2==="enabled")cleaned.enabled=v4;else cleaned.mediaOnly=v4}else if(key2==="minToolTokens"){if(typeof v4!=="number"||!Number.isFinite(v4)){ok=false;continue}cleaned.minToolTokens=v4}else if(key2==="contextThresholdPct"){if(!numberOrPercent(v4)){ok=false;continue}cleaned.contextThresholdPct=typeof v4==="string"?v4.trim():v4}else if(key2==="excludeTools"){if(!Array.isArray(v4)||v4.some(x2=>typeof x2!=="string")){ok=false;continue}cleaned.excludeTools=[...v4]}else{if(typeof v4!=="string"||v4.trim().length===0){ok=false;continue}cleaned.toolName=v4.trim()}}if(ok)out.absorb=cleaned}}if("ccr"in obj&&obj.ccr!==void 0){const c=obj.ccr;if(!c||typeof c!=="object"||Array.isArray(c)){ok=false}else{const co2=c;const cleaned={};for(const key2 of["enabled","minToolTokens","excludeTools","toolName","maxHeadChars"]){if(!(key2 in co2))continue;const v4=co2[key2];if(key2==="enabled"){if(typeof v4!=="boolean"){ok=false;continue}cleaned.enabled=v4}else if(key2==="minToolTokens"||key2==="maxHeadChars"){if(typeof v4!=="number"||!Number.isFinite(v4)){ok=false;continue}cleaned[key2]=v4}else if(key2==="excludeTools"){if(!Array.isArray(v4)||v4.some(x2=>typeof x2!=="string")){ok=false;continue}cleaned.excludeTools=[...v4]}else{if(typeof v4!=="string"||v4.trim().length===0){ok=false;continue}cleaned.toolName=v4.trim()}}if(ok)out.ccr=cleaned}}if("search"in obj&&obj.search!==void 0){const c=obj.search;if(!c||typeof c!=="object"||Array.isArray(c)){ok=false}else{const co2=c;const cleaned={};for(const key2 of["planAware"]){if(!(key2 in co2))continue;const v4=co2[key2];if(typeof v4!=="boolean"){ok=false;continue}cleaned.planAware=v4}if(ok)out.search=cleaned}}if("prompts"in obj&&obj.prompts!==void 0){const prompts=obj.prompts;if(!prompts||typeof prompts!=="object"||Array.isArray(prompts)){ok=false}else{const cleaned={};for(const[key2,value]of Object.entries(prompts)){if(typeof value!=="string"||value.trim().length===0){ok=false;continue}if(key2!=="compressPhilosophy"&&key2!=="howToCompressRules"&&key2!=="tier2DistillRules"&&key2!=="tier3CondenseRules"){ok=false;continue}cleaned[key2]=value}if(ok)out.prompts=cleaned}}if("promptPack"in obj&&obj.promptPack!==void 0){if(typeof obj.promptPack!=="string"||obj.promptPack.trim().length===0)ok=false;else out.promptPack=obj.promptPack.trim()}if("reasoningGuard"in obj&&obj.reasoningGuard!==void 0){const rg=obj.reasoningGuard;if(!rg||typeof rg!=="object"||Array.isArray(rg)){ok=false}else{const rgo=rg;const cleaned={};for(const key2 of["enabled","maxContinue","maxTierN","markerText","base","offset","debugLog"]){if(!(key2 in rgo))continue;const v4=rgo[key2];if(key2==="enabled"){if(typeof v4!=="boolean"){ok=false;continue}cleaned.enabled=v4}else if(key2==="debugLog"){if(typeof v4!=="boolean"){ok=false;continue}cleaned.debugLog=v4}else if(key2==="markerText"){if(typeof v4!=="string"||v4.trim().length===0){ok=false;continue}cleaned.markerText=v4.trim()}else{if(typeof v4!=="number"||!Number.isFinite(v4)){ok=false;continue}cleaned[key2]=v4}}if(ok)out.reasoningGuard=cleaned}}if("outputSteering"in obj&&obj.outputSteering!==void 0){const os13=obj.outputSteering;if(!os13||typeof os13!=="object"||Array.isArray(os13)){ok=false}else{out.outputSteering=os13}}if("priceProfile"in obj&&obj.priceProfile!==void 0){const pp=obj.priceProfile;if(!pp||typeof pp!=="object"||Array.isArray(pp)){ok=false}else{const ppo=pp;const cleaned={};for(const key2 of["w","r","q"]){if(!(key2 in ppo))continue;const v4=ppo[key2];if(typeof v4!=="number"||!Number.isFinite(v4)||v4<0){ok=false;continue}cleaned[key2]=v4}if(ok)out.priceProfile=cleaned}}if(!ok)return void 0;return out}function rejectLegacyRoute(key2,value){if(typeof value!=="string")return;const masked=maskUrlForLog(value);throw new Error(`[acp-config] legacy provider route "${key2}": "${masked}" is no longer valid; use the upstream URL as the key, for example { "${masked.replace(/\/+$/,"")}": {} }`)}var CONTEXT_LIMIT_TABLE,TIER_GATED_FAMILIES,FALLBACK_EFFECTIVE_WINDOW_FLOOR,NAMED_PROVIDER_ROUTING_FIELDS,seenNamedProviderWarnings,NAMED_PROVIDER_RECIPE_FIELDS,ABSORB_DIVERGENCE_FIELDS,seenAbsorbDivergenceWarnings,CCR_FIELDS,MCP_BILI_TOOL_PREFIX,MCP_HARD_PROTECTED_BARE_NAMES,KNOWN_TOP_LEVEL_KEYS,COMPRESS_SETTING_FIELDS,seenUnknownTopLevelKeySignatures,configFileCache,removedDshAllowKeySignature,removedDshEnvWarned,RESIGN_BUILTIN_SCHEME,inertResignPassthroughSignature,seenInertStripImagesSignature,INERT_REMOVED_COMPRESS_KEYS,seenInertRemovedCompressKeysSignature,ZONE_PORT_BASE,TEMPLATE_CONFIG,CACHE_KEEPALIVE_FIELDS;var init_config=__esm({"src/config.ts"(){"use strict";init_dist();init_main();init_paths();init_logger();init_upstream_proxy();init_log_mask();init_util();init_mitm_domains();init_compat_roles();init_compat_drop();init_external_summary_settings();CONTEXT_LIMIT_TABLE=[{match:/^claude-/i,limit:2e5},{match:/^gpt-5/i,limit:4e5},{match:/^gpt-4\.1/i,limit:1e6},{match:/^gpt-4o/i,limit:128e3},{match:/^gpt-4-turbo/i,limit:128e3},{match:/^o[13]-/i,limit:2e5},{match:/^gemini-3/i,limit:1048576},{match:/^gemini-2\.5/i,limit:1e6},{match:/^gemini-1\.5/i,limit:1e6},{match:/^glm-4\.6/i,limit:128e3},{match:/^glm-5/i,limit:1e6},{match:/^glm-/i,limit:2e5},{match:/^deepseek-(r1|v3|ocr)/i,limit:128e3},{match:/^deepseek/i,limit:1e6},{match:/^minimax/i,limit:204800},{match:/^qwen/i,limit:2e5},{match:/^kimi/i,limit:2e5},{match:/^llama-/i,limit:2e5}];TIER_GATED_FAMILIES=[{match:/^claude-/i}];FALLBACK_EFFECTIVE_WINDOW_FLOOR=1e5;NAMED_PROVIDER_ROUTING_FIELDS=["compress","models","proxy","passthrough","compressProtocol","protocol","compat","imageBilling","imageTokenCap"];seenNamedProviderWarnings=new Set;NAMED_PROVIDER_RECIPE_FIELDS=["baseUrl","api","apiKeyEnv","credentialRef","models"];ABSORB_DIVERGENCE_FIELDS=["enabled","toolName","minToolTokens","contextThresholdPct","excludeTools","mediaOnly"];seenAbsorbDivergenceWarnings=new Set;CCR_FIELDS=["enabled","toolName","minToolTokens","excludeTools","maxHeadChars"];MCP_BILI_TOOL_PREFIX="mcp__bili__";MCP_HARD_PROTECTED_BARE_NAMES=["compress","acp_rule"];KNOWN_TOP_LEVEL_KEYS=new Set(["port","host","upstream","providersPath","providers","proxy","modelContextLimit","sessionHeader","log","debug","dumpSse","passthrough","autoUpdate","autoRestartOnUpdate","updateTag","advisoryCheck","advisoryUrl","releaseNotesCheck","releaseNotesUrl","upstreamProxy","upstreamProxyMode","logFile","compress","promptCache","mitm","maskHosts","subagentSplit","forkAdoption","affinitySimhash","resumeInheritance","chainContentDetection","chainEgressStamp","stableSystemAnchor","rollout","dsh","compat","imageBilling","imageTokenCap","claude","native","resign","pi","storage","security","network","persist","sessions","plugin","update","diagnostics","fakeCompletion","codexCompact","ccrRetrievalTtlMs","decompressTmpCap","autoModeForge","imageRescale","guardrails","cacheKeepalive"]);COMPRESS_SETTING_FIELDS=new Set(["modelContextLimit","maxContextLimit","emergencyThresholdPercent","nudgeGrowthTokens","minPressureBenefitTokens","tierNudgeTokens","nudgeModelDecided","nudgeDecisionMaxTokens","preserveRecentMessages","preserveRecentTokens","minCompressRange","minCompressRangeChars","outputHeadroomMaxPct","tiers","protectedLatestTools","protectedTools","neverPreserveRecentTools","preserveRecentTools","visibilityMarkers","rules","injectTool","injectNudge","acknowledgePromptsRisk","absorb","ccr","search","prompts","promptPack","reasoningGuard","outputSteering","priceProfile","reconcile","streamSummary"]);seenUnknownTopLevelKeySignatures=new Set;configFileCache=null;removedDshAllowKeySignature="";removedDshEnvWarned=false;RESIGN_BUILTIN_SCHEME="sdk-hmac-sha256";inertResignPassthroughSignature=null;seenInertStripImagesSignature="";INERT_REMOVED_COMPRESS_KEYS=["imageCompression"];seenInertRemovedCompressKeysSignature="";ZONE_PORT_BASE=18787;TEMPLATE_CONFIG=`{
362
362
  "providers": {
363
363
  }
364
- }`;CACHE_KEEPALIVE_FIELDS=["enabled","ttlFactor","maxDurationMs","maxConcurrentPings","assumeTtl","armWithoutBreakpoints","intervalMs"]}});function parseDurationField(text2){let rest=text2.trim().toLowerCase();if(rest.length===0)return void 0;let total=0;while(rest.length>0){const m3=rest.match(DURATION_SEGMENT_RE);if(!m3)return void 0;total+=Number(m3[1])*DURATION_UNITS_MS[m3[2]];rest=rest.slice(m3[0].length)}return Number.isFinite(total)?Math.floor(total):void 0}var DURATION_UNITS_MS,DURATION_SEGMENT_RE;var init_duration=__esm({"src/duration.ts"(){"use strict";DURATION_UNITS_MS={s:1e3,m:6e4,h:36e5,d:864e5,w:6048e5};DURATION_SEGMENT_RE=/^(\d+(?:\.\d+)?)([smhdw])/}});import{createHash as createHash5}from"crypto";function sha256Hex(bytes){return createHash5("sha256").update(bytes).digest("hex")}function splitMediaContent(content){let media=[];let split=content;if(content.includes('"imageBase64"')){let parsed;try{parsed=JSON.parse(content)}catch{parsed=void 0}if(parsed){const bytes=parsed.imageBase64;if(typeof bytes==="string"&&bytes.length>0){const mediaHash=sha256Hex(bytes);parsed.imageBase64={$media:mediaHash};split=JSON.stringify(parsed);media.push({hash:mediaHash,bytes})}}}if(split.includes(";base64,")){const byHash=new Map(media.map(m3=>[m3.hash,m3.bytes]));split=split.replace(MEDIA_URL_MARKER_RE,(_all,mime,payload)=>{const mediaHash=sha256Hex(payload);if(!byHash.has(mediaHash)){byHash.set(mediaHash,payload);media=[...media,{hash:mediaHash,bytes:payload}]}return`data:${mime};base64,{$media:${mediaHash}}`})}return{content:split,hash:sha256Hex(split),media}}function identityInputOf(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return raw}if(parsed.id===void 0&&parsed.wireIndex===void 0)return raw;delete parsed.id;delete parsed.wireIndex;return JSON.stringify(parsed)}function identityOfStoredContent(content){return sha256Hex(identityInputOf(content))}var MIN_MEDIA_URL_SPLIT_BYTES,MEDIA_URL_MARKER_RE;var init_identity=__esm({"src/storage/identity.ts"(){"use strict";MIN_MEDIA_URL_SPLIT_BYTES=2048;MEDIA_URL_MARKER_RE=new RegExp(`data:([a-zA-Z0-9.+\\/-]+);base64,([A-Za-z0-9+/=]{${MIN_MEDIA_URL_SPLIT_BYTES},})`,"g")}});function storagePragmas(walJournalSizeLimitBytes){return["PRAGMA journal_mode = WAL","PRAGMA synchronous = NORMAL","PRAGMA busy_timeout = 5000","PRAGMA foreign_keys = ON",`PRAGMA journal_size_limit = ${walJournalSizeLimitBytes}`,"PRAGMA auto_vacuum = INCREMENTAL"]}function migrateSchema(db){const row=db.prepare("PRAGMA user_version").get();const from=row?.user_version??0;if(from>=STORAGE_SCHEMA_VERSION)return{from,to:from};db.transaction(()=>{if(from<1)db.exec(STORAGE_DDL_V1);if(from<2){const cols=db.prepare("PRAGMA table_info(sessions)").all().map(c=>typeof c?.name==="string"?c.name:"");if(!cols.includes("namespace")){db.exec("ALTER TABLE sessions ADD COLUMN namespace TEXT NOT NULL DEFAULT 'proxy'")}if(!cols.includes("origin")){db.exec("ALTER TABLE sessions ADD COLUMN origin TEXT")}}if(from<3){db.exec("CREATE TABLE IF NOT EXISTS conversations (\n namespace TEXT NOT NULL,\n conversation_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n claimed_at INTEGER NOT NULL,\n PRIMARY KEY (namespace, conversation_id)\n ) WITHOUT ROWID");db.exec("INSERT OR IGNORE INTO conversations (namespace, conversation_id, session_id, claimed_at) SELECT namespace, session_id, session_id, updated_at FROM sessions")}if(from<4){db.exec("CREATE TABLE IF NOT EXISTS session_ext (\n session_id TEXT NOT NULL,\n key TEXT NOT NULL,\n value_json TEXT NOT NULL,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (session_id, key)\n ) WITHOUT ROWID");db.exec("CREATE TABLE IF NOT EXISTS kv_store (\n namespace TEXT NOT NULL,\n key TEXT NOT NULL,\n value_json TEXT NOT NULL,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (namespace, key)\n ) WITHOUT ROWID")}if(from<7){db.exec("CREATE TABLE IF NOT EXISTS message_media (\n session_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n media_hash TEXT NOT NULL REFERENCES content(hash),\n PRIMARY KEY (session_id, seq, media_hash)\n ) WITHOUT ROWID")}if(from<5){const cols=db.prepare("PRAGMA table_info(sessions)").all().map(c=>typeof c?.name==="string"?c.name:"");if(!cols.includes("last_ingested_seq")){db.exec("ALTER TABLE sessions ADD COLUMN last_ingested_seq INTEGER")}}if(from<6){const cols=db.prepare("PRAGMA table_info(sessions)").all().map(c=>typeof c?.name==="string"?c.name:"");if(!cols.includes("orphans_json")){db.exec("ALTER TABLE sessions ADD COLUMN orphans_json TEXT")}}if(from<8){const msgCols=db.prepare("PRAGMA table_info(messages)").all().map(c=>typeof c?.name==="string"?c.name:"");if(!msgCols.includes("identity")){db.exec("ALTER TABLE messages ADD COLUMN identity TEXT NOT NULL DEFAULT ''")}if(!msgCols.includes("retired_at")){db.exec("ALTER TABLE messages ADD COLUMN retired_at INTEGER")}db.exec("CREATE INDEX IF NOT EXISTS idx_messages_identity ON messages (session_id, msg_id, identity)");const rows=db.prepare("SELECT m.session_id AS session_id, m.seq AS seq, m.msg_id AS msg_id, m.content_hash AS content_hash, c.bytes AS content FROM messages m JOIN content c ON c.hash = m.content_hash").all();const keep=new Map;const drop=[];const rawByIdentityKey=new Map;for(const r of rows){const raw=typeof r.content==="string"?r.content:Buffer.from(r.content).toString("utf8");const identity=identityOfStoredContent(raw);rawByIdentityKey.set(`${r.session_id}\0${r.msg_id}\0${identity}`,raw);const key2=`${r.session_id}\0${r.msg_id}\0${identity}`;const seen=keep.get(key2);if(seen===void 0){keep.set(key2,{session_id:r.session_id,seq:r.seq,content_hash:r.content_hash})}else if(r.seq<seen.seq){drop.push({session_id:seen.session_id,seq:seen.seq,content_hash:seen.content_hash});keep.set(key2,{session_id:r.session_id,seq:r.seq,content_hash:r.content_hash})}else{drop.push({session_id:r.session_id,seq:r.seq,content_hash:r.content_hash})}}const identityBySeq=new Map;for(const r of rows){const raw=rawByIdentityKey.get(`${r.session_id}\0${r.msg_id}\0${identityOfStoredContent(typeof r.content==="string"?r.content:Buffer.from(r.content).toString("utf8"))}`)??(typeof r.content==="string"?r.content:Buffer.from(r.content).toString("utf8"));const identity=identityOfStoredContent(raw);const key2=`${r.session_id}\0${r.msg_id}\0${identity}`;if(keep.get(key2)?.seq===r.seq)identityBySeq.set(`${r.session_id}\0${r.seq}`,identity)}const upd=db.prepare("UPDATE messages SET identity = ? WHERE session_id = ? AND seq = ?");for(const[k2,identity]of identityBySeq){const[sessionId,seqStr]=k2.split("\0");upd.run(identity,sessionId,Number(seqStr))}const decRef=db.prepare("UPDATE content SET refcount = refcount - 1 WHERE hash = ?");const delMedia=db.prepare("DELETE FROM message_media WHERE session_id = ? AND seq = ?");const mediaOf=db.prepare("SELECT media_hash FROM message_media WHERE session_id = ? AND seq = ?");const delMsg=db.prepare("DELETE FROM messages WHERE session_id = ? AND seq = ?");for(const d2 of drop){for(const mm of mediaOf.all(d2.session_id,d2.seq)){decRef.run(mm.media_hash)}delMedia.run(d2.session_id,d2.seq);delMsg.run(d2.session_id,d2.seq);decRef.run(d2.content_hash)}}db.exec(`PRAGMA user_version = ${STORAGE_SCHEMA_VERSION}`)});return{from,to:STORAGE_SCHEMA_VERSION}}var STORAGE_SCHEMA_VERSION,WAL_JOURNAL_SIZE_LIMIT,STORAGE_PRAGMAS,STORAGE_DDL_V1;var init_schema=__esm({"src/storage/schema.ts"(){"use strict";init_identity();STORAGE_SCHEMA_VERSION=8;WAL_JOURNAL_SIZE_LIMIT=8*1024*1024;STORAGE_PRAGMAS=storagePragmas(WAL_JOURNAL_SIZE_LIMIT);STORAGE_DDL_V1=`CREATE TABLE IF NOT EXISTS sessions (
364
+ }`;CACHE_KEEPALIVE_FIELDS=["enabled","ttlFactor","maxDurationMs","maxConcurrentPings","assumeTtl","armWithoutBreakpoints","intervalMs"]}});function parseDurationField(text2){let rest=text2.trim().toLowerCase();if(rest.length===0)return void 0;let total=0;while(rest.length>0){const m3=rest.match(DURATION_SEGMENT_RE);if(!m3)return void 0;total+=Number(m3[1])*DURATION_UNITS_MS[m3[2]];rest=rest.slice(m3[0].length)}return Number.isFinite(total)?Math.floor(total):void 0}var DURATION_UNITS_MS,DURATION_SEGMENT_RE;var init_duration=__esm({"src/duration.ts"(){"use strict";DURATION_UNITS_MS={s:1e3,m:6e4,h:36e5,d:864e5,w:6048e5};DURATION_SEGMENT_RE=/^(\d+(?:\.\d+)?)([smhdw])/}});import{createHash as createHash5}from"crypto";function sha256Hex(bytes){return createHash5("sha256").update(bytes).digest("hex")}function splitMediaContent(content){let media=[];let split=content;if(content.includes('"imageBase64"')){let parsed;try{parsed=JSON.parse(content)}catch{parsed=void 0}if(parsed){const bytes=parsed.imageBase64;if(typeof bytes==="string"&&bytes.length>0){const mediaHash=sha256Hex(bytes);parsed.imageBase64={$media:mediaHash};split=JSON.stringify(parsed);media.push({hash:mediaHash,bytes})}}}if(split.includes(";base64,")){const byHash=new Map(media.map(m3=>[m3.hash,m3.bytes]));split=split.replace(MEDIA_URL_MARKER_RE,(_all,mime,payload)=>{const mediaHash=sha256Hex(payload);if(!byHash.has(mediaHash)){byHash.set(mediaHash,payload);media=[...media,{hash:mediaHash,bytes:payload}]}return`data:${mime};base64,{$media:${mediaHash}}`})}return{content:split,hash:sha256Hex(split),media}}function identityInputOf(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return raw}if(parsed.id===void 0&&parsed.wireIndex===void 0)return raw;delete parsed.id;delete parsed.wireIndex;return JSON.stringify(parsed)}function identityOfStoredContent(content){return sha256Hex(identityInputOf(content))}var MIN_MEDIA_URL_SPLIT_BYTES,MEDIA_URL_MARKER_RE;var init_identity=__esm({"src/storage/identity.ts"(){"use strict";MIN_MEDIA_URL_SPLIT_BYTES=2048;MEDIA_URL_MARKER_RE=new RegExp(`data:([a-zA-Z0-9.+\\/-]+);base64,([A-Za-z0-9+/=]{${MIN_MEDIA_URL_SPLIT_BYTES},})`,"g")}});function storagePragmas(walJournalSizeLimitBytes){return["PRAGMA journal_mode = WAL","PRAGMA synchronous = NORMAL","PRAGMA busy_timeout = 5000","PRAGMA foreign_keys = ON",`PRAGMA journal_size_limit = ${walJournalSizeLimitBytes}`,"PRAGMA auto_vacuum = INCREMENTAL"]}function migrateSchema(db){const row=db.prepare("PRAGMA user_version").get();const from=row?.user_version??0;if(from>=STORAGE_SCHEMA_VERSION)return{from,to:from};let needV8Backfill=false;db.transaction(()=>{if(from<1)db.exec(STORAGE_DDL_V1);if(from<2){const cols=db.prepare("PRAGMA table_info(sessions)").all().map(c=>typeof c?.name==="string"?c.name:"");if(!cols.includes("namespace")){db.exec("ALTER TABLE sessions ADD COLUMN namespace TEXT NOT NULL DEFAULT 'proxy'")}if(!cols.includes("origin")){db.exec("ALTER TABLE sessions ADD COLUMN origin TEXT")}}if(from<3){db.exec("CREATE TABLE IF NOT EXISTS conversations (\n namespace TEXT NOT NULL,\n conversation_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n claimed_at INTEGER NOT NULL,\n PRIMARY KEY (namespace, conversation_id)\n ) WITHOUT ROWID");db.exec("INSERT OR IGNORE INTO conversations (namespace, conversation_id, session_id, claimed_at) SELECT namespace, session_id, session_id, updated_at FROM sessions")}if(from<4){db.exec("CREATE TABLE IF NOT EXISTS session_ext (\n session_id TEXT NOT NULL,\n key TEXT NOT NULL,\n value_json TEXT NOT NULL,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (session_id, key)\n ) WITHOUT ROWID");db.exec("CREATE TABLE IF NOT EXISTS kv_store (\n namespace TEXT NOT NULL,\n key TEXT NOT NULL,\n value_json TEXT NOT NULL,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (namespace, key)\n ) WITHOUT ROWID")}if(from<7){db.exec("CREATE TABLE IF NOT EXISTS message_media (\n session_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n media_hash TEXT NOT NULL REFERENCES content(hash),\n PRIMARY KEY (session_id, seq, media_hash)\n ) WITHOUT ROWID")}if(from<5){const cols=db.prepare("PRAGMA table_info(sessions)").all().map(c=>typeof c?.name==="string"?c.name:"");if(!cols.includes("last_ingested_seq")){db.exec("ALTER TABLE sessions ADD COLUMN last_ingested_seq INTEGER")}}if(from<6){const cols=db.prepare("PRAGMA table_info(sessions)").all().map(c=>typeof c?.name==="string"?c.name:"");if(!cols.includes("orphans_json")){db.exec("ALTER TABLE sessions ADD COLUMN orphans_json TEXT")}}if(from<8){const msgCols=db.prepare("PRAGMA table_info(messages)").all().map(c=>typeof c?.name==="string"?c.name:"");if(!msgCols.includes("identity")){db.exec("ALTER TABLE messages ADD COLUMN identity TEXT NOT NULL DEFAULT ''")}if(!msgCols.includes("retired_at")){db.exec("ALTER TABLE messages ADD COLUMN retired_at INTEGER")}db.exec("CREATE INDEX IF NOT EXISTS idx_messages_identity ON messages (session_id, msg_id, identity)");needV8Backfill=true}});if(needV8Backfill)migrateV8Identities(db);db.exec(`PRAGMA user_version = ${STORAGE_SCHEMA_VERSION}`);return{from,to:STORAGE_SCHEMA_VERSION}}function migrateV8Identities(db){const sessions2=db.prepare("SELECT DISTINCT session_id FROM messages WHERE identity = ''").all();if(sessions2.length===0)return;log("info",`[storage] schema v8 migration: streaming identity backfill over ${sessions2.length} session(s), one transaction per session (resumable \u2014 committed sessions are not reprocessed after a crash)`);const total=sessions2.length;let done=0;const page=db.prepare("SELECT m.seq AS seq, m.msg_id AS msg_id, m.content_hash AS content_hash, c.bytes AS content FROM messages m LEFT JOIN content c ON c.hash = m.content_hash WHERE m.session_id = ? AND m.identity = '' AND m.seq > ? ORDER BY m.seq LIMIT ?");const upd=db.prepare("UPDATE messages SET identity = ? WHERE session_id = ? AND seq = ?");const decRef=db.prepare("UPDATE content SET refcount = refcount - 1 WHERE hash = ?");const delMedia=db.prepare("DELETE FROM message_media WHERE session_id = ? AND seq = ?");const mediaOf=db.prepare("SELECT media_hash FROM message_media WHERE session_id = ? AND seq = ?");const delMsg=db.prepare("DELETE FROM messages WHERE session_id = ? AND seq = ?");try{for(const s3 of sessions2){const keep=new Set;const updates=[];const drops=[];let cursor=-1;for(;;){const rows=page.all(s3.session_id,cursor,V8_BACKFILL_PAGE);if(rows.length===0)break;for(const r of rows){cursor=r.seq;const identity=r.content==null?ABSENT_IDENTITY:identityOfStoredContent(typeof r.content==="string"?r.content:Buffer.from(r.content).toString("utf8"));const key2=`${r.msg_id}\0${identity}`;if(keep.has(key2))drops.push({seq:r.seq,content_hash:r.content_hash});else{keep.add(key2);updates.push({seq:r.seq,identity})}}if(rows.length<V8_BACKFILL_PAGE)break}db.transaction(()=>{for(const u2 of updates)upd.run(u2.identity,s3.session_id,u2.seq);for(const d2 of drops){for(const mm of mediaOf.all(s3.session_id,d2.seq)){decRef.run(mm.media_hash)}delMedia.run(s3.session_id,d2.seq);delMsg.run(s3.session_id,d2.seq);decRef.run(d2.content_hash)}});done+=1;if(done%100===0||done===total){log("info",`[storage] schema v8 migration: ${done}/${total} session(s) backfilled`)}}}catch(err2){log("error",`[storage] schema v8 migration failed after ${done}/${total} session(s) \u2014 committed sessions keep their progress and the migration resumes automatically on the next open (no data loss, no need to touch user_version by hand). Error: ${String(err2)}`);throw err2}}var STORAGE_SCHEMA_VERSION,WAL_JOURNAL_SIZE_LIMIT,STORAGE_PRAGMAS,STORAGE_DDL_V1,ABSENT_IDENTITY,V8_BACKFILL_PAGE;var init_schema=__esm({"src/storage/schema.ts"(){"use strict";init_identity();init_logger();STORAGE_SCHEMA_VERSION=8;WAL_JOURNAL_SIZE_LIMIT=8*1024*1024;STORAGE_PRAGMAS=storagePragmas(WAL_JOURNAL_SIZE_LIMIT);STORAGE_DDL_V1=`CREATE TABLE IF NOT EXISTS sessions (
365
365
  session_id TEXT PRIMARY KEY,
366
366
  parent_session_id TEXT,
367
367
  fork_point_seq INTEGER,
@@ -532,7 +532,7 @@ CREATE INDEX IF NOT EXISTS idx_blocks_session ON blocks(session_id, ord);
532
532
  CREATE INDEX IF NOT EXISTS idx_dead_refs_session ON dead_refs(session_id, ord);
533
533
  CREATE INDEX IF NOT EXISTS idx_refs_session ON refs(session_id, ord);
534
534
  CREATE INDEX IF NOT EXISTS idx_checkpoints_session ON checkpoints(session_id, created_at);
535
- `}});import path6 from"path";function tNum(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0)return Number(envRaw);return typeof fileValue==="number"&&Number.isFinite(fileValue)?fileValue:NaN}function tNumLoose(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0&&envRaw!=="")return Number(envRaw);return typeof fileValue==="number"&&Number.isFinite(fileValue)?fileValue:NaN}function tInt(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0)return Number.parseInt(envRaw,10);return typeof fileValue==="number"&&Number.isFinite(fileValue)?fileValue:NaN}function tIntLoose(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0&&envRaw!=="")return Number.parseInt(envRaw,10);return typeof fileValue==="number"&&Number.isFinite(fileValue)?fileValue:NaN}function staggerKnobMs(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0&&envRaw!=="")return Number(envRaw);if(typeof fileValue==="number"&&Number.isFinite(fileValue))return fileValue;if(typeof fileValue==="string"){const ms2=parseDurationField(fileValue);if(ms2!==void 0)return ms2}return NaN}function fileNetwork(){return loadConfigFile().network??{}}function upstreamTimeoutMs(){const v3=tNum("BILI_UPSTREAM_TIMEOUT_MS",fileNetwork().upstreamTimeoutMs);return Number.isInteger(v3)&&v3>0?v3:UPSTREAM_TIMEOUT_MS}function upstreamCaFile(){const envRaw=process.env["BILI_CA_FILE"];if(envRaw!==void 0&&envRaw!=="")return envRaw;const fileValue=fileNetwork().caFile;return typeof fileValue==="string"&&fileValue!==""?fileValue:void 0}function replayMaxAttempts(){const v3=tNum("BILI_REPLAY_RETRY_MAX",fileNetwork().replayRetryMax);return Number.isInteger(v3)&&v3>=1?v3:REPLAY_MAX_ATTEMPTS}function replayBaseDelayMs(){const v3=tNum("BILI_REPLAY_RETRY_BASE_MS",fileNetwork().replayRetryBaseMs);return Number.isFinite(v3)&&v3>=0?v3:REPLAY_BASE_DELAY_MS}function maxShrinkPerCompress(){const v3=tNum("BILI_MAX_SHRINK_PER_COMPRESS",fileNetwork().maxShrinkPerCompress);return Number.isFinite(v3)&&v3>0&&v3<=1?v3:void 0}function streamKeepAliveMs(){const v3=tNumLoose("BILI_STREAM_KEEPALIVE_MS",fileNetwork().streamKeepAliveMs);return Number.isFinite(v3)&&v3>=0?Math.floor(v3):STREAM_KEEPALIVE_DEFAULT_MS}function preflightHoldGraceMs(){const v3=tNumLoose("BILI_PREFLIGHT_HOLD_MS",fileNetwork().preflightHoldMs);return Number.isFinite(v3)&&v3>=0?Math.floor(v3):PREFLIGHT_HOLD_GRACE_DEFAULT_MS}function proxyKeepAliveMaxMs(){const v3=tNum("BILI_PROXY_KEEPALIVE_MAX_MS",fileNetwork().proxyKeepAliveMaxMs);return Number.isFinite(v3)&&v3<0?PROXY_KEEPALIVE_MAX_MS:v3===0?0:Number.isFinite(v3)&&v3>0?Math.floor(v3):PROXY_KEEPALIVE_MAX_MS}function allowPrivateHttpProviders(){const envRaw=process.env.BILI_ALLOW_PRIVATE_HTTP_PROVIDERS;if(envRaw!==void 0)return envRaw==="1"||envRaw==="true";return fileNetwork().allowPrivateHttpProviders===true}function limitsReceiveBytes(){const v3=tInt("BILI_RECEIVE_BODY_BYTES",loadConfigFile().network?.receiveBodyBytes);return Number.isFinite(v3)&&v3>0?Math.floor(v3):DEFAULT_LIMITS_RECEIVE_BYTES}function limitsDecodedBytes(){const v3=tInt("BILI_DECODED_BODY_BYTES",loadConfigFile().network?.decodedBodyBytes);return Number.isFinite(v3)&&v3>0?Math.floor(v3):DEFAULT_LIMITS_DECODED_BYTES}function limitsOutboundBytes(){const v3=tInt("BILI_OUTBOUND_BODY_BYTES",loadConfigFile().network?.outboundBodyBytes);return Number.isFinite(v3)&&v3>0?Math.floor(v3):DEFAULT_LIMITS_OUTBOUND_BYTES}function limitsWsOutboundBytes(){const v3=tInt("BILI_WS_OUTBOUND_BYTES",loadConfigFile().network?.wsOutboundBytes);return Number.isFinite(v3)&&v3>=0?Math.floor(v3):DEFAULT_WS_OUTBOUND_BYTES}function filePersist(){return loadConfigFile().persist??{}}function persistEnabled(){const envRaw=process.env.BILI_PERSIST;if(envRaw!==void 0)return!(envRaw==="0"||envRaw==="false");return filePersist().enabled!==false}function autoModeForgeEnabled(){const envRaw=process.env.BILI_AUTO_MODE_FORGE;if(envRaw!==void 0)return!(envRaw==="0"||envRaw==="false");return loadConfigFile().autoModeForge?.enabled!==false}function guardrailBashTimeout(){const n=tNumLoose("BILI_GUARDRAIL_BASH_TIMEOUT",loadConfigFile().guardrails?.bashTimeout);if(!Number.isFinite(n))return 60;return n>0?Math.floor(n):void 0}function guardrailMaxOutputBytes(){const n=tNumLoose("BILI_GUARDRAIL_MAX_OUTPUT_BYTES",loadConfigFile().guardrails?.maxOutputBytes);if(!Number.isFinite(n))return 5e4;return n>0?Math.floor(n):void 0}function guardrailRepetition(){const envRaw=process.env.BILI_GUARDRAIL_REPETITION;if(envRaw!==void 0)return!(envRaw==="0"||envRaw==="false");return loadConfigFile().guardrails?.repetition!==false}function guardrailTextRunThreshold(){const n=tNumLoose("BILI_GUARDRAIL_TEXT_RUN_THRESHOLD",loadConfigFile().guardrails?.textRunThreshold);if(!Number.isFinite(n))return DEFAULT_TEXT_RUN_THRESHOLD;return n>0?Math.floor(n):0}function persistZstdEnabled(){const envRaw=process.env.BILI_PERSIST_ZSTD;if(envRaw!==void 0)return envRaw==="1"||envRaw==="true";return filePersist().zstd===true}function persistDebounceMs(){const v3=tInt("BILI_PERSIST_DEBOUNCE_MS",filePersist().debounceMs);return Number.isFinite(v3)&&v3>=0?v3:500}function persistTailTokens(){const v3=tInt("BILI_PERSIST_TAIL_TOKENS",filePersist().tailTokens);return Number.isFinite(v3)&&v3>=0?v3:16384}function persistEpermAlertThreshold(){const v3=tInt("BILI_PERSIST_EPERM_ALERT_THRESHOLD",filePersist().epermAlertThreshold);return Number.isFinite(v3)&&v3>0?v3:5}function persistEpermAlertRepeatMs(){const v3=tInt("BILI_PERSIST_EPERM_ALERT_REPEAT_MS",filePersist().epermAlertRepeatMs);return Number.isFinite(v3)&&v3>=0?v3:0}function maxSessions(){const envRaw=process.env.BILI_MAX_SESSIONS;const v3=envRaw!==void 0?Number.parseInt(envRaw,10):(()=>{const f2=loadConfigFile().sessions?.max;return typeof f2==="number"&&Number.isFinite(f2)?f2:NaN})();return Math.max(1,v3||256)}function sessionWarmMax(){const v3=tInt("BILI_SESSION_WARM_MAX",loadConfigFile().sessions?.warmMax);return Number.isFinite(v3)&&v3>=0?Math.floor(v3):0}function sessionWarmMaxBytes(){const v3=tInt("BILI_SESSION_WARM_MAX_BYTES",loadConfigFile().sessions?.warmMaxBytes);return Number.isFinite(v3)&&v3>=0?Math.floor(v3):64*1024*1024}function sessionResidentMaxBytes(){const v3=tInt("BILI_SESSION_RESIDENT_MAX_BYTES",loadConfigFile().sessions?.residentMaxBytes);return Number.isFinite(v3)&&v3>=0?Math.floor(v3):512*1024*1024}function gcSettings(){const gc=loadConfigFile().sessions?.gc??{};const envRaw=process.env.BILI_SESSION_GC;const enabled=envRaw!==void 0?["1","true","on"].includes(envRaw.toLowerCase()):gc.enabled===true;const ageDays=tIntLoose("BILI_SESSION_GC_MAX_AGE_DAYS",gc.maxAgeDays);const maxTokens=tIntLoose("BILI_SESSION_GC_MAX_TOKENS",gc.maxTokens);const intervalMs=tIntLoose("BILI_SESSION_GC_INTERVAL_MS",gc.intervalMs);return{enabled,maxAgeMs:(Number.isFinite(ageDays)&&ageDays>0?Math.floor(ageDays):7)*GC_DAY_MS,maxTokens:Number.isFinite(maxTokens)&&maxTokens>0?Math.floor(maxTokens):1e6,intervalMs:Number.isFinite(intervalMs)&&intervalMs>0?Math.floor(intervalMs):36e5}}function updateRegistryBase(){const envRaw=process.env.BILI_UPDATE_REGISTRY;if(envRaw!==void 0&&envRaw.trim().length>0)return envRaw.trim();const f2=loadConfigFile().update?.registry;return typeof f2==="string"&&f2.trim().length>0?f2.trim():void 0}function updateCheckIntervalMs(){const v3=tNumLoose("BILI_UPDATE_CHECK_INTERVAL_MS",loadConfigFile().update?.checkIntervalMs);return Number.isFinite(v3)&&v3>0?Math.floor(v3):3*60*1e3}function updatePolicyUrl(){const envRaw=process.env.BILI_UPDATE_POLICY_URL;if(envRaw!==void 0&&envRaw.trim().length>0)return envRaw.trim();const f2=loadConfigFile().update?.policyUrl;return typeof f2==="string"&&f2.trim().length>0?f2.trim():void 0}function updateStaggerMinDelayMs(){const v3=staggerKnobMs("BILI_UPDATE_STAGGER_MIN_MS",loadConfigFile().update?.staggerMinDelayMs);return Number.isInteger(v3)&&v3>=0?Math.floor(v3):void 0}function updateStaggerMaxDelayMs(){const v3=staggerKnobMs("BILI_UPDATE_STAGGER_MAX_MS",loadConfigFile().update?.staggerMaxDelayMs);return Number.isInteger(v3)&&v3>=0?Math.floor(v3):void 0}function publicSnapshotCapBytes(){const raw=process.env.BILI_PUBLIC_SNAPSHOT_CAP_BYTES;const v3=raw!==void 0?Number(raw):(()=>{const f2=loadConfigFile().plugin?.snapshotCapBytes;return typeof f2==="number"&&Number.isFinite(f2)?f2:NaN})();return Number.isFinite(v3)&&v3>=0?v3:104857600}function ccrRetrievalTtlMs(){const envRaw=process.env.BILI_CCR_RETRIEVAL_TTL_MS;const v3=envRaw===void 0||envRaw===""?(()=>{const f2=loadConfigFile().ccrRetrievalTtlMs;return typeof f2==="number"?f2:NaN})():Number(envRaw);return Number.isFinite(v3)&&v3>=0?v3:10*60*1e3}function codexCompactMode(){const envRaw=process.env.BILI_CODEX_COMPACT;if(envRaw!==void 0)return envRaw.trim().toLowerCase()==="pass"?"pass":"intercept";return loadConfigFile().codexCompact==="pass"?"pass":"intercept"}function dshAuthoredCompactionEnabled(){const envRaw=process.env.BILI_DSH_AUTHORED_COMPACTION;if(envRaw!==void 0)return envRaw.trim()!=="0";const file=loadConfigFile().dsh?.authoredCompaction;if(typeof file==="boolean")return file;return true}function decompressTmpCap(){const v3=tIntLoose("BILI_DECOMPRESS_TMP_CAP",loadConfigFile().decompressTmpCap);return Number.isFinite(v3)&&v3>0?v3:50}function imageRescaleEnabled(){const envRaw=process.env.BILI_IMAGE_RESCALE;if(envRaw!==void 0)return!(envRaw==="0"||envRaw==="false");return loadConfigFile().imageRescale!==false}function imageRescaleMaxDim(){const v3=tIntLoose("BILI_IMAGE_RESCALE_MAX_DIM",void 0);return Number.isInteger(v3)&&v3>=128?v3:IMAGE_RESCALE_DEFAULT_MAX_DIM}function fileDiag(){return loadConfigFile().diagnostics??{}}function bodyDumpEnabled(){const envRaw=process.env.ACP_DUMP_BODY;if(envRaw!==void 0)return envRaw==="1";return fileDiag().dumpBody===true}function dumpReqAllowed(){const envRaw=process.env.ACP_DUMP_REQ;if(envRaw!==void 0)return envRaw!=="0";return fileDiag().dumpReq!==false}function rawDumpDir(){const envRaw=process.env.ACP_RAW_DUMP_DIR;if(envRaw)return envRaw;const f2=fileDiag().rawDumpDir;if(typeof f2==="string"&&f2.trim().length>0)return f2;return path6.join(stateDir(),"raw")}function dump4xxEnabled(){const envRaw=process.env.BILI_DUMP_4XX;if(envRaw!==void 0)return envRaw==="1";return fileDiag().dump4xx===true}function dump4xxMaxBytes(){const envRaw=process.env.BILI_DUMP_4XX_MAX_BYTES;if(envRaw!==void 0)return Math.max(1024,Number(envRaw)||2*1024*1024);const f2=fileDiag().dump4xxMaxBytes;const n=typeof f2==="number"&&Number.isFinite(f2)&&f2>0?f2:NaN;return Math.max(1024,n||2*1024*1024)}function dumpGcMaxTotalBytes(){const envRaw=process.env.BILI_DUMP_MAX_TOTAL_BYTES;if(envRaw!==void 0){const v3=Number(envRaw);return Number.isFinite(v3)&&v3>0?Math.max(1<<20,v3):null}const f2=fileDiag().maxTotalBytes;if(typeof f2==="number"&&Number.isFinite(f2)&&f2>0)return Math.max(1<<20,f2);return null}function dumpGcMaxAgeMs(){const envRaw=process.env.BILI_DUMP_MAX_AGE_DAYS;if(envRaw!==void 0){const d2=Number(envRaw);return Number.isFinite(d2)&&d2>0?Math.max(1/24,d2)*864e5:null}const f2=fileDiag().maxAgeDays;if(typeof f2==="number"&&Number.isFinite(f2)&&f2>0)return Math.max(1/24,f2)*864e5;return null}function renderNone(){const envRaw=process.env.ACP_RENDER_NONE;if(envRaw!==void 0)return envRaw.length>0;return fileDiag().renderNone===true}function invariantJudgeEnabled(){const envRaw=process.env.BILI_INVARIANT_JUDGE;if(envRaw!==void 0)return!(envRaw==="0"||envRaw==="false"||envRaw==="off");const f2=fileDiag().invariantJudge;return typeof f2==="boolean"?f2:true}function noInjectTool(){const envRaw=process.env.ACP_NO_INJECT_TOOL;if(envRaw!==void 0)return envRaw.length>0;return fileDiag().noInjectTool===true}function noCompressPrompt(){const envRaw=process.env.ACP_NO_COMPRESS_PROMPT;if(envRaw!==void 0)return envRaw.length>0;return fileDiag().noCompressPrompt===true}function countTokensPassthrough(){const envRaw=process.env.ACP_COUNT_TOKENS_PASSTHROUGH;if(envRaw!==void 0)return envRaw==="1";return fileDiag().countTokensPassthrough===true}function forceTextProtocol(){const envRaw=process.env.ACP_COMPRESS_PROTOCOL;if(envRaw!==void 0)return envRaw==="text";return fileDiag().compressProtocol==="text"}function keepResponseId(){const envRaw=process.env.ACP_KEEP_RESPONSE_ID;if(envRaw!==void 0)return envRaw==="1";return loadConfigFile().compat?.keepResponseId===true}function noCacheControl(){const envRaw=process.env.BILI_NO_CACHE_CONTROL;if(envRaw!==void 0)return envRaw.length>0;return loadConfigFile().compat?.noCacheControl===true}function fakeCompletionRetries(){const v3=tInt("BILI_FAKE_COMPLETION_RETRIES",loadConfigFile().fakeCompletion?.retries);return Number.isFinite(v3)&&v3>=0?v3:0}function fakeBufCapBytes(){const v3=tInt("BILI_FAKE_BUF_CAP",loadConfigFile().fakeCompletion?.bufCapBytes);return Number.isFinite(v3)&&v3>0?v3:16*1024*1024}function fileStorageUnified(){const v3=loadConfigFile().storage?.unified;return typeof v3==="string"?v3:void 0}function fileStorageJsonWriter(){const v3=loadConfigFile().storage?.jsonWriter;return typeof v3==="string"?v3:void 0}function fileStorageAutoDownload(){const v3=loadConfigFile().storage?.sqliteAutoDownload;return typeof v3==="boolean"?v3:void 0}function fileStorageArchiveAfterDays(){const v3=loadConfigFile().storage?.archiveAfterDays;return typeof v3==="number"&&Number.isFinite(v3)&&v3>=0?v3:void 0}function fileStorageBackend(){const v3=loadConfigFile().storage?.backend;return typeof v3==="string"?v3:void 0}function fileStorageMysqlDsn(){const v3=loadConfigFile().storage?.mysql?.dsn;return typeof v3==="string"&&v3.trim().length>0?v3:void 0}function fileStorageWalJournalSizeLimit(){const v3=loadConfigFile().storage?.walJournalSizeLimitBytes;return typeof v3==="number"&&Number.isInteger(v3)&&v3>0?v3:void 0}function resolveArchiveAfterDays(env=process.env,fileDays){const raw=env.BILI_STORAGE_ARCHIVE_AFTER_DAYS?.trim();if(raw!==void 0&&raw!==""){const n=Number.parseInt(raw,10);if(Number.isFinite(n)&&n>=0)return n}if(typeof fileDays==="number"&&Number.isFinite(fileDays)&&fileDays>=0)return fileDays;return 365}function resolveStorageMode(env=process.env,fileUnified){const raw=env.BILI_STORAGE_UNIFIED?.trim().toLowerCase();if(raw){if(raw==="full"||raw==="unified")return"full";if(raw==="1"||raw==="true"||raw==="shadow")return"shadow";return"legacy"}const file=fileUnified?.trim().toLowerCase();if(file==="full")return"full";if(file==="shadow")return"shadow";if(file)return"legacy";return"full"}function resolveJsonWriterOff(env=process.env,fileValue){const raw=env.BILI_STORAGE_JSON_WRITER?.trim().toLowerCase();if(raw==="0"||raw==="false"||raw==="off")return true;if(raw==="1"||raw==="true"||raw==="on")return false;return fileValue?.trim().toLowerCase()==="off"}function resolveSnapshotShadow(env=process.env,fileShadow){const raw=env.BILI_SNAPSHOT_SHADOW?.trim().toLowerCase();if(raw==="1"||raw==="true"||raw==="on")return true;if(raw==="0"||raw==="false"||raw==="off")return false;return typeof fileShadow==="boolean"?fileShadow:true}function resolveSqliteAutoDownload(env=process.env,fileValue){const raw=env.BILI_SQLITE_AUTO_DOWNLOAD?.trim().toLowerCase();if(raw==="1"||raw==="true")return true;if(raw==="0"||raw==="false")return false;return typeof fileValue==="boolean"?fileValue:true}function resolveStorageWalJournalSizeLimit(env=process.env,fileValue){const raw=env.BILI_STORAGE_WAL_JOURNAL_SIZE_LIMIT_BYTES?.trim();if(raw){const n=Number(raw);if(Number.isInteger(n)&&n>0)return n}if(typeof fileValue==="number"&&Number.isInteger(fileValue)&&fileValue>0)return fileValue;return WAL_JOURNAL_SIZE_LIMIT}var STREAM_KEEPALIVE_DEFAULT_MS,PREFLIGHT_HOLD_GRACE_DEFAULT_MS,DEFAULT_LIMITS_RECEIVE_BYTES,DEFAULT_LIMITS_DECODED_BYTES,DEFAULT_LIMITS_OUTBOUND_BYTES,DEFAULT_WS_OUTBOUND_BYTES,DEFAULT_TEXT_RUN_THRESHOLD,GC_DAY_MS,IMAGE_RESCALE_DEFAULT_MAX_DIM;var init_knobs=__esm({"src/knobs.ts"(){"use strict";init_paths();init_config();init_duration();init_fetch_util();init_upstream_proxy();init_schema();STREAM_KEEPALIVE_DEFAULT_MS=15e3;PREFLIGHT_HOLD_GRACE_DEFAULT_MS=3e4;DEFAULT_LIMITS_RECEIVE_BYTES=5*1024*1024*1024;DEFAULT_LIMITS_DECODED_BYTES=10*1024*1024*1024;DEFAULT_LIMITS_OUTBOUND_BYTES=5*1024*1024*1024;DEFAULT_WS_OUTBOUND_BYTES=10*1024*1024;DEFAULT_TEXT_RUN_THRESHOLD=200;GC_DAY_MS=864e5;IMAGE_RESCALE_DEFAULT_MAX_DIM=1600}});import{readFileSync as readFileSync4,statSync as statSync2}from"fs";import*as tls2 from"tls";function readPem(path54){try{return[readFileSync4(path54,"utf8")]}catch(err2){log("warn",`[upstream-ca] CA file ${path54} unreadable (${err2.message}); ignoring \u2014 upstream TLS falls back to whatever else is trusted`);return[]}}function upstreamCaIdentity(now=Date.now()){const caFile=upstreamCaFile();if(!caFile){lastIdentity="none";return"none"}if(now-lastStatAt<IDENTITY_TTL_MS&&lastIdentity!=="none")return lastIdentity;let mtimeMs=0;try{mtimeMs=statSync2(caFile).mtimeMs}catch{}lastIdentity=`${caFile}\0${mtimeMs}`;lastStatAt=now;return lastIdentity}function upstreamExtraCa(){const identity=upstreamCaIdentity();if(identity==="none")return void 0;if(cacheKey===identity)return cacheValue;const merged=[...tls2.rootCertificates];const nodeExtra=process.env["NODE_EXTRA_CA_CERTS"];if(nodeExtra)merged.push(...readPem(nodeExtra));const caFile=upstreamCaFile();if(caFile)merged.push(...readPem(caFile));cacheKey=identity;cacheValue=merged;log("info",`[upstream-ca] upstream TLS trust extended with ${caFile} (${merged.length} certs total)`);return merged}var IDENTITY_TTL_MS,lastStatAt,lastIdentity,cacheKey,cacheValue;var init_upstream_ca=__esm({"src/upstream-ca.ts"(){"use strict";init_logger();init_knobs();IDENTITY_TTL_MS=3e4;lastStatAt=0;lastIdentity="none";cacheKey=null}});function checkOutboundBody(body){const bytes=typeof body==="string"?Buffer.byteLength(body):Buffer.isBuffer(body)?body.byteLength:0;if(bytes>limitsOutboundBytes())throw new OutboundBodyTooLargeError(bytes)}var MAX_REQUEST_BYTES,MAX_DECODED_REQUEST_BYTES,MAX_LARGE_DECODED_REQUESTS,largeDecodedRequests,DecodedRequestBusyError,DecodedRequestAdmission,OutboundBodyTooLargeError;var init_request_body_budget=__esm({"src/request-body-budget.ts"(){"use strict";init_knobs();MAX_REQUEST_BYTES=100*1024*1024;MAX_DECODED_REQUEST_BYTES=2*MAX_REQUEST_BYTES;MAX_LARGE_DECODED_REQUESTS=2;largeDecodedRequests=0;DecodedRequestBusyError=class extends Error{constructor(){super("large decoded request budget is busy; retry after an active request finishes");this.name="DecodedRequestBusyError"}};DecodedRequestAdmission=class{admitted=false;observe(bytes){if(bytes<=limitsReceiveBytes()||this.admitted)return;if(largeDecodedRequests>=MAX_LARGE_DECODED_REQUESTS)throw new DecodedRequestBusyError;largeDecodedRequests++;this.admitted=true}release(){if(!this.admitted)return;largeDecodedRequests--;this.admitted=false}};OutboundBodyTooLargeError=class extends Error{constructor(bytes){super(`rebuilt request exceeds ${limitsOutboundBytes()} bytes (${bytes} bytes); reduce historical images or content before retrying`);this.bytes=bytes;this.name="OutboundBodyTooLargeError"}bytes}}});function upstreamTimeoutMs2(){return upstreamTimeoutMs()}function directDispatcher(timeoutMs){const key2=`${timeoutMs}\0${upstreamCaIdentity()}`;let agent=directDispatchers.get(key2);if(!agent){const ca=upstreamExtraCa();agent=new import_undici.Agent({headersTimeout:timeoutMs,bodyTimeout:timeoutMs,...ca?{connect:{ca}}:{}});directDispatchers.set(key2,agent)}return agent}function restrictAcceptEncoding(headers){if(!headers)return headers;const entries2=[];if(typeof Headers!=="undefined"&&headers instanceof Headers){headers.forEach((v3,k2)=>entries2.push([k2,v3]))}else if(Array.isArray(headers)){for(const pair of headers)entries2.push([pair[0],String(pair[1])])}else{for(const[k2,v3]of Object.entries(headers))entries2.push([k2,String(v3)])}const out={};for(const[k2,v3]of entries2){if(k2.toLowerCase()!=="accept-encoding"){out[k2]=v3;continue}const kept=v3.split(",").map(part=>part.trim()).filter(part=>part!=="").filter(part=>DECODABLE_ENCODINGS.has(part.split(";")[0].trim().toLowerCase()));if(kept.length>0)out["accept-encoding"]=kept.join(", ")}return out}async function fetchWithTimeout(url,opts,timeoutMs,externalSignal,forceDirect){checkOutboundBody(opts.body);const effective=timeoutMs??upstreamTimeoutMs2();const controller=new AbortController;let cleared=false;const armTimer=()=>{const t=setTimeout(()=>{liveUpstreamTimers.delete(t);controller.abort()},idleTimerDelayOverrideMs??effective);liveUpstreamTimers.add(t);return t};let timer4=armTimer();const rearm=()=>{if(cleared)return;clearTimeout(timer4);liveUpstreamTimers.delete(timer4);idleRearmCount+=1;timer4=armTimer()};let onExternalAbort=null;if(externalSignal){if(externalSignal.aborted)controller.abort();else{onExternalAbort=()=>controller.abort();externalSignal.addEventListener("abort",onExternalAbort,{once:true})}}const stopIdleTimer=()=>{cleared=true;clearTimeout(timer4);liveUpstreamTimers.delete(timer4)};const cleanup=()=>{stopIdleTimer();if(onExternalAbort&&externalSignal)externalSignal.removeEventListener("abort",onExternalAbort)};try{const finalOpts={...opts,signal:controller.signal,dispatcher:opts.dispatcher??directDispatcher(idleTimerDelayOverrideMs??effective),redirect:opts.redirect??"manual",headers:restrictAcceptEncoding(opts.headers)};const transport=forceDirect?void 0:currentFetchTransport();const raw=transport?await transport(url,finalOpts):await fetch(url,finalOpts);if(raw.body){const wrapped=armIdleBody(raw.body,rearm);return{response:new Response(wrapped,{status:raw.status,statusText:raw.statusText,headers:raw.headers}),clearTimer:cleanup,stopIdleTimer}}return{response:raw,clearTimer:cleanup,stopIdleTimer}}catch(e){cleanup();throw e}}function armIdleBody(body,rearm){const reader=body.getReader();return new ReadableStream({async pull(controller){try{const result=await reader.read();if(result.done){controller.close();return}rearm();controller.enqueue(result.value)}catch(e){controller.error(e)}},async cancel(reason){try{await reader.cancel(reason)}catch{}}})}function isTransientUpstreamError(status,body){if(status===429||status>=500)return true;if(status<400)return false;const lower=body.toLowerCase();return TRANSIENT_BODY_MARKERS.some(marker=>lower.includes(marker))}function replayMaxAttempts2(){return replayMaxAttempts()}function replayBaseDelayMs2(){return replayBaseDelayMs()}function maxShrinkPerCompress2(){return maxShrinkPerCompress()}function replayBackoffMs(attempt){return replayBaseDelayMs2()*2**(attempt-1)}function sleep(ms2,signal){if(ms2<=0||signal?.aborted)return Promise.resolve();return new Promise(resolve=>{let timer4=null;const finish2=()=>{if(timer4)clearTimeout(timer4);if(signal)signal.removeEventListener("abort",finish2);resolve()};timer4=setTimeout(finish2,ms2);if(signal)signal.addEventListener("abort",finish2,{once:true})})}async function fetchWithRetry(url,opts,timeoutMs,externalSignal,onRetry){const maxAttempts=replayMaxAttempts2();for(let attempt=1;;attempt++){let result;try{result=await fetchWithTimeout(url,opts,timeoutMs,externalSignal)}catch(error){const kind=classifyUpstreamFailure(error,{viaProxy:opts.dispatcher!==void 0,externalAborted:externalSignal?.aborted===true});if(!isFailFastUpstreamKind(kind))throw error;const lastAttempt2=attempt>=maxAttempts;if(lastAttempt2)throw error;const delayMs=replayBackoffMs(attempt);onRetry?.({attempt,status:0,detail:`${kind} (pre-response network failure): ${error instanceof Error?error.message:String(error)}`,delayMs,maxAttempts});await sleep(delayMs,externalSignal);continue}if(result.response.ok)return result;const errText2=await result.response.text().catch(()=>"upstream error");result.clearTimer();const lastAttempt=attempt>=maxAttempts;if(!lastAttempt&&isTransientUpstreamError(result.response.status,errText2)){const delayMs=replayBackoffMs(attempt);onRetry?.({attempt,status:result.response.status,detail:errText2,delayMs,maxAttempts});await sleep(delayMs,externalSignal);continue}throw new UpstreamHttpError(result.response.status,errText2,attempt)}}async function fetchWithTransportRetry(url,opts,timeoutMs,externalSignal,onRetry){const maxAttempts=replayMaxAttempts2();for(let attempt=1;;attempt++){try{return await fetchWithTimeout(url,opts,timeoutMs,externalSignal)}catch(error){const kind=classifyUpstreamFailure(error,{viaProxy:opts.dispatcher!==void 0,externalAborted:externalSignal?.aborted===true});if(!isFailFastUpstreamKind(kind))throw error;const lastAttempt=attempt>=maxAttempts;if(lastAttempt)throw error;const delayMs=replayBackoffMs(attempt);onRetry?.({attempt,status:0,detail:`${kind} (pre-response network failure): ${error instanceof Error?error.message:String(error)}`,delayMs,maxAttempts});await sleep(delayMs,externalSignal)}}}var import_undici,UPSTREAM_TIMEOUT_MS,liveUpstreamTimers,idleTimerDelayOverrideMs,idleRearmCount,directDispatchers,DECODABLE_ENCODINGS,UpstreamHttpError,TRANSIENT_BODY_MARKERS,REPLAY_MAX_ATTEMPTS,REPLAY_BASE_DELAY_MS;var init_fetch_util=__esm({"src/fetch-util.ts"(){"use strict";import_undici=__toESM(require_undici(),1);init_fetch_transport();init_upstream_fail();init_upstream_ca();init_knobs();init_request_body_budget();init_request_body_budget();UPSTREAM_TIMEOUT_MS=12*60*1e3;liveUpstreamTimers=new Set;idleTimerDelayOverrideMs=null;idleRearmCount=0;directDispatchers=new Map;DECODABLE_ENCODINGS=new Set(["gzip","x-gzip","deflate","br"]);UpstreamHttpError=class extends Error{status;body;attempts;constructor(status,body,attempts){super(`upstream error ${status}`);this.name="UpstreamHttpError";this.status=status;this.body=body;this.attempts=attempts}};TRANSIENT_BODY_MARKERS=["captcha","verify failed","risk control","\u98CE\u63A7","rate limit","too many requests","try again"];REPLAY_MAX_ATTEMPTS=3;REPLAY_BASE_DELAY_MS=1500}});import{execFileSync as execFileSync3}from"child_process";import net from"net";import tls3 from"tls";function defaultPort(protocol){return protocol==="https:"?443:80}function hostIsLoopback(host){const normalized=host.replace(/^\[|\]$/g,"").toLowerCase();return normalized==="localhost"||normalized==="0.0.0.0"||normalized==="::"||normalized==="::1"||normalized==="0:0:0:0:0:0:0:1"||normalized.startsWith("127.")||normalized.startsWith("::ffff:127.")||/^::ffff:7f[0-9a-f]{2}:/.test(normalized)}function proxyAuthorization(url){if(!url.username&&!url.password)return void 0;const username=decodeURIComponent(url.username);const password=decodeURIComponent(url.password);return`Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`}function parseHttpProxy(proxy,biliPort){if(!proxy||typeof proxy!=="string"||!proxy.trim())return void 0;const candidate=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(proxy.trim())?proxy.trim():`http://${proxy.trim()}`;let url;try{url=new URL(candidate)}catch{return void 0}if(url.protocol!=="http:"&&url.protocol!=="https:")return void 0;if(url.pathname&&url.pathname!=="/"||url.search||url.hash)return void 0;const port=url.port?Number.parseInt(url.port,10):defaultPort(url.protocol);if(!Number.isInteger(port)||port<1||port>65535)return void 0;if(biliPort&&hostIsLoopback(url.hostname)&&port===biliPort){throw new Error(`upstream proxy would loop back into bili: ${redactProxyUrl(url.href)}`)}return{url:url.href,host:url.hostname,port,protocol:url.protocol,...proxyAuthorization(url)?{authorization:proxyAuthorization(url)}:{}}}function unsupportedProxyScheme(proxy){if(!proxy||typeof proxy!=="string"||!proxy.trim())return void 0;const candidate=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(proxy.trim())?proxy.trim():`http://${proxy.trim()}`;let url;try{url=new URL(candidate)}catch{return void 0}return url.protocol==="http:"||url.protocol==="https:"?void 0:url.protocol.replace(/:$/,"")}function warnUnsupportedScheme(source,value,scheme){const key2=`${source}\0${scheme}`;if(warnedUnsupportedSchemes.has(key2))return;warnedUnsupportedSchemes.add(key2);log("warn",`[upstream-proxy] ignoring ${source}=${redactProxyUrl(value)}: scheme "${scheme}" is not supported \u2014 only http:// and https:// proxy origins work. For Clash/mihomo, point bili at the same mixed port over http:// (e.g. http://127.0.0.1:7890).`)}function validateHttpProxy(proxy,biliPort){if(!proxy?.trim())return;const scheme=unsupportedProxyScheme(proxy);if(scheme){throw new Error(`upstream proxy uses unsupported scheme "${scheme}" (${redactProxyUrl(proxy)}) \u2014 only http:// and https:// proxies are supported; for Clash/mihomo use the same mixed port over http:// (e.g. http://127.0.0.1:7890)`)}if(!parseHttpProxy(proxy,biliPort)){throw new Error(`upstream proxy must be an HTTP/HTTPS proxy origin: ${redactProxyUrl(proxy)}`)}}function targetUrl(upstreamUrl){if(!upstreamUrl)return void 0;try{return new URL(upstreamUrl.replace(/^mitm:\/\//,"https://"))}catch{return void 0}}function parseFallbackProxy(proxy,biliPort){try{return parseHttpProxy(proxy,biliPort)}catch{return void 0}}function wildcardHostMatch(host,token){const pattern="^"+token.split("*").map(part=>part.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*")+"$";return new RegExp(pattern).test(host)}function matchesNoProxy(target,noProxy,options={}){if(!noProxy)return false;const host=target.hostname.replace(/^\[|\]$/g,"").toLowerCase();const port=target.port?Number.parseInt(target.port,10):defaultPort(target.protocol);for(const raw of noProxy.split(/[;,]/)){let token=raw.trim().toLowerCase();if(!token)continue;if(token==="*")return true;if(token==="<local>"&&!host.includes("."))return true;let tokenPort;if(token.startsWith("[")){const bracket=token.indexOf("]");if(bracket>0&&token[bracket+1]===":"){tokenPort=Number.parseInt(token.slice(bracket+2),10);token=token.slice(1,bracket)}else token=token.replace(/^\[|\]$/g,"")}else{const colon=token.lastIndexOf(":");if(colon>0&&token.indexOf(":")===colon&&/^\d+$/.test(token.slice(colon+1))){tokenPort=Number.parseInt(token.slice(colon+1),10);token=token.slice(0,colon)}}if(tokenPort!==void 0&&tokenPort!==port)continue;if(options.windowsBypass&&!token.startsWith("*")&&token.includes("*")&&wildcardHostMatch(host,token))return true;const suffix=token.startsWith("*.")?token.slice(1):token.startsWith(".")?token:void 0;if(suffix?host.endsWith(suffix)||host===suffix.slice(1):host===token)return true}return false}function parseWindowsProxyServer(value){const trimmed=value.trim();if(!trimmed)return{};if(!trimmed.includes("=")){const normalized=parseHttpProxy(trimmed)?.url;return normalized?{http:normalized,https:normalized}:{}}const result={};for(const item of trimmed.split(";")){const[scheme,address]=item.split("=",2).map(part=>part?.trim());const normalizedScheme=scheme?.toLowerCase();if((normalizedScheme==="http"||normalizedScheme==="https")&&address){const normalized=parseHttpProxy(address)?.url;if(normalized)result[normalizedScheme]=normalized}}return result}function registryValue(output,name){const escaped=name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return output.match(new RegExp(`^\\s*${escaped}\\s+REG_\\w+\\s+(.+)$`,"mi"))?.[1]?.trim()}function readWindowsSystemProxy(){if(process.platform!=="win32")return{enabled:false};const now=Date.now();if(windowsProxyCache&&now-windowsProxyCache.at<5e3)return windowsProxyCache.value;let value={enabled:false};try{const output=execFileSync3("reg",["query","HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"],{encoding:"utf8",windowsHide:true,timeout:3e3,stdio:["ignore","pipe","ignore"]});const enabledRaw=registryValue(output,"ProxyEnable");const enabled=enabledRaw==="0x1"||enabledRaw==="1";const staticProxy=enabled?parseWindowsProxyServer(registryValue(output,"ProxyServer")??""):{};value={enabled,...staticProxy,...registryValue(output,"ProxyOverride")?{bypass:registryValue(output,"ProxyOverride")}:{},...registryValue(output,"AutoConfigURL")?{autoConfigUrl:registryValue(output,"AutoConfigURL")}:{}}}catch{}windowsProxyCache={at:now,value};return value}function resolveProxyDecision(routes,globalProxy,upstreamUrl,fallback={}){const target=targetUrl(upstreamUrl);let bestKey="";if(upstreamUrl){for(const key2 of Object.keys(routes)){if(upstreamUrl===key2||upstreamUrl.startsWith(key2+"/")){if(key2.length>bestKey.length)bestKey=key2}}}if(bestKey){const routeProxy=routes[bestKey].proxy;if(routeProxy!==void 0){if(!routeProxy.trim())return{source:"provider-direct"};const parsed=parseHttpProxy(routeProxy,fallback.biliPort);if(!parsed)throw new Error(`invalid per-URL upstream proxy for ${bestKey}: ${redactProxyUrl(routeProxy)}`);return{proxy:parsed.url,source:"provider"}}}if(globalProxy===""&&fallback.explicitDirect){if(!fallback.defaultDirect)return{source:"direct"};const peek=autoDetectProxy(target,fallback);return peek.proxy?{source:"direct",skippedProxy:{proxy:peek.proxy,source:peek.source}}:{source:"direct"}}const explicit=parseHttpProxy(globalProxy,fallback.biliPort)?.url;if(explicit)return{proxy:explicit,source:fallback.globalSource??"global"};return autoDetectProxy(target,fallback)}function autoDetectProxy(target,fallback){if(target&&matchesNoProxy(target,fallback.noProxy))return{source:"no-proxy"};const environmentCandidates=target?.protocol==="http:"?[["HTTP_PROXY",fallback.httpProxy],["ALL_PROXY",fallback.allProxy]]:[["HTTPS_PROXY",fallback.httpsProxy],["HTTP_PROXY",fallback.httpProxy],["ALL_PROXY",fallback.allProxy]];for(const[source,value]of environmentCandidates){const parsed=parseFallbackProxy(value,fallback.biliPort);if(parsed)return{proxy:parsed.url,source};if(!value)continue;const scheme=unsupportedProxyScheme(value);if(scheme)warnUnsupportedScheme(source,value,scheme)}const system=fallback.systemProxy??readWindowsSystemProxy();if(target&&matchesNoProxy(target,system.bypass,{windowsBypass:true})){return{source:"windows-bypass",...system.autoConfigUrl?{autoConfigUrl:system.autoConfigUrl}:{}}}const systemValue=target?.protocol==="http:"?system.http:system.https??system.http;const systemScheme=unsupportedProxyScheme(systemValue);if(systemValue&&systemScheme)warnUnsupportedScheme("windows-system",systemValue,systemScheme);const systemProxy=parseFallbackProxy(systemValue,fallback.biliPort)?.url;if(systemProxy){return{proxy:systemProxy,source:"windows-system",...system.autoConfigUrl?{autoConfigUrl:system.autoConfigUrl}:{}}}return{source:"direct",...system.autoConfigUrl?{autoConfigUrl:system.autoConfigUrl}:{}}}function resolveProxy(routes,globalProxy,upstreamUrl,fallback={}){return resolveProxyDecision(routes,globalProxy,upstreamUrl,fallback).proxy}function proxyKeepAliveMaxMs2(){return proxyKeepAliveMaxMs()}function proxyDispatcher(proxyUrl,timeoutMs){if(!proxyUrl)return void 0;const t=timeoutMs??upstreamTimeoutMs2();const ka=proxyKeepAliveMaxMs2();const key2=`${proxyUrl}\0${t}\0${ka}\0${upstreamCaIdentity()}`;let agent=dispatcherCache.get(key2);if(!agent){const withTimeouts=options=>{const capped={...options,headersTimeout:t,bodyTimeout:t};if(ka>0){capped.keepAliveTimeout=Math.min(typeof capped.keepAliveTimeout==="number"?capped.keepAliveTimeout:ka,ka);capped.keepAliveMaxTimeout=ka}return capped};const base={uri:proxyUrl,headersTimeout:t,bodyTimeout:t,factory:(origin,options)=>new import_undici2.Pool(origin,withTimeouts(options)),clientFactory:(origin,options)=>new import_undici2.Pool(origin,withTimeouts(options))};const ca=upstreamExtraCa();const withConnect=ca?{...base,connect:{ca}}:base;agent=ka>0?new import_undici2.ProxyAgent({...withConnect,keepAliveTimeout:ka,keepAliveMaxTimeout:ka}):new import_undici2.ProxyAgent(withConnect);dispatcherCache.set(key2,agent)}return agent}function resetProxyCache(){for(const agent of dispatcherCache.values()){try{void agent.close().catch(()=>void 0)}catch{}}dispatcherCache.clear();lastConnection={}}function errorChain(error){const chain=[];const seen=new Set;let current=error;while(current&&!seen.has(current)){seen.add(current);if(current instanceof Error){const record3={message:current.message};for(const key2 of["code","errno","syscall","address","port"]){const value=current[key2];if(value!==void 0)record3[key2]=value}chain.push(record3);current=current.cause}else{chain.push({message:String(current)});break}}return chain}function describeUpstreamFailure(error,url,proxyUrl,skipped){const chain=errorChain(error);const kind=classifyUpstreamFailure(error,{viaProxy:proxyUrl!==void 0});const fields=["code","errno","syscall","address","port"];const parts=[`kind=${kind}`];const maskHostIn=s3=>{try{return maskHostInText(s3,new URL(url).hostname)}catch{}return s3};let codeValue;for(const field of fields){const value=chain.find(entry=>entry[field]!==void 0)?.[field];if(value!==void 0){if(field==="code"&&codeValue===void 0)codeValue=value;parts.push(`${field}=${maskHostIn(String(value))}`)}}const messages=chain.map(entry=>maskHostIn(String(entry.message??""))).filter(Boolean);if(messages.length>0)parts.push(`message=${messages.join(" <- ")}`);parts.push(`url=${maskUrlForLog(url)}`);parts.push(`proxy=${redactProxyUrl(proxyUrl)??"direct"}`);let hint=hintWithSkippedProxy(kind,skipped);if(kind==="tls"&&chain.some(entry=>isTlsTrustCode(entry.code))){hint=`${hint}; ${tlsTrustRemediation()}`}parts.push(`hint=${hint}`);return{message:parts.join(" "),detail:{kind,...codeValue!==void 0?{code:String(codeValue)}:{},hint}}}function formatUpstreamError(error,url,proxyUrl,skipped){return describeUpstreamFailure(error,url,proxyUrl,skipped).message}function recordUpstreamConnection(url,proxyUrl,error,skipped){lastConnection={url,proxy:redactProxyUrl(proxyUrl),connected:error===void 0,...error===void 0?{}:{error:formatUpstreamError(error,url,proxyUrl,skipped)},checkedAt:new Date().toISOString()}}function getUpstreamConnectionStatus(){return{...lastConnection}}var import_undici2,dispatcherCache,lastConnection,windowsProxyCache,warnedUnsupportedSchemes,PROXY_KEEPALIVE_MAX_MS;var init_upstream_proxy=__esm({"src/upstream-proxy.ts"(){"use strict";import_undici2=__toESM(require_undici(),1);init_logger();init_log_mask();init_fetch_util();init_upstream_fail();init_upstream_ca();init_knobs();dispatcherCache=new Map;lastConnection={};warnedUnsupportedSchemes=new Set;PROXY_KEEPALIVE_MAX_MS=55e3}});function normalizeVertexModelId(id){const trimmed=id.trim();const at2=trimmed.indexOf("@");return at2>0?trimmed.slice(0,at2):trimmed}var init_vertex=__esm({"src/vertex.ts"(){"use strict"}});import fs2 from"fs";import os2 from"os";import path7 from"path";function toModelWindow(id,contextWindow,maxOutput){if(typeof id!=="string"||id.length===0||typeof contextWindow!=="number"||!Number.isFinite(contextWindow)||contextWindow<=0)return null;const win={id,contextWindow:Math.floor(contextWindow)};if(typeof maxOutput==="number"&&Number.isFinite(maxOutput)&&maxOutput>0)win.maxOutput=Math.floor(maxOutput);return win}function nonEmpty2(s3){return typeof s3==="string"&&s3.trim().length>0}function resolvePiHome(env){const h=os2.homedir();return nonEmpty2(env.PI_CODING_AGENT_DIR)?env.PI_CODING_AGENT_DIR:nonEmpty2(env.PI_HOME)?env.PI_HOME:path7.join(h,".pi","agent")}function resolveOmpHome(env){const h=os2.homedir();return nonEmpty2(env.PI_CODING_AGENT_DIR)?env.PI_CODING_AGENT_DIR:path7.join(h,".omp","agent")}function resolveHermesHome(env){const h=os2.homedir();return nonEmpty2(env.HERMES_HOME)?env.HERMES_HOME:path7.join(h,".hermes")}function resolveDshHome(env){const h=os2.homedir();return nonEmpty2(env.DSH_HOME)?env.DSH_HOME:path7.join(h,".dsh")}function resolveCodexHome(env){const h=os2.homedir();return nonEmpty2(env.CODEX_HOME)?env.CODEX_HOME:path7.join(h,".codex")}function parseCodexToml(text2){const result={providers:{}};let table="";let curProvider=null;let codexModel;let codexContextWindow;let codexAutoCompactLimit;let codexMaxOutput;for(const rawLine of text2.split(/\r?\n/)){const line=rawLine.trim();if(!line||line.startsWith("#"))continue;const tableMatch=/^\[([^\]]+)\]$/.exec(line);if(tableMatch){table=tableMatch[1].trim();curProvider=table.startsWith("model_providers.")?table.slice("model_providers.".length).trim():null;if(curProvider&&!result.providers[curProvider]){result.providers[curProvider]={}}continue}const strMatch=/^([A-Za-z0-9_.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(line);const numMatch=/^([A-Za-z0-9_.-]+)\s*=\s*([0-9]+)\b/.exec(line);if(strMatch){const key2=strMatch[1];const val=strMatch[2]!==void 0?strMatch[2]:strMatch[3];if(table===""){if(key2==="model_provider")result.modelProvider=val;else if(key2==="openai_base_url")result.openaiBaseUrl=val;else if(key2==="model")codexModel=val}else if(curProvider&&key2==="base_url"){result.providers[curProvider].baseUrl=val}}else if(numMatch&&table===""){if(numMatch[1]==="model_context_window")codexContextWindow=Number(numMatch[2]);else if(numMatch[1]==="model_auto_compact_token_limit")codexAutoCompactLimit=Number(numMatch[2]);else if(numMatch[1]==="model_max_output_tokens")codexMaxOutput=Number(numMatch[2])}}if(codexModel)result.model=codexModel;if(codexContextWindow)result.contextWindow=codexContextWindow;if(codexAutoCompactLimit)result.autoCompactLimit=codexAutoCompactLimit;if(codexMaxOutput)result.maxOutput=codexMaxOutput;const win=toModelWindow(codexModel,codexContextWindow,codexMaxOutput);if(win)result.modelWindows=[win];return result}function readCodexConfig(codexHome){const cfgPath=path7.join(codexHome,"config.toml");let text2;try{text2=fs2.readFileSync(cfgPath,"utf8")}catch{return{providers:{}}}return parseCodexToml(text2)}function resolveKimiHome(env=process.env){return nonEmpty2(env.KIMI_CODE_HOME)?env.KIMI_CODE_HOME:path7.join(os2.homedir(),".kimi-code")}function parseConfigText(text2){let parsed;try{parsed=JSON.parse(text2)}catch{const errors=[];parsed=parse2(text2,errors,{allowTrailingComma:true})}if(parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed))return parsed;return void 0}function readConfigFileRoot(file){try{return parseConfigText(fs2.readFileSync(file,"utf8"))}catch{return void 0}}function mergeConfigDeep(target,source){const out={...target};for(const[key2,value]of Object.entries(source)){const existing=out[key2];out[key2]=value!==null&&typeof value==="object"&&!Array.isArray(value)&&existing!==null&&typeof existing==="object"&&!Array.isArray(existing)?mergeConfigDeep(existing,value):value}return out}function readOpencodeConfigRoot(env){let root;const xdg2=nonEmpty2(env.XDG_CONFIG_HOME)?env.XDG_CONFIG_HOME:path7.join(os2.homedir(),".config");const dir=path7.join(xdg2,"opencode");for(const file of["config.json","opencode.json","opencode.jsonc"]){const next=readConfigFileRoot(path7.join(dir,file));if(next!==void 0)root=root===void 0?next:mergeConfigDeep(root,next)}if(nonEmpty2(env.OPENCODE_CONFIG)){const next=readConfigFileRoot(env.OPENCODE_CONFIG);if(next!==void 0)root=root===void 0?next:mergeConfigDeep(root,next)}return root}var TOML_KEY_PART_RE,OPENCODE_CONFIG_FILES;var init_client_config=__esm({"src/client-config.ts"(){"use strict";init_main();init_vertex();TOML_KEY_PART_RE=new RegExp(String.raw`^(?:[A-Za-z0-9_-]+|"(?:[^"\\\n]|\\.)*"|'(?:[^'\n])*')(?:\.(?:[A-Za-z0-9_-]+|"(?:[^"\\\n]|\\.)*"|'(?:[^'\n])*'))*$`);OPENCODE_CONFIG_FILES=["opencode.jsonc","opencode.json","config.json"]}});import{createHash as createHash6,randomUUID}from"crypto";import fs4 from"fs";import os4 from"os";import path9 from"path";function isProxyInstanceFile(v3){return v3!==void 0&&"instanceId"in v3}function readProxyInstanceFile(file){let raw;try{raw=fs4.readFileSync(file??instanceFilePath(),"utf8").trim()}catch{return void 0}if(raw.startsWith("{")){try{const parsed=JSON.parse(raw);if(typeof parsed.origin==="string"&&/^https?:\/\/\S+$/.test(parsed.origin)){const windows={};if(parsed.modelWindows&&typeof parsed.modelWindows==="object"){for(const[k2,v3]of Object.entries(parsed.modelWindows)){const n=Number(v3);if(Number.isFinite(n)&&n>0)windows[k2]=n}}const maxOutputs={};if(parsed.modelMaxOutputs&&typeof parsed.modelMaxOutputs==="object"){for(const[k2,v3]of Object.entries(parsed.modelMaxOutputs)){const n=Number(v3);if(Number.isFinite(n)&&n>0)maxOutputs[k2]=n}}return{origin:parsed.origin,instanceId:typeof parsed.instanceId==="string"?parsed.instanceId:"",pid:typeof parsed.pid==="number"?parsed.pid:0,startedAt:typeof parsed.startedAt==="number"?parsed.startedAt:0,host:typeof parsed.host==="string"?parsed.host:"",port:typeof parsed.port==="number"?parsed.port:0,passthrough:Boolean(parsed.passthrough),mitmDomains:Array.isArray(parsed.mitmDomains)?parsed.mitmDomains.map(String):[],modelWindows:windows,modelMaxOutputs:Object.keys(maxOutputs).length>0?maxOutputs:void 0,launchToken:typeof parsed.launchToken==="string"?parsed.launchToken:void 0,lane:typeof parsed.lane==="string"&&parsed.lane!==""?parsed.lane:void 0,codeFingerprint:typeof parsed.codeFingerprint==="string"&&parsed.codeFingerprint!==""?parsed.codeFingerprint:void 0}}}catch{}}if(/^https?:\/\/\S+$/.test(raw))return{origin:raw};return void 0}function instanceFilePath(){return path9.join(stateDir(),"proxy-origin")}function portZoneFilePath(){return path9.join(stateDir(),"port-zone.json")}function readZonePort(lane,file=portZoneFilePath()){let raw;try{raw=fs4.readFileSync(file,"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);const v3=parsed?.lanes?.[lane];if(typeof v3==="number"&&Number.isInteger(v3)&&v3>0&&v3<65536)return v3;return void 0}catch{return void 0}}function writeZonePort(lane,port,file=portZoneFilePath()){if(!Number.isInteger(port)||port<=0||port>=65536)return;let cur={};try{const parsed=JSON.parse(fs4.readFileSync(file,"utf8"));if(parsed!==null&&typeof parsed==="object"&&parsed.lanes!==null&&typeof parsed.lanes==="object")cur=parsed}catch{}atomicWriteJson({lanes:{...cur.lanes??{},[lane]:port}},file)}function lanePreferredPort(lane,env=process.env,file=portZoneFilePath()){return readZonePort(lane,file)??resolveZonePortBase(env)}function entryScriptFingerprint(scriptPath){if(!scriptPath)return void 0;const resolved=path9.resolve(scriptPath);const cached=scriptFingerprints.get(resolved);if(cached!==void 0)return cached;let digest;try{digest=createHash6("sha256").update(fs4.readFileSync(resolved)).digest("hex")}catch{return void 0}scriptFingerprints.set(resolved,digest);return digest}function atomicWriteJson(obj,filePath){fs4.mkdirSync(path9.dirname(filePath),{recursive:true});const tempPath=`${filePath}.${process.pid}.${randomUUID()}.tmp`;let descriptor;try{descriptor=fs4.openSync(tempPath,"wx",420);fs4.writeSync(descriptor,JSON.stringify(obj)+"\n",null,"utf8");fs4.fsyncSync(descriptor);fs4.closeSync(descriptor);descriptor=void 0;fs4.renameSync(tempPath,filePath)}catch(error){if(descriptor!==void 0){try{fs4.closeSync(descriptor)}catch{}}try{fs4.unlinkSync(tempPath)}catch{}throw error}}function startingMarkerPath(){return path9.join(stateDir(),"proxy-starting")}function readStartingMarker(file){let raw;try{raw=fs4.readFileSync(file??startingMarkerPath(),"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);if(typeof parsed.token!=="string"||parsed.token==="")return void 0;if(typeof parsed.pid!=="number"||!Number.isInteger(parsed.pid)||parsed.pid<=0)return void 0;if(typeof parsed.startedAt!=="number")return void 0;return{token:parsed.token,pid:parsed.pid,host:typeof parsed.host==="string"?parsed.host:"",port:typeof parsed.port==="number"?parsed.port:0,startedAt:parsed.startedAt,...typeof parsed.lane==="string"&&parsed.lane!==""?{lane:parsed.lane}:{}}}catch{return void 0}}function claimStartingMarker(marker,file){const filePath=file??startingMarkerPath();let descriptor;try{fs4.mkdirSync(path9.dirname(filePath),{recursive:true});descriptor=fs4.openSync(filePath,"wx",420);fs4.writeSync(descriptor,JSON.stringify(marker)+"\n",null,"utf8");fs4.fsyncSync(descriptor);descriptor=void 0;return true}catch{if(descriptor!==void 0){try{fs4.closeSync(descriptor)}catch{}}return false}}function clearStartingMarker(token,file){const filePath=file??startingMarkerPath();const current=readStartingMarker(filePath);if(current&&current.token===token){try{fs4.unlinkSync(filePath)}catch{}}}function removeStartingMarker(file){try{fs4.unlinkSync(file??startingMarkerPath())}catch{}}function isPidAlive(pid){if(!Number.isInteger(pid)||pid<=0)return false;try{process.kill(pid,0);return true}catch(err2){return err2.code==="EPERM"}}function registryDirPath(){return path9.join(stateDir(),"instances")}function legacyRegistryFilePath(){return path9.join(stateDir(),"instances.json")}function safeReadJson2(file){try{return JSON.parse(fs4.readFileSync(file,"utf8"))}catch{return void 0}}function coerceEntry(value){if(!value||typeof value!=="object")return void 0;const o=value;if(typeof o.instanceId!=="string"||o.instanceId==="")return void 0;const windows={};if(o.modelWindows&&typeof o.modelWindows==="object"){for(const[k2,v3]of Object.entries(o.modelWindows)){const n=Number(v3);if(Number.isFinite(n)&&n>0)windows[k2]=n}}const maxOutputs={};if(o.modelMaxOutputs&&typeof o.modelMaxOutputs==="object"){for(const[k2,v3]of Object.entries(o.modelMaxOutputs)){const n=Number(v3);if(Number.isFinite(n)&&n>0)maxOutputs[k2]=n}}return{instanceId:o.instanceId,pid:typeof o.pid==="number"?o.pid:0,port:typeof o.port==="number"?o.port:0,origin:typeof o.origin==="string"?o.origin:"",startedAt:typeof o.startedAt==="number"?o.startedAt:0,...typeof o.host==="string"&&o.host!==""?{host:o.host}:{},...typeof o.passthrough==="boolean"?{passthrough:o.passthrough}:{},...Array.isArray(o.mitmDomains)?{mitmDomains:o.mitmDomains.map(String)}:{},...Object.keys(windows).length>0?{modelWindows:windows}:{},...Object.keys(maxOutputs).length>0?{modelMaxOutputs:maxOutputs}:{},...typeof o.lane==="string"&&o.lane!==""?{lane:o.lane}:{},...typeof o.codeFingerprint==="string"&&o.codeFingerprint!==""?{codeFingerprint:o.codeFingerprint}:{}}}function readMarkerNames(){try{return fs4.readdirSync(registryDirPath())}catch{return[]}}function readAllRegistryEntries(){const seen=new Set;const out=[];for(const name of readMarkerNames()){if(!name.endsWith(".json"))continue;const entry=coerceEntry(safeReadJson2(path9.join(registryDirPath(),name)));if(entry&&!seen.has(entry.instanceId)){seen.add(entry.instanceId);out.push(entry)}}const legacy=safeReadJson2(legacyRegistryFilePath());if(legacy&&Array.isArray(legacy.instances)){for(const raw of legacy.instances){const entry=coerceEntry(raw);if(entry&&!seen.has(entry.instanceId)){seen.add(entry.instanceId);out.push(entry)}}}return out}function listInstances(){return readAllRegistryEntries()}function discoverLiveInstances(){const out=[];for(const e of readAllRegistryEntries()){if(!isPidAlive(e.pid))continue;out.push({origin:e.origin,instanceId:e.instanceId,pid:e.pid,startedAt:e.startedAt,host:e.host??"",port:e.port,passthrough:Boolean(e.passthrough),mitmDomains:e.mitmDomains??[],modelWindows:e.modelWindows??{},modelMaxOutputs:e.modelMaxOutputs,lane:e.lane,codeFingerprint:e.codeFingerprint})}return out}var scriptFingerprints;var init_instance=__esm({"src/instance.ts"(){"use strict";init_config();init_paths();scriptFingerprints=new Map}});function winCmdUnsafeToken(token){if(token==="")return"an empty argument";if(token.includes('"'))return"a double quote";if(token.includes("%"))return"% (cmd.exe expands %VAR%)";if(/[&|<>^()]/.test(token))return"cmd metacharacters (& | < > ^ ( ))";if(/[\r\n]/.test(token))return"a line break";if(/\s/.test(token)){const trail=/\\+$/.exec(token)?.[0].length??0;if(trail%2===1)return"an odd number of trailing backslashes"}return void 0}function winCmdRefusalError(what,reason,hint){return new Error(`this ${what} cannot be passed through cmd.exe: it contains ${reason}. cmd.exe re-parses the whole command line \u2014 embedded quotes split tokens, %VAR% expands, &|<>^() are command operators \u2014 so such arguments arrive corrupted or execute unintended commands. ${hint}`)}var init_win_cmd=__esm({"src/win-cmd.ts"(){"use strict"}});import fs5 from"fs";import path10 from"path";import{execFile,spawnSync}from"child_process";import{promisify}from"util";function dshProfileDirs(env=process.env){const profiles=path10.join(resolveDshHome(env),"profiles");let entries2;try{entries2=fs5.readdirSync(profiles,{withFileTypes:true})}catch(err2){if(err2.code==="ENOENT"){throw new Error(`no dsh profiles found under ${profiles} \u2014 run dsh once (any profile) so the profile dirs exist, then retry`)}throw err2}return entries2.filter(e=>e.isDirectory()&&e.name!=="node_modules").map(e=>path10.join(profiles,e.name))}function parseDshPatchEntries(text2){const itemRe=/^\s*-\s*id\s*:\s*(\S+)/;const listItemRe=/^\s*-\s/;const disabledRe=/^\s+disabled\s*:\s*true\b/;const out=[];let current;for(const line of text2.split(/\r?\n/)){const m3=line.match(itemRe);if(m3){if(current)out.push(current);let v3=m3[1];if(v3.startsWith('"')&&v3.endsWith('"')||v3.startsWith("'")&&v3.endsWith("'"))v3=v3.slice(1,-1);v3=v3.trim();current=v3.length>0?{id:v3,disabled:false}:void 0;continue}if(listItemRe.test(line)){if(current)out.push(current);current=void 0;continue}if(current&&disabledRe.test(line))current.disabled=true}if(current)out.push(current);return out}function readManifestDependencies(profileDir){const manifest=JSON.parse(fs5.readFileSync(path10.join(profileDir,"package.json"),"utf8"));return manifest.dependencies??{}}function dshProfileDepSpec(profileDir){try{const v3=readManifestDependencies(profileDir)[DSH_PACKAGE];return typeof v3==="string"?v3:void 0}catch{return void 0}}function dshProfileDependsOnBili(profileDir){return dshProfileDepSpec(profileDir)!==void 0}function planDshProfileManifestSpec(profileDir,installedVersion){const file=path10.join(profileDir,"package.json");let raw;try{raw=fs5.readFileSync(file,"utf8")}catch{return{action:"keep",reason:"no readable package.json"}}let doc;try{doc=JSON.parse(raw)}catch{return{action:"keep",reason:"malformed package.json"}}const deps=doc.dependencies;if(!deps||typeof deps[DSH_PACKAGE]!=="string")return{action:"keep",reason:"no billion-context dependency declared"};const spec=deps[DSH_PACKAGE];if(!isRegistryDepSpec(spec))return{action:"keep",reason:`local pin ${spec} respected`};const m3=spec.match(/^\^?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/);if(!m3)return{action:"keep",reason:`non-version spec ${spec} respected`};if(m3[1]===installedVersion)return{action:"keep"};const nextSpec=spec.startsWith("^")?`^${installedVersion}`:installedVersion;deps[DSH_PACKAGE]=nextSpec;return{action:"rewrite",nextSpec,nextRaw:JSON.stringify(doc,null,2)+"\n"}}function installedProfileVersion(profileDir){try{const pkg=JSON.parse(fs5.readFileSync(path10.join(profileDir,"node_modules",DSH_PACKAGE,"package.json"),"utf-8"));return typeof pkg.version==="string"?pkg.version:void 0}catch{return void 0}}function isRegistryDepSpec(spec){return!/^[a-z][a-z0-9+.-]*:/i.test(spec)}function underDir(dir,root){return dir===root||dir.startsWith(root+path10.sep)}function isDshProfileCopy(installDir,env=process.env){const profiles=path10.join(resolveDshHome(env),"profiles");const roots=new Set([profiles]);try{roots.add(fs5.realpathSync(profiles))}catch{}const dirs=[installDir];try{dirs.push(fs5.realpathSync(installDir))}catch{}return dirs.some(dir=>[...roots].some(root=>underDir(dir,root)))}function resolveDshBinary(env=process.env,platform=process.platform,existsImpl=fs5.existsSync,execPath=process.execPath){const override=env.BILI_DSH_BIN?.trim();if(override&&override.length>0)return override;const sep2=platform==="win32"?";":":";const extensions=platform==="win32"?(env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0):[""];const nodeDir=path10.dirname(execPath);const home=platform==="win32"?env.USERPROFILE??"":env.HOME??"";const extraDirs=platform==="win32"?[nodeDir,env.APPDATA?env.APPDATA+"/npm":"",env.LOCALAPPDATA?env.LOCALAPPDATA+"/pnpm":""]:[nodeDir,"/usr/local/bin","/opt/homebrew/bin","/opt/local/bin",home?home+"/.local/bin":""];for(const dir of[...(env.PATH??"").split(sep2),...extraDirs]){if(!dir)continue;for(const ext of extensions){const name=ext===""?"dsh":`dsh${ext}`;const candidate=dir.endsWith("/")||dir.endsWith("\\")?dir+name:dir+"/"+name;if(existsImpl(candidate))return candidate}}return"dsh"}function quoteWinToken(token){if(!/\s/.test(token)||token.includes('"'))return token;return`"${token}"`}function planDshSpawn(command,args,env=process.env,platform=process.platform){if(platform!=="win32")return{command,args:[...args]};const lower=command.toLowerCase();const base=command.slice(Math.max(command.lastIndexOf("/"),command.lastIndexOf("\\"))+1);const needsCmd=lower.endsWith(".cmd")||lower.endsWith(".bat")||!path10.extname(base);if(!needsCmd)return{command,args:[...args]};[command,...args].forEach((token,i)=>{const reason=winCmdUnsafeToken(token);if(reason)throw winCmdRefusalError(i===0?"resolved dsh command":`argument #${i-1}`,reason,"Set BILI_DSH_BIN to the dsh executable, or reword the argument.")});const comspec=env.COMSPEC?.trim()||"cmd.exe";const line=`"${[command,...args].map(quoteWinToken).join(" ")}"`;return{command:comspec,args:["/d","/s","/c",line],windowsVerbatimArguments:true}}function formatDshError(err2,args){const e=err2;if(e.code==="ENOENT"){return new Error("dsh CLI not found (not on PATH, not in the known install locations probed) \u2014 install deepseek-harness, or set BILI_DSH_BIN to its executable path, then retry")}const stderr=typeof e.stderr==="string"?e.stderr.trim():e.stderr instanceof Buffer?decodeChildOutput(e.stderr).trim():"";const detail=stderr||(typeof e.message==="string"&&e.message.length>0?e.message:`exit ${e.status??"?"}`);return new Error(`dsh ${args.join(" ")} failed: ${detail}`)}function decodeChildOutput(buf){if(buf==null)return"";const raw=typeof buf==="string"?Buffer.from(buf,"utf8"):buf;if(raw.length===0)return"";try{const utf8=new TextDecoder("utf-8",{fatal:true}).decode(raw);if(UTF8_GBK_TRAP.test(utf8)){try{const gbk=new TextDecoder("gbk").decode(raw);if(HAS_CJK.test(gbk))return gbk}catch{}}return utf8}catch{try{return new TextDecoder("gbk").decode(raw)}catch{return raw.toString("utf8")}}}async function defaultAsyncRun(plan2){const{stdout,stderr}=await pExecFile(plan2.command,plan2.args,{timeout:DSH_EXEC_TIMEOUT_MS,encoding:"buffer",windowsVerbatimArguments:plan2.windowsVerbatimArguments,windowsHide:true});return{stdout:decodeChildOutput(stdout),stderr:decodeChildOutput(stderr)}}async function runDshPluginAsync(args,env=process.env){const plan2=planDshSpawn(resolveDshBinary(env),args);const run=testRunners?.async??defaultAsyncRun;try{await run(plan2)}catch(err2){throw formatDshError(err2,args)}}async function refreshDshProfileBundles(targetVersion,log2,env=process.env){let dirs;try{dirs=dshProfileDirs(env)}catch{return{refreshed:0,failed:0}}const targets=dirs.filter(dir=>dshProfileDependsOnBili(dir));if(targets.length===0)return{refreshed:0,failed:0};let refreshed=0;let failed=0;for(const dir of targets){const name=path10.basename(dir);const spec=dshProfileDepSpec(dir);if(spec!==void 0&&!isRegistryDepSpec(spec)){log2("info",`[update] dsh profile ${name}: billion-context pinned to ${spec} (local source) \u2014 leaving it alone`);continue}if(name===DSH_DESKTOP_PROFILE){continue}if(installedProfileVersion(dir)===targetVersion)continue;try{await runDshPluginAsync(["plugin","--profile",name,"add",`${DSH_PACKAGE}@${targetVersion}`],env);refreshed+=1}catch(err2){failed+=1;const detail=err2 instanceof Error?err2.message:String(err2);log2("warn",`[update] dsh profile ${name}: bundle refresh to ${targetVersion} failed: ${detail} \u2014 manual fix: run \`dsh plugin --profile ${name} add billion-context@${targetVersion}\` from a shell where \`dsh\` resolves (or point BILI_DSH_BIN at dsh's executable)`)}}if(refreshed>0){log2("info",`[update] refreshed ${refreshed} dsh profile bundle(s) to ${targetVersion} \u2014 restart dsh to load it`)}return{refreshed,failed}}var DSH_PACKAGE,DSH_DESKTOP_PROFILE,DSH_EXEC_TIMEOUT_MS,testRunners,UTF8_GBK_TRAP,HAS_CJK,pExecFile;var init_dsh_channel=__esm({"src/dsh-channel.ts"(){"use strict";init_client_config();init_win_cmd();DSH_PACKAGE="billion-context";DSH_DESKTOP_PROFILE="desktop";DSH_EXEC_TIMEOUT_MS=5*60*1e3;UTF8_GBK_TRAP=/[\u0370-\u052F]{2}/;HAS_CJK=/[\u3400-\u9FFF\uF900-\uFAFF]/;pExecFile=promisify(execFile)}});import fs6 from"fs";import path11 from"path";import{execFile as execFile2}from"child_process";import{promisify as promisify2}from"util";function resolvePiBinary(env=process.env,platform=process.platform,existsImpl=fs6.existsSync,execPath=process.execPath){const override=env.BILI_PI_BIN?.trim();if(override&&override.length>0)return override;const probeNames=["pi","pi-stable"];const sep2=platform==="win32"?";":":";const extensions=platform==="win32"?(env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0):[""];const nodeDir=path11.dirname(execPath);const home=platform==="win32"?env.USERPROFILE??"":env.HOME??"";const extraDirs=platform==="win32"?[nodeDir,env.APPDATA?env.APPDATA+"/npm":""]:[nodeDir,"/usr/local/bin","/opt/homebrew/bin","/opt/local/bin",home?home+"/.local/bin":""];for(const dir of[...(env.PATH??"").split(sep2),...extraDirs]){if(!dir)continue;for(const name of probeNames){for(const ext of extensions){const fileName=ext===""?name:`${name}${ext}`;const candidate=dir.endsWith("/")||dir.endsWith("\\")?dir+fileName:dir+"/"+fileName;if(existsImpl(candidate))return candidate}}}return"pi"}function formatPiError(err2,args){const e=err2;if(e.code==="ENOENT"){return new Error("pi CLI not found (not on PATH, not in the known install locations probed) \u2014 set BILI_PI_BIN to its executable path, then retry")}const stderr=typeof e.stderr==="string"?e.stderr.trim():e.stderr instanceof Buffer?decodeChildOutput(e.stderr).trim():"";const detail=stderr||(typeof e.message==="string"&&e.message.length>0?e.message:`exit ${e.status??"?"}`);return new Error(`pi ${args.join(" ")} failed: ${detail}`)}async function defaultAsyncRun2(plan2){const{stdout,stderr}=await pExecFile2(plan2.command,plan2.args,{timeout:PI_EXEC_TIMEOUT_MS,encoding:"buffer",windowsVerbatimArguments:plan2.windowsVerbatimArguments,windowsHide:true});return{stdout:decodeChildOutput(stdout),stderr:decodeChildOutput(stderr)}}async function runPiAsync(args,env=process.env){const plan2=planDshSpawn(resolvePiBinary(env),args,env);const run=testRunners2?.async??defaultAsyncRun2;try{await run(plan2)}catch(err2){throw formatPiError(err2,args)}}function piNpmCopyRoot(env=process.env){return path11.join(resolvePiHome(env),"npm","node_modules",PI_PACKAGE)}function isPiNpmCopy(installDir,env=process.env){const root=piNpmCopyRoot(env);let real=installDir;try{real=fs6.realpathSync(installDir)}catch{}let realRoot=root;try{realRoot=fs6.realpathSync(root)}catch{}for(const dir of[installDir,real]){if(dir===root||dir===realRoot||dir.startsWith(realRoot+path11.sep))return true}return false}function piNpmEntrySpec(env=process.env){let parsed;try{parsed=JSON.parse(fs6.readFileSync(path11.join(resolvePiHome(env),"settings.json"),"utf-8"))}catch{return void 0}if(!Array.isArray(parsed.packages))return void 0;const re2=new RegExp(`^npm:${PI_PACKAGE}(@.*)?$`);return parsed.packages.find(p2=>typeof p2==="string"&&re2.test(p2))}var PI_PACKAGE,PI_NPM_SPEC,PI_EXEC_TIMEOUT_MS,testRunners2,pExecFile2;var init_pi_channel=__esm({"src/pi-channel.ts"(){"use strict";init_client_config();init_dsh_channel();PI_PACKAGE="billion-context";PI_NPM_SPEC="npm:billion-context";PI_EXEC_TIMEOUT_MS=5*60*1e3;pExecFile2=promisify2(execFile2)}});import Qr from"events";import I from"fs";import{EventEmitter as Di}from"events";import Cs from"stream";import{StringDecoder as Hr}from"string_decoder";import cr from"path";import Kt from"fs";import{dirname as Fn,parse as kn}from"path";import{EventEmitter as Dn}from"events";import zi from"assert";import{Buffer as Ot}from"buffer";import*as Ps from"zlib";import en from"zlib";import{posix as Zt}from"path";import{basename as _n}from"path";import mi from"fs";import X from"fs";import js from"path";import{win32 as Pn}from"path";import ar from"path";import Br from"fs";import co from"assert";import{randomBytes as Mr}from"crypto";import u from"fs";import R from"path";import pr from"fs";import wi from"fs";import we from"path";import k from"fs";import ro from"fs/promises";import Si from"path";import{join as xr}from"path";import v from"fs";import Pr from"path";function Zn(s3,t,e){let i=t,r=t?t.next:s3.head,n=new ue(e,i,r,s3);return n.next===void 0&&(s3.tail=n),n.prev===void 0&&(s3.head=n),s3.length++,n}function Yn(s3,t){s3.tail=new ue(t,s3.tail,void 0,s3),s3.head||(s3.head=s3.tail),s3.length++}function Kn(s3,t){s3.head=new ue(t,void 0,s3.head,s3),s3.tail||(s3.tail=s3.head),s3.length++}var zr,Ur,Ds,Wr,Gr,Zr,Q,J,nt,De,qt,Ne,Ns,Ae,As,z,Mt,g,Qt,Bt,b,N,_,bi,Ie,L,S,_i,Oi,Is,Ti,Z,xi,Ce,Jt,Rt,C,jt,Yr,Kr,Vr,$r,Fe,Li,Xr,qr,A,Jr,ht,H,te,m,Ni,tt,Ai,ki,vi,ie,ke,Ut,Ht,Ii,Pt,at,U,ot,Y,zt,Ci,j,ee,Fi,ve,gt,Me,bt,_t,Be,et,Wt,jr,Fs,ks,vs,Ms,Bs,tn,se,K,sn,M,rn,zs,nn,Bi,Tt,Gt,Pi,re,Pe,ze,Ue,He,We,Ge,Ze,Ye,Ke,Us,hn,an,Hs,ln,cn,Ws,Gs,Hi,ne,dn,Ui,oe,Ve,un,F,mn,xt,Wi,pn,lt,En,wn,Sn,ct,yn,Rn,gn,Gi,bn,Lt,ft,On,Tn,xn,Ln,f,$e,Dt,Nn,Xi,qi,An,B,Nt,it,Zi,Zs,V,he,dt,Ys,p,st,ut,Yi,At,w,Xe,qe,Ki,Ks,Vs,ae,Vi,Qe,Yt,$,Je,It,je,ti,$s,In,le,$i,Xs,Cn,rt,mt,vn,Qi,Mn,Bn,Ct,Ji,zn,qs,ce,ei,ji,Un,Hn,ts,Qs,rr,Wn,tr,er,ir,is,sr,fe,ii,ss,si,rs,ns,os5,hs,pt,ri,as,es,q,de,ni,oi,Gn,hi,ue,pi,nr,li,me,W,pe,Et,Ft,Ee,ai,G,ls,ci,or,ds,us,fi,di,hr,cs,ui,lr,fs7,wt,kt,Vn,$n,fr,dr,Xn,qn,Qn,Jn,Er,wr,ur,Sr,yr,Rr,jn,to,eo,mr,ms,ps,Ei,io,Es,so,ws,Se,St,no,gr,Ss,br,oo,_r,ys,Or,Vt,Tr,ho,ao,lo,yi,Lr,Dr,_s,Nr,Os,P,Ts,xs,gi,Ar,Ir,Re,Cr,Fr,Rs,yt,O,Ri,kr,$t,gs,bs,Ls,ge,be,_e,Oe,fo,Te,uo,mo,po,vr,Xt,ye,xe,Eo,wo,So,yo,Ro,go,bo,_o,vt,Oo,To;var init_index_min=__esm({"node_modules/tar/dist/esm/index.min.js"(){"use strict";zr=Object.defineProperty;Ur=(s3,t)=>{for(var e in t)zr(s3,e,{get:t[e],enumerable:true})};Ds=typeof process=="object"&&process?process:{stdout:null,stderr:null};Wr=s3=>!!s3&&typeof s3=="object"&&(s3 instanceof A||s3 instanceof Cs||Gr(s3)||Zr(s3));Gr=s3=>!!s3&&typeof s3=="object"&&s3 instanceof Di&&typeof s3.pipe=="function"&&s3.pipe!==Cs.Writable.prototype.pipe;Zr=s3=>!!s3&&typeof s3=="object"&&s3 instanceof Di&&typeof s3.write=="function"&&typeof s3.end=="function";Q=Symbol("EOF");J=Symbol("maybeEmitEnd");nt=Symbol("emittedEnd");De=Symbol("emittingEnd");qt=Symbol("emittedError");Ne=Symbol("closed");Ns=Symbol("read");Ae=Symbol("flush");As=Symbol("flushChunk");z=Symbol("encoding");Mt=Symbol("decoder");g=Symbol("flowing");Qt=Symbol("paused");Bt=Symbol("resume");b=Symbol("buffer");N=Symbol("pipes");_=Symbol("bufferLength");bi=Symbol("bufferPush");Ie=Symbol("bufferShift");L=Symbol("objectMode");S=Symbol("destroyed");_i=Symbol("error");Oi=Symbol("emitData");Is=Symbol("emitEnd");Ti=Symbol("emitEnd2");Z=Symbol("async");xi=Symbol("abort");Ce=Symbol("aborted");Jt=Symbol("signal");Rt=Symbol("dataListeners");C=Symbol("discarded");jt=s3=>Promise.resolve().then(s3);Yr=s3=>s3();Kr=s3=>s3==="end"||s3==="finish"||s3==="prefinish";Vr=s3=>s3 instanceof ArrayBuffer||!!s3&&typeof s3=="object"&&s3.constructor&&s3.constructor.name==="ArrayBuffer"&&s3.byteLength>=0;$r=s3=>!Buffer.isBuffer(s3)&&ArrayBuffer.isView(s3);Fe=class{src;dest;opts;ondrain;constructor(t,e,i){this.src=t,this.dest=e,this.opts=i,this.ondrain=()=>t[Bt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}};Li=class extends Fe{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,i){super(t,e,i),this.proxyErrors=r=>this.dest.emit("error",r),t.on("error",this.proxyErrors)}};Xr=s3=>!!s3.objectMode;qr=s3=>!s3.objectMode&&!!s3.encoding&&s3.encoding!=="buffer";A=class extends Di{[g]=false;[Qt]=false;[N]=[];[b]=[];[L];[z];[Z];[Mt];[Q]=false;[nt]=false;[De]=false;[Ne]=false;[qt]=null;[_]=0;[S]=false;[Jt];[Ce]=false;[Rt]=0;[C]=false;writable=true;readable=true;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Xr(e)?(this[L]=true,this[z]=null):qr(e)?(this[z]=e.encoding,this[L]=false):(this[L]=false,this[z]=null),this[Z]=!!e.async,this[Mt]=this[z]?new Hr(this[z]):null,e&&e.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[b]}),e&&e.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[N]});let{signal:i}=e;i&&(this[Jt]=i,i.aborted?this[xi]():i.addEventListener("abort",()=>this[xi]()))}get bufferLength(){return this[_]}get encoding(){return this[z]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[L]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Z]}set async(t){this[Z]=this[Z]||!!t}[xi](){this[Ce]=true,this.emit("abort",this[Jt]?.reason),this.destroy(this[Jt]?.reason)}get aborted(){return this[Ce]}set aborted(t){}write(t,e,i){if(this[Ce])return false;if(this[Q])throw new Error("write after end");if(this[S])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof e=="function"&&(i=e,e="utf8"),e||(e="utf8");let r=this[Z]?jt:Yr;if(!this[L]&&!Buffer.isBuffer(t)){if($r(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Vr(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[L]?(this[g]&&this[_]!==0&&this[Ae](true),this[g]?this.emit("data",t):this[bi](t),this[_]!==0&&this.emit("readable"),i&&r(i),this[g]):t.length?(typeof t=="string"&&!(e===this[z]&&!this[Mt]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[z]&&(t=this[Mt].write(t)),this[g]&&this[_]!==0&&this[Ae](true),this[g]?this.emit("data",t):this[bi](t),this[_]!==0&&this.emit("readable"),i&&r(i),this[g]):(this[_]!==0&&this.emit("readable"),i&&r(i),this[g])}read(t){if(this[S])return null;if(this[C]=false,this[_]===0||t===0||t&&t>this[_])return this[J](),null;this[L]&&(t=null),this[b].length>1&&!this[L]&&(this[b]=[this[z]?this[b].join(""):Buffer.concat(this[b],this[_])]);let e=this[Ns](t||null,this[b][0]);return this[J](),e}[Ns](t,e){if(this[L])this[Ie]();else{let i=e;t===i.length||t===null?this[Ie]():typeof i=="string"?(this[b][0]=i.slice(t),e=i.slice(0,t),this[_]-=t):(this[b][0]=i.subarray(t),e=i.subarray(0,t),this[_]-=t)}return this.emit("data",e),!this[b].length&&!this[Q]&&this.emit("drain"),e}end(t,e,i){return typeof t=="function"&&(i=t,t=void 0),typeof e=="function"&&(i=e,e="utf8"),t!==void 0&&this.write(t,e),i&&this.once("end",i),this[Q]=true,this.writable=false,(this[g]||!this[Qt])&&this[J](),this}[Bt](){this[S]||(!this[Rt]&&!this[N].length&&(this[C]=true),this[Qt]=false,this[g]=true,this.emit("resume"),this[b].length?this[Ae]():this[Q]?this[J]():this.emit("drain"))}resume(){return this[Bt]()}pause(){this[g]=false,this[Qt]=true,this[C]=false}get destroyed(){return this[S]}get flowing(){return this[g]}get paused(){return this[Qt]}[bi](t){this[L]?this[_]+=1:this[_]+=t.length,this[b].push(t)}[Ie](){return this[L]?this[_]-=1:this[_]-=this[b][0].length,this[b].shift()}[Ae](t=false){do;while(this[As](this[Ie]())&&this[b].length);!t&&!this[b].length&&!this[Q]&&this.emit("drain")}[As](t){return this.emit("data",t),this[g]}pipe(t,e){if(this[S])return t;this[C]=false;let i=this[nt];return e=e||{},t===Ds.stdout||t===Ds.stderr?e.end=false:e.end=e.end!==false,e.proxyErrors=!!e.proxyErrors,i?e.end&&t.end():(this[N].push(e.proxyErrors?new Li(this,t,e):new Fe(this,t,e)),this[Z]?jt(()=>this[Bt]()):this[Bt]()),t}unpipe(t){let e=this[N].find(i=>i.dest===t);e&&(this[N].length===1?(this[g]&&this[Rt]===0&&(this[g]=false),this[N]=[]):this[N].splice(this[N].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let i=super.on(t,e);if(t==="data")this[C]=false,this[Rt]++,!this[N].length&&!this[g]&&this[Bt]();else if(t==="readable"&&this[_]!==0)super.emit("readable");else if(Kr(t)&&this[nt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[qt]){let r=e;this[Z]?jt(()=>r.call(this,this[qt])):r.call(this,this[qt])}return i}removeListener(t,e){return this.off(t,e)}off(t,e){let i=super.off(t,e);return t==="data"&&(this[Rt]=this.listeners("data").length,this[Rt]===0&&!this[C]&&!this[N].length&&(this[g]=false)),i}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Rt]=0,!this[C]&&!this[N].length&&(this[g]=false)),e}get emittedEnd(){return this[nt]}[J](){!this[De]&&!this[nt]&&!this[S]&&this[b].length===0&&this[Q]&&(this[De]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ne]&&this.emit("close"),this[De]=false)}emit(t,...e){let i=e[0];if(t!=="error"&&t!=="close"&&t!==S&&this[S])return false;if(t==="data")return!this[L]&&!i?false:this[Z]?(jt(()=>this[Oi](i)),true):this[Oi](i);if(t==="end")return this[Is]();if(t==="close"){if(this[Ne]=true,!this[nt]&&!this[S])return false;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[qt]=i,super.emit(_i,i);let n=!this[Jt]||this.listeners("error").length?super.emit("error",i):false;return this[J](),n}else if(t==="resume"){let n=super.emit("resume");return this[J](),n}else if(t==="finish"||t==="prefinish"){let n=super.emit(t);return this.removeAllListeners(t),n}let r=super.emit(t,...e);return this[J](),r}[Oi](t){for(let i of this[N])i.dest.write(t)===false&&this.pause();let e=this[C]?false:super.emit("data",t);return this[J](),e}[Is](){return this[nt]?false:(this[nt]=true,this.readable=false,this[Z]?(jt(()=>this[Ti]()),true):this[Ti]())}[Ti](){if(this[Mt]){let e=this[Mt].end();if(e){for(let i of this[N])i.dest.write(e);this[C]||super.emit("data",e)}}for(let e of this[N])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[L]||(t.dataLength=0);let e=this.promise();return this.on("data",i=>{t.push(i),this[L]||(t.dataLength+=i.length)}),await e,t}async concat(){if(this[L])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[z]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(S,()=>e(new Error("stream destroyed"))),this.on("error",i=>e(i)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[C]=false;let t=false,e=async()=>(this.pause(),t=true,{value:void 0,done:true});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:false,value:r});if(this[Q])return e();let n,o,h=d2=>{this.off("data",a),this.off("end",l3),this.off(S,c),e(),o(d2)},a=d2=>{this.off("error",h),this.off("end",l3),this.off(S,c),this.pause(),n({value:d2,done:!!this[Q]})},l3=()=>{this.off("error",h),this.off("data",a),this.off(S,c),e(),n({done:true,value:void 0})},c=()=>h(new Error("stream destroyed"));return new Promise((d2,y2)=>{o=y2,n=d2,this.once(S,c),this.once("error",h),this.once("end",l3),this.once("data",a)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[C]=false;let t=false,e=()=>(this.pause(),this.off(_i,e),this.off(S,e),this.off("end",e),t=true,{done:true,value:void 0}),i=()=>{if(t)return e();let r=this.read();return r===null?e():{done:false,value:r}};return this.once("end",e),this.once(_i,e),this.once(S,e),{next:i,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[S])return t?this.emit("error",t):this.emit(S),this;this[S]=true,this[C]=true,this[b].length=0,this[_]=0;let e=this;return typeof e.close=="function"&&!this[Ne]&&e.close(),t?this.emit("error",t):this.emit(S),this}static get isStream(){return Wr}};Jr=I.writev;ht=Symbol("_autoClose");H=Symbol("_close");te=Symbol("_ended");m=Symbol("_fd");Ni=Symbol("_finished");tt=Symbol("_flags");Ai=Symbol("_flush");ki=Symbol("_handleChunk");vi=Symbol("_makeBuf");ie=Symbol("_mode");ke=Symbol("_needDrain");Ut=Symbol("_onerror");Ht=Symbol("_onopen");Ii=Symbol("_onread");Pt=Symbol("_onwrite");at=Symbol("_open");U=Symbol("_path");ot=Symbol("_pos");Y=Symbol("_queue");zt=Symbol("_read");Ci=Symbol("_readSize");j=Symbol("_reading");ee=Symbol("_remain");Fi=Symbol("_size");ve=Symbol("_write");gt=Symbol("_writing");Me=Symbol("_defaultFlag");bt=Symbol("_errored");_t=class extends A{[bt]=false;[m];[U];[Ci];[j]=false;[Fi];[ee];[ht];constructor(t,e){if(e=e||{},super(e),this.readable=true,this.writable=false,typeof t!="string")throw new TypeError("path must be a string");this[bt]=false,this[m]=typeof e.fd=="number"?e.fd:void 0,this[U]=t,this[Ci]=e.readSize||16*1024*1024,this[j]=false,this[Fi]=typeof e.size=="number"?e.size:1/0,this[ee]=this[Fi],this[ht]=typeof e.autoClose=="boolean"?e.autoClose:true,typeof this[m]=="number"?this[zt]():this[at]()}get fd(){return this[m]}get path(){return this[U]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[at](){I.open(this[U],"r",(t,e)=>this[Ht](t,e))}[Ht](t,e){t?this[Ut](t):(this[m]=e,this.emit("open",e),this[zt]())}[vi](){return Buffer.allocUnsafe(Math.min(this[Ci],this[ee]))}[zt](){if(!this[j]){this[j]=true;let t=this[vi]();if(t.length===0)return process.nextTick(()=>this[Ii](null,0,t));I.read(this[m],t,0,t.length,null,(e,i,r)=>this[Ii](e,i,r))}}[Ii](t,e,i){this[j]=false,t?this[Ut](t):this[ki](e,i)&&this[zt]()}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Ut](t){this[j]=true,this[H](),this.emit("error",t)}[ki](t,e){let i=false;return this[ee]-=t,t>0&&(i=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[ee]<=0)&&(i=false,this[H](),super.end()),i}emit(t,...e){switch(t){case"prefinish":case"finish":return false;case"drain":return typeof this[m]=="number"&&this[zt](),false;case"error":return this[bt]?false:(this[bt]=true,super.emit(t,...e));default:return super.emit(t,...e)}}};Be=class extends _t{[at](){let t=true;try{this[Ht](null,I.openSync(this[U],"r")),t=false}finally{t&&this[H]()}}[zt](){let t=true;try{if(!this[j]){this[j]=true;do{let e=this[vi](),i=e.length===0?0:I.readSync(this[m],e,0,e.length,null);if(!this[ki](i,e))break}while(true);this[j]=false}t=false}finally{t&&this[H]()}}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.closeSync(t),this.emit("close")}}};et=class extends Qr{readable=false;writable=true;[bt]=false;[gt]=false;[te]=false;[Y]=[];[ke]=false;[U];[ie];[ht];[m];[Me];[tt];[Ni]=false;[ot];constructor(t,e){e=e||{},super(e),this[U]=t,this[m]=typeof e.fd=="number"?e.fd:void 0,this[ie]=e.mode===void 0?438:e.mode,this[ot]=typeof e.start=="number"?e.start:void 0,this[ht]=typeof e.autoClose=="boolean"?e.autoClose:true;let i=this[ot]!==void 0?"r+":"w";this[Me]=e.flags===void 0,this[tt]=e.flags===void 0?i:e.flags,this[m]===void 0&&this[at]()}emit(t,...e){if(t==="error"){if(this[bt])return false;this[bt]=true}return super.emit(t,...e)}get fd(){return this[m]}get path(){return this[U]}[Ut](t){this[H](),this[gt]=true,this.emit("error",t)}[at](){I.open(this[U],this[tt],this[ie],(t,e)=>this[Ht](t,e))}[Ht](t,e){this[Me]&&this[tt]==="r+"&&t&&t.code==="ENOENT"?(this[tt]="w",this[at]()):t?this[Ut](t):(this[m]=e,this.emit("open",e),this[gt]||this[Ai]())}end(t,e){return t&&this.write(t,e),this[te]=true,!this[gt]&&!this[Y].length&&typeof this[m]=="number"&&this[Pt](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[te]?(this.emit("error",new Error("write() after end()")),false):this[m]===void 0||this[gt]||this[Y].length?(this[Y].push(t),this[ke]=true,false):(this[gt]=true,this[ve](t),true)}[ve](t){I.write(this[m],t,0,t.length,this[ot],(e,i)=>this[Pt](e,i))}[Pt](t,e){t?this[Ut](t):(this[ot]!==void 0&&typeof e=="number"&&(this[ot]+=e),this[Y].length?this[Ai]():(this[gt]=false,this[te]&&!this[Ni]?(this[Ni]=true,this[H](),this.emit("finish")):this[ke]&&(this[ke]=false,this.emit("drain"))))}[Ai](){if(this[Y].length===0)this[te]&&this[Pt](null,0);else if(this[Y].length===1)this[ve](this[Y].pop());else{let t=this[Y];this[Y]=[],Jr(this[m],t,this[ot],(e,i)=>this[Pt](e,i))}}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.close(t,e=>e?this.emit("error",e):this.emit("close"))}}};Wt=class extends et{[at](){let t;if(this[Me]&&this[tt]==="r+")try{t=I.openSync(this[U],this[tt],this[ie])}catch(e){if(e?.code==="ENOENT")return this[tt]="w",this[at]();throw e}else t=I.openSync(this[U],this[tt],this[ie]);this[Ht](null,t)}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.closeSync(t),this.emit("close")}}[ve](t){let e=true;try{this[Pt](null,I.writeSync(this[m],t,0,t.length,this[ot])),e=false}finally{if(e)try{this[H]()}catch{}}}};jr=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]);Fs=s3=>!!s3.sync&&!!s3.file;ks=s3=>!s3.sync&&!!s3.file;vs=s3=>!!s3.sync&&!s3.file;Ms=s3=>!s3.sync&&!s3.file;Bs=s3=>!!s3.file;tn=s3=>{let t=jr.get(s3);return t||s3};se=(s3={})=>{if(!s3)return{};let t={};for(let[e,i]of Object.entries(s3)){let r=tn(e);t[r]=i}return t.chmod===void 0&&t.noChmod===false&&(t.chmod=true),delete t.noChmod,t};K=(s3,t,e,i,r)=>Object.assign((n=[],o,h)=>{Array.isArray(n)&&(o=n,n={}),typeof o=="function"&&(h=o,o=void 0),o=o?Array.from(o):[];let a=se(n);if(r?.(a,o),Fs(a)){if(typeof h=="function")throw new TypeError("callback not supported for sync tar functions");return s3(a,o)}else if(ks(a)){let l3=t(a,o);return h?l3.then(()=>h(),h):l3}else if(vs(a)){if(typeof h=="function")throw new TypeError("callback not supported for sync tar functions");return e(a,o)}else if(Ms(a)){if(typeof h=="function")throw new TypeError("callback only supported with file option");return i(a,o)}throw new Error("impossible options??")},{syncFile:s3,asyncFile:t,syncNoFile:e,asyncNoFile:i,validate:r});sn=en.constants||{ZLIB_VERNUM:4736};M=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},sn));rn=Ot.concat;zs=Object.getOwnPropertyDescriptor(Ot,"concat");nn=s3=>s3;Bi=zs?.writable===true||zs?.set!==void 0?s3=>{Ot.concat=s3?nn:rn}:s3=>{};Tt=Symbol("_superWrite");Gt=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}};Pi=Symbol("flushFlag");re=class extends A{#t=false;#i=false;#s;#n;#r;#e;#o;get sawError(){return this.#t}get handle(){return this.#e}get flushFlag(){return this.#s}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#s=t.flush??0,this.#n=t.finishFlush??0,this.#r=t.fullFlushFlag??0,typeof Ps[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#e=new Ps[e](t)}catch(i){throw new Gt(i,this.constructor)}this.#o=i=>{this.#t||(this.#t=true,this.close(),this.emit("error",i))},this.#e?.on("error",i=>this.#o(new Gt(i))),this.once("end",()=>this.close)}close(){this.#e&&(this.#e.close(),this.#e=void 0,this.emit("close"))}reset(){if(!this.#t)return zi(this.#e,"zlib binding closed"),this.#e.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#r),this.write(Object.assign(Ot.alloc(0),{[Pi]:t})))}end(t,e,i){return typeof t=="function"&&(i=t,e=void 0,t=void 0),typeof e=="function"&&(i=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#n),this.#i=true,super.end(i)}get ended(){return this.#i}[Tt](t){return super.write(t)}write(t,e,i){if(typeof e=="function"&&(i=e,e="utf8"),typeof t=="string"&&(t=Ot.from(t,e)),this.#t)return;zi(this.#e,"zlib binding closed");let r=this.#e._handle,n=r.close;r.close=()=>{};let o=this.#e.close;this.#e.close=()=>{},Bi(true);let h;try{let l3=typeof t[Pi]=="number"?t[Pi]:this.#s;h=this.#e._processChunk(t,l3),Bi(false)}catch(l3){Bi(false),this.#o(new Gt(l3,this.write))}finally{this.#e&&(this.#e._handle=r,r.close=n,this.#e.close=o,this.#e.removeAllListeners("error"))}this.#e&&this.#e.on("error",l3=>this.#o(new Gt(l3,this.write)));let a;if(h)if(Array.isArray(h)&&h.length>0){let l3=h[0];a=this[Tt](Ot.from(l3));for(let c=1;c<h.length;c++)a=this[Tt](h[c])}else a=this[Tt](Ot.from(h));return i&&i(),a}};Pe=class extends re{#t;#i;constructor(t,e){t=t||{},t.flush=t.flush||M.Z_NO_FLUSH,t.finishFlush=t.finishFlush||M.Z_FINISH,t.fullFlushFlag=M.Z_FULL_FLUSH,super(t,e),this.#t=t.level,this.#i=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#t!==t||this.#i!==e){this.flush(M.Z_SYNC_FLUSH),zi(this.handle,"zlib binding closed");let i=this.handle.flush;this.handle.flush=(r,n)=>{typeof r=="function"&&(n=r,r=this.flushFlag),this.flush(r),n?.()};try{this.handle.params(t,e)}finally{this.handle.flush=i}this.handle&&(this.#t=t,this.#i=e)}}}};ze=class extends Pe{#t;constructor(t){super(t,"Gzip"),this.#t=t&&!!t.portable}[Tt](t){return this.#t?(this.#t=false,t[9]=255,super[Tt](t)):super[Tt](t)}};Ue=class extends Pe{constructor(t){super(t,"Unzip")}};He=class extends re{constructor(t,e){t=t||{},t.flush=t.flush||M.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||M.BROTLI_OPERATION_FINISH,t.fullFlushFlag=M.BROTLI_OPERATION_FLUSH,super(t,e)}};We=class extends He{constructor(t){super(t,"BrotliCompress")}};Ge=class extends He{constructor(t){super(t,"BrotliDecompress")}};Ze=class extends re{constructor(t,e){t=t||{},t.flush=t.flush||M.ZSTD_e_continue,t.finishFlush=t.finishFlush||M.ZSTD_e_end,t.fullFlushFlag=M.ZSTD_e_flush,super(t,e)}};Ye=class extends Ze{constructor(t){super(t,"ZstdCompress")}};Ke=class extends Ze{constructor(t){super(t,"ZstdDecompress")}};Us=(s3,t)=>{if(Number.isSafeInteger(s3))s3<0?an(s3,t):hn(s3,t);else throw Error("cannot encode number outside of javascript safe integer range");return t};hn=(s3,t)=>{t[0]=128;for(var e=t.length;e>1;e--)t[e-1]=s3&255,s3=Math.floor(s3/256)};an=(s3,t)=>{t[0]=255;var e=false;s3=s3*-1;for(var i=t.length;i>1;i--){var r=s3&255;s3=Math.floor(s3/256),e?t[i-1]=Ws(r):r===0?t[i-1]=0:(e=true,t[i-1]=Gs(r))}};Hs=s3=>{let t=s3[0],e=t===128?cn(s3.subarray(1,s3.length)):t===255?ln(s3):null;if(e===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(e))throw Error("parsed number outside of javascript safe integer range");return e};ln=s3=>{for(var t=s3.length,e=0,i=false,r=t-1;r>-1;r--){var n=Number(s3[r]),o;i?o=Ws(n):n===0?o=n:(i=true,o=Gs(n)),o!==0&&(e-=o*Math.pow(256,t-r-1))}return e};cn=s3=>{for(var t=s3.length,e=0,i=t-1;i>-1;i--){var r=Number(s3[i]);r!==0&&(e+=r*Math.pow(256,t-i-1))}return e};Ws=s3=>(255^s3)&255;Gs=s3=>(255^s3)+1&255;Hi={};Ur(Hi,{code:()=>Ve,isCode:()=>ne,isName:()=>dn,name:()=>oe,normalFsTypes:()=>Ui});ne=s3=>oe.has(s3);dn=s3=>Ve.has(s3);Ui=new Set(["0","","1","2","3","4","5","6","7","D"]);oe=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]);Ve=new Map(Array.from(oe).map(s3=>[s3[1],s3[0]]));un=s3=>s3===void 0||s3<0?void 0:s3;F=class{cksumValid=false;needPax=false;nullBlock=false;block;path;mode;uid;gid;size;cksum;#t="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,i,r){Buffer.isBuffer(t)?this.decode(t,e||0,i,r):t&&this.#i(t)}decode(t,e,i,r){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let n=xt(t,e+156,1),o=Ui.has(n),h=o?i:void 0,a=o?r:void 0;if(this.path=h?.path??xt(t,e,100),this.mode=h?.mode??a?.mode??lt(t,e+100,8),this.uid=h?.uid??a?.uid??lt(t,e+108,8),this.gid=h?.gid??a?.gid??lt(t,e+116,8),this.size=un(h?.size??a?.size??lt(t,e+124,12)),this.mtime=h?.mtime??a?.mtime??Wi(t,e+136,12),this.cksum=lt(t,e+148,12),a&&this.#i(a,true),h&&this.#i(h),ne(n)&&(this.#t=n||"0"),this.#t==="0"&&this.path.slice(-1)==="/"&&(this.#t="5"),this.#t==="5"&&(this.size=0),this.linkpath=xt(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=h?.uname??a?.uname??xt(t,e+265,32),this.gname=h?.gname??a?.gname??xt(t,e+297,32),this.devmaj=h?.devmaj??a?.devmaj??lt(t,e+329,8)??0,this.devmin=h?.devmin??a?.devmin??lt(t,e+337,8)??0,t[e+475]!==0){let c=xt(t,e+345,155);this.path=c+"/"+this.path}else{let c=xt(t,e+345,130);c&&(this.path=c+"/"+this.path),this.atime=i?.atime??r?.atime??Wi(t,e+476,12),this.ctime=i?.ctime??r?.ctime??Wi(t,e+488,12)}let l3=256;for(let c=e;c<e+148;c++)l3+=t[c];for(let c=e+156;c<e+512;c++)l3+=t[c];this.cksumValid=l3===this.cksum,this.cksum===void 0&&l3===256&&(this.nullBlock=true)}#i(t,e=false){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([i,r])=>!(r==null||i==="size"&&Number(r)<0||i==="path"&&e||i==="linkpath"&&e||i==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#t==="Unsupported"&&(this.#t="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let i=this.ctime||this.atime?130:155,r=mn(this.path||"",i),n=r[0],o=r[1];this.needPax=!!r[2],this.needPax=Lt(t,e,100,n)||this.needPax,this.needPax=ct(t,e+100,8,this.mode)||this.needPax,this.needPax=ct(t,e+108,8,this.uid)||this.needPax,this.needPax=ct(t,e+116,8,this.gid)||this.needPax,this.needPax=ct(t,e+124,12,this.size)||this.needPax,this.needPax=Gi(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#t.codePointAt(0)),this.needPax=Lt(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Lt(t,e+265,32,this.uname)||this.needPax,this.needPax=Lt(t,e+297,32,this.gname)||this.needPax,this.needPax=ct(t,e+329,8,this.devmaj)||this.needPax,this.needPax=ct(t,e+337,8,this.devmin)||this.needPax,this.needPax=Lt(t,e+345,i,o)||this.needPax,t[e+475]!==0?this.needPax=Lt(t,e+345,155,o)||this.needPax:(this.needPax=Lt(t,e+345,130,o)||this.needPax,this.needPax=Gi(t,e+476,12,this.atime)||this.needPax,this.needPax=Gi(t,e+488,12,this.ctime)||this.needPax);let h=256;for(let a=e;a<e+148;a++)h+=t[a];for(let a=e+156;a<e+512;a++)h+=t[a];return this.cksum=h,ct(t,e+148,8,this.cksum),this.cksumValid=true,this.needPax}get type(){return this.#t==="Unsupported"?this.#t:oe.get(this.#t)}get typeKey(){return this.#t}set type(t){let e=String(Ve.get(t));if(ne(e)||e==="Unsupported")this.#t=e;else if(ne(t))this.#t=t;else throw new TypeError("invalid entry type: "+t)}};mn=(s3,t)=>{let i=s3,r="",n,o=Zt.parse(s3).root||".";if(Buffer.byteLength(i)<100)n=[i,r,false];else{r=Zt.dirname(i),i=Zt.basename(i);do Buffer.byteLength(i)<=100&&Buffer.byteLength(r)<=t?n=[i,r,false]:Buffer.byteLength(i)>100&&Buffer.byteLength(r)<=t?n=[i.slice(0,99),r,true]:(i=Zt.join(Zt.basename(r),i),r=Zt.dirname(r));while(r!==o&&n===void 0);n||(n=[s3.slice(0,99),"",true])}return n};xt=(s3,t,e)=>s3.subarray(t,t+e).toString("utf8").replace(/\0.*/,"");Wi=(s3,t,e)=>pn(lt(s3,t,e));pn=s3=>s3===void 0?void 0:new Date(s3*1e3);lt=(s3,t,e)=>Number(s3[t])&128?Hs(s3.subarray(t,t+e)):wn(s3,t,e);En=s3=>isNaN(s3)?void 0:s3;wn=(s3,t,e)=>En(parseInt(s3.subarray(t,t+e).toString("utf8").replace(/\0.*$/,"").trim(),8));Sn={12:8589934591,8:2097151};ct=(s3,t,e,i)=>i===void 0?false:i>Sn[e]||i<0?(Us(i,s3.subarray(t,t+e)),true):(yn(s3,t,e,i),false);yn=(s3,t,e,i)=>s3.write(Rn(i,e),t,e,"ascii");Rn=(s3,t)=>gn(Math.floor(s3).toString(8),t);gn=(s3,t)=>(s3.length===t-1?s3:new Array(t-s3.length-1).join("0")+s3+" ")+"\0";Gi=(s3,t,e,i)=>i===void 0?false:ct(s3,t,e,i.getTime()/1e3);bn=new Array(156).join("\0");Lt=(s3,t,e,i)=>i===void 0?false:(s3.write(i+bn,t,e,"utf8"),i.length!==Buffer.byteLength(i)||i.length>e);ft=class s{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(t,e=false){this.atime=t.atime,this.charset=t.charset,this.comment=t.comment,this.ctime=t.ctime,this.dev=t.dev,this.gid=t.gid,this.global=e,this.gname=t.gname,this.ino=t.ino,this.linkpath=t.linkpath,this.mtime=t.mtime,this.nlink=t.nlink,this.path=t.path,this.size=t.size,this.uid=t.uid,this.uname=t.uname}encode(){let t=this.encodeBody();if(t==="")return Buffer.allocUnsafe(0);let e=Buffer.byteLength(t),i=512*Math.ceil(1+e/512),r=Buffer.allocUnsafe(i);for(let n=0;n<512;n++)r[n]=0;new F({path:("PaxHeader/"+_n(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:e,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(r),r.write(t,512,e,"utf8");for(let n=e+512;n<r.length;n++)r[n]=0;return r}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(t){if(this[t]===void 0)return"";let e=this[t],i=e instanceof Date?e.getTime()/1e3:e,r=" "+(t==="dev"||t==="ino"||t==="nlink"?"SCHILY.":"")+t+"="+i+`
535
+ `;ABSENT_IDENTITY="absent:";V8_BACKFILL_PAGE=500}});import path6 from"path";function tNum(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0)return Number(envRaw);return typeof fileValue==="number"&&Number.isFinite(fileValue)?fileValue:NaN}function tNumLoose(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0&&envRaw!=="")return Number(envRaw);return typeof fileValue==="number"&&Number.isFinite(fileValue)?fileValue:NaN}function tInt(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0)return Number.parseInt(envRaw,10);return typeof fileValue==="number"&&Number.isFinite(fileValue)?fileValue:NaN}function tIntLoose(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0&&envRaw!=="")return Number.parseInt(envRaw,10);return typeof fileValue==="number"&&Number.isFinite(fileValue)?fileValue:NaN}function staggerKnobMs(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0&&envRaw!=="")return Number(envRaw);if(typeof fileValue==="number"&&Number.isFinite(fileValue))return fileValue;if(typeof fileValue==="string"){const ms2=parseDurationField(fileValue);if(ms2!==void 0)return ms2}return NaN}function fileNetwork(){return loadConfigFile().network??{}}function upstreamTimeoutMs(){const v3=tNum("BILI_UPSTREAM_TIMEOUT_MS",fileNetwork().upstreamTimeoutMs);return Number.isInteger(v3)&&v3>0?v3:UPSTREAM_TIMEOUT_MS}function upstreamCaFile(){const envRaw=process.env["BILI_CA_FILE"];if(envRaw!==void 0&&envRaw!=="")return envRaw;const fileValue=fileNetwork().caFile;return typeof fileValue==="string"&&fileValue!==""?fileValue:void 0}function replayMaxAttempts(){const v3=tNum("BILI_REPLAY_RETRY_MAX",fileNetwork().replayRetryMax);return Number.isInteger(v3)&&v3>=1?v3:REPLAY_MAX_ATTEMPTS}function replayBaseDelayMs(){const v3=tNum("BILI_REPLAY_RETRY_BASE_MS",fileNetwork().replayRetryBaseMs);return Number.isFinite(v3)&&v3>=0?v3:REPLAY_BASE_DELAY_MS}function maxShrinkPerCompress(){const v3=tNum("BILI_MAX_SHRINK_PER_COMPRESS",fileNetwork().maxShrinkPerCompress);return Number.isFinite(v3)&&v3>0&&v3<=1?v3:void 0}function streamKeepAliveMs(){const v3=tNumLoose("BILI_STREAM_KEEPALIVE_MS",fileNetwork().streamKeepAliveMs);return Number.isFinite(v3)&&v3>=0?Math.floor(v3):STREAM_KEEPALIVE_DEFAULT_MS}function preflightHoldGraceMs(){const v3=tNumLoose("BILI_PREFLIGHT_HOLD_MS",fileNetwork().preflightHoldMs);return Number.isFinite(v3)&&v3>=0?Math.floor(v3):PREFLIGHT_HOLD_GRACE_DEFAULT_MS}function proxyKeepAliveMaxMs(){const v3=tNum("BILI_PROXY_KEEPALIVE_MAX_MS",fileNetwork().proxyKeepAliveMaxMs);return Number.isFinite(v3)&&v3<0?PROXY_KEEPALIVE_MAX_MS:v3===0?0:Number.isFinite(v3)&&v3>0?Math.floor(v3):PROXY_KEEPALIVE_MAX_MS}function allowPrivateHttpProviders(){const envRaw=process.env.BILI_ALLOW_PRIVATE_HTTP_PROVIDERS;if(envRaw!==void 0)return envRaw==="1"||envRaw==="true";return fileNetwork().allowPrivateHttpProviders===true}function limitsReceiveBytes(){const v3=tInt("BILI_RECEIVE_BODY_BYTES",loadConfigFile().network?.receiveBodyBytes);return Number.isFinite(v3)&&v3>0?Math.floor(v3):DEFAULT_LIMITS_RECEIVE_BYTES}function limitsDecodedBytes(){const v3=tInt("BILI_DECODED_BODY_BYTES",loadConfigFile().network?.decodedBodyBytes);return Number.isFinite(v3)&&v3>0?Math.floor(v3):DEFAULT_LIMITS_DECODED_BYTES}function limitsOutboundBytes(){const v3=tInt("BILI_OUTBOUND_BODY_BYTES",loadConfigFile().network?.outboundBodyBytes);return Number.isFinite(v3)&&v3>0?Math.floor(v3):DEFAULT_LIMITS_OUTBOUND_BYTES}function limitsWsOutboundBytes(){const v3=tInt("BILI_WS_OUTBOUND_BYTES",loadConfigFile().network?.wsOutboundBytes);return Number.isFinite(v3)&&v3>=0?Math.floor(v3):DEFAULT_WS_OUTBOUND_BYTES}function filePersist(){return loadConfigFile().persist??{}}function persistEnabled(){const envRaw=process.env.BILI_PERSIST;if(envRaw!==void 0)return!(envRaw==="0"||envRaw==="false");return filePersist().enabled!==false}function autoModeForgeEnabled(){const envRaw=process.env.BILI_AUTO_MODE_FORGE;if(envRaw!==void 0)return!(envRaw==="0"||envRaw==="false");return loadConfigFile().autoModeForge?.enabled!==false}function guardrailBashTimeout(){const n=tNumLoose("BILI_GUARDRAIL_BASH_TIMEOUT",loadConfigFile().guardrails?.bashTimeout);if(!Number.isFinite(n))return 60;return n>0?Math.floor(n):void 0}function guardrailMaxOutputBytes(){const n=tNumLoose("BILI_GUARDRAIL_MAX_OUTPUT_BYTES",loadConfigFile().guardrails?.maxOutputBytes);if(!Number.isFinite(n))return 5e4;return n>0?Math.floor(n):void 0}function guardrailRepetition(){const envRaw=process.env.BILI_GUARDRAIL_REPETITION;if(envRaw!==void 0)return!(envRaw==="0"||envRaw==="false");return loadConfigFile().guardrails?.repetition!==false}function guardrailTextRunThreshold(){const n=tNumLoose("BILI_GUARDRAIL_TEXT_RUN_THRESHOLD",loadConfigFile().guardrails?.textRunThreshold);if(!Number.isFinite(n))return DEFAULT_TEXT_RUN_THRESHOLD;return n>0?Math.floor(n):0}function persistZstdEnabled(){const envRaw=process.env.BILI_PERSIST_ZSTD;if(envRaw!==void 0)return envRaw==="1"||envRaw==="true";return filePersist().zstd===true}function persistDebounceMs(){const v3=tInt("BILI_PERSIST_DEBOUNCE_MS",filePersist().debounceMs);return Number.isFinite(v3)&&v3>=0?v3:500}function persistTailTokens(){const v3=tInt("BILI_PERSIST_TAIL_TOKENS",filePersist().tailTokens);return Number.isFinite(v3)&&v3>=0?v3:16384}function persistEpermAlertThreshold(){const v3=tInt("BILI_PERSIST_EPERM_ALERT_THRESHOLD",filePersist().epermAlertThreshold);return Number.isFinite(v3)&&v3>0?v3:5}function persistEpermAlertRepeatMs(){const v3=tInt("BILI_PERSIST_EPERM_ALERT_REPEAT_MS",filePersist().epermAlertRepeatMs);return Number.isFinite(v3)&&v3>=0?v3:0}function maxSessions(){const envRaw=process.env.BILI_MAX_SESSIONS;const v3=envRaw!==void 0?Number.parseInt(envRaw,10):(()=>{const f2=loadConfigFile().sessions?.max;return typeof f2==="number"&&Number.isFinite(f2)?f2:NaN})();return Math.max(1,v3||256)}function sessionWarmMax(){const v3=tInt("BILI_SESSION_WARM_MAX",loadConfigFile().sessions?.warmMax);return Number.isFinite(v3)&&v3>=0?Math.floor(v3):0}function sessionWarmMaxBytes(){const v3=tInt("BILI_SESSION_WARM_MAX_BYTES",loadConfigFile().sessions?.warmMaxBytes);return Number.isFinite(v3)&&v3>=0?Math.floor(v3):64*1024*1024}function sessionResidentMaxBytes(){const v3=tInt("BILI_SESSION_RESIDENT_MAX_BYTES",loadConfigFile().sessions?.residentMaxBytes);return Number.isFinite(v3)&&v3>=0?Math.floor(v3):512*1024*1024}function gcSettings(){const gc=loadConfigFile().sessions?.gc??{};const envRaw=process.env.BILI_SESSION_GC;const enabled=envRaw!==void 0?["1","true","on"].includes(envRaw.toLowerCase()):gc.enabled===true;const ageDays=tIntLoose("BILI_SESSION_GC_MAX_AGE_DAYS",gc.maxAgeDays);const maxTokens=tIntLoose("BILI_SESSION_GC_MAX_TOKENS",gc.maxTokens);const intervalMs=tIntLoose("BILI_SESSION_GC_INTERVAL_MS",gc.intervalMs);return{enabled,maxAgeMs:(Number.isFinite(ageDays)&&ageDays>0?Math.floor(ageDays):7)*GC_DAY_MS,maxTokens:Number.isFinite(maxTokens)&&maxTokens>0?Math.floor(maxTokens):1e6,intervalMs:Number.isFinite(intervalMs)&&intervalMs>0?Math.floor(intervalMs):36e5}}function updateRegistryBase(){const envRaw=process.env.BILI_UPDATE_REGISTRY;if(envRaw!==void 0&&envRaw.trim().length>0)return envRaw.trim();const f2=loadConfigFile().update?.registry;return typeof f2==="string"&&f2.trim().length>0?f2.trim():void 0}function updateCheckIntervalMs(){const v3=tNumLoose("BILI_UPDATE_CHECK_INTERVAL_MS",loadConfigFile().update?.checkIntervalMs);return Number.isFinite(v3)&&v3>0?Math.floor(v3):3*60*1e3}function updatePolicyUrl(){const envRaw=process.env.BILI_UPDATE_POLICY_URL;if(envRaw!==void 0&&envRaw.trim().length>0)return envRaw.trim();const f2=loadConfigFile().update?.policyUrl;return typeof f2==="string"&&f2.trim().length>0?f2.trim():void 0}function updateStaggerMinDelayMs(){const v3=staggerKnobMs("BILI_UPDATE_STAGGER_MIN_MS",loadConfigFile().update?.staggerMinDelayMs);return Number.isInteger(v3)&&v3>=0?Math.floor(v3):void 0}function updateStaggerMaxDelayMs(){const v3=staggerKnobMs("BILI_UPDATE_STAGGER_MAX_MS",loadConfigFile().update?.staggerMaxDelayMs);return Number.isInteger(v3)&&v3>=0?Math.floor(v3):void 0}function publicSnapshotCapBytes(){const raw=process.env.BILI_PUBLIC_SNAPSHOT_CAP_BYTES;const v3=raw!==void 0?Number(raw):(()=>{const f2=loadConfigFile().plugin?.snapshotCapBytes;return typeof f2==="number"&&Number.isFinite(f2)?f2:NaN})();return Number.isFinite(v3)&&v3>=0?v3:104857600}function ccrRetrievalTtlMs(){const envRaw=process.env.BILI_CCR_RETRIEVAL_TTL_MS;const v3=envRaw===void 0||envRaw===""?(()=>{const f2=loadConfigFile().ccrRetrievalTtlMs;return typeof f2==="number"?f2:NaN})():Number(envRaw);return Number.isFinite(v3)&&v3>=0?v3:10*60*1e3}function codexCompactMode(){const envRaw=process.env.BILI_CODEX_COMPACT;if(envRaw!==void 0)return envRaw.trim().toLowerCase()==="pass"?"pass":"intercept";return loadConfigFile().codexCompact==="pass"?"pass":"intercept"}function dshAuthoredCompactionEnabled(){const envRaw=process.env.BILI_DSH_AUTHORED_COMPACTION;if(envRaw!==void 0)return envRaw.trim()!=="0";const file=loadConfigFile().dsh?.authoredCompaction;if(typeof file==="boolean")return file;return true}function decompressTmpCap(){const v3=tIntLoose("BILI_DECOMPRESS_TMP_CAP",loadConfigFile().decompressTmpCap);return Number.isFinite(v3)&&v3>0?v3:50}function imageRescaleEnabled(){const envRaw=process.env.BILI_IMAGE_RESCALE;if(envRaw!==void 0)return!(envRaw==="0"||envRaw==="false");return loadConfigFile().imageRescale!==false}function imageRescaleMaxDim(){const v3=tIntLoose("BILI_IMAGE_RESCALE_MAX_DIM",void 0);return Number.isInteger(v3)&&v3>=128?v3:IMAGE_RESCALE_DEFAULT_MAX_DIM}function fileDiag(){return loadConfigFile().diagnostics??{}}function bodyDumpEnabled(){const envRaw=process.env.ACP_DUMP_BODY;if(envRaw!==void 0)return envRaw==="1";return fileDiag().dumpBody===true}function dumpReqAllowed(){const envRaw=process.env.ACP_DUMP_REQ;if(envRaw!==void 0)return envRaw!=="0";return fileDiag().dumpReq!==false}function rawDumpDir(){const envRaw=process.env.ACP_RAW_DUMP_DIR;if(envRaw)return envRaw;const f2=fileDiag().rawDumpDir;if(typeof f2==="string"&&f2.trim().length>0)return f2;return path6.join(stateDir(),"raw")}function dump4xxEnabled(){const envRaw=process.env.BILI_DUMP_4XX;if(envRaw!==void 0)return envRaw==="1";return fileDiag().dump4xx===true}function dump4xxMaxBytes(){const envRaw=process.env.BILI_DUMP_4XX_MAX_BYTES;if(envRaw!==void 0)return Math.max(1024,Number(envRaw)||2*1024*1024);const f2=fileDiag().dump4xxMaxBytes;const n=typeof f2==="number"&&Number.isFinite(f2)&&f2>0?f2:NaN;return Math.max(1024,n||2*1024*1024)}function dumpGcMaxTotalBytes(){const envRaw=process.env.BILI_DUMP_MAX_TOTAL_BYTES;if(envRaw!==void 0){const v3=Number(envRaw);return Number.isFinite(v3)&&v3>0?Math.max(1<<20,v3):null}const f2=fileDiag().maxTotalBytes;if(typeof f2==="number"&&Number.isFinite(f2)&&f2>0)return Math.max(1<<20,f2);return null}function dumpGcMaxAgeMs(){const envRaw=process.env.BILI_DUMP_MAX_AGE_DAYS;if(envRaw!==void 0){const d2=Number(envRaw);return Number.isFinite(d2)&&d2>0?Math.max(1/24,d2)*864e5:null}const f2=fileDiag().maxAgeDays;if(typeof f2==="number"&&Number.isFinite(f2)&&f2>0)return Math.max(1/24,f2)*864e5;return null}function renderNone(){const envRaw=process.env.ACP_RENDER_NONE;if(envRaw!==void 0)return envRaw.length>0;return fileDiag().renderNone===true}function invariantJudgeEnabled(){const envRaw=process.env.BILI_INVARIANT_JUDGE;if(envRaw!==void 0)return!(envRaw==="0"||envRaw==="false"||envRaw==="off");const f2=fileDiag().invariantJudge;return typeof f2==="boolean"?f2:true}function noInjectTool(){const envRaw=process.env.ACP_NO_INJECT_TOOL;if(envRaw!==void 0)return envRaw.length>0;return fileDiag().noInjectTool===true}function noCompressPrompt(){const envRaw=process.env.ACP_NO_COMPRESS_PROMPT;if(envRaw!==void 0)return envRaw.length>0;return fileDiag().noCompressPrompt===true}function countTokensPassthrough(){const envRaw=process.env.ACP_COUNT_TOKENS_PASSTHROUGH;if(envRaw!==void 0)return envRaw==="1";return fileDiag().countTokensPassthrough===true}function forceTextProtocol(){const envRaw=process.env.ACP_COMPRESS_PROTOCOL;if(envRaw!==void 0)return envRaw==="text";return fileDiag().compressProtocol==="text"}function keepResponseId(){const envRaw=process.env.ACP_KEEP_RESPONSE_ID;if(envRaw!==void 0)return envRaw==="1";return loadConfigFile().compat?.keepResponseId===true}function noCacheControl(){const envRaw=process.env.BILI_NO_CACHE_CONTROL;if(envRaw!==void 0)return envRaw.length>0;return loadConfigFile().compat?.noCacheControl===true}function fakeCompletionRetries(){const v3=tInt("BILI_FAKE_COMPLETION_RETRIES",loadConfigFile().fakeCompletion?.retries);return Number.isFinite(v3)&&v3>=0?v3:0}function fakeBufCapBytes(){const v3=tInt("BILI_FAKE_BUF_CAP",loadConfigFile().fakeCompletion?.bufCapBytes);return Number.isFinite(v3)&&v3>0?v3:16*1024*1024}function fileStorageUnified(){const v3=loadConfigFile().storage?.unified;return typeof v3==="string"?v3:void 0}function fileStorageJsonWriter(){const v3=loadConfigFile().storage?.jsonWriter;return typeof v3==="string"?v3:void 0}function fileStorageAutoDownload(){const v3=loadConfigFile().storage?.sqliteAutoDownload;return typeof v3==="boolean"?v3:void 0}function fileStorageArchiveAfterDays(){const v3=loadConfigFile().storage?.archiveAfterDays;return typeof v3==="number"&&Number.isFinite(v3)&&v3>=0?v3:void 0}function fileStorageBackend(){const v3=loadConfigFile().storage?.backend;return typeof v3==="string"?v3:void 0}function fileStorageMysqlDsn(){const v3=loadConfigFile().storage?.mysql?.dsn;return typeof v3==="string"&&v3.trim().length>0?v3:void 0}function fileStorageWalJournalSizeLimit(){const v3=loadConfigFile().storage?.walJournalSizeLimitBytes;return typeof v3==="number"&&Number.isInteger(v3)&&v3>0?v3:void 0}function resolveArchiveAfterDays(env=process.env,fileDays){const raw=env.BILI_STORAGE_ARCHIVE_AFTER_DAYS?.trim();if(raw!==void 0&&raw!==""){const n=Number.parseInt(raw,10);if(Number.isFinite(n)&&n>=0)return n}if(typeof fileDays==="number"&&Number.isFinite(fileDays)&&fileDays>=0)return fileDays;return 365}function resolveStorageMode(env=process.env,fileUnified){const raw=env.BILI_STORAGE_UNIFIED?.trim().toLowerCase();if(raw){if(raw==="full"||raw==="unified")return"full";if(raw==="1"||raw==="true"||raw==="shadow")return"shadow";return"legacy"}const file=fileUnified?.trim().toLowerCase();if(file==="full")return"full";if(file==="shadow")return"shadow";if(file)return"legacy";return"full"}function resolveJsonWriterOff(env=process.env,fileValue){const raw=env.BILI_STORAGE_JSON_WRITER?.trim().toLowerCase();if(raw==="0"||raw==="false"||raw==="off")return true;if(raw==="1"||raw==="true"||raw==="on")return false;return fileValue?.trim().toLowerCase()==="off"}function resolveSnapshotShadow(env=process.env,fileShadow){const raw=env.BILI_SNAPSHOT_SHADOW?.trim().toLowerCase();if(raw==="1"||raw==="true"||raw==="on")return true;if(raw==="0"||raw==="false"||raw==="off")return false;return typeof fileShadow==="boolean"?fileShadow:true}function resolveSqliteAutoDownload(env=process.env,fileValue){const raw=env.BILI_SQLITE_AUTO_DOWNLOAD?.trim().toLowerCase();if(raw==="1"||raw==="true")return true;if(raw==="0"||raw==="false")return false;return typeof fileValue==="boolean"?fileValue:true}function resolveStorageWalJournalSizeLimit(env=process.env,fileValue){const raw=env.BILI_STORAGE_WAL_JOURNAL_SIZE_LIMIT_BYTES?.trim();if(raw){const n=Number(raw);if(Number.isInteger(n)&&n>0)return n}if(typeof fileValue==="number"&&Number.isInteger(fileValue)&&fileValue>0)return fileValue;return WAL_JOURNAL_SIZE_LIMIT}var STREAM_KEEPALIVE_DEFAULT_MS,PREFLIGHT_HOLD_GRACE_DEFAULT_MS,DEFAULT_LIMITS_RECEIVE_BYTES,DEFAULT_LIMITS_DECODED_BYTES,DEFAULT_LIMITS_OUTBOUND_BYTES,DEFAULT_WS_OUTBOUND_BYTES,DEFAULT_TEXT_RUN_THRESHOLD,GC_DAY_MS,IMAGE_RESCALE_DEFAULT_MAX_DIM;var init_knobs=__esm({"src/knobs.ts"(){"use strict";init_paths();init_config();init_duration();init_fetch_util();init_upstream_proxy();init_schema();STREAM_KEEPALIVE_DEFAULT_MS=15e3;PREFLIGHT_HOLD_GRACE_DEFAULT_MS=3e4;DEFAULT_LIMITS_RECEIVE_BYTES=5*1024*1024*1024;DEFAULT_LIMITS_DECODED_BYTES=10*1024*1024*1024;DEFAULT_LIMITS_OUTBOUND_BYTES=5*1024*1024*1024;DEFAULT_WS_OUTBOUND_BYTES=10*1024*1024;DEFAULT_TEXT_RUN_THRESHOLD=200;GC_DAY_MS=864e5;IMAGE_RESCALE_DEFAULT_MAX_DIM=1600}});import{readFileSync as readFileSync4,statSync as statSync2}from"fs";import*as tls2 from"tls";function readPem(path54){try{return[readFileSync4(path54,"utf8")]}catch(err2){log("warn",`[upstream-ca] CA file ${path54} unreadable (${err2.message}); ignoring \u2014 upstream TLS falls back to whatever else is trusted`);return[]}}function upstreamCaIdentity(now=Date.now()){const caFile=upstreamCaFile();if(!caFile){lastIdentity="none";return"none"}if(now-lastStatAt<IDENTITY_TTL_MS&&lastIdentity!=="none")return lastIdentity;let mtimeMs=0;try{mtimeMs=statSync2(caFile).mtimeMs}catch{}lastIdentity=`${caFile}\0${mtimeMs}`;lastStatAt=now;return lastIdentity}function upstreamExtraCa(){const identity=upstreamCaIdentity();if(identity==="none")return void 0;if(cacheKey===identity)return cacheValue;const merged=[...tls2.rootCertificates];const nodeExtra=process.env["NODE_EXTRA_CA_CERTS"];if(nodeExtra)merged.push(...readPem(nodeExtra));const caFile=upstreamCaFile();if(caFile)merged.push(...readPem(caFile));cacheKey=identity;cacheValue=merged;log("info",`[upstream-ca] upstream TLS trust extended with ${caFile} (${merged.length} certs total)`);return merged}var IDENTITY_TTL_MS,lastStatAt,lastIdentity,cacheKey,cacheValue;var init_upstream_ca=__esm({"src/upstream-ca.ts"(){"use strict";init_logger();init_knobs();IDENTITY_TTL_MS=3e4;lastStatAt=0;lastIdentity="none";cacheKey=null}});function checkOutboundBody(body){const bytes=typeof body==="string"?Buffer.byteLength(body):Buffer.isBuffer(body)?body.byteLength:0;if(bytes>limitsOutboundBytes())throw new OutboundBodyTooLargeError(bytes)}var MAX_REQUEST_BYTES,MAX_DECODED_REQUEST_BYTES,MAX_LARGE_DECODED_REQUESTS,largeDecodedRequests,DecodedRequestBusyError,DecodedRequestAdmission,OutboundBodyTooLargeError;var init_request_body_budget=__esm({"src/request-body-budget.ts"(){"use strict";init_knobs();MAX_REQUEST_BYTES=100*1024*1024;MAX_DECODED_REQUEST_BYTES=2*MAX_REQUEST_BYTES;MAX_LARGE_DECODED_REQUESTS=2;largeDecodedRequests=0;DecodedRequestBusyError=class extends Error{constructor(){super("large decoded request budget is busy; retry after an active request finishes");this.name="DecodedRequestBusyError"}};DecodedRequestAdmission=class{admitted=false;observe(bytes){if(bytes<=limitsReceiveBytes()||this.admitted)return;if(largeDecodedRequests>=MAX_LARGE_DECODED_REQUESTS)throw new DecodedRequestBusyError;largeDecodedRequests++;this.admitted=true}release(){if(!this.admitted)return;largeDecodedRequests--;this.admitted=false}};OutboundBodyTooLargeError=class extends Error{constructor(bytes){super(`rebuilt request exceeds ${limitsOutboundBytes()} bytes (${bytes} bytes); reduce historical images or content before retrying`);this.bytes=bytes;this.name="OutboundBodyTooLargeError"}bytes}}});function upstreamTimeoutMs2(){return upstreamTimeoutMs()}function directDispatcher(timeoutMs){const key2=`${timeoutMs}\0${upstreamCaIdentity()}`;let agent=directDispatchers.get(key2);if(!agent){const ca=upstreamExtraCa();agent=new import_undici.Agent({headersTimeout:timeoutMs,bodyTimeout:timeoutMs,...ca?{connect:{ca}}:{}});directDispatchers.set(key2,agent)}return agent}function restrictAcceptEncoding(headers){if(!headers)return headers;const entries2=[];if(typeof Headers!=="undefined"&&headers instanceof Headers){headers.forEach((v3,k2)=>entries2.push([k2,v3]))}else if(Array.isArray(headers)){for(const pair of headers)entries2.push([pair[0],String(pair[1])])}else{for(const[k2,v3]of Object.entries(headers))entries2.push([k2,String(v3)])}const out={};for(const[k2,v3]of entries2){if(k2.toLowerCase()!=="accept-encoding"){out[k2]=v3;continue}const kept=v3.split(",").map(part=>part.trim()).filter(part=>part!=="").filter(part=>DECODABLE_ENCODINGS.has(part.split(";")[0].trim().toLowerCase()));if(kept.length>0)out["accept-encoding"]=kept.join(", ")}return out}async function fetchWithTimeout(url,opts,timeoutMs,externalSignal,forceDirect){checkOutboundBody(opts.body);const effective=timeoutMs??upstreamTimeoutMs2();const controller=new AbortController;let cleared=false;const armTimer=()=>{const t=setTimeout(()=>{liveUpstreamTimers.delete(t);controller.abort()},idleTimerDelayOverrideMs??effective);liveUpstreamTimers.add(t);return t};let timer4=armTimer();const rearm=()=>{if(cleared)return;clearTimeout(timer4);liveUpstreamTimers.delete(timer4);idleRearmCount+=1;timer4=armTimer()};let onExternalAbort=null;if(externalSignal){if(externalSignal.aborted)controller.abort();else{onExternalAbort=()=>controller.abort();externalSignal.addEventListener("abort",onExternalAbort,{once:true})}}const stopIdleTimer=()=>{cleared=true;clearTimeout(timer4);liveUpstreamTimers.delete(timer4)};const cleanup=()=>{stopIdleTimer();if(onExternalAbort&&externalSignal)externalSignal.removeEventListener("abort",onExternalAbort)};try{const finalOpts={...opts,signal:controller.signal,dispatcher:opts.dispatcher??directDispatcher(idleTimerDelayOverrideMs??effective),redirect:opts.redirect??"manual",headers:restrictAcceptEncoding(opts.headers)};const transport=forceDirect?void 0:currentFetchTransport();const raw=transport?await transport(url,finalOpts):await fetch(url,finalOpts);if(raw.body){const wrapped=armIdleBody(raw.body,rearm);return{response:new Response(wrapped,{status:raw.status,statusText:raw.statusText,headers:raw.headers}),clearTimer:cleanup,stopIdleTimer}}return{response:raw,clearTimer:cleanup,stopIdleTimer}}catch(e){cleanup();throw e}}function armIdleBody(body,rearm){const reader=body.getReader();return new ReadableStream({async pull(controller){try{const result=await reader.read();if(result.done){controller.close();return}rearm();controller.enqueue(result.value)}catch(e){controller.error(e)}},async cancel(reason){try{await reader.cancel(reason)}catch{}}})}function isTransientUpstreamError(status,body){if(status===429||status>=500)return true;if(status<400)return false;const lower=body.toLowerCase();return TRANSIENT_BODY_MARKERS.some(marker=>lower.includes(marker))}function replayMaxAttempts2(){return replayMaxAttempts()}function replayBaseDelayMs2(){return replayBaseDelayMs()}function maxShrinkPerCompress2(){return maxShrinkPerCompress()}function replayBackoffMs(attempt){return replayBaseDelayMs2()*2**(attempt-1)}function sleep(ms2,signal){if(ms2<=0||signal?.aborted)return Promise.resolve();return new Promise(resolve=>{let timer4=null;const finish2=()=>{if(timer4)clearTimeout(timer4);if(signal)signal.removeEventListener("abort",finish2);resolve()};timer4=setTimeout(finish2,ms2);if(signal)signal.addEventListener("abort",finish2,{once:true})})}async function fetchWithRetry(url,opts,timeoutMs,externalSignal,onRetry){const maxAttempts=replayMaxAttempts2();for(let attempt=1;;attempt++){let result;try{result=await fetchWithTimeout(url,opts,timeoutMs,externalSignal)}catch(error){const kind=classifyUpstreamFailure(error,{viaProxy:opts.dispatcher!==void 0,externalAborted:externalSignal?.aborted===true});if(!isFailFastUpstreamKind(kind))throw error;const lastAttempt2=attempt>=maxAttempts;if(lastAttempt2)throw error;const delayMs=replayBackoffMs(attempt);onRetry?.({attempt,status:0,detail:`${kind} (pre-response network failure): ${error instanceof Error?error.message:String(error)}`,delayMs,maxAttempts});await sleep(delayMs,externalSignal);continue}if(result.response.ok)return result;const errText2=await result.response.text().catch(()=>"upstream error");result.clearTimer();const lastAttempt=attempt>=maxAttempts;if(!lastAttempt&&isTransientUpstreamError(result.response.status,errText2)){const delayMs=replayBackoffMs(attempt);onRetry?.({attempt,status:result.response.status,detail:errText2,delayMs,maxAttempts});await sleep(delayMs,externalSignal);continue}throw new UpstreamHttpError(result.response.status,errText2,attempt)}}async function fetchWithTransportRetry(url,opts,timeoutMs,externalSignal,onRetry){const maxAttempts=replayMaxAttempts2();for(let attempt=1;;attempt++){try{return await fetchWithTimeout(url,opts,timeoutMs,externalSignal)}catch(error){const kind=classifyUpstreamFailure(error,{viaProxy:opts.dispatcher!==void 0,externalAborted:externalSignal?.aborted===true});if(!isFailFastUpstreamKind(kind))throw error;const lastAttempt=attempt>=maxAttempts;if(lastAttempt)throw error;const delayMs=replayBackoffMs(attempt);onRetry?.({attempt,status:0,detail:`${kind} (pre-response network failure): ${error instanceof Error?error.message:String(error)}`,delayMs,maxAttempts});await sleep(delayMs,externalSignal)}}}var import_undici,UPSTREAM_TIMEOUT_MS,liveUpstreamTimers,idleTimerDelayOverrideMs,idleRearmCount,directDispatchers,DECODABLE_ENCODINGS,UpstreamHttpError,TRANSIENT_BODY_MARKERS,REPLAY_MAX_ATTEMPTS,REPLAY_BASE_DELAY_MS;var init_fetch_util=__esm({"src/fetch-util.ts"(){"use strict";import_undici=__toESM(require_undici(),1);init_fetch_transport();init_upstream_fail();init_upstream_ca();init_knobs();init_request_body_budget();init_request_body_budget();UPSTREAM_TIMEOUT_MS=12*60*1e3;liveUpstreamTimers=new Set;idleTimerDelayOverrideMs=null;idleRearmCount=0;directDispatchers=new Map;DECODABLE_ENCODINGS=new Set(["gzip","x-gzip","deflate","br"]);UpstreamHttpError=class extends Error{status;body;attempts;constructor(status,body,attempts){super(`upstream error ${status}`);this.name="UpstreamHttpError";this.status=status;this.body=body;this.attempts=attempts}};TRANSIENT_BODY_MARKERS=["captcha","verify failed","risk control","\u98CE\u63A7","rate limit","too many requests","try again"];REPLAY_MAX_ATTEMPTS=3;REPLAY_BASE_DELAY_MS=1500}});import{execFileSync as execFileSync3}from"child_process";import net from"net";import tls3 from"tls";function defaultPort(protocol){return protocol==="https:"?443:80}function hostIsLoopback(host){const normalized=host.replace(/^\[|\]$/g,"").toLowerCase();return normalized==="localhost"||normalized==="0.0.0.0"||normalized==="::"||normalized==="::1"||normalized==="0:0:0:0:0:0:0:1"||normalized.startsWith("127.")||normalized.startsWith("::ffff:127.")||/^::ffff:7f[0-9a-f]{2}:/.test(normalized)}function proxyAuthorization(url){if(!url.username&&!url.password)return void 0;const username=decodeURIComponent(url.username);const password=decodeURIComponent(url.password);return`Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`}function parseHttpProxy(proxy,biliPort){if(!proxy||typeof proxy!=="string"||!proxy.trim())return void 0;const candidate=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(proxy.trim())?proxy.trim():`http://${proxy.trim()}`;let url;try{url=new URL(candidate)}catch{return void 0}if(url.protocol!=="http:"&&url.protocol!=="https:")return void 0;if(url.pathname&&url.pathname!=="/"||url.search||url.hash)return void 0;const port=url.port?Number.parseInt(url.port,10):defaultPort(url.protocol);if(!Number.isInteger(port)||port<1||port>65535)return void 0;if(biliPort&&hostIsLoopback(url.hostname)&&port===biliPort){throw new Error(`upstream proxy would loop back into bili: ${redactProxyUrl(url.href)}`)}return{url:url.href,host:url.hostname,port,protocol:url.protocol,...proxyAuthorization(url)?{authorization:proxyAuthorization(url)}:{}}}function unsupportedProxyScheme(proxy){if(!proxy||typeof proxy!=="string"||!proxy.trim())return void 0;const candidate=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(proxy.trim())?proxy.trim():`http://${proxy.trim()}`;let url;try{url=new URL(candidate)}catch{return void 0}return url.protocol==="http:"||url.protocol==="https:"?void 0:url.protocol.replace(/:$/,"")}function warnUnsupportedScheme(source,value,scheme){const key2=`${source}\0${scheme}`;if(warnedUnsupportedSchemes.has(key2))return;warnedUnsupportedSchemes.add(key2);log("warn",`[upstream-proxy] ignoring ${source}=${redactProxyUrl(value)}: scheme "${scheme}" is not supported \u2014 only http:// and https:// proxy origins work. For Clash/mihomo, point bili at the same mixed port over http:// (e.g. http://127.0.0.1:7890).`)}function validateHttpProxy(proxy,biliPort){if(!proxy?.trim())return;const scheme=unsupportedProxyScheme(proxy);if(scheme){throw new Error(`upstream proxy uses unsupported scheme "${scheme}" (${redactProxyUrl(proxy)}) \u2014 only http:// and https:// proxies are supported; for Clash/mihomo use the same mixed port over http:// (e.g. http://127.0.0.1:7890)`)}if(!parseHttpProxy(proxy,biliPort)){throw new Error(`upstream proxy must be an HTTP/HTTPS proxy origin: ${redactProxyUrl(proxy)}`)}}function targetUrl(upstreamUrl){if(!upstreamUrl)return void 0;try{return new URL(upstreamUrl.replace(/^mitm:\/\//,"https://"))}catch{return void 0}}function parseFallbackProxy(proxy,biliPort){try{return parseHttpProxy(proxy,biliPort)}catch{return void 0}}function wildcardHostMatch(host,token){const pattern="^"+token.split("*").map(part=>part.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*")+"$";return new RegExp(pattern).test(host)}function matchesNoProxy(target,noProxy,options={}){if(!noProxy)return false;const host=target.hostname.replace(/^\[|\]$/g,"").toLowerCase();const port=target.port?Number.parseInt(target.port,10):defaultPort(target.protocol);for(const raw of noProxy.split(/[;,]/)){let token=raw.trim().toLowerCase();if(!token)continue;if(token==="*")return true;if(token==="<local>"&&!host.includes("."))return true;let tokenPort;if(token.startsWith("[")){const bracket=token.indexOf("]");if(bracket>0&&token[bracket+1]===":"){tokenPort=Number.parseInt(token.slice(bracket+2),10);token=token.slice(1,bracket)}else token=token.replace(/^\[|\]$/g,"")}else{const colon=token.lastIndexOf(":");if(colon>0&&token.indexOf(":")===colon&&/^\d+$/.test(token.slice(colon+1))){tokenPort=Number.parseInt(token.slice(colon+1),10);token=token.slice(0,colon)}}if(tokenPort!==void 0&&tokenPort!==port)continue;if(options.windowsBypass&&!token.startsWith("*")&&token.includes("*")&&wildcardHostMatch(host,token))return true;const suffix=token.startsWith("*.")?token.slice(1):token.startsWith(".")?token:void 0;if(suffix?host.endsWith(suffix)||host===suffix.slice(1):host===token)return true}return false}function parseWindowsProxyServer(value){const trimmed=value.trim();if(!trimmed)return{};if(!trimmed.includes("=")){const normalized=parseHttpProxy(trimmed)?.url;return normalized?{http:normalized,https:normalized}:{}}const result={};for(const item of trimmed.split(";")){const[scheme,address]=item.split("=",2).map(part=>part?.trim());const normalizedScheme=scheme?.toLowerCase();if((normalizedScheme==="http"||normalizedScheme==="https")&&address){const normalized=parseHttpProxy(address)?.url;if(normalized)result[normalizedScheme]=normalized}}return result}function registryValue(output,name){const escaped=name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return output.match(new RegExp(`^\\s*${escaped}\\s+REG_\\w+\\s+(.+)$`,"mi"))?.[1]?.trim()}function readWindowsSystemProxy(){if(process.platform!=="win32")return{enabled:false};const now=Date.now();if(windowsProxyCache&&now-windowsProxyCache.at<5e3)return windowsProxyCache.value;let value={enabled:false};try{const output=execFileSync3("reg",["query","HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"],{encoding:"utf8",windowsHide:true,timeout:3e3,stdio:["ignore","pipe","ignore"]});const enabledRaw=registryValue(output,"ProxyEnable");const enabled=enabledRaw==="0x1"||enabledRaw==="1";const staticProxy=enabled?parseWindowsProxyServer(registryValue(output,"ProxyServer")??""):{};value={enabled,...staticProxy,...registryValue(output,"ProxyOverride")?{bypass:registryValue(output,"ProxyOverride")}:{},...registryValue(output,"AutoConfigURL")?{autoConfigUrl:registryValue(output,"AutoConfigURL")}:{}}}catch{}windowsProxyCache={at:now,value};return value}function resolveProxyDecision(routes,globalProxy,upstreamUrl,fallback={}){const target=targetUrl(upstreamUrl);let bestKey="";if(upstreamUrl){for(const key2 of Object.keys(routes)){if(upstreamUrl===key2||upstreamUrl.startsWith(key2+"/")){if(key2.length>bestKey.length)bestKey=key2}}}if(bestKey){const routeProxy=routes[bestKey].proxy;if(routeProxy!==void 0){if(!routeProxy.trim())return{source:"provider-direct"};const parsed=parseHttpProxy(routeProxy,fallback.biliPort);if(!parsed)throw new Error(`invalid per-URL upstream proxy for ${bestKey}: ${redactProxyUrl(routeProxy)}`);return{proxy:parsed.url,source:"provider"}}}if(globalProxy===""&&fallback.explicitDirect){if(!fallback.defaultDirect)return{source:"direct"};const peek=autoDetectProxy(target,fallback);return peek.proxy?{source:"direct",skippedProxy:{proxy:peek.proxy,source:peek.source}}:{source:"direct"}}const explicit=parseHttpProxy(globalProxy,fallback.biliPort)?.url;if(explicit)return{proxy:explicit,source:fallback.globalSource??"global"};return autoDetectProxy(target,fallback)}function autoDetectProxy(target,fallback){if(target&&matchesNoProxy(target,fallback.noProxy))return{source:"no-proxy"};const environmentCandidates=target?.protocol==="http:"?[["HTTP_PROXY",fallback.httpProxy],["ALL_PROXY",fallback.allProxy]]:[["HTTPS_PROXY",fallback.httpsProxy],["HTTP_PROXY",fallback.httpProxy],["ALL_PROXY",fallback.allProxy]];for(const[source,value]of environmentCandidates){const parsed=parseFallbackProxy(value,fallback.biliPort);if(parsed)return{proxy:parsed.url,source};if(!value)continue;const scheme=unsupportedProxyScheme(value);if(scheme)warnUnsupportedScheme(source,value,scheme)}const system=fallback.systemProxy??readWindowsSystemProxy();if(target&&matchesNoProxy(target,system.bypass,{windowsBypass:true})){return{source:"windows-bypass",...system.autoConfigUrl?{autoConfigUrl:system.autoConfigUrl}:{}}}const systemValue=target?.protocol==="http:"?system.http:system.https??system.http;const systemScheme=unsupportedProxyScheme(systemValue);if(systemValue&&systemScheme)warnUnsupportedScheme("windows-system",systemValue,systemScheme);const systemProxy=parseFallbackProxy(systemValue,fallback.biliPort)?.url;if(systemProxy){return{proxy:systemProxy,source:"windows-system",...system.autoConfigUrl?{autoConfigUrl:system.autoConfigUrl}:{}}}return{source:"direct",...system.autoConfigUrl?{autoConfigUrl:system.autoConfigUrl}:{}}}function resolveProxy(routes,globalProxy,upstreamUrl,fallback={}){return resolveProxyDecision(routes,globalProxy,upstreamUrl,fallback).proxy}function proxyKeepAliveMaxMs2(){return proxyKeepAliveMaxMs()}function proxyDispatcher(proxyUrl,timeoutMs){if(!proxyUrl)return void 0;const t=timeoutMs??upstreamTimeoutMs2();const ka=proxyKeepAliveMaxMs2();const key2=`${proxyUrl}\0${t}\0${ka}\0${upstreamCaIdentity()}`;let agent=dispatcherCache.get(key2);if(!agent){const withTimeouts=options=>{const capped={...options,headersTimeout:t,bodyTimeout:t};if(ka>0){capped.keepAliveTimeout=Math.min(typeof capped.keepAliveTimeout==="number"?capped.keepAliveTimeout:ka,ka);capped.keepAliveMaxTimeout=ka}return capped};const base={uri:proxyUrl,headersTimeout:t,bodyTimeout:t,factory:(origin,options)=>new import_undici2.Pool(origin,withTimeouts(options)),clientFactory:(origin,options)=>new import_undici2.Pool(origin,withTimeouts(options))};const ca=upstreamExtraCa();const withConnect=ca?{...base,connect:{ca}}:base;agent=ka>0?new import_undici2.ProxyAgent({...withConnect,keepAliveTimeout:ka,keepAliveMaxTimeout:ka}):new import_undici2.ProxyAgent(withConnect);dispatcherCache.set(key2,agent)}return agent}function resetProxyCache(){for(const agent of dispatcherCache.values()){try{void agent.close().catch(()=>void 0)}catch{}}dispatcherCache.clear();lastConnection={}}function errorChain(error){const chain=[];const seen=new Set;let current=error;while(current&&!seen.has(current)){seen.add(current);if(current instanceof Error){const record3={message:current.message};for(const key2 of["code","errno","syscall","address","port"]){const value=current[key2];if(value!==void 0)record3[key2]=value}chain.push(record3);current=current.cause}else{chain.push({message:String(current)});break}}return chain}function describeUpstreamFailure(error,url,proxyUrl,skipped){const chain=errorChain(error);const kind=classifyUpstreamFailure(error,{viaProxy:proxyUrl!==void 0});const fields=["code","errno","syscall","address","port"];const parts=[`kind=${kind}`];const maskHostIn=s3=>{try{return maskHostInText(s3,new URL(url).hostname)}catch{}return s3};let codeValue;for(const field of fields){const value=chain.find(entry=>entry[field]!==void 0)?.[field];if(value!==void 0){if(field==="code"&&codeValue===void 0)codeValue=value;parts.push(`${field}=${maskHostIn(String(value))}`)}}const messages=chain.map(entry=>maskHostIn(String(entry.message??""))).filter(Boolean);if(messages.length>0)parts.push(`message=${messages.join(" <- ")}`);parts.push(`url=${maskUrlForLog(url)}`);parts.push(`proxy=${redactProxyUrl(proxyUrl)??"direct"}`);let hint=hintWithSkippedProxy(kind,skipped);if(kind==="tls"&&chain.some(entry=>isTlsTrustCode(entry.code))){hint=`${hint}; ${tlsTrustRemediation()}`}parts.push(`hint=${hint}`);return{message:parts.join(" "),detail:{kind,...codeValue!==void 0?{code:String(codeValue)}:{},hint}}}function formatUpstreamError(error,url,proxyUrl,skipped){return describeUpstreamFailure(error,url,proxyUrl,skipped).message}function recordUpstreamConnection(url,proxyUrl,error,skipped){lastConnection={url,proxy:redactProxyUrl(proxyUrl),connected:error===void 0,...error===void 0?{}:{error:formatUpstreamError(error,url,proxyUrl,skipped)},checkedAt:new Date().toISOString()}}function getUpstreamConnectionStatus(){return{...lastConnection}}var import_undici2,dispatcherCache,lastConnection,windowsProxyCache,warnedUnsupportedSchemes,PROXY_KEEPALIVE_MAX_MS;var init_upstream_proxy=__esm({"src/upstream-proxy.ts"(){"use strict";import_undici2=__toESM(require_undici(),1);init_logger();init_log_mask();init_fetch_util();init_upstream_fail();init_upstream_ca();init_knobs();dispatcherCache=new Map;lastConnection={};warnedUnsupportedSchemes=new Set;PROXY_KEEPALIVE_MAX_MS=55e3}});function normalizeVertexModelId(id){const trimmed=id.trim();const at2=trimmed.indexOf("@");return at2>0?trimmed.slice(0,at2):trimmed}var init_vertex=__esm({"src/vertex.ts"(){"use strict"}});import fs2 from"fs";import os2 from"os";import path7 from"path";function toModelWindow(id,contextWindow,maxOutput){if(typeof id!=="string"||id.length===0||typeof contextWindow!=="number"||!Number.isFinite(contextWindow)||contextWindow<=0)return null;const win={id,contextWindow:Math.floor(contextWindow)};if(typeof maxOutput==="number"&&Number.isFinite(maxOutput)&&maxOutput>0)win.maxOutput=Math.floor(maxOutput);return win}function nonEmpty2(s3){return typeof s3==="string"&&s3.trim().length>0}function resolvePiHome(env){const h=os2.homedir();return nonEmpty2(env.PI_CODING_AGENT_DIR)?env.PI_CODING_AGENT_DIR:nonEmpty2(env.PI_HOME)?env.PI_HOME:path7.join(h,".pi","agent")}function resolveOmpHome(env){const h=os2.homedir();return nonEmpty2(env.PI_CODING_AGENT_DIR)?env.PI_CODING_AGENT_DIR:path7.join(h,".omp","agent")}function resolveHermesHome(env){const h=os2.homedir();return nonEmpty2(env.HERMES_HOME)?env.HERMES_HOME:path7.join(h,".hermes")}function resolveDshHome(env){const h=os2.homedir();return nonEmpty2(env.DSH_HOME)?env.DSH_HOME:path7.join(h,".dsh")}function resolveCodexHome(env){const h=os2.homedir();return nonEmpty2(env.CODEX_HOME)?env.CODEX_HOME:path7.join(h,".codex")}function parseCodexToml(text2){const result={providers:{}};let table="";let curProvider=null;let codexModel;let codexContextWindow;let codexAutoCompactLimit;let codexMaxOutput;for(const rawLine of text2.split(/\r?\n/)){const line=rawLine.trim();if(!line||line.startsWith("#"))continue;const tableMatch=/^\[([^\]]+)\]$/.exec(line);if(tableMatch){table=tableMatch[1].trim();curProvider=table.startsWith("model_providers.")?table.slice("model_providers.".length).trim():null;if(curProvider&&!result.providers[curProvider]){result.providers[curProvider]={}}continue}const strMatch=/^([A-Za-z0-9_.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(line);const numMatch=/^([A-Za-z0-9_.-]+)\s*=\s*([0-9]+)\b/.exec(line);if(strMatch){const key2=strMatch[1];const val=strMatch[2]!==void 0?strMatch[2]:strMatch[3];if(table===""){if(key2==="model_provider")result.modelProvider=val;else if(key2==="openai_base_url")result.openaiBaseUrl=val;else if(key2==="model")codexModel=val}else if(curProvider&&key2==="base_url"){result.providers[curProvider].baseUrl=val}}else if(numMatch&&table===""){if(numMatch[1]==="model_context_window")codexContextWindow=Number(numMatch[2]);else if(numMatch[1]==="model_auto_compact_token_limit")codexAutoCompactLimit=Number(numMatch[2]);else if(numMatch[1]==="model_max_output_tokens")codexMaxOutput=Number(numMatch[2])}}if(codexModel)result.model=codexModel;if(codexContextWindow)result.contextWindow=codexContextWindow;if(codexAutoCompactLimit)result.autoCompactLimit=codexAutoCompactLimit;if(codexMaxOutput)result.maxOutput=codexMaxOutput;const win=toModelWindow(codexModel,codexContextWindow,codexMaxOutput);if(win)result.modelWindows=[win];return result}function readCodexConfig(codexHome){const cfgPath=path7.join(codexHome,"config.toml");let text2;try{text2=fs2.readFileSync(cfgPath,"utf8")}catch{return{providers:{}}}return parseCodexToml(text2)}function resolveKimiHome(env=process.env){return nonEmpty2(env.KIMI_CODE_HOME)?env.KIMI_CODE_HOME:path7.join(os2.homedir(),".kimi-code")}function parseConfigText(text2){let parsed;try{parsed=JSON.parse(text2)}catch{const errors=[];parsed=parse2(text2,errors,{allowTrailingComma:true})}if(parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed))return parsed;return void 0}function readConfigFileRoot(file){try{return parseConfigText(fs2.readFileSync(file,"utf8"))}catch{return void 0}}function mergeConfigDeep(target,source){const out={...target};for(const[key2,value]of Object.entries(source)){const existing=out[key2];out[key2]=value!==null&&typeof value==="object"&&!Array.isArray(value)&&existing!==null&&typeof existing==="object"&&!Array.isArray(existing)?mergeConfigDeep(existing,value):value}return out}function readOpencodeConfigRoot(env){let root;const xdg2=nonEmpty2(env.XDG_CONFIG_HOME)?env.XDG_CONFIG_HOME:path7.join(os2.homedir(),".config");const dir=path7.join(xdg2,"opencode");for(const file of["config.json","opencode.json","opencode.jsonc"]){const next=readConfigFileRoot(path7.join(dir,file));if(next!==void 0)root=root===void 0?next:mergeConfigDeep(root,next)}if(nonEmpty2(env.OPENCODE_CONFIG)){const next=readConfigFileRoot(env.OPENCODE_CONFIG);if(next!==void 0)root=root===void 0?next:mergeConfigDeep(root,next)}return root}var TOML_KEY_PART_RE,OPENCODE_CONFIG_FILES;var init_client_config=__esm({"src/client-config.ts"(){"use strict";init_main();init_vertex();TOML_KEY_PART_RE=new RegExp(String.raw`^(?:[A-Za-z0-9_-]+|"(?:[^"\\\n]|\\.)*"|'(?:[^'\n])*')(?:\.(?:[A-Za-z0-9_-]+|"(?:[^"\\\n]|\\.)*"|'(?:[^'\n])*'))*$`);OPENCODE_CONFIG_FILES=["opencode.jsonc","opencode.json","config.json"]}});import{createHash as createHash6,randomUUID}from"crypto";import fs4 from"fs";import os4 from"os";import path9 from"path";function isProxyInstanceFile(v3){return v3!==void 0&&"instanceId"in v3}function readProxyInstanceFile(file){let raw;try{raw=fs4.readFileSync(file??instanceFilePath(),"utf8").trim()}catch{return void 0}if(raw.startsWith("{")){try{const parsed=JSON.parse(raw);if(typeof parsed.origin==="string"&&/^https?:\/\/\S+$/.test(parsed.origin)){const windows={};if(parsed.modelWindows&&typeof parsed.modelWindows==="object"){for(const[k2,v3]of Object.entries(parsed.modelWindows)){const n=Number(v3);if(Number.isFinite(n)&&n>0)windows[k2]=n}}const maxOutputs={};if(parsed.modelMaxOutputs&&typeof parsed.modelMaxOutputs==="object"){for(const[k2,v3]of Object.entries(parsed.modelMaxOutputs)){const n=Number(v3);if(Number.isFinite(n)&&n>0)maxOutputs[k2]=n}}return{origin:parsed.origin,instanceId:typeof parsed.instanceId==="string"?parsed.instanceId:"",pid:typeof parsed.pid==="number"?parsed.pid:0,startedAt:typeof parsed.startedAt==="number"?parsed.startedAt:0,host:typeof parsed.host==="string"?parsed.host:"",port:typeof parsed.port==="number"?parsed.port:0,passthrough:Boolean(parsed.passthrough),mitmDomains:Array.isArray(parsed.mitmDomains)?parsed.mitmDomains.map(String):[],modelWindows:windows,modelMaxOutputs:Object.keys(maxOutputs).length>0?maxOutputs:void 0,launchToken:typeof parsed.launchToken==="string"?parsed.launchToken:void 0,lane:typeof parsed.lane==="string"&&parsed.lane!==""?parsed.lane:void 0,codeFingerprint:typeof parsed.codeFingerprint==="string"&&parsed.codeFingerprint!==""?parsed.codeFingerprint:void 0}}}catch{}}if(/^https?:\/\/\S+$/.test(raw))return{origin:raw};return void 0}function instanceFilePath(){return path9.join(stateDir(),"proxy-origin")}function portZoneFilePath(){return path9.join(stateDir(),"port-zone.json")}function readZonePort(lane,file=portZoneFilePath()){let raw;try{raw=fs4.readFileSync(file,"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);const v3=parsed?.lanes?.[lane];if(typeof v3==="number"&&Number.isInteger(v3)&&v3>0&&v3<65536)return v3;return void 0}catch{return void 0}}function writeZonePort(lane,port,file=portZoneFilePath()){if(!Number.isInteger(port)||port<=0||port>=65536)return;let cur={};try{const parsed=JSON.parse(fs4.readFileSync(file,"utf8"));if(parsed!==null&&typeof parsed==="object"&&parsed.lanes!==null&&typeof parsed.lanes==="object")cur=parsed}catch{}atomicWriteJson({lanes:{...cur.lanes??{},[lane]:port}},file)}function lanePreferredPort(lane,env=process.env,file=portZoneFilePath()){return readZonePort(lane,file)??resolveZonePortBase(env)}function entryScriptFingerprint(scriptPath){if(!scriptPath)return void 0;const resolved=path9.resolve(scriptPath);const cached=scriptFingerprints.get(resolved);if(cached!==void 0)return cached;let digest;try{digest=createHash6("sha256").update(fs4.readFileSync(resolved)).digest("hex")}catch{return void 0}scriptFingerprints.set(resolved,digest);return digest}function atomicWriteJson(obj,filePath){fs4.mkdirSync(path9.dirname(filePath),{recursive:true});const tempPath=`${filePath}.${process.pid}.${randomUUID()}.tmp`;let descriptor;try{descriptor=fs4.openSync(tempPath,"wx",420);fs4.writeSync(descriptor,JSON.stringify(obj)+"\n",null,"utf8");fs4.fsyncSync(descriptor);fs4.closeSync(descriptor);descriptor=void 0;fs4.renameSync(tempPath,filePath)}catch(error){if(descriptor!==void 0){try{fs4.closeSync(descriptor)}catch{}}try{fs4.unlinkSync(tempPath)}catch{}throw error}}function startingMarkerPath(){return path9.join(stateDir(),"proxy-starting")}function readStartingMarker(file){let raw;try{raw=fs4.readFileSync(file??startingMarkerPath(),"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);if(typeof parsed.token!=="string"||parsed.token==="")return void 0;if(typeof parsed.pid!=="number"||!Number.isInteger(parsed.pid)||parsed.pid<=0)return void 0;if(typeof parsed.startedAt!=="number")return void 0;return{token:parsed.token,pid:parsed.pid,host:typeof parsed.host==="string"?parsed.host:"",port:typeof parsed.port==="number"?parsed.port:0,startedAt:parsed.startedAt,...typeof parsed.lane==="string"&&parsed.lane!==""?{lane:parsed.lane}:{}}}catch{return void 0}}function claimStartingMarker(marker,file){const filePath=file??startingMarkerPath();let descriptor;try{fs4.mkdirSync(path9.dirname(filePath),{recursive:true});descriptor=fs4.openSync(filePath,"wx",420);fs4.writeSync(descriptor,JSON.stringify(marker)+"\n",null,"utf8");fs4.fsyncSync(descriptor);descriptor=void 0;return true}catch{if(descriptor!==void 0){try{fs4.closeSync(descriptor)}catch{}}return false}}function clearStartingMarker(token,file){const filePath=file??startingMarkerPath();const current=readStartingMarker(filePath);if(current&&current.token===token){try{fs4.unlinkSync(filePath)}catch{}}}function removeStartingMarker(file){try{fs4.unlinkSync(file??startingMarkerPath())}catch{}}function isPidAlive(pid){if(!Number.isInteger(pid)||pid<=0)return false;try{process.kill(pid,0);return true}catch(err2){return err2.code==="EPERM"}}function registryDirPath(){return path9.join(stateDir(),"instances")}function legacyRegistryFilePath(){return path9.join(stateDir(),"instances.json")}function safeReadJson2(file){try{return JSON.parse(fs4.readFileSync(file,"utf8"))}catch{return void 0}}function coerceEntry(value){if(!value||typeof value!=="object")return void 0;const o=value;if(typeof o.instanceId!=="string"||o.instanceId==="")return void 0;const windows={};if(o.modelWindows&&typeof o.modelWindows==="object"){for(const[k2,v3]of Object.entries(o.modelWindows)){const n=Number(v3);if(Number.isFinite(n)&&n>0)windows[k2]=n}}const maxOutputs={};if(o.modelMaxOutputs&&typeof o.modelMaxOutputs==="object"){for(const[k2,v3]of Object.entries(o.modelMaxOutputs)){const n=Number(v3);if(Number.isFinite(n)&&n>0)maxOutputs[k2]=n}}return{instanceId:o.instanceId,pid:typeof o.pid==="number"?o.pid:0,port:typeof o.port==="number"?o.port:0,origin:typeof o.origin==="string"?o.origin:"",startedAt:typeof o.startedAt==="number"?o.startedAt:0,...typeof o.host==="string"&&o.host!==""?{host:o.host}:{},...typeof o.passthrough==="boolean"?{passthrough:o.passthrough}:{},...Array.isArray(o.mitmDomains)?{mitmDomains:o.mitmDomains.map(String)}:{},...Object.keys(windows).length>0?{modelWindows:windows}:{},...Object.keys(maxOutputs).length>0?{modelMaxOutputs:maxOutputs}:{},...typeof o.lane==="string"&&o.lane!==""?{lane:o.lane}:{},...typeof o.codeFingerprint==="string"&&o.codeFingerprint!==""?{codeFingerprint:o.codeFingerprint}:{}}}function readMarkerNames(){try{return fs4.readdirSync(registryDirPath())}catch{return[]}}function readAllRegistryEntries(){const seen=new Set;const out=[];for(const name of readMarkerNames()){if(!name.endsWith(".json"))continue;const entry=coerceEntry(safeReadJson2(path9.join(registryDirPath(),name)));if(entry&&!seen.has(entry.instanceId)){seen.add(entry.instanceId);out.push(entry)}}const legacy=safeReadJson2(legacyRegistryFilePath());if(legacy&&Array.isArray(legacy.instances)){for(const raw of legacy.instances){const entry=coerceEntry(raw);if(entry&&!seen.has(entry.instanceId)){seen.add(entry.instanceId);out.push(entry)}}}return out}function listInstances(){return readAllRegistryEntries()}function discoverLiveInstances(){const out=[];for(const e of readAllRegistryEntries()){if(!isPidAlive(e.pid))continue;out.push({origin:e.origin,instanceId:e.instanceId,pid:e.pid,startedAt:e.startedAt,host:e.host??"",port:e.port,passthrough:Boolean(e.passthrough),mitmDomains:e.mitmDomains??[],modelWindows:e.modelWindows??{},modelMaxOutputs:e.modelMaxOutputs,lane:e.lane,codeFingerprint:e.codeFingerprint})}return out}var scriptFingerprints;var init_instance=__esm({"src/instance.ts"(){"use strict";init_config();init_paths();scriptFingerprints=new Map}});function winCmdUnsafeToken(token){if(token==="")return"an empty argument";if(token.includes('"'))return"a double quote";if(token.includes("%"))return"% (cmd.exe expands %VAR%)";if(/[&|<>^()]/.test(token))return"cmd metacharacters (& | < > ^ ( ))";if(/[\r\n]/.test(token))return"a line break";if(/\s/.test(token)){const trail=/\\+$/.exec(token)?.[0].length??0;if(trail%2===1)return"an odd number of trailing backslashes"}return void 0}function winCmdRefusalError(what,reason,hint){return new Error(`this ${what} cannot be passed through cmd.exe: it contains ${reason}. cmd.exe re-parses the whole command line \u2014 embedded quotes split tokens, %VAR% expands, &|<>^() are command operators \u2014 so such arguments arrive corrupted or execute unintended commands. ${hint}`)}var init_win_cmd=__esm({"src/win-cmd.ts"(){"use strict"}});import fs5 from"fs";import path10 from"path";import{execFile,spawnSync}from"child_process";import{promisify}from"util";function dshProfileDirs(env=process.env){const profiles=path10.join(resolveDshHome(env),"profiles");let entries2;try{entries2=fs5.readdirSync(profiles,{withFileTypes:true})}catch(err2){if(err2.code==="ENOENT"){throw new Error(`no dsh profiles found under ${profiles} \u2014 run dsh once (any profile) so the profile dirs exist, then retry`)}throw err2}return entries2.filter(e=>e.isDirectory()&&e.name!=="node_modules").map(e=>path10.join(profiles,e.name))}function parseDshPatchEntries(text2){const itemRe=/^\s*-\s*id\s*:\s*(\S+)/;const listItemRe=/^\s*-\s/;const disabledRe=/^\s+disabled\s*:\s*true\b/;const out=[];let current;for(const line of text2.split(/\r?\n/)){const m3=line.match(itemRe);if(m3){if(current)out.push(current);let v3=m3[1];if(v3.startsWith('"')&&v3.endsWith('"')||v3.startsWith("'")&&v3.endsWith("'"))v3=v3.slice(1,-1);v3=v3.trim();current=v3.length>0?{id:v3,disabled:false}:void 0;continue}if(listItemRe.test(line)){if(current)out.push(current);current=void 0;continue}if(current&&disabledRe.test(line))current.disabled=true}if(current)out.push(current);return out}function readManifestDependencies(profileDir){const manifest=JSON.parse(fs5.readFileSync(path10.join(profileDir,"package.json"),"utf8"));return manifest.dependencies??{}}function dshProfileDepSpec(profileDir){try{const v3=readManifestDependencies(profileDir)[DSH_PACKAGE];return typeof v3==="string"?v3:void 0}catch{return void 0}}function dshProfileDependsOnBili(profileDir){return dshProfileDepSpec(profileDir)!==void 0}function planDshProfileManifestSpec(profileDir,installedVersion){const file=path10.join(profileDir,"package.json");let raw;try{raw=fs5.readFileSync(file,"utf8")}catch{return{action:"keep",reason:"no readable package.json"}}let doc;try{doc=JSON.parse(raw)}catch{return{action:"keep",reason:"malformed package.json"}}const deps=doc.dependencies;if(!deps||typeof deps[DSH_PACKAGE]!=="string")return{action:"keep",reason:"no billion-context dependency declared"};const spec=deps[DSH_PACKAGE];if(!isRegistryDepSpec(spec))return{action:"keep",reason:`local pin ${spec} respected`};const m3=spec.match(/^\^?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/);if(!m3)return{action:"keep",reason:`non-version spec ${spec} respected`};if(m3[1]===installedVersion)return{action:"keep"};const nextSpec=spec.startsWith("^")?`^${installedVersion}`:installedVersion;deps[DSH_PACKAGE]=nextSpec;return{action:"rewrite",nextSpec,nextRaw:JSON.stringify(doc,null,2)+"\n"}}function installedProfileVersion(profileDir){try{const pkg=JSON.parse(fs5.readFileSync(path10.join(profileDir,"node_modules",DSH_PACKAGE,"package.json"),"utf-8"));return typeof pkg.version==="string"?pkg.version:void 0}catch{return void 0}}function isRegistryDepSpec(spec){return!/^[a-z][a-z0-9+.-]*:/i.test(spec)}function underDir(dir,root){return dir===root||dir.startsWith(root+path10.sep)}function isDshProfileCopy(installDir,env=process.env){const profiles=path10.join(resolveDshHome(env),"profiles");const roots=new Set([profiles]);try{roots.add(fs5.realpathSync(profiles))}catch{}const dirs=[installDir];try{dirs.push(fs5.realpathSync(installDir))}catch{}return dirs.some(dir=>[...roots].some(root=>underDir(dir,root)))}function resolveDshBinary(env=process.env,platform=process.platform,existsImpl=fs5.existsSync,execPath=process.execPath){const override=env.BILI_DSH_BIN?.trim();if(override&&override.length>0)return override;const sep2=platform==="win32"?";":":";const extensions=platform==="win32"?(env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0):[""];const nodeDir=path10.dirname(execPath);const home=platform==="win32"?env.USERPROFILE??"":env.HOME??"";const extraDirs=platform==="win32"?[nodeDir,env.APPDATA?env.APPDATA+"/npm":"",env.LOCALAPPDATA?env.LOCALAPPDATA+"/pnpm":""]:[nodeDir,"/usr/local/bin","/opt/homebrew/bin","/opt/local/bin",home?home+"/.local/bin":""];for(const dir of[...(env.PATH??"").split(sep2),...extraDirs]){if(!dir)continue;for(const ext of extensions){const name=ext===""?"dsh":`dsh${ext}`;const candidate=dir.endsWith("/")||dir.endsWith("\\")?dir+name:dir+"/"+name;if(existsImpl(candidate))return candidate}}return"dsh"}function quoteWinToken(token){if(!/\s/.test(token)||token.includes('"'))return token;return`"${token}"`}function planDshSpawn(command,args,env=process.env,platform=process.platform){if(platform!=="win32")return{command,args:[...args]};const lower=command.toLowerCase();const base=command.slice(Math.max(command.lastIndexOf("/"),command.lastIndexOf("\\"))+1);const needsCmd=lower.endsWith(".cmd")||lower.endsWith(".bat")||!path10.extname(base);if(!needsCmd)return{command,args:[...args]};[command,...args].forEach((token,i)=>{const reason=winCmdUnsafeToken(token);if(reason)throw winCmdRefusalError(i===0?"resolved dsh command":`argument #${i-1}`,reason,"Set BILI_DSH_BIN to the dsh executable, or reword the argument.")});const comspec=env.COMSPEC?.trim()||"cmd.exe";const line=`"${[command,...args].map(quoteWinToken).join(" ")}"`;return{command:comspec,args:["/d","/s","/c",line],windowsVerbatimArguments:true}}function formatDshError(err2,args){const e=err2;if(e.code==="ENOENT"){return new Error("dsh CLI not found (not on PATH, not in the known install locations probed) \u2014 install deepseek-harness, or set BILI_DSH_BIN to its executable path, then retry")}const stderr=typeof e.stderr==="string"?e.stderr.trim():e.stderr instanceof Buffer?decodeChildOutput(e.stderr).trim():"";const detail=stderr||(typeof e.message==="string"&&e.message.length>0?e.message:`exit ${e.status??"?"}`);return new Error(`dsh ${args.join(" ")} failed: ${detail}`)}function decodeChildOutput(buf){if(buf==null)return"";const raw=typeof buf==="string"?Buffer.from(buf,"utf8"):buf;if(raw.length===0)return"";try{const utf8=new TextDecoder("utf-8",{fatal:true}).decode(raw);if(UTF8_GBK_TRAP.test(utf8)){try{const gbk=new TextDecoder("gbk").decode(raw);if(HAS_CJK.test(gbk))return gbk}catch{}}return utf8}catch{try{return new TextDecoder("gbk").decode(raw)}catch{return raw.toString("utf8")}}}async function defaultAsyncRun(plan2){const{stdout,stderr}=await pExecFile(plan2.command,plan2.args,{timeout:DSH_EXEC_TIMEOUT_MS,encoding:"buffer",windowsVerbatimArguments:plan2.windowsVerbatimArguments,windowsHide:true});return{stdout:decodeChildOutput(stdout),stderr:decodeChildOutput(stderr)}}async function runDshPluginAsync(args,env=process.env){const plan2=planDshSpawn(resolveDshBinary(env),args);const run=testRunners?.async??defaultAsyncRun;try{await run(plan2)}catch(err2){throw formatDshError(err2,args)}}async function refreshDshProfileBundles(targetVersion,log2,env=process.env){let dirs;try{dirs=dshProfileDirs(env)}catch{return{refreshed:0,failed:0}}const targets=dirs.filter(dir=>dshProfileDependsOnBili(dir));if(targets.length===0)return{refreshed:0,failed:0};let refreshed=0;let failed=0;for(const dir of targets){const name=path10.basename(dir);const spec=dshProfileDepSpec(dir);if(spec!==void 0&&!isRegistryDepSpec(spec)){log2("info",`[update] dsh profile ${name}: billion-context pinned to ${spec} (local source) \u2014 leaving it alone`);continue}if(name===DSH_DESKTOP_PROFILE){continue}if(installedProfileVersion(dir)===targetVersion)continue;try{await runDshPluginAsync(["plugin","--profile",name,"add",`${DSH_PACKAGE}@${targetVersion}`],env);refreshed+=1}catch(err2){failed+=1;const detail=err2 instanceof Error?err2.message:String(err2);log2("warn",`[update] dsh profile ${name}: bundle refresh to ${targetVersion} failed: ${detail} \u2014 manual fix: run \`dsh plugin --profile ${name} add billion-context@${targetVersion}\` from a shell where \`dsh\` resolves (or point BILI_DSH_BIN at dsh's executable)`)}}if(refreshed>0){log2("info",`[update] refreshed ${refreshed} dsh profile bundle(s) to ${targetVersion} \u2014 restart dsh to load it`)}return{refreshed,failed}}var DSH_PACKAGE,DSH_DESKTOP_PROFILE,DSH_EXEC_TIMEOUT_MS,testRunners,UTF8_GBK_TRAP,HAS_CJK,pExecFile;var init_dsh_channel=__esm({"src/dsh-channel.ts"(){"use strict";init_client_config();init_win_cmd();DSH_PACKAGE="billion-context";DSH_DESKTOP_PROFILE="desktop";DSH_EXEC_TIMEOUT_MS=5*60*1e3;UTF8_GBK_TRAP=/[\u0370-\u052F]{2}/;HAS_CJK=/[\u3400-\u9FFF\uF900-\uFAFF]/;pExecFile=promisify(execFile)}});import fs6 from"fs";import path11 from"path";import{execFile as execFile2}from"child_process";import{promisify as promisify2}from"util";function resolvePiBinary(env=process.env,platform=process.platform,existsImpl=fs6.existsSync,execPath=process.execPath){const override=env.BILI_PI_BIN?.trim();if(override&&override.length>0)return override;const probeNames=["pi","pi-stable"];const sep2=platform==="win32"?";":":";const extensions=platform==="win32"?(env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0):[""];const nodeDir=path11.dirname(execPath);const home=platform==="win32"?env.USERPROFILE??"":env.HOME??"";const extraDirs=platform==="win32"?[nodeDir,env.APPDATA?env.APPDATA+"/npm":""]:[nodeDir,"/usr/local/bin","/opt/homebrew/bin","/opt/local/bin",home?home+"/.local/bin":""];for(const dir of[...(env.PATH??"").split(sep2),...extraDirs]){if(!dir)continue;for(const name of probeNames){for(const ext of extensions){const fileName=ext===""?name:`${name}${ext}`;const candidate=dir.endsWith("/")||dir.endsWith("\\")?dir+fileName:dir+"/"+fileName;if(existsImpl(candidate))return candidate}}}return"pi"}function formatPiError(err2,args){const e=err2;if(e.code==="ENOENT"){return new Error("pi CLI not found (not on PATH, not in the known install locations probed) \u2014 set BILI_PI_BIN to its executable path, then retry")}const stderr=typeof e.stderr==="string"?e.stderr.trim():e.stderr instanceof Buffer?decodeChildOutput(e.stderr).trim():"";const detail=stderr||(typeof e.message==="string"&&e.message.length>0?e.message:`exit ${e.status??"?"}`);return new Error(`pi ${args.join(" ")} failed: ${detail}`)}async function defaultAsyncRun2(plan2){const{stdout,stderr}=await pExecFile2(plan2.command,plan2.args,{timeout:PI_EXEC_TIMEOUT_MS,encoding:"buffer",windowsVerbatimArguments:plan2.windowsVerbatimArguments,windowsHide:true});return{stdout:decodeChildOutput(stdout),stderr:decodeChildOutput(stderr)}}async function runPiAsync(args,env=process.env){const plan2=planDshSpawn(resolvePiBinary(env),args,env);const run=testRunners2?.async??defaultAsyncRun2;try{await run(plan2)}catch(err2){throw formatPiError(err2,args)}}function piNpmCopyRoot(env=process.env){return path11.join(resolvePiHome(env),"npm","node_modules",PI_PACKAGE)}function isPiNpmCopy(installDir,env=process.env){const root=piNpmCopyRoot(env);let real=installDir;try{real=fs6.realpathSync(installDir)}catch{}let realRoot=root;try{realRoot=fs6.realpathSync(root)}catch{}for(const dir of[installDir,real]){if(dir===root||dir===realRoot||dir.startsWith(realRoot+path11.sep))return true}return false}function piNpmEntrySpec(env=process.env){let parsed;try{parsed=JSON.parse(fs6.readFileSync(path11.join(resolvePiHome(env),"settings.json"),"utf-8"))}catch{return void 0}if(!Array.isArray(parsed.packages))return void 0;const re2=new RegExp(`^npm:${PI_PACKAGE}(@.*)?$`);return parsed.packages.find(p2=>typeof p2==="string"&&re2.test(p2))}var PI_PACKAGE,PI_NPM_SPEC,PI_EXEC_TIMEOUT_MS,testRunners2,pExecFile2;var init_pi_channel=__esm({"src/pi-channel.ts"(){"use strict";init_client_config();init_dsh_channel();PI_PACKAGE="billion-context";PI_NPM_SPEC="npm:billion-context";PI_EXEC_TIMEOUT_MS=5*60*1e3;pExecFile2=promisify2(execFile2)}});import Qr from"events";import I from"fs";import{EventEmitter as Di}from"events";import Cs from"stream";import{StringDecoder as Hr}from"string_decoder";import cr from"path";import Kt from"fs";import{dirname as Fn,parse as kn}from"path";import{EventEmitter as Dn}from"events";import zi from"assert";import{Buffer as Ot}from"buffer";import*as Ps from"zlib";import en from"zlib";import{posix as Zt}from"path";import{basename as _n}from"path";import mi from"fs";import X from"fs";import js from"path";import{win32 as Pn}from"path";import ar from"path";import Br from"fs";import co from"assert";import{randomBytes as Mr}from"crypto";import u from"fs";import R from"path";import pr from"fs";import wi from"fs";import we from"path";import k from"fs";import ro from"fs/promises";import Si from"path";import{join as xr}from"path";import v from"fs";import Pr from"path";function Zn(s3,t,e){let i=t,r=t?t.next:s3.head,n=new ue(e,i,r,s3);return n.next===void 0&&(s3.tail=n),n.prev===void 0&&(s3.head=n),s3.length++,n}function Yn(s3,t){s3.tail=new ue(t,s3.tail,void 0,s3),s3.head||(s3.head=s3.tail),s3.length++}function Kn(s3,t){s3.head=new ue(t,void 0,s3.head,s3),s3.tail||(s3.tail=s3.head),s3.length++}var zr,Ur,Ds,Wr,Gr,Zr,Q,J,nt,De,qt,Ne,Ns,Ae,As,z,Mt,g,Qt,Bt,b,N,_,bi,Ie,L,S,_i,Oi,Is,Ti,Z,xi,Ce,Jt,Rt,C,jt,Yr,Kr,Vr,$r,Fe,Li,Xr,qr,A,Jr,ht,H,te,m,Ni,tt,Ai,ki,vi,ie,ke,Ut,Ht,Ii,Pt,at,U,ot,Y,zt,Ci,j,ee,Fi,ve,gt,Me,bt,_t,Be,et,Wt,jr,Fs,ks,vs,Ms,Bs,tn,se,K,sn,M,rn,zs,nn,Bi,Tt,Gt,Pi,re,Pe,ze,Ue,He,We,Ge,Ze,Ye,Ke,Us,hn,an,Hs,ln,cn,Ws,Gs,Hi,ne,dn,Ui,oe,Ve,un,F,mn,xt,Wi,pn,lt,En,wn,Sn,ct,yn,Rn,gn,Gi,bn,Lt,ft,On,Tn,xn,Ln,f,$e,Dt,Nn,Xi,qi,An,B,Nt,it,Zi,Zs,V,he,dt,Ys,p,st,ut,Yi,At,w,Xe,qe,Ki,Ks,Vs,ae,Vi,Qe,Yt,$,Je,It,je,ti,$s,In,le,$i,Xs,Cn,rt,mt,vn,Qi,Mn,Bn,Ct,Ji,zn,qs,ce,ei,ji,Un,Hn,ts,Qs,rr,Wn,tr,er,ir,is,sr,fe,ii,ss,si,rs,ns,os5,hs,pt,ri,as,es,q,de,ni,oi,Gn,hi,ue,pi,nr,li,me,W,pe,Et,Ft,Ee,ai,G,ls,ci,or,ds,us,fi,di,hr,cs,ui,lr,fs7,wt,kt,Vn,$n,fr,dr,Xn,qn,Qn,Jn,Er,wr,ur,Sr,yr,Rr,jn,to,eo,mr,ms,ps,Ei,io,Es,so,ws,Se,St,no,gr,Ss,br,oo,_r,ys,Or,Vt,Tr,ho,ao,lo,yi,Lr,Dr,_s,Nr,Os,P,Ts,xs,gi,Ar,Ir,Re,Cr,Fr,Rs,yt,O,Ri,kr,$t,gs,bs,Ls,ge,be,_e,Oe,fo,Te,uo,mo,po,vr,Xt,ye,xe,Eo,wo,So,yo,Ro,go,bo,_o,vt,Oo,To;var init_index_min=__esm({"node_modules/tar/dist/esm/index.min.js"(){"use strict";zr=Object.defineProperty;Ur=(s3,t)=>{for(var e in t)zr(s3,e,{get:t[e],enumerable:true})};Ds=typeof process=="object"&&process?process:{stdout:null,stderr:null};Wr=s3=>!!s3&&typeof s3=="object"&&(s3 instanceof A||s3 instanceof Cs||Gr(s3)||Zr(s3));Gr=s3=>!!s3&&typeof s3=="object"&&s3 instanceof Di&&typeof s3.pipe=="function"&&s3.pipe!==Cs.Writable.prototype.pipe;Zr=s3=>!!s3&&typeof s3=="object"&&s3 instanceof Di&&typeof s3.write=="function"&&typeof s3.end=="function";Q=Symbol("EOF");J=Symbol("maybeEmitEnd");nt=Symbol("emittedEnd");De=Symbol("emittingEnd");qt=Symbol("emittedError");Ne=Symbol("closed");Ns=Symbol("read");Ae=Symbol("flush");As=Symbol("flushChunk");z=Symbol("encoding");Mt=Symbol("decoder");g=Symbol("flowing");Qt=Symbol("paused");Bt=Symbol("resume");b=Symbol("buffer");N=Symbol("pipes");_=Symbol("bufferLength");bi=Symbol("bufferPush");Ie=Symbol("bufferShift");L=Symbol("objectMode");S=Symbol("destroyed");_i=Symbol("error");Oi=Symbol("emitData");Is=Symbol("emitEnd");Ti=Symbol("emitEnd2");Z=Symbol("async");xi=Symbol("abort");Ce=Symbol("aborted");Jt=Symbol("signal");Rt=Symbol("dataListeners");C=Symbol("discarded");jt=s3=>Promise.resolve().then(s3);Yr=s3=>s3();Kr=s3=>s3==="end"||s3==="finish"||s3==="prefinish";Vr=s3=>s3 instanceof ArrayBuffer||!!s3&&typeof s3=="object"&&s3.constructor&&s3.constructor.name==="ArrayBuffer"&&s3.byteLength>=0;$r=s3=>!Buffer.isBuffer(s3)&&ArrayBuffer.isView(s3);Fe=class{src;dest;opts;ondrain;constructor(t,e,i){this.src=t,this.dest=e,this.opts=i,this.ondrain=()=>t[Bt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}};Li=class extends Fe{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,i){super(t,e,i),this.proxyErrors=r=>this.dest.emit("error",r),t.on("error",this.proxyErrors)}};Xr=s3=>!!s3.objectMode;qr=s3=>!s3.objectMode&&!!s3.encoding&&s3.encoding!=="buffer";A=class extends Di{[g]=false;[Qt]=false;[N]=[];[b]=[];[L];[z];[Z];[Mt];[Q]=false;[nt]=false;[De]=false;[Ne]=false;[qt]=null;[_]=0;[S]=false;[Jt];[Ce]=false;[Rt]=0;[C]=false;writable=true;readable=true;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Xr(e)?(this[L]=true,this[z]=null):qr(e)?(this[z]=e.encoding,this[L]=false):(this[L]=false,this[z]=null),this[Z]=!!e.async,this[Mt]=this[z]?new Hr(this[z]):null,e&&e.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[b]}),e&&e.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[N]});let{signal:i}=e;i&&(this[Jt]=i,i.aborted?this[xi]():i.addEventListener("abort",()=>this[xi]()))}get bufferLength(){return this[_]}get encoding(){return this[z]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[L]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Z]}set async(t){this[Z]=this[Z]||!!t}[xi](){this[Ce]=true,this.emit("abort",this[Jt]?.reason),this.destroy(this[Jt]?.reason)}get aborted(){return this[Ce]}set aborted(t){}write(t,e,i){if(this[Ce])return false;if(this[Q])throw new Error("write after end");if(this[S])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof e=="function"&&(i=e,e="utf8"),e||(e="utf8");let r=this[Z]?jt:Yr;if(!this[L]&&!Buffer.isBuffer(t)){if($r(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Vr(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[L]?(this[g]&&this[_]!==0&&this[Ae](true),this[g]?this.emit("data",t):this[bi](t),this[_]!==0&&this.emit("readable"),i&&r(i),this[g]):t.length?(typeof t=="string"&&!(e===this[z]&&!this[Mt]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[z]&&(t=this[Mt].write(t)),this[g]&&this[_]!==0&&this[Ae](true),this[g]?this.emit("data",t):this[bi](t),this[_]!==0&&this.emit("readable"),i&&r(i),this[g]):(this[_]!==0&&this.emit("readable"),i&&r(i),this[g])}read(t){if(this[S])return null;if(this[C]=false,this[_]===0||t===0||t&&t>this[_])return this[J](),null;this[L]&&(t=null),this[b].length>1&&!this[L]&&(this[b]=[this[z]?this[b].join(""):Buffer.concat(this[b],this[_])]);let e=this[Ns](t||null,this[b][0]);return this[J](),e}[Ns](t,e){if(this[L])this[Ie]();else{let i=e;t===i.length||t===null?this[Ie]():typeof i=="string"?(this[b][0]=i.slice(t),e=i.slice(0,t),this[_]-=t):(this[b][0]=i.subarray(t),e=i.subarray(0,t),this[_]-=t)}return this.emit("data",e),!this[b].length&&!this[Q]&&this.emit("drain"),e}end(t,e,i){return typeof t=="function"&&(i=t,t=void 0),typeof e=="function"&&(i=e,e="utf8"),t!==void 0&&this.write(t,e),i&&this.once("end",i),this[Q]=true,this.writable=false,(this[g]||!this[Qt])&&this[J](),this}[Bt](){this[S]||(!this[Rt]&&!this[N].length&&(this[C]=true),this[Qt]=false,this[g]=true,this.emit("resume"),this[b].length?this[Ae]():this[Q]?this[J]():this.emit("drain"))}resume(){return this[Bt]()}pause(){this[g]=false,this[Qt]=true,this[C]=false}get destroyed(){return this[S]}get flowing(){return this[g]}get paused(){return this[Qt]}[bi](t){this[L]?this[_]+=1:this[_]+=t.length,this[b].push(t)}[Ie](){return this[L]?this[_]-=1:this[_]-=this[b][0].length,this[b].shift()}[Ae](t=false){do;while(this[As](this[Ie]())&&this[b].length);!t&&!this[b].length&&!this[Q]&&this.emit("drain")}[As](t){return this.emit("data",t),this[g]}pipe(t,e){if(this[S])return t;this[C]=false;let i=this[nt];return e=e||{},t===Ds.stdout||t===Ds.stderr?e.end=false:e.end=e.end!==false,e.proxyErrors=!!e.proxyErrors,i?e.end&&t.end():(this[N].push(e.proxyErrors?new Li(this,t,e):new Fe(this,t,e)),this[Z]?jt(()=>this[Bt]()):this[Bt]()),t}unpipe(t){let e=this[N].find(i=>i.dest===t);e&&(this[N].length===1?(this[g]&&this[Rt]===0&&(this[g]=false),this[N]=[]):this[N].splice(this[N].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let i=super.on(t,e);if(t==="data")this[C]=false,this[Rt]++,!this[N].length&&!this[g]&&this[Bt]();else if(t==="readable"&&this[_]!==0)super.emit("readable");else if(Kr(t)&&this[nt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[qt]){let r=e;this[Z]?jt(()=>r.call(this,this[qt])):r.call(this,this[qt])}return i}removeListener(t,e){return this.off(t,e)}off(t,e){let i=super.off(t,e);return t==="data"&&(this[Rt]=this.listeners("data").length,this[Rt]===0&&!this[C]&&!this[N].length&&(this[g]=false)),i}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Rt]=0,!this[C]&&!this[N].length&&(this[g]=false)),e}get emittedEnd(){return this[nt]}[J](){!this[De]&&!this[nt]&&!this[S]&&this[b].length===0&&this[Q]&&(this[De]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ne]&&this.emit("close"),this[De]=false)}emit(t,...e){let i=e[0];if(t!=="error"&&t!=="close"&&t!==S&&this[S])return false;if(t==="data")return!this[L]&&!i?false:this[Z]?(jt(()=>this[Oi](i)),true):this[Oi](i);if(t==="end")return this[Is]();if(t==="close"){if(this[Ne]=true,!this[nt]&&!this[S])return false;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[qt]=i,super.emit(_i,i);let n=!this[Jt]||this.listeners("error").length?super.emit("error",i):false;return this[J](),n}else if(t==="resume"){let n=super.emit("resume");return this[J](),n}else if(t==="finish"||t==="prefinish"){let n=super.emit(t);return this.removeAllListeners(t),n}let r=super.emit(t,...e);return this[J](),r}[Oi](t){for(let i of this[N])i.dest.write(t)===false&&this.pause();let e=this[C]?false:super.emit("data",t);return this[J](),e}[Is](){return this[nt]?false:(this[nt]=true,this.readable=false,this[Z]?(jt(()=>this[Ti]()),true):this[Ti]())}[Ti](){if(this[Mt]){let e=this[Mt].end();if(e){for(let i of this[N])i.dest.write(e);this[C]||super.emit("data",e)}}for(let e of this[N])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[L]||(t.dataLength=0);let e=this.promise();return this.on("data",i=>{t.push(i),this[L]||(t.dataLength+=i.length)}),await e,t}async concat(){if(this[L])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[z]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(S,()=>e(new Error("stream destroyed"))),this.on("error",i=>e(i)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[C]=false;let t=false,e=async()=>(this.pause(),t=true,{value:void 0,done:true});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:false,value:r});if(this[Q])return e();let n,o,h=d2=>{this.off("data",a),this.off("end",l3),this.off(S,c),e(),o(d2)},a=d2=>{this.off("error",h),this.off("end",l3),this.off(S,c),this.pause(),n({value:d2,done:!!this[Q]})},l3=()=>{this.off("error",h),this.off("data",a),this.off(S,c),e(),n({done:true,value:void 0})},c=()=>h(new Error("stream destroyed"));return new Promise((d2,y2)=>{o=y2,n=d2,this.once(S,c),this.once("error",h),this.once("end",l3),this.once("data",a)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[C]=false;let t=false,e=()=>(this.pause(),this.off(_i,e),this.off(S,e),this.off("end",e),t=true,{done:true,value:void 0}),i=()=>{if(t)return e();let r=this.read();return r===null?e():{done:false,value:r}};return this.once("end",e),this.once(_i,e),this.once(S,e),{next:i,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[S])return t?this.emit("error",t):this.emit(S),this;this[S]=true,this[C]=true,this[b].length=0,this[_]=0;let e=this;return typeof e.close=="function"&&!this[Ne]&&e.close(),t?this.emit("error",t):this.emit(S),this}static get isStream(){return Wr}};Jr=I.writev;ht=Symbol("_autoClose");H=Symbol("_close");te=Symbol("_ended");m=Symbol("_fd");Ni=Symbol("_finished");tt=Symbol("_flags");Ai=Symbol("_flush");ki=Symbol("_handleChunk");vi=Symbol("_makeBuf");ie=Symbol("_mode");ke=Symbol("_needDrain");Ut=Symbol("_onerror");Ht=Symbol("_onopen");Ii=Symbol("_onread");Pt=Symbol("_onwrite");at=Symbol("_open");U=Symbol("_path");ot=Symbol("_pos");Y=Symbol("_queue");zt=Symbol("_read");Ci=Symbol("_readSize");j=Symbol("_reading");ee=Symbol("_remain");Fi=Symbol("_size");ve=Symbol("_write");gt=Symbol("_writing");Me=Symbol("_defaultFlag");bt=Symbol("_errored");_t=class extends A{[bt]=false;[m];[U];[Ci];[j]=false;[Fi];[ee];[ht];constructor(t,e){if(e=e||{},super(e),this.readable=true,this.writable=false,typeof t!="string")throw new TypeError("path must be a string");this[bt]=false,this[m]=typeof e.fd=="number"?e.fd:void 0,this[U]=t,this[Ci]=e.readSize||16*1024*1024,this[j]=false,this[Fi]=typeof e.size=="number"?e.size:1/0,this[ee]=this[Fi],this[ht]=typeof e.autoClose=="boolean"?e.autoClose:true,typeof this[m]=="number"?this[zt]():this[at]()}get fd(){return this[m]}get path(){return this[U]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[at](){I.open(this[U],"r",(t,e)=>this[Ht](t,e))}[Ht](t,e){t?this[Ut](t):(this[m]=e,this.emit("open",e),this[zt]())}[vi](){return Buffer.allocUnsafe(Math.min(this[Ci],this[ee]))}[zt](){if(!this[j]){this[j]=true;let t=this[vi]();if(t.length===0)return process.nextTick(()=>this[Ii](null,0,t));I.read(this[m],t,0,t.length,null,(e,i,r)=>this[Ii](e,i,r))}}[Ii](t,e,i){this[j]=false,t?this[Ut](t):this[ki](e,i)&&this[zt]()}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Ut](t){this[j]=true,this[H](),this.emit("error",t)}[ki](t,e){let i=false;return this[ee]-=t,t>0&&(i=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[ee]<=0)&&(i=false,this[H](),super.end()),i}emit(t,...e){switch(t){case"prefinish":case"finish":return false;case"drain":return typeof this[m]=="number"&&this[zt](),false;case"error":return this[bt]?false:(this[bt]=true,super.emit(t,...e));default:return super.emit(t,...e)}}};Be=class extends _t{[at](){let t=true;try{this[Ht](null,I.openSync(this[U],"r")),t=false}finally{t&&this[H]()}}[zt](){let t=true;try{if(!this[j]){this[j]=true;do{let e=this[vi](),i=e.length===0?0:I.readSync(this[m],e,0,e.length,null);if(!this[ki](i,e))break}while(true);this[j]=false}t=false}finally{t&&this[H]()}}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.closeSync(t),this.emit("close")}}};et=class extends Qr{readable=false;writable=true;[bt]=false;[gt]=false;[te]=false;[Y]=[];[ke]=false;[U];[ie];[ht];[m];[Me];[tt];[Ni]=false;[ot];constructor(t,e){e=e||{},super(e),this[U]=t,this[m]=typeof e.fd=="number"?e.fd:void 0,this[ie]=e.mode===void 0?438:e.mode,this[ot]=typeof e.start=="number"?e.start:void 0,this[ht]=typeof e.autoClose=="boolean"?e.autoClose:true;let i=this[ot]!==void 0?"r+":"w";this[Me]=e.flags===void 0,this[tt]=e.flags===void 0?i:e.flags,this[m]===void 0&&this[at]()}emit(t,...e){if(t==="error"){if(this[bt])return false;this[bt]=true}return super.emit(t,...e)}get fd(){return this[m]}get path(){return this[U]}[Ut](t){this[H](),this[gt]=true,this.emit("error",t)}[at](){I.open(this[U],this[tt],this[ie],(t,e)=>this[Ht](t,e))}[Ht](t,e){this[Me]&&this[tt]==="r+"&&t&&t.code==="ENOENT"?(this[tt]="w",this[at]()):t?this[Ut](t):(this[m]=e,this.emit("open",e),this[gt]||this[Ai]())}end(t,e){return t&&this.write(t,e),this[te]=true,!this[gt]&&!this[Y].length&&typeof this[m]=="number"&&this[Pt](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[te]?(this.emit("error",new Error("write() after end()")),false):this[m]===void 0||this[gt]||this[Y].length?(this[Y].push(t),this[ke]=true,false):(this[gt]=true,this[ve](t),true)}[ve](t){I.write(this[m],t,0,t.length,this[ot],(e,i)=>this[Pt](e,i))}[Pt](t,e){t?this[Ut](t):(this[ot]!==void 0&&typeof e=="number"&&(this[ot]+=e),this[Y].length?this[Ai]():(this[gt]=false,this[te]&&!this[Ni]?(this[Ni]=true,this[H](),this.emit("finish")):this[ke]&&(this[ke]=false,this.emit("drain"))))}[Ai](){if(this[Y].length===0)this[te]&&this[Pt](null,0);else if(this[Y].length===1)this[ve](this[Y].pop());else{let t=this[Y];this[Y]=[],Jr(this[m],t,this[ot],(e,i)=>this[Pt](e,i))}}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.close(t,e=>e?this.emit("error",e):this.emit("close"))}}};Wt=class extends et{[at](){let t;if(this[Me]&&this[tt]==="r+")try{t=I.openSync(this[U],this[tt],this[ie])}catch(e){if(e?.code==="ENOENT")return this[tt]="w",this[at]();throw e}else t=I.openSync(this[U],this[tt],this[ie]);this[Ht](null,t)}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.closeSync(t),this.emit("close")}}[ve](t){let e=true;try{this[Pt](null,I.writeSync(this[m],t,0,t.length,this[ot])),e=false}finally{if(e)try{this[H]()}catch{}}}};jr=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]);Fs=s3=>!!s3.sync&&!!s3.file;ks=s3=>!s3.sync&&!!s3.file;vs=s3=>!!s3.sync&&!s3.file;Ms=s3=>!s3.sync&&!s3.file;Bs=s3=>!!s3.file;tn=s3=>{let t=jr.get(s3);return t||s3};se=(s3={})=>{if(!s3)return{};let t={};for(let[e,i]of Object.entries(s3)){let r=tn(e);t[r]=i}return t.chmod===void 0&&t.noChmod===false&&(t.chmod=true),delete t.noChmod,t};K=(s3,t,e,i,r)=>Object.assign((n=[],o,h)=>{Array.isArray(n)&&(o=n,n={}),typeof o=="function"&&(h=o,o=void 0),o=o?Array.from(o):[];let a=se(n);if(r?.(a,o),Fs(a)){if(typeof h=="function")throw new TypeError("callback not supported for sync tar functions");return s3(a,o)}else if(ks(a)){let l3=t(a,o);return h?l3.then(()=>h(),h):l3}else if(vs(a)){if(typeof h=="function")throw new TypeError("callback not supported for sync tar functions");return e(a,o)}else if(Ms(a)){if(typeof h=="function")throw new TypeError("callback only supported with file option");return i(a,o)}throw new Error("impossible options??")},{syncFile:s3,asyncFile:t,syncNoFile:e,asyncNoFile:i,validate:r});sn=en.constants||{ZLIB_VERNUM:4736};M=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},sn));rn=Ot.concat;zs=Object.getOwnPropertyDescriptor(Ot,"concat");nn=s3=>s3;Bi=zs?.writable===true||zs?.set!==void 0?s3=>{Ot.concat=s3?nn:rn}:s3=>{};Tt=Symbol("_superWrite");Gt=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}};Pi=Symbol("flushFlag");re=class extends A{#t=false;#i=false;#s;#n;#r;#e;#o;get sawError(){return this.#t}get handle(){return this.#e}get flushFlag(){return this.#s}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#s=t.flush??0,this.#n=t.finishFlush??0,this.#r=t.fullFlushFlag??0,typeof Ps[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#e=new Ps[e](t)}catch(i){throw new Gt(i,this.constructor)}this.#o=i=>{this.#t||(this.#t=true,this.close(),this.emit("error",i))},this.#e?.on("error",i=>this.#o(new Gt(i))),this.once("end",()=>this.close)}close(){this.#e&&(this.#e.close(),this.#e=void 0,this.emit("close"))}reset(){if(!this.#t)return zi(this.#e,"zlib binding closed"),this.#e.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#r),this.write(Object.assign(Ot.alloc(0),{[Pi]:t})))}end(t,e,i){return typeof t=="function"&&(i=t,e=void 0,t=void 0),typeof e=="function"&&(i=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#n),this.#i=true,super.end(i)}get ended(){return this.#i}[Tt](t){return super.write(t)}write(t,e,i){if(typeof e=="function"&&(i=e,e="utf8"),typeof t=="string"&&(t=Ot.from(t,e)),this.#t)return;zi(this.#e,"zlib binding closed");let r=this.#e._handle,n=r.close;r.close=()=>{};let o=this.#e.close;this.#e.close=()=>{},Bi(true);let h;try{let l3=typeof t[Pi]=="number"?t[Pi]:this.#s;h=this.#e._processChunk(t,l3),Bi(false)}catch(l3){Bi(false),this.#o(new Gt(l3,this.write))}finally{this.#e&&(this.#e._handle=r,r.close=n,this.#e.close=o,this.#e.removeAllListeners("error"))}this.#e&&this.#e.on("error",l3=>this.#o(new Gt(l3,this.write)));let a;if(h)if(Array.isArray(h)&&h.length>0){let l3=h[0];a=this[Tt](Ot.from(l3));for(let c=1;c<h.length;c++)a=this[Tt](h[c])}else a=this[Tt](Ot.from(h));return i&&i(),a}};Pe=class extends re{#t;#i;constructor(t,e){t=t||{},t.flush=t.flush||M.Z_NO_FLUSH,t.finishFlush=t.finishFlush||M.Z_FINISH,t.fullFlushFlag=M.Z_FULL_FLUSH,super(t,e),this.#t=t.level,this.#i=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#t!==t||this.#i!==e){this.flush(M.Z_SYNC_FLUSH),zi(this.handle,"zlib binding closed");let i=this.handle.flush;this.handle.flush=(r,n)=>{typeof r=="function"&&(n=r,r=this.flushFlag),this.flush(r),n?.()};try{this.handle.params(t,e)}finally{this.handle.flush=i}this.handle&&(this.#t=t,this.#i=e)}}}};ze=class extends Pe{#t;constructor(t){super(t,"Gzip"),this.#t=t&&!!t.portable}[Tt](t){return this.#t?(this.#t=false,t[9]=255,super[Tt](t)):super[Tt](t)}};Ue=class extends Pe{constructor(t){super(t,"Unzip")}};He=class extends re{constructor(t,e){t=t||{},t.flush=t.flush||M.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||M.BROTLI_OPERATION_FINISH,t.fullFlushFlag=M.BROTLI_OPERATION_FLUSH,super(t,e)}};We=class extends He{constructor(t){super(t,"BrotliCompress")}};Ge=class extends He{constructor(t){super(t,"BrotliDecompress")}};Ze=class extends re{constructor(t,e){t=t||{},t.flush=t.flush||M.ZSTD_e_continue,t.finishFlush=t.finishFlush||M.ZSTD_e_end,t.fullFlushFlag=M.ZSTD_e_flush,super(t,e)}};Ye=class extends Ze{constructor(t){super(t,"ZstdCompress")}};Ke=class extends Ze{constructor(t){super(t,"ZstdDecompress")}};Us=(s3,t)=>{if(Number.isSafeInteger(s3))s3<0?an(s3,t):hn(s3,t);else throw Error("cannot encode number outside of javascript safe integer range");return t};hn=(s3,t)=>{t[0]=128;for(var e=t.length;e>1;e--)t[e-1]=s3&255,s3=Math.floor(s3/256)};an=(s3,t)=>{t[0]=255;var e=false;s3=s3*-1;for(var i=t.length;i>1;i--){var r=s3&255;s3=Math.floor(s3/256),e?t[i-1]=Ws(r):r===0?t[i-1]=0:(e=true,t[i-1]=Gs(r))}};Hs=s3=>{let t=s3[0],e=t===128?cn(s3.subarray(1,s3.length)):t===255?ln(s3):null;if(e===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(e))throw Error("parsed number outside of javascript safe integer range");return e};ln=s3=>{for(var t=s3.length,e=0,i=false,r=t-1;r>-1;r--){var n=Number(s3[r]),o;i?o=Ws(n):n===0?o=n:(i=true,o=Gs(n)),o!==0&&(e-=o*Math.pow(256,t-r-1))}return e};cn=s3=>{for(var t=s3.length,e=0,i=t-1;i>-1;i--){var r=Number(s3[i]);r!==0&&(e+=r*Math.pow(256,t-i-1))}return e};Ws=s3=>(255^s3)&255;Gs=s3=>(255^s3)+1&255;Hi={};Ur(Hi,{code:()=>Ve,isCode:()=>ne,isName:()=>dn,name:()=>oe,normalFsTypes:()=>Ui});ne=s3=>oe.has(s3);dn=s3=>Ve.has(s3);Ui=new Set(["0","","1","2","3","4","5","6","7","D"]);oe=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]);Ve=new Map(Array.from(oe).map(s3=>[s3[1],s3[0]]));un=s3=>s3===void 0||s3<0?void 0:s3;F=class{cksumValid=false;needPax=false;nullBlock=false;block;path;mode;uid;gid;size;cksum;#t="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,i,r){Buffer.isBuffer(t)?this.decode(t,e||0,i,r):t&&this.#i(t)}decode(t,e,i,r){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let n=xt(t,e+156,1),o=Ui.has(n),h=o?i:void 0,a=o?r:void 0;if(this.path=h?.path??xt(t,e,100),this.mode=h?.mode??a?.mode??lt(t,e+100,8),this.uid=h?.uid??a?.uid??lt(t,e+108,8),this.gid=h?.gid??a?.gid??lt(t,e+116,8),this.size=un(h?.size??a?.size??lt(t,e+124,12)),this.mtime=h?.mtime??a?.mtime??Wi(t,e+136,12),this.cksum=lt(t,e+148,12),a&&this.#i(a,true),h&&this.#i(h),ne(n)&&(this.#t=n||"0"),this.#t==="0"&&this.path.slice(-1)==="/"&&(this.#t="5"),this.#t==="5"&&(this.size=0),this.linkpath=xt(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=h?.uname??a?.uname??xt(t,e+265,32),this.gname=h?.gname??a?.gname??xt(t,e+297,32),this.devmaj=h?.devmaj??a?.devmaj??lt(t,e+329,8)??0,this.devmin=h?.devmin??a?.devmin??lt(t,e+337,8)??0,t[e+475]!==0){let c=xt(t,e+345,155);this.path=c+"/"+this.path}else{let c=xt(t,e+345,130);c&&(this.path=c+"/"+this.path),this.atime=i?.atime??r?.atime??Wi(t,e+476,12),this.ctime=i?.ctime??r?.ctime??Wi(t,e+488,12)}let l3=256;for(let c=e;c<e+148;c++)l3+=t[c];for(let c=e+156;c<e+512;c++)l3+=t[c];this.cksumValid=l3===this.cksum,this.cksum===void 0&&l3===256&&(this.nullBlock=true)}#i(t,e=false){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([i,r])=>!(r==null||i==="size"&&Number(r)<0||i==="path"&&e||i==="linkpath"&&e||i==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#t==="Unsupported"&&(this.#t="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let i=this.ctime||this.atime?130:155,r=mn(this.path||"",i),n=r[0],o=r[1];this.needPax=!!r[2],this.needPax=Lt(t,e,100,n)||this.needPax,this.needPax=ct(t,e+100,8,this.mode)||this.needPax,this.needPax=ct(t,e+108,8,this.uid)||this.needPax,this.needPax=ct(t,e+116,8,this.gid)||this.needPax,this.needPax=ct(t,e+124,12,this.size)||this.needPax,this.needPax=Gi(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#t.codePointAt(0)),this.needPax=Lt(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Lt(t,e+265,32,this.uname)||this.needPax,this.needPax=Lt(t,e+297,32,this.gname)||this.needPax,this.needPax=ct(t,e+329,8,this.devmaj)||this.needPax,this.needPax=ct(t,e+337,8,this.devmin)||this.needPax,this.needPax=Lt(t,e+345,i,o)||this.needPax,t[e+475]!==0?this.needPax=Lt(t,e+345,155,o)||this.needPax:(this.needPax=Lt(t,e+345,130,o)||this.needPax,this.needPax=Gi(t,e+476,12,this.atime)||this.needPax,this.needPax=Gi(t,e+488,12,this.ctime)||this.needPax);let h=256;for(let a=e;a<e+148;a++)h+=t[a];for(let a=e+156;a<e+512;a++)h+=t[a];return this.cksum=h,ct(t,e+148,8,this.cksum),this.cksumValid=true,this.needPax}get type(){return this.#t==="Unsupported"?this.#t:oe.get(this.#t)}get typeKey(){return this.#t}set type(t){let e=String(Ve.get(t));if(ne(e)||e==="Unsupported")this.#t=e;else if(ne(t))this.#t=t;else throw new TypeError("invalid entry type: "+t)}};mn=(s3,t)=>{let i=s3,r="",n,o=Zt.parse(s3).root||".";if(Buffer.byteLength(i)<100)n=[i,r,false];else{r=Zt.dirname(i),i=Zt.basename(i);do Buffer.byteLength(i)<=100&&Buffer.byteLength(r)<=t?n=[i,r,false]:Buffer.byteLength(i)>100&&Buffer.byteLength(r)<=t?n=[i.slice(0,99),r,true]:(i=Zt.join(Zt.basename(r),i),r=Zt.dirname(r));while(r!==o&&n===void 0);n||(n=[s3.slice(0,99),"",true])}return n};xt=(s3,t,e)=>s3.subarray(t,t+e).toString("utf8").replace(/\0.*/,"");Wi=(s3,t,e)=>pn(lt(s3,t,e));pn=s3=>s3===void 0?void 0:new Date(s3*1e3);lt=(s3,t,e)=>Number(s3[t])&128?Hs(s3.subarray(t,t+e)):wn(s3,t,e);En=s3=>isNaN(s3)?void 0:s3;wn=(s3,t,e)=>En(parseInt(s3.subarray(t,t+e).toString("utf8").replace(/\0.*$/,"").trim(),8));Sn={12:8589934591,8:2097151};ct=(s3,t,e,i)=>i===void 0?false:i>Sn[e]||i<0?(Us(i,s3.subarray(t,t+e)),true):(yn(s3,t,e,i),false);yn=(s3,t,e,i)=>s3.write(Rn(i,e),t,e,"ascii");Rn=(s3,t)=>gn(Math.floor(s3).toString(8),t);gn=(s3,t)=>(s3.length===t-1?s3:new Array(t-s3.length-1).join("0")+s3+" ")+"\0";Gi=(s3,t,e,i)=>i===void 0?false:ct(s3,t,e,i.getTime()/1e3);bn=new Array(156).join("\0");Lt=(s3,t,e,i)=>i===void 0?false:(s3.write(i+bn,t,e,"utf8"),i.length!==Buffer.byteLength(i)||i.length>e);ft=class s{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(t,e=false){this.atime=t.atime,this.charset=t.charset,this.comment=t.comment,this.ctime=t.ctime,this.dev=t.dev,this.gid=t.gid,this.global=e,this.gname=t.gname,this.ino=t.ino,this.linkpath=t.linkpath,this.mtime=t.mtime,this.nlink=t.nlink,this.path=t.path,this.size=t.size,this.uid=t.uid,this.uname=t.uname}encode(){let t=this.encodeBody();if(t==="")return Buffer.allocUnsafe(0);let e=Buffer.byteLength(t),i=512*Math.ceil(1+e/512),r=Buffer.allocUnsafe(i);for(let n=0;n<512;n++)r[n]=0;new F({path:("PaxHeader/"+_n(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:e,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(r),r.write(t,512,e,"utf8");for(let n=e+512;n<r.length;n++)r[n]=0;return r}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(t){if(this[t]===void 0)return"";let e=this[t],i=e instanceof Date?e.getTime()/1e3:e,r=" "+(t==="dev"||t==="ino"||t==="nlink"?"SCHILY.":"")+t+"="+i+`
536
536
  `,n=Buffer.byteLength(r),o=Math.floor(Math.log(n)/Math.log(10))+1;return n+o>=Math.pow(10,o)&&(o+=1),o+n+r}static parse(t,e,i=false){return new s(On(Tn(t),e),i)}};On=(s3,t)=>t?Object.assign({},t,s3):s3;Tn=s3=>s3.replace(/\n$/,"").split(`
537
537
  `).reduce(xn,Object.create(null));xn=(s3,t)=>{let e=parseInt(t,10);if(e!==Buffer.byteLength(t)+1)return s3;t=t.slice((e+" ").length);let i=t.split("="),r=i.shift();if(!r)return s3;let n=r.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),o=i.join("=").replace(/\0.*/,"");switch(n){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":s3[n]=o;break;case"ctime":case"atime":case"mtime":s3[n]=new Date(Number(o)*1e3);break;case"size":let h=+o;h>=0&&(s3[n]=h);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":s3[n]=+o;break}return s3};Ln=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform;f=Ln!=="win32"?s3=>String(s3):s3=>String(s3).replaceAll(/\\/g,"/");$e=class extends A{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=false;ignore=false;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=false;absolute;unsupported=false;constructor(t,e,i){switch(super({}),this.pause(),this.extended=e,this.globalExtended=i,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=true;break;default:this.ignore=true}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=f(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?f(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#t(e),i&&this.#t(i,true)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let i=this.remain,r=this.blockRemain;return this.remain=Math.max(0,i-e),this.blockRemain=Math.max(0,r-e),this.ignore?true:i>=e?super.write(t):super.write(t.subarray(0,i))}#t(t,e=false){t.path&&(t.path=f(t.path)),t.linkpath&&(t.linkpath=f(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([i,r])=>!(r==null||i==="path"&&e))))}};Dt=(s3,t,e,i={})=>{s3.file&&(i.file=s3.file),s3.cwd&&(i.cwd=s3.cwd),i.code=e instanceof Error&&e.code||t,i.tarCode=t,!s3.strict&&i.recoverable!==false?(e instanceof Error&&(i=Object.assign(e,i),e=e.message),s3.emit("warn",t,e,i)):e instanceof Error?s3.emit("error",Object.assign(e,i)):s3.emit("error",Object.assign(new Error(`${t}: ${e}`),i))};Nn=1024*1024;Xi=Buffer.from([31,139]);qi=Buffer.from([40,181,47,253]);An=Math.max(Xi.length,qi.length);B=Symbol("state");Nt=Symbol("writeEntry");it=Symbol("readEntry");Zi=Symbol("nextEntry");Zs=Symbol("processEntry");V=Symbol("extendedHeader");he=Symbol("globalExtendedHeader");dt=Symbol("meta");Ys=Symbol("emitMeta");p=Symbol("buffer");st=Symbol("queue");ut=Symbol("ended");Yi=Symbol("emittedEnd");At=Symbol("emit");w=Symbol("unzip");Xe=Symbol("consumeChunk");qe=Symbol("consumeChunkSub");Ki=Symbol("consumeBody");Ks=Symbol("consumeMeta");Vs=Symbol("consumeHeader");ae=Symbol("consuming");Vi=Symbol("bufferConcat");Qe=Symbol("maybeEnd");Yt=Symbol("writing");$=Symbol("aborted");Je=Symbol("onDone");It=Symbol("sawValidEntry");je=Symbol("sawNullBlock");ti=Symbol("sawEOF");$s=Symbol("closeStream");In=1e3;le=Symbol("compressedBytesRead");$i=Symbol("decompressedBytesRead");Xs=Symbol("checkDecompressionRatio");Cn=()=>true;rt=class extends Dn{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=true;readable=false;[st]=[];[p];[it];[Nt];[B]="begin";[dt]="";[V];[he];[ut]=false;[w];[$]=false;[It];[je]=false;[ti]=false;[Yt]=false;[ae]=false;[Yi]=false;[le]=0;[$i]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Je,()=>{(this[B]==="begin"||this[It]===false)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Je,t.ondone):this.on(Je,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:In,this.maxMetaEntrySize=t.maxMetaEntrySize||Nn,this.filter=typeof t.filter=="function"?t.filter:Cn;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:false;let i=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:i?true:void 0,this.on("end",()=>this[$s]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,i={}){Dt(this,t,e,i)}[Vs](t,e){this[It]===void 0&&(this[It]=false);let i;try{i=new F(t,e,this[V],this[he])}catch(r){return this.warn("TAR_ENTRY_INVALID",r)}if(i.nullBlock)this[je]?(this[ti]=true,this[B]==="begin"&&(this[B]="header"),this[At]("eof")):(this[je]=true,this[At]("nullBlock"));else if(this[je]=false,!i.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:i});else if(!i.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:i});else{let r=i.type;if(/^(Symbolic)?Link$/.test(r)&&!i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:i});else if(!/^(Symbolic)?Link$/.test(r)&&!/^(Global)?ExtendedHeader$/.test(r)&&i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:i});else{let n=this[Nt]=new $e(i,this[V],this[he]);if(!this[It])if(n.remain){let o=()=>{n.invalid||(this[It]=true)};n.on("end",o)}else this[It]=true;n.meta?n.size>this.maxMetaEntrySize?(n.ignore=true,this[At]("ignoredEntry",n),this[B]="ignore",n.resume()):n.size>0&&(this[dt]="",n.on("data",o=>this[dt]+=o),this[B]="meta"):(this[V]=void 0,n.ignore=n.ignore||!this.filter(n.path,n),n.ignore?(this[At]("ignoredEntry",n),this[B]=n.remain?"ignore":"header",n.resume()):(n.remain?this[B]="body":(this[B]="header",n.end()),this[it]?this[st].push(n):(this[st].push(n),this[Zi]())))}}}[$s](){queueMicrotask(()=>this.emit("close"))}[Zs](t){let e=true;if(!t)this[it]=void 0,e=false;else if(Array.isArray(t)){let[i,...r]=t;this.emit(i,...r)}else this[it]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Zi]()),e=false);return e}[Zi](){do;while(this[Zs](this[st].shift()));if(this[st].length===0){let t=this[it];!t||t.flowing||t.size===t.remain?this[Yt]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Ki](t,e){let i=this[Nt];if(!i)throw new Error("attempt to consume body without entry??");let r=i.blockRemain??0,n=r>=t.length&&e===0?t:t.subarray(e,e+r);return i.write(n),i.blockRemain||(this[B]="header",this[Nt]=void 0,i.end()),n.length}[Ks](t,e){let i=this[Nt],r=this[Ki](t,e);return!this[Nt]&&i&&this[Ys](i),r}[At](t,e,i){this[st].length===0&&!this[it]?this.emit(t,e,i):this[st].push([t,e,i])}[Ys](t){switch(this[At]("meta",this[dt]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[V]=ft.parse(this[dt],this[V],false);break;case"GlobalExtendedHeader":this[he]=ft.parse(this[dt],this[he],true);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[V]??Object.create(null);this[V]=e,e.path=this[dt].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[V]||Object.create(null);this[V]=e,e.linkpath=this[dt].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[$]){if(this[w]){let e=this[w];e.write=()=>true,e.end=()=>e,e.emit=()=>false,e.destroy?.()}this[$]=true,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:false})}}[Xs](t){this[$i]+=t.length;let e=this[$i]/this[le];return e>this.maxDecompressionRatio?(this.abort(new Error(`max decompression ratio exceeded: ${e.toFixed(2)} > ${this.maxDecompressionRatio}`)),false):true}write(t,e,i){if(typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[$])return i?.(),false;if((this[w]===void 0||this.brotli===void 0&&this[w]===false)&&t){if(this[p]&&(t=Buffer.concat([this[p],t]),this[p]=void 0),t.length<An)return this[p]=t,i?.(),true;for(let a=0;this[w]===void 0&&a<Xi.length;a++)t[a]!==Xi[a]&&(this[w]=false);let o=false;if(this[w]===false&&this.zstd!==false){o=true;for(let a=0;a<qi.length;a++)if(t[a]!==qi[a]){o=false;break}}let h=this.brotli===void 0&&!o;if(this[w]===false&&h)if(t.length<512)if(this[ut])this.brotli=true;else return this[p]=t,i?.(),true;else try{new F(t.subarray(0,512)),this.brotli=false}catch{this.brotli=true}if(this[w]===void 0||this[w]===false&&(this.brotli||o)){let a=this[ut];this[ut]=false,this[w]=this[w]===void 0?new Ue({}):o?new Ke({}):new Ge({}),this[w].on("data",c=>{this[Xs](c)&&this[Xe](c)}),this[w].on("error",c=>{this[$]||this.abort(c)}),this[w].on("end",()=>{this[ut]=true,this[Xe]()}),this[Yt]=true,this[le]+=t.length;let l3=!!this[w][a?"end":"write"](t);return this[Yt]=false,i?.(),l3}}this[Yt]=true,this[w]?(this[le]+=t.length,this[w].write(t)):this[Xe](t),this[Yt]=false;let n=this[st].length>0?false:this[it]?this[it].flowing:true;return!n&&this[st].length===0&&this[it]?.once("drain",()=>this.emit("drain")),i?.(),n}[Vi](t){t&&!this[$]&&(this[p]=this[p]?Buffer.concat([this[p],t]):t)}[Qe](){if(this[ut]&&!this[Yi]&&!this[$]&&!this[ae]){this[Yi]=true;let t=this[Nt];if(t?.blockRemain){let e=this[p]?this[p].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[p]&&t.write(this[p]),t.end()}this[At](Je)}}[Xe](t){if(this[ae]&&t)this[Vi](t);else if(!t&&!this[p])this[Qe]();else if(t){if(this[ae]=true,this[p]){this[Vi](t);let e=this[p];this[p]=void 0,this[qe](e)}else this[qe](t);for(;this[p]&&this[p]?.length>=512&&!this[$]&&!this[ti];){let e=this[p];this[p]=void 0,this[qe](e)}this[ae]=false}(!this[p]||this[ut])&&this[Qe]()}[qe](t){let e=0,i=t.length;for(;e+512<=i&&!this[$]&&!this[ti];)switch(this[B]){case"begin":case"header":this[Vs](t,e),e+=512;break;case"ignore":case"body":e+=this[Ki](t,e);break;case"meta":e+=this[Ks](t,e);break;default:throw new Error("invalid state: "+this[B])}e<i&&(this[p]=this[p]?Buffer.concat([t.subarray(e),this[p]]):t.subarray(e))}end(t,e,i){return typeof t=="function"&&(i=t,e=void 0,t=void 0),typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),i&&this.once("finish",i),this[$]||(this[w]?(t&&(this[le]+=t.length,this[w].write(t)),this[w].end()):(this[ut]=true,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Qe]())),this}};mt=s3=>{let t=s3.length-1,e=-1;for(;t>-1&&s3.charAt(t)==="/";)e=t,t--;return e===-1?s3:s3.slice(0,e)};vn=s3=>{let t=s3.onReadEntry;s3.onReadEntry=t?e=>{t(e),e.resume()}:e=>e.resume()};Qi=(s3,t)=>{let e=new Map(t.map(o=>[mt(o),true])),i=s3.filter,r=100,n=(o,h="",a=0)=>{if(a>=r)return e.set(o,false),false;let l3=h||kn(o).root||".",c;if(o===l3)c=false;else{let d2=e.get(o);c=d2!==void 0?d2:n(Fn(o),l3,a+1)}return e.set(o,c),c};s3.filter=i?(o,h)=>i(o,h)&&n(mt(o)):o=>n(mt(o))};Mn=s3=>{let t=new rt(s3),e=s3.file,i;try{i=Kt.openSync(e,"r");let r=Kt.fstatSync(i),n=s3.maxReadSize||16*1024*1024;if(r.size<n){let o=Buffer.allocUnsafe(r.size),h=Kt.readSync(i,o,0,r.size,0);t.end(h===o.byteLength?o:o.subarray(0,h))}else{let o=0,h=Buffer.allocUnsafe(n);for(;o<r.size;){let a=Kt.readSync(i,h,0,n,o);if(a===0)break;o+=a,t.write(h.subarray(0,a))}t.end()}}finally{if(typeof i=="number")try{Kt.closeSync(i)}catch{}}};Bn=(s3,t)=>{let e=new rt(s3),i=s3.maxReadSize||16*1024*1024,r=s3.file;return new Promise((o,h)=>{e.on("error",h),e.on("end",o),Kt.stat(r,(a,l3)=>{if(a)h(a);else{let c=new _t(r,{readSize:i,size:l3.size});c.on("error",h),c.pipe(e)}})})};Ct=K(Mn,Bn,s3=>new rt(s3),s3=>new rt(s3),(s3,t)=>{t?.length&&Qi(s3,t),s3.noResume||vn(s3)});Ji=(s3,t,e)=>(s3&=4095,e&&(s3=(s3|384)&-19),t&&(s3&256&&(s3|=64),s3&32&&(s3|=8),s3&4&&(s3|=1)),s3);({isAbsolute:zn,parse:qs}=Pn);ce=s3=>{let t="",e=qs(s3);for(;zn(s3)||e.root;){let i=s3.charAt(0)==="/"&&s3.slice(0,4)!=="//?/"?"/":e.root;s3=s3.slice(i.length),t+=i,e=qs(s3)}return[t,s3]};ei=["|","<",">","?",":"];ji=ei.map(s3=>String.fromCodePoint(61440+Number(s3.codePointAt(0))));Un=new Map(ei.map((s3,t)=>[s3,ji[t]]));Hn=new Map(ji.map((s3,t)=>[s3,ei[t]]));ts=s3=>ei.reduce((t,e)=>t.split(e).join(Un.get(e)),s3);Qs=s3=>ji.reduce((t,e)=>t.split(e).join(Hn.get(e)),s3);rr=(s3,t)=>t?(s3=f(s3).replace(/^\.(\/|$)/,""),mt(t)+"/"+s3):f(s3);Wn=16*1024*1024;tr=Symbol("process");er=Symbol("file");ir=Symbol("directory");is=Symbol("symlink");sr=Symbol("hardlink");fe=Symbol("header");ii=Symbol("read");ss=Symbol("lstat");si=Symbol("onlstat");rs=Symbol("onread");ns=Symbol("onreadlink");os5=Symbol("openfile");hs=Symbol("onopenfile");pt=Symbol("close");ri=Symbol("mode");as=Symbol("awaitDrain");es=Symbol("ondrain");q=Symbol("prefix");de=class extends A{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#t=false;constructor(t,e={}){let i=se(e);super(),this.path=f(t),this.portable=!!i.portable,this.maxReadSize=i.maxReadSize||Wn,this.linkCache=i.linkCache||new Map,this.statCache=i.statCache||new Map,this.preservePaths=!!i.preservePaths,this.cwd=f(i.cwd||process.cwd()),this.strict=!!i.strict,this.noPax=!!i.noPax,this.noMtime=!!i.noMtime,this.mtime=i.mtime,this.prefix=i.prefix?f(i.prefix):void 0,this.onWriteEntry=i.onWriteEntry,typeof i.onwarn=="function"&&this.on("warn",i.onwarn);let r=false;if(!this.preservePaths){let[o,h]=ce(this.path);o&&typeof h=="string"&&(this.path=h,r=o)}this.win32=!!i.win32||process.platform==="win32",this.win32&&(this.path=Qs(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=f(i.absolute||js.resolve(this.cwd,t)),this.path===""&&(this.path="./"),r&&this.warn("TAR_ENTRY_INFO",`stripping ${r} from absolute path`,{entry:this,path:r+this.path});let n=this.statCache.get(this.absolute);n?this[si](n):this[ss]()}warn(t,e,i={}){return Dt(this,t,e,i)}emit(t,...e){return t==="error"&&(this.#t=true),super.emit(t,...e)}[ss](){X.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[si](e)})}[si](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=Gn(t),this.emit("stat",t),this[tr]()}[tr](){switch(this.type){case"File":return this[er]();case"Directory":return this[ir]();case"SymbolicLink":return this[is]();default:return this.end()}}[ri](t){return Ji(t,this.type==="Directory",this.portable)}[q](t){return rr(t,this.prefix)}[fe](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=true),this.onWriteEntry?.(this),this.header=new F({path:this[q](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[q](this.linkpath):this.linkpath,mode:this[ri](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new ft({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[q](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[q](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[ir](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[fe](),this.end()}[is](){X.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[ns](e)})}[ns](t){this.linkpath=f(t),this[fe](),this.end()}[sr](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=f(js.relative(this.cwd,t)),this.stat.size=0,this[fe](),this.end()}[er](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let t=`${this.stat.dev}:${this.stat.ino}`,e=this.linkCache.get(t);if(e?.indexOf(this.cwd)===0)return this[sr](e);this.linkCache.set(t,this.absolute)}if(this[fe](),this.stat.size===0)return this.end();this[os5]()}[os5](){X.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[hs](e)})}[hs](t){if(this.fd=t,this.#t)return this[pt]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[ii]()}[ii](){let{fd:t,buf:e,offset:i,length:r,pos:n}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");X.read(t,e,i,r,n,(o,h)=>{if(o)return this[pt](()=>this.emit("error",o));this[rs](h)})}[pt](t=()=>{}){this.fd!==void 0&&X.close(this.fd,t)}[rs](t){if(t<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[pt](()=>this.emit("error",r))}if(t>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[pt](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let r=t;r<this.length&&t<this.blockRemain;r++)this.buf[r+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[es]():this[as](()=>this[es]())}[as](t){this.once("drain",t)}write(t,e,i){if(typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let r=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",r)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,i)}[es](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[pt](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[ii]()}};ni=class extends de{sync=true;[ss](){this[si](X.lstatSync(this.absolute))}[is](){this[ns](X.readlinkSync(this.absolute))}[os5](){this[hs](X.openSync(this.absolute,"r"))}[ii](){let t=true;try{let{fd:e,buf:i,offset:r,length:n,pos:o}=this;if(e===void 0||i===void 0)throw new Error("fd and buf must be set in READ method");let h=X.readSync(e,i,r,n,o);this[rs](h),t=false}finally{if(t)try{this[pt](()=>{})}catch{}}}[as](t){t()}[pt](t=()=>{}){this.fd!==void 0&&X.closeSync(this.fd),t()}};oi=class extends A{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,i={}){return Dt(this,t,e,i)}constructor(t,e={}){let i=se(e);super(),this.preservePaths=!!i.preservePaths,this.portable=!!i.portable,this.strict=!!i.strict,this.noPax=!!i.noPax,this.noMtime=!!i.noMtime,this.onWriteEntry=i.onWriteEntry,this.readEntry=t;let{type:r}=t;if(r==="Unsupported")throw new Error("writing entry that should be ignored");this.type=r,this.type==="Directory"&&this.portable&&(this.noMtime=true),this.prefix=i.prefix,this.path=f(t.path),this.mode=t.mode!==void 0?this[ri](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:i.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?f(t.linkpath):void 0,typeof i.onwarn=="function"&&this.on("warn",i.onwarn);let n=false;if(!this.preservePaths){let[h,a]=ce(this.path);h&&typeof a=="string"&&(this.path=a,n=h)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new F({path:this[q](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[q](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path}),this.header.encode()&&!this.noPax&&super.write(new ft({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[q](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[q](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let o=this.header?.block;if(!o)throw new Error("failed to encode header");super.write(o),t.pipe(this)}[q](t){return rr(t,this.prefix)}[ri](t){return Ji(t,this.type==="Directory",this.portable)}write(t,e,i){typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let r=t.length;if(r>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=r,super.write(t,i)}end(t,e,i){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(i=t,e=void 0,t=void 0),typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),i&&this.once("finish",i),t?super.end(t,i):super.end(i),this}};Gn=s3=>s3.isFile()?"File":s3.isDirectory()?"Directory":s3.isSymbolicLink()?"SymbolicLink":"Unsupported";hi=class s2{tail;head;length=0;static create(t=[]){return new s2(t)}constructor(t=[]){for(let e of t)this.push(e)}*[Symbol.iterator](){for(let t=this.head;t;t=t.next)yield t.value}removeNode(t){if(t.list!==this)throw new Error("removing node which does not belong to this list");let e=t.next,i=t.prev;return e&&(e.prev=i),i&&(i.next=e),t===this.head&&(this.head=e),t===this.tail&&(this.tail=i),this.length--,t.next=void 0,t.prev=void 0,t.list=void 0,e}unshiftNode(t){if(t===this.head)return;t.list&&t.list.removeNode(t);let e=this.head;t.list=this,t.next=e,e&&(e.prev=t),this.head=t,this.tail||(this.tail=t),this.length++}pushNode(t){if(t===this.tail)return;t.list&&t.list.removeNode(t);let e=this.tail;t.list=this,t.prev=e,e&&(e.next=t),this.tail=t,this.head||(this.head=t),this.length++}push(...t){for(let e=0,i=t.length;e<i;e++)Yn(this,t[e]);return this.length}unshift(...t){for(var e=0,i=t.length;e<i;e++)Kn(this,t[e]);return this.length}pop(){if(!this.tail)return;let t=this.tail.value,e=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,e.list=void 0,this.length--,t}shift(){if(!this.head)return;let t=this.head.value,e=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,e.list=void 0,this.length--,t}forEach(t,e){e=e||this;for(let i=this.head,r=0;i;r++)t.call(e,i.value,r,this),i=i.next}forEachReverse(t,e){e=e||this;for(let i=this.tail,r=this.length-1;i;r--)t.call(e,i.value,r,this),i=i.prev}get(t){let e=0,i=this.head;for(;i&&e<t;e++)i=i.next;if(e===t&&i)return i.value}getReverse(t){let e=0,i=this.tail;for(;i&&e<t;e++)i=i.prev;if(e===t&&i)return i.value}map(t,e){e=e||this;let i=new s2;for(let r=this.head;r;)i.push(t.call(e,r.value,this)),r=r.next;return i}mapReverse(t,e){e=e||this;var i=new s2;for(let r=this.tail;r;)i.push(t.call(e,r.value,this)),r=r.prev;return i}reduce(t,e){let i,r=this.head;if(arguments.length>1)i=e;else if(this.head)r=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=0;r;n++)i=t(i,r.value,n),r=r.next;return i}reduceReverse(t,e){let i,r=this.tail;if(arguments.length>1)i=e;else if(this.tail)r=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let n=this.length-1;r;n--)i=t(i,r.value,n),r=r.prev;return i}toArray(){let t=new Array(this.length);for(let e=0,i=this.head;i;e++)t[e]=i.value,i=i.next;return t}toArrayReverse(){let t=new Array(this.length);for(let e=0,i=this.tail;i;e++)t[e]=i.value,i=i.prev;return t}slice(t=0,e=this.length){e<0&&(e+=this.length),t<0&&(t+=this.length);let i=new s2;if(e<t||e<0)return i;t<0&&(t=0),e>this.length&&(e=this.length);let r=this.head,n=0;for(n=0;r&&n<t;n++)r=r.next;for(;r&&n<e;n++,r=r.next)i.push(r.value);return i}sliceReverse(t=0,e=this.length){e<0&&(e+=this.length),t<0&&(t+=this.length);let i=new s2;if(e<t||e<0)return i;t<0&&(t=0),e>this.length&&(e=this.length);let r=this.length,n=this.tail;for(;n&&r>e;r--)n=n.prev;for(;n&&r>t;r--,n=n.prev)i.push(n.value);return i}splice(t,e=0,...i){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);let r=this.head;for(let o=0;r&&o<t;o++)r=r.next;let n=[];for(let o=0;r&&o<e;o++)n.push(r.value),r=this.removeNode(r);r?r!==this.tail&&(r=r.prev):r=this.tail;for(let o of i)r=Zn(this,r,o);return n}reverse(){let t=this.head,e=this.tail;for(let i=t;i;i=i.prev){let r=i.prev;i.prev=i.next,i.next=r}return this.head=e,this.tail=t,this}};ue=class{list;next;prev;value;constructor(t,e,i,r){this.list=r,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,i?(i.prev=this,this.next=i):this.next=void 0}};pi=class{path;absolute;entry;stat;readdir;pending=false;pendingLink=false;ignore=false;piped=false;constructor(t,e){this.path=t||"./",this.absolute=e}};nr=Buffer.alloc(1024);li=Symbol("onStat");me=Symbol("ended");W=Symbol("queue");pe=Symbol("pendingLinks");Et=Symbol("current");Ft=Symbol("process");Ee=Symbol("processing");ai=Symbol("processJob");G=Symbol("jobs");ls=Symbol("jobDone");ci=Symbol("addFSEntry");or=Symbol("addTarEntry");ds=Symbol("stat");us=Symbol("readdir");fi=Symbol("onreaddir");di=Symbol("pipe");hr=Symbol("entry");cs=Symbol("entryOpt");ui=Symbol("writeEntryClass");lr=Symbol("write");fs7=Symbol("ondrain");wt=class extends A{sync=false;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[ui];onWriteEntry;[W];[pe]=new Map;[G]=0;[Ee]=false;[me]=false;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=f(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[ui]=de,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=true),this.zip=new ze(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new We(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Ye(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",i=>super.write(i)),e.on("end",()=>super.end()),e.on("drain",()=>this[fs7]()),this.on("resume",()=>e.resume())}else this.on("drain",this[fs7]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>true,this[W]=new hi,this[G]=0,this.jobs=Number(t.jobs)||4,this[Ee]=false,this[me]=false}[lr](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,i){return typeof t=="function"&&(i=t,t=void 0),typeof e=="function"&&(i=e,e=void 0),t&&this.add(t),this[me]=true,this[Ft](),i&&i(),this}write(t){if(this[me])throw new Error("write after end");return typeof t=="string"?this[ci](t):this[or](t),this.flowing}[or](t){let e=f(ar.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let i=new pi(t.path,e);i.entry=new oi(t,this[cs](i)),i.entry.on("end",()=>this[ls](i)),this[G]+=1,this[W].push(i)}this[Ft]()}[ci](t){let e=f(ar.resolve(this.cwd,t));this[W].push(new pi(t,e)),this[Ft]()}[ds](t){t.pending=true,this[G]+=1;let e=this.follow?"stat":"lstat";mi[e](t.absolute,(i,r)=>{t.pending=false,this[G]-=1,i?this.emit("error",i):this[li](t,r)})}[li](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=true;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[Et])this[ai](t);else{let i=`${e.dev}:${e.ino}`,r=this[pe].get(i);r?r.push(t):this[pe].set(i,[t]),t.pendingLink=true,t.pending=true}this[Ft]()}[us](t){t.pending=true,this[G]+=1,mi.readdir(t.absolute,(e,i)=>{if(t.pending=false,this[G]-=1,e)return this.emit("error",e);this[fi](t,i)})}[fi](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Ft]()}[Ft](){if(!this[Ee]){this[Ee]=true;for(let t=this[W].head;t&&this[G]<this.jobs;t=t.next)if(this[ai](t.value),t.value.ignore){let e=t.next;this[W].removeNode(t),t.next=e}this[Ee]=false,this[me]&&this[W].length===0&&this[G]===0&&(this.zip?this.zip.end(nr):(super.write(nr),super.end()))}}get[Et](){return this[W]&&this[W].head&&this[W].head.value}[ls](t){this[W].shift(),this[G]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let i=`${e.dev}:${e.ino}`,r=this[pe].get(i);if(r){this[pe].delete(i);for(let n of r)n.pending=false,this[ai](n)}}this[Ft]()}[ai](t){if(t.pending&&t.pendingLink&&t===this[Et]&&(t.pending=false,t.pendingLink=false),!t.pending){if(t.entry){t===this[Et]&&!t.piped&&this[di](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[li](t,e):this[ds](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[fi](t,e):this[us](t),!t.readdir)return}if(t.entry=this[hr](t),!t.entry){t.ignore=true;return}t===this[Et]&&!t.piped&&this[di](t)}}}[cs](t){return{onwarn:(e,i,r)=>this.warn(e,i,r),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[hr](t){this[G]+=1;try{return new this[ui](t.path,this[cs](t)).on("end",()=>this[ls](t)).on("error",i=>this.emit("error",i))}catch(e){this.emit("error",e)}}[fs7](){this[Et]&&this[Et].entry&&this[Et].entry.resume()}[di](t){t.piped=true,t.readdir&&t.readdir.forEach(r=>{let n=t.path,o=n==="./"?"":n.replace(/\/*$/,"/");this[ci](o+r)});let e=t.entry,i=this.zip;if(!e)throw new Error("cannot pipe without source");i?e.on("data",r=>{i.write(r)||e.pause()}):e.on("data",r=>{super.write(r)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,i={}){Dt(this,t,e,i)}};kt=class extends wt{sync=true;constructor(t){super(t),this[ui]=ni}pause(){}resume(){}[ds](t){let e=this.follow?"statSync":"lstatSync";this[li](t,mi[e](t.absolute))}[us](t){this[fi](t,mi.readdirSync(t.absolute))}[di](t){let e=t.entry,i=this.zip;if(t.readdir&&t.readdir.forEach(r=>{let n=t.path,o=n==="./"?"":n.replace(/\/*$/,"/");this[ci](o+r)}),!e)throw new Error("Cannot pipe without source");i?e.on("data",r=>{i.write(r)}):e.on("data",r=>{super[lr](r)})}};Vn=(s3,t)=>{let e=new kt(s3),i=new Wt(s3.file,{mode:s3.mode||438});e.pipe(i),fr(e,t)};$n=(s3,t)=>{let e=new wt(s3),i=new et(s3.file,{mode:s3.mode||438});e.pipe(i);let r=new Promise((n,o)=>{i.on("error",o),i.on("close",n),e.on("error",o)});return dr(e,t).catch(n=>e.emit("error",n)),r};fr=(s3,t)=>{t.forEach(e=>{e.charAt(0)==="@"?Ct({file:cr.resolve(s3.cwd,e.slice(1)),sync:true,noResume:true,onReadEntry:i=>s3.add(i)}):s3.add(e)}),s3.end()};dr=async(s3,t)=>{for(let e of t)e.charAt(0)==="@"?await Ct({file:cr.resolve(String(s3.cwd),e.slice(1)),noResume:true,onReadEntry:i=>{s3.add(i)}}):s3.add(e);s3.end()};Xn=(s3,t)=>{let e=new kt(s3);return fr(e,t),e};qn=(s3,t)=>{let e=new wt(s3);return dr(e,t).catch(i=>e.emit("error",i)),e};Qn=K(Vn,$n,Xn,qn,(s3,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")});Jn=process.env.__FAKE_PLATFORM__||process.platform;Er=Jn==="win32";({O_CREAT:wr,O_NOFOLLOW:ur,O_TRUNC:Sr,O_WRONLY:yr}=pr.constants);Rr=Number(process.env.__FAKE_FS_O_FILENAME__)||pr.constants.UV_FS_O_FILEMAP||0;jn=Er&&!!Rr;to=512*1024;eo=Rr|Sr|wr|yr;mr=!Er&&typeof ur=="number"?ur|Sr|wr|yr:null;ms=mr!==null?()=>mr:jn?s3=>s3<to?eo:"w":()=>"w";ps=(s3,t,e)=>{try{return wi.lchownSync(s3,t,e)}catch(i){if(i?.code!=="ENOENT")throw i}};Ei=(s3,t,e,i)=>{wi.lchown(s3,t,e,r=>{i(r&&r?.code!=="ENOENT"?r:null)})};io=(s3,t,e,i,r)=>{if(t.isDirectory())Es(we.resolve(s3,t.name),e,i,n=>{if(n)return r(n);let o=we.resolve(s3,t.name);Ei(o,e,i,r)});else{let n=we.resolve(s3,t.name);Ei(n,e,i,r)}};Es=(s3,t,e,i)=>{wi.readdir(s3,{withFileTypes:true},(r,n)=>{if(r){if(r.code==="ENOENT")return i();if(r.code!=="ENOTDIR"&&r.code!=="ENOTSUP")return i(r)}if(r||!n.length)return Ei(s3,t,e,i);let o=n.length,h=null,a=l3=>{if(!h){if(l3)return i(h=l3);if(--o===0)return Ei(s3,t,e,i)}};for(let l3 of n)io(s3,l3,t,e,a)})};so=(s3,t,e,i)=>{t.isDirectory()&&ws(we.resolve(s3,t.name),e,i),ps(we.resolve(s3,t.name),e,i)};ws=(s3,t,e)=>{let i;try{i=wi.readdirSync(s3,{withFileTypes:true})}catch(r){let n=r;if(n?.code==="ENOENT")return;if(n?.code==="ENOTDIR"||n?.code==="ENOTSUP")return ps(s3,t,e);throw n}for(let r of i)so(s3,r,t,e);return ps(s3,t,e)};Se=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}};St=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}};no=(s3,t)=>{k.stat(s3,(e,i)=>{(e||!i.isDirectory())&&(e=new Se(s3,e?.code||"ENOTDIR")),t(e)})};gr=(s3,t,e)=>{s3=f(s3);let i=t.umask??18,r=t.mode|448,n=(r&i)!==0,o=t.uid,h=t.gid,a=typeof o=="number"&&typeof h=="number"&&(o!==t.processUid||h!==t.processGid),l3=t.preserve,c=t.unlink,d2=f(t.cwd),y2=(E2,x2)=>{E2?e(E2):x2&&a?Es(x2,o,h,Le2=>y2(Le2)):n?k.chmod(s3,r,e):e()};if(s3===d2)return no(s3,y2);if(l3)return ro.mkdir(s3,{mode:r,recursive:true}).then(E2=>y2(null,E2??void 0),y2);let D2=f(Si.relative(d2,s3)).split("/");Ss(d2,D2,r,c,d2,void 0,y2)};Ss=(s3,t,e,i,r,n,o)=>{if(t.length===0)return o(null,n);let h=t.shift(),a=f(Si.resolve(s3+"/"+h));k.mkdir(a,e,br(a,t,e,i,r,n,o))};br=(s3,t,e,i,r,n,o)=>h=>{h?k.lstat(s3,(a,l3)=>{if(a)a.path=a.path&&f(a.path),o(a);else if(l3.isDirectory())Ss(s3,t,e,i,r,n,o);else if(i)k.unlink(s3,c=>{if(c)return o(c);k.mkdir(s3,e,br(s3,t,e,i,r,n,o))});else{if(l3.isSymbolicLink())return o(new St(s3,s3+"/"+t.join("/")));o(h)}}):(n=n||s3,Ss(s3,t,e,i,r,n,o))};oo=s3=>{let t=false,e;try{t=k.statSync(s3).isDirectory()}catch(i){e=i?.code}finally{if(!t)throw new Se(s3,e??"ENOTDIR")}};_r=(s3,t)=>{s3=f(s3);let e=t.umask??18,i=t.mode|448,r=(i&e)!==0,n=t.uid,o=t.gid,h=typeof n=="number"&&typeof o=="number"&&(n!==t.processUid||o!==t.processGid),a=t.preserve,l3=t.unlink,c=f(t.cwd),d2=E2=>{E2&&h&&ws(E2,n,o),r&&k.chmodSync(s3,i)};if(s3===c)return oo(c),d2();if(a)return d2(k.mkdirSync(s3,{mode:i,recursive:true})??void 0);let T2=f(Si.relative(c,s3)).split("/"),D2;for(let E2=T2.shift(),x2=c;E2&&(x2+="/"+E2);E2=T2.shift()){x2=f(Si.resolve(x2));try{k.mkdirSync(x2,i),D2=D2||x2}catch{let Le2=k.lstatSync(x2);if(Le2.isDirectory())continue;if(l3){k.unlinkSync(x2),k.mkdirSync(x2,i),D2=D2||x2;continue}else if(Le2.isSymbolicLink())return new St(x2,x2+"/"+T2.join("/"))}}return d2(D2)};ys=Object.create(null);Or=1e4;Vt=new Set;Tr=s3=>{Vt.has(s3)?Vt.delete(s3):ys[s3]=s3.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Vt.add(s3);let t=ys[s3],e=Vt.size-Or;if(e>Or/10){for(let i of Vt)if(Vt.delete(i),delete ys[i],--e<=0)break}return t};ho=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform;ao=ho==="win32";lo=s3=>s3.split("/").slice(0,-1).reduce((e,i)=>{let r=e.at(-1);return r!==void 0&&(i=xr(r,i)),e.push(i||"/"),e},[]);yi=class{#t=new Map;#i=new Map;#s=new Set;reserve(t,e){t=ao?["win32 parallelization disabled"]:t.map(r=>mt(xr(Tr(r))));let i=new Set(t.map(r=>lo(r)).reduce((r,n)=>r.concat(n)));this.#i.set(e,{dirs:i,paths:t});for(let r of t){let n=this.#t.get(r);n?n.push(e):this.#t.set(r,[e])}for(let r of i){let n=this.#t.get(r);if(!n)this.#t.set(r,[new Set([e])]);else{let o=n.at(-1);o instanceof Set?o.add(e):n.push(new Set([e]))}}return this.#r(e)}#n(t){let e=this.#i.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(i=>this.#t.get(i)),dirs:[...e.dirs].map(i=>this.#t.get(i))}}check(t){let{paths:e,dirs:i}=this.#n(t);return e.every(r=>r&&r[0]===t)&&i.every(r=>r&&r[0]instanceof Set&&r[0].has(t))}#r(t){return this.#s.has(t)||!this.check(t)?false:(this.#s.add(t),t(()=>this.#e(t)),true)}#e(t){if(!this.#s.has(t))return false;let e=this.#i.get(t);if(!e)throw new Error("invalid reservation");let{paths:i,dirs:r}=e,n=new Set;for(let o of i){let h=this.#t.get(o);if(!h||h?.[0]!==t)continue;let a=h[1];if(!a){this.#t.delete(o);continue}if(h.shift(),typeof a=="function")n.add(a);else for(let l3 of a)n.add(l3)}for(let o of r){let h=this.#t.get(o),a=h?.[0];if(!(!h||!(a instanceof Set)))if(a.size===1&&h.length===1){this.#t.delete(o);continue}else if(a.size===1){h.shift();let l3=h[0];typeof l3=="function"&&n.add(l3)}else a.delete(t)}return this.#s.delete(t),n.forEach(o=>this.#r(o)),true}};Lr=()=>process.umask();Dr=Symbol("onEntry");_s=Symbol("checkFs");Nr=Symbol("checkFs2");Os=Symbol("isReusable");P=Symbol("makeFs");Ts=Symbol("file");xs=Symbol("directory");gi=Symbol("link");Ar=Symbol("symlink");Ir=Symbol("hardlink");Re=Symbol("ensureNoSymlink");Cr=Symbol("unsupported");Fr=Symbol("checkPath");Rs=Symbol("stripAbsolutePath");yt=Symbol("mkdir");O=Symbol("onError");Ri=Symbol("pending");kr=Symbol("pend");$t=Symbol("unpend");gs=Symbol("ended");bs=Symbol("maybeClose");Ls=Symbol("skip");ge=Symbol("doChown");be=Symbol("uid");_e=Symbol("gid");Oe=Symbol("checkedCwd");fo=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform;Te=fo==="win32";uo=1024;mo=(s3,t)=>{if(!Te)return u.unlink(s3,t);let e=s3+".DELETE."+Mr(16).toString("hex");u.rename(s3,e,i=>{if(i)return t(i);u.unlink(e,t)})};po=s3=>{if(!Te)return u.unlinkSync(s3);let t=s3+".DELETE."+Mr(16).toString("hex");u.renameSync(s3,t),u.unlinkSync(t)};vr=(s3,t,e)=>s3!==void 0&&s3===s3>>>0?s3:t!==void 0&&t===t>>>0?t:e;Xt=class extends rt{[gs]=false;[Oe]=false;[Ri]=0;reservations=new yi;transform;writable=true;readable=false;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[gs]=true,this[bs]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=true}else this.uid=void 0,this.gid=void 0,this.setOwner=false;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?process.getuid?.()===0:!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:uo,this.forceChown=t.forceChown===true,this.win32=!!t.win32||Te,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=f(R.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:Lr():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[Dr](e))}warn(t,e,i={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(i.recoverable=false),super.warn(t,e,i)}[bs](){this[gs]&&this[Ri]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Rs](t,e){let i=t[e],{type:r}=t;if(!i||this.preservePaths)return true;let[n,o]=ce(i),h=o.replaceAll(/\\/g,"/").split("/");if(h.includes("..")||Te&&/^[a-z]:\.\.$/i.test(h[0]??"")){if(e==="path"||r==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:i}),false;let a=R.posix.dirname(t.path),l3=R.posix.normalize(R.posix.join(a,h.join("/")));if(l3.startsWith("../")||l3==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:i}),false}return n&&(t[e]=String(o),this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute ${e}`,{entry:t,[e]:i})),true}[Fr](t){let e=f(t.path),i=e.split("/");if(this.strip){if(i.length<this.strip)return false;if(t.type==="Link"){let r=f(String(t.linkpath)).split("/");if(r.length>=this.strip)t.linkpath=r.slice(this.strip).join("/");else return false}i.splice(0,this.strip),t.path=i.join("/")}if(isFinite(this.maxDepth)&&i.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:i.length,maxDepth:this.maxDepth}),false;if(!this[Rs](t,"path")||!this[Rs](t,"linkpath"))return false;if(t.absolute=R.isAbsolute(t.path)?f(R.resolve(t.path)):f(R.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:f(t.path),resolvedPath:t.absolute,cwd:this.cwd}),false;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return false;if(this.win32){let{root:r}=R.win32.parse(String(t.absolute));t.absolute=r+ts(String(t.absolute).slice(r.length));let{root:n}=R.win32.parse(t.path);t.path=n+ts(t.path.slice(n.length))}return true}[Dr](t){if(!this[Fr](t))return t.resume();switch(co.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[_s](t);default:return this[Cr](t)}}[O](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[$t](),e.resume())}[yt](t,e,i){gr(f(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},i)}[ge](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[be](t){return vr(this.uid,t.uid,this.processUid)}[_e](t){return vr(this.gid,t.gid,this.processGid)}[Ts](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.fmode,r=new et(String(t.absolute),{flags:ms(t.size),mode:i,autoClose:false});r.on("error",a=>{r.fd&&u.close(r.fd,()=>{}),r.write=()=>true,this[O](a,t),e()});let n=1,o=a=>{if(a){r.fd&&u.close(r.fd,()=>{}),this[O](a,t),e();return}--n===0&&r.fd!==void 0&&u.close(r.fd,l3=>{l3?this[O](l3,t):this[$t](),e()})};r.on("finish",()=>{let a=String(t.absolute),l3=r.fd;if(typeof l3=="number"&&t.mtime&&!this.noMtime){n++;let c=t.atime||new Date,d2=t.mtime;u.futimes(l3,c,d2,y2=>y2?u.utimes(a,c,d2,T2=>o(T2&&y2)):o())}if(typeof l3=="number"&&this[ge](t)){n++;let c=this[be](t),d2=this[_e](t);typeof c=="number"&&typeof d2=="number"&&u.fchown(l3,c,d2,y2=>y2?u.chown(a,c,d2,T2=>o(T2&&y2)):o())}o()});let h=this.transform&&this.transform(t)||t;h!==t&&(h.on("error",a=>{this[O](a,t),e()}),t.pipe(h)),h.pipe(r)}[xs](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.dmode;this[yt](String(t.absolute),i,r=>{if(r){this[O](r,t),e();return}let n=1,o=()=>{--n===0&&(e(),this[$t](),t.resume())};t.mtime&&!this.noMtime&&(n++,u.utimes(String(t.absolute),t.atime||new Date,t.mtime,o)),this[ge](t)&&(n++,u.chown(String(t.absolute),Number(this[be](t)),Number(this[_e](t)),o)),o()})}[Cr](t){t.unsupported=true,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Ar](t,e){let i=f(R.relative(this.cwd,R.resolve(R.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Re](t,this.cwd,i,()=>this[gi](t,String(t.linkpath),"symlink",e),r=>{this[O](r,t),e()})}[Ir](t,e){let i=f(R.resolve(this.cwd,String(t.linkpath))),r=f(String(t.linkpath)).split("/");this[Re](t,this.cwd,r,()=>this[gi](t,i,"link",e),n=>{this[O](n,t),e()})}[Re](t,e,i,r,n){let o=i.shift();if(this.preservePaths||o===void 0)return r();let h=R.resolve(e,o);u.lstat(h,(a,l3)=>{if(a)return r();if(l3?.isSymbolicLink())return n(new St(h,R.resolve(h,i.join("/"))));this[Re](t,h,i,r,n)})}[kr](){this[Ri]++}[$t](){this[Ri]--,this[bs]()}[Ls](t){this[$t](),t.resume()}[Os](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Te}[_s](t){this[kr]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,i=>this[Nr](t,i))}[Nr](t,e){let i=h=>{e(h)},r=()=>{this[yt](this.cwd,this.dmode,h=>{if(h){this[O](h,t),i();return}this[Oe]=true,n()})},n=()=>{if(t.absolute!==this.cwd){let h=f(R.dirname(String(t.absolute)));if(h!==this.cwd)return this[yt](h,this.dmode,a=>{if(a){this[O](a,t),i();return}o()})}o()},o=()=>{u.lstat(String(t.absolute),(h,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(t.mtime??a.mtime))){this[Ls](t),i();return}if(h||this[Os](t,a))return this[P](null,t,i);if(a.isDirectory()){if(t.type==="Directory"){let l3=this.chmod&&t.mode&&(a.mode&4095)!==t.mode,c=d2=>this[P](d2??null,t,i);return l3?u.chmod(String(t.absolute),Number(t.mode),c):c()}if(t.absolute!==this.cwd)return u.rmdir(String(t.absolute),l3=>this[P](l3??null,t,i))}if(t.absolute===this.cwd)return this[P](null,t,i);mo(String(t.absolute),l3=>this[P](l3??null,t,i))})};this[Oe]?n():r()}[P](t,e,i){if(t){this[O](t,e),i();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Ts](e,i);case"Link":return this[Ir](e,i);case"SymbolicLink":return this[Ar](e,i);case"Directory":case"GNUDumpDir":return this[xs](e,i)}}[gi](t,e,i,r){u[i](e,String(t.absolute),n=>{n?this[O](n,t):(this[$t](),t.resume()),r()})}};ye=s3=>{try{return[null,s3()]}catch(t){return[t,null]}};xe=class extends Xt{sync=true;[P](t,e){return super[P](t,e,()=>{})}[_s](t){if(!this[Oe]){let n=this[yt](this.cwd,this.dmode);if(n)return this[O](n,t);this[Oe]=true}if(t.absolute!==this.cwd){let n=f(R.dirname(String(t.absolute)));if(n!==this.cwd){let o=this[yt](n,this.dmode);if(o)return this[O](o,t)}}let[e,i]=ye(()=>u.lstatSync(String(t.absolute)));if(i&&(this.keep||this.newer&&i.mtime>(t.mtime??i.mtime)))return this[Ls](t);if(e||this[Os](t,i))return this[P](null,t);if(i.isDirectory()){if(t.type==="Directory"){let o=this.chmod&&t.mode&&(i.mode&4095)!==t.mode,[h]=o?ye(()=>{u.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[P](h,t)}let[n]=ye(()=>u.rmdirSync(String(t.absolute)));this[P](n,t)}let[r]=t.absolute===this.cwd?[]:ye(()=>po(String(t.absolute)));this[P](r,t)}[Ts](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.fmode,r=h=>{let a;try{u.closeSync(n)}catch(l3){a=l3}(h||a)&&this[O](h||a,t),e()},n;try{n=u.openSync(String(t.absolute),ms(t.size),i)}catch(h){return r(h)}let o=this.transform&&this.transform(t)||t;o!==t&&(o.on("error",h=>this[O](h,t)),t.pipe(o)),o.on("data",h=>{try{u.writeSync(n,h,0,h.length)}catch(a){r(a)}}),o.on("end",()=>{let h=null;if(t.mtime&&!this.noMtime){let a=t.atime||new Date,l3=t.mtime;try{u.futimesSync(n,a,l3)}catch(c){try{u.utimesSync(String(t.absolute),a,l3)}catch{h=c}}}if(this[ge](t)){let a=this[be](t),l3=this[_e](t);try{u.fchownSync(n,Number(a),Number(l3))}catch(c){try{u.chownSync(String(t.absolute),Number(a),Number(l3))}catch{h=h||c}}}r(h)})}[xs](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.dmode,r=this[yt](String(t.absolute),i);if(r){this[O](r,t),e();return}if(t.mtime&&!this.noMtime)try{u.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[ge](t))try{u.chownSync(String(t.absolute),Number(this[be](t)),Number(this[_e](t)))}catch{}e(),t.resume()}[yt](t,e){try{return _r(f(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(i){return i}}[Re](t,e,i,r,n){if(this.preservePaths||i.length===0)return r();let o=e;for(let h of i){o=R.resolve(o,h);let[a,l3]=ye(()=>u.lstatSync(o));if(a)return r();if(l3.isSymbolicLink())return n(new St(o,R.resolve(e,i.join("/"))))}r()}[gi](t,e,i,r){let n=`${i}Sync`;try{u[n](e,String(t.absolute)),r(),t.resume()}catch(o){return this[O](o,t)}}};Eo=s3=>{let t=new xe(s3),e=s3.file,i=Br.statSync(e),r=s3.maxReadSize||16*1024*1024;new Be(e,{readSize:r,size:i.size}).pipe(t)};wo=(s3,t)=>{let e=new Xt(s3),i=s3.maxReadSize||16*1024*1024,r=s3.file;return new Promise((o,h)=>{e.on("error",h),e.on("close",o),Br.stat(r,(a,l3)=>{if(a)h(a);else{let c=new _t(r,{readSize:i,size:l3.size});c.on("error",h),c.pipe(e)}})})};So=K(Eo,wo,s3=>new xe(s3),s3=>new Xt(s3),(s3,t)=>{t?.length&&Qi(s3,t)});yo=(s3,t)=>{let e=new kt(s3),i=true,r,n;try{try{r=v.openSync(s3.file,"r+")}catch(a){if(a?.code==="ENOENT")r=v.openSync(s3.file,"w+");else throw a}let o=v.fstatSync(r),h=Buffer.alloc(512);t:for(n=0;n<o.size;n+=512){for(let c=0,d2=0;c<512;c+=d2){if(d2=v.readSync(r,h,c,h.length-c,n+c),n===0&&h[0]===31&&h[1]===139)throw new Error("cannot append to compressed archives");if(!d2)break t}let a=new F(h);if(!a.cksumValid)break;let l3=512*Math.ceil((a.size||0)/512);if(n+l3+512>o.size)break;n+=l3,s3.mtimeCache&&a.mtime&&s3.mtimeCache.set(String(a.path),a.mtime)}i=false,Ro(s3,e,n,r,t)}finally{if(i)try{v.closeSync(r)}catch{}}};Ro=(s3,t,e,i,r)=>{let n=new Wt(s3.file,{fd:i,start:e});t.pipe(n),bo(t,r)};go=(s3,t)=>{t=Array.from(t);let e=new wt(s3),i=(n,o,h)=>{let a=(T2,D2)=>{T2?v.close(n,E2=>h(T2)):h(null,D2)},l3=0;if(o===0)return a(null,0);let c=0,d2=Buffer.alloc(512),y2=(T2,D2)=>{if(T2||D2===void 0)return a(T2);if(c+=D2,c<512&&D2)return v.read(n,d2,c,d2.length-c,l3+c,y2);if(l3===0&&d2[0]===31&&d2[1]===139)return a(new Error("cannot append to compressed archives"));if(c<512)return a(null,l3);let E2=new F(d2);if(!E2.cksumValid)return a(null,l3);let x2=512*Math.ceil((E2.size??0)/512);if(l3+x2+512>o||(l3+=x2+512,l3>=o))return a(null,l3);s3.mtimeCache&&E2.mtime&&s3.mtimeCache.set(String(E2.path),E2.mtime),c=0,v.read(n,d2,0,512,l3,y2)};v.read(n,d2,0,512,l3,y2)};return new Promise((n,o)=>{e.on("error",o);let h="r+",a=(l3,c)=>{if(l3&&l3.code==="ENOENT"&&h==="r+")return h="w+",v.open(s3.file,h,a);if(l3||!c)return o(l3);v.fstat(c,(d2,y2)=>{if(d2)return v.close(c,()=>o(d2));i(c,y2.size,(T2,D2)=>{if(T2)return o(T2);let E2=new et(s3.file,{fd:c,start:D2});e.pipe(E2),E2.on("error",o),E2.on("close",n),_o(e,t)})})};v.open(s3.file,h,a)})};bo=(s3,t)=>{t.forEach(e=>{e.charAt(0)==="@"?Ct({file:Pr.resolve(s3.cwd,e.slice(1)),sync:true,noResume:true,onReadEntry:i=>s3.add(i)}):s3.add(e)}),s3.end()};_o=async(s3,t)=>{for(let e of t)e.charAt(0)==="@"?await Ct({file:Pr.resolve(String(s3.cwd),e.slice(1)),noResume:true,onReadEntry:i=>s3.add(i)}):s3.add(e);s3.end()};vt=K(yo,go,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(s3,t)=>{if(!Bs(s3))throw new TypeError("file is required");if(s3.gzip||s3.brotli||s3.zstd||s3.file.endsWith(".br")||s3.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!t?.length)throw new TypeError("no paths specified to add/replace")});Oo=K(vt.syncFile,vt.asyncFile,vt.syncNoFile,vt.asyncNoFile,(s3,t=[])=>{vt.validate?.(s3,t),To(s3)});To=s3=>{let t=s3.filter;s3.mtimeCache||(s3.mtimeCache=new Map),s3.filter=t?(e,i)=>t(e,i)&&!((s3.mtimeCache?.get(e)??i.mtime??0)>(i.mtime??0)):(e,i)=>!((s3.mtimeCache?.get(e)??i.mtime??0)>(i.mtime??0))}}});function safePrefix(text2,n){let cut=Math.min(n,text2.length);if(cut>0&&cut<text2.length){const c=text2.charCodeAt(cut-1);if(c>=55296&&c<=56319)cut-=1}return text2.slice(0,cut)}function safeSuffix(text2,n){const cut0=Math.max(0,text2.length-n);let cut=cut0;if(cut>0&&cut<text2.length){const c=text2.charCodeAt(cut);if(c>=56320&&c<=57343)cut+=1}return text2.slice(cut)}function scrubLoneSurrogates2(text2){return text2.replace(/[\ud800-\udbff](?![\udc00-\udfff])/g,"\uFFFD").replace(/(?<![\ud800-\udbff])[\udc00-\udfff]/g,"\uFFFD")}function scrubLoneSurrogateEscapes(text2){if(text2.indexOf("\\u")===-1)return text2;const n=text2.length;const parts=[];let pos=0;let i=0;while((i=text2.indexOf("\\",i))!==-1){if(i>pos)parts.push(text2.slice(pos,i));let j3=i;while(j3<n&&text2.charCodeAt(j3)===92)j3+=1;const run=j3-i;parts.push(text2.slice(i,j3));pos=j3;if(run%2===0){i=j3;continue}if(text2.charCodeAt(j3)!==117){i=j3;continue}const hex=text2.slice(j3+1,j3+5);if(!/^[0-9a-fA-F]{4}$/.test(hex)){i=j3;continue}const cp2=parseInt(hex,16);if(cp2>=56320&&cp2<=57343){parts.push("ufffd");pos=j3+5;i=j3+5;continue}if(cp2>=55296&&cp2<=56319){const nextHex=text2.slice(j3+7,j3+11);if(text2.charCodeAt(j3+5)===92&&text2.charCodeAt(j3+6)===117&&/^[0-9a-fA-F]{4}$/.test(nextHex)){const lo2=parseInt(nextHex,16);if(lo2>=56320&&lo2<=57343){parts.push(text2.slice(j3,j3+11));pos=j3+11;i=j3+11;continue}}parts.push("ufffd");pos=j3+5;i=j3+5;continue}parts.push(text2.slice(j3,j3+5));pos=j3+5;i=j3+5}if(pos<n)parts.push(text2.slice(pos));return parts.join("")}function scrubLoneSurrogatesOnWire(text2){return scrubLoneSurrogateEscapes(scrubLoneSurrogates2(text2))}var init_text_safe=__esm({"src/text-safe.ts"(){"use strict"}});import fs8 from"fs";import path12 from"path";function readJsonFile(file){try{return JSON.parse(fs8.readFileSync(file,"utf8"))}catch{return void 0}}function unquote(v3){return v3.replace(/^["']|["']$/g,"")}function yamlScalar(v3){return/^[A-Za-z0-9.^~_-][\w.^~*-]*$/.test(v3)?v3:JSON.stringify(v3)}function readDshLedgerState(profileDir){const state6={spec:dshProfileDepSpec(profileDir),lockKind:"none"};const doc=readJsonFile(path12.join(profileDir,"node_modules",DSH_PACKAGE,"package.json"));if(typeof doc?.version==="string")state6.copyVersion=doc.version;const pnpm=readPnpmLockResolution(profileDir);if(pnpm!==void 0){state6.lockKind="pnpm";state6.lockSpecifier=pnpm.specifier;state6.lockVersion=pnpm.version;return state6}const npm=readPackageLockResolution(profileDir);if(npm!==void 0){state6.lockKind="npm";state6.lockSpecifier=npm.specifier;state6.lockVersion=npm.version}return state6}function readPnpmLockResolution(profileDir){let text2;try{text2=fs8.readFileSync(path12.join(profileDir,"pnpm-lock.yaml"),"utf8")}catch{return void 0}const lines=text2.split("\n");const out={};let section="";for(let i=0;i<lines.length;i++){const line=lines[i];if(!/^[ \t]/.test(line)){section=line.match(/^([A-Za-z_][\w-]*):/)?.[1]??"";continue}const m3=line.match(PKG_ENTRY_RE);if(m3===null)continue;if(m3[3]!==void 0){if(section==="specifiers"&&out.specifier===void 0)out.specifier=unquote(m3[3]);else if(section==="dependencies"&&out.version===void 0)out.version=unquote(m3[3]);continue}const indent=m3[1].length;for(let j3=i+1;j3<lines.length;j3++){const inner=lines[j3];if(inner.trim()==="")continue;const innerIndent=inner.match(/^[ \t]*/)?.[0].length??0;if(innerIndent<=indent)break;const spec=inner.match(/^\s*specifier:\s*(\S+)/);if(spec&&out.specifier===void 0)out.specifier=unquote(spec[1]);const ver=inner.match(/^\s*version:\s*(\S+)/);if(ver&&out.version===void 0)out.version=unquote(ver[1])}}return out.specifier!==void 0||out.version!==void 0?out:void 0}function readPackageLockResolution(profileDir){const doc=readJsonFile(path12.join(profileDir,"package-lock.json"));if(doc?.packages===void 0)return void 0;const out={};const spec=doc.packages[""]?.dependencies?.[DSH_PACKAGE];if(typeof spec==="string")out.specifier=spec;const resolved=doc.packages[`node_modules/${DSH_PACKAGE}`];if(resolved!==void 0&&typeof resolved.version==="string")out.version=resolved.version;return out.specifier!==void 0||out.version!==void 0?out:void 0}function specAdmits(spec,version){const base=spec.replace(/^[~^]/,"");const parse4=s3=>{const m3=s3.match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return m3?[Number(m3[1]),Number(m3[2]),Number(m3[3])]:void 0};const b3=parse4(base);const v3=parse4(version);if(b3===void 0||v3===void 0)return void 0;if(v3[0]!==b3[0])return false;if(spec.startsWith("^"))return v3[1]>b3[1]||v3[1]===b3[1]&&v3[2]>=b3[2];if(spec.startsWith("~"))return v3[1]===b3[1]&&v3[2]>=b3[2];return v3[1]===b3[1]&&v3[2]===b3[2]}function topLevelSections(lines){const sections=new Map;let current;for(let i=0;i<lines.length;i++){const m3=lines[i].match(/^([A-Za-z_][\w-]*):/);if(m3!==null){if(current!==void 0)sections.set(current[0],[current[1],i]);current=[m3[1],i]}else if(current!==void 0&&lines[i].trim()!==""&&!/^[ \t]/.test(lines[i])){sections.set(current[0],[current[1],i]);current=void 0}}if(current!==void 0)sections.set(current[0],[current[1],lines.length]);return sections}function patchNestedEntries(lines,from,to2,spec,version){const details=[];let patched=0;for(let i=from;i<to2;i++){const m3=lines[i].match(PKG_ENTRY_RE);if(m3===null||m3[3]!==void 0)continue;const indent=m3[1].length;let sawSpecifier=false;let sawVersion=false;for(let j3=i+1;j3<to2;j3++){const inner=lines[j3];if(inner.trim()==="")continue;const innerIndent=inner.match(/^[ \t]*/)?.[0].length??0;if(innerIndent<=indent)break;const sm=inner.match(/^([ \t]*)specifier:[ \t]*(\S.*)?$/);if(sm!==null){sawSpecifier=true;const want=yamlScalar(spec);if(unquote(sm[2]??"")!==spec){lines[j3]=`${sm[1]}specifier: ${want}`;details.push({file:"pnpm-lock.yaml",field:"specifier",before:unquote(sm[2]??""),after:spec})}continue}const vm=inner.match(/^([ \t]*)version:[ \t]*(\S.*)?$/);if(vm!==null){sawVersion=true;if(unquote(vm[2]??"")!==version){lines[j3]=`${vm[1]}version: ${yamlScalar(version)}`;details.push({file:"pnpm-lock.yaml",field:"version",before:unquote(vm[2]??""),after:version})}}}if(!sawSpecifier||!sawVersion){return{kind:"fail",reason:"the lockfile's billion-context entry lacks both specifier: and version: fields \u2014 structure not recognized, manual repair needed"}}patched++}if(patched===0)return{kind:"fail",reason:"no billion-context entry found in the lockfile \u2014 run 'dsh plugin --profile <name> add billion-context' once so the package manager records the resolution, then retry"};return{kind:"ok",next:lines.join("\n"),details}}function patchFlatEntries(lines,spec,version){const sections=topLevelSections(lines);const details=[];const patchSection=(key2,value,field)=>{const range=sections.get(key2);if(range===void 0)return`no top-level '${key2}:' section in the lockfile`;for(let i=range[0]+1;i<range[1];i++){const m3=lines[i].match(PKG_ENTRY_RE);if(m3===null||m3[3]===void 0)continue;const cur=unquote(m3[3]);if(cur!==value){lines[i]=`${m3[1]}${DSH_PACKAGE}: ${yamlScalar(value)}`;details.push({file:"pnpm-lock.yaml",field,before:cur,after:value})}return void 0}return`no ${DSH_PACKAGE} entry under the '${key2}:' section`};const err1=patchSection("specifiers",spec,"specifier");if(err1!==void 0)return{kind:"fail",reason:err1};const err2=patchSection("dependencies",version,"version");if(err2!==void 0)return{kind:"fail",reason:err2};return{kind:"ok",next:lines.join("\n"),details}}function patchPnpmLock(text2,spec,version){const lines=text2.split("\n");const sections=topLevelSections(lines);if(sections.has("importers")){const range=sections.get("importers");return patchNestedEntries(lines,range[0],range[1],spec,version)}if(sections.has("specifiers")){return patchFlatEntries(lines,spec,version)}const candidates=["dependencies","devDependencies"].filter(k2=>sections.has(k2));if(candidates.length>0){const details=[];let patched=0;for(const key2 of candidates){const range=sections.get(key2);const sub=patchNestedEntries(lines.slice(range[0],range[1]),0,range[1]-range[0],spec,version);if(sub.kind==="fail"){if(patched===0&&!sub.reason.startsWith("no billion-context entry"))return sub;continue}lines.splice(range[0],range[1]-range[0],...sub.next.split("\n"));details.push(...sub.details);patched++}if(patched===0)return{kind:"fail",reason:"no billion-context entry found in the lockfile \u2014 run 'dsh plugin --profile <name> add billion-context' once so the package manager records the resolution, then retry"};return{kind:"ok",next:lines.join("\n"),details}}return{kind:"fail",reason:"lockfile shape not recognized (no importers/specifiers/dependencies sections)"}}function patchNpmLock(raw,spec,version){let doc;try{doc=JSON.parse(raw)}catch{return{kind:"fail",reason:"malformed package-lock.json \u2014 manual repair needed"}}if(doc.packages===void 0)return{kind:"fail",reason:"package-lock.json has no packages map"};const details=[];const root=doc.packages[""];if(root===void 0)return{kind:"fail",reason:'package-lock.json has no root ("") package entry'};const deps=typeof root.dependencies==="object"&&root.dependencies!==null?root.dependencies:{};if(typeof deps[DSH_PACKAGE]==="string"&&deps[DSH_PACKAGE]!==spec){details.push({file:"package-lock.json",field:"root dependencies[billion-context]",before:String(deps[DSH_PACKAGE]),after:spec})}deps[DSH_PACKAGE]=spec;root.dependencies=deps;const entry=doc.packages[`node_modules/${DSH_PACKAGE}`];if(entry===void 0)return{kind:"fail",reason:`package-lock.json has no node_modules/${DSH_PACKAGE} entry \u2014 manual repair needed`};if(typeof entry.version==="string"&&entry.version!==version){details.push({file:"package-lock.json",field:"version",before:entry.version,after:version});entry.version=version;if(typeof entry.resolved==="string"&&entry.resolved.includes(`/${DSH_PACKAGE}/-/${DSH_PACKAGE}-`)){const nextResolved=entry.resolved.replace(new RegExp(`${PKG_ESCAPED}-[^/"]*\\.tgz$`),`${DSH_PACKAGE}-${version}.tgz`);if(nextResolved!==entry.resolved)details.push({file:"package-lock.json",field:"resolved",before:entry.resolved,after:nextResolved});entry.resolved=nextResolved}if(entry.integrity!==void 0){details.push({file:"package-lock.json",field:"integrity",before:"stale hash dropped",after:"(removed \u2014 re-fetched on next install)"});delete entry.integrity}}return{kind:"ok",next:JSON.stringify(doc,null,2)+"\n",details}}function atomicWriteText(file,content){const tmp=`${file}.${process.pid}.tmp`;try{const fd=fs8.openSync(tmp,"w");try{fs8.writeFileSync(fd,content);fs8.fsyncSync(fd)}finally{fs8.closeSync(fd)}fs8.renameSync(tmp,file)}catch(e){try{fs8.rmSync(tmp,{force:true})}catch{}return e instanceof Error?e.message:String(e)}return void 0}function convergeDshLedger(profileDir,targetVersion){const notes=[];const state6=readDshLedgerState(profileDir);const fail=error=>({changed:[],details:[],notes,error});const spec=state6.spec;if(spec===void 0)return fail("no billion-context dependency declared in the profile manifest \u2014 nothing to converge");if(!isRegistryDepSpec(spec)){notes.push(`local pin ${spec} respected \u2014 nothing written`);return{changed:[],details:[],notes}}if(state6.copyVersion===void 0)return fail("no readable bundle copy under node_modules \u2014 converge needs the on-disk version as the meeting point (reinstall through the host channel first)");if(state6.copyVersion!==targetVersion){return fail(`on-disk copy is v${state6.copyVersion}, not v${targetVersion} \u2014 refusing to converge against a moving target`)}const plan2=planDshProfileManifestSpec(profileDir,targetVersion);let finalSpec=spec;if(plan2.action==="rewrite"){finalSpec=plan2.nextSpec??spec}else if(plan2.reason!==void 0&&plan2.reason.startsWith("non-version spec")){if(specAdmits(spec,targetVersion)===false){return fail(`manifest spec ${spec} does not admit the on-disk v${targetVersion} and is outside bili's rewrite authority (only ^x.y.z / x.y.z forms are converged) \u2014 align the declaration yourself, or reinstall through the host channel`)}notes.push(`spec ${spec} kept as declared (not a convergable form)`)}else if(plan2.reason!==void 0){return fail(plan2.reason)}let lockNext;let lockDetails=[];if(state6.lockKind==="none"){notes.push("no lockfile present \u2014 manifest/copy agreement is the whole story")}else{const lockFile=state6.lockKind==="pnpm"?"pnpm-lock.yaml":"package-lock.json";let raw;try{raw=fs8.readFileSync(path12.join(profileDir,lockFile),"utf8")}catch{return fail(`lockfile ${lockFile} vanished between read and patch \u2014 retry`)}const patch=state6.lockKind==="pnpm"?patchPnpmLock(raw,finalSpec,targetVersion):patchNpmLock(raw,finalSpec,targetVersion);if(patch.kind==="fail")return fail(patch.reason);if(patch.details.length>0){lockNext=patch.next;lockDetails=patch.details}}const changed=[];const details=[];if(plan2.action==="rewrite"){const err2=atomicWriteText(path12.join(profileDir,"package.json"),plan2.nextRaw??"");if(err2!==void 0)return{changed,details,notes,error:`manifest write failed: ${err2}`};changed.push("package.json");details.push({file:"package.json",field:"dependencies[billion-context]",before:spec,after:finalSpec})}if(lockNext!==void 0){const lockFile=state6.lockKind==="pnpm"?"pnpm-lock.yaml":"package-lock.json";const err2=atomicWriteText(path12.join(profileDir,lockFile),lockNext);if(err2!==void 0)return{changed,details,notes,error:`lockfile write failed: ${err2}${changed.length>0?` (package.json already updated \u2014 rerun to finish)`:""}`};changed.push(lockFile);details.push(...lockDetails)}return{changed,details,notes}}var PKG_ESCAPED,PKG_ENTRY_RE;var init_dsh_ledger=__esm({"src/dsh-ledger.ts"(){"use strict";init_dsh_channel();PKG_ESCAPED=DSH_PACKAGE.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");PKG_ENTRY_RE=new RegExp(`^([ \\t]+)${PKG_ESCAPED}:([ \\t]*(\\S+))?[ \\t]*$`)}});import{readFile,writeFile,mkdir,rename,unlink}from"fs/promises";import path13 from"path";function parseSemver(version){const match=version.match(SEMVER_LOOSE_RE);if(!match)return void 0;return{parts:[Number(match[1]),Number(match[2]),Number(match[3])],pre:match[4]?.split(".")??[]}}function compareSemver(a,b3){for(let i=0;i<3;i++){if(a.parts[i]!==b3.parts[i])return a.parts[i]<b3.parts[i]?-1:1}if(a.pre.length===0&&b3.pre.length===0)return 0;if(a.pre.length===0)return 1;if(b3.pre.length===0)return-1;const len=Math.max(a.pre.length,b3.pre.length);for(let i=0;i<len;i++){const x2=a.pre[i];const y2=b3.pre[i];if(x2===void 0)return-1;if(y2===void 0)return 1;const xn2=/^\d+$/.test(x2);const yn2=/^\d+$/.test(y2);if(xn2&&yn2){if(x2!==y2)return Number(x2)<Number(y2)?-1:1}else if(xn2){return-1}else if(yn2){return 1}else if(x2!==y2){return x2<y2?-1:1}}return 0}function expandCaret(v3){const base=parseSemver(v3);if(!base)return void 0;const[maj,min,pat]=base.parts;let upper;if(maj>0)upper={parts:[maj+1,0,0],pre:[]};else if(min>0)upper={parts:[0,min+1,0],pre:[]};else upper={parts:[0,0,pat+1],pre:[]};return[{op:"gte",v:base},{op:"lt",v:upper}]}function expandTilde(v3){const base=parseSemver(v3);if(!base)return void 0;const[maj,min]=base.parts;return[{op:"gte",v:base},{op:"lt",v:{parts:[maj,min+1,0],pre:[]}}]}function parseComparatorToken(token){const t=token.trim();if(t===""||t==="*")return[];let m3;if(m3=t.match(/^\^(.+)$/))return expandCaret(m3[1]);if(m3=t.match(/^~(.+)$/))return expandTilde(m3[1]);if(m3=t.match(/^(>=|<=|>|<|=)?\s*(.+)$/)){const v3=parseSemver(m3[2].trim());if(!v3)return void 0;const opRaw=m3[1]??"=";const op=opRaw===">="?"gte":opRaw==="<="?"lte":opRaw===">"?"gt":opRaw==="<"?"lt":"eq";return[{op,v:v3}]}return void 0}function parseSemverRange(range){const groups=range.split("||").map(g3=>g3.trim()).filter(g3=>g3.length>0);if(groups.length===0)return[[]];const out=[];for(const group of groups){const comps=[];for(const token of group.split(/\s+/)){const parsed=parseComparatorToken(token);if(!parsed)return void 0;comps.push(...parsed)}out.push(comps)}return out}function compareWithOp(cmp,op){switch(op){case"eq":return cmp===0;case"gt":return cmp>0;case"gte":return cmp>=0;case"lt":return cmp<0;case"lte":return cmp<=0}}function satisfiesGroup(v3,group){if(v3.pre.length>0){const tagged=group.some(c=>c.v.pre.length>0&&c.v.parts[0]===v3.parts[0]&&c.v.parts[1]===v3.parts[1]&&c.v.parts[2]===v3.parts[2]);if(!tagged)return false}return group.every(c=>compareWithOp(compareSemver(v3,c.v),c.op))}function satisfiesRange(version,range){const v3=parseSemver(version);if(!v3)return false;return range.some(group=>satisfiesGroup(v3,group))}function delayField(value,label,warnings){if(value===void 0)return void 0;if(typeof value==="number"&&Number.isInteger(value)&&value>=0&&value<=DELAY_SANITY_CAP_MS)return value;if(typeof value==="string"){const ms2=parseDurationField(value);if(ms2!==void 0&&ms2<=DELAY_SANITY_CAP_MS)return ms2}warnings.push(`${label}: invalid value ${JSON.stringify(value)} (a duration like "15m"/"2d"/"1d12h", or a non-negative integer ms \u2264 ${DELAY_SANITY_CAP_MS}) \u2014 field ignored`);return void 0}function normalizePolicyDoc(raw){const warnings=[];if(typeof raw!=="object"||raw===null||Array.isArray(raw)){return{doc:void 0,error:"document is not a JSON object",warnings}}const p2=raw;if(p2.schemaVersion!==POLICY_SCHEMA_VERSION){return{doc:void 0,error:`unsupported schemaVersion ${JSON.stringify(p2.schemaVersion)} (supported: ${POLICY_SCHEMA_VERSION})`,warnings}}let defaultWindow;if(p2.default!==void 0){if(typeof p2.default==="object"&&p2.default!==null&&!Array.isArray(p2.default)){const d2=p2.default;const mn2=delayField(d2.minDelay,"default.minDelay",warnings);const mx=delayField(d2.maxDelay,"default.maxDelay",warnings);if(mn2!==void 0&&mx!==void 0){if(mn2<=mx)defaultWindow={minDelayMs:mn2,maxDelayMs:mx};else warnings.push("default: minDelay > maxDelay \u2014 block ignored")}else if(mn2!==void 0||mx!==void 0){defaultWindow={};if(mn2!==void 0)defaultWindow.minDelayMs=mn2;if(mx!==void 0)defaultWindow.maxDelayMs=mx}}else{warnings.push("default: not an object \u2014 ignored")}}const overrides=[];if(p2.overrides!==void 0){if(!Array.isArray(p2.overrides)){warnings.push("overrides: not an array \u2014 ignored")}else{if(p2.overrides.length>MAX_OVERRIDES)warnings.push(`overrides: more than ${MAX_OVERRIDES} entries \u2014 extras ignored`);for(const item of p2.overrides.slice(0,MAX_OVERRIDES)){if(typeof item!=="object"||item===null){warnings.push("overrides: non-object entry ignored");continue}const o=item;const entry={};let selectorCount=0;let usable=true;if(o.version!==void 0){if(typeof o.version==="string"&&SEMVER_STRICT_RE.test(o.version)){entry.version=o.version;selectorCount++}else{warnings.push(`overrides: entry with invalid version ${JSON.stringify(o.version)} ignored`);usable=false}}if(o.range!==void 0){if(typeof o.range==="string"){const r=parseSemverRange(o.range);if(r){entry.range=r;selectorCount++}else{warnings.push(`overrides: unparseable range ${JSON.stringify(o.range)} \u2014 ignored`)}}else{warnings.push("overrides: range must be a string \u2014 ignored")}}if(selectorCount===0){warnings.push("overrides: entry without a usable version/range selector ignored");continue}if(selectorCount===2){warnings.push(`overrides: entry has both version and range (${JSON.stringify({version:o.version,range:o.range})}) \u2014 entry ignored`);continue}const mn2=delayField(o.minDelay,"overrides[].minDelay",warnings);const mx=delayField(o.maxDelay,"overrides[].maxDelay",warnings);if(mn2===void 0&&mx===void 0){warnings.push("overrides: entry without min/max delay has no effect \u2014 ignored");continue}if(mn2!==void 0&&mx!==void 0&&mn2>mx){warnings.push("overrides: entry minDelay > maxDelay \u2014 entry ignored");continue}if(!usable)continue;if(mn2!==void 0)entry.minDelayMs=mn2;if(mx!==void 0)entry.maxDelayMs=mx;overrides.push(entry)}}}let hold=false;if(p2.hold!==void 0){if(typeof p2.hold==="boolean")hold=p2.hold;else warnings.push(`hold: not a boolean (${JSON.stringify(p2.hold)}) \u2014 treated as false`)}let blocked=[];if(p2.blocked!==void 0){if(!Array.isArray(p2.blocked)){warnings.push("blocked: not an array \u2014 ignored")}else{if(p2.blocked.length>MAX_BLOCKED)warnings.push(`blocked: more than ${MAX_BLOCKED} entries \u2014 extras ignored`);for(const item of p2.blocked.slice(0,MAX_BLOCKED)){if(typeof item==="string"&&SEMVER_STRICT_RE.test(item)&&!blocked.includes(item))blocked.push(item);else warnings.push(`blocked: invalid version ${JSON.stringify(item)} (must be a published semver like "0.1.200") \u2014 entry ignored`)}}}let pinned=null;if(p2.pinned!==void 0&&p2.pinned!==null){if(typeof p2.pinned==="string"&&SEMVER_STRICT_RE.test(p2.pinned))pinned=p2.pinned;else warnings.push(`pinned: invalid version ${JSON.stringify(p2.pinned)} (must be null or a published semver) \u2014 treated as null`)}return{doc:{defaultWindow,overrides,hold,blocked,pinned},warnings}}function resolveStaggerWindow(candidate,policy,localMinMs,localMaxMs){const d2=policy?.defaultWindow;let minMs=localMinMs??d2?.minDelayMs??STAGGER_MIN_DELAY_DEFAULT_MS;let maxMs=localMaxMs??d2?.maxDelayMs??STAGGER_MAX_DELAY_DEFAULT_MS;if(minMs>maxMs)minMs=maxMs;const overs=policy?.overrides??[];const match=overs.find(o=>o.version===candidate)??overs.find(o=>o.range!==void 0&&satisfiesRange(candidate,o.range));if(match){const nMin=match.minDelayMs??minMs;const nMax=match.maxDelayMs??maxMs;if(nMin>nMax){minMs=nMax;maxMs=nMax}else{minMs=nMin;maxMs=nMax}}return{minMs,maxMs}}async function readStaggerDraws(){try{const text2=await readFile(path13.join(cacheDir(),STAGGER_FILE_NAME),"utf-8");const data=JSON.parse(text2);if(data.v!==1||typeof data.draws!=="object"||data.draws===null)return{};const out={};for(const[k2,v3]of Object.entries(data.draws)){if(typeof v3==="number"&&Number.isFinite(v3))out[k2]=v3}return out}catch{return{}}}async function persistStaggerDraw(key2,at2,now){try{await mkdir(cacheDir(),{recursive:true});const draws=await readStaggerDraws();draws[key2]=Math.min(draws[key2]??at2,at2);for(const k2 of Object.keys(draws)){if(now-draws[k2]>STAGGER_PRUNE_MS)delete draws[k2]}const file=path13.join(cacheDir(),STAGGER_FILE_NAME);const tmp=`${file}.tmp-${process.pid}-${Date.now()}`;await writeFile(tmp,JSON.stringify({v:1,draws}),"utf-8");await rename(tmp,file)}catch{}}function staggerKey(tag,version){return`${tag}:${version}`}async function ensureStaggerDraw(args){const span=Math.max(0,args.maxDelayMs-args.minDelayMs);const existing=(await readStaggerDraws())[args.key];if(existing!==void 0)return{at:existing,drawnNow:false};const rand=args.rand??Math.random;const at2=args.now+args.minDelayMs+Math.floor(rand()*(span+1));await persistStaggerDraw(args.key,at2,args.now);return{at:at2,drawnNow:true}}async function readPolicyCache(){try{const text2=await readFile(path13.join(cacheDir(),POLICY_CACHE_FILE_NAME),"utf-8");const data=JSON.parse(text2);if(data.v!==1||typeof data.body!=="string"||typeof data.fetchedAt!=="number")return void 0;return{v:1,etag:typeof data.etag==="string"?data.etag:void 0,fetchedAt:data.fetchedAt,body:data.body}}catch{return void 0}}async function writePolicyCache(c){try{await mkdir(cacheDir(),{recursive:true});const file=path13.join(cacheDir(),POLICY_CACHE_FILE_NAME);const tmp=`${file}.tmp-${process.pid}-${Date.now()}`;await writeFile(tmp,JSON.stringify(c),"utf-8");await rename(tmp,file)}catch{}}async function clearPolicyCache(){try{await unlink(path13.join(cacheDir(),POLICY_CACHE_FILE_NAME))}catch{}}function policyLogOnce(log2,key2,level,message){if(policyWarnedKeys.has(key2))return;policyWarnedKeys.add(key2);log2(level,message)}function parseCachedBody(body){try{return normalizePolicyDoc(JSON.parse(body)).doc}catch{return void 0}}function getUpdatePolicyState(){return lastPolicyState}async function loadUpdatePolicy(opts){const log2=opts.log??log;const failOpen=async error=>{const cached2=await readPolicyCache();const doc=cached2?parseCachedBody(cached2.body):void 0;if(cached2&&doc&&Date.now()-cached2.fetchedAt<=POLICY_STALE_CAP_MS){policyLogOnce(log2,`stale:${opts.url}`,"warn",`[update-policy] fetch failed (${error}) \u2014 using last good policy from ${new Date(cached2.fetchedAt).toISOString()} (#3619)`);const state8={doc,source:"stale-cache",fetchedAt:cached2.fetchedAt,error,url:opts.url};lastPolicyState=state8;return state8}policyLogOnce(log2,`fetchfail:${error}`,"info",`[update-policy] fetch failed (${error}) \u2014 using local defaults (#3619)`);const state7={doc:void 0,source:"local-default",error,url:opts.url};lastPolicyState=state7;return state7};const cached=await readPolicyCache();const headers={Accept:"application/json"};if(cached?.etag)headers["If-None-Match"]=cached.etag;let res;try{const dispatcher=proxyDispatcher(opts.resolveProxy?.(opts.url));res=await fetch(opts.url,{headers,signal:AbortSignal.timeout(POLICY_FETCH_TIMEOUT_MS),...dispatcher?{dispatcher}:{}})}catch(e){return await failOpen(String(e))}if(res.status===304){if(cached){const doc=parseCachedBody(cached.body);if(doc){const state8={doc,source:"remote",fetchedAt:cached.fetchedAt,url:opts.url};lastPolicyState=state8;return state8}}const state7={doc:void 0,source:"local-default",error:"304 without a local cache",url:opts.url};lastPolicyState=state7;return state7}if(!res.ok){return await failOpen(`policy source returned HTTP ${res.status}`)}let body;try{body=await res.text()}catch(e){return await failOpen(`reading the policy body failed: ${String(e)}`)}let parsed;try{parsed=JSON.parse(body)}catch{await clearPolicyCache();policyLogOnce(log2,"malformed:invalid-json","warn",`[update-policy] document is not valid JSON \u2014 ignoring it and using local defaults (#3619)`);const state7={doc:void 0,source:"local-default",error:"invalid JSON",url:opts.url};lastPolicyState=state7;return state7}const norm=normalizePolicyDoc(parsed);if(!norm.doc){await clearPolicyCache();policyLogOnce(log2,`malformed:${norm.error}`,"warn",`[update-policy] ignoring policy document (${norm.error}) \u2014 using local defaults (#3619)`);const state7={doc:void 0,source:"local-default",error:norm.error,url:opts.url};lastPolicyState=state7;return state7}const etag=res.headers.get("etag")??void 0;const fetchedAt=Date.now();await writePolicyCache({v:1,etag,fetchedAt,body});for(const w3 of norm.warnings)policyLogOnce(log2,`warn:${w3}`,"warn",`[update-policy] ${w3}`);if(norm.doc.hold){policyLogOnce(log2,"hold-active","warn",`[update-policy] HOLD active in the remote policy \u2014 auto-upgrades are frozen fleet-wide until the owner lifts it (#3619)`)}if(norm.doc.pinned!==null){policyLogOnce(log2,`pinned:${norm.doc.pinned}`,"warn",`[update-policy] fleet pinned at ${norm.doc.pinned} \u2014 nothing newer will be auto-installed until unpinned (#3619)`)}const state6={doc:norm.doc,source:"remote",fetchedAt,url:opts.url};lastPolicyState=state6;return state6}function setPlannedUpgrade(p2){lastPlannedUpgrade=p2}function getPlannedUpgrade(){return lastPlannedUpgrade}async function fetchPublishedVersions(opts){if(publishedVersionsCache&&publishedVersionsCache.url===opts.url&&Date.now()-publishedVersionsCache.fetchedAt<PUBLISHED_VERSIONS_TTL_MS){return publishedVersionsCache.versions}try{const dispatcher=proxyDispatcher(opts.resolveProxy?.(opts.url));const res=await fetch(opts.url,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(PACKUMENT_FETCH_TIMEOUT_MS),...dispatcher?{dispatcher}:{}});if(!res.ok)return void 0;const data=await res.json();if(typeof data.versions!=="object"||data.versions===null)return void 0;const versions=Object.keys(data.versions).filter(v3=>SEMVER_STRICT_RE.test(v3));publishedVersionsCache={url:opts.url,fetchedAt:Date.now(),versions};return versions}catch{return void 0}}function resolveCandidateAgainstPolicy(args){const{currentVersion,doc,publishedVersions}=args;const publishedSet=new Set(publishedVersions);let pinned=doc.pinned;if(pinned!==null&&!publishedSet.has(pinned))pinned=null;const blocked=new Set(doc.blocked.filter(v3=>publishedSet.has(v3)));const current=parseSemver(currentVersion);const candidates=publishedVersions.filter(v3=>!blocked.has(v3)).map(v3=>({v:v3,p:parseSemver(v3)})).filter(x2=>current?compareSemver(x2.p,current)>0:true).sort((a,b3)=>compareSemver(b3.p,a.p));if(pinned!==null){const pinP=parseSemver(pinned);const ceiled=candidates.filter(x2=>compareSemver(x2.p,pinP)<=0);if(ceiled.length===0){return{kind:"none",reason:`fleet pinned at ${doc.pinned}: nothing newer than ${currentVersion} sits under the ceiling`}}candidates.length=0;candidates.push(...ceiled)}if(candidates.length===0){const reason=blocked.size>0?`all newer versions are blocked by the remote policy (${[...blocked].join(", ")})`:"no published version newer than the current one";return{kind:"none",reason}}return{kind:"proceed",candidate:candidates[0].v}}async function resolveUpgradeCandidate(args){const log2=args.log??log;if(args.doc.pinned===null&&args.doc.blocked.length===0){return{kind:"proceed",candidate:args.latest}}const versions=await fetchPublishedVersions({url:args.packumentUrl,resolveProxy:args.resolveProxy});if(!versions){return{kind:"deferred",reason:"pin/block controls are active but the registry packument could not be fetched \u2014 retrying next cycle"}}const droppedPinned=args.doc.pinned!==null&&!versions.includes(args.doc.pinned);const droppedBlocked=args.doc.blocked.filter(v3=>!versions.includes(v3));if(droppedPinned){policyLogOnce(log2,`unpublished-pin:${args.doc.pinned}`,"warn",`[update-policy] pinned value ${args.doc.pinned} is not a published version \u2014 pin ignored (#3619)`)}for(const v3 of droppedBlocked){policyLogOnce(log2,`unpublished-block:${v3}`,"warn",`[update-policy] blocked value ${v3} is not a published version \u2014 entry ignored (#3619)`)}return resolveCandidateAgainstPolicy({currentVersion:args.currentVersion,latest:args.latest,doc:args.doc,publishedVersions:versions})}var STAGGER_MIN_DELAY_DEFAULT_MS,STAGGER_MAX_DELAY_DEFAULT_MS,POLICY_URL_DEFAULT,POLICY_SCHEMA_VERSION,POLICY_FETCH_TIMEOUT_MS,PACKUMENT_FETCH_TIMEOUT_MS,POLICY_STALE_CAP_MS,DELAY_SANITY_CAP_MS,MAX_OVERRIDES,MAX_BLOCKED,PUBLISHED_VERSIONS_TTL_MS,POLICY_CACHE_FILE_NAME,STAGGER_FILE_NAME,STAGGER_PRUNE_MS,SEMVER_LOOSE_RE,SEMVER_STRICT_RE,lastPolicyState,policyWarnedKeys,lastPlannedUpgrade,publishedVersionsCache;var init_update_policy=__esm({"src/update-policy.ts"(){"use strict";init_paths();init_logger();init_upstream_proxy();init_duration();STAGGER_MIN_DELAY_DEFAULT_MS=15*6e4;STAGGER_MAX_DELAY_DEFAULT_MS=48*36e5;POLICY_URL_DEFAULT="https://raw.githubusercontent.com/ranxianglei/billion-context/master/auto-update-policy.json";POLICY_SCHEMA_VERSION=1;POLICY_FETCH_TIMEOUT_MS=5e3;PACKUMENT_FETCH_TIMEOUT_MS=1e4;POLICY_STALE_CAP_MS=30*864e5;DELAY_SANITY_CAP_MS=366*864e5;MAX_OVERRIDES=64;MAX_BLOCKED=100;PUBLISHED_VERSIONS_TTL_MS=10*6e4;POLICY_CACHE_FILE_NAME=".update-policy.json";STAGGER_FILE_NAME=".update-stagger.json";STAGGER_PRUNE_MS=7*864e5;SEMVER_LOOSE_RE=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.+)?$/;SEMVER_STRICT_RE=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;policyWarnedKeys=new Set}});import{readFile as readFile2,writeFile as writeFile2,mkdir as mkdir2,access,constants,rm,cp,unlink as unlink2,lstat,stat,rename as rename2,mkdtemp,readdir}from"fs/promises";import{execFile as execFile3,spawn}from"child_process";import{realpathSync}from"fs";import crypto2 from"crypto";import path14 from"path";import os6 from"os";import{fileURLToPath as fileURLToPath2}from"url";function normalizeRegistryBase(raw){const v3=raw?.trim();if(!v3)return"https://registry.npmjs.org";return v3.replace(/\/+$/,"")}function normalizeUpdateTag(tag){return(tag??"latest").trim()||"latest"}function registryUrlFor(packageName,tag){return`${REGISTRY_BASE}/${packageName}/${encodeURIComponent(tag)}`}function ownerLaneIntervalMs(rand=Math.random){return OWNER_LANE_CHECK_BASE_MS+Math.floor(rand()*OWNER_LANE_CHECK_JITTER_MS)}function shouldStealLock(holderAlive,ageMs){return!holderAlive||ageMs>=LOCK_MAX_AGE_MS}function warnAdvisoryOnce(advisoryId,message){const key2=`${advisoryId}\0${message}`;if(advisoryRefusalWarnKeys.has(key2))return;advisoryRefusalWarnKeys.add(key2);log("warn",message)}function validatePersisted(val,now){const b3=val;if(!b3||typeof b3!=="object")return void 0;if(typeof b3.count!=="number"||typeof b3.nextRetryAt!=="number"||typeof b3.updatedAt!=="number")return void 0;if(!Number.isFinite(b3.count)||!Number.isFinite(b3.nextRetryAt)||!Number.isFinite(b3.updatedAt))return void 0;if(b3.count<=0)return void 0;if(b3.nextRetryAt>now+BACKOFF_CAP_MS)return void 0;if(b3.updatedAt<now-BACKOFF_PRUNE_MS)return void 0;return{count:b3.count,nextRetryAt:b3.nextRetryAt,updatedAt:b3.updatedAt}}async function statBackoffFile(){try{return(await stat(BACKOFF_STATE_FILE)).mtimeMs}catch{return 0}}async function readBackoffFile(){const mtime=await statBackoffFile();if(mtime===0)return void 0;let raw;try{raw=await readFile2(BACKOFF_STATE_FILE,"utf-8")}catch{return void 0}try{const doc=JSON.parse(raw);if(!doc||typeof doc!=="object"||doc.v!==1||!doc.entries||typeof doc.entries!=="object"||Array.isArray(doc.entries))return void 0;const now=Date.now();const entries2=new Map;for(const[key2,val]of Object.entries(doc.entries)){const v3=validatePersisted(val,now);if(v3)entries2.set(key2,v3)}return{mtime,entries:entries2}}catch{return void 0}}function mergeFromFile(f2,skipAdopt){for(const[key2,v3]of f2.entries){const m3=installBackoffs.get(key2);if(m3?v3.updatedAt>m3.updatedAt:!skipAdopt?.has(key2))installBackoffs.set(key2,v3)}for(const[key2,m3]of[...installBackoffs]){if(!f2.entries.has(key2)&&f2.mtime>m3.updatedAt)installBackoffs.delete(key2)}backoffFileMtime=f2.mtime}async function ensureBackoffsLoaded(){if(backoffsLoaded)return;backoffsLoaded=true;const f2=await readBackoffFile();if(!f2){backoffFileMtime=0;return}mergeFromFile(f2)}async function syncBackoffsIfFileChanged(){const mtime=await statBackoffFile();if(mtime===backoffFileMtime)return;const f2=await readBackoffFile();if(f2){mergeFromFile(f2);return}if(backoffFileMtime>0&&mtime===0)installBackoffs.clear();backoffFileMtime=mtime}async function persistBackoffs(skipAdopt){try{const f2=await readBackoffFile();if(f2)mergeFromFile(f2,skipAdopt);const now=Date.now();const entries2={};let live=0;for(const[key2,b3]of installBackoffs){if(b3.updatedAt<now-BACKOFF_PRUNE_MS)continue;entries2[key2]={count:b3.count,nextRetryAt:b3.nextRetryAt,updatedAt:b3.updatedAt};live+=1}await mkdir2(path14.dirname(BACKOFF_STATE_FILE),{recursive:true});if(live===0){await rm(BACKOFF_STATE_FILE,{force:true});backoffFileMtime=0}else{const tmp=`${BACKOFF_STATE_FILE}.${process.pid}.tmp`;await writeFile2(tmp,JSON.stringify({v:1,entries:entries2}),"utf-8");await rename2(tmp,BACKOFF_STATE_FILE);backoffFileMtime=await statBackoffFile()}}catch{}}function parseLastInstallDoc(raw){const doc=JSON.parse(raw);if(!doc||typeof doc!=="object"||doc.v!==1)return void 0;const r=doc.record;if(!r||typeof r!=="object")return void 0;if(typeof r.version!=="string"||typeof r.source!=="string"||typeof r.at!=="number")return void 0;if(!Number.isFinite(r.at))return void 0;if(r.from!==void 0&&typeof r.from!=="string")return void 0;return{from:r.from,version:r.version,source:r.source,at:r.at}}async function getLastInstall(){try{return parseLastInstallDoc(await readFile2(LAST_INSTALL_FILE,"utf-8"))}catch{return void 0}}async function persistLastInstall(from,version,source){try{await mkdir2(path14.dirname(LAST_INSTALL_FILE),{recursive:true});const tmp=`${LAST_INSTALL_FILE}.${process.pid}.tmp`;await writeFile2(tmp,JSON.stringify({v:1,record:{...from?{from}:{},version,source,at:Date.now()}}),"utf-8");await rename2(tmp,LAST_INSTALL_FILE)}catch{}}function backoffKey(installDir,version){return`${installDir??"<unknown-install-dir>"}\0${version}`}function ownerLaneKey(lane,version){return`owner:${lane}:${version}`}async function backoffInCooldown(key2){await ensureBackoffsLoaded();await syncBackoffsIfFileChanged();const b3=installBackoffs.get(key2);return!!b3&&Date.now()<b3.nextRetryAt}async function clearInstallBackoff(key2){await ensureBackoffsLoaded();const had=(installBackoffs.delete(key2)?1:0)|(installBackoffRemediatedKeys.delete(key2)?1:0);if(had)await persistBackoffs(new Set([key2]))}function backoffMs(count){const exp=Math.max(0,count-BACKOFF_THRESHOLD);return Math.min(BACKOFF_CAP_MS,BACKOFF_BASE_MS*2**exp)}function remediationHint(error){if(/not writable/i.test(error)){if(process.platform==="win32"){return"the install dir is not writable by this user. On Windows the default npm prefix (%APPDATA%\\npm) is user-writable \u2014 repair that dir's ownership/permissions and reinstall (npm install -g billion-context), or disable auto-update (config autoUpdate:false / env ACP_AUTO_UPDATE=0)"}return'the install dir is not writable by this user. Fix its ownership/permissions, or reinstall into a user-level prefix \u2014 npm install -g billion-context --prefix="$HOME/.local" (put "$HOME/.local/bin" on PATH; pass --prefix again on future npm reinstalls) \u2014 or disable auto-update (config autoUpdate:false / env ACP_AUTO_UPDATE=0)'}if(/git working tree/i.test(error)){return"this copy runs from a source checkout. Install globally instead (npm install -g billion-context) so auto-update has a writable target"}if(/managed by/i.test(error)){return"this copy is managed by its host. Update it through the host's own channel rather than in place"}return"review the error above. Auto-update keeps retrying with an increasing delay"}function installDirNote(installDir){if(!installDir)return"";try{const real=realpathSync(installDir);return real===installDir?"":` (target ${installDir} resolves via symlink to ${real})`}catch{return""}}async function recordInstallFailure(key2,error,installDir,hint){await ensureBackoffsLoaded();const now=Date.now();const b3=installBackoffs.get(key2)??{count:0,nextRetryAt:0,updatedAt:now};b3.count+=1;b3.updatedAt=now;if(b3.count>=BACKOFF_THRESHOLD){b3.nextRetryAt=now+backoffMs(b3.count)}installBackoffs.set(key2,b3);await persistBackoffs();const note=installDirNote(installDir);if(b3.count<BACKOFF_THRESHOLD){log("warn",`[update] install failed: ${error}${note}. Will retry next cycle.`);return}const waitMin=Math.round(backoffMs(b3.count)/6e4);if(!installBackoffRemediatedKeys.has(key2)){installBackoffRemediatedKeys.add(key2);log("warn",`[update] install keeps failing (${b3.count}\xD7 in a row): ${error}${note}. ${hint??remediationHint(error)}. Backing off \u2014 next attempt in ~${waitMin}m.`);return}log("warn",`[update] install failed: ${error}${note}. Still failing \u2014 next attempt in ~${waitMin}m.`)}function isVersionNewer(latest,current){const next=parseSemVer(latest);const prev=parseSemVer(current);if(!next||!prev)return false;for(let i=0;i<3;i++){const a=next.parts[i]??0;const b3=prev.parts[i]??0;if(a!==b3)return a>b3}if(!next.pre.length&&prev.pre.length)return true;if(next.pre.length&&!prev.pre.length)return false;for(let i=0;i<Math.max(next.pre.length,prev.pre.length);i++){const a=next.pre[i];const b3=prev.pre[i];if(a===void 0)return false;if(b3===void 0)return true;if(a===b3)continue;const aNumber=/^\d+$/.test(a)?Number(a):void 0;const bNumber=/^\d+$/.test(b3)?Number(b3):void 0;if(aNumber!==void 0&&bNumber!==void 0)return aNumber>bNumber;if(aNumber!==void 0)return false;if(bNumber!==void 0)return true;return a>b3}return false}function parseSemVer(version){const match=version.match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.+)?$/);if(!match)return void 0;return{parts:[Number(match[1]),Number(match[2]),Number(match[3])],pre:match[4]?.split(".")??[]}}function staleInstallStatus(diskVersion,runningVersion){return diskVersion!==void 0&&isVersionNewer(diskVersion,runningVersion)?"restart":"current"}function reportNotNewer(latest,tag,diskVersion,runningVersion,log2){const currentVersion=diskVersion??runningVersion;if(isVersionNewer(latest,currentVersion))return false;if(staleInstallStatus(diskVersion,runningVersion)==="restart"){const key2=`${runningVersion}->${diskVersion}`;if(key2!==staleWarnKey){staleWarnKey=key2;log2("warn",`[update] running v${runningVersion} but v${diskVersion} is installed \u2014 restart bili to activate (auto-update replaced the on-disk install; this process is still on the old code)`)}}else{staleWarnKey=void 0;log2("info",`[update] current=${currentVersion} latest=${latest} tag=${tag} (up to date)`)}return true}async function readLastCheck(file){try{const data=await readFile2(file,"utf-8");return parseInt(data.trim(),10)||0}catch{return 0}}async function writeLastCheck(file,ts3){try{await mkdir2(path14.dirname(file),{recursive:true});await writeFile2(file,String(ts3),"utf-8")}catch{}}async function lastUpdateCheckTime(){const ts3=Math.max(await readLastCheck(THROTTLE_FILE),await readLastCheck(OWNER_THROTTLE_FILE));return ts3>0?ts3:void 0}async function findPackageRoot(startDir,packageName){let dir=startDir;for(;;){try{const pkg=JSON.parse(await readFile2(path14.join(dir,"package.json"),"utf-8"));const name=typeof pkg.name==="string"?pkg.name:void 0;if(name===packageName)return dir;if(name!==void 0)return void 0}catch{}const parent=path14.dirname(dir);if(parent===dir)return void 0;dir=parent}}async function findInstallDir(packageName){return findPackageRoot(path14.dirname(fileURLToPath2(import.meta.url)),packageName)}function describeInstallLocation(installDir,runningModule){const parts=[];if(installDir){parts.push(`target=${installDir}`);try{const real=realpathSync(installDir);if(real!==installDir)parts.push(`real=${real}`)}catch{}}else{parts.push("target=<unresolved>")}if(runningModule){let real=runningModule;try{real=realpathSync(runningModule)}catch{}parts.push(`running=${real}`)}return parts.join(" ")}function logInstallLocationOnce(installDir,packageName,log2=log){if(installLocationLogged)return;installLocationLogged=true;let running;try{running=fileURLToPath2(import.meta.url)}catch{running=void 0}log2("warn",`[update] install location: ${describeInstallLocation(installDir,running)} \u2014 this process updates only the copy it runs from; if your host loads ${packageName} from a different location, that copy is not being updated here`)}async function isGitWorkingTree(dir){try{await access(path14.join(dir,".git"));return true}catch{return false}}function dshDesktopCopyPathMatches(installDir,real,anchor,suffix,ci2){const a=ci2?anchor.toLowerCase():anchor;const suf=ci2?suffix.toLowerCase():suffix;return[installDir,real].some(dir=>{const norm=dir.split(path14.sep).join("/");const n=ci2?norm.toLowerCase():norm;return n.startsWith(a+"/")&&n.endsWith(suf)})}function isDshDesktopBiliCopy(installDir,real,env){const anchor=path14.join(resolveDshHome(env),"profiles",DSH_DESKTOP_PROFILE).split(path14.sep).join("/");return dshDesktopCopyPathMatches(installDir,real,anchor,`/node_modules/${DSH_PACKAGE}`,process.platform==="win32")}function isOpencodeCacheBiliCopy(installDir,real,env){const xdgCache=env.XDG_CACHE_HOME&&env.XDG_CACHE_HOME.trim().length>0?env.XDG_CACHE_HOME:path14.join(os6.homedir(),".cache");const anchor=path14.join(xdgCache,"opencode").split(path14.sep).join("/");return[installDir,real].some(dir=>{const norm=dir.split(path14.sep).join("/");return norm.startsWith(anchor+"/")&&norm.endsWith(`/node_modules/${DSH_PACKAGE}`)})}function hostManagedInstall(installDir,env=process.env){let real=installDir;try{real=realpathSync(installDir)}catch{}if(isDshDesktopBiliCopy(installDir,real,env))return void 0;if(isOpencodeCacheBiliCopy(installDir,real,env))return void 0;for(const dir of[installDir,real]){if(dir.split(path14.sep).some(seg=>seg===".pnpm")){return{owner:"pnpm",channel:"dsh profiles refresh automatically (on the next global bili self-update, or from the profile proxy's own periodic check when no global is running, #1196); a pnpm-global install upgrades via `pnpm add -g billion-context@latest`"}}}const xdgData=env.XDG_DATA_HOME&&env.XDG_DATA_HOME.trim().length>0?env.XDG_DATA_HOME:path14.join(os6.homedir(),".local","share");const homes=[["pi",resolvePiHome(env),"`pi update --extension npm:billion-context` (the pi copy's own proxy drives pi's update channel every check cycle, #1196; manual: `pi update --all`)"],["opencode",path14.join(xdgData,"opencode"),"opencode's own plugin manager (reload/reinstall the billion-context plugin)"],["dsh",resolveDshHome(env),"the dsh plugin channel (the global bili self-update refreshes profiles, and so does the profile proxy's own periodic check; or `dsh plugin add billion-context@latest`)"],["kimi",resolveKimiHome(env),"`bili plugin install kimi` after updating the global bili install"],["omp",resolveOmpHome(env),"the global bili install (the extensions entry points at it)"]];for(const[owner,home,channel]of homes){if(!home)continue;for(const dir of[installDir,real]){if(dir===home||dir.startsWith(home+path14.sep)){return{owner,channel}}}}return void 0}async function readDiskVersion(installDir){try{const pkg=JSON.parse(await readFile2(path14.join(installDir,"package.json"),"utf-8"));return pkg.version}catch{return void 0}}function declaredEntryRelPaths(pkg){const entries2=new Set;if(typeof pkg.main==="string")entries2.add(pkg.main);const bin=pkg.bin;if(typeof bin==="string")entries2.add(bin);else if(bin&&typeof bin==="object"){for(const v3 of Object.values(bin)){if(typeof v3==="string")entries2.add(v3)}}return[...entries2]}function runNodeCheck(file){return new Promise(resolve=>{execFile3(process.execPath,["--check",file],{timeout:15e3,maxBuffer:4*1024*1024,windowsHide:true},(err2,_stdout,stderr)=>{resolve({code:err2?1:0,stderr:String(stderr)})})})}async function syntaxCheckEntry(entryAbs){let source;try{source=await readFile2(entryAbs,"utf-8")}catch(e){return`entry unreadable: ${String(e)}`}const tmpCheck=path14.join(cacheDir(),`.update-syntax-check-${crypto2.randomBytes(6).toString("hex")}.mjs`);try{await mkdir2(cacheDir(),{recursive:true});await writeFile2(tmpCheck,source);const r=await runNodeCheck(tmpCheck);if(r.code!==0){return`entry does not parse (${path14.basename(entryAbs)}): ${r.stderr.split("\n").filter(Boolean).slice(0,3).join(" | ").slice(0,300)}`}return null}finally{try{await rm(tmpCheck,{force:true})}catch{}}}async function verifyEntries(dir,label){let pkg;try{pkg=JSON.parse(await readFile2(path14.join(dir,"package.json"),"utf-8"))}catch(e){return`${label}: package.json unreadable: ${String(e)}`}const entries2=declaredEntryRelPaths(pkg);if(entries2.length===0){return`${label}: no declared entry (main/bin)`}for(const rel2 of entries2){try{await access(path14.join(dir,rel2))}catch{return`${label}: entry missing: ${rel2}`}const reason=await syntaxCheckEntry(path14.join(dir,rel2));if(reason)return`${label}: ${reason}`}return null}async function tryAcquireLock(){const pid=process.pid;const now=Date.now();async function readLock(){try{const raw=await readFile2(LOCK_FILE,"utf-8");const data=JSON.parse(raw);if(typeof data.pid==="number"&&typeof data.ts==="number"){return data}}catch{}return null}function isAlive(checkPid){try{process.kill(checkPid,0);return true}catch{return false}}const existing=await readLock();if(existing){const holderAlive=isAlive(existing.pid);if(!shouldStealLock(holderAlive,now-existing.ts)){log("info",`[update] lock held by live pid=${existing.pid} (age=${Math.round((now-existing.ts)/1e3)}s), skipping update`);return null}log("info",`[update] stealing lock from pid=${existing.pid} (alive=${holderAlive}, age=${Math.round((now-existing.ts)/1e3)}s)`);try{await unlink2(LOCK_FILE)}catch(e){const code=e.code;if(code!=="ENOENT"){log("warn",`[update] could not remove stale lock: ${e.message}`);return null}}}await mkdir2(path14.dirname(LOCK_FILE),{recursive:true}).catch(()=>{});try{await writeFile2(LOCK_FILE,JSON.stringify({pid,ts:now}),{flag:"wx"})}catch{const winner=await readLock();if(winner&&winner.pid!==pid){log("info",`[update] lost lock race to pid=${winner.pid}, skipping update`);return null}}const confirmed=await readLock();if(!confirmed||confirmed.pid!==pid){log("info",`[update] lock held by pid=${confirmed?.pid}, skipping update`);return null}return{release:async()=>{const current=await readLock();if(current?.pid===pid){await rm(LOCK_FILE,{force:true}).catch(()=>{})}}}}function notifyStaleInstall(opts,diskVersion){const hook=opts.onStaleInstall;if(!hook)return;try{const result=hook({diskVersion,runningVersion:opts.currentVersion});if(result instanceof Promise){result.catch(e=>log("warn",`[update] stale-install handler failed: ${String(e)}`))}}catch(e){log("warn",`[update] stale-install handler failed: ${String(e)}`)}}function egressDispatcher(opts,url){return proxyDispatcher(opts.resolveProxy?.(url))}function fetchWithEgress(url,init){return fetch(url,init)}async function fetchRegistryVersion(opts,packageName){const tag=normalizeUpdateTag(opts.updateTag);const url=registryUrlFor(packageName,tag);const dispatcher=egressDispatcher(opts,url);const res=await fetchWithEgress(url,{signal:AbortSignal.timeout(5e3),headers:{Accept:"application/json"},...dispatcher?{dispatcher}:{}});if(!res.ok)return void 0;const data=await res.json();return data.version}async function runProfileBundlesRefresh(targetVersion,log2,env=process.env){const key2=ownerLaneKey("dsh-profile",targetVersion);if(await backoffInCooldown(key2))return;const res=await refreshDshProfileBundles(targetVersion,log2,env);if(res.failed>0){await recordInstallFailure(key2,`${res.failed} dsh profile bundle(s) failed to refresh to ${targetVersion}`,void 0,PROFILE_LANE_HINT)}else{await clearInstallBackoff(key2)}}async function refreshDshProfileCopy(installDir,opts,env=process.env,log2=log){if(!isDshProfileCopy(installDir,env))return;let latest;try{latest=await fetchRegistryVersion(opts,opts.packageName)}catch(e){log2("warn",`[update] dsh profile bundle check failed: ${String(e)} \u2014 leaving profile copies alone`);return}if(!latest){log2("warn",`[update] could not resolve the latest version for ${opts.packageName} \u2014 leaving dsh profile bundles alone`);return}const diskVersion=await readDiskVersion(installDir);const currentVersion=diskVersion??opts.currentVersion;if(!isVersionNewer(latest,currentVersion)){log2("info",`[update] dsh profile bundle up to date (current=${currentVersion} latest=${latest} tag=${normalizeUpdateTag(opts.updateTag)})`);return}const gate=await passUpdatePolicyGate({packageName:opts.packageName,currentVersion,latest,tag:normalizeUpdateTag(opts.updateTag),force:false,resolveProxy:opts.resolveProxy});if("reason"in gate)return;const target=gate.candidate;log2("info",`[update] dsh profile bundle is stale (${currentVersion} \u2192 ${latest}) \u2014 refreshing via dsh's plugin channel`);const lock=await tryAcquireLock();if(!lock){log2("info",`[update] another process is updating, will check next cycle`);return}try{await runProfileBundlesRefresh(target,log2,env);await refreshDshDesktopCopy(target,log2,env)}finally{await lock.release()}}async function refreshDshDesktopCopy(targetVersion,log2=log,env=process.env,resolveProxy2){const flat=path14.join(resolveDshHome(env),"profiles",DSH_DESKTOP_PROFILE,"node_modules",DSH_PACKAGE);const bkey=ownerLaneKey("dsh-desktop",targetVersion);let diskVersion;try{try{await access(flat,constants.F_OK)}catch{return}diskVersion=await readDiskVersion(flat);if(!isVersionNewer(targetVersion,diskVersion??"0.0.0"))return}catch(err2){const msg=err2 instanceof Error?err2.message:String(err2);log2("warn",`[update] dsh ${DSH_DESKTOP_PROFILE} in-place refresh check failed: ${msg}; leaving the copy untouched`);await recordInstallFailure(bkey,`dsh ${DSH_DESKTOP_PROFILE} in-place refresh check failed: ${msg}`,void 0,DESKTOP_LANE_HINT);return}if(await backoffInCooldown(bkey))return;try{const doc=await fetchVersionDoc({resolveProxy:resolveProxy2},DSH_PACKAGE,targetVersion);if(!doc?.tarball){log2("warn",`[update] dsh ${DSH_DESKTOP_PROFILE}: in-place refresh to ${targetVersion} failed \u2014 no dist.tarball for that version on the registry; retrying next cycle`);await recordInstallFailure(bkey,`dsh ${DSH_DESKTOP_PROFILE}: no dist.tarball for ${targetVersion} on the registry`,void 0,DESKTOP_LANE_HINT);return}const result=await installViaTarball(targetVersion,doc.tarball,flat,doc.integrity,doc.shasum,egressDispatcher({resolveProxy:resolveProxy2},doc.tarball),env,{bootSmoke:true});if(result.ok){await clearInstallBackoff(bkey);log2("info",`[update] refreshed dsh ${DSH_DESKTOP_PROFILE} profile copy in place (${diskVersion??"?"} \u2192 ${targetVersion}) \u2014 restart dsh to load it (the running app keeps the old code in memory; across the handoff bili tools may fail once until dsh restarts, #2082)`)}else{log2("warn",`[update] dsh ${DSH_DESKTOP_PROFILE}: in-place refresh to ${targetVersion} failed: ${result.error}; retrying next cycle`);await recordInstallFailure(bkey,`dsh ${DSH_DESKTOP_PROFILE} in-place refresh to ${targetVersion} failed: ${result.error}`,void 0,DESKTOP_LANE_HINT)}}catch(err2){const msg=err2 instanceof Error?err2.message:String(err2);log2("warn",`[update] dsh ${DSH_DESKTOP_PROFILE} in-place refresh check failed: ${msg}; leaving the copy untouched`);await recordInstallFailure(bkey,`dsh ${DSH_DESKTOP_PROFILE} in-place refresh check failed: ${msg}`,void 0,DESKTOP_LANE_HINT)}}async function refreshPiNpmCopy(installDir,opts,env=process.env,log2=log){if(!isPiNpmCopy(installDir,env))return;const entry=piNpmEntrySpec(env);if(entry!==PI_NPM_SPEC){log2("info",`[update] pi packages entry is ${entry??"(missing)"} \u2014 leaving the pi copy alone (only the unpinned ${PI_NPM_SPEC} form self-refreshes)`);return}let latest;try{latest=await fetchRegistryVersion(opts,opts.packageName)}catch(e){log2("warn",`[update] pi npm copy check failed: ${String(e)} \u2014 leaving the copy alone`);return}if(!latest){log2("warn",`[update] could not resolve the latest version for ${opts.packageName} \u2014 leaving the pi copy alone`);return}const diskVersion=await readDiskVersion(installDir);const currentVersion=diskVersion??opts.currentVersion;if(!isVersionNewer(latest,currentVersion)){log2("info",`[update] pi npm copy up to date (current=${currentVersion} latest=${latest} tag=${normalizeUpdateTag(opts.updateTag)})`);return}const gate=await passUpdatePolicyGate({packageName:opts.packageName,currentVersion,latest,tag:normalizeUpdateTag(opts.updateTag),force:false,resolveProxy:opts.resolveProxy});if("reason"in gate)return;if(gate.candidate!==latest){log2("info",`[update] policy selected ${gate.candidate} below dist-tag ${latest}; not driving pi update (it would install ${latest}) \u2014 manual escape: pi update --extension ${PI_NPM_SPEC}@${gate.candidate}`);return}if(await backoffInCooldown(ownerLaneKey("pi-npm",latest)))return;log2("info",`[update] pi npm copy is stale (${currentVersion} \u2192 ${latest}) \u2014 refreshing via pi's update channel`);const lock=await tryAcquireLock();if(!lock){log2("info",`[update] another process is updating, will check next cycle`);return}try{await runPiAsync(["update","--extension",PI_NPM_SPEC],env);await clearInstallBackoff(ownerLaneKey("pi-npm",latest));log2("info",`[update] pi npm copy refreshed to ${latest} \u2014 restart pi to load it`)}catch(err2){const detail=err2 instanceof Error?err2.message:String(err2);log2("warn",`[update] pi npm copy refresh to ${latest} failed: ${detail} \u2014 manual fix: run \`pi update --extension ${PI_NPM_SPEC}\` from a shell where \`pi\` resolves (or point BILI_PI_BIN at pi's executable); retries next check cycle`);await recordInstallFailure(ownerLaneKey("pi-npm",latest),`pi npm copy refresh to ${latest} failed: ${detail}`,void 0,PI_LANE_HINT)}finally{await lock.release()}}async function refreshOwnerManagedCopies(installDir,opts,env,log2){await refreshDshProfileCopy(installDir,opts,env,log2);await refreshPiNpmCopy(installDir,opts,env,log2)}async function staleDshProfileCopies(globalVersion,env){let dirs;try{dirs=dshProfileDirs(env)}catch{return[]}const out=[];for(const dir of dirs){if(!dshProfileDependsOnBili(dir))continue;const spec=dshProfileDepSpec(dir);if(spec!==void 0&&!isRegistryDepSpec(spec))continue;const version=await readDiskVersion(path14.join(dir,"node_modules",DSH_PACKAGE));if(version&&isVersionNewer(globalVersion,version))out.push(`${path14.basename(dir)}@${version}`)}return out}async function convergeDshProfileBundles(installDir,globalVersion,env=process.env,log2=log){if(!installDir||!globalVersion)return;let stale;try{stale=await staleDshProfileCopies(globalVersion,env)}catch{return}if(stale.length===0)return;log2("info",`[update] dsh profile bundle(s) behind the global copy (${stale.join(", ")} < ${globalVersion}) \u2014 converging via dsh's plugin channel (#1803)`);const lock=await tryAcquireLock();if(!lock){log2("info",`[update] another process is updating, will check next cycle`);return}try{await runProfileBundlesRefresh(globalVersion,log2,env);await refreshDshDesktopCopy(globalVersion,log2,env)}finally{await lock.release()}}function policyGateLogOnce(key2,message){if(policyGateLogged.has(key2))return;policyGateLogged.add(key2);log("info",message)}async function passUpdatePolicyGate(args){const{force}=args;try{const policy=await loadUpdatePolicy({url:updatePolicyUrl()??POLICY_URL_DEFAULT,resolveProxy:args.resolveProxy});const doc=policy.doc;if(!force&&doc?.hold){setPlannedUpgrade(void 0);policyGateLogOnce("policy:hold",`[update] HOLD active in the remote update policy \u2014 ${args.latest} is available but auto-upgrade is frozen fleet-wide until the owner lifts it; manual escape: \`bili update\` (bypasses hold) or npm install -g ${args.packageName}@${args.latest} (#3619)`);return{reason:"hold"}}let candidate=args.latest;if(doc&&(doc.pinned!==null||doc.blocked.length>0)){const res=await resolveUpgradeCandidate({currentVersion:args.currentVersion,latest:args.latest,doc,packumentUrl:`${REGISTRY_BASE}/${encodeURIComponent(args.packageName)}`,resolveProxy:args.resolveProxy});if(res.kind==="deferred"){setPlannedUpgrade(void 0);policyGateLogOnce("policy:deferred",`[update] ${res.reason} (#3619)`);return{reason:"deferred"}}if(res.kind==="none"){setPlannedUpgrade(void 0);policyGateLogOnce(`policy:none:${res.reason}`,`[update] ${res.reason} \u2014 staying at ${args.currentVersion} (#3619)`);return{reason:"none"}}candidate=res.candidate;if(candidate!==args.latest){policyGateLogOnce(`policy:stepped:${args.latest}->${candidate}`,`[update] installing ${candidate} instead of dist-tag ${args.latest} per the remote policy (#3619)`)}}if(!force){const win=resolveStaggerWindow(candidate,doc,updateStaggerMinDelayMs(),updateStaggerMaxDelayMs());const now=Date.now();const draw=await ensureStaggerDraw({key:staggerKey(args.tag,candidate),minDelayMs:win.minMs,maxDelayMs:win.maxMs,now});if(draw.at>now){setPlannedUpgrade({tag:args.tag,version:candidate,at:draw.at});const mins=Math.max(1,Math.round((draw.at-now)/6e4));policyGateLogOnce(`policy:stagger:${args.tag}:${candidate}:${draw.at}`,`[update] staggered rollout (#3619): upgrade to ${candidate} scheduled for ${new Date(draw.at).toISOString()} (~${mins} min from now; window ${win.minMs/6e4|0}-${win.maxMs/6e4|0} min)`);return{reason:"stagger"}}}setPlannedUpgrade(void 0);return{candidate}}catch(e){policyGateLogOnce(`policy:gatefail:${String(e)}`,`[update] policy gate failed (${String(e)}) \u2014 proceeding with the legacy immediate install (#3619)`);return{candidate:args.latest}}}async function checkForUpdate(opts,force=false){if(!opts.autoUpdate&&!force)return;if(inFlight)return;inFlight=true;try{const now=Date.now();const installDir=opts.installDir??await findInstallDir(opts.packageName);const managed=installDir?hostManagedInstall(installDir):void 0;const ownerLane=Boolean(managed&&installDir);const throttleFile=ownerLane?OWNER_THROTTLE_FILE:THROTTLE_FILE;const intervalMs=ownerLane?ownerLaneIntervalMs():CHECK_INTERVAL_MS;const lastCheck=await readLastCheck(throttleFile);const sinceLastSec=lastCheck?(now-lastCheck)/1e3|0:-1;if(!force&&firstCheckDone&&now-lastCheck<intervalMs){const retryIn=(intervalMs-(now-lastCheck))/1e3|0;log("info",`[update] throttled \u2014 last checked ${sinceLastSec}s ago, retry in ${retryIn}s`);return}await writeLastCheck(throttleFile,now);firstCheckDone=true;if(!force&&opts.advisoryActive?.()){if(managed&&installDir){log("info",`[update] deferring to the advisory loop; ${managed.owner}-managed install keeps its owner-channel refresh (#991/#1196)`);await refreshOwnerManagedCopies(installDir,opts,process.env,log);return}log("info","[update] deferring to the advisory loop (an active critical-bug advisory owns this install)");return}if(installDir&&await isGitWorkingTree(installDir)){log("info",`[update] running from a source checkout (${installDir}) \u2014 skipping auto-update (use npm install -g ${opts.packageName})`);return}if(managed&&installDir){log("info",`[update] install dir is managed by ${managed.owner} (${installDir}) \u2014 skipping in-place self-update; update it via ${managed.channel} (#991)`);await refreshOwnerManagedCopies(installDir,opts,process.env,log);return}if(!force&&opts.advisoryAwaitingFirstCheck?.()){log("info","[update] deferring this cycle: the advisory's first check has not landed yet (#2456) \u2014 will follow latest next cycle once its state is known");return}log("info",`[update] checking npm registry for ${opts.packageName}${sinceLastSec<0?" (startup check)":sinceLastSec===0?"":` (last check ${sinceLastSec}s ago)`}\u2026`);const tag=normalizeUpdateTag(opts.updateTag);const url=registryUrlFor(opts.packageName,tag);const registryDispatcher=egressDispatcher(opts,url);const res=await fetchWithEgress(url,{signal:AbortSignal.timeout(5e3),headers:{Accept:"application/json"},...registryDispatcher?{dispatcher:registryDispatcher}:{}});if(!res.ok){log("warn",`[update] registry returned ${res.status} ${res.statusText}, skipping`);return}const data=await res.json();const latest=data.version;if(!latest){log("warn",`[update] registry response had no version, skipping`);return}const diskVersion=installDir?await readDiskVersion(installDir):void 0;const currentVersion=diskVersion??opts.currentVersion;if(reportNotNewer(latest,tag,diskVersion,opts.currentVersion,log)){if(diskVersion&&staleInstallStatus(diskVersion,opts.currentVersion)==="restart"){notifyStaleInstall(opts,diskVersion)}await convergeDshProfileBundles(installDir,diskVersion,process.env);return}if(!force&&opts.advisoryBlocksVersion?.(latest)){log("info",`[update] skipping ${latest}: covered by a critical-bug advisory's affected range (#1588) \u2014 not pulling this install back into the defect; retrying next cycle`);return}const gate=await passUpdatePolicyGate({packageName:opts.packageName,currentVersion,latest,tag,force,resolveProxy:opts.resolveProxy});if("reason"in gate)return;const target=gate.candidate;let tarballUrl=data.dist?.tarball;let integrity=data.dist?.integrity;let shasum=data.dist?.shasum;if(target!==latest){const steppedDoc=await fetchVersionDoc(opts,opts.packageName,target);if(!steppedDoc?.tarball){log("warn",`[update] registry has no tarball for policy-selected ${target}, skipping`);return}tarballUrl=steppedDoc.tarball;integrity=steppedDoc.integrity;shasum=steppedDoc.shasum}if(!tarballUrl){log("warn",`[update] registry response for ${latest} had no tarball URL`);return}const bkey=backoffKey(installDir,target);if(!force&&await backoffInCooldown(bkey)){return}log("info",`[update] new version found: ${currentVersion} \u2192 ${target}${target!==latest?` (dist-tag says ${latest})`:""}, downloading\u2026`);const lock=await tryAcquireLock();if(!lock){log("info",`[update] another process is updating, will check next cycle`);return}try{const result=await installViaTarball(target,tarballUrl,installDir,integrity,shasum,egressDispatcher(opts,tarballUrl));if(result.ok){await clearInstallBackoff(bkey);await persistLastInstall(currentVersion,target,force?"manual":"auto-update");log("info",`[update] installed ${currentVersion} \u2192 ${target}. Restart to finish.`);await runProfileBundlesRefresh(target,log);await refreshDshDesktopCopy(target,log,process.env,opts.resolveProxy);notifyStaleInstall(opts,target)}else{await recordInstallFailure(bkey,result.error??"unknown error",installDir);logInstallLocationOnce(installDir,opts.packageName,log)}}finally{await lock.release()}}catch(e){log("warn",`[update] check failed: ${String(e)}`)}finally{inFlight=false}}function verifyTarballIntegrity(buf,integrity,shasum){if(integrity){const dash=integrity.indexOf("-");if(dash<=0)return{ok:false,error:"malformed integrity field"};const alg=integrity.slice(0,dash);const expected=integrity.slice(dash+1);let actual;try{actual=crypto2.createHash(alg).update(buf).digest("base64")}catch{return{ok:false,error:`unsupported integrity algorithm: ${alg}`}}if(actual!==expected)return{ok:false,error:`${alg} mismatch`};return{ok:true}}if(shasum){const actual=crypto2.createHash("sha1").update(buf).digest("hex");if(actual!==shasum)return{ok:false,error:"sha1 shasum mismatch"};return{ok:true}}return{ok:false,error:"no integrity or shasum from registry"}}async function bootSmoke(installDir,env){let entry;try{const pkg=JSON.parse(await readFile2(path14.join(installDir,"package.json"),"utf8"));if(typeof pkg.main==="string"&&pkg.main.length>0)entry=pkg.main}catch(err2){return`package.json unreadable: ${err2 instanceof Error?err2.message:String(err2)}`}if(entry===void 0)return"package.json declares no main entry to smoke";const childEnv={};for(const[key2,value]of Object.entries(env)){if(value===void 0)continue;if(key2.startsWith("BILI_")||key2.startsWith("BILLION_CONTEXT_")||key2.startsWith("ACP_"))continue;if(key2==="NODE_OPTIONS"||key2==="NODE_TEST_CONTEXT"||key2==="NODE_ENV")continue;childEnv[key2]=value}return await new Promise(resolve=>{const child=spawn(process.execPath,[path14.join(installDir,entry),"--version"],{cwd:installDir,env:childEnv,stdio:["ignore","ignore","pipe"],windowsHide:true});let stderr="";child.stderr?.on("data",chunk=>{stderr+=chunk.toString();if(stderr.length>8192)stderr=safeSuffix(stderr,8192)});const timer4=setTimeout(()=>{child.kill();resolve(`boot smoke timed out after ${BOOT_SMOKE_TIMEOUT_MS}ms`)},BOOT_SMOKE_TIMEOUT_MS);child.on("error",err2=>{clearTimeout(timer4);resolve(`boot smoke could not spawn ${process.execPath}: ${err2.message}`)});child.on("close",(code,signal)=>{clearTimeout(timer4);if(code===0){resolve(null);return}const lines=stderr.split("\n").filter(l3=>l3.trim().length>0&&!l3.trim().startsWith("at ")&&!/^Node\.js v/.test(l3.trim()));const tail=lines.length>0?`: ${safeSuffix(lines.join(" | "),600)}`:"";resolve(`boot smoke exited ${code??signal}${tail}`)})})}async function sweepStaleUpdateTmp(){try{const dir=cacheDir();const now=Date.now();for(const entry of await readdir(dir)){if(!entry.startsWith(".update-wip-")&&!entry.startsWith(".update-syntax-check-"))continue;try{const st3=await lstat(path14.join(dir,entry));if(now-st3.mtimeMs>=UPDATE_TMP_MAX_AGE_MS){await rm(path14.join(dir,entry),{recursive:true,force:true})}}catch{}}}catch{}}async function installViaTarball(version,tarballUrl,installDir,integrity,shasum,dispatcher,env=process.env,opts={}){if(!installDir){return{ok:false,error:"cannot determine install directory (package.json not found walking up from running binary)"}}try{await access(installDir,constants.W_OK)}catch{return{ok:false,error:`install dir not writable: ${installDir}`}}if(await isGitWorkingTree(installDir)){return{ok:false,error:`install dir is a git working tree (${installDir}) \u2014 refusing to overwrite a source checkout (use npm install -g)`}}let real=installDir;try{real=realpathSync(installDir)}catch{}const managed=hostManagedInstall(installDir,env);if(managed){return{ok:false,error:`install dir is managed by ${managed.owner} (${installDir}) \u2014 refusing in-place overwrite (single-writer); update via ${managed.channel}`}}const MAX_TARBALL_BYTES=100*1024*1024;let tgzBuffer;try{const tgzRes=await fetchWithEgress(tarballUrl,{signal:AbortSignal.timeout(6e4),...dispatcher?{dispatcher}:{}});if(!tgzRes.ok){return{ok:false,error:`tarball download failed: HTTP ${tgzRes.status} ${tgzRes.statusText}`}}if(!tgzRes.body){return{ok:false,error:"tarball download failed: empty response body"}}const reader=tgzRes.body.getReader();const chunks=[];let total=0;try{for(;;){const{done,value}=await reader.read();if(done)break;total+=value.byteLength;if(total>MAX_TARBALL_BYTES){return{ok:false,error:`tarball exceeds ${MAX_TARBALL_BYTES} byte cap`}}chunks.push(value)}}finally{reader.releaseLock()}tgzBuffer=Buffer.concat(chunks)}catch(e){return{ok:false,error:`tarball download failed: ${String(e)}`}}const v3=verifyTarballIntegrity(tgzBuffer,integrity,shasum);if(!v3.ok){return{ok:false,error:`tarball integrity verification failed: ${v3.error}`}}await sweepStaleUpdateTmp();let workDir;try{await mkdir2(cacheDir(),{recursive:true});workDir=await mkdtemp(path14.join(cacheDir(),".update-wip-"))}catch(e){return{ok:false,error:`failed to create temp workdir under ${cacheDir()}: ${String(e)}`}}const tmpFile=path14.join(workDir,"tarball.tgz");try{await writeFile2(tmpFile,tgzBuffer)}catch(e){return{ok:false,error:`failed to write temp file ${tmpFile}: ${String(e)}`}}const stagingDir=path14.join(workDir,"staging");try{await mkdir2(stagingDir);await So({file:tmpFile,cwd:stagingDir,strip:1});const stagingVersion=await readDiskVersion(stagingDir);if(stagingVersion!==version){return{ok:false,error:`staging verification failed: version is ${stagingVersion??"missing"}, expected ${version}`}}const stagingEntryErr=await verifyEntries(stagingDir,"staging verification failed");if(stagingEntryErr){return{ok:false,error:stagingEntryErr}}}catch(e){return{ok:false,error:`extraction failed: ${String(e)}`}}finally{await rm(tmpFile,{force:true})}let pnpmOldLink=null;{let linkStat=null;try{linkStat=await lstat(installDir)}catch{}if(linkStat?.isSymbolicLink()){pnpmOldLink=`${installDir}.pnpm-${Date.now()}`;try{await rename2(installDir,pnpmOldLink)}catch(e){return{ok:false,error:`failed to move the pnpm link aside (${pnpmOldLink}): ${String(e)} (install left untouched)`}}}}const backupDir=path14.join(workDir,"backup");if(!pnpmOldLink){try{await cp(installDir,backupDir,{recursive:true,force:true})}catch(e){return{ok:false,error:`backup of current install failed (install left untouched): ${String(e)}`}}}const restoreFromBackup=async()=>{try{await rm(installDir,{recursive:true,force:true});if(pnpmOldLink){await rename2(pnpmOldLink,installDir)}else{await cp(backupDir,installDir,{recursive:true,force:true})}return null}catch(e){return`ROLLBACK FAILED \u2014 restore ${pnpmOldLink??backupDir} to ${installDir} manually: ${String(e)}`}};let copyError=null;try{await cp(stagingDir,installDir,{recursive:true,force:true})}catch(e){copyError=`failed to copy to install dir: ${String(e)}`}finally{await rm(stagingDir,{recursive:true,force:true})}if(copyError!==null){const rb2=await restoreFromBackup();return{ok:false,error:rb2??copyError}}const newVersion=await readDiskVersion(installDir);if(newVersion!==version){const rb2=await restoreFromBackup();return{ok:false,error:rb2??`post-install verification failed: package.json version is ${newVersion??"missing"}, expected ${version}`}}const postEntryErr=await verifyEntries(installDir,"post-install verification failed");if(postEntryErr){const rb2=await restoreFromBackup();return{ok:false,error:rb2??postEntryErr}}if(opts.bootSmoke){const smokeErr=await bootSmoke(installDir,env);if(smokeErr!==null){const rb2=await restoreFromBackup();return{ok:false,error:rb2??`boot smoke failed (rolled back to the previous copy): ${smokeErr}`}}}await rm(backupDir,{recursive:true,force:true});if(pnpmOldLink){try{await unlink2(pnpmOldLink)}catch{}}await rm(workDir,{recursive:true,force:true});if(isDshDesktopBiliCopy(installDir,real,env)){const profileDir=path14.join(resolveDshHome(env),"profiles",DSH_DESKTOP_PROFILE);const conv=convergeDshLedger(profileDir,version);if(conv.error!==void 0){log("warn",`[update] dsh ${DSH_DESKTOP_PROFILE} profile copy replaced at ${version} but its ledgers were not converged (${conv.error}) \u2014 dsh may revert the copy on its next plugin install; rerun 'bili doctor --fix'`)}else if(conv.changed.length>0){log("info",`[update] dsh ${DSH_DESKTOP_PROFILE} profile ledgers converged to ${version}: ${conv.details.map(d2=>`${d2.file} ${d2.field} ${d2.before} \u2192 ${d2.after}`).join("; ")}`)}}return{ok:true}}async function detectStaleInstall(packageName,runningVersion){const installDir=await findInstallDir(packageName);if(!installDir||await isGitWorkingTree(installDir)){return{diskVersion:void 0,stale:false}}const diskVersion=await readDiskVersion(installDir);return{diskVersion,stale:staleInstallStatus(diskVersion,runningVersion)==="restart"}}async function fetchVersionDoc(opts,packageName,version){const url=`${REGISTRY_BASE}/${encodeURIComponent(packageName)}/${encodeURIComponent(version)}`;const dispatcher=egressDispatcher(opts,url);try{const res=await fetchWithEgress(url,{signal:AbortSignal.timeout(5e3),headers:{Accept:"application/json"},...dispatcher?{dispatcher}:{}});if(!res.ok)return void 0;const data=await res.json();return data?.dist?.tarball?data.dist:void 0}catch{return void 0}}async function forceInstallVersion(targetVersion,installDir,opts,advisoryId){if(!installDir){const error="cannot locate the install directory";warnAdvisoryOnce(advisoryId,`[update] advisory ${advisoryId}: ${error}`);return{ok:false,error}}const diskNow=await readDiskVersion(installDir);if((diskNow??opts.currentVersion)===targetVersion){const error=`advisory ${advisoryId} targets the current version ${targetVersion} (misconfigured advisory)`;warnAdvisoryOnce(advisoryId,`[update] ${error} \u2014 fix the advisory document`);return{ok:false,error}}if(await isGitWorkingTree(installDir)){warnAdvisoryOnce(advisoryId,`[update] advisory ${advisoryId}: running from a source checkout (${installDir}) \u2014 refusing self-update (#580); upgrade manually with npm install -g ${opts.packageName}@${targetVersion}`);return{ok:false,error:"running from a source checkout \u2014 refusing self-update (#580)"}}const managed=hostManagedInstall(installDir);if(managed){warnAdvisoryOnce(advisoryId,`[update] advisory ${advisoryId}: install dir belongs to ${managed.owner} \u2014 no in-place overwrite (#991); update via ${managed.channel}`);return{ok:false,error:`install dir is managed by ${managed.owner}; update via ${managed.channel}`}}const doc=await fetchVersionDoc(opts,opts.packageName,targetVersion);if(!doc?.tarball){const error=`cannot resolve ${targetVersion} on the registry`;warnAdvisoryOnce(advisoryId,`[update] advisory ${advisoryId}: ${error}`);return{ok:false,error}}const lock=await tryAcquireLock();if(!lock){warnAdvisoryOnce(advisoryId,`[update] advisory ${advisoryId}: another process is updating, will retry next cycle`);return{ok:false,error:"another process is updating, will retry next cycle"}}try{const diskUnderLock=await readDiskVersion(installDir);if(diskUnderLock===targetVersion)return{ok:true};const result=await installViaTarball(targetVersion,doc.tarball,installDir,doc.integrity,doc.shasum,egressDispatcher(opts,doc.tarball));if(result.ok){await persistLastInstall(diskUnderLock??opts.currentVersion,targetVersion,`advisory:${advisoryId}`);log("info",`[update] advisory ${advisoryId}: installed ${diskUnderLock??opts.currentVersion} \u2192 ${targetVersion}. Restart to finish.`);await runProfileBundlesRefresh(targetVersion,log);await refreshDshDesktopCopy(targetVersion,log,process.env,opts.resolveProxy);notifyStaleInstall(opts,targetVersion);return{ok:true}}warnAdvisoryOnce(advisoryId,`[update] advisory ${advisoryId}: install failed: ${result.error} (will retry next cycle)`);return{ok:false,error:result.error}}finally{await lock.release()}}var REGISTRY_BASE,CHECK_INTERVAL_MS,THROTTLE_FILE,OWNER_THROTTLE_FILE,LOCK_FILE,OWNER_LANE_CHECK_BASE_MS,OWNER_LANE_CHECK_JITTER_MS,LOCK_MAX_AGE_MS,UPDATE_TMP_MAX_AGE_MS,inFlight,firstCheckDone,staleWarnKey,advisoryRefusalWarnKeys,BACKOFF_THRESHOLD,BACKOFF_BASE_MS,BACKOFF_CAP_MS,installBackoffs,installBackoffRemediatedKeys,BACKOFF_STATE_FILE,BACKOFF_PRUNE_MS,backoffsLoaded,backoffFileMtime,LAST_INSTALL_FILE,installLocationLogged,DESKTOP_LANE_HINT,PROFILE_LANE_HINT,PI_LANE_HINT,policyGateLogged,BOOT_SMOKE_TIMEOUT_MS;var init_update=__esm({"src/update.ts"(){"use strict";init_index_min();init_text_safe();init_paths();init_logger();init_dsh_channel();init_dsh_ledger();init_pi_channel();init_client_config();init_upstream_proxy();init_knobs();init_update_policy();REGISTRY_BASE=normalizeRegistryBase(updateRegistryBase());CHECK_INTERVAL_MS=updateCheckIntervalMs();THROTTLE_FILE=path14.join(cacheDir(),".update-check");OWNER_THROTTLE_FILE=path14.join(cacheDir(),".owner-update-check");LOCK_FILE=path14.join(cacheDir(),".update-lock");OWNER_LANE_CHECK_BASE_MS=10*60*1e3;OWNER_LANE_CHECK_JITTER_MS=5*60*1e3;LOCK_MAX_AGE_MS=30*60*1e3;UPDATE_TMP_MAX_AGE_MS=60*60*1e3;inFlight=false;firstCheckDone=false;advisoryRefusalWarnKeys=new Set;BACKOFF_THRESHOLD=3;BACKOFF_BASE_MS=5*60*1e3;BACKOFF_CAP_MS=6*60*60*1e3;installBackoffs=new Map;installBackoffRemediatedKeys=new Set;BACKOFF_STATE_FILE=path14.join(cacheDir(),".install-backoff.json");BACKOFF_PRUNE_MS=7*24*60*60*1e3;backoffsLoaded=false;backoffFileMtime=-1;LAST_INSTALL_FILE=path14.join(cacheDir(),".last-install.json");installLocationLogged=false;DESKTOP_LANE_HINT="the dsh desktop profile layout is likely broken \u2014 recreate the desktop profile from dsh (or move DSH_HOME to a shorter path if pnpm virtual-store path limits are hit); retries resume automatically";PROFILE_LANE_HINT="run `dsh plugin --profile <name> add billion-context@<version>` from a shell where `dsh` resolves (or point BILI_DSH_BIN at dsh's executable)";PI_LANE_HINT=`run \`pi update --extension ${PI_NPM_SPEC}\` from a shell where \`pi\` resolves (or point BILI_PI_BIN at pi's executable)`;policyGateLogged=new Set;BOOT_SMOKE_TIMEOUT_MS=2e4}});import{createRequire as createRequire2}from"module";function wrapBetterSqlite3(db){return{exec:sql=>void db.exec(sql),prepare:sql=>db.prepare(sql),transaction:fn=>db.transaction(fn).immediate(),close:()=>void db.close(),get open(){return db.open}}}function openNodeSqlite(path54){const{DatabaseSync}=require3("node:sqlite");const db=new DatabaseSync(path54);let depth=0;const begin=()=>db.exec(depth===0?"BEGIN IMMEDIATE":`SAVEPOINT sp${depth}`);const commit=()=>db.exec(depth===1?"COMMIT":`RELEASE sp${depth-1}`);const rollback=()=>db.exec(depth===1?"ROLLBACK":`ROLLBACK TO sp${depth-1}`);return{exec:sql=>void db.exec(sql),prepare:sql=>adaptNodeSqliteStatement(db.prepare(sql)),transaction:fn=>{if(db.getAutoCommit?.()===false&&depth===0){return fn()}begin();depth++;try{const out=fn();commit();return out}catch(err2){rollback();throw err2}finally{depth--}},close:()=>void db.close(),get open(){return db.open}}}function adaptNodeSqliteStatement(stmt){return{run:(...args)=>{const res=stmt.run(...args);return{changes:Number(res?.changes??0),lastInsertRowid:Number(res?.lastInsertRowid??0)}},get:(...args)=>stmt.get(...args),all:(...args)=>stmt.all(...args)}}function probeBuiltinSqlite(){if(probeOverridesForTests?.builtin!==void 0)return probeOverridesForTests.builtin;try{require3("node:sqlite");return true}catch{return false}}function probeHostBetterSqlite3(){if(probeOverridesForTests?.host!==void 0)return probeOverridesForTests.host;try{require3("better-sqlite3");return true}catch{return false}}function registerSelfDownloadedBetterSqlite3(loader){selfDownloadedLoader=loader}function detectEngine(){if(cachedEngine)return cachedEngine;if(probeBuiltinSqlite())cachedEngine={name:"node:sqlite",source:"builtin"};else if(probeHostBetterSqlite3())cachedEngine={name:"better-sqlite3",source:"host"};else if(selfDownloadedLoader)cachedEngine={name:"better-sqlite3",source:"self-downloaded"};else throw new SqliteDriverError("no SQLite engine available","node:sqlite");return cachedEngine}function loadHostBetterSqlite3(){return require3("better-sqlite3")}function openSqliteDatabase(path54,engine){if(enginesUnavailableForTests){throw new SqliteDriverError("no SQLite engine available","node:sqlite")}const resolved=engine?{name:engine,source:engine==="node:sqlite"?"builtin":"host"}:detectEngine();if(resolved.name==="better-sqlite3"){try{const ctor=resolved.source==="self-downloaded"?selfDownloadedLoader():loadHostBetterSqlite3();return{db:wrapBetterSqlite3(new ctor(path54)),engine:resolved.name,source:resolved.source}}catch(err2){throw new SqliteDriverError(String(err2),resolved.name)}}try{return{db:openNodeSqlite(path54),engine:"node:sqlite",source:"builtin"}}catch(err2){throw new SqliteDriverError(String(err2),"node:sqlite")}}var SqliteDriverError,require3,probeOverridesForTests,selfDownloadedLoader,cachedEngine,enginesUnavailableForTests;var init_driver=__esm({"src/storage/driver.ts"(){"use strict";SqliteDriverError=class extends Error{constructor(message,engine){super(`[storage:${engine}] ${message}`);this.engine=engine}engine};require3=createRequire2(import.meta.url);probeOverridesForTests=null;selfDownloadedLoader=null;cachedEngine=null;enginesUnavailableForTests=false}});import{createHash as createHash8,randomBytes}from"crypto";import{existsSync as existsSync3,readFileSync as readFileSync5}from"fs";import{promises as fsp2}from"fs";import{createRequire as createRequire3}from"module";import path23 from"path";import{gunzipSync}from"zlib";function nodeMajorSatisfiesFloor(minNodeMajor,nodeVersion=process.versions.node){const major=Number.parseInt(nodeVersion.split(".")[0]??"",10);if(!Number.isFinite(major))return true;return major>=minNodeMajor}function specUnusableReason(spec,nodeVersion=process.versions.node,nodeAbi=process.versions.modules,napiVersion=process.versions.napi??""){if(!nodeMajorSatisfiesFloor(spec.minNodeMajor,nodeVersion)){return`better-sqlite3@${spec.version} needs Node.js >= ${spec.minNodeMajor}, this is ${nodeVersion}`}if(spec.minNapiVersion!==void 0){const napi=Number.parseInt(napiVersion,10);if(!Number.isFinite(napi))return null;if(napi<spec.minNapiVersion){return`better-sqlite3@${spec.version} is built against N-API ${spec.minNapiVersion}, this Node.js ${nodeVersion} ships N-API ${napiVersion}`}}if(spec.prebuild&&!spec.prebuild.sha512Base64ByAbi[nodeAbi]){return`better-sqlite3@${spec.version} ships no binding for Node ABI ${nodeAbi} (pinned ABIs: ${Object.keys(spec.prebuild.sha512Base64ByAbi).join(", ")}), this is Node.js ${nodeVersion}`}return null}function pinnedSpecForThisNode(){return ENGINE_SPECS.find(s3=>specUnusableReason(s3)===null)??null}function unsupportedNodeDetail(nodeVersion=process.versions.node,nodeAbi=process.versions.modules){const covered=ENGINE_SPECS.map(s3=>s3.prebuild?`better-sqlite3@${s3.version} on Node.js ${s3.minNodeMajor}.x (ABI ${Object.keys(s3.prebuild.sha512Base64ByAbi).join("/")})`:`better-sqlite3@${s3.version} on Node.js >= ${s3.minNodeMajor} (N-API >= ${s3.minNapiVersion??0})`).join(" or ");return`no pinned SQLite engine runs on Node.js ${nodeVersion} (ABI ${nodeAbi}) \u2014 the pinned artifacts cover ${covered}`}function platformTargetKey(overrides){const platform=overrides?.platform??process.platform;const arch=overrides?.arch??process.arch;const p2=platform==="linux"&&!hasGlibcRuntime()?"linuxmusl":platform;return`${p2}-${arch}`}function hasGlibcRuntime(){try{const report=process.report.getReport();return report.header?.glibcVersionRuntime!==void 0}catch{return false}}function cacheRoot(){return path23.join(cacheDir(),"sqlite")}function finalDir(spec,nodeAbi=process.versions.modules){const suffix=spec.prebuild?`-abi${nodeAbi}`:"";return path23.join(cacheRoot(),`better-sqlite3-${spec.version}${suffix}`)}function cooldownFile(){return path23.join(cacheRoot(),".bootstrap-failed.json")}function bootstrapFailureMarkerPath(){return cooldownFile()}function readBootstrapFailureMarker(){try{const raw=readFileSync5(cooldownFile(),"utf8");const j3=JSON.parse(raw);if(typeof j3.atMs==="number"&&typeof j3.reason==="string")return{atMs:j3.atMs,reason:j3.reason};return null}catch{return null}}async function readCooldown(){try{const raw=await fsp2.readFile(cooldownFile(),"utf8");const j3=JSON.parse(raw);if(typeof j3.atMs==="number"&&typeof j3.reason==="string")return{atMs:j3.atMs,reason:j3.reason};return null}catch{return null}}async function writeCooldown(reason){try{await fsp2.mkdir(cacheRoot(),{recursive:true});const tmp=`${cooldownFile()}.tmp-${randomBytes(4).toString("hex")}`;await fsp2.writeFile(tmp,JSON.stringify({atMs:Date.now(),reason},null,1));await fsp2.rename(tmp,cooldownFile())}catch(err2){log("debug",`[storage] sqlite bootstrap cooldown marker not written (${String(err2)})`)}}async function clearCooldown(){await fsp2.rm(cooldownFile(),{force:true}).catch(()=>{})}function cacheUsable(dir,target){return existsSync3(path23.join(dir,"package.json"))&&existsSync3(path23.join(dir,"lib","index.js"))&&existsSync3(path23.join(dir,"prebuilds",`${target}.node`))}function ensureSqliteEngine(opts={}){if(!inFlight2)inFlight2=runBootstrap(opts);return inFlight2}async function runBootstrap(opts){const env=opts.env??process.env;if(resolveStorageMode(env,fileStorageUnified())==="legacy"){return{status:"not-needed",detail:"unified storage disabled"}}if(probeBuiltinSqlite()){return{status:"not-needed",detail:"builtin node:sqlite available"}}if(probeHostBetterSqlite3()){return{status:"not-needed",detail:"host-provided better-sqlite3 available"}}const spec=specOverride??pinnedSpecForThisNode();if(!spec){const detail=unsupportedNodeDetail();log("warn",`[storage] sqlite engine self-bootstrap: skipped \u2014 ${detail}; staying on legacy storage${nodeSqliteUpgradeHint()}`);return{status:"unsupported-node",detail}}const unusable=specUnusableReason(spec);if(unusable){log("warn",`[storage] sqlite engine self-bootstrap: skipped \u2014 ${unusable}; a self-downloaded engine would crash this process on load, staying on legacy storage${nodeSqliteUpgradeHint()}`);return{status:"unsupported-node",detail:unusable}}const target=platformOverride??platformTargetKey();const dest=finalDir(spec);if(cacheUsable(dest,target)){if(!tryRegisterFromCache(dest,spec,target)){log("warn",`[storage] sqlite engine self-bootstrap: cached copy present but unloadable \u2014 removed, retrying one pinned download`);await fsp2.rm(dest,{recursive:true,force:true}).catch(()=>{})}else{return{status:"cache-hit",detail:target}}}if(!SUPPORTED_TARGETS.includes(target)){return{status:"unsupported-platform",detail:target}}if(spec.prebuild&&!spec.prebuild.sha512Base64ByAbi[process.versions.modules]?.[target]){return{status:"unsupported-platform",detail:`${target} (no pinned prebuild for better-sqlite3@${spec.version})`}}if(!resolveSqliteAutoDownload(env,fileStorageAutoDownload())){return{status:"disabled",detail:"storage.sqliteAutoDownload=false"}}const cd=await readCooldown();if(cd&&Date.now()-cd.atMs<COOLDOWN_MS){log("debug",`[storage] sqlite engine self-bootstrap in cooldown (${cd.reason}); skipping`);return{status:"cooldown",detail:cd.reason}}log("info",`[storage] sqlite engine self-bootstrap: downloading better-sqlite3@${spec.version}${spec.prebuild?" + its Node-ABI prebuild":""} from ${engineMirrors().join(" \u2192 ")} ...`);try{await downloadAndInstall(spec,target,process.versions.modules,opts.resolveProxy);if(!tryRegisterFromCache(dest,spec,target)){const reason="post-download registration failed";await writeCooldown(reason);log("warn",`[storage] sqlite engine self-bootstrap: download ok but engine still unloadable (${reason}) \u2014 continuing without it; retrying after ${COOLDOWN_MS/36e5}h`);return{status:"failed",detail:reason}}await clearCooldown();await pruneSiblingVersions(dest);log("info",`[storage] sqlite engine self-bootstrap: ok \u2014 engine=better-sqlite3(self-downloaded v${spec.version})`);return{status:"downloaded",detail:target}}catch(err2){const reason=err2 instanceof Error?err2.message:String(err2);await writeCooldown(reason);log("warn",`[storage] sqlite engine self-bootstrap failed (${reason}) \u2014 continuing without a self-downloaded engine; retrying after ${COOLDOWN_MS/36e5}h${nodeSqliteUpgradeHint()}`);return{status:"failed",detail:reason}}}function engineMirrors(){if(mirrorsOverride)return[...mirrorsOverride];const configured=normalizeRegistryBase(updateRegistryBase());const list=configured?[configured,...BUILTIN_REGISTRY_MIRRORS]:[...BUILTIN_REGISTRY_MIRRORS];return[...new Set(list)]}function prebuildMirrors(){return prebuildMirrorsOverride?[...prebuildMirrorsOverride]:[...BUILTIN_PREBUILD_MIRRORS]}function nodeSqliteUpgradeHint(nodeVersion=process.versions.node){const parts=nodeVersion.split(".").map(p2=>Number.parseInt(p2,10));const major=parts[0];const minor=parts[1];const hasBuiltin=typeof major==="number"&&typeof minor==="number"&&!Number.isNaN(major)&&!Number.isNaN(minor)&&(major>22||major===22&&minor>=5);if(hasBuiltin)return"";return" \u2014 node:sqlite needs Node.js >= 22.5; upgrade Node.js for the builtin engine (engine tarball mirrors tried in order: npm + npmmirror; set BILI_UPDATE_REGISTRY or update.registry to pin one)"}function withNativeBinding(Database,addonPath){const Bound=function BoundDatabase(file){return new Database(file,{nativeBinding:addonPath})};return Bound}function tryRegisterFromCache(dir,spec,target){try{const r=createRequire3(path23.join(dir,"package.json"));const mod=r("./lib/index.js");if(!spec.prebuild){registerSelfDownloadedBetterSqlite3(()=>mod);return true}const addonPath=path23.join(dir,"prebuilds",`${target}.node`);if(!existsSync3(addonPath))return false;registerSelfDownloadedBetterSqlite3(()=>withNativeBinding(mod,addonPath));return true}catch(err2){log("debug",`[storage] sqlite engine self-bootstrap: cache registration failed (${String(err2)})`);return false}}async function pruneSiblingVersions(keepDir){try{const entries2=await fsp2.readdir(cacheRoot());await Promise.all(entries2.flatMap(e=>{const dir=path23.join(cacheRoot(),e);if(!e.startsWith("better-sqlite3-")||dir===keepDir)return[];if(PINNED_DIR_PREFIXES.some(p2=>e===p2||e.startsWith(`${p2}-abi`)))return[];return[fsp2.rm(dir,{recursive:true,force:true}).catch(()=>{})]}))}catch{}}async function downloadAndInstall(spec,target,nodeAbi,resolveProxy2){const root=cacheRoot();await fsp2.mkdir(root,{recursive:true});const tmpDir=path23.join(root,`.wip-${randomBytes(6).toString("hex")}`);try{const npmTgz=await fetchFirstMirror(engineMirrors().map(base=>({url:`${base}/better-sqlite3/-/better-sqlite3-${spec.version}.tgz`,label:base})),spec.sha512Base64,root,resolveProxy2);await extractTgzToDir(npmTgz,tmpDir,target,{withPrebuilds:!spec.prebuild});if(spec.prebuild){const pinned=spec.prebuild.sha512Base64ByAbi[nodeAbi]?.[target];if(!pinned)throw new Error(`no pinned prebuild digest for ${target} on ABI ${nodeAbi}`);const fileName=`better-sqlite3-v${spec.version}-node-v${nodeAbi}-${target}.tar.gz`;const prebuildTgz=await fetchFirstMirror(prebuildMirrors().map(base=>({url:`${base}/v${spec.version}/${fileName}`,label:base})),pinned,root,resolveProxy2);await extractPrebuildTgz(prebuildTgz,tmpDir,target)}const dest=finalDir(spec,nodeAbi);if(existsSync3(dest)){if(!cacheUsable(dest,target))await fsp2.rm(dest,{recursive:true,force:true});else return}await fsp2.rename(tmpDir,dest)}finally{await fsp2.rm(tmpDir,{recursive:true,force:true}).catch(()=>{})}}async function fetchFirstMirror(attempts,expectedSha512Base64,scratchDir,resolveProxy2){const tmpTgz=path23.join(scratchDir,`.dl-${randomBytes(6).toString("hex")}.tgz`);const attempted=[];let lastErr=null;try{for(const attempt of attempts){attempted.push(attempt.label);try{return await fetchVerifiedTarball(attempt.url,expectedSha512Base64,tmpTgz,resolveProxy2)}catch(err2){lastErr=err2;log("warn",`[storage] sqlite engine self-bootstrap: mirror ${attempt.label} failed (${err2 instanceof Error?err2.message:String(err2)}) \u2014 trying next mirror`)}}const reason=lastErr instanceof Error?lastErr.message:String(lastErr);throw new Error(`${reason} (tried mirrors: ${attempted.join(", ")})`)}finally{await fsp2.rm(tmpTgz,{force:true}).catch(()=>{})}}async function fetchVerifiedTarball(url,expectedSha512Base64,tmpTgz,resolveProxy2){const dispatcher=proxyDispatcher(resolveProxy2?.(url));const res=await fetch(url,{signal:AbortSignal.timeout(bootstrapTimeoutOverrideMs??BOOTSTRAP_TIMEOUT_MS),...dispatcher?{dispatcher}:{}});if(!res.ok||!res.body)throw new Error(`registry returned HTTP ${res.status} for ${url}`);const hash=createHash8("sha512");const out=await fsp2.open(tmpTgz,"w");try{const reader=res.body.getReader();for(;;){const{done,value}=await reader.read();if(done)break;if(value){hash.update(value);await out.write(value)}}}finally{await out.close()}const digest=hash.digest("base64");if(digest!==expectedSha512Base64){throw new Error(`sha512 mismatch (got ${digest.slice(0,16)}..., pinned ${expectedSha512Base64.slice(0,16)}...) \u2014 quarantining download`)}return await fsp2.readFile(tmpTgz)}function included(name,withPrebuilds){if(INCLUDE_EXACT.has(name)||name.startsWith("package/lib/"))return true;return withPrebuilds&&name.startsWith("package/prebuilds/")}async function extractTgzToDir(tgz,destDir,target,opts={}){const withPrebuilds=opts.withPrebuilds??true;await fsp2.mkdir(destDir,{recursive:true});await extractTgzEntries(tgz,name=>included(name,withPrebuilds)?destFor(name,destDir):null);const required=withPrebuilds?["package.json",path23.join("lib","index.js"),path23.join("prebuilds",`${target}.node`)]:["package.json",path23.join("lib","index.js")];for(const rel2 of required){if(!existsSync3(path23.join(destDir,rel2)))throw new Error(`tarball missing required file: ${rel2}`)}}async function extractPrebuildTgz(tgz,destDir,target){const dest=path23.join(destDir,"prebuilds",`${target}.node`);await fsp2.mkdir(path23.dirname(dest),{recursive:true});await extractTgzEntries(tgz,name=>name.endsWith(".node")?dest:null);if(!existsSync3(dest))throw new Error(`prebuild tarball missing a .node binding for ${target}`)}async function extractTgzEntries(tgz,resolveDest){let data;try{data=gunzipSync(tgz)}catch(err2){throw new Error(`gunzip failed: ${String(err2)}`)}let off=0;let pendingName=null;while(off+512<=data.length){const header=data.subarray(off,off+512);if(header.every(b3=>b3===0))break;const size=parseOctal(header.subarray(124,136));const typeflag=header[156];const name=pendingName??cstr(header.subarray(0,100));pendingName=null;off+=512;const payload=data.subarray(off,off+size);off+=size+pad512(size);if(typeflag===76){pendingName=cstr(payload);continue}if(typeflag===120||typeflag===103){const paxPath=paxRecordPath(payload);if(paxPath)pendingName=paxPath;continue}const dest=resolveDest(name);if(dest===null)continue;if(typeflag===48||typeflag===0){await fsp2.mkdir(path23.dirname(dest),{recursive:true});await fsp2.writeFile(dest,payload)}else if(typeflag===53){await fsp2.mkdir(dest,{recursive:true})}else{throw new Error(`unsupported tar entry type 0x${typeflag.toString(16)} for ${name}`)}}}function destFor(name,destDir){const rel2=name.startsWith("package/")?name.slice("package/".length):name;if(rel2.length===0||rel2.includes("..")||path23.isAbsolute(rel2))throw new Error(`unsafe tar path: ${name}`);return path23.join(destDir,rel2)}function cstr(buf){const nul=buf.indexOf(0);return buf.subarray(0,nul===-1?buf.length:nul).toString("utf8")}function parseOctal(field){const digits=field.toString("ascii").replace(/[^\d]/g,"").slice(0,11);const n=digits.length>0?parseInt(digits,8):0;return Number.isFinite(n)?n:0}function pad512(n){return(512-n%512)%512}function paxRecordPath(payload){let off=0;while(off<payload.length){const sp=payload.indexOf(32,off);if(sp===-1)break;const len=parseInt(payload.subarray(off,sp).toString("ascii"),10);if(!Number.isFinite(len)||len<=0||off+len>payload.length)break;const rec=payload.subarray(off,off+len).toString("utf8");const m3=/^(\d+) ([\w.-]+)=(.*)$/.exec(rec);if(m3&&m3[2]==="path")return m3[3];off+=len}return null}var ENGINE_SPECS,SUPPORTED_TARGETS,BOOTSTRAP_TIMEOUT_MS,COOLDOWN_MS,specOverride,platformOverride,inFlight2,bootstrapTimeoutOverrideMs,BUILTIN_REGISTRY_MIRRORS,BUILTIN_PREBUILD_MIRRORS,mirrorsOverride,prebuildMirrorsOverride,PINNED_DIR_PREFIXES,INCLUDE_EXACT;var init_engine_bootstrap=__esm({"src/storage/engine-bootstrap.ts"(){"use strict";init_logger();init_paths();init_driver();init_knobs();init_update();init_upstream_proxy();ENGINE_SPECS=Object.freeze([{version:"13.0.3",sha512Base64:"RbOBxmLBG8uvFUc15X9+9SFemKcQ0WBuISBVkpuiaUB2qblC8UWlHEjdVVoZ8AdhSwmoEgsiXKfopX0CQxaACQ==",minNodeMajor:22,minNapiVersion:10},{version:"12.9.0",sha512Base64:"wqUv4Gm3toFpHDQmaKD4QhZm3g1DjUBI0yzS4UBl6lElUmXFYdTQmmEDpAFa5o8FiFiymURypEnfVHzILKaxqQ==",minNodeMajor:20,prebuild:{sha512Base64ByAbi:Object.freeze({"115":Object.freeze({"linux-x64":"fNMKurhPKb0ki9mnZJK9PVazCiRugcdmauo5qGjqQjUGIrdaVWrb4nlLwU7IiyppcfLu8n/qUsQ5CEZ36uoGaw==","linux-arm64":"7q7wZe0+5LLQt2YUkocGb41B9TvEMLKIaNI+CiQUQQ2DFBO1RPr3ixj/Gtb+0noMYHjJrqtqKUMO1xMQXnE0iw==","linuxmusl-x64":"GCriICDKw7K5dNjAVo8xFpSJXcYXXBAK9RDoeuSUv6rB5IVRP96IwxeynTy4Xc21l1507Efz+I2yy6FW5gKQ/w==","linuxmusl-arm64":"2OWfVP1nklnuR8ZfCwozJcLB0ZpOTRHqAkDpsLonEF5uHZMBnOAzGtd5d+nuPU+KaS5czciU0tXZFhsCUw7dbg==","darwin-x64":"tW2Vb19+Bh+PLfcGVnrERhc9Mk50Vi8HciIc0nwIJXlPm21xzKL6uEQHMoyKIAxF+vNXxDsUoJyNRg/TgCXjkA==","darwin-arm64":"H6jehr7s1D/RSTRplCL++hneLTgpqVzgzjrX/NJCsf0OMBSKNGCd9kMYAZJjMlp0IetS39sG5PTG7AcLCTQKeg==","win32-x64":"r+BAeN980mQEdIwDcrNU3iJqzAryuOyfeICFfYHuHVclonTr2L0IlzsaGp2D50KNWUeLQrIhBCFuNoT2+iBDTw==","win32-arm64":"jMSa36VrAiLsWFtnwWX+FEs4JWIjHeduVITY44ZcHsqn7BzPcMljL8LdJ0tVVGssV8x9PuqgIqMD5gFmzcYh9w=="}),"127":Object.freeze({"linux-x64":"jpVKlRCjwmKDIfohRK4Zf/potrKjl2CuvKiWm2SOL1eY7pTRQrGBc1DSEr4OBulYHE6PTl59w7hoAlzNOefG3g==","linux-arm64":"ei++r3DQbhwXsP97PHYENHnNd3jrai5dy11SCDZqzmqEm6mjloT1qwrpglVJmW4TLliYBJ8U9bMG/6Y8nbDBCQ==","linuxmusl-x64":"eFglLYVSmdQo7ehLh30dOF4H9csX92XIn1oKB3TdtTZ+7TTh7cfViO7TQIC4NPt6Ufbl3cos9y6/pU8FNL1dQg==","linuxmusl-arm64":"e72bURjJ4SYseIMY7uW1IkubTqzuKzD6NIVP0InsD8+DJBnRwi8+yIEEcODIK4xsFKSO6tE8TLuvPmetXEk8aA==","darwin-x64":"GxXg+WENfyP9DGnvOSMnPge+kDkEZmU8cF7EFOoFSzAFhEwYOBvFB4VTTqhZ6G4y54I7ufkjgkOxZmafdSOXOw==","darwin-arm64":"V1mPpKKnv3AvfZb/++CSOx49tmUi4fba4vORsD8GTaJVwvKmveJ/uPqXaEVhYQgDkao5VLiWL6gN2wk9rQXfPw==","win32-x64":"7chlb4LP9ETESK6djkGxDq4aDTTByiG1VoUwadJk7JZFhfn2u7vblPCulZaM2C3Ju3jHowc8LBKKQZiH52Uc5g==","win32-arm64":"0mD1nLGHG066cUFdIgMTEJfhbIeOgD52+dE0r8LAALarhU5JD0uyKPvpQH/V3rBjvwTOtaQtYqeEFgRj5NUL/g=="})})}}]);SUPPORTED_TARGETS=["linux-x64","linux-arm64","linuxmusl-x64","linuxmusl-arm64","darwin-x64","darwin-arm64","win32-x64","win32-arm64"];BOOTSTRAP_TIMEOUT_MS=6e4;COOLDOWN_MS=6*60*60*1e3;specOverride=null;platformOverride=null;inFlight2=null;bootstrapTimeoutOverrideMs=null;BUILTIN_REGISTRY_MIRRORS=["https://registry.npmjs.org","https://registry.npmmirror.com"];BUILTIN_PREBUILD_MIRRORS=["https://registry.npmmirror.com/-/binary/better-sqlite3","https://github.com/WiseLibs/better-sqlite3/releases/download"];mirrorsOverride=null;prebuildMirrorsOverride=null;PINNED_DIR_PREFIXES=ENGINE_SPECS.map(s3=>`better-sqlite3-${s3.version}`);INCLUDE_EXACT=new Set(["package/package.json"])}});function refToIndex2(ref){const match=REF_PATTERN2.exec(ref.trim().toLowerCase());if(!match)return null;const index=Number(match[1]);if(index<MIN_INDEX2||index>MAX_INDEX2)return null;return index}var MIN_INDEX2,MAX_INDEX2,REF_PATTERN2;var init_refs=__esm({"kernel/src/refs.ts"(){"use strict";MIN_INDEX2=1;MAX_INDEX2=9999999;REF_PATTERN2=/^m0*(\d{1,7})$/}});import{createHash as createHash9}from"crypto";import{mkdirSync as mkdirSync4,writeFileSync as writeFileSync2,appendFileSync as appendFileSync2,readFileSync as readFileSync6,existsSync as existsSync4,unlinkSync as unlinkSync2,statSync as statSync4}from"fs";import{dirname as dirname2,join as join3}from"path";function sha256Hex2(bytes){return createHash9("sha256").update(bytes).digest("hex")}function validateExtKey(value,what){if(typeof value!=="string"||value.length===0||value.length>EXT_KEY_MAX){throw new Error(`[storage] extension ${what} must be a non-empty string of at most ${EXT_KEY_MAX} characters`)}for(let i=0;i<value.length;i++){const c=value.charCodeAt(i);if(c<32||c===127){throw new Error(`[storage] extension ${what} must not contain control characters`)}}}function serializeExtValue(value){const json=JSON.stringify(value);if(json===void 0){throw new Error("[storage] extension values must be JSON-serializable (undefined/functions are not)")}if(json.length>EXT_VALUE_MAX_BYTES){throw new Error(`[storage] extension value exceeds ${EXT_VALUE_MAX_BYTES} bytes \u2014 store large payloads in the content CAS instead`)}return json}function likeEscape(prefix){return prefix.replace(/[\\%_]/g,ch=>"\\"+ch)}function processAlive(pid){try{process.kill(pid,0);return true}catch(err2){return err2.code==="EPERM"}}var WAL_CHECKPOINT_EVERY_INGESTS,EXT_KEY_MAX,EXT_VALUE_MAX_BYTES,StorageIntegrityError,UnifiedStore;var init_store=__esm({"src/storage/store.ts"(){"use strict";init_logger();init_driver();init_schema();init_identity();init_runtime_status();init_instance();WAL_CHECKPOINT_EVERY_INGESTS=20;EXT_KEY_MAX=256;EXT_VALUE_MAX_BYTES=4*1024*1024;StorageIntegrityError=class extends Error{constructor(dbPath,detail){super(`[storage] integrity quick_check failed for ${dbPath}: ${detail}`);this.dbPath=dbPath;this.detail=detail;this.name="StorageIntegrityError"}dbPath;detail};UnifiedStore=class _UnifiedStore{engine;engineSource;db;ingestCount=0;foreignLockHolder;lockPath;constructor(db,engine,engineSource,lockPath,foreignLockHolder){this.db=db;this.engine=engine;this.engineSource=engineSource;this.lockPath=lockPath;this.foreignLockHolder=foreignLockHolder}static open(path54,engine,opts){mkdirSync4(dirname2(path54),{recursive:true});const{db,engine:used,source}=openSqliteDatabase(path54,engine);if(process.env.BILI_STORAGE_QUICK_CHECK!=="0"){const started=Date.now();let verdict;try{const rows=db.prepare("PRAGMA quick_check").all();verdict=rows.map(row=>String(row.quick_check??"")).join(" ").trim()}catch(err2){recordIntegrityOutcome(path54,false,Date.now()-started,String(err2).slice(0,400));db.close();throw err2}const durationMs=Date.now()-started;recordIntegrityOutcome(path54,verdict==="ok",durationMs,verdict==="ok"?void 0:verdict.slice(0,400));if(verdict!=="ok"){db.close();throw new StorageIntegrityError(path54,verdict.slice(0,400))}}const lockPath=`${path54}.lock`;let foreignLockHolder=null;try{if(existsSync4(lockPath)){const parsed=JSON.parse(readFileSync6(lockPath,"utf8"));const pid=typeof parsed.pid==="number"?parsed.pid:null;if(pid!==null&&pid!==process.pid&&processAlive(pid)){foreignLockHolder={pid};const peer=listInstances().filter(e=>e.pid===pid).reduce((best,e)=>best===void 0||(e.startedAt??0)>(best.startedAt??0)?e:best,void 0);const ownLane=process.env.BILI_LAUNCHER_LANE?.trim()||void 0;const benign=peer!==void 0&&ownLane!==void 0&&peer.lane!==void 0&&peer.lane!==ownLane;if(benign){log("info",`[storage] process (pid ${pid}, lane ${peer?.lane}, instance ${peer?.instanceId.slice(0,8)}) is also using ${path54} \u2014 different lanes sharing one sessions directory is the supported topology (#3923/#3959); informational only.`)}else{log("error",`[storage] another process (pid ${pid}) is already writing ${path54} \u2014 two processes on one index.db corrupt it (#3923/#3959). One session dir must have exactly one instance (#3633); this lane keeps running but the condition is reported.`)}recordSecondProcessOwner(pid,{lane:peer?.lane,instanceId:peer?.instanceId,benign})}}writeFileSync2(lockPath,JSON.stringify({pid:process.pid,boot:Date.now()}))}catch(err2){log("warn",`[storage] lockfile discipline skipped for ${path54}: ${String(err2)}`)}try{const limit=opts?.walJournalSizeLimitBytes??WAL_JOURNAL_SIZE_LIMIT;for(const pragma of storagePragmas(limit))db.exec(pragma);migrateSchema(db)}catch(err2){db.close();throw err2}try{db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get()}catch(err2){log("warn",`[storage] WAL checkpoint on open failed for ${path54}: ${String(err2)}`)}return new _UnifiedStore(db,used,source,lockPath,foreignLockHolder)}close(){try{this.db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get()}catch(err2){log("warn",`[storage] WAL checkpoint on close failed: ${String(err2)}`)}this.db.close();if(this.lockPath!==null&&this.foreignLockHolder===null){try{unlinkSync2(this.lockPath)}catch{}}}lockHolder(){return this.foreignLockHolder}backupInto(dstPath){if(existsSync4(dstPath)){throw new Error(`[storage] backup target already exists: ${dstPath}`)}mkdirSync4(dirname2(dstPath),{recursive:true});const quoted=dstPath.replace(/'/g,"''");this.db.exec(`VACUUM INTO '${quoted}'`);recordBackupOutcome(dstPath,statSync4(dstPath).size);return statSync4(dstPath).size}sessionCounters(sessionId){const row=this.db.prepare("SELECT next_block_id, stats_json FROM sessions WHERE session_id = ?").get(sessionId);if(!row)return null;try{const stats=JSON.parse(row.stats_json);return{requests:typeof stats.requests==="number"?stats.requests:0,nextBlockId:row.next_block_id}}catch{return null}}putContent(content,precomputedHash){const bytes=typeof content==="string"?Buffer.from(content,"utf8"):content;const hash=precomputedHash??sha256Hex2(bytes);const existing=this.db.prepare("SELECT refcount FROM content WHERE hash = ?").get(hash);if(existing){this.db.prepare("UPDATE content SET refcount = refcount + 1 WHERE hash = ?").run(hash)}else{this.db.prepare("INSERT INTO content (hash, byte_len, refcount, algo, bytes) VALUES (?, ?, 1, 'sha256', ?)").run(hash,bytes.byteLength,bytes)}return hash}mergeOrphansJson(sessionId,incomingJson){if(incomingJson===null){const row=this.db.prepare("SELECT orphans_json FROM sessions WHERE session_id = ?").get(sessionId);return row?.orphans_json??null}let merged={};try{const existing=this.db.prepare("SELECT orphans_json FROM sessions WHERE session_id = ?").get(sessionId);if(existing?.orphans_json){const parsed=JSON.parse(existing.orphans_json);if(parsed&&typeof parsed==="object")merged=parsed}}catch{}try{const incoming=JSON.parse(incomingJson);if(incoming&&typeof incoming==="object")merged={...merged,...incoming}}catch{}return Object.keys(merged).length>0?JSON.stringify(merged):null}releaseContent(hash){if(!hash)return;this.db.prepare("UPDATE content SET refcount = refcount - 1 WHERE hash = ? AND refcount > 0 RETURNING refcount").all(hash).forEach(row=>{if(row.refcount<=0){this.db.prepare("DELETE FROM content WHERE hash = ? AND refcount <= 0").run(hash)}})}ingestSession(input,delta,opts){const s3=input.session;const ok=this.db.transaction(()=>{let messages;let watermark;if(delta){const probe=this.probeIngestBoundary(s3.sessionId,delta.trustedSeq);if(!probe||probe.msgId!==delta.boundaryMsgId||probe.contentHash!==delta.boundaryHash){return false}const existingIdentity=this.db.prepare("SELECT 1 FROM messages WHERE session_id = ? AND msg_id = ? AND identity = ?");for(const m3 of input.messages){if(!m3.contentHash)return false;if(existingIdentity.get(s3.sessionId,m3.msgId,m3.identity??identityOfStoredContent(m3.content)))return false}messages=input.messages.map((m3,i)=>({...m3,seq:probe.maxSeq+1+i}));const tail=JSON.parse(s3.tailJson);const prefixOk=Array.isArray(tail.tailSeqs)&&tail.tailSeqs.length===delta.trustedTailSeqs.length+input.messages.length&&delta.trustedTailSeqs.every((v3,i)=>tail.tailSeqs?.[i]===v3);if(!prefixOk)return false;s3.tailJson=JSON.stringify({...tail,tailSeqs:[...delta.trustedTailSeqs,...messages.map(m3=>m3.seq)]});watermark=messages.length>0?messages[messages.length-1].seq:delta.trustedSeq}else{const full=this.remapPlanToAbsolute(input);messages=full.messages;watermark=full.watermark;if(opts?.completeLog===true&&!this.hasLaneExt(s3.sessionId)){const incomingIds=new Set;for(const m3 of messages){incomingIds.add(`${m3.msgId}\0${m3.identity??identityOfStoredContent(m3.content)}`)}const staleRows=this.db.prepare("SELECT seq, msg_id, identity, retired_at FROM messages WHERE session_id = ?").all(s3.sessionId);for(const row of staleRows){if(incomingIds.has(`${row.msg_id}\0${row.identity}`)){if(row.retired_at!==null){this.db.prepare("UPDATE messages SET retired_at = NULL WHERE session_id = ? AND seq = ?").run(s3.sessionId,row.seq)}continue}this.db.prepare("UPDATE messages SET retired_at = ? WHERE session_id = ? AND seq = ? AND retired_at IS NULL").run(Date.now(),s3.sessionId,row.seq);const retiredMedia=this.db.prepare("SELECT media_hash FROM message_media WHERE session_id = ? AND seq = ?").all(s3.sessionId,row.seq);this.db.prepare("DELETE FROM message_media WHERE session_id = ? AND seq = ?").run(s3.sessionId,row.seq);for(const rm5 of retiredMedia)this.releaseContent(rm5.media_hash)}}}this.db.prepare(`INSERT INTO sessions (session_id, parent_session_id, fork_point_seq, protocol, label, title, host_title, namespace, origin,
538
538
  status, created_at, updated_at, next_block_id, next_run_id,