billion-context 0.1.215 → 0.1.216
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +2 -2
- package/README.md +2 -2
- package/README.zh-CN.md +2 -2
- package/dist/agent/dsh-native.js +4 -4
- package/dist/agent/omp-native.js +15 -12
- package/dist/agent/omp.js +14 -11
- package/dist/agent/opencode-native.js +411 -40
- package/dist/agent/opencode.js +2 -2
- package/dist/agent/pi-native.js +423 -49
- package/dist/agent/pi.js +14 -11
- package/dist/build-info.json +1 -1
- package/dist/claude-mcp-entry.js +1 -1
- package/dist/claude-native-bootstrap.js +1 -1
- package/dist/index.js +414 -43
- package/dist/kimi/bootstrap-hook.js +1 -1
- package/dist/kimi/native-mcp.js +1 -1
- package/dist/zcode/bootstrap-hook.js +1 -1
- package/dist/zcode/mcp-entry.js +1 -1
- package/docs/configuration.md +1 -0
- package/docs/configuration.zh-CN.md +1 -0
- package/hermes-plugin/__init__.py +32 -8
- package/hermes-plugin/plugin.yaml +9 -0
- package/package.json +2 -1
package/dist/agent/opencode.js
CHANGED
|
@@ -319,7 +319,7 @@ ${partialOutcomeNote(blocksCreated)}`;const out={text,failed:outcome==="failure"
|
|
|
319
319
|
[${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")+`
|
|
320
320
|
|
|
321
321
|
[${kind} truncated] ${dropped} more line${dropped===1?"":"s"}`;return desc.length<=max?desc:desc.slice(0,max)}init_toml_integer();init_client_config();import fs10 from"fs";import path18 from"path";import crypto3 from"crypto";import fs11 from"fs";import path19 from"path";init_instance();init_config();init_log_mask();init_logger();init_paths();init_version();import{appendFileSync,mkdirSync as mkdirSync4}from"fs";import path21 from"path";function logHostEvent(level,origin,msg){try{const file=defaultLogFile();mkdirSync4(path21.dirname(file),{recursive:true});const safe=maskUrlsForDiagnostics(maskIpsInText(redactSecretsInText(msg)));appendFileSync(file,`${logTimestamp()} [${level}] [v=${VERSION}] ${origin?`${origin} `:""}${safe}
|
|
322
|
-
`)}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();var KIRO_COMPAT_ROLES=Object.freeze({developer:"user",system:"user"});init_logger();import{createHash as createHash13}from"crypto";import{createHash as createHash12,randomUUID as randomUUID5}from"crypto";import{closeSync as closeSync5,existsSync as existsSync8,fsyncSync as fsyncSync2,mkdirSync as mkdirSync7,openSync as openSync5,readdirSync as readdirSync3,readFileSync as readFileSync7,renameSync as renameSync3,rmSync,statSync as statSync9,unlinkSync as unlinkSync3,writeFileSync as writeFileSync5}from"fs";import{readdir as readdir2,readFile as readFile5,rm as rm2}from"fs/promises";import*as path24 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 randomUUID3}from"crypto";import{mkdirSync as mkdirSync6,writeFileSync as writeFileSync4}from"fs";import{dirname as dirname4,join as join2}from"path";init_knobs();import{createHash as createHash11,randomUUID as randomUUID4}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=randomUUID4();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}=path24;var FROZEN_SKIP_NOTICE_COOLDOWN_MS=10*6e4;var _store=null;function kvStore(){try{const s3=_store;if(!s3||s3.liveStorageStamp==="legacy")return null;if(typeof s3.getKvAsync!=="function"||typeof s3.setKvAsync!=="function"||typeof s3.listKvAsync!=="function")return null;return s3}catch{return null}}init_version();init_knobs();init_config();init_config();init_paths();init_logger();init_external_summary_settings();import*as path25 from"path";init_external_summary_settings();init_private_host();init_knobs();init_turn_separator();init_turn_separator();var ABORT_REANCHOR_MAX_AGE_MS=30*60*1e3;var TRUNCATED_UPSTREAM_MAX_AGE_MS=5*60*1e3;var MAX_SESSIONS=maxSessions();var MAX_RESIDENT_BYTES=sessionResidentMaxBytes();var COLD_LOAD_EVICT_GRACE_MS=10*6e4;var SPLIT_CANARY_FRESH_MS=10*60*1e3;import{createHash as createHash14,randomUUID as randomUUID6}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 path26 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}}function formatWatcherError(err){const head=err instanceof Error?(err.name!=="Error"?`${err.name}: `:"")+err.message:String(err);let detail=head;let cur=err instanceof Error?err.cause:void 0;for(let i=0;i<3&&cur!==void 0&&cur!==null;i++){const c=cur;if(typeof c.code==="string"||typeof c.code==="number"){detail+=` [cause: ${c.code}]`;return detail}if(typeof c.message==="string"&&c.message.trim()!==""){detail+=` [cause: ${c.message}]`;return detail}cur=c.cause}return detail}async function registerWatcherDefault(origin,pid){const tail=pid===process.pid?"a later heartbeat will re-register us and report recovery":"no heartbeat runs for a foreign owner pid \u2014 registration stays unconfirmed unless a retry succeeds";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 at ${origin} (owner pid ${pid}) returned HTTP ${res.status} \u2014 the shared proxy may exit when its first owner does; ${tail}`);return"failed"}return"ok"}catch(err){console.error(`bili: watcher registration at ${origin} (owner pid ${pid}) failed \u2014 the shared proxy may exit when its first owner does (${formatWatcherError(err)}); ${tail}`);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}
|
|
322
|
+
`)}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();var KIRO_COMPAT_ROLES=Object.freeze({developer:"user",system:"user"});init_logger();import{createHash as createHash13}from"crypto";import{createHash as createHash12,randomUUID as randomUUID5}from"crypto";import{closeSync as closeSync5,existsSync as existsSync8,fsyncSync as fsyncSync2,mkdirSync as mkdirSync7,openSync as openSync5,readdirSync as readdirSync3,readFileSync as readFileSync7,renameSync as renameSync3,rmSync,statSync as statSync9,unlinkSync as unlinkSync3,writeFileSync as writeFileSync5}from"fs";import{readdir as readdir2,readFile as readFile5,rm as rm2}from"fs/promises";import*as path24 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 randomUUID3}from"crypto";import{mkdirSync as mkdirSync6,writeFileSync as writeFileSync4}from"fs";import{dirname as dirname4,join as join2}from"path";init_knobs();import{createHash as createHash11,randomUUID as randomUUID4}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=randomUUID4();var RECOVERY_BURST_MS=10*6e4;var RECOVERY_STALE_MS=30*6e4;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}=path24;var FROZEN_SKIP_NOTICE_COOLDOWN_MS=10*6e4;var _store=null;function kvStore(){try{const s3=_store;if(!s3||s3.liveStorageStamp==="legacy")return null;if(typeof s3.getKvAsync!=="function"||typeof s3.setKvAsync!=="function"||typeof s3.listKvAsync!=="function")return null;return s3}catch{return null}}init_version();init_knobs();init_config();init_config();init_paths();init_logger();init_external_summary_settings();import*as path25 from"path";init_external_summary_settings();init_private_host();init_knobs();init_turn_separator();init_turn_separator();var ABORT_REANCHOR_MAX_AGE_MS=30*60*1e3;var TRUNCATED_UPSTREAM_MAX_AGE_MS=5*60*1e3;var MAX_SESSIONS=maxSessions();var MAX_RESIDENT_BYTES=sessionResidentMaxBytes();var COLD_LOAD_EVICT_GRACE_MS=10*6e4;var SPLIT_CANARY_FRESH_MS=10*60*1e3;import{createHash as createHash14,randomUUID as randomUUID6}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 path26 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}}function formatWatcherError(err){const head=err instanceof Error?(err.name!=="Error"?`${err.name}: `:"")+err.message:String(err);let detail=head;let cur=err instanceof Error?err.cause:void 0;for(let i=0;i<3&&cur!==void 0&&cur!==null;i++){const c=cur;if(typeof c.code==="string"||typeof c.code==="number"){detail+=` [cause: ${c.code}]`;return detail}if(typeof c.message==="string"&&c.message.trim()!==""){detail+=` [cause: ${c.message}]`;return detail}cur=c.cause}return detail}async function registerWatcherDefault(origin,pid){const tail=pid===process.pid?"a later heartbeat will re-register us and report recovery":"no heartbeat runs for a foreign owner pid \u2014 registration stays unconfirmed unless a retry succeeds";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 at ${origin} (owner pid ${pid}) returned HTTP ${res.status} \u2014 the shared proxy may exit when its first owner does; ${tail}`);return"failed"}return"ok"}catch(err){console.error(`bili: watcher registration at ${origin} (owner pid ${pid}) failed \u2014 the shared proxy may exit when its first owner does (${formatWatcherError(err)}); ${tail}`);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}
|
|
323
323
|
`)}}function pickEphemeralPort(host=LAUNCHER_DEFAULT_HOST){return new Promise((resolve2,reject)=>{const srv=net3.createServer();srv.once("error",reject);srv.listen(0,host,()=>{const addr=srv.address();srv.close(()=>{if(addr&&typeof addr==="object")resolve2(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}}function probeNodeIdentity(candidate,env){try{const out=execFileSync5(candidate,["-e","process.stdout.write(JSON.stringify({ p: process.execPath, e: process.versions.electron || null }))"],{windowsHide:true,timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","pipe"],env});const parsed=JSON.parse(out.trim());if(typeof parsed.p!=="string"||parsed.p.length===0)return void 0;return{execPath:parsed.p,electron:typeof parsed.e==="string"?parsed.e: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,probeIdentity=probeNodeIdentity){const base=path27.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){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)`);return void 0}const identity=probeIdentity(subject,env);if(identity?.electron&&identity.execPath.toLowerCase()!==execPath.toLowerCase()){log("warn",`bili: skipping ${candidate} \u2014 reports v${major}.x but is an Electron-as-node process of ${identity.execPath} (Electron ${identity.electron}), a different application than this host (${execPath}); such a daemon loses macOS Local Network authorization (instant EHOSTUNREACH to LAN upstreams) \u2014 set BILLION_CONTEXT_NODE to a real Node (#5663)`);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){log("info",`bili: proxy runtime resolved: ${resolved}${resolved.toLowerCase()!==candidate.toLowerCase()?` (via wrapper ${candidate})`:""}`);return resolved}}}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;var WATCHER_REG_ATTEMPTS=3;var WATCHER_REG_RETRY_BACKOFF_MS=500;async function requestInstanceShutdown(origin,timeoutMs=SHUTDOWN_REQUEST_TIMEOUT_MS){try{const res=await fetch(`${origin}/__bili/shutdown`,{method:"POST",headers:{"content-type":"application/json",connection:"close"},body:"{}",signal:AbortSignal.timeout(timeoutMs)});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)}}var WEDGED_TAKEOVER_WINDOW_MS=6e5;var WEDGED_MIN_OBSERVATIONS=3;var WEDGED_OBSERVATION_STALE_MS=3e5;var WEDGED_SHUTDOWN_BUDGET_MS=1e3;var WEDGED_POST_SHUTDOWN_WAIT_MS=2e3;var WEDGED_TERM_GRACE_MS=1e3;var WEDGED_POST_KILL_WAIT_MS=2e3;var WEDGED_POST_KILL_SETTLE_MS=2e3;function wedgedLedgerFilePath(){return path27.join(stateDir(),"wedged-takeover.json")}function isWedgedLedgerEntry(value){if(typeof value!=="object"||value===null)return false;const e=value;return typeof e.pid==="number"&&Number.isInteger(e.pid)&&e.pid>0&&typeof e.firstBusyAt==="number"&&Number.isFinite(e.firstBusyAt)&&typeof e.lastObservedAt==="number"&&Number.isFinite(e.lastObservedAt)&&typeof e.observations==="number"&&Number.isInteger(e.observations)&&e.observations>=1}function readWedgedLedger(file){let raw;try{raw=fs14.readFileSync(file,"utf8")}catch(error){if(error?.code!=="ENOENT"){log("warn",`bili: cannot read wedged-takeover ledger at ${file}: ${String(error)} \u2014 starting fresh, patience window restarts (#5955)`)}return{}}const entries={};let unparseable=false;let dropped=0;try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||!("entries"in parsed))throw new Error("missing entries");for(const[key,value]of Object.entries(parsed.entries)){if(isWedgedLedgerEntry(value))entries[key]=value;else dropped+=1}}catch{unparseable=true}if(unparseable||dropped>0){log("warn",`bili: wedged-takeover ledger at ${file} is ${unparseable?"unparseable":`malformed (${dropped} bad entr${dropped===1?"y":"ies"})`} \u2014 starting fresh, patience window restarts (#5955)`)}return entries}function writeWedgedLedger(file,entries){try{atomicWriteJson({entries},file)}catch(error){log("warn",`bili: failed to persist wedged-takeover ledger at ${file}: ${String(error)} \u2014 observation not saved, patience window may extend by one cycle (#5955)`)}}function runCommandCapture(command,args,timeoutMs){return new Promise((resolve2,reject)=>{execFile4(command,[...args],{timeout:timeoutMs,windowsHide:true},(error,stdout)=>{if(error!==null)reject(error instanceof Error?error:new Error(String(error)));else resolve2(String(stdout))})})}async function processBirthStamp(pid){if(!Number.isInteger(pid)||pid<=0)return void 0;try{if(process.platform==="linux"){const raw=fs14.readFileSync(`/proc/${pid}/stat`,"utf8");const closeParen=raw.lastIndexOf(")");if(closeParen<0)return void 0;const fields=raw.slice(closeParen+1).trim().split(/\s+/);const starttime=fields[19];if(starttime!==void 0&&/^\d+$/.test(starttime))return`boot-${starttime}`;return void 0}if(process.platform==="win32"){const out2=await runCommandCapture("powershell",["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToString('o')`],1e4);const trimmed2=out2.trim();return trimmed2===""?void 0:`ps-${trimmed2}`}const out=await runCommandCapture("ps",["-o","lstart=","-p",String(pid)],2e3);const trimmed=out.trim();return trimmed===""?void 0:`ps-${trimmed}`}catch{return void 0}}function isWedgedSameLaneCandidate(c,opts,targetPort,codeFingerprint,foreignLanes){if(c.inst.port!==targetPort)return false;if(opts.lane===void 0||c.inst.lane!==opts.lane)return false;if(isUserZoneInstance(c.inst))return false;if(c.health!==void 0)return false;return instanceCompatible(c.inst,opts,codeFingerprint,foreignLanes)==="code-fingerprint-mismatch"}function stepWedgedLedger(existing,pid,nowMs){const fresh=existing===void 0||nowMs-existing.lastObservedAt>WEDGED_OBSERVATION_STALE_MS;const entry=fresh?{pid,firstBusyAt:nowMs,lastObservedAt:nowMs,observations:1}:{pid,firstBusyAt:existing.firstBusyAt,lastObservedAt:nowMs,observations:existing.observations+1};const escalate=nowMs-entry.firstBusyAt>=WEDGED_TAKEOVER_WINDOW_MS&&entry.observations>=WEDGED_MIN_OBSERVATIONS;return{entry,escalate,fresh}}async function waitForListenerClose(origin,isConnectable,now,sleep,budgetMs){const deadline=now()+budgetMs;for(;;){if(!await isConnectable(origin))return true;if(now()>=deadline)return false;await sleep(HEALTH_POLL_INTERVAL_MS)}}async function resolveWedgedSameLaneHolder(probed,resolveTargetPort,opts,attachUrl,foreignLanes,codeFingerprint,ledgerPath,birthStamp,now,sleep,requestShutdown,isConnectable,signalHolder,hardKillHolder,diag){if(attachUrl!==void 0)return;const maybeWedged=probed.some(c=>c.health===void 0&&opts.lane!==void 0&&c.inst.lane===opts.lane&&!isUserZoneInstance(c.inst)&&instanceCompatible(c.inst,opts,codeFingerprint,foreignLanes)==="code-fingerprint-mismatch");if(!maybeWedged)return;const targetPort=resolveTargetPort();if(targetPort===void 0)return;const entries=readWedgedLedger(ledgerPath);for(const[key,entry]of Object.entries(entries)){if(!isPidAlive(entry.pid))delete entries[key]}let dirty=false;const persist=()=>{if(!dirty)return;dirty=false;if(Object.keys(entries).length===0){try{fs14.unlinkSync(ledgerPath)}catch{}return}writeWedgedLedger(ledgerPath,entries)};for(const c of probed){if(!isWedgedSameLaneCandidate(c,opts,targetPort,codeFingerprint,foreignLanes))continue;const stamp=await birthStamp(c.inst.pid);const key=stamp!==void 0?`${c.inst.origin}#${c.inst.pid}#${stamp}`:`${c.inst.origin}#${c.inst.pid}`;const{entry,escalate,fresh}=stepWedgedLedger(entries[key],c.inst.pid,now());entries[key]=entry;dirty=true;if(fresh){const startMsg=`native-attach: ${c.inst.origin} (pid ${c.inst.pid}) unresponsive \u2014 TCP alive but health silent on port ${targetPort}; patience window started, forced takeover after ${WEDGED_TAKEOVER_WINDOW_MS/1e3}s of continuous observations (#5955)`;console.error(startMsg);log("warn",startMsg);diag(startMsg)}else if(!escalate){diag(`native-attach: watching ${c.inst.origin} (pid ${c.inst.pid}): BUSY same-lane holder with foreign bytes holds port ${targetPort} \u2014 observation ${entry.observations}, ${Math.round((now()-entry.firstBusyAt)/1e3)}s of ${WEDGED_TAKEOVER_WINDOW_MS/1e3}s patience before forced takeover (#5955)`)}if(!escalate){persist();continue}const msg=`native-attach: forcing takeover of wedged same-lane proxy ${c.inst.origin} (pid ${c.inst.pid}): BUSY (TCP alive, health silent) for ${Math.round((now()-entry.firstBusyAt)/1e3)}s across ${entry.observations} bring-up cycles while holding port ${targetPort} with foreign bytes \u2014 requesting graceful shutdown, then terminating (#5955)`;console.error(msg);log("warn",msg);const t0=now();await requestShutdown(c.inst.origin,WEDGED_SHUTDOWN_BUDGET_MS);let released=await waitForListenerClose(c.inst.origin,isConnectable,now,sleep,WEDGED_POST_SHUTDOWN_WAIT_MS);let killedHard=false;if(!released){signalHolder(c.inst.pid);released=await waitForListenerClose(c.inst.origin,isConnectable,now,sleep,WEDGED_TERM_GRACE_MS)}if(!released){hardKillHolder(c.inst.pid);killedHard=true;released=await waitForListenerClose(c.inst.origin,isConnectable,now,sleep,WEDGED_POST_KILL_WAIT_MS)}if(released){if(killedHard){await sleep(WEDGED_POST_KILL_SETTLE_MS)}delete entries[key];dirty=true;const done=`native-attach: wedged holder pid ${c.inst.pid} released port ${targetPort} after ${now()-t0}ms \u2014 continuing to spawn`;console.error(done);log("info",done)}else{const failed=`native-attach: FAILED to release port ${targetPort} from wedged holder pid ${c.inst.pid} \u2014 falling back to the normal spawn ladder (may ladder to the next free port); takeover retries on the next bring-up (#5955)`;console.error(failed);log("warn",failed)}persist();return}persist()}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,origin);return runOwnerHeartbeatWorker(origin,pid,intervalMs)}var ownerHeartbeatWorkers=new Map;var watcherPendingRecovery=new Map;function markWatcherPendingRecovery(origin,pid,diag){watcherPendingRecovery.set(origin,{pid,diag})}function noteWatcherHeartbeatAck(origin){const pending=watcherPendingRecovery.get(origin);if(pending===void 0)return;watcherPendingRecovery.delete(origin);pending.diag(`bili: watcher registration recovered at ${origin} (owner pid ${pending.pid}) \u2014 the shared proxy's watchdog now tracks this owner again; the earlier "may exit when its first owner does" warning is cleared`)}function runOwnerHeartbeatLoop(post,pid,intervalMs,origin){let stopped=false;const beat=async()=>{while(!stopped){await new Promise(r=>{const t=setTimeout(r,intervalMs);t.unref?.()});if(stopped)return;try{const result=await post(JSON.stringify({pid,hb:true}));if(result===true&&origin!==void 0)noteWatcherHeartbeatAck(origin)}catch{}}};void beat();return()=>{stopped=true}}var OWNER_HEARTBEAT_WORKER_SOURCE=`
|
|
324
324
|
const { parentPort, workerData } = require("node:worker_threads");
|
|
325
325
|
const { origin, pid, intervalMs, timeoutMs } = workerData;
|
|
@@ -350,7 +350,7 @@ const beat = async () => {
|
|
|
350
350
|
parentPort.postMessage("stopped");
|
|
351
351
|
};
|
|
352
352
|
void beat();
|
|
353
|
-
`;function runOwnerHeartbeatWorker(origin,pid,intervalMs,spawn3=(source,workerData)=>new Worker3(source,{eval:true,workerData})){const existing=ownerHeartbeatWorkers.get(origin);if(existing!==void 0){existing.refs+=1;let released2=false;return()=>{if(released2)return;released2=true;existing.refs-=1}}let stopped=false;let worker;let fallbackStop;try{const beatWorker=spawn3(OWNER_HEARTBEAT_WORKER_SOURCE,{origin,pid,intervalMs,timeoutMs:OWNER_HEARTBEAT_POST_TIMEOUT_MS});beatWorker.on("message",message=>{if(message==="ack")noteWatcherHeartbeatAck(origin);beatWorker.unref()});beatWorker.on("error",()=>{if(!stopped&&fallbackStop===void 0){fallbackStop=runOwnerHeartbeatLoop(defaultOwnerPost(origin),pid,intervalMs,origin)}});beatWorker.unref();worker=beatWorker}catch{return runOwnerHeartbeatLoop(defaultOwnerPost(origin),pid,intervalMs,origin)}const entry={refs:1,stop:()=>{}};const stop=()=>{if(stopped)return;stopped=true;ownerHeartbeatWorkers.delete(origin);watcherPendingRecovery.delete(origin);try{worker?.postMessage("stop")}catch{}setTimeout(()=>{void worker?.terminate()},50).unref?.();fallbackStop?.()};entry.stop=stop;ownerHeartbeatWorkers.set(origin,entry);let released=false;return()=>{if(released)return;released=true;entry.refs-=1;if(entry.refs<=0)entry.stop()}}function defaultOwnerPost(origin){return async body=>{const res=await fetch(`${origin}/__bili/watcher`,{method:"POST",headers:{"content-type":"application/json"},body,signal:AbortSignal.timeout(OWNER_HEARTBEAT_POST_TIMEOUT_MS)});return res.ok}}async function ensureProxyRunning(opts,deps={}){const fetchImpl=deps.fetchImpl??defaultFetch;const fetchHealthInfo=deps.fetchHealthInfo??fetchHealthInfoDefault;const fetchDetail=deps.fetchDetailImpl??defaultFetchDetail;const readInstance=deps.readInstanceFile??readProxyInstanceFile;const listRegistry=deps.listRegistryInstances??discoverLiveInstances;const spawnImpl=deps.spawnImpl??spawn2;const now=deps.now??Date.now;const sleepImpl=deps.sleep??(ms2=>new Promise(r=>setTimeout(r,ms2)));const registerWatcher=deps.registerWatcher??registerWatcherDefault;const attachExternal=(deps.resolveAttachExternal??resolveNativeAttachExternal)();const foreignLanes=(deps.attachLanePriority??resolveNativeAttachLanePriority)();const attachPolicy=(deps.resolveAttachPolicy??resolveNativeAttachPolicy)();const attachUrl=(deps.resolveAttachUrl??resolveNativeAttachUrl)();const refusedLog=new Set;const attachDiag=deps.attachDiag??defaultAttachDiag(opts.debug);const watchPid=opts.parentPid??process.pid;const registerOwner=async inst=>{let reg=await registerWatcher(inst.origin,watchPid);for(let attempt=1;reg==="failed"&&attempt<WATCHER_REG_ATTEMPTS;attempt++){await sleepImpl(WATCHER_REG_RETRY_BACKOFF_MS);reg=await registerWatcher(inst.origin,watchPid)}return reg};const attachTo=async inst=>{attachDiag(`bili: attaching to running proxy at ${inst.origin} (pid ${inst.pid})`);const reg=await registerOwner(inst);startOwnerHeartbeat(inst.origin,watchPid);const handle={origin:inst.origin,port:inst.port,attached:true,watcherRegistration:reg};if(reg==="refused")handle.refusedWatcher=true;if(reg==="failed"){markWatcherPendingRecovery(inst.origin,watchPid,attachDiag)}else{watcherPendingRecovery.delete(inst.origin)}return handle};const script=deps.scriptPath??process.argv[1];const codeFingerprint=entryScriptFingerprint(script);const probed=await probeLiveInstances(readInstance,fetchHealthInfo,attachDiag,deps?.isConnectable??tcpConnectable);const existing=pickAttachable(probed,opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,attachDiag,foreignLanes);if(existing){return attachTo(existing)}if(attachUrl!==void 0&&existing===void 0){const target=probed.find(c=>normalizeOrigin(c.inst.origin)===normalizeOrigin(attachUrl));let msg;if(target!==void 0){const reason=instanceCompatible(target.inst,opts,codeFingerprint,foreignLanes);const remedy=reason==="code-fingerprint-mismatch"?"the target runs different bili bytes than this lane (typical: global install vs host-managed copy right after an update). A target that reports a STRICTLY NEWER build attaches automatically \u2014 reaching this message means it reports the same or an older build: align the two installs (restart the host once its copy converges), or stop the target":reason!==void 0?`config shape mismatch (${reason}) \u2014 align the target's launch config with this lane's, or stop the target`:"it passes compatibility but fails the lifecycle gate (no armed watchdog) \u2014 set native.attachExternal=true or BILI_NATIVE_ATTACH_EXTERNAL=1 to attach anyway";msg=`bili: explicit attach target ${attachUrl} (pid ${target.inst.pid}) is not attachable: ${reason??"lifecycle gate"} \u2014 ${remedy}`}else{msg=`bili: no live instance registered at the explicit attach target ${attachUrl} \u2014 the proxy there never published an instance record or its owner pid is dead; check its startup log`}console.error(msg);attachDiag(msg)}const resolveTargetPort=()=>{const rotLane=opts.lane!==void 0&&opts.port<=0?opts.lane:void 0;return opts.port>0?opts.port:rotLane!==void 0?(deps?.zonePreferredPort??lanePreferredPort)(rotLane):void 0};{await rotateStalePredecessor(probed,resolveTargetPort,opts,attachUrl,foreignLanes,deps?.fetchHealthInfoNoReuse??(origin=>fetchHealthInfoDefault(origin,{noKeepAlive:true})),now,sleepImpl,deps?.requestInstanceShutdown??requestInstanceShutdown)}{await resolveWedgedSameLaneHolder(probed,resolveTargetPort,opts,attachUrl,foreignLanes,codeFingerprint,deps?.wedgedLedgerPath?.()??wedgedLedgerFilePath(),deps?.processBirthStamp??(pid=>processBirthStamp(pid)),now,sleepImpl,deps?.requestInstanceShutdown??requestInstanceShutdown,deps?.isConnectable??tcpConnectable,deps?.signalWedgedHolder??signalWedgedHolderDefault,deps?.killWedgedHolder??killWedgedHolderDefault,attachDiag)}if(!attachExternal&&opts.strictPort){const squatter=probed.find(c=>c.inst.port===opts.port&&instanceCompatible(c.inst,opts,codeFingerprint,foreignLanes)===void 0);if(squatter){throw new Error(`bili: port ${opts.port} is held by a lifecycle-less bili proxy at ${squatter.inst.origin} (pid ${squatter.inst.pid}) \u2014 the #1335 attach gate refuses it by default and this launch pins the port, so no session-owned proxy can bind it either. Kill that process (kill ${squatter.inst.pid}) or set native.attachExternal=true / BILI_NATIVE_ATTACH_EXTERNAL=1 to attach to it anyway.`)}}const waitForOtherStarter=async()=>{attachDiag("bili: another bili launch is bringing up a proxy \u2014 waiting for it instead of spawning a second");const waited=await waitForStarterInstance(readInstance,fetchHealthInfo,now,sleepImpl,opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,attachDiag,foreignLanes,deps?.isConnectable??tcpConnectable);if(waited){return attachTo(waited)}return void 0};const starterLaneMatches=m2=>opts.lane===void 0||m2.lane===void 0||m2.lane===opts.lane;const marker=readStartingMarker();if(marker){if(!isStartingMarkerActive(marker,now())){removeStartingMarker()}else if(starterLaneMatches(marker)){const attached=await waitForOtherStarter();if(attached)return attached}}const launchToken=randomUUID7();const zoneLane=opts.lane!==void 0&&opts.port<=0?opts.lane:void 0;const preferredPort=deps?.zonePreferredPort??lanePreferredPort;const port=opts.port>0?opts.port:zoneLane!==void 0?preferredPort(zoneLane):await pickEphemeralPort(opts.host);const settleZonePort=settled=>{if(zoneLane!==void 0)(deps?.writeZonePort??writeZonePort)(zoneLane,settled)};if(!script)throw new Error("bili: cannot resolve launcher script path");const logPath2=path27.join(os9.tmpdir(),`bili-proxy-${port}.log`);rotatePortLogIfNeeded(logPath2);const logFd=fs14.openSync(logPath2,"a");let spawnLogOffset=0;try{spawnLogOffset=fs14.fstatSync(logFd).size}catch{}const claimMarker=()=>claimStartingMarker({token:launchToken,pid:process.pid,host:opts.host,port,startedAt:now(),lane:opts.lane});let claimed=claimMarker();if(!claimed){const holder=readStartingMarker();if(holder&&isStartingMarkerActive(holder,now())){if(starterLaneMatches(holder)){const attached=await waitForOtherStarter();if(attached)return attached;claimed=claimMarker()}}else{removeStartingMarker();claimed=claimMarker()}}try{let child;const runtime=deps.nodeRuntime??resolveNodeRuntime();try{child=spawnImpl(runtime,[script,...proxyStartArgs({...opts,port})],{detached:true,windowsHide:true,stdio:["ignore",logFd,logFd],env:{...stripInheritedLauncherChannels(stripInheritedProxy(process.env)),...captureInheritedProxyEnv(process.env),...process.versions.electron?{ELECTRON_RUN_AS_NODE:"1"}:{},BILI_LAUNCH_TOKEN:launchToken,BILI_PARENT_PID:String(opts.parentPid??process.pid),...opts.lane?{BILI_LAUNCHER_LANE:opts.lane}:{},...opts.mitmDomains&&opts.mitmDomains.length?{BILI_MITM_DOMAINS:opts.mitmDomains.join(",")}:{},...opts.modelWindows&&Object.keys(opts.modelWindows).length>0?{BILI_LAUNCHER_MODEL_WINDOWS:JSON.stringify(opts.modelWindows)}:{},...opts.modelMaxOutputs&&Object.keys(opts.modelMaxOutputs).length>0?{BILI_LAUNCHER_MODEL_MAX_OUTPUTS:JSON.stringify(opts.modelMaxOutputs)}:{},...opts.strictPort?{BILI_STRICT_PORT:"1"}:{},...codeFingerprint!==void 0?{[SPAWN_FINGERPRINT_ENV]:codeFingerprint}:{}}})}finally{try{fs14.closeSync(logFd)}catch{}}try{child.unref?.()}catch{}let childExit;let childError;let squatterAnnounced=false;child.on?.("exit",(...rest)=>{childExit={code:typeof rest[0]==="number"?rest[0]:null,signal:typeof rest[1]==="string"?rest[1]:null}});child.on?.("error",(...rest)=>{childError=rest[0]});const logHeadSample=()=>{try{const size=fs14.statSync(logPath2).size;let start=spawnLogOffset;if(size<start)start=Math.max(0,size-256);const span=size-start;if(span<=0)return"";const len=Math.min(256,span);const off=span>len?start+(span-len):start;const label=span>len?"tail":"head";const fd=fs14.openSync(logPath2,"r");try{const buf=Buffer.alloc(len);const n=fs14.readSync(fd,buf,0,len,off);if(n===0)return"";let s3=buf.subarray(0,n).toString("utf8").replace(/\s+/g," ").trim();if(s3.length>200)s3=`${s3.slice(0,200)}\u2026`;return` \u2014 child output ${label}: "${s3}"`}finally{fs14.closeSync(fd)}}catch{return""}};const logTailSample=()=>{try{const size=fs14.statSync(logPath2).size;if(size>=spawnLogOffset&&size-spawnLogOffset<=256)return"";const start=size<spawnLogOffset?Math.max(0,size-256):Math.max(spawnLogOffset,size-256);const len=Math.min(256,size-start);if(len<=0)return"";const fd=fs14.openSync(logPath2,"r");try{const buf=Buffer.alloc(len);const n=fs14.readSync(fd,buf,0,len,start);if(n===0)return"";let s3=buf.subarray(0,n).toString("utf8").replace(/\s+/g," ").trim();if(s3.length>200)s3=`\u2026${s3.slice(s3.length-200)}`;return` \u2014 child output tail: "${s3}"`}finally{fs14.closeSync(fd)}}catch{return""}};const failureHint=()=>{try{const size=fs14.statSync(logPath2).size;const start=size<spawnLogOffset?Math.max(0,size-1024):Math.max(spawnLogOffset,size-1024);const len=Math.min(1024,size-start);if(len<=0)return"";const fd=fs14.openSync(logPath2,"r");try{const buf=Buffer.alloc(len);const n=fs14.readSync(fd,buf,0,len,start);if(n===0)return"";const hint=classifyStartupFailure(buf.subarray(0,n).toString("utf8"));return hint?` (${hint})`:""}finally{fs14.closeSync(fd)}}catch{return""}};const logTail=()=>{try{const size=fs14.statSync(logPath2).size;const rotatedFile=fs14.existsSync(`${logPath2}.old`);const rotated=rotatedFile?`; earlier output rotated to ${logPath2}.old`:"";if(size===0)return`, ${size} bytes \u2014 EMPTY, the child produced no output of its own${rotated}`;if(size===spawnLogOffset&&!rotatedFile)return`, ${size} bytes \u2014 this child appended nothing of its own (earlier content stays on disk until rotation)`;return`, ${size} bytes${rotated}${logHeadSample()}${logTailSample()}`}catch{return""}};const diagnosePort=async childAlive=>{const origin=proxyOrigin(opts.host,port);let info;let det={ok:false,detail:"probe error"};try{const[i,d2]=await Promise.all([fetchHealthInfo(origin),fetchDetail(healthUrl(origin))]);info=i;det=d2}catch{}const selfHealthy=Boolean(info?.ok&&child.pid!==void 0&&info.pid===child.pid);if(info?.ok){return selfHealthy?{text:`port ${port} finally answers healthy from our child (pid ${info.pid}) but its instance handshake never matched \u2014 check the instance-file/registry state dir`,selfHealthy}:{text:`port ${port} is held by a different process${info.pid!==void 0?` (pid ${info.pid})`:""} \u2014 the spawned child never bound it. Kill that process (kill ${info.pid??"?"}) or set native.attachExternal=true / BILI_NATIVE_ATTACH_EXTERNAL=1 to attach to it instead`,selfHealthy:false}}if(det.ok){return{text:`port ${port} answered but not with bili's health payload \u2014 a foreign service likely holds it`,selfHealthy:false}}const d=det.detail??"unknown error";if(/^(ECONNREFUSED|ECONNRESET|EHOSTUNREACH|ENETUNREACH|EPIPE)$/i.test(d)){return{text:`nothing is listening on port ${port} \u2014 the spawned child (${childAlive?"still alive":"already exited"}, pid ${child.pid??"?"}) never bound it`,selfHealthy:false}}if(/^HTTP \d{3}$/.test(d)){return{text:`port ${port} answered ${d} \u2014 the listener there is not reporting bili health`,selfHealthy:false}}if(/^timeout after \d+ms$/i.test(d)&&await(deps.isConnectable??tcpConnectable)(origin)){return{text:`port ${port} accepts TCP connections but never answers /__bili/health within the probe budget \u2014 the instance there is BUSY (event loop saturated, typically a large compression), not dead (#3654)`,selfHealthy:false}}return{text:`last health probe failed with ${d}`,selfHealthy:false}};const deadline=now()+SPAWN_BUDGET_MS;let slowStartNoticed=false;while(now()<deadline){if(childExit||childError!==void 0)break;if(!slowStartNoticed&&now()>=deadline-SLOW_START_GRACE_MS){slowStartNoticed=true;console.error(`bili: spawned proxy not healthy after ${SPAWN_WAIT_MS}ms \u2014 child pid ${child.pid??"?"} is still starting up; extending wait to ${SPAWN_BUDGET_MS}ms total (${(await diagnosePort(true)).text}) (log: ${logPath2}${logTail()})`)}await sleepImpl(HEALTH_POLL_INTERVAL_MS);const inst=readInstance();if(isProxyInstanceFile(inst)&&inst.launchToken===launchToken){if(await probeHealth(inst.origin,fetchImpl)){settleZonePort(inst.port);startOwnerHeartbeat(inst.origin,watchPid);return{origin:inst.origin,port:inst.port,child,logPath:logPath2}}continue}if(child.pid!==void 0){const mine=listRegistry().find(e=>e.pid===child.pid);if(mine&&mine.origin!==""&&await probeHealth(mine.origin,fetchImpl)){settleZonePort(mine.port);startOwnerHeartbeat(mine.origin,watchPid);return{origin:mine.origin,port:mine.port,child,logPath:logPath2}}}const stale=!isProxyInstanceFile(inst)||!isPidAlive(inst.pid);if(stale){const preferredOrigin=proxyOrigin(opts.host,port);const info=await fetchHealthInfo(preferredOrigin);if(info?.ok&&child.pid!==void 0&&info.pid===child.pid){settleZonePort(port);startOwnerHeartbeat(preferredOrigin,watchPid);return{origin:preferredOrigin,port,child,logPath:logPath2}}if(info?.ok&&!squatterAnnounced){squatterAnnounced=true;attachDiag(`bili: port ${port} answers health${info.pid!==void 0?` (pid ${info.pid})`:""} but is not the proxy this launcher spawned (child pid ${child.pid??"?"}) \u2014 waiting for the spawned instance to report its real origin; if that never happens, kill pid ${info.pid??"?"} or set native.attachExternal=true / BILI_NATIVE_ATTACH_EXTERNAL=1 to attach to the holder instead`)}}}const adoptServingTwin=async()=>{const candidates=(deps.listAdoptCandidates??discoverLiveInstances)().filter(inst=>isPidAlive(inst.pid)).sort((a,b2)=>Number(b2.port===port)-Number(a.port===port)||b2.startedAt-a.startedAt);for(const inst of candidates){let compatible=instanceCompatible(inst,opts,codeFingerprint,foreignLanes)===void 0;let adoptedNewerVersion;if(!compatible){const reported=await fetchHealthInfo(inst.origin);if(reported!==void 0&&isNewerSameLaneHolder(inst,opts.lane,reported.version,VERSION,isUserZoneInstance(inst))&&instanceShapeMismatch(inst,opts,foreignLanes)===void 0){compatible=true;adoptedNewerVersion=reported.version}}if(!compatible)continue;if(!await(deps.isConnectable??tcpConnectable)(inst.origin))continue;attachDiag(adoptedNewerVersion!==void 0?`bili: adopting serving twin ${inst.origin} (pid ${inst.pid}) \u2014 reports v${adoptedNewerVersion}, strictly NEWER than this lane's v${VERSION}: the older generation yields so this spawn rides the newer build instead of deadlocking behind it (#4125)`:`bili: adopting serving twin ${inst.origin} (pid ${inst.pid}) \u2014 the spawned child lost the #3044 duplicate race to it; requests ride the existing instance (#3654)`);return attachTo(inst)}return void 0};const rediscoverAfterChildExit=async()=>{console.error(`bili: spawned proxy exited before becoming healthy \u2014 re-checking for a late-publishing listener on port ${port} before failing`);const rediscoveryDeadline=now()+POST_EXIT_REDISCOVERY_MS;while(now()<rediscoveryDeadline){await sleepImpl(HEALTH_POLL_INTERVAL_MS);const probedAgain=await probeLiveInstances(readInstance,fetchHealthInfo,attachDiag,deps.isConnectable??tcpConnectable);const late=pickAttachable(probedAgain,opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,attachDiag,foreignLanes);if(late){attachDiag(`bili: attached to ${late.origin} (pid ${late.pid}) \u2014 it published its instance record after the initial discovery`);return attachTo(late)}}return void 0};if(childError!==void 0){const detail=childError instanceof Error?childError.message:String(childError);throw new Error(`bili: proxy spawn failed (${detail}) (runtime: ${runtime}) (log: ${logPath2})`)}if(childExit){if(childExit.code===TWIN_ADOPT_EXIT_CODE){const adopted=await adoptServingTwin();if(adopted!==void 0)return adopted;attachDiag("bili: serving-twin adoption failed verification \u2014 continuing with the standard post-exit re-discovery")}const retried=await rediscoverAfterChildExit();if(retried)return retried;const detail=childExit.code!==null?`code ${childExit.code}${childExit.code===TWIN_ADOPT_EXIT_CODE?" (twin-collision signal)":""}`:childExit.signal?`signal ${childExit.signal}`:"unknown reason";throw new Error(`bili: proxy child exited before becoming healthy (${detail}) \u2014 ${(await diagnosePort(false)).text} (runtime: ${runtime}) (log: ${logPath2}${logTail()})${failureHint()}`)}const childLogBoundOrigin=()=>{try{const size=fs14.statSync(logPath2).size;let start=spawnLogOffset;if(size<start)start=Math.max(0,size-8192);if(size<=start)return void 0;const fd=fs14.openSync(logPath2,"r");let seg;try{seg=Buffer.alloc(size-start);const n=fs14.readSync(fd,seg,0,seg.length,start);seg=seg.subarray(0,n)}finally{fs14.closeSync(fd)}const text=seg.toString("utf8");const re2=/\(pid (\d+), id [^)]+\) listening on (https?:\/\/\S+)/g;let m2;let last;while((m2=re2.exec(text))!==null)last=m2;if(!last||Number(last[1])!==child.pid)return void 0;const u2=new URL(last[2]);const p2=Number(u2.port);if(!Number.isInteger(p2)||p2<=0)return void 0;return{origin:u2.origin,port:p2}}catch{return void 0}};const diagnosis=await diagnosePort(true);if(diagnosis.selfHealthy){settleZonePort(port);startOwnerHeartbeat(proxyOrigin(opts.host,port),watchPid);attachDiag(`bili: adopting our own healthy child (pid ${child.pid}) at ${proxyOrigin(opts.host,port)} after ${SPAWN_BUDGET_MS}ms \u2014 the instance handshake never matched but the health probe proves this child serves the port; keeping it instead of killing (#4994)`);return{origin:proxyOrigin(opts.host,port),port,child,logPath:logPath2}}const bound=childLogBoundOrigin();if(bound){const info=await fetchHealthInfo(bound.origin);if(info?.ok&&info.pid===child.pid){settleZonePort(bound.port);startOwnerHeartbeat(bound.origin,watchPid);attachDiag(`bili: adopting our own healthy child (pid ${child.pid}) at ${bound.origin} after ${SPAWN_BUDGET_MS}ms \u2014 it bound ${bound.port} per its own listen line and answers health under our pid; keeping it instead of killing (#4994)`);return{origin:bound.origin,port:bound.port,child,logPath:logPath2}}}killAbandonedChild(child);console.error(`bili: killed spawned proxy (pid ${child.pid??"?"}) after ${SPAWN_BUDGET_MS}ms without health \u2014 ${diagnosis.text} (log: ${logPath2}${logTail()})`);throw new Error(`bili: proxy did not become healthy within ${SPAWN_BUDGET_MS}ms \u2014 ${diagnosis.text} (runtime: ${runtime}) (log: ${logPath2}${logTail()})${failureHint()}`)}finally{if(claimed)clearStartingMarker(launchToken)}}function hardKillProxyTree(pid,label){if(process.platform!=="win32"){try{process.kill(pid,"SIGKILL")}catch(err){if(err?.code!=="ESRCH"){log("warn",`bili: SIGKILL of ${label} ${pid} failed (${err instanceof Error?err.message:String(err)}) \u2014 its listener may survive the cleanup (#4125)`)}}return}let tkError;try{const tk=spawnSync3("taskkill",["/F","/T","/PID",String(pid)],{windowsHide:true,stdio:"ignore"});if(tk.error!==void 0)tkError=tk.error.message;else if(tk.status!==0)tkError=`exit ${tk.status}`}catch(err){tkError=err instanceof Error?err.message:String(err)}if(tkError!==void 0){log("warn",`bili: taskkill of ${label} ${pid} reported failure (${tkError}) \u2014 its listener may survive the cleanup (#4125)`)}try{process.kill(pid,"SIGKILL")}catch(err){if(err?.code!=="ESRCH"){log("warn",`bili: direct SIGKILL of ${label} ${pid} failed (${err instanceof Error?err.message:String(err)}) \u2014 its listener may survive the cleanup (#4125)`)}}}function signalWedgedHolderDefault(pid){if(process.platform==="win32")return;try{process.kill(pid,"SIGTERM")}catch{}}function killWedgedHolderDefault(pid){hardKillProxyTree(pid,"wedged holder")}function killAbandonedChild(child){if(!child||child.pid===void 0||child.pid<=0)return;if(process.platform!=="win32"){try{process.kill(-child.pid,"SIGKILL")}catch{}}hardKillProxyTree(child.pid,"abandoned proxy");try{child.kill?.("SIGKILL")}catch{log("warn",`bili: SIGKILL of abandoned proxy ${child.pid} via its own handle failed \u2014 it may survive the cleanup (#4125)`)}}var PATH_EXTS=process.platform==="win32"?[".cmd",".bat",".exe",""]:[""];init_util();import{createHash as createHash17}from"crypto";import{createHash as createHash16}from"crypto";function hashId2(s3){return createHash16("sha256").update(s3,"utf8").digest("hex").slice(0,16)}var CANONICAL_IMAGE_TEXT="[image]";var CANONICAL_REDACTED_THINKING_TEXT="[redacted_thinking]";function canonicalToolArgs(argsText){const trimmed=argsText.trim();if(!trimmed.startsWith("{")&&!trimmed.startsWith("["))return argsText;try{return JSON.stringify(canonicalize2(JSON.parse(trimmed)))}catch{return argsText}}function canonicalize2(v2){if(Array.isArray(v2))return v2.map(canonicalize2);if(v2!==null&&typeof v2==="object"){const src=v2;const out={};for(const k2 of Object.keys(src).sort())out[k2]=canonicalize2(src[k2]);return out}return v2}var idSalt=null;function deriveCanonicalMessageId(role,contentType,text,options={}){const seed=`${idSalt?idSalt+"|":""}${role}|${contentType}||${options.toolName??""}|${text}`+(options.mediaFingerprint!==void 0?`|${options.mediaFingerprint}`:"");return"h_"+hashId2(seed)}function imageMediaFingerprint(base64OrUrl){return hashId2(base64OrUrl)}function canonicalOpaqueSeed(item){if(item===null||typeof item!=="object")return hashId2(String(item));const src=item;const out={};for(const k2 of Object.keys(src)){if(k2==="id"||k2==="status")continue;out[k2]=src[k2]}return hashId2(JSON.stringify(out))}var ClusterCounter=class{counts=new Map;next(baseId){const n=this.counts.get(baseId)??0;this.counts.set(baseId,n+1);return n===0?baseId:`${baseId}_${n}`}};function anthropicToCore(body){const msgs=[];const cacheControls=new Map;const clusters=new ClusterCounter;const toolNames=new Map;for(const[wireIndex,m2]of body.messages.entries()){const before=msgs.length;if(m2.role==="system"){const core=systemMessageCore(m2,clusters);core.wireIndex=wireIndex;msgs.push(core);const mark=systemMessageMark(m2);if(mark)cacheControls.set(core.id,mark);continue}const blocks=typeof m2.content==="string"?[{type:"text",text:m2.content}]:m2.content;for(const b2 of blocks){switch(b2.type){case"text":{const base=deriveCanonicalMessageId(m2.role,"text",b2.text);const id=clusters.next(base);msgs.push({id,role:m2.role,contentType:"text",text:b2.text});if(b2.cache_control)cacheControls.set(id,b2.cache_control);break}case"tool_use":{const base=deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(safeStringify(b2.input)),{toolName:b2.name});const id=clusters.next(base);msgs.push({id,role:"assistant",contentType:"tool-call",toolName:b2.name,toolCallId:b2.id,text:safeStringify(b2.input)});toolNames.set(b2.id,b2.name);if(b2.cache_control)cacheControls.set(id,b2.cache_control);break}case"tool_result":{const hasNonText=Array.isArray(b2.content)&&b2.content.some(c=>c.type!=="text");const text=typeof b2.content==="string"?b2.content:b2.content.map(c=>c.type==="text"?c.text:"").join("\n");const name=toolNames.get(b2.tool_use_id);const base=deriveCanonicalMessageId("tool","tool-result",text,{toolName:name});const id=clusters.next(base);msgs.push({id,role:"tool",contentType:"tool-result",toolCallId:b2.tool_use_id,text,...name?{toolName:name}:{},...b2.is_error===true?{toolIsError:true}:{},...hasNonText?{rawAnthropicBlock:b2}:{}});if(b2.cache_control)cacheControls.set(id,b2.cache_control);break}case"thinking":{const base=deriveCanonicalMessageId("assistant","reasoning",b2.thinking);msgs.push({id:clusters.next(base),role:"assistant",contentType:"reasoning",text:b2.thinking,...b2.signature?{thinkingSignature:b2.signature}:{}});break}case"image":{const source=b2.source&&typeof b2.source==="object"&&!Array.isArray(b2.source)?b2.source:void 0;const mediaSidecar=source?.type==="base64"&&typeof source.media_type==="string"&&typeof source.data==="string"?{imageMediaType:source.media_type,imageBase64:source.data}:{};const base=deriveCanonicalMessageId(m2.role,"text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:source?.type==="base64"&&typeof source.data==="string"?imageMediaFingerprint(source.data):typeof source?.url==="string"?imageMediaFingerprint(source.url):void 0});msgs.push({id:clusters.next(base),role:m2.role,contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawAnthropicBlock:b2,...mediaSidecar});break}case"redacted_thinking":{const base=deriveCanonicalMessageId(m2.role,"text",CANONICAL_REDACTED_THINKING_TEXT);msgs.push({id:clusters.next(base),role:m2.role,contentType:"text",text:"[redacted_thinking]",rawAnthropicBlock:b2});break}default:{const unknownType=b2.type;const label=typeof unknownType==="string"?`[${unknownType}]`:"[unknown]";const base=deriveCanonicalMessageId(m2.role,"text",label);msgs.push({id:clusters.next(base),role:m2.role,contentType:"text",text:label,rawAnthropicBlock:b2});break}}}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}}return{msgs,cacheControls}}function systemMessageCore(m2,clusters){const label=systemMessageText(m2);const base=deriveCanonicalMessageId("system","text",label);return{id:clusters.next(base),role:"system",contentType:"text",text:label,rawAnthropicMessage:m2}}function systemMessageText(m2){const text=typeof m2.content==="string"?m2.content:m2.content.map(b2=>b2.type==="text"?b2.text:`[${b2.type}]`).join("\n");return text.length>0?text:"[system]"}function systemMessageMark(m2){if(typeof m2.content==="string")return void 0;let mark;for(const b2 of m2.content)if(b2.cache_control)mark=b2.cache_control;return mark}function safeStringify(v2){try{return JSON.stringify(v2??{})}catch{return"{}"}}var FORMS=[{open:"<think>\n",close:"\n</think>"},{open:"<thinking>\n",close:"\n</thinking>"},{open:"```thinking\n",close:"\n```"}];function splitDemotedThinking(content){let rest=content;const parts=[];for(;;){let matched=false;for(const form of FORMS){if(!rest.startsWith(form.open))continue;const end=rest.indexOf(form.close,form.open.length);if(end<0)continue;const inner=rest.slice(form.open.length,end);if(inner.length===0)continue;parts.push(inner);rest=rest.slice(end+form.close.length);if(rest.startsWith("\n"))rest=rest.slice(1);matched=true;break}if(!matched)break}if(parts.length===0)return null;return{reasoning:parts.join("\n"),text:rest}}function parseDataUrl(url){const m2=/^data:([^;,]+)(?:;base64)?,(.+)$/i.exec(url);if(!m2)return void 0;return{mediaType:m2[1],base64:m2[2]}}function imageFingerprintsOfParts(parts){const out=[];for(const part of parts){if(!part||typeof part!=="object")continue;const p2=part;if(p2.type!=="image_url")continue;const url=typeof p2.image_url?.url==="string"?p2.image_url.url:void 0;if(!url)continue;const parsed=parseDataUrl(url);out.push(imageMediaFingerprint(parsed?parsed.base64:url))}return out}function openaiToCore(body){const msgs=[];const systemParts=[];const clusters=new ClusterCounter;const toolNames=new Map;for(const[wireIndex,m2]of body.messages.entries()){const before=msgs.length;switch(m2.role){case"system":case"developer":{if(msgs.length===0){systemParts.push(stringContent(m2.content));break}const base=deriveCanonicalMessageId(m2.role,"text",stringContent(m2.content));msgs.push({id:clusters.next(base),role:"system",contentType:"text",text:stringContent(m2.content),originalRole:m2.role,rawOpenaiMessage:m2});break}case"user":{if(typeof m2.content==="string"||m2.content==null||!Array.isArray(m2.content)){const base=deriveCanonicalMessageId("user","text",typeof m2.content==="string"?m2.content:"");msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:typeof m2.content==="string"?m2.content:""});break}let lastTextCore=null;let leadingOpaque=[];let sawText=false;for(const part of m2.content){if(typeof part==="string"){const base=deriveCanonicalMessageId("user","text",part);lastTextCore={id:clusters.next(base),role:"user",contentType:"text",text:part};msgs.push(lastTextCore);sawText=true;continue}if(part?.type==="text"&&typeof part.text==="string"){const base=deriveCanonicalMessageId("user","text",part.text);lastTextCore={id:clusters.next(base),role:"user",contentType:"text",text:part.text};msgs.push(lastTextCore);sawText=true;continue}if(part?.type==="image_url"){const url=part.image_url?.url;const parsed=typeof url==="string"?parseDataUrl(url):void 0;const base=deriveCanonicalMessageId("user","text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:imageMediaFingerprint(parsed?parsed.base64:typeof url==="string"?url:"")});msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawOpenaiContent:part,...parsed?{imageMediaType:parsed.mediaType,imageBase64:parsed.base64}:{}});continue}if(lastTextCore){lastTextCore.rawOpenaiContentParts=[...lastTextCore.rawOpenaiContentParts??[],part]}else{leadingOpaque=[...leadingOpaque,part]}}if(leadingOpaque.length>0){if(sawText&&msgs.length>0){const firstTextCore=msgs.find((c,i)=>i>=before&&c.role==="user"&&c.contentType==="text"&&!c.rawOpenaiContent);const host=firstTextCore??msgs[msgs.length-1];host.rawOpenaiContentParts=[...leadingOpaque,...host.rawOpenaiContentParts??[]]}else{const base=deriveCanonicalMessageId("user","text","",{mediaFingerprint:imageFingerprintsOfParts(leadingOpaque).join(",")||void 0});msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:"",rawOpenaiContentParts:leadingOpaque})}}break}case"assistant":{const rawReasoning=m2.reasoning_content;const fieldPresent=typeof rawReasoning==="string";const fieldReasoning=fieldPresent?rawReasoning:"";let reasoning=fieldReasoning;let text=stringContent(m2.content);if(!reasoning){const split=splitDemotedThinking(text);if(split){reasoning=split.reasoning;text=split.text}}const blankEcho=fieldPresent&&reasoning.length===0;if(reasoning){const base=deriveCanonicalMessageId("assistant","reasoning",reasoning);msgs.push({id:clusters.next(base),role:"assistant",contentType:"reasoning",text:reasoning,reasoningContent:reasoning})}if(text){const base=deriveCanonicalMessageId("assistant","text",text);msgs.push({id:clusters.next(base),role:"assistant",contentType:"text",text,...blankEcho?{reasoningPresent:true}:{}})}if(Array.isArray(m2.tool_calls)){for(const tc of m2.tool_calls){const base=deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(tc.function.arguments??""),{toolName:tc.function.name});msgs.push({id:clusters.next(base),role:"assistant",contentType:"tool-call",toolName:tc.function.name,toolCallId:tc.id,text:tc.function.arguments??"",...blankEcho?{reasoningPresent:true}:{}});toolNames.set(tc.id,tc.function.name)}}break}case"tool":{const base=deriveCanonicalMessageId("tool","tool-result",stringContent(m2.content),{toolName:m2.name||toolNames.get(m2.tool_call_id??"")});const name=m2.name||toolNames.get(m2.tool_call_id??"");msgs.push({id:clusters.next(base),role:"tool",contentType:"tool-result",toolCallId:m2.tool_call_id??"",text:stringContent(m2.content),...name?{toolName:name}:{}});break}}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}}return{msgs,systemText:systemParts.join("\n\n")}}function stringContent(content){if(content==null)return"";if(typeof content==="string")return content;if(Array.isArray(content)){return content.map(p2=>typeof p2==="string"?p2:p2.type==="text"?p2.text??"":"").join("\n")}return""}var OPAQUE_ITEM_TYPES=new Set(["additional_tools","mcp_list_tools"]);function isOpaqueItem(item){return OPAQUE_ITEM_TYPES.has(item.type)}var EASY_INPUT_ROLES=new Set(["user","assistant","system","developer"]);function normalizeEasyInputItem(item){if(typeof item.type==="string")return item;if(EASY_INPUT_ROLES.has(String(item.role))){return{...item,type:"message"}}return item}function shouldDropAllReasoning(){return(process.env.ACP_REASONING_KEEP??"").trim().toLowerCase()==="none"}function partText(part){if(part.type==="input_text"||part.type==="output_text"){return typeof part.text==="string"?part.text:""}return""}function messageContent(content){return typeof content==="string"?content:content.map(partText).join("\n")}function userDisplayText(content,text){if(typeof content==="string")return text;const hasImage=content.some(part=>part.type==="input_image");const hasTextPart=content.some(part=>part.type==="input_text"||part.type==="output_text");return!text||hasImage&&!hasTextPart?"[image]":text}function reasoningText(item){const fromParts=(parts,type)=>{if(!Array.isArray(parts))return"";const texts=[];for(const part of parts){if(part&&typeof part==="object"&&"type"in part&&"text"in part){const rec=part;if(rec.type===type&&typeof rec.text==="string")texts.push(rec.text)}}return texts.join("\n")};const content="content"in item?item.content:void 0;const summary="summary"in item?item.summary:void 0;return fromParts(content,"reasoning_text")||fromParts(summary,"summary_text")}function responsesToCore(body){const msgs=[];const systemParts=[];const preamble=[];const customToolCallIds=new Set;const layout=[];let droppedReasoning=0;const clusters=new ClusterCounter;const toolNames=new Map;let idx=0;if(typeof body.instructions==="string"&&body.instructions.trim())systemParts.push(body.instructions);if(typeof body.input==="string"){const id=clusters.next(deriveCanonicalMessageId("user","text",body.input));msgs.push({id,role:"user",contentType:"text",text:body.input});return{msgs,systemParts,preamble,customToolCallIds,layout,droppedReasoning,stringInput:{original:body.input,coreId:id}}}let sysDevHead=true;let headRole;for(const[wireIndex,raw]of body.input.entries()){const item=normalizeEasyInputItem(raw);let coreId;const before=msgs.length;if(isOpaqueItem(item))preamble.push(item);switch(item.type){case"reasoning":{if(shouldDropAllReasoning()){droppedReasoning++;continue}const text=reasoningText(item);const rid=text.length>0?text:canonicalOpaqueSeed(item);coreId=clusters.next(deriveCanonicalMessageId("assistant","reasoning",rid));msgs.push({id:coreId,role:"assistant",contentType:"reasoning",text:rid,rawResponsesItem:item});break}case"message":{const message=item;const text=messageContent(message.content);if(message.role==="system"||message.role==="developer"){if(sysDevHead){headRole??=message.role;systemParts.push(text);idx++;continue}const midBase=deriveCanonicalMessageId(message.role,"text",text);msgs.push({id:clusters.next(midBase),role:"system",contentType:"text",text,originalRole:message.role,rawResponsesItem:item});break}else if(message.role==="user"||message.role==="assistant"&&text){const role2=message.role;const splittable=role2==="user"&&Array.isArray(message.content)&&message.content.length>1&&message.content.every(part=>typeof part==="object"&&part!==null&&(part.type==="input_text"||part.type==="output_text"||part.type==="input_image"));if(splittable){for(const rawPart of message.content){const part=typeof rawPart==="object"&&rawPart!==null?rawPart:void 0;if(!part)continue;if((part.type==="input_text"||part.type==="output_text")&&typeof part.text==="string"&&part.text.length>0){const base=deriveCanonicalMessageId("user","text",part.text);msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:part.text})}else if(part.type==="input_image"&&typeof part.image_url==="string"){const image=parseDataUrl(part.image_url);const base=deriveCanonicalMessageId("user","text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:imageMediaFingerprint(image?image.base64:part.image_url)});msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawResponsesItem:item,...image?{imageMediaType:image.mediaType,imageBase64:image.base64}:{}})}}break}let effText=text;if(role2==="assistant"){const split=splitDemotedThinking(text);if(split){msgs.push({id:clusters.next(deriveCanonicalMessageId("assistant","reasoning",split.reasoning)),role:"assistant",contentType:"reasoning",text:split.reasoning,rawResponsesItem:item});effText=split.text}}const hasImage=Array.isArray(message.content)&&message.content.some(part=>part.type==="input_image");if(effText||role2==="user"&&hasImage){const displayText=role2==="user"?userDisplayText(message.content,effText):effText;const mediaFingerprint=Array.isArray(message.content)?message.content.flatMap(part=>{if(part?.type==="input_image"&&typeof part.image_url==="string"){const raw2=part.image_url;const decoded=parseDataUrl(raw2);return[imageMediaFingerprint(decoded?decoded.base64:raw2)]}return[]}).join(",")||void 0:void 0;coreId=clusters.next(deriveCanonicalMessageId(role2,"text",displayText,{mediaFingerprint}));const imageUrl=Array.isArray(message.content)?message.content.find(part=>part.type==="input_image"&&typeof part.image_url==="string")?.image_url:void 0;const image=typeof imageUrl==="string"?parseDataUrl(imageUrl):void 0;msgs.push({id:coreId,role:role2,contentType:"text",text:displayText,rawResponsesItem:item,...image?{imageMediaType:image.mediaType,imageBase64:image.base64}:{}})}}break}case"function_call":{const call=item;coreId=clusters.next(deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(call.arguments??""),{toolName:call.name}));msgs.push({id:coreId,role:"assistant",contentType:"tool-call",toolName:call.name,toolCallId:call.call_id,text:call.arguments??"",rawResponsesItem:item});toolNames.set(call.call_id,call.name);break}case"function_call_output":{const output=item;const text=typeof output.output==="string"?output.output:JSON.stringify(output.output);coreId=clusters.next(deriveCanonicalMessageId("tool","tool-result",text,{toolName:toolNames.get(output.call_id)}));const name=toolNames.get(output.call_id);msgs.push({id:coreId,role:"tool",contentType:"tool-result",toolCallId:output.call_id,text,...name?{toolName:name}:{},rawResponsesItem:item});break}case"computer_call":case"computer_call_output":case"file_search_call":case"web_search_call":case"image_generation_call":case"code_interpreter_call":case"mcp_call":{const rid=canonicalOpaqueSeed(item);coreId=clusters.next(deriveCanonicalMessageId("assistant","responses-call",rid));msgs.push({id:coreId,role:"assistant",contentType:"reasoning",text:rid,rawResponsesItem:item});break}case"custom_tool_call":{const ctc=item;const callId=ctc.call_id??`call_${idx}`;customToolCallIds.add(callId);const argText=ctc.input??ctc.arguments??"";coreId=clusters.next(deriveCanonicalMessageId("assistant","tool-call",argText,{toolName:ctc.name??"custom"}));msgs.push({id:coreId,role:"assistant",contentType:"tool-call",toolName:ctc.name??"custom",toolCallId:callId,text:argText,rawResponsesItem:item});toolNames.set(callId,ctc.name??"custom");break}case"custom_tool_call_output":{const ctco=item;const callId=ctco.call_id??`call_${idx}`;customToolCallIds.add(callId);const outText=typeof ctco.output==="string"?ctco.output:JSON.stringify(ctco.output??"");coreId=clusters.next(deriveCanonicalMessageId("tool","tool-result",outText,{toolName:toolNames.get(callId)}));const name=toolNames.get(callId);msgs.push({id:coreId,role:"tool",contentType:"tool-result",toolCallId:callId,text:outText,...name?{toolName:name}:{},rawResponsesItem:item});break}default:if(!isOpaqueItem(item))preamble.push(item);break}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}const role=item.role;const isSysDevMsgItem=(item.type===void 0||item.type==="message")&&(role==="system"||role==="developer");if(!isSysDevMsgItem&&item.type!=="additional_tools"&&item.type!=="mcp_list_tools")sysDevHead=false;const produced=msgs.slice(before).map(m2=>m2.id);layout.push({original:item,...produced.length>0?{coreId:produced[0]}:{},...produced.length>1?{coreIds:produced}:{}});idx++}return{msgs,systemParts,preamble,customToolCallIds,layout,droppedReasoning,...headRole?{headRole}:{}}}function createSubagentNamespaces(){const anchors=new Map;return{namespaceFor(identityValue,instructions){if(typeof instructions!=="string"||instructions.trim().length===0)return identityValue;const fp=hashId2(instructions);const anchor=anchors.get(identityValue);if(anchor===void 0){anchors.set(identityValue,fp);return identityValue}return anchor===fp?identityValue:`${identityValue}|sub:${fp}`}}}var defaultNamespaces=createSubagentNamespaces();function detectWireFormat(payload){if(payload===null||typeof payload!=="object")return void 0;const p2=payload;if(Array.isArray(p2.contents))return"google";if(Array.isArray(p2.input))return"responses";const messages=p2.messages;if(!Array.isArray(messages))return void 0;if("system"in p2||"anthropic_version"in p2)return"anthropic";for(const m2 of messages){if(m2===null||typeof m2!=="object")continue;const c=m2.content;if(Array.isArray(c)){for(const b2 of c){if(b2&&typeof b2==="object"&&typeof b2.type==="string"){if(b2.type==="tool_use"||b2.type==="tool_result"||b2.type==="thinking")return"anthropic";if(b2.type==="text"&&"cache_control"in b2)return"anthropic"}}}if(Array.isArray(m2.tool_calls))return"openai";if(m2.role==="tool"&&typeof m2.tool_call_id==="string")return"openai";if(m2.role==="system"||m2.role==="developer")return"openai"}return"openai"}var DEFAULT_MAX_FUTURE_SKEW_MS=2*60*1e3;var DEFAULT_RECENT_CHECKPOINT_WINDOW_MS=10*60*1e3;var MAX_CHECKPOINT_CHARS=512;var TAG_OPEN2="<bili-chain ";var TAG_CLOSE2="/>";var ATTRS=["v","processor","issued-at","request-id","digest"];function validAttrValue(name,raw){switch(name){case"v":return/^\d+$/.test(raw)&&Number(raw)>=1;case"issued-at":return/^\d{1,16}$/.test(raw);case"processor":return/^[A-Za-z0-9._-]{1,64}$/.test(raw);case"request-id":return/^[A-Za-z0-9._:-]{1,64}$/.test(raw);case"digest":return/^sha256:[0-9a-f]{64}$/.test(raw)}}function parseChainCheckpoint(text){if(typeof text!=="string"||text.length===0||text.length>MAX_CHECKPOINT_CHARS)return null;if(!text.startsWith(TAG_OPEN2)||!text.endsWith(TAG_CLOSE2))return null;const inner=text.slice(TAG_OPEN2.length,-TAG_CLOSE2.length);const found={};for(const token of inner.split(/\s+/)){const m2=/^([a-z][a-z0-9-]*)="([^"]*)"$/.exec(token);if(!m2)return null;const name=m2[1];if(!ATTRS.includes(name))return null;if(Object.hasOwn(found,name))return null;found[name]=m2[2]}for(const attr of ATTRS){const raw=found[attr];if(raw===void 0||!validAttrValue(attr,raw))return null}return{v:Number(found.v),processor:found.processor,issuedAt:Number(found["issued-at"]),requestId:found["request-id"],digest:found.digest}}function stripEmbeddedChainCarriers(parsed,wire){if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed))return 0;const body=parsed;let stripped=0;if(wire==="google"){const contents=body.contents;if(!Array.isArray(contents))return 0;for(let i=contents.length-1;i>=0;i--){const c=contents[i];if(!c||typeof c!=="object"||Array.isArray(c))continue;const ct2=c;const role=typeof ct2.role==="string"?ct2.role:"user";if(role!=="user"&&role!=="model")continue;const parts=ct2.parts;if(!Array.isArray(parts))continue;let removed=0;for(let j2=parts.length-1;j2>=0;j2--){const p2=parts[j2];if(p2&&typeof p2==="object"&&!Array.isArray(p2)&&Object.keys(p2).length===1&&typeof p2.text==="string"){if(parseChainCheckpoint(p2.text)){parts.splice(j2,1);removed++}}}if(removed>0){if(parts.length===0)contents.splice(i,1);stripped+=removed}}return stripped}if(wire==="responses"){const input=body.input;if(!Array.isArray(input))return 0;for(let i=input.length-1;i>=0;i--){const item=input[i];if(!item||typeof item!=="object"||Array.isArray(item))continue;const it2=item;if(it2.type!=="message")continue;const role=typeof it2.role==="string"?it2.role:"";if(role!=="user"&&role!=="assistant")continue;const content=it2.content;if(typeof content==="string"){if(parseChainCheckpoint(content)){input.splice(i,1);stripped++}continue}if(!Array.isArray(content))continue;let removed=0;for(let j2=content.length-1;j2>=0;j2--){const p2=content[j2];if(p2&&typeof p2==="object"&&!Array.isArray(p2)){const po2=p2;if(po2.type==="input_text"&&typeof po2.text==="string"&&Object.keys(po2).length===2&&parseChainCheckpoint(po2.text)){content.splice(j2,1);removed++}}}if(removed>0){if(content.length===0)input.splice(i,1);stripped+=removed}}return stripped}const messages=body.messages;if(!Array.isArray(messages))return 0;for(let i=messages.length-1;i>=0;i--){const rec=messages[i];if(!rec||typeof rec!=="object"||Array.isArray(rec))continue;const m2=rec;if(m2.role!=="user"&&m2.role!=="assistant")continue;const content=m2.content;if(typeof content==="string"){if(parseChainCheckpoint(content)){messages.splice(i,1);stripped++}continue}if(!Array.isArray(content))continue;let removed=0;for(let j2=content.length-1;j2>=0;j2--){const p2=content[j2];if(p2&&typeof p2==="object"&&!Array.isArray(p2)){const po2=p2;if(po2.type==="text"&&typeof po2.text==="string"&&Object.keys(po2).length===2&&parseChainCheckpoint(po2.text)){content.splice(j2,1);removed++}}}if(removed>0){if(content.length===0)messages.splice(i,1);stripped+=removed}}return stripped}var ZERO_DIGEST="sha256:"+"0".repeat(64);function buildAcplikeName(){const cores=["acp","apc","cap","cpa","pac","pca"];const ci2=ch=>`[${ch}${ch.toUpperCase()}]`;const attestedDrift=["[aA][cC][cC][eE][sS][sS][pP]","[aA][cC][aA][cC][pP]","[aA][cC][bB]"];const fourLetter=new Set;const threeLetter=new Set;for(const c of cores){threeLetter.add(ci2(c.charAt(0))+ci2(c.charAt(1))+ci2(c.charAt(2)));for(let pos=0;pos<=c.length;pos++){fourLetter.add(c.slice(0,pos).split("").map(ci2).join("")+"[aAcCpPiI]"+c.slice(pos).split("").map(ci2).join(""))}}return[...attestedDrift,...fourLetter,...threeLetter].join("|")}var ACP_NAME_ALT=`(?:${buildAcplikeName()})`;var NAME=ACP_NAME_ALT;var REF_TOKEN="m\\d{4,}";var REFS_RUN=REF_TOKEN+"(?:\\s*(?:[\u2013\u2014,-]\\s*)?"+REF_TOKEN+")*";var REFS_ONLY=new RegExp("^\\s*"+REFS_RUN+"\\s*$");var PENDING_REF_SPAN=new RegExp("^\\s*"+REFS_RUN+"(?:\\s*(?:[\\u2013\\u2014,\\-]\\s*)?(?:m\\d{0,3})?)?\\s*$");var PAIRED_BODY="\\s*(?:"+REFS_RUN+")?\\s*";var PAIRED=new RegExp("<"+NAME+"(?:\\s[^<>]*)?>("+PAIRED_BODY+")<\\/"+NAME+">");var ORPHAN_REF_CLOSE=new RegExp("(?<![\\w>])"+REFS_RUN+"\\s*<\\/"+NAME+"(?=[\\s>])[^<>]{0,32}>");var ORPHAN_RUN_BEFORE=new RegExp("(?<![\\w>])"+REFS_RUN+"\\s*$");var LONE_OPEN=new RegExp("<"+NAME+"(?:\\s[^<>]*)?>");var LONE_CLOSE=new RegExp("<\\/"+NAME+"(?=[\\s>])[^<>]{0,32}>");var DEGEN_PAIR=new RegExp("<"+NAME+"(?:\\s[^<>]*)?>\\s*m\\d{4,}\\s*<\\/[^<>]{1,32}>","g");var SELF_CLOSE=new RegExp("<"+NAME+"(?:\\s[^<>]*)?\\/>");var PARTIAL_TAIL=new RegExp("(<"+NAME+"\\s[^<>]*|<"+NAME+"\\s*=\\s*[^<>]*|<\\/"+NAME+"(?:\\s[^<>]{0,32})?|<\\/?[aAcCpPiI]*(?:/)?|(?<![\\w>])\\s*"+REFS_RUN+"\\s*<[^<>]*|(?<![\\w>])\\s*"+REFS_RUN+"(?:\\s*(?:[\\u2013\\u2014,\\-]\\s*)?(?:m\\d{0,3})?)?\\s*|(?<![\\w>])\\s*m\\d{0,3})$");var TRUNC_OPEN=new RegExp("<"+NAME+"\\s[^<>]*$|<"+NAME+"\\s*=\\s*[^<>]*$");var TRUNC_CLOSE=new RegExp("<\\/"+NAME+"(?:\\s[^<>]{0,32})?$");var TRUNC_REF_CLOSE=new RegExp("m\\d{4,}\\s*\\x3c\\/([a-zA-Z]{0,32})$");var DEAD_REF_CLOSE=new RegExp("(?<![\\w>])m\\d{4,}\\s*\\x3c\\/[a-zA-Z]{0,32}(?![a-zA-Z])(?![^\\x3c\\x3e]{0,32}\\x3e)","g");var BROKEN_ATTRS=new RegExp("<"+NAME+"\\s[^<>]*(?=<)");var MANGLED_OPEN=new RegExp("<"+NAME+"\\s*=\\s*[^<>]*>");var DEFINITE_TAIL=new RegExp("^<"+NAME+"\\s|^<"+NAME+"=|^<\\/"+NAME);var OPEN_WITH_ATTRS=new RegExp("^<"+NAME+"\\s");var CLOSE_NAME_ANCHORED=new RegExp("^"+NAME);var MARKER_HEAD=new RegExp("^\\p{So}(?:[ \\t])?\\[ACP\\]","u");var MARKER_LINE=new RegExp("^\\p{So}(?:[ \\t])?\\[ACP\\][^\\n]*\\n?","gmu");function stripMarkerLines(text){return text.replace(MARKER_LINE,"")}var MARKER_LINE_PROBE=new RegExp(MARKER_LINE.source,"mu");var RENDER_TAG_DETECT=new RegExp("<\\/?"+NAME+"(?=[\\s>])|\\\\u003c\\/?"+NAME+"(?=[\\s>\\\\])|<"+NAME+"\\s*\\/|\\\\u003c"+NAME+"\\s*\\/");var BROAD_TAG_HEAD_TAIL=new RegExp("<\\/?[A-Za-z0-9]{0,16}$");var RAW_WS="(?:\\\\[a-z]|\\s|\\\\)*";var TC_PARAM_REF_RAW=new RegExp(`\\x3c(?:antml:)?parameter(?:\\s*=\\s*["']?ref["']?|\\s+name\\s*=\\s*["']ref["'])?[^<>]*\\x3e`+RAW_WS+"m\\d{4,}"+RAW_WS+"\\x3c\\/(?:antml:)?parameter","i");var CHAIN_OPEN_ESCAPED="\\u003c"+TAG_OPEN2.slice(1);function reEscape(s3){return s3.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function prefixAlts(s3,minLen){const out=[];for(let k2=minLen;k2<s3.length;k2++)out.push(reEscape(s3.slice(0,k2)));return out}var CHAIN_PARTIAL_TAIL=new RegExp("("+[...new Set([...prefixAlts(TAG_OPEN2,1),reEscape(TAG_OPEN2),...prefixAlts(CHAIN_OPEN_ESCAPED,1),reEscape(CHAIN_OPEN_ESCAPED)])].join("|")+")$");var HEAD_PREFIX_TAIL=new RegExp("(?:^|\n)("+[...new Set([...prefixAlts(CODEX_FORGED_HANDOFF_HEADER,1),...prefixAlts(FORGED_SUMMARY_HEADER,1)])].join("|")+")$");var TAG_PARTIAL_TAIL=new RegExp("(<"+NAME+"\\s[^<>]*|<\\/"+NAME+"(?:\\s[^<>]{0,32})?|<\\/?[aAcCpPiI]*(?:/)?)$");var PANEL_BOX_TOP="\u256D";var PANEL_BOX_TITLE="ACP Context Analysis";var PANEL_BOX_FOOTER="Tag visibility: tags injected to LLM only (deep copy), not persisted in session, not shown in terminal.";var PANEL_FALLBACK_HEADER="\u{1F4CA} ACP status";var CACHE_REPORT_OPEN="[acp-cache]";var CACHE_REPORT_CLOSE="[/acp-cache]";var RULE_REPORT_OPEN="[acp-rule]";var RULE_REPORT_CLOSE="[/acp-rule]";var STATUS_REPORT_OPEN="[acp-status]";var STATUS_REPORT_CLOSE="[/acp-status]";function wrapCacheReport(report){return`${CACHE_REPORT_OPEN}
|
|
353
|
+
`;function runOwnerHeartbeatWorker(origin,pid,intervalMs,spawn3=(source,workerData)=>new Worker3(source,{eval:true,workerData})){const existing=ownerHeartbeatWorkers.get(origin);if(existing!==void 0){existing.refs+=1;let released2=false;return()=>{if(released2)return;released2=true;existing.refs-=1}}let stopped=false;let worker;let fallbackStop;try{const beatWorker=spawn3(OWNER_HEARTBEAT_WORKER_SOURCE,{origin,pid,intervalMs,timeoutMs:OWNER_HEARTBEAT_POST_TIMEOUT_MS});beatWorker.on("message",message=>{if(message==="ack")noteWatcherHeartbeatAck(origin);beatWorker.unref()});beatWorker.on("error",()=>{if(!stopped&&fallbackStop===void 0){fallbackStop=runOwnerHeartbeatLoop(defaultOwnerPost(origin),pid,intervalMs,origin)}});beatWorker.unref();worker=beatWorker}catch{return runOwnerHeartbeatLoop(defaultOwnerPost(origin),pid,intervalMs,origin)}const entry={refs:1,stop:()=>{}};const stop=()=>{if(stopped)return;stopped=true;ownerHeartbeatWorkers.delete(origin);watcherPendingRecovery.delete(origin);try{worker?.postMessage("stop")}catch{}setTimeout(()=>{void worker?.terminate()},50).unref?.();fallbackStop?.()};entry.stop=stop;ownerHeartbeatWorkers.set(origin,entry);let released=false;return()=>{if(released)return;released=true;entry.refs-=1;if(entry.refs<=0)entry.stop()}}function defaultOwnerPost(origin){return async body=>{const res=await fetch(`${origin}/__bili/watcher`,{method:"POST",headers:{"content-type":"application/json"},body,signal:AbortSignal.timeout(OWNER_HEARTBEAT_POST_TIMEOUT_MS)});return res.ok}}async function ensureProxyRunning(opts,deps={}){const fetchImpl=deps.fetchImpl??defaultFetch;const fetchHealthInfo=deps.fetchHealthInfo??fetchHealthInfoDefault;const fetchDetail=deps.fetchDetailImpl??defaultFetchDetail;const readInstance=deps.readInstanceFile??readProxyInstanceFile;const listRegistry=deps.listRegistryInstances??discoverLiveInstances;const spawnImpl=deps.spawnImpl??spawn2;const now=deps.now??Date.now;const sleepImpl=deps.sleep??(ms2=>new Promise(r=>setTimeout(r,ms2)));const registerWatcher=deps.registerWatcher??registerWatcherDefault;const attachExternal=(deps.resolveAttachExternal??resolveNativeAttachExternal)();const foreignLanes=(deps.attachLanePriority??resolveNativeAttachLanePriority)();const attachPolicy=(deps.resolveAttachPolicy??resolveNativeAttachPolicy)();const attachUrl=(deps.resolveAttachUrl??resolveNativeAttachUrl)();const refusedLog=new Set;const attachDiag=deps.attachDiag??defaultAttachDiag(opts.debug);const watchPid=opts.parentPid??process.pid;const registerOwner=async inst=>{let reg=await registerWatcher(inst.origin,watchPid);for(let attempt=1;reg==="failed"&&attempt<WATCHER_REG_ATTEMPTS;attempt++){await sleepImpl(WATCHER_REG_RETRY_BACKOFF_MS);reg=await registerWatcher(inst.origin,watchPid)}return reg};const attachTo=async inst=>{attachDiag(`bili: attaching to running proxy at ${inst.origin} (pid ${inst.pid})`);const reg=await registerOwner(inst);startOwnerHeartbeat(inst.origin,watchPid);const handle={origin:inst.origin,port:inst.port,attached:true,watcherRegistration:reg};if(reg==="refused")handle.refusedWatcher=true;if(reg==="failed"){markWatcherPendingRecovery(inst.origin,watchPid,attachDiag)}else{watcherPendingRecovery.delete(inst.origin)}return handle};const script=deps.scriptPath??process.argv[1];const codeFingerprint=entryScriptFingerprint(script);const probed=await probeLiveInstances(readInstance,fetchHealthInfo,attachDiag,deps?.isConnectable??tcpConnectable);const existing=pickAttachable(probed,opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,attachDiag,foreignLanes);if(existing){return attachTo(existing)}if(attachUrl!==void 0&&existing===void 0){const target=probed.find(c=>normalizeOrigin(c.inst.origin)===normalizeOrigin(attachUrl));let msg;if(target!==void 0){const reason=instanceCompatible(target.inst,opts,codeFingerprint,foreignLanes);const remedy=reason==="code-fingerprint-mismatch"?"the target runs different bili bytes than this lane (typical: global install vs host-managed copy right after an update). A target that reports a STRICTLY NEWER build attaches automatically \u2014 reaching this message means it reports the same or an older build: align the two installs (restart the host once its copy converges), or stop the target":reason!==void 0?`config shape mismatch (${reason}) \u2014 align the target's launch config with this lane's, or stop the target`:"it passes compatibility but fails the lifecycle gate (no armed watchdog) \u2014 set native.attachExternal=true or BILI_NATIVE_ATTACH_EXTERNAL=1 to attach anyway";msg=`bili: explicit attach target ${attachUrl} (pid ${target.inst.pid}) is not attachable: ${reason??"lifecycle gate"} \u2014 ${remedy}`}else{msg=`bili: no live instance registered at the explicit attach target ${attachUrl} \u2014 the proxy there never published an instance record or its owner pid is dead; check its startup log`}console.error(msg);attachDiag(msg)}const resolveTargetPort=()=>{const rotLane=opts.lane!==void 0&&opts.port<=0?opts.lane:void 0;return opts.port>0?opts.port:rotLane!==void 0?(deps?.zonePreferredPort??lanePreferredPort)(rotLane):void 0};{await rotateStalePredecessor(probed,resolveTargetPort,opts,attachUrl,foreignLanes,deps?.fetchHealthInfoNoReuse??(origin=>fetchHealthInfoDefault(origin,{noKeepAlive:true})),now,sleepImpl,deps?.requestInstanceShutdown??requestInstanceShutdown)}{await resolveWedgedSameLaneHolder(probed,resolveTargetPort,opts,attachUrl,foreignLanes,codeFingerprint,deps?.wedgedLedgerPath?.()??wedgedLedgerFilePath(),deps?.processBirthStamp??(pid=>processBirthStamp(pid)),now,sleepImpl,deps?.requestInstanceShutdown??requestInstanceShutdown,deps?.isConnectable??tcpConnectable,deps?.signalWedgedHolder??signalWedgedHolderDefault,deps?.killWedgedHolder??killWedgedHolderDefault,attachDiag)}if(!attachExternal&&opts.strictPort){const squatter=probed.find(c=>c.inst.port===opts.port&&instanceCompatible(c.inst,opts,codeFingerprint,foreignLanes)===void 0);if(squatter){throw new Error(`bili: port ${opts.port} is held by a lifecycle-less bili proxy at ${squatter.inst.origin} (pid ${squatter.inst.pid}) \u2014 the #1335 attach gate refuses it by default and this launch pins the port, so no session-owned proxy can bind it either. Kill that process (kill ${squatter.inst.pid}) or set native.attachExternal=true / BILI_NATIVE_ATTACH_EXTERNAL=1 to attach to it anyway.`)}}const waitForOtherStarter=async()=>{attachDiag("bili: another bili launch is bringing up a proxy \u2014 waiting for it instead of spawning a second");const waited=await waitForStarterInstance(readInstance,fetchHealthInfo,now,sleepImpl,opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,attachDiag,foreignLanes,deps?.isConnectable??tcpConnectable);if(waited){return attachTo(waited)}return void 0};const starterLaneMatches=m2=>opts.lane===void 0||m2.lane===void 0||m2.lane===opts.lane;const marker=readStartingMarker();if(marker){if(!isStartingMarkerActive(marker,now())){removeStartingMarker()}else if(starterLaneMatches(marker)){const attached=await waitForOtherStarter();if(attached)return attached}}const launchToken=randomUUID7();const zoneLane=opts.lane!==void 0&&opts.port<=0?opts.lane:void 0;const preferredPort=deps?.zonePreferredPort??lanePreferredPort;const port=opts.port>0?opts.port:zoneLane!==void 0?preferredPort(zoneLane):await pickEphemeralPort(opts.host);const settleZonePort=settled=>{if(zoneLane!==void 0)(deps?.writeZonePort??writeZonePort)(zoneLane,settled)};if(!script)throw new Error("bili: cannot resolve launcher script path");const logPath2=path27.join(os9.tmpdir(),`bili-proxy-${port}.log`);rotatePortLogIfNeeded(logPath2);const logFd=fs14.openSync(logPath2,"a");let spawnLogOffset=0;try{spawnLogOffset=fs14.fstatSync(logFd).size}catch{}const claimMarker=()=>claimStartingMarker({token:launchToken,pid:process.pid,host:opts.host,port,startedAt:now(),lane:opts.lane});let claimed=claimMarker();if(!claimed){const holder=readStartingMarker();if(holder&&isStartingMarkerActive(holder,now())){if(starterLaneMatches(holder)){const attached=await waitForOtherStarter();if(attached)return attached;claimed=claimMarker()}}else{removeStartingMarker();claimed=claimMarker()}}try{let child;const runtime=deps.nodeRuntime??resolveNodeRuntime();try{child=spawnImpl(runtime,[script,...proxyStartArgs({...opts,port})],{detached:true,windowsHide:true,stdio:["ignore",logFd,logFd],env:{...stripInheritedLauncherChannels(stripInheritedProxy(process.env)),...captureInheritedProxyEnv(process.env),...process.versions.electron?{ELECTRON_RUN_AS_NODE:"1"}:{},BILI_LAUNCH_TOKEN:launchToken,BILI_PARENT_PID:String(opts.parentPid??process.pid),...opts.lane?{BILI_LAUNCHER_LANE:opts.lane}:{},...opts.mitmDomains&&opts.mitmDomains.length?{BILI_MITM_DOMAINS:opts.mitmDomains.join(",")}:{},...opts.modelWindows&&Object.keys(opts.modelWindows).length>0?{BILI_LAUNCHER_MODEL_WINDOWS:JSON.stringify(opts.modelWindows)}:{},...opts.modelMaxOutputs&&Object.keys(opts.modelMaxOutputs).length>0?{BILI_LAUNCHER_MODEL_MAX_OUTPUTS:JSON.stringify(opts.modelMaxOutputs)}:{},...opts.strictPort?{BILI_STRICT_PORT:"1"}:{},...codeFingerprint!==void 0?{[SPAWN_FINGERPRINT_ENV]:codeFingerprint}:{}}})}finally{try{fs14.closeSync(logFd)}catch{}}try{child.unref?.()}catch{}let childExit;let childError;let squatterAnnounced=false;child.on?.("exit",(...rest)=>{childExit={code:typeof rest[0]==="number"?rest[0]:null,signal:typeof rest[1]==="string"?rest[1]:null}});child.on?.("error",(...rest)=>{childError=rest[0]});const logHeadSample=()=>{try{const size=fs14.statSync(logPath2).size;let start=spawnLogOffset;if(size<start)start=Math.max(0,size-256);const span=size-start;if(span<=0)return"";const len=Math.min(256,span);const off=span>len?start+(span-len):start;const label=span>len?"tail":"head";const fd=fs14.openSync(logPath2,"r");try{const buf=Buffer.alloc(len);const n=fs14.readSync(fd,buf,0,len,off);if(n===0)return"";let s3=buf.subarray(0,n).toString("utf8").replace(/\s+/g," ").trim();if(s3.length>200)s3=`${s3.slice(0,200)}\u2026`;return` \u2014 child output ${label}: "${s3}"`}finally{fs14.closeSync(fd)}}catch{return""}};const logTailSample=()=>{try{const size=fs14.statSync(logPath2).size;if(size>=spawnLogOffset&&size-spawnLogOffset<=256)return"";const start=size<spawnLogOffset?Math.max(0,size-256):Math.max(spawnLogOffset,size-256);const len=Math.min(256,size-start);if(len<=0)return"";const fd=fs14.openSync(logPath2,"r");try{const buf=Buffer.alloc(len);const n=fs14.readSync(fd,buf,0,len,start);if(n===0)return"";let s3=buf.subarray(0,n).toString("utf8").replace(/\s+/g," ").trim();if(s3.length>200)s3=`\u2026${s3.slice(s3.length-200)}`;return` \u2014 child output tail: "${s3}"`}finally{fs14.closeSync(fd)}}catch{return""}};const failureHint=()=>{try{const size=fs14.statSync(logPath2).size;const start=size<spawnLogOffset?Math.max(0,size-1024):Math.max(spawnLogOffset,size-1024);const len=Math.min(1024,size-start);if(len<=0)return"";const fd=fs14.openSync(logPath2,"r");try{const buf=Buffer.alloc(len);const n=fs14.readSync(fd,buf,0,len,start);if(n===0)return"";const hint=classifyStartupFailure(buf.subarray(0,n).toString("utf8"));return hint?` (${hint})`:""}finally{fs14.closeSync(fd)}}catch{return""}};const logTail=()=>{try{const size=fs14.statSync(logPath2).size;const rotatedFile=fs14.existsSync(`${logPath2}.old`);const rotated=rotatedFile?`; earlier output rotated to ${logPath2}.old`:"";if(size===0)return`, ${size} bytes \u2014 EMPTY, the child produced no output of its own${rotated}`;if(size===spawnLogOffset&&!rotatedFile)return`, ${size} bytes \u2014 this child appended nothing of its own (earlier content stays on disk until rotation)`;return`, ${size} bytes${rotated}${logHeadSample()}${logTailSample()}`}catch{return""}};const diagnosePort=async childAlive=>{const origin=proxyOrigin(opts.host,port);let info;let det={ok:false,detail:"probe error"};try{const[i,d2]=await Promise.all([fetchHealthInfo(origin),fetchDetail(healthUrl(origin))]);info=i;det=d2}catch{}const selfHealthy=Boolean(info?.ok&&child.pid!==void 0&&info.pid===child.pid);if(info?.ok){return selfHealthy?{text:`port ${port} finally answers healthy from our child (pid ${info.pid}) but its instance handshake never matched \u2014 check the instance-file/registry state dir`,selfHealthy}:{text:`port ${port} is held by a different process${info.pid!==void 0?` (pid ${info.pid})`:""} \u2014 the spawned child never bound it. Kill that process (kill ${info.pid??"?"}) or set native.attachExternal=true / BILI_NATIVE_ATTACH_EXTERNAL=1 to attach to it instead`,selfHealthy:false}}if(det.ok){return{text:`port ${port} answered but not with bili's health payload \u2014 a foreign service likely holds it`,selfHealthy:false}}const d=det.detail??"unknown error";if(/^(ECONNREFUSED|ECONNRESET|EHOSTUNREACH|ENETUNREACH|EPIPE)$/i.test(d)){return{text:`nothing is listening on port ${port} \u2014 the spawned child (${childAlive?"still alive":"already exited"}, pid ${child.pid??"?"}) never bound it`,selfHealthy:false}}if(/^HTTP \d{3}$/.test(d)){return{text:`port ${port} answered ${d} \u2014 the listener there is not reporting bili health`,selfHealthy:false}}if(/^timeout after \d+ms$/i.test(d)&&await(deps.isConnectable??tcpConnectable)(origin)){return{text:`port ${port} accepts TCP connections but never answers /__bili/health within the probe budget \u2014 the instance there is BUSY (event loop saturated, typically a large compression), not dead (#3654)`,selfHealthy:false}}return{text:`last health probe failed with ${d}`,selfHealthy:false}};const deadline=now()+SPAWN_BUDGET_MS;let slowStartNoticed=false;while(now()<deadline){if(childExit||childError!==void 0)break;if(!slowStartNoticed&&now()>=deadline-SLOW_START_GRACE_MS){slowStartNoticed=true;console.error(`bili: spawned proxy not healthy after ${SPAWN_WAIT_MS}ms \u2014 child pid ${child.pid??"?"} is still starting up; extending wait to ${SPAWN_BUDGET_MS}ms total (${(await diagnosePort(true)).text}) (log: ${logPath2}${logTail()})`)}await sleepImpl(HEALTH_POLL_INTERVAL_MS);const inst=readInstance();if(isProxyInstanceFile(inst)&&inst.launchToken===launchToken){if(await probeHealth(inst.origin,fetchImpl)){settleZonePort(inst.port);startOwnerHeartbeat(inst.origin,watchPid);return{origin:inst.origin,port:inst.port,child,logPath:logPath2}}continue}if(child.pid!==void 0){const mine=listRegistry().find(e=>e.pid===child.pid);if(mine&&mine.origin!==""&&await probeHealth(mine.origin,fetchImpl)){settleZonePort(mine.port);startOwnerHeartbeat(mine.origin,watchPid);return{origin:mine.origin,port:mine.port,child,logPath:logPath2}}}const stale=!isProxyInstanceFile(inst)||!isPidAlive(inst.pid);if(stale){const preferredOrigin=proxyOrigin(opts.host,port);const info=await fetchHealthInfo(preferredOrigin);if(info?.ok&&child.pid!==void 0&&info.pid===child.pid){settleZonePort(port);startOwnerHeartbeat(preferredOrigin,watchPid);return{origin:preferredOrigin,port,child,logPath:logPath2}}if(info?.ok&&!squatterAnnounced){squatterAnnounced=true;attachDiag(`bili: port ${port} answers health${info.pid!==void 0?` (pid ${info.pid})`:""} but is not the proxy this launcher spawned (child pid ${child.pid??"?"}) \u2014 waiting for the spawned instance to report its real origin; if that never happens, kill pid ${info.pid??"?"} or set native.attachExternal=true / BILI_NATIVE_ATTACH_EXTERNAL=1 to attach to the holder instead`)}}}const adoptServingTwin=async()=>{const candidates=(deps.listAdoptCandidates??discoverLiveInstances)().filter(inst=>isPidAlive(inst.pid)).sort((a,b2)=>Number(b2.port===port)-Number(a.port===port)||b2.startedAt-a.startedAt);for(const inst of candidates){let compatible=instanceCompatible(inst,opts,codeFingerprint,foreignLanes)===void 0;let adoptedNewerVersion;if(!compatible){const reported=await fetchHealthInfo(inst.origin);if(reported!==void 0&&isNewerSameLaneHolder(inst,opts.lane,reported.version,VERSION,isUserZoneInstance(inst))&&instanceShapeMismatch(inst,opts,foreignLanes)===void 0){compatible=true;adoptedNewerVersion=reported.version}}if(!compatible)continue;if(!await(deps.isConnectable??tcpConnectable)(inst.origin))continue;attachDiag(adoptedNewerVersion!==void 0?`bili: adopting serving twin ${inst.origin} (pid ${inst.pid}) \u2014 reports v${adoptedNewerVersion}, strictly NEWER than this lane's v${VERSION}: the older generation yields so this spawn rides the newer build instead of deadlocking behind it (#4125)`:`bili: adopting serving twin ${inst.origin} (pid ${inst.pid}) \u2014 the spawned child lost the #3044 duplicate race to it; requests ride the existing instance (#3654)`);return attachTo(inst)}return void 0};const rediscoverAfterChildExit=async()=>{console.error(`bili: spawned proxy exited before becoming healthy \u2014 re-checking for a late-publishing listener on port ${port} before failing`);const rediscoveryDeadline=now()+POST_EXIT_REDISCOVERY_MS;while(now()<rediscoveryDeadline){await sleepImpl(HEALTH_POLL_INTERVAL_MS);const probedAgain=await probeLiveInstances(readInstance,fetchHealthInfo,attachDiag,deps.isConnectable??tcpConnectable);const late=pickAttachable(probedAgain,opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,attachDiag,foreignLanes);if(late){attachDiag(`bili: attached to ${late.origin} (pid ${late.pid}) \u2014 it published its instance record after the initial discovery`);return attachTo(late)}}return void 0};if(childError!==void 0){const detail=childError instanceof Error?childError.message:String(childError);throw new Error(`bili: proxy spawn failed (${detail}) (runtime: ${runtime}) (log: ${logPath2})`)}if(childExit){if(childExit.code===TWIN_ADOPT_EXIT_CODE){const adopted=await adoptServingTwin();if(adopted!==void 0)return adopted;attachDiag("bili: serving-twin adoption failed verification \u2014 continuing with the standard post-exit re-discovery")}const retried=await rediscoverAfterChildExit();if(retried)return retried;const detail=childExit.code!==null?`code ${childExit.code}${childExit.code===TWIN_ADOPT_EXIT_CODE?" (twin-collision signal)":""}`:childExit.signal?`signal ${childExit.signal}`:"unknown reason";throw new Error(`bili: proxy child exited before becoming healthy (${detail}) \u2014 ${(await diagnosePort(false)).text} (runtime: ${runtime}) (log: ${logPath2}${logTail()})${failureHint()}`)}const childLogBoundOrigin=()=>{try{const size=fs14.statSync(logPath2).size;let start=spawnLogOffset;if(size<start)start=Math.max(0,size-8192);if(size<=start)return void 0;const fd=fs14.openSync(logPath2,"r");let seg;try{seg=Buffer.alloc(size-start);const n=fs14.readSync(fd,seg,0,seg.length,start);seg=seg.subarray(0,n)}finally{fs14.closeSync(fd)}const text=seg.toString("utf8");const re2=/\(pid (\d+), id [^)]+\) listening on (https?:\/\/\S+)/g;let m2;let last;while((m2=re2.exec(text))!==null)last=m2;if(!last||Number(last[1])!==child.pid)return void 0;const u2=new URL(last[2]);const p2=Number(u2.port);if(!Number.isInteger(p2)||p2<=0)return void 0;return{origin:u2.origin,port:p2}}catch{return void 0}};const diagnosis=await diagnosePort(true);if(diagnosis.selfHealthy){settleZonePort(port);startOwnerHeartbeat(proxyOrigin(opts.host,port),watchPid);attachDiag(`bili: adopting our own healthy child (pid ${child.pid}) at ${proxyOrigin(opts.host,port)} after ${SPAWN_BUDGET_MS}ms \u2014 the instance handshake never matched but the health probe proves this child serves the port; keeping it instead of killing (#4994)`);return{origin:proxyOrigin(opts.host,port),port,child,logPath:logPath2}}const bound=childLogBoundOrigin();if(bound){const info=await fetchHealthInfo(bound.origin);if(info?.ok&&info.pid===child.pid){settleZonePort(bound.port);startOwnerHeartbeat(bound.origin,watchPid);attachDiag(`bili: adopting our own healthy child (pid ${child.pid}) at ${bound.origin} after ${SPAWN_BUDGET_MS}ms \u2014 it bound ${bound.port} per its own listen line and answers health under our pid; keeping it instead of killing (#4994)`);return{origin:bound.origin,port:bound.port,child,logPath:logPath2}}}killAbandonedChild(child);console.error(`bili: killed spawned proxy (pid ${child.pid??"?"}) after ${SPAWN_BUDGET_MS}ms without health \u2014 ${diagnosis.text} (log: ${logPath2}${logTail()})`);throw new Error(`bili: proxy did not become healthy within ${SPAWN_BUDGET_MS}ms \u2014 ${diagnosis.text} (runtime: ${runtime}) (log: ${logPath2}${logTail()})${failureHint()}`)}finally{if(claimed)clearStartingMarker(launchToken)}}function hardKillProxyTree(pid,label){if(process.platform!=="win32"){try{process.kill(pid,"SIGKILL")}catch(err){if(err?.code!=="ESRCH"){log("warn",`bili: SIGKILL of ${label} ${pid} failed (${err instanceof Error?err.message:String(err)}) \u2014 its listener may survive the cleanup (#4125)`)}}return}let tkError;try{const tk=spawnSync3("taskkill",["/F","/T","/PID",String(pid)],{windowsHide:true,stdio:"ignore"});if(tk.error!==void 0)tkError=tk.error.message;else if(tk.status!==0)tkError=`exit ${tk.status}`}catch(err){tkError=err instanceof Error?err.message:String(err)}if(tkError!==void 0){log("warn",`bili: taskkill of ${label} ${pid} reported failure (${tkError}) \u2014 its listener may survive the cleanup (#4125)`)}try{process.kill(pid,"SIGKILL")}catch(err){if(err?.code!=="ESRCH"){log("warn",`bili: direct SIGKILL of ${label} ${pid} failed (${err instanceof Error?err.message:String(err)}) \u2014 its listener may survive the cleanup (#4125)`)}}}function signalWedgedHolderDefault(pid){if(process.platform==="win32")return;try{process.kill(pid,"SIGTERM")}catch{}}function killWedgedHolderDefault(pid){hardKillProxyTree(pid,"wedged holder")}function killAbandonedChild(child){if(!child||child.pid===void 0||child.pid<=0)return;if(process.platform!=="win32"){try{process.kill(-child.pid,"SIGKILL")}catch{}}hardKillProxyTree(child.pid,"abandoned proxy");try{child.kill?.("SIGKILL")}catch{log("warn",`bili: SIGKILL of abandoned proxy ${child.pid} via its own handle failed \u2014 it may survive the cleanup (#4125)`)}}var PATH_EXTS=process.platform==="win32"?[".cmd",".bat",".exe",""]:[""];init_util();import{createHash as createHash17}from"crypto";import{createHash as createHash16}from"crypto";function hashId2(s3){return createHash16("sha256").update(s3,"utf8").digest("hex").slice(0,16)}var CANONICAL_IMAGE_TEXT="[image]";var CANONICAL_REDACTED_THINKING_TEXT="[redacted_thinking]";function canonicalToolArgs(argsText){const trimmed=argsText.trim();if(!trimmed.startsWith("{")&&!trimmed.startsWith("["))return argsText;try{return JSON.stringify(canonicalize2(JSON.parse(trimmed)))}catch{return argsText}}function canonicalize2(v2){if(Array.isArray(v2))return v2.map(canonicalize2);if(v2!==null&&typeof v2==="object"){const src=v2;const out={};for(const k2 of Object.keys(src).sort())out[k2]=canonicalize2(src[k2]);return out}return v2}var idSalt=null;function deriveCanonicalMessageId(role,contentType,text,options={}){const seed=`${idSalt?idSalt+"|":""}${role}|${contentType}||${options.toolName??""}|${text}`+(options.mediaFingerprint!==void 0?`|${options.mediaFingerprint}`:"");return"h_"+hashId2(seed)}function imageMediaFingerprint(base64OrUrl){return hashId2(base64OrUrl)}function canonicalOpaqueSeed(item){if(item===null||typeof item!=="object")return hashId2(String(item));const src=item;const out={};for(const k2 of Object.keys(src)){if(k2==="id"||k2==="status")continue;out[k2]=src[k2]}return hashId2(JSON.stringify(out))}var ClusterCounter=class{counts=new Map;next(baseId){const n=this.counts.get(baseId)??0;this.counts.set(baseId,n+1);return n===0?baseId:`${baseId}_${n}`}};function anthropicToCore(body){const msgs=[];const cacheControls=new Map;const clusters=new ClusterCounter;const toolNames=new Map;for(const[wireIndex,m2]of body.messages.entries()){const before=msgs.length;if(m2.role==="system"){const core=systemMessageCore(m2,clusters);core.wireIndex=wireIndex;msgs.push(core);const mark=systemMessageMark(m2);if(mark)cacheControls.set(core.id,mark);continue}const blocks=typeof m2.content==="string"?[{type:"text",text:m2.content}]:m2.content;for(const b2 of blocks){switch(b2.type){case"text":{const base=deriveCanonicalMessageId(m2.role,"text",b2.text);const id=clusters.next(base);msgs.push({id,role:m2.role,contentType:"text",text:b2.text});if(b2.cache_control)cacheControls.set(id,b2.cache_control);break}case"tool_use":{const base=deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(safeStringify(b2.input)),{toolName:b2.name});const id=clusters.next(base);msgs.push({id,role:"assistant",contentType:"tool-call",toolName:b2.name,toolCallId:b2.id,text:safeStringify(b2.input)});toolNames.set(b2.id,b2.name);if(b2.cache_control)cacheControls.set(id,b2.cache_control);break}case"tool_result":{const hasNonText=Array.isArray(b2.content)&&b2.content.some(c=>c.type!=="text");const text=typeof b2.content==="string"?b2.content:b2.content.map(c=>c.type==="text"?c.text:"").join("\n");const name=toolNames.get(b2.tool_use_id);const base=deriveCanonicalMessageId("tool","tool-result",text,{toolName:name});const id=clusters.next(base);msgs.push({id,role:"tool",contentType:"tool-result",toolCallId:b2.tool_use_id,text,...name?{toolName:name}:{},...b2.is_error===true?{toolIsError:true}:{},...hasNonText?{rawAnthropicBlock:b2}:{}});if(b2.cache_control)cacheControls.set(id,b2.cache_control);break}case"thinking":{const base=deriveCanonicalMessageId("assistant","reasoning",b2.thinking);msgs.push({id:clusters.next(base),role:"assistant",contentType:"reasoning",text:b2.thinking,...b2.signature?{thinkingSignature:b2.signature}:{}});break}case"image":{const source=b2.source&&typeof b2.source==="object"&&!Array.isArray(b2.source)?b2.source:void 0;const mediaSidecar=source?.type==="base64"&&typeof source.media_type==="string"&&typeof source.data==="string"?{imageMediaType:source.media_type,imageBase64:source.data}:{};const base=deriveCanonicalMessageId(m2.role,"text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:source?.type==="base64"&&typeof source.data==="string"?imageMediaFingerprint(source.data):typeof source?.url==="string"?imageMediaFingerprint(source.url):void 0});msgs.push({id:clusters.next(base),role:m2.role,contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawAnthropicBlock:b2,...mediaSidecar});break}case"redacted_thinking":{const base=deriveCanonicalMessageId(m2.role,"text",CANONICAL_REDACTED_THINKING_TEXT);msgs.push({id:clusters.next(base),role:m2.role,contentType:"text",text:"[redacted_thinking]",rawAnthropicBlock:b2});break}default:{const unknownType=b2.type;const label=typeof unknownType==="string"?`[${unknownType}]`:"[unknown]";const base=deriveCanonicalMessageId(m2.role,"text",label);msgs.push({id:clusters.next(base),role:m2.role,contentType:"text",text:label,rawAnthropicBlock:b2});break}}}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}}return{msgs,cacheControls}}function systemMessageCore(m2,clusters){const label=systemMessageText(m2);const base=deriveCanonicalMessageId("system","text",label);return{id:clusters.next(base),role:"system",contentType:"text",text:label,rawAnthropicMessage:m2}}function systemMessageText(m2){const text=typeof m2.content==="string"?m2.content:m2.content.map(b2=>b2.type==="text"?b2.text:`[${b2.type}]`).join("\n");return text.length>0?text:"[system]"}function systemMessageMark(m2){if(typeof m2.content==="string")return void 0;let mark;for(const b2 of m2.content)if(b2.cache_control)mark=b2.cache_control;return mark}function safeStringify(v2){try{return JSON.stringify(v2??{})}catch{return"{}"}}var FORMS=[{open:"<think>\n",close:"\n</think>"},{open:"<thinking>\n",close:"\n</thinking>"},{open:"```thinking\n",close:"\n```"}];function splitDemotedThinking(content){let rest=content;const parts=[];for(;;){let matched=false;for(const form of FORMS){if(!rest.startsWith(form.open))continue;const end=rest.indexOf(form.close,form.open.length);if(end<0)continue;const inner=rest.slice(form.open.length,end);if(inner.length===0)continue;parts.push(inner);rest=rest.slice(end+form.close.length);if(rest.startsWith("\n"))rest=rest.slice(1);matched=true;break}if(!matched)break}if(parts.length===0)return null;return{reasoning:parts.join("\n"),text:rest}}function parseDataUrl(url){const m2=/^data:([^;,]+)(?:;base64)?,(.+)$/i.exec(url);if(!m2)return void 0;return{mediaType:m2[1],base64:m2[2]}}function imageFingerprintsOfParts(parts){const out=[];for(const part of parts){if(!part||typeof part!=="object")continue;const p2=part;if(p2.type!=="image_url")continue;const url=typeof p2.image_url?.url==="string"?p2.image_url.url:void 0;if(!url)continue;const parsed=parseDataUrl(url);out.push(imageMediaFingerprint(parsed?parsed.base64:url))}return out}function openaiToCore(body){const msgs=[];const systemParts=[];const clusters=new ClusterCounter;const toolNames=new Map;for(const[wireIndex,m2]of body.messages.entries()){const before=msgs.length;switch(m2.role){case"system":case"developer":{if(msgs.length===0){systemParts.push(stringContent(m2.content));break}const base=deriveCanonicalMessageId(m2.role,"text",stringContent(m2.content));msgs.push({id:clusters.next(base),role:"system",contentType:"text",text:stringContent(m2.content),originalRole:m2.role,rawOpenaiMessage:m2});break}case"user":{if(typeof m2.content==="string"||m2.content==null||!Array.isArray(m2.content)){const base=deriveCanonicalMessageId("user","text",typeof m2.content==="string"?m2.content:"");msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:typeof m2.content==="string"?m2.content:""});break}let lastTextCore=null;let leadingOpaque=[];let sawText=false;for(const part of m2.content){if(typeof part==="string"){const base=deriveCanonicalMessageId("user","text",part);lastTextCore={id:clusters.next(base),role:"user",contentType:"text",text:part};msgs.push(lastTextCore);sawText=true;continue}if(part?.type==="text"&&typeof part.text==="string"){const base=deriveCanonicalMessageId("user","text",part.text);lastTextCore={id:clusters.next(base),role:"user",contentType:"text",text:part.text};msgs.push(lastTextCore);sawText=true;continue}if(part?.type==="image_url"){const url=part.image_url?.url;const parsed=typeof url==="string"?parseDataUrl(url):void 0;const base=deriveCanonicalMessageId("user","text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:imageMediaFingerprint(parsed?parsed.base64:typeof url==="string"?url:"")});msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawOpenaiContent:part,...parsed?{imageMediaType:parsed.mediaType,imageBase64:parsed.base64}:{}});continue}if(lastTextCore){lastTextCore.rawOpenaiContentParts=[...lastTextCore.rawOpenaiContentParts??[],part]}else{leadingOpaque=[...leadingOpaque,part]}}if(leadingOpaque.length>0){if(sawText&&msgs.length>0){const firstTextCore=msgs.find((c,i)=>i>=before&&c.role==="user"&&c.contentType==="text"&&!c.rawOpenaiContent);const host=firstTextCore??msgs[msgs.length-1];host.rawOpenaiContentParts=[...leadingOpaque,...host.rawOpenaiContentParts??[]]}else{const base=deriveCanonicalMessageId("user","text","",{mediaFingerprint:imageFingerprintsOfParts(leadingOpaque).join(",")||void 0});msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:"",rawOpenaiContentParts:leadingOpaque})}}break}case"assistant":{const rawReasoning=m2.reasoning_content;const fieldPresent=typeof rawReasoning==="string";const fieldReasoning=fieldPresent?rawReasoning:"";let reasoning=fieldReasoning;let text=stringContent(m2.content);if(!reasoning){const split=splitDemotedThinking(text);if(split){reasoning=split.reasoning;text=split.text}}const blankEcho=fieldPresent&&reasoning.length===0;if(reasoning){const base=deriveCanonicalMessageId("assistant","reasoning",reasoning);msgs.push({id:clusters.next(base),role:"assistant",contentType:"reasoning",text:reasoning,reasoningContent:reasoning})}if(text){const base=deriveCanonicalMessageId("assistant","text",text);msgs.push({id:clusters.next(base),role:"assistant",contentType:"text",text,...blankEcho?{reasoningPresent:true}:{}})}if(Array.isArray(m2.tool_calls)){for(const tc of m2.tool_calls){const base=deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(tc.function.arguments??""),{toolName:tc.function.name});msgs.push({id:clusters.next(base),role:"assistant",contentType:"tool-call",toolName:tc.function.name,toolCallId:tc.id,text:tc.function.arguments??"",...blankEcho?{reasoningPresent:true}:{}});toolNames.set(tc.id,tc.function.name)}}break}case"tool":{const base=deriveCanonicalMessageId("tool","tool-result",stringContent(m2.content),{toolName:m2.name||toolNames.get(m2.tool_call_id??"")});const name=m2.name||toolNames.get(m2.tool_call_id??"");msgs.push({id:clusters.next(base),role:"tool",contentType:"tool-result",toolCallId:m2.tool_call_id??"",text:stringContent(m2.content),...name?{toolName:name}:{}});break}}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}}return{msgs,systemText:systemParts.join("\n\n")}}function stringContent(content){if(content==null)return"";if(typeof content==="string")return content;if(Array.isArray(content)){return content.map(p2=>typeof p2==="string"?p2:p2.type==="text"?p2.text??"":"").join("\n")}return""}var OPAQUE_ITEM_TYPES=new Set(["additional_tools","mcp_list_tools"]);function isOpaqueItem(item){return OPAQUE_ITEM_TYPES.has(item.type)}var EASY_INPUT_ROLES=new Set(["user","assistant","system","developer"]);function normalizeEasyInputItem(item){if(typeof item.type==="string")return item;if(EASY_INPUT_ROLES.has(String(item.role))){return{...item,type:"message"}}return item}function shouldDropAllReasoning(){return(process.env.ACP_REASONING_KEEP??"").trim().toLowerCase()==="none"}function partText(part){if(part.type==="input_text"||part.type==="output_text"){return typeof part.text==="string"?part.text:""}return""}function messageContent(content){return typeof content==="string"?content:content.map(partText).join("\n")}function userDisplayText(content,text){if(typeof content==="string")return text;const hasImage=content.some(part=>part.type==="input_image");const hasTextPart=content.some(part=>part.type==="input_text"||part.type==="output_text");return!text||hasImage&&!hasTextPart?"[image]":text}function reasoningText(item){const fromParts=(parts,type)=>{if(!Array.isArray(parts))return"";const texts=[];for(const part of parts){if(part&&typeof part==="object"&&"type"in part&&"text"in part){const rec=part;if(rec.type===type&&typeof rec.text==="string")texts.push(rec.text)}}return texts.join("\n")};const content="content"in item?item.content:void 0;const summary="summary"in item?item.summary:void 0;return fromParts(content,"reasoning_text")||fromParts(summary,"summary_text")}function responsesToCore(body){const msgs=[];const systemParts=[];const preamble=[];const customToolCallIds=new Set;const layout=[];let droppedReasoning=0;const clusters=new ClusterCounter;const toolNames=new Map;let idx=0;if(typeof body.instructions==="string"&&body.instructions.trim())systemParts.push(body.instructions);if(typeof body.input==="string"){const id=clusters.next(deriveCanonicalMessageId("user","text",body.input));msgs.push({id,role:"user",contentType:"text",text:body.input});return{msgs,systemParts,preamble,customToolCallIds,layout,droppedReasoning,stringInput:{original:body.input,coreId:id}}}let sysDevHead=true;let headRole;for(const[wireIndex,raw]of body.input.entries()){const item=normalizeEasyInputItem(raw);let coreId;const before=msgs.length;if(isOpaqueItem(item))preamble.push(item);switch(item.type){case"reasoning":{if(shouldDropAllReasoning()){droppedReasoning++;continue}const text=reasoningText(item);const rid=text.length>0?text:canonicalOpaqueSeed(item);coreId=clusters.next(deriveCanonicalMessageId("assistant","reasoning",rid));msgs.push({id:coreId,role:"assistant",contentType:"reasoning",text:rid,rawResponsesItem:item});break}case"message":{const message=item;const text=messageContent(message.content);if(message.role==="system"||message.role==="developer"){if(sysDevHead){headRole??=message.role;systemParts.push(text);idx++;continue}const midBase=deriveCanonicalMessageId(message.role,"text",text);msgs.push({id:clusters.next(midBase),role:"system",contentType:"text",text,originalRole:message.role,rawResponsesItem:item});break}else if(message.role==="user"||message.role==="assistant"&&text){const role2=message.role;const splittable=role2==="user"&&Array.isArray(message.content)&&message.content.length>1&&message.content.every(part=>typeof part==="object"&&part!==null&&(part.type==="input_text"||part.type==="output_text"||part.type==="input_image"));if(splittable){for(const rawPart of message.content){const part=typeof rawPart==="object"&&rawPart!==null?rawPart:void 0;if(!part)continue;if((part.type==="input_text"||part.type==="output_text")&&typeof part.text==="string"&&part.text.length>0){const base=deriveCanonicalMessageId("user","text",part.text);msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:part.text})}else if(part.type==="input_image"&&typeof part.image_url==="string"){const image=parseDataUrl(part.image_url);const base=deriveCanonicalMessageId("user","text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:imageMediaFingerprint(image?image.base64:part.image_url)});msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawResponsesItem:item,...image?{imageMediaType:image.mediaType,imageBase64:image.base64}:{}})}}break}let effText=text;if(role2==="assistant"){const split=splitDemotedThinking(text);if(split){msgs.push({id:clusters.next(deriveCanonicalMessageId("assistant","reasoning",split.reasoning)),role:"assistant",contentType:"reasoning",text:split.reasoning,rawResponsesItem:item});effText=split.text}}const hasImage=Array.isArray(message.content)&&message.content.some(part=>part.type==="input_image");if(effText||role2==="user"&&hasImage){const displayText=role2==="user"?userDisplayText(message.content,effText):effText;const mediaFingerprint=Array.isArray(message.content)?message.content.flatMap(part=>{if(part?.type==="input_image"&&typeof part.image_url==="string"){const raw2=part.image_url;const decoded=parseDataUrl(raw2);return[imageMediaFingerprint(decoded?decoded.base64:raw2)]}return[]}).join(",")||void 0:void 0;coreId=clusters.next(deriveCanonicalMessageId(role2,"text",displayText,{mediaFingerprint}));const imageUrl=Array.isArray(message.content)?message.content.find(part=>part.type==="input_image"&&typeof part.image_url==="string")?.image_url:void 0;const image=typeof imageUrl==="string"?parseDataUrl(imageUrl):void 0;msgs.push({id:coreId,role:role2,contentType:"text",text:displayText,rawResponsesItem:item,...image?{imageMediaType:image.mediaType,imageBase64:image.base64}:{}})}}break}case"function_call":{const call=item;coreId=clusters.next(deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(call.arguments??""),{toolName:call.name}));msgs.push({id:coreId,role:"assistant",contentType:"tool-call",toolName:call.name,toolCallId:call.call_id,text:call.arguments??"",rawResponsesItem:item});toolNames.set(call.call_id,call.name);break}case"function_call_output":{const output=item;const text=typeof output.output==="string"?output.output:JSON.stringify(output.output);coreId=clusters.next(deriveCanonicalMessageId("tool","tool-result",text,{toolName:toolNames.get(output.call_id)}));const name=toolNames.get(output.call_id);msgs.push({id:coreId,role:"tool",contentType:"tool-result",toolCallId:output.call_id,text,...name?{toolName:name}:{},rawResponsesItem:item});break}case"computer_call":case"computer_call_output":case"file_search_call":case"web_search_call":case"image_generation_call":case"code_interpreter_call":case"mcp_call":{const rid=canonicalOpaqueSeed(item);coreId=clusters.next(deriveCanonicalMessageId("assistant","responses-call",rid));msgs.push({id:coreId,role:"assistant",contentType:"reasoning",text:rid,rawResponsesItem:item});break}case"custom_tool_call":{const ctc=item;const callId=ctc.call_id??`call_${idx}`;customToolCallIds.add(callId);const argText=ctc.input??ctc.arguments??"";coreId=clusters.next(deriveCanonicalMessageId("assistant","tool-call",argText,{toolName:ctc.name??"custom"}));msgs.push({id:coreId,role:"assistant",contentType:"tool-call",toolName:ctc.name??"custom",toolCallId:callId,text:argText,rawResponsesItem:item});toolNames.set(callId,ctc.name??"custom");break}case"custom_tool_call_output":{const ctco=item;const callId=ctco.call_id??`call_${idx}`;customToolCallIds.add(callId);const outText=typeof ctco.output==="string"?ctco.output:JSON.stringify(ctco.output??"");coreId=clusters.next(deriveCanonicalMessageId("tool","tool-result",outText,{toolName:toolNames.get(callId)}));const name=toolNames.get(callId);msgs.push({id:coreId,role:"tool",contentType:"tool-result",toolCallId:callId,text:outText,...name?{toolName:name}:{},rawResponsesItem:item});break}default:if(!isOpaqueItem(item))preamble.push(item);break}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}const role=item.role;const isSysDevMsgItem=(item.type===void 0||item.type==="message")&&(role==="system"||role==="developer");if(!isSysDevMsgItem&&item.type!=="additional_tools"&&item.type!=="mcp_list_tools")sysDevHead=false;const produced=msgs.slice(before).map(m2=>m2.id);layout.push({original:item,...produced.length>0?{coreId:produced[0]}:{},...produced.length>1?{coreIds:produced}:{}});idx++}return{msgs,systemParts,preamble,customToolCallIds,layout,droppedReasoning,...headRole?{headRole}:{}}}function createSubagentNamespaces(){const anchors=new Map;return{namespaceFor(identityValue,instructions){if(typeof instructions!=="string"||instructions.trim().length===0)return identityValue;const fp=hashId2(instructions);const anchor=anchors.get(identityValue);if(anchor===void 0){anchors.set(identityValue,fp);return identityValue}return anchor===fp?identityValue:`${identityValue}|sub:${fp}`}}}var defaultNamespaces=createSubagentNamespaces();function detectWireFormat(payload){if(payload===null||typeof payload!=="object")return void 0;const p2=payload;if(Array.isArray(p2.contents))return"google";if(Array.isArray(p2.input))return"responses";const messages=p2.messages;if(!Array.isArray(messages))return void 0;if("system"in p2||"anthropic_version"in p2)return"anthropic";for(const m2 of messages){if(m2===null||typeof m2!=="object")continue;const c=m2.content;if(Array.isArray(c)){for(const b2 of c){if(b2&&typeof b2==="object"&&typeof b2.type==="string"){if(b2.type==="tool_use"||b2.type==="tool_result"||b2.type==="thinking")return"anthropic";if(b2.type==="text"&&"cache_control"in b2)return"anthropic"}}}if(Array.isArray(m2.tool_calls))return"openai";if(m2.role==="tool"&&typeof m2.tool_call_id==="string")return"openai";if(m2.role==="system"||m2.role==="developer")return"openai"}return"openai"}var DEFAULT_MAX_FUTURE_SKEW_MS=2*60*1e3;var DEFAULT_RECENT_CHECKPOINT_WINDOW_MS=10*60*1e3;var MAX_CHECKPOINT_CHARS=512;var TAG_OPEN2="<bili-chain ";var TAG_CLOSE2="/>";var ATTRS=["v","processor","issued-at","request-id","digest"];function validAttrValue(name,raw){switch(name){case"v":return/^\d+$/.test(raw)&&Number(raw)>=1;case"issued-at":return/^\d{1,16}$/.test(raw);case"processor":return/^[A-Za-z0-9._-]{1,64}$/.test(raw);case"request-id":return/^[A-Za-z0-9._:-]{1,64}$/.test(raw);case"digest":return/^sha256:[0-9a-f]{64}$/.test(raw)}}function parseChainCheckpoint(text){if(typeof text!=="string"||text.length===0||text.length>MAX_CHECKPOINT_CHARS)return null;if(!text.startsWith(TAG_OPEN2)||!text.endsWith(TAG_CLOSE2))return null;const inner=text.slice(TAG_OPEN2.length,-TAG_CLOSE2.length);const found={};for(const token of inner.split(/\s+/)){const m2=/^([a-z][a-z0-9-]*)="([^"]*)"$/.exec(token);if(!m2)return null;const name=m2[1];if(!ATTRS.includes(name))return null;if(Object.hasOwn(found,name))return null;found[name]=m2[2]}for(const attr of ATTRS){const raw=found[attr];if(raw===void 0||!validAttrValue(attr,raw))return null}return{v:Number(found.v),processor:found.processor,issuedAt:Number(found["issued-at"]),requestId:found["request-id"],digest:found.digest}}function stripEmbeddedChainCarriers(parsed,wire){if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed))return 0;const body=parsed;let stripped=0;if(wire==="google"){const contents=body.contents;if(!Array.isArray(contents))return 0;for(let i=contents.length-1;i>=0;i--){const c=contents[i];if(!c||typeof c!=="object"||Array.isArray(c))continue;const ct2=c;const role=typeof ct2.role==="string"?ct2.role:"user";if(role!=="user"&&role!=="model")continue;const parts=ct2.parts;if(!Array.isArray(parts))continue;let removed=0;for(let j2=parts.length-1;j2>=0;j2--){const p2=parts[j2];if(p2&&typeof p2==="object"&&!Array.isArray(p2)&&Object.keys(p2).length===1&&typeof p2.text==="string"){if(parseChainCheckpoint(p2.text)){parts.splice(j2,1);removed++}}}if(removed>0){if(parts.length===0)contents.splice(i,1);stripped+=removed}}return stripped}if(wire==="responses"){const input=body.input;if(!Array.isArray(input))return 0;for(let i=input.length-1;i>=0;i--){const item=input[i];if(!item||typeof item!=="object"||Array.isArray(item))continue;const it2=item;if(it2.type!=="message")continue;const role=typeof it2.role==="string"?it2.role:"";if(role!=="user"&&role!=="assistant")continue;const content=it2.content;if(typeof content==="string"){if(parseChainCheckpoint(content)){input.splice(i,1);stripped++}continue}if(!Array.isArray(content))continue;let removed=0;for(let j2=content.length-1;j2>=0;j2--){const p2=content[j2];if(p2&&typeof p2==="object"&&!Array.isArray(p2)){const po2=p2;if(po2.type==="input_text"&&typeof po2.text==="string"&&Object.keys(po2).length===2&&parseChainCheckpoint(po2.text)){content.splice(j2,1);removed++}}}if(removed>0){if(content.length===0)input.splice(i,1);stripped+=removed}}return stripped}const messages=body.messages;if(!Array.isArray(messages))return 0;for(let i=messages.length-1;i>=0;i--){const rec=messages[i];if(!rec||typeof rec!=="object"||Array.isArray(rec))continue;const m2=rec;if(m2.role!=="user"&&m2.role!=="assistant")continue;const content=m2.content;if(typeof content==="string"){if(parseChainCheckpoint(content)){messages.splice(i,1);stripped++}continue}if(!Array.isArray(content))continue;let removed=0;for(let j2=content.length-1;j2>=0;j2--){const p2=content[j2];if(p2&&typeof p2==="object"&&!Array.isArray(p2)){const po2=p2;if(po2.type==="text"&&typeof po2.text==="string"&&Object.keys(po2).length===2&&parseChainCheckpoint(po2.text)){content.splice(j2,1);removed++}}}if(removed>0){if(content.length===0)messages.splice(i,1);stripped+=removed}}return stripped}var ZERO_DIGEST="sha256:"+"0".repeat(64);function buildAcplikeName(){const cores=["acp","apc","cap","cpa","pac","pca"];const ci2=ch=>`[${ch}${ch.toUpperCase()}]`;const attestedDrift=["[aA][cC][cC][eE][sS][sS][pP]","[aA][cC][aA][cC][pP]","[aA][cC][bB]"];const fourLetter=new Set;const threeLetter=new Set;for(const c of cores){threeLetter.add(ci2(c.charAt(0))+ci2(c.charAt(1))+ci2(c.charAt(2)));for(let pos=0;pos<=c.length;pos++){fourLetter.add(c.slice(0,pos).split("").map(ci2).join("")+"[aAcCpPiI]"+c.slice(pos).split("").map(ci2).join(""))}}return[...attestedDrift,...fourLetter,...threeLetter].join("|")}var ACP_NAME_ALT=`(?:${buildAcplikeName()})`;var NAME=ACP_NAME_ALT;var REF_TOKEN="m\\d{4,}";var REFS_RUN=REF_TOKEN+"(?:\\s*(?:[\u2013\u2014,-]\\s*)?"+REF_TOKEN+")*";var REFS_ONLY=new RegExp("^\\s*"+REFS_RUN+"\\s*$");var PENDING_REF_SPAN=new RegExp("^\\s*"+REFS_RUN+"(?:\\s*(?:[\\u2013\\u2014,\\-]\\s*)?(?:m\\d{0,3})?)?\\s*$");var PAIRED_BODY="\\s*(?:"+REFS_RUN+")?\\s*";var PAIRED=new RegExp("<"+NAME+"(?:\\s[^<>]*)?>("+PAIRED_BODY+")<\\/"+NAME+">");var ORPHAN_REF_CLOSE=new RegExp("(?<![\\w>])"+REFS_RUN+"\\s*<\\/"+NAME+"(?=[\\s>])[^<>]{0,32}>");var ORPHAN_RUN_BEFORE=new RegExp("(?<![\\w>])"+REFS_RUN+"\\s*$");var LONE_OPEN=new RegExp("<"+NAME+"(?:\\s[^<>]*)?>");var LONE_CLOSE=new RegExp("<\\/"+NAME+"(?=[\\s>])[^<>]{0,32}>");var DEGEN_PAIR=new RegExp("<"+NAME+"(?:\\s[^<>]*)?>\\s*m\\d{4,}\\s*<\\/[^<>]{1,32}>","g");var SELF_CLOSE=new RegExp("<"+NAME+"(?:\\s[^<>]*)?\\/>");var PARTIAL_TAIL=new RegExp("(<"+NAME+"\\s[^<>]*|<"+NAME+"\\s*=\\s*[^<>]*|<\\/"+NAME+"(?:\\s[^<>]{0,32})?|<\\/?[aAcCpPiI]*(?:/)?|(?<![\\w>])\\s*"+REFS_RUN+"\\s*<[^<>]*|(?<![\\w>])\\s*"+REFS_RUN+"(?:\\s*(?:[\\u2013\\u2014,\\-]\\s*)?(?:m\\d{0,3})?)?\\s*|(?<![\\w>])\\s*m\\d{0,3})$");var TRUNC_OPEN=new RegExp("<"+NAME+"\\s[^<>]*$|<"+NAME+"\\s*=\\s*[^<>]*$");var TRUNC_CLOSE=new RegExp("<\\/"+NAME+"(?:\\s[^<>]{0,32})?$");var TRUNC_REF_CLOSE=new RegExp("m\\d{4,}\\s*\\x3c\\/([a-zA-Z]{0,32})$");var DEAD_REF_CLOSE=new RegExp("(?<![\\w>])m\\d{4,}\\s*\\x3c\\/[a-zA-Z]{0,32}(?![a-zA-Z])(?![^\\x3c\\x3e]{0,32}\\x3e)","g");var BROKEN_ATTRS=new RegExp("<"+NAME+"\\s[^<>]*(?=<)");var MANGLED_OPEN=new RegExp("<"+NAME+"\\s*=\\s*[^<>]*>");var DEFINITE_TAIL=new RegExp("^<"+NAME+"\\s|^<"+NAME+"=|^<\\/"+NAME);var OPEN_WITH_ATTRS=new RegExp("^<"+NAME+"\\s");var TOOL_TYPE_ATTR=`\\s+[tT][yY][pP][eE]\\s*=\\s*["']\\s*[tT][oO][oO][lL]:`;var TOOL_TYPE_ATTR_RE=new RegExp(TOOL_TYPE_ATTR);var TOOL_TYPED_OPEN=new RegExp("<"+NAME+"(?:\\s[^<>]*?)?"+TOOL_TYPE_ATTR+"[^<>]*[^/<>]>");var TOOL_TYPED_PAIR=new RegExp(TOOL_TYPED_OPEN.source+"[\\s\\S]*?<\\/"+NAME+">");var CLOSE_NAME_ANCHORED=new RegExp("^"+NAME);var MARKER_HEAD=new RegExp("^\\p{So}(?:[ \\t])?\\[ACP\\]","u");var MARKER_LINE=new RegExp("^\\p{So}(?:[ \\t])?\\[ACP\\][^\\n]*\\n?","gmu");function stripMarkerLines(text){return text.replace(MARKER_LINE,"")}var MARKER_LINE_PROBE=new RegExp(MARKER_LINE.source,"mu");var RENDER_TAG_DETECT=new RegExp("<\\/?"+NAME+"(?=[\\s>])|\\\\u003c\\/?"+NAME+"(?=[\\s>\\\\])|<"+NAME+"\\s*\\/|\\\\u003c"+NAME+"\\s*\\/");var BROAD_TAG_HEAD_TAIL=new RegExp("<\\/?[A-Za-z0-9]{0,16}$");var RAW_WS="(?:\\\\[a-z]|\\s|\\\\)*";var TC_PARAM_REF_RAW=new RegExp(`\\x3c(?:antml:)?parameter(?:\\s*=\\s*["']?ref["']?|\\s+name\\s*=\\s*["']ref["'])?[^<>]*\\x3e`+RAW_WS+"m\\d{4,}"+RAW_WS+"\\x3c\\/(?:antml:)?parameter","i");var CHAIN_OPEN_ESCAPED="\\u003c"+TAG_OPEN2.slice(1);function reEscape(s3){return s3.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function prefixAlts(s3,minLen){const out=[];for(let k2=minLen;k2<s3.length;k2++)out.push(reEscape(s3.slice(0,k2)));return out}var CHAIN_PARTIAL_TAIL=new RegExp("("+[...new Set([...prefixAlts(TAG_OPEN2,1),reEscape(TAG_OPEN2),...prefixAlts(CHAIN_OPEN_ESCAPED,1),reEscape(CHAIN_OPEN_ESCAPED)])].join("|")+")$");var HEAD_PREFIX_TAIL=new RegExp("(?:^|\n)("+[...new Set([...prefixAlts(CODEX_FORGED_HANDOFF_HEADER,1),...prefixAlts(FORGED_SUMMARY_HEADER,1)])].join("|")+")$");var TAG_PARTIAL_TAIL=new RegExp("(<"+NAME+"\\s[^<>]*|<\\/"+NAME+"(?:\\s[^<>]{0,32})?|<\\/?[aAcCpPiI]*(?:/)?)$");var PANEL_BOX_TOP="\u256D";var PANEL_BOX_TITLE="ACP Context Analysis";var PANEL_BOX_FOOTER="Tag visibility: tags injected to LLM only (deep copy), not persisted in session, not shown in terminal.";var PANEL_FALLBACK_HEADER="\u{1F4CA} ACP status";var CACHE_REPORT_OPEN="[acp-cache]";var CACHE_REPORT_CLOSE="[/acp-cache]";var RULE_REPORT_OPEN="[acp-rule]";var RULE_REPORT_CLOSE="[/acp-rule]";var STATUS_REPORT_OPEN="[acp-status]";var STATUS_REPORT_CLOSE="[/acp-status]";function wrapCacheReport(report){return`${CACHE_REPORT_OPEN}
|
|
354
354
|
${report}
|
|
355
355
|
${CACHE_REPORT_CLOSE}`}function isAcpPanelText(text){const t=text.trim();if(t.length===0)return false;return isBoxPanel(t)||isFallbackPanel(t)||isCacheReport(t)||isRuleReport(t)}function isCacheReport(t){return t.startsWith(CACHE_REPORT_OPEN)&&t.endsWith(CACHE_REPORT_CLOSE)}function isRuleReport(t){return t.startsWith(RULE_REPORT_OPEN)&&t.endsWith(RULE_REPORT_CLOSE)}function isBoxPanel(t){return t.startsWith(PANEL_BOX_TOP)&&t.includes(PANEL_BOX_TITLE)&&t.endsWith(PANEL_BOX_FOOTER)}function isFallbackPanel(t){const lines=t.split("\n");if(lines[0]!==PANEL_FALLBACK_HEADER)return false;for(let i=1;i<lines.length;i++){const line=lines[i];if(line.length>0&&!line.startsWith(" "))return false}return true}function messageText(content){if(typeof content==="string")return content;if(Array.isArray(content)){let joined="";for(const part of content){const p2=part;if(p2===null||typeof p2!=="object")return void 0;const pt2=p2.type;if(pt2!==void 0&&pt2!=="text"&&pt2!=="input_text")return void 0;if(typeof p2.text==="string")joined+=p2.text}return joined}return void 0}function stripAcpPanelMessages(messages){if(!Array.isArray(messages))return 0;let stripped=0;for(let i=messages.length-1;i>=0;i--){const rec=messages[i];if(rec===null||typeof rec!=="object")continue;if(rec.role!=="user")continue;const text=messageText(rec.content);if(text!==void 0&&isAcpPanelText(text)){messages.splice(i,1);stripped++}}return stripped}var STATUS_MARKER_HEAD=new RegExp("^\\p{So}(?:[ \\t])?\\[ACP\\] acp_status result:","u");function stripAcpPanelResponsesInput(input){if(!Array.isArray(input))return 0;let stripped=0;for(let i=input.length-1;i>=0;i--){const rec=input[i];if(rec===null||typeof rec!=="object")continue;const type=rec.type;if(type!=="message"&&type!==void 0)continue;if(rec.role!=="user")continue;const text=messageText(rec.content);if(text!==void 0&&isAcpPanelText(text)){input.splice(i,1);stripped++}}return stripped}async function showAcpText(ctx,sid,text){const session=ctx.client?.session;if(!session||typeof session.prompt!=="function"){console.error("[bili-opencode] /acp render failed: session.prompt unavailable");return}try{await session.prompt({path:{id:sid},body:{noReply:true,parts:[{type:"text",text,ignored:true}]}})}catch(err){console.error(`[bili-opencode] /acp render failed: ${err instanceof Error?err.message:String(err)}`)}}function createAcpCommandHooks(getProxyBase,ctx){return{config:async opencodeConfig=>{opencodeConfig.command??={};opencodeConfig.command["acp"]={template:"",description:"Show ACP status (billion-context proxy)"};opencodeConfig.command["acp-cache"]={template:"",description:"Prompt-cache reconciliation for this session (same report as the acp_cache tool). Usage: /acp-cache [full]"}},"command.execute.before":async input=>{if(input.command!=="acp"&&input.command!=="acp-cache")return;const sid=input.sessionID;const proxyBase2=getProxyBase();let text;if(proxyBase2===void 0||proxyBase2.length===0){text=input.command==="acp-cache"?"bili: no bili proxy detected \u2014 /acp-cache needs the proxy to run the cache report (launch opencode through `bili opencode` or install the native plugin)":"bili: proxy not running (native bootstrap failed) \u2014 model traffic goes direct"}else if(input.command==="acp-cache"){const toolArgs=/(^|\s)(--)?full(\s|$)/.test(input.arguments??"")?{detail:"full"}:{};try{const report=await forwardTool(proxyBase2,sid,"acp_cache",toolArgs,void 0,true);await showAcpText(ctx,sid,wrapCacheReport(report.text))}catch(err){const msg=err instanceof Error?err.message:String(err);text=msg.includes("no model request has arrived")?"bili: no ACP session yet for this conversation (send a model request first, then run /acp-cache)":`bili: cache report failed (${msg})`;await showAcpText(ctx,sid,text)}throw new Error("__BILI_ACP_HANDLED__")}else{try{const res=await fetch(`${proxyBase2}/__bili/plugin/status?conversationId=${encodeURIComponent(sid)}&fallback=latest`);const status=await res.json();if(typeof status.panel==="string"&&status.panel.length>0){text=status.panel}else if(status.ok===false){let version;try{version=await fetchProxyVersion(proxyBase2)}catch{version=void 0}text=version!==void 0?armedIdleNotice(version,proxyBase2):noSessionWarning()}else{text="bili: proxy returned no status panel"}}catch(err){text=`bili: /acp failed (${err instanceof Error?err.message:String(err)})`}const staleNotice=await fetchStaleNotice(proxyBase2).catch(()=>void 0);if(staleNotice!==void 0)text+=`
|
|
356
356
|
|