billion-context 0.1.210 → 0.1.211

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -316,7 +316,7 @@ ${partialOutcomeNote(blocksCreated)}`;const out={text,failed:outcome==="failure"
316
316
  [${kind} truncated] ${lines.length} more lines`;const budget=max-probeMarker.length;const kept=[];let acc=0;for(const line of lines){const next=acc+(kept.length>0?1:0)+line.length;if(next>budget&&kept.length>0)break;kept.push(line);acc=next}const dropped=lines.length-kept.length;const desc=kept.join("\n")+`
317
317
 
318
318
  [${kind} truncated] ${dropped} more line${dropped===1?"":"s"}`;return desc.length<=max?desc:desc.slice(0,max)}init_client_config();import fs10 from"fs";import path17 from"path";import crypto3 from"crypto";import fs11 from"fs";import path18 from"path";init_instance();init_config();init_log_mask();init_logger();init_paths();init_version();import{appendFileSync,mkdirSync as mkdirSync3}from"fs";import path20 from"path";function logHostEvent(level,origin,msg){try{const file=defaultLogFile();mkdirSync3(path20.dirname(file),{recursive:true});const safe=maskUrlsForDiagnostics(maskIpsInText(redactSecretsInText(msg)));appendFileSync(file,`${logTimestamp()} [${level}] [v=${VERSION}] ${origin?`${origin} `:""}${safe}
319
- `)}catch{}}init_logger();init_version();import http from"http";var PERMISSION_DENIED_SIGNATURE=/\b(?:EPERM|EACCES|EROFS|EBUSY)\b|operation not permitted|permission denied|read-only file system|readonly database/i;var BILI_DATA_PATH_SIGNATURE=/billion-context|combined-ca\.pem|index\.db|\.local[\\/](?:share|state)[\\/]/i;function classifyStartupFailure(sample){if(!PERMISSION_DENIED_SIGNATURE.test(sample)||!BILI_DATA_PATH_SIGNATURE.test(sample))return"";return"possible cause: the proxy could not write its own data files (EPERM/EACCES/read-only on the bili data dir) \u2014 most often antivirus (e.g. Windows Defender Controlled Folder Access) blocking the node runtime, a read-only flag or ACL on the directory, or another process holding the files; add the bili data dir and the node runtime to AV exclusions (see #367) or fix the directory permissions, then retry"}var MAX_HOLD_MS=10*6e4;init_update();init_win_cmd();init_client_config();init_config();init_registry();init_config();init_logger();function parseLauncherModelWindows(raw){if(!raw)return{};try{const parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return{};const out={};for(const[id,v2]of Object.entries(parsed)){if(typeof v2==="number"&&Number.isFinite(v2)&&v2>0)out[id]=Math.floor(v2)}return out}catch{return{}}}var LAUNCHER_MODEL_WINDOWS=parseLauncherModelWindows(process.env.BILI_LAUNCHER_MODEL_WINDOWS);function parseLauncherModelMaxOutputs(raw){if(!raw)return{};try{const parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return{};const out={};for(const[id,v2]of Object.entries(parsed)){if(typeof v2==="number"&&Number.isFinite(v2)&&v2>0)out[id]=Math.floor(v2)}return out}catch{return{}}}var LAUNCHER_MODEL_MAX_OUTPUTS=parseLauncherModelMaxOutputs(process.env.BILI_LAUNCHER_MODEL_MAX_OUTPUTS);init_vertex();init_client_config();init_logger();import{createHash as createHash13}from"crypto";import{createHash as createHash12,randomUUID as randomUUID4}from"crypto";import{closeSync,existsSync as existsSync6,fsyncSync,mkdirSync as mkdirSync6,openSync,readdirSync,readFileSync as readFileSync7,renameSync as renameSync2,rmSync,statSync as statSync6,writeFileSync as writeFileSync5}from"fs";import{readdir as readdir2,readFile as readFile4,rm as rm2}from"fs/promises";import*as path23 from"path";init_paths();init_knobs();init_logger();init_runtime_status();init_version();import{createCipheriv,createDecipheriv,randomBytes as randomBytes2}from"crypto";import*as zlib from"zlib";var ENCRYPT_MAGIC=Buffer.from("BILIENC1","utf8");var ZSTD_MAGIC=Buffer.from("BILIZSTD1","utf8");var NONCE_LEN=12;var TAG_LEN=16;var ENCRYPT_HEADER_LEN=ENCRYPT_MAGIC.length+2+NONCE_LEN;var MIN_ENCRYPTED_LEN=ENCRYPT_HEADER_LEN+TAG_LEN;var PLAIN_HEADER_LEN=ZSTD_MAGIC.length+2;init_logger();init_billing();init_state_hydration();init_shadow();init_backend();init_ingest();init_store();init_logger();init_paths();import{randomUUID as randomUUID2}from"crypto";import{mkdirSync as mkdirSync5,writeFileSync as writeFileSync4}from"fs";import{dirname as dirname3,join as join2}from"path";init_knobs();import{createHash as createHash11,randomUUID as randomUUID3}from"crypto";import{AsyncLocalStorage as AsyncLocalStorage3}from"async_hooks";init_logger();import{createHash as createHash10}from"crypto";import{createHash as createHash9}from"crypto";init_logger();init_logger();init_billing();init_util();var BOOT_ID=randomUUID3();var SEAM_BODY_CAP=512*1024;var BODY_FULL_CAP=8*1024*1024;var captures=new AsyncLocalStorage3;var LEARNED_IMAGE_COST_TTL_MS=24*60*60*1e3;var{join:join4}=path23;init_version();init_knobs();init_config();init_config();init_paths();init_logger();init_external_summary_settings();import*as path24 from"path";init_turn_separator();init_turn_separator();var ABORT_REANCHOR_MAX_AGE_MS=30*60*1e3;var MAX_SESSIONS=maxSessions();var MAX_RESIDENT_BYTES=sessionResidentMaxBytes();var SPLIT_CANARY_FRESH_MS=10*60*1e3;import{randomUUID as randomUUID5}from"crypto";init_knobs();var CODEX_FORGED_HANDOFF_HEADER="[bili] context summary after compaction:";var FORGED_SUMMARY_HEADER="[Compressed conversation section]";init_client_config();import fs13 from"fs";import path25 from"path";init_dsh_channel();var SCAN_CACHE_TTL_MS=5*60*1e3;var CONFLICT_ACTIVE_WINDOW_MS=7*24*60*60*1e3;var LAUNCHER_DEFAULT_HOST="127.0.0.1";var HEALTH_PATH="/__bili/health";var HEALTH_POLL_INTERVAL_MS=200;var SPAWN_WAIT_MS=envMillis(process.env,"BILI_SPAWN_WAIT_MS",2e4);var SLOW_START_GRACE_MS=envMillis(process.env,"BILI_SLOW_START_GRACE_MS",4e4);var SPAWN_BUDGET_MS=SPAWN_WAIT_MS+SLOW_START_GRACE_MS;var PROBE_TIMEOUT_MS=1500;var STARTING_MARKER_TTL_MS=SPAWN_BUDGET_MS+3e4;var POST_EXIT_REDISCOVERY_MS=3e3;var DEFAULT_MITM_DOMAIN_SET=new Set(DEFAULT_MITM_DOMAINS.map(d=>d.toLowerCase()));function proxyOrigin(host,port){return`http://${host}:${port}`}function healthUrl(origin){return origin+HEALTH_PATH}async function defaultFetch(url){const ctrl=new AbortController;const t=setTimeout(()=>ctrl.abort(),PROBE_TIMEOUT_MS);try{const res=await fetch(url,{signal:ctrl.signal});return{ok:res.ok}}catch{return{ok:false}}finally{clearTimeout(t)}}async function probeHealth(origin,fetchImpl){try{const{ok}=await fetchImpl(healthUrl(origin));return ok}catch{return false}}function describeProbeFailure(err){const e=err;const code=e?.cause?.code??e?.code;if(typeof code==="string"&&code.length>0)return code;if(e?.name==="TimeoutError"||e?.name==="AbortError")return`timeout after ${PROBE_TIMEOUT_MS}ms`;if(typeof e?.message==="string"&&e.message.length>0)return e.message.slice(0,160);return String(err)}async function defaultFetchDetail(url){const ctrl=new AbortController;const t=setTimeout(()=>ctrl.abort(),PROBE_TIMEOUT_MS);try{const res=await fetch(url,{signal:ctrl.signal});return res.ok?{ok:true}:{ok:false,detail:`HTTP ${res.status}`}}catch(err){return{ok:false,detail:describeProbeFailure(err)}}finally{clearTimeout(t)}}async function fetchHealthInfoDefault(origin,opts){try{const res=await fetch(healthUrl(origin),{signal:AbortSignal.timeout(PROBE_TIMEOUT_MS),...opts?.noKeepAlive?{headers:{connection:"close"}}:{}});if(!res.ok)return void 0;const data=await res.json();const info={ok:Boolean(data.ok),instanceId:typeof data.instanceId==="string"?data.instanceId:void 0};if(typeof data.version==="string")info.version=data.version;if(typeof data.pid==="number")info.pid=data.pid;if(typeof data.auxProxy==="string"&&data.auxProxy.length>0)info.auxProxy=data.auxProxy;if(typeof data.auxProxySource==="string"&&data.auxProxySource.length>0)info.auxProxySource=data.auxProxySource;if(data.watchdog&&typeof data.watchdog==="object"&&typeof data.watchdog.armed==="boolean"){const wd=data.watchdog;const watchers=Array.isArray(wd.watchers)?wd.watchers.filter(w2=>typeof w2==="number"):void 0;info.watchdog={armed:wd.armed,watchers}}return info}catch{return void 0}}async function registerWatcherDefault(origin,pid){try{const res=await fetch(`${origin}/__bili/watcher`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({pid}),signal:AbortSignal.timeout(2e3)});if(!res.ok){if(res.status===409)return"refused";console.error(`bili: watcher registration returned HTTP ${res.status} \u2014 the shared proxy may exit when its first owner does`);return"failed"}return"ok"}catch(err){console.error(`bili: watcher registration failed \u2014 the shared proxy may exit when its first owner does (${err instanceof Error?err.message:String(err)})`);return"failed"}}function isStartingMarkerActive(marker,nowMs){return isPidAlive(marker.pid)&&nowMs-marker.startedAt<STARTING_MARKER_TTL_MS}function recordedModelMap(passed,ambientRaw,parse3){return parse3(passed&&Object.keys(passed).length>0?JSON.stringify(passed):ambientRaw)}function instanceShapeMismatch(inst,opts,foreignLanes=[]){if(opts.lane!==void 0&&inst.lane!==void 0&&inst.lane!==opts.lane&&!foreignLanes.includes(inst.lane))return"lane-mismatch";if(inst.host!==opts.host||inst.passthrough!==resolveRecordedPassthrough(opts.passthrough))return"host-or-passthrough-mismatch";const wantDomains=resolveRecordedMitmDomains(opts.mitmDomains);if(inst.mitmDomains.length!==wantDomains.length||inst.mitmDomains.some((d,i)=>d!==wantDomains[i]))return"mitm-domains-mismatch";const wantWindows=recordedModelMap(opts.modelWindows,process.env.BILI_LAUNCHER_MODEL_WINDOWS,parseLauncherModelWindows);if(Object.keys(inst.modelWindows).length!==Object.keys(wantWindows).length)return"model-windows-mismatch";if(!Object.keys(wantWindows).every(k2=>inst.modelWindows[k2]===wantWindows[k2]))return"model-windows-mismatch";const wantMax=recordedModelMap(opts.modelMaxOutputs,process.env.BILI_LAUNCHER_MODEL_MAX_OUTPUTS,parseLauncherModelMaxOutputs);if(Object.keys(inst.modelMaxOutputs??{}).length!==Object.keys(wantMax).length)return"model-max-outputs-mismatch";return Object.keys(wantMax).every(k2=>(inst.modelMaxOutputs??{})[k2]===wantMax[k2])?void 0:"model-max-outputs-mismatch"}function isNewerSameLaneHolder(inst,optsLane,healthVersion,ownVersion,userZone){if(userZone||optsLane===void 0||healthVersion===void 0)return false;return inst.lane===optsLane&&isVersionNewer(healthVersion,ownVersion)}function instanceCompatible(inst,opts,codeFingerprint,foreignLanes=[]){if(inst.codeFingerprint===void 0||inst.codeFingerprint!==codeFingerprint)return"code-fingerprint-mismatch";return instanceShapeMismatch(inst,opts,foreignLanes)}async function probeLiveInstances(readInstance,fetchHealthInfo,diag,isConnectable=tcpConnectable){const seen=new Map;const inst=readInstance();if(isProxyInstanceFile(inst))seen.set(inst.instanceId||inst.origin,inst);for(const live of discoverLiveInstances())seen.set(live.instanceId||live.origin,live);const checked=await Promise.all([...seen.values()].map(async c=>{if(!isPidAlive(c.pid)){diag?.(`native-attach: drop ${c.origin} (pid ${c.pid}): owner process gone`);return void 0}const health=await fetchHealthInfo(c.origin);if(!health||!health.ok){if(health===void 0&&await isConnectable(c.origin)){diag?.(`native-attach: keep ${c.origin} (pid ${c.pid}): health probe failed but TCP connect succeeded \u2014 instance is BUSY (event loop saturated), not dead (#3654/#4811)`);return{inst:c,health:void 0}}diag?.(health===void 0?`native-attach: drop ${c.origin} (pid ${c.pid}): health probe failed`:`native-attach: drop ${c.origin} (pid ${c.pid}): health probe answered but reports not-ok`);return void 0}if(health.instanceId!==void 0&&health.instanceId!==c.instanceId){diag?.(`native-attach: drop ${c.origin} (pid ${c.pid}): instance id mismatch (${c.instanceId} vs ${health.instanceId})`);return void 0}return{inst:c,health}}));return checked.filter(c=>c!==void 0)}function attachGateAllows(health,attachExternal){if(attachExternal)return true;return health?.watchdog?.armed===true}function isUserZoneInstance(inst){return inst.lane===void 0&&inst.launchToken===void 0}function gateRefusalMessage(inst,health){const reason=health.watchdog&&health.watchdog.armed===false?"it reports NO session-lifecycle watchdog (started without BILI_PARENT_PID, e.g. manual `bili start`)":"it does not report watchdog state (older bili build) \u2014 its lifecycle is unverifiable";return`bili: refusing to attach to ${inst.origin} (pid ${inst.pid}) \u2014 ${reason}. It would outlive this session and ignore config edits until killed (#1322/#1335). Starting a session-owned proxy instead; set native.attachExternal=true or BILI_NATIVE_ATTACH_EXTERNAL=1 to attach anyway.`}function attachClass(inst,lane,foreignLanes){if(lane===void 0)return 1;if(inst.lane===lane)return 0;if(inst.lane!==void 0)return 1+foreignLanes.indexOf(inst.lane);return foreignLanes.length+1}function normalizeOrigin(o){return o.trim().replace(/\/+$/,"").toLowerCase()}function pickAttachable(candidates,opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,diag,foreignLanes=[]){let best;let bestClass=Number.MAX_SAFE_INTEGER;let bestStartedAt=Number.NEGATIVE_INFINITY;for(const c of candidates){if(attachUrl&&normalizeOrigin(c.inst.origin)!==normalizeOrigin(attachUrl)){diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): not the explicit attachUrl target`);continue}let incompatible=instanceCompatible(c.inst,opts,codeFingerprint,foreignLanes);if(incompatible==="code-fingerprint-mismatch"&&c.health?.version!==void 0&&isNewerSameLaneHolder(c.inst,opts.lane,c.health.version,VERSION,isUserZoneInstance(c.inst))){const adoptedShape=instanceShapeMismatch(c.inst,opts,foreignLanes);if(adoptedShape===void 0){diag?.(`native-attach: adopt ${c.inst.origin} (pid ${c.inst.pid}): foreign bytes but self-reported v${c.health.version} is strictly NEWER than this lane's v${VERSION} \u2014 riding the newer build instead of deadlocking behind it (#4125)`);incompatible=void 0}else{diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): reports v${c.health.version} (newer) but its config shape differs (${adoptedShape}) \u2014 shape guards survive upward adoption (#4125)`);incompatible=adoptedShape}}if(incompatible!==void 0){diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): incompatible (${incompatible})`);continue}if(opts.strictPort&&c.inst.port!==opts.port){diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): port mismatch`);continue}const sameLane=opts.lane!==void 0&&c.inst.lane===opts.lane;if(!attachUrl&&!attachExternal&&attachPolicy==="own-lane"&&opts.lane!==void 0&&!sameLane&&c.health?.watchdog?.armed!==true){diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): not own lane and not an armed shared daemon (attachPolicy=own-lane)`);continue}if(c.health===void 0){if(!sameLane&&!attachExternal&&!isUserZoneInstance(c.inst)){if(!refusedLog.has(c.inst.origin)){refusedLog.add(c.inst.origin);const msg=`bili: refusing to attach to ${c.inst.origin} (pid ${c.inst.pid}) \u2014 health probe silent but TCP alive (BUSY, event loop saturated #3654) and its lifecycle is unverifiable from this lane. Starting a session-owned proxy instead; set native.attachExternal=true or BILI_NATIVE_ATTACH_EXTERNAL=1 to attach anyway.`;console.error(msg);diag?.(msg)}continue}}else if(!attachGateAllows(c.health,attachExternal)&&!isUserZoneInstance(c.inst)){if(!refusedLog.has(c.inst.origin)){refusedLog.add(c.inst.origin);console.error(gateRefusalMessage(c.inst,c.health));diag?.(gateRefusalMessage(c.inst,c.health))}continue}const cls=attachClass(c.inst,opts.lane,foreignLanes);if(cls<bestClass||cls===bestClass&&c.inst.startedAt>bestStartedAt){best=c.inst;bestClass=cls;bestStartedAt=c.inst.startedAt}}return best}async function waitForStarterInstance(readInstance,fetchHealthInfo,now,sleepImpl,opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,diag,foreignLanes=[],isConnectable=tcpConnectable){const deadline=now()+SPAWN_BUDGET_MS;const probe=async()=>pickAttachable(await probeLiveInstances(readInstance,fetchHealthInfo,diag,isConnectable),opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,diag,foreignLanes);let inst;while(now()<deadline){await sleepImpl(HEALTH_POLL_INTERVAL_MS);inst=await probe();if(inst)break;const still=readStartingMarker();if(!still||!isStartingMarkerActive(still,now()))break}return inst??await probe()}function defaultAttachDiag(debug){return msg=>{logHostEvent("info","",msg);if(debug)process.stderr.write(`${logTimestamp()} [info] [v=${VERSION}] ${msg}
319
+ `)}catch{}}init_logger();init_version();import http from"http";var PERMISSION_DENIED_SIGNATURE=/\b(?:EPERM|EACCES|EROFS|EBUSY)\b|operation not permitted|permission denied|read-only file system|readonly database/i;var BILI_DATA_PATH_SIGNATURE=/billion-context|combined-ca\.pem|index\.db|\.local[\\/](?:share|state)[\\/]/i;function classifyStartupFailure(sample){if(!PERMISSION_DENIED_SIGNATURE.test(sample)||!BILI_DATA_PATH_SIGNATURE.test(sample))return"";return"possible cause: the proxy could not write its own data files (EPERM/EACCES/read-only on the bili data dir) \u2014 most often antivirus (e.g. Windows Defender Controlled Folder Access) blocking the node runtime, a read-only flag or ACL on the directory, or another process holding the files; add the bili data dir and the node runtime to AV exclusions (see #367) or fix the directory permissions, then retry"}var MAX_HOLD_MS=10*6e4;init_update();init_win_cmd();init_client_config();init_config();init_registry();init_config();init_logger();function parseLauncherModelWindows(raw){if(!raw)return{};try{const parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return{};const out={};for(const[id,v2]of Object.entries(parsed)){if(typeof v2==="number"&&Number.isFinite(v2)&&v2>0)out[id]=Math.floor(v2)}return out}catch{return{}}}var LAUNCHER_MODEL_WINDOWS=parseLauncherModelWindows(process.env.BILI_LAUNCHER_MODEL_WINDOWS);function parseLauncherModelMaxOutputs(raw){if(!raw)return{};try{const parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return{};const out={};for(const[id,v2]of Object.entries(parsed)){if(typeof v2==="number"&&Number.isFinite(v2)&&v2>0)out[id]=Math.floor(v2)}return out}catch{return{}}}var LAUNCHER_MODEL_MAX_OUTPUTS=parseLauncherModelMaxOutputs(process.env.BILI_LAUNCHER_MODEL_MAX_OUTPUTS);init_vertex();init_client_config();init_logger();import{createHash as createHash13}from"crypto";import{createHash as createHash12,randomUUID as randomUUID4}from"crypto";import{closeSync,existsSync as existsSync6,fsyncSync,mkdirSync as mkdirSync6,openSync,readdirSync,readFileSync as readFileSync7,renameSync as renameSync2,rmSync,statSync as statSync6,writeFileSync as writeFileSync5}from"fs";import{readdir as readdir2,readFile as readFile4,rm as rm2}from"fs/promises";import*as path23 from"path";init_paths();init_knobs();init_logger();init_runtime_status();init_version();import{createCipheriv,createDecipheriv,randomBytes as randomBytes2}from"crypto";import*as zlib from"zlib";var ENCRYPT_MAGIC=Buffer.from("BILIENC1","utf8");var ZSTD_MAGIC=Buffer.from("BILIZSTD1","utf8");var NONCE_LEN=12;var TAG_LEN=16;var ENCRYPT_HEADER_LEN=ENCRYPT_MAGIC.length+2+NONCE_LEN;var MIN_ENCRYPTED_LEN=ENCRYPT_HEADER_LEN+TAG_LEN;var PLAIN_HEADER_LEN=ZSTD_MAGIC.length+2;init_logger();init_billing();init_state_hydration();init_shadow();init_logger();var HOT_ATTACH_WINDOW_MS=10*6e4;var ATTACH_SILENCE_MS=5*6e4;init_backend();init_ingest();init_store();init_logger();init_paths();import{randomUUID as randomUUID2}from"crypto";import{mkdirSync as mkdirSync5,writeFileSync as writeFileSync4}from"fs";import{dirname as dirname3,join as join2}from"path";init_knobs();import{createHash as createHash11,randomUUID as randomUUID3}from"crypto";import{AsyncLocalStorage as AsyncLocalStorage3}from"async_hooks";init_logger();import{createHash as createHash10}from"crypto";import{createHash as createHash9}from"crypto";init_logger();init_logger();init_billing();init_util();var BOOT_ID=randomUUID3();var SEAM_BODY_CAP=512*1024;var BODY_FULL_CAP=8*1024*1024;var captures=new AsyncLocalStorage3;var LEARNED_IMAGE_COST_TTL_MS=24*60*60*1e3;var{join:join4}=path23;var FROZEN_SKIP_NOTICE_COOLDOWN_MS=10*6e4;init_version();init_knobs();init_config();init_config();init_paths();init_logger();init_external_summary_settings();import*as path24 from"path";init_turn_separator();init_turn_separator();var ABORT_REANCHOR_MAX_AGE_MS=30*60*1e3;var MAX_SESSIONS=maxSessions();var MAX_RESIDENT_BYTES=sessionResidentMaxBytes();var SPLIT_CANARY_FRESH_MS=10*60*1e3;import{randomUUID as randomUUID5}from"crypto";init_knobs();var CODEX_FORGED_HANDOFF_HEADER="[bili] context summary after compaction:";var FORGED_SUMMARY_HEADER="[Compressed conversation section]";init_client_config();import fs13 from"fs";import path25 from"path";init_dsh_channel();var SCAN_CACHE_TTL_MS=5*60*1e3;var CONFLICT_ACTIVE_WINDOW_MS=7*24*60*60*1e3;var LAUNCHER_DEFAULT_HOST="127.0.0.1";var HEALTH_PATH="/__bili/health";var HEALTH_POLL_INTERVAL_MS=200;var SPAWN_WAIT_MS=envMillis(process.env,"BILI_SPAWN_WAIT_MS",2e4);var SLOW_START_GRACE_MS=envMillis(process.env,"BILI_SLOW_START_GRACE_MS",4e4);var SPAWN_BUDGET_MS=SPAWN_WAIT_MS+SLOW_START_GRACE_MS;var PROBE_TIMEOUT_MS=1500;var STARTING_MARKER_TTL_MS=SPAWN_BUDGET_MS+3e4;var POST_EXIT_REDISCOVERY_MS=3e3;var DEFAULT_MITM_DOMAIN_SET=new Set(DEFAULT_MITM_DOMAINS.map(d=>d.toLowerCase()));function proxyOrigin(host,port){return`http://${host}:${port}`}function healthUrl(origin){return origin+HEALTH_PATH}async function defaultFetch(url){const ctrl=new AbortController;const t=setTimeout(()=>ctrl.abort(),PROBE_TIMEOUT_MS);try{const res=await fetch(url,{signal:ctrl.signal});return{ok:res.ok}}catch{return{ok:false}}finally{clearTimeout(t)}}async function probeHealth(origin,fetchImpl){try{const{ok}=await fetchImpl(healthUrl(origin));return ok}catch{return false}}function describeProbeFailure(err){const e=err;const code=e?.cause?.code??e?.code;if(typeof code==="string"&&code.length>0)return code;if(e?.name==="TimeoutError"||e?.name==="AbortError")return`timeout after ${PROBE_TIMEOUT_MS}ms`;if(typeof e?.message==="string"&&e.message.length>0)return e.message.slice(0,160);return String(err)}async function defaultFetchDetail(url){const ctrl=new AbortController;const t=setTimeout(()=>ctrl.abort(),PROBE_TIMEOUT_MS);try{const res=await fetch(url,{signal:ctrl.signal});return res.ok?{ok:true}:{ok:false,detail:`HTTP ${res.status}`}}catch(err){return{ok:false,detail:describeProbeFailure(err)}}finally{clearTimeout(t)}}async function fetchHealthInfoDefault(origin,opts){try{const res=await fetch(healthUrl(origin),{signal:AbortSignal.timeout(PROBE_TIMEOUT_MS),...opts?.noKeepAlive?{headers:{connection:"close"}}:{}});if(!res.ok)return void 0;const data=await res.json();const info={ok:Boolean(data.ok),instanceId:typeof data.instanceId==="string"?data.instanceId:void 0};if(typeof data.version==="string")info.version=data.version;if(typeof data.pid==="number")info.pid=data.pid;if(typeof data.auxProxy==="string"&&data.auxProxy.length>0)info.auxProxy=data.auxProxy;if(typeof data.auxProxySource==="string"&&data.auxProxySource.length>0)info.auxProxySource=data.auxProxySource;if(data.watchdog&&typeof data.watchdog==="object"&&typeof data.watchdog.armed==="boolean"){const wd=data.watchdog;const watchers=Array.isArray(wd.watchers)?wd.watchers.filter(w2=>typeof w2==="number"):void 0;info.watchdog={armed:wd.armed,watchers}}return info}catch{return void 0}}async function registerWatcherDefault(origin,pid){try{const res=await fetch(`${origin}/__bili/watcher`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({pid}),signal:AbortSignal.timeout(2e3)});if(!res.ok){if(res.status===409)return"refused";console.error(`bili: watcher registration returned HTTP ${res.status} \u2014 the shared proxy may exit when its first owner does`);return"failed"}return"ok"}catch(err){console.error(`bili: watcher registration failed \u2014 the shared proxy may exit when its first owner does (${err instanceof Error?err.message:String(err)})`);return"failed"}}function isStartingMarkerActive(marker,nowMs){return isPidAlive(marker.pid)&&nowMs-marker.startedAt<STARTING_MARKER_TTL_MS}function recordedModelMap(passed,ambientRaw,parse3){return parse3(passed&&Object.keys(passed).length>0?JSON.stringify(passed):ambientRaw)}function instanceShapeMismatch(inst,opts,foreignLanes=[]){if(opts.lane!==void 0&&inst.lane!==void 0&&inst.lane!==opts.lane&&!foreignLanes.includes(inst.lane))return"lane-mismatch";if(inst.host!==opts.host||inst.passthrough!==resolveRecordedPassthrough(opts.passthrough))return"host-or-passthrough-mismatch";const wantDomains=resolveRecordedMitmDomains(opts.mitmDomains);if(inst.mitmDomains.length!==wantDomains.length||inst.mitmDomains.some((d,i)=>d!==wantDomains[i]))return"mitm-domains-mismatch";const wantWindows=recordedModelMap(opts.modelWindows,process.env.BILI_LAUNCHER_MODEL_WINDOWS,parseLauncherModelWindows);if(Object.keys(inst.modelWindows).length!==Object.keys(wantWindows).length)return"model-windows-mismatch";if(!Object.keys(wantWindows).every(k2=>inst.modelWindows[k2]===wantWindows[k2]))return"model-windows-mismatch";const wantMax=recordedModelMap(opts.modelMaxOutputs,process.env.BILI_LAUNCHER_MODEL_MAX_OUTPUTS,parseLauncherModelMaxOutputs);if(Object.keys(inst.modelMaxOutputs??{}).length!==Object.keys(wantMax).length)return"model-max-outputs-mismatch";return Object.keys(wantMax).every(k2=>(inst.modelMaxOutputs??{})[k2]===wantMax[k2])?void 0:"model-max-outputs-mismatch"}function isNewerSameLaneHolder(inst,optsLane,healthVersion,ownVersion,userZone){if(userZone||optsLane===void 0||healthVersion===void 0)return false;return inst.lane===optsLane&&isVersionNewer(healthVersion,ownVersion)}function instanceCompatible(inst,opts,codeFingerprint,foreignLanes=[]){if(inst.codeFingerprint===void 0||inst.codeFingerprint!==codeFingerprint)return"code-fingerprint-mismatch";return instanceShapeMismatch(inst,opts,foreignLanes)}async function probeLiveInstances(readInstance,fetchHealthInfo,diag,isConnectable=tcpConnectable){const seen=new Map;const inst=readInstance();if(isProxyInstanceFile(inst))seen.set(inst.instanceId||inst.origin,inst);for(const live of discoverLiveInstances())seen.set(live.instanceId||live.origin,live);const checked=await Promise.all([...seen.values()].map(async c=>{if(!isPidAlive(c.pid)){diag?.(`native-attach: drop ${c.origin} (pid ${c.pid}): owner process gone`);return void 0}const health=await fetchHealthInfo(c.origin);if(!health||!health.ok){if(health===void 0&&await isConnectable(c.origin)){diag?.(`native-attach: keep ${c.origin} (pid ${c.pid}): health probe failed but TCP connect succeeded \u2014 instance is BUSY (event loop saturated), not dead (#3654/#4811)`);return{inst:c,health:void 0}}diag?.(health===void 0?`native-attach: drop ${c.origin} (pid ${c.pid}): health probe failed`:`native-attach: drop ${c.origin} (pid ${c.pid}): health probe answered but reports not-ok`);return void 0}if(health.instanceId!==void 0&&health.instanceId!==c.instanceId){diag?.(`native-attach: drop ${c.origin} (pid ${c.pid}): instance id mismatch (${c.instanceId} vs ${health.instanceId})`);return void 0}return{inst:c,health}}));return checked.filter(c=>c!==void 0)}function attachGateAllows(health,attachExternal){if(attachExternal)return true;return health?.watchdog?.armed===true}function isUserZoneInstance(inst){return inst.lane===void 0&&inst.launchToken===void 0}function gateRefusalMessage(inst,health){const reason=health.watchdog&&health.watchdog.armed===false?"it reports NO session-lifecycle watchdog (started without BILI_PARENT_PID, e.g. manual `bili start`)":"it does not report watchdog state (older bili build) \u2014 its lifecycle is unverifiable";return`bili: refusing to attach to ${inst.origin} (pid ${inst.pid}) \u2014 ${reason}. It would outlive this session and ignore config edits until killed (#1322/#1335). Starting a session-owned proxy instead; set native.attachExternal=true or BILI_NATIVE_ATTACH_EXTERNAL=1 to attach anyway.`}function attachClass(inst,lane,foreignLanes){if(lane===void 0)return 1;if(inst.lane===lane)return 0;if(inst.lane!==void 0)return 1+foreignLanes.indexOf(inst.lane);return foreignLanes.length+1}function normalizeOrigin(o){return o.trim().replace(/\/+$/,"").toLowerCase()}function pickAttachable(candidates,opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,diag,foreignLanes=[]){let best;let bestClass=Number.MAX_SAFE_INTEGER;let bestStartedAt=Number.NEGATIVE_INFINITY;for(const c of candidates){if(attachUrl&&normalizeOrigin(c.inst.origin)!==normalizeOrigin(attachUrl)){diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): not the explicit attachUrl target`);continue}let incompatible=instanceCompatible(c.inst,opts,codeFingerprint,foreignLanes);if(incompatible==="code-fingerprint-mismatch"&&c.health?.version!==void 0&&isNewerSameLaneHolder(c.inst,opts.lane,c.health.version,VERSION,isUserZoneInstance(c.inst))){const adoptedShape=instanceShapeMismatch(c.inst,opts,foreignLanes);if(adoptedShape===void 0){diag?.(`native-attach: adopt ${c.inst.origin} (pid ${c.inst.pid}): foreign bytes but self-reported v${c.health.version} is strictly NEWER than this lane's v${VERSION} \u2014 riding the newer build instead of deadlocking behind it (#4125)`);incompatible=void 0}else{diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): reports v${c.health.version} (newer) but its config shape differs (${adoptedShape}) \u2014 shape guards survive upward adoption (#4125)`);incompatible=adoptedShape}}if(incompatible!==void 0){diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): incompatible (${incompatible})`);continue}if(opts.strictPort&&c.inst.port!==opts.port){diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): port mismatch`);continue}const sameLane=opts.lane!==void 0&&c.inst.lane===opts.lane;if(!attachUrl&&!attachExternal&&attachPolicy==="own-lane"&&opts.lane!==void 0&&!sameLane&&c.health?.watchdog?.armed!==true){diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): not own lane and not an armed shared daemon (attachPolicy=own-lane)`);continue}if(c.health===void 0){if(!sameLane&&!attachExternal&&!isUserZoneInstance(c.inst)){if(!refusedLog.has(c.inst.origin)){refusedLog.add(c.inst.origin);const msg=`bili: refusing to attach to ${c.inst.origin} (pid ${c.inst.pid}) \u2014 health probe silent but TCP alive (BUSY, event loop saturated #3654) and its lifecycle is unverifiable from this lane. Starting a session-owned proxy instead; set native.attachExternal=true or BILI_NATIVE_ATTACH_EXTERNAL=1 to attach anyway.`;console.error(msg);diag?.(msg)}continue}}else if(!attachGateAllows(c.health,attachExternal)&&!isUserZoneInstance(c.inst)){if(!refusedLog.has(c.inst.origin)){refusedLog.add(c.inst.origin);console.error(gateRefusalMessage(c.inst,c.health));diag?.(gateRefusalMessage(c.inst,c.health))}continue}const cls=attachClass(c.inst,opts.lane,foreignLanes);if(cls<bestClass||cls===bestClass&&c.inst.startedAt>bestStartedAt){best=c.inst;bestClass=cls;bestStartedAt=c.inst.startedAt}}return best}async function waitForStarterInstance(readInstance,fetchHealthInfo,now,sleepImpl,opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,diag,foreignLanes=[],isConnectable=tcpConnectable){const deadline=now()+SPAWN_BUDGET_MS;const probe=async()=>pickAttachable(await probeLiveInstances(readInstance,fetchHealthInfo,diag,isConnectable),opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,diag,foreignLanes);let inst;while(now()<deadline){await sleepImpl(HEALTH_POLL_INTERVAL_MS);inst=await probe();if(inst)break;const still=readStartingMarker();if(!still||!isStartingMarkerActive(still,now()))break}return inst??await probe()}function defaultAttachDiag(debug){return msg=>{logHostEvent("info","",msg);if(debug)process.stderr.write(`${logTimestamp()} [info] [v=${VERSION}] ${msg}
320
320
  `)}}function pickEphemeralPort(host=LAUNCHER_DEFAULT_HOST){return new Promise((resolve,reject)=>{const srv=net3.createServer();srv.once("error",reject);srv.listen(0,host,()=>{const addr=srv.address();srv.close(()=>{if(addr&&typeof addr==="object")resolve(addr.port);else reject(new Error("could not allocate a free port"))})})})}var INHERITED_PROXY_VARS=["http_proxy","https_proxy","all_proxy","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","no_proxy","NO_PROXY"];var INTERNAL_LAUNCHER_CHANNEL_VARS=["BILI_LAUNCHER_LANE","BILI_LAUNCHER_MODEL_WINDOWS","BILI_LAUNCHER_MODEL_MAX_OUTPUTS","BILI_STRICT_PORT"];function stripInternalLauncherChannels(env){const cleaned={...env};for(const key of INTERNAL_LAUNCHER_CHANNEL_VARS)delete cleaned[key];return cleaned}function stripInheritedProxy(env){const cleaned={...env};for(const key of INHERITED_PROXY_VARS)delete cleaned[key];return stripInternalLauncherChannels(cleaned)}var INHERITED_LAUNCHER_CHANNELS=["BILI_LAUNCHER_LANE","BILI_LAUNCHER_MODEL_WINDOWS","BILI_LAUNCHER_MODEL_MAX_OUTPUTS","BILI_STRICT_PORT",SPAWN_FINGERPRINT_ENV];function stripInheritedLauncherChannels(env){const cleaned={...env};for(const key of INHERITED_LAUNCHER_CHANNELS)delete cleaned[key];return cleaned}function captureInheritedProxyEnv(env){const captured={};const pairs=[["BILI_INHERITED_HTTP_PROXY",env.HTTP_PROXY,env.http_proxy],["BILI_INHERITED_HTTPS_PROXY",env.HTTPS_PROXY,env.https_proxy],["BILI_INHERITED_ALL_PROXY",env.ALL_PROXY,env.all_proxy],["BILI_INHERITED_NO_PROXY",env.NO_PROXY,env.no_proxy]];for(const[name,upper,lower]of pairs){const value=(upper??lower??"").trim();if(value)captured[name]=value}return captured}function proxyStartArgs(opts){const args=["start","--host",opts.host,"--port",String(opts.port)];if(opts.passthrough)args.push("--passthrough");if(opts.debug)args.push("--debug");return args}function probeNodeWrapperTarget(candidate,env){try{const out=execFileSync5(candidate,["-p","process.execPath"],{windowsHide:true,timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","pipe"],env});const p2=out.trim();return p2.length>0?p2:void 0}catch{return void 0}}function probeNodeMajor(candidate,env){try{const out=execFileSync5(candidate,["--version"],{windowsHide:true,timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","pipe"],env});const m2=/^v(\d+)\.\d+\.\d+/.exec(out.trim());return m2?Number(m2[1]):void 0}catch{return void 0}}var MIN_PROXY_NODE_MAJOR=20;function looksLikeNodeExecutable(p2,platform){if(platform==="win32"){if(!/^[a-zA-Z]:[\\/]/.test(p2))return false}else if(!p2.startsWith("/")){return false}const base=p2.split(/[\\/]/).pop()?.toLowerCase()??"";return base==="node"||base==="node.exe"}function resolveNodeRuntime(execPath=process.execPath,env=process.env,platform=process.platform,existsImpl=fs14.existsSync,electronVersion=typeof process.versions.electron==="string"?process.versions.electron:void 0,probeWrapper=probeNodeWrapperTarget,probeNode=probeNodeMajor){const base=path26.basename(execPath).toLowerCase();if(base==="node"||base==="node.exe")return execPath;const override=typeof env.BILLION_CONTEXT_NODE==="string"?env.BILLION_CONTEXT_NODE.trim():"";if(override.length>0&&existsImpl(override))return override;const resolveDiscovered=candidate=>{let subject=candidate;if(platform==="win32"){const probed=probeWrapper(candidate,env);const target=probed?.trim();if(target&&target.length>0&&looksLikeNodeExecutable(target,platform)&&existsImpl(target)){if(target.toLowerCase()!==candidate.toLowerCase()){log("info",`bili: ${candidate} is a Windows node wrapper resolving to ${target} \u2014 spawning the real Node directly (#1887)`);subject=target}}}const major=probeNode(subject,env);if(major===void 0||major<MIN_PROXY_NODE_MAJOR)return void 0;return subject};const sep=platform==="win32"?";":":";const names=platform==="win32"?["node.exe"]:["node"];const home=platform==="win32"?env.USERPROFILE??"":env.HOME??"";const voltaHome=platform==="win32"?env.VOLTA_HOME??(home?home+"/Tools/volta":""):home?home+"/.volta":"";const extraDirs=platform==="win32"?["C:/Program Files/nodejs",env.LOCALAPPDATA?env.LOCALAPPDATA+"/Programs/nodejs":"",voltaHome?voltaHome+"/bin":""]:["/usr/local/bin","/opt/homebrew/bin","/opt/local/bin",voltaHome?voltaHome+"/bin":"",home?home+"/.local/bin":""];for(const dir of[...(env.PATH??"").split(sep),...extraDirs]){if(!dir)continue;for(const name of names){const candidate=dir.endsWith("/")||dir.endsWith("\\")?dir+name:dir+"/"+name;if(!existsImpl(candidate))continue;const resolved=resolveDiscovered(candidate);if(resolved!==void 0)return resolved;log("warn",`bili: skipping ${candidate} \u2014 not a usable Node runtime (--version did not report v${MIN_PROXY_NODE_MAJOR}+; set BILLION_CONTEXT_NODE if this is wrong, #3383)`)}}if(electronVersion&&electronVersion.length>0){log("warn",`bili: no usable Node runtime found on PATH or install dirs \u2014 falling back to the Electron host binary ${execPath} run as Node via ELECTRON_RUN_AS_NODE=1 (#1429/#3383)`);return execPath}throw new Error("bili: cannot find a Node runtime to spawn the proxy (this process is not Node) \u2014 set BILLION_CONTEXT_NODE")}var PORT_LOG_MAX_BYTES=5*1024*1024;function rotatePortLogIfNeeded(logPath2){try{if(fs14.statSync(logPath2).size<PORT_LOG_MAX_BYTES)return;try{fs14.unlinkSync(`${logPath2}.old`)}catch{}fs14.renameSync(logPath2,`${logPath2}.old`)}catch{}}var STALE_ROTATION_WAIT_MS=12e3;var SHUTDOWN_REQUEST_TIMEOUT_MS=3e3;var OWNER_HEARTBEAT_INTERVAL_MS=5e3;var OWNER_HEARTBEAT_POST_TIMEOUT_MS=2e3;async function requestInstanceShutdown(origin){try{const res=await fetch(`${origin}/__bili/shutdown`,{method:"POST",headers:{"content-type":"application/json",connection:"close"},body:"{}",signal:AbortSignal.timeout(SHUTDOWN_REQUEST_TIMEOUT_MS)});return res.ok}catch{return false}}async function rotateStalePredecessor(probed,resolveTargetPort,opts,attachUrl,foreignLanes,fetchHealthInfoNoReuse,now,sleep,requestShutdown){if(attachUrl!==void 0)return;const stale=probed.filter(c=>c.health!==void 0&&!isUserZoneInstance(c.inst)&&c.health.watchdog?.armed===true&&instanceShapeMismatch(c.inst,opts,foreignLanes)===void 0&&c.health.version!==void 0&&isVersionNewer(VERSION,c.health.version));if(stale.length===0)return;const targetPort=resolveTargetPort();if(targetPort===void 0)return;const candidate=stale.find(c=>c.inst.port===targetPort);if(!candidate)return;const running=candidate.health.version;if(running===void 0||!isVersionNewer(VERSION,running))return;console.error(`bili: rotating stale proxy ${candidate.inst.origin} (pid ${candidate.inst.pid}, running v${running}) \u2014 ours is v${VERSION}; requesting graceful shutdown before taking over port ${targetPort}`);const asked=await requestShutdown(candidate.inst.origin);if(!asked){console.error(`bili: stale rotation skipped \u2014 ${candidate.inst.origin} refused /__bili/shutdown (older build); falling back to the normal spawn ladder`);return}const deadline=now()+STALE_ROTATION_WAIT_MS;for(;;){const h=await fetchHealthInfoNoReuse(candidate.inst.origin);if(!h?.ok)break;if(now()>=deadline){console.error(`bili: stale rotation timed out after ${STALE_ROTATION_WAIT_MS}ms \u2014 ${candidate.inst.origin} still accepts fresh connections (listener open); falling back to the normal spawn ladder`);return}await sleep(HEALTH_POLL_INTERVAL_MS)}}function startOwnerHeartbeat(origin,pid,intervalMs=OWNER_HEARTBEAT_INTERVAL_MS,post){if(pid!==process.pid)return void 0;if(post!==void 0)return runOwnerHeartbeatLoop(post,pid,intervalMs);return runOwnerHeartbeatWorker(origin,pid,intervalMs)}var ownerHeartbeatWorkers=new Map;function runOwnerHeartbeatLoop(post,pid,intervalMs){let stopped=false;const beat=async()=>{while(!stopped){await new Promise(r=>{const t=setTimeout(r,intervalMs);t.unref?.()});if(stopped)return;try{await post(JSON.stringify({pid,hb:true}))}catch{}}};void beat();return()=>{stopped=true}}var OWNER_HEARTBEAT_WORKER_SOURCE=`
321
321
  const { parentPort, workerData } = require("node:worker_threads");
322
322
  const { origin, pid, intervalMs, timeoutMs } = workerData;