billion-context 0.1.205 → 0.1.206

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.
@@ -826,7 +826,7 @@ ${summary}`}]});replaced++}return{items,replaced,dropped}}var CODEX_COMPACT_HEAL
826
826
 
827
827
  `;let body="";body+=frame2({type:"response.created",response:{id,status:"in_progress"}});body+=frame2({type:"response.output_item.added",output_index:0,item:{...messageItem,status:"in_progress"}});body+=frame2({type:"response.content_part.added",item_id:messageId,output_index:0,content_index:0,part:{type:"output_text",text:"",annotations:[]}});body+=frame2({type:"response.output_text.delta",item_id:messageId,output_index:0,content_index:0,delta:summaryText});body+=frame2({type:"response.output_text.done",item_id:messageId,output_index:0,content_index:0,text:summaryText});body+=frame2({type:"response.content_part.done",item_id:messageId,output_index:0,content_index:0,part:{type:"output_text",text:summaryText,annotations:[]}});body+=frame2({type:"response.output_item.done",output_index:0,item:messageItem});body+=frame2({type:"response.completed",response:{id,status:"completed",usage:usageJson}});body+="data: [DONE]\n\n";return{body,contentType:"text/event-stream"}}var FORGED_SUMMARY_HEADER="[Compressed conversation section]";function renderForgedSummary(block){const body=block.summary.trim();const topicLine=block.topic?`${FORGED_SUMMARY_HEADER} \u2014 ${block.topic}`:FORGED_SUMMARY_HEADER;return body.length===0?topicLine:`${topicLine}
828
828
  ${body}`}function mergeForgedSummaries(existing,blocks){const merged=existing?[...existing]:[];for(const block of blocks){if(!block.active)continue;const rendered=renderForgedSummary(block);if(!merged.includes(rendered))merged.push(rendered)}return merged}init_client_config();import fs14 from"fs";import path27 from"path";init_dsh_channel();function isDesignBenign(finding,pluginAgent){if(finding.match!=="known")return false;if(finding.client==="opencode"&&finding.knownId==="opencode-acp")return pluginAgent==="opencode";if(finding.client==="pi"&&finding.knownId==="billion-context-pi")return pluginAgent==="pi";return false}function parsePluginConflictDetail(detail){const m3=/^(\S+): (.+) \((.+)\)( \[suspected\])?$/.exec(detail.trim());if(!m3)return void 0;return{client:m3[1],entry:m3[2],source:m3[3],suspected:m3[4]!==void 0}}function isSiblingConflictDetail(detail){const p2=parsePluginConflictDetail(detail);if(!p2)return false;return isLegacyBcpEntry(p2.entry)||isOpencodeAcpEntry(p2.entry)}function isDisplayOnlyConflictDetail(detail){const p2=parsePluginConflictDetail(detail);if(!p2)return false;return isKnownDisplayOnlyPlugin(p2.entry)}var SCAN_CACHE_TTL_MS=5*60*1e3;var KEYWORD_RE=/\b(compress\w*|compact\w*|acp|summar\w*)\b/i;var cache3=new Map;function conflictScanEnabled(env=process.env){const v3=env.BILI_CONFLICT_SCAN?.trim().toLowerCase();return!(v3==="0"||v3==="false")}function sniffScanClient(headers){const h=name=>{const v3=headers[name];return Array.isArray(v3)?v3[0]:typeof v3==="string"?v3:void 0};if(h("x-claude-code-session-id"))return"claude";const ua=h("user-agent");if(ua&&isCodexClient({"user-agent":ua}))return void 0;if(h("x-opencode-session"))return"opencode";const affinity=h("x-session-affinity");if(affinity?.startsWith("ses_"))return"opencode";return void 0}function empty(client){return{client,findings:[],sourcesScanned:0}}function add(c,f2){const key2=`${f2.entry}\0${f2.source}`;if(c.seen.has(key2))return;c.seen.add(key2);c.findings.push(f2)}function entryName(entry){let s3=entry.trim();s3=s3.replace(/^npm:/,"");if(s3.startsWith("@")){const at2=s3.indexOf("@",1);if(at2!==-1)s3=s3.slice(0,at2)}else{const at2=s3.indexOf("@");if(at2!==-1)s3=s3.slice(0,at2)}const base=s3.split(/[\\/]/).pop()??s3;return base.replace(/\.(js|ts|mjs|cjs|json)$/i,"")}function isBiliSelf(entry){const name=entryName(entry);if(name==="billion-context")return true;return/[/\\]billion-context([/\\]|$)/.test(entry.trim())}function isOpencodeAcpEntry(entry){const trimmed=entry.trim();const bare=trimmed.replace(/^npm:/,"");return bare==="opencode-acp"||/^opencode-acp@/.test(bare)||/(^|[/\\])opencode-acp([/\\]|$)/.test(trimmed)}var KNOWN_NON_COMPRESSORS=new Set(["pi-compact-transcript","pi-context-inspector","@openma/deepseek-harness-acp"]);function isKnownDisplayOnlyPlugin(entry){const trimmed=entry.trim();const bare=trimmed.replace(/^npm:/,"");for(const name of KNOWN_NON_COMPRESSORS){if(bare===name||bare.startsWith(name+"@"))return true;const esc=name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").split("/").join("[/\\\\]");if(new RegExp(`(^|[/\\\\])${esc}([/\\\\]|$)`).test(trimmed))return true}return false}function classifyOpencodeEntry(c,entry,source){if(isBiliSelf(entry))return;if(isKnownDisplayOnlyPlugin(entry))return;if(isOpencodeAcpEntry(entry)){add(c,{client:"opencode",entry,source,match:"known",knownId:"opencode-acp"});return}if(KEYWORD_RE.test(entryName(entry))){add(c,{client:"opencode",entry,source,match:"keyword"})}}function opencodePluginEntries(root,source,c){const arr=root?.plugin;if(!Array.isArray(arr))return;for(const item of arr){if(typeof item==="string"&&item!=="")classifyOpencodeEntry(c,item,source);else if(item&&typeof item==="object"){const name=item.name;if(typeof name==="string"&&name!=="")classifyOpencodeEntry(c,name,source)}}}function scanOpencode(env,cwd){const c={findings:[],sources:0,seen:new Set};try{const root=readOpencodeConfigRoot(env);if(root){opencodePluginEntries(root,"global config",c);c.sources+=1}}catch{}try{const start=path27.resolve(cwd);let gitRoot;let cur=start;for(;;){if(fs14.existsSync(path27.join(cur,".git"))){gitRoot=cur;break}const parent=path27.dirname(cur);if(parent===cur)break;cur=parent}const dirs=[];cur=start;for(;;){dirs.push(cur);if(gitRoot===void 0||cur===gitRoot)break;const parent=path27.dirname(cur);if(parent===cur)break;cur=parent}for(const dir of dirs){for(const file of[...OPENCODE_CONFIG_FILES,...OPENCODE_CONFIG_FILES.map(f2=>`.opencode/${f2}`)]){const full=path27.join(dir,file);let text2;try{text2=fs14.readFileSync(full,"utf8")}catch{continue}const parsed=parseConfigText(text2);if(!parsed)continue;opencodePluginEntries(parsed,full,c);c.sources+=1}}}catch{}return{client:"opencode",findings:c.findings,sourcesScanned:c.sources}}function scanPi(env,cwd){const c={findings:[],sources:0,seen:new Set};const files=[path27.join(resolvePiHome(env),"settings.json"),path27.join(path27.resolve(cwd),".pi","settings.json")];for(const file of files){let obj;try{obj=JSON.parse(fs14.readFileSync(file,"utf8"))}catch{continue}if(!obj||typeof obj!=="object")continue;const packages=obj.packages;if(!Array.isArray(packages))continue;c.sources+=1;for(const p2 of packages){if(typeof p2!=="string"||p2==="")continue;if(isBiliSelf(p2))continue;if(isLegacyBcpEntry(p2)){add(c,{client:"pi",entry:p2,source:file,match:"known",knownId:"billion-context-pi"});continue}if(isKnownDisplayOnlyPlugin(p2))continue;if(KEYWORD_RE.test(entryName(p2)))add(c,{client:"pi",entry:p2,source:file,match:"keyword"})}}return{client:"pi",findings:c.findings,sourcesScanned:c.sources}}function scanOmp(env){const c={findings:[],sources:0,seen:new Set};const file=path27.join(resolveOmpHome(env),"config.yml");let text2;try{text2=fs14.readFileSync(file,"utf8")}catch{return{client:"omp",findings:[],sourcesScanned:0}}c.sources+=1;const lines=text2.split(/\r?\n/);let inBlock=false;for(const line of lines){if(/^extensions:(\s+(#.*)?)?$/.test(line)){inBlock=true;continue}if(inBlock){const item=/^\s+-\s+(.*)$/.exec(line);if(item){const entry=item[1].trim().replace(/^["']|["']$/g,"");if(!entry||isBiliSelf(entry))continue;if(isKnownDisplayOnlyPlugin(entry))continue;if(KEYWORD_RE.test(entryName(entry)))add(c,{client:"omp",entry,source:file,match:"keyword"});continue}if(/^\S/.test(line))inBlock=false}}return{client:"omp",findings:c.findings,sourcesScanned:c.sources}}function scanKimi(env){const c={findings:[],sources:0,seen:new Set};const pluginsDir=path27.join(resolveKimiHome(env),"plugins");const registry4=path27.join(pluginsDir,"installed.json");let ids=[];try{const parsed=JSON.parse(fs14.readFileSync(registry4,"utf8"));if(Array.isArray(parsed.plugins)){ids=parsed.plugins.map(p2=>typeof p2.id==="string"?p2.id:"").filter(s3=>s3!=="");c.sources+=1}}catch{}if(ids.length===0){try{ids=fs14.readdirSync(pluginsDir,{withFileTypes:true}).filter(e=>e.isDirectory()&&e.name!=="managed"&&e.name!=="node_modules").map(e=>e.name);c.sources+=1}catch{}}for(const id of ids){if(id==="billion-context")continue;if(isKnownDisplayOnlyPlugin(id))continue;if(KEYWORD_RE.test(id))add(c,{client:"kimi",entry:id,source:registry4,match:"keyword"})}return{client:"kimi",findings:c.findings,sourcesScanned:c.sources}}function scanHermes(env){const c={findings:[],sources:0,seen:new Set};const pluginsDir=path27.join(resolveHermesHome(env),"plugins");let entries2;try{entries2=fs14.readdirSync(pluginsDir,{withFileTypes:true})}catch{return{client:"hermes",findings:[],sourcesScanned:0}}c.sources+=1;for(const e of entries2){if(!e.isDirectory()||e.name==="billion-context")continue;if(isKnownDisplayOnlyPlugin(e.name))continue;if(KEYWORD_RE.test(e.name))add(c,{client:"hermes",entry:e.name,source:path27.join(pluginsDir,e.name),match:"keyword"})}return{client:"hermes",findings:c.findings,sourcesScanned:c.sources}}function scanDsh(env){const c={findings:[],sources:0,seen:new Set};let dirs;try{dirs=dshProfileDirs(env)}catch{return{client:"dsh",findings:[],sourcesScanned:0}}for(const dir of dirs){const file=path27.join(dir,"package.json");let obj;try{obj=JSON.parse(fs14.readFileSync(file,"utf8"))}catch{continue}c.sources+=1;for(const key2 of["dependencies","devDependencies"]){const deps=obj[key2];if(!deps||typeof deps!=="object"||Array.isArray(deps))continue;for(const dep of Object.keys(deps)){if(dep==="billion-context")continue;if(isKnownDisplayOnlyPlugin(dep))continue;if(KEYWORD_RE.test(dep))add(c,{client:"dsh",entry:dep,source:file,match:"keyword"})}}}return{client:"dsh",findings:c.findings,sourcesScanned:c.sources}}function claudeSettingsFiles(env,cwd){const home=env.CLAUDE_CONFIG_DIR??path27.join(env.HOME??env.USERPROFILE??".",".claude");return[path27.join(home,"settings.json"),path27.join(path27.resolve(cwd),".claude","settings.json")]}function scanClaude(env,cwd){const c={findings:[],sources:0,seen:new Set};for(const file of claudeSettingsFiles(env,cwd)){let obj;try{obj=JSON.parse(fs14.readFileSync(file,"utf8"))}catch{continue}if(!obj||typeof obj!=="object")continue;c.sources+=1;const enabled=obj.enabledPlugins;if(enabled&&typeof enabled==="object"&&!Array.isArray(enabled)){for(const name of Object.keys(enabled)){if(isKnownDisplayOnlyPlugin(name))continue;if(KEYWORD_RE.test(name))add(c,{client:"claude",entry:name,source:file,match:"keyword"})}}const plugins=obj.plugins;if(Array.isArray(plugins)){for(const p2 of plugins){if(typeof p2!=="string"||p2==="")continue;if(isKnownDisplayOnlyPlugin(p2))continue;if(KEYWORD_RE.test(p2))add(c,{client:"claude",entry:p2,source:file,match:"keyword"})}}}try{const dir=path27.join(env.CLAUDE_CONFIG_DIR??path27.join(env.HOME??env.USERPROFILE??".",".claude"),"plugins");for(const e of fs14.readdirSync(dir,{withFileTypes:true})){if(!e.isDirectory())continue;if(isKnownDisplayOnlyPlugin(e.name))continue;if(KEYWORD_RE.test(e.name))add(c,{client:"claude",entry:e.name,source:path27.join(dir,e.name),match:"keyword"})}}catch{}return{client:"claude",findings:c.findings,sourcesScanned:c.sources}}function scanClientPlugins(client,opts={}){const env=opts.env??process.env;const cwd=opts.cwd??process.cwd();const key2=`${client}\0${cwd}`;const hit=cache3.get(key2);if(hit&&Date.now()-hit.at<SCAN_CACHE_TTL_MS)return hit.result;let result;switch(client){case"opencode":result=scanOpencode(env,cwd);break;case"pi":result=scanPi(env,cwd);break;case"omp":result=scanOmp(env);break;case"kimi":result=scanKimi(env);break;case"hermes":result=scanHermes(env);break;case"dsh":result=scanDsh(env);break;case"claude":result=scanClaude(env,cwd);break;default:result=empty(client);break}cache3.set(key2,{at:Date.now(),result});return result}var CONFLICT_LEDGER_MAX=20;var CONFLICT_ACTIVE_WINDOW_MS=7*24*60*60*1e3;function splitConflictEvents(events,now=Date.now()){const active=[];const historical=[];for(const e of events)(now-e.at<=CONFLICT_ACTIVE_WINDOW_MS?active:historical).push(e);return{active,historical}}function conflictEventsOf(session){const raw=session.metadata.conflictEvents;if(!Array.isArray(raw))return[];return raw.filter(e=>!!e&&typeof e==="object"&&typeof e.at==="number"&&typeof e.kind==="string"&&typeof e.detail==="string")}function recordConflict(session,kind,detail){const events=conflictEventsOf(session);events.push({at:Date.now(),kind,detail});while(events.length>CONFLICT_LEDGER_MAX)events.shift();session.metadata.conflictEvents=events;markDirty(session)}var DSH_COMPACTION_LANDING_MAX_INCOMING_RATIO=.75;function dshNativeCompactionWitness(session,fingerprint){const md=session.metadata;if(!md||md.pluginAgent!=="dsh")return void 0;const n=md["dshCompactionRefusals"];if(typeof n!=="number"||n<=0)return void 0;if(fingerprint&&fingerprint.knownBefore>0&&fingerprint.incomingTotal>=fingerprint.knownBefore*DSH_COMPACTION_LANDING_MAX_INCOMING_RATIO){return void 0}return n}function conflictClientOf(session){const pa=session.metadata.pluginAgent;if(typeof pa==="string"&&pa.length>0&&pa!=="mcp")return pa;const hint=session.metadata.clientHint;if(typeof hint!=="string"||!hint)return void 0;if(/^[a-z][a-z0-9-]*$/.test(hint))return hint;if(isCodexClient({"user-agent":hint}))return"codex";return void 0}var CONFLICT_DOCS_POINTER='CONFIGURATION.md \u2192 "Detecting other compression plugins (#1206)"';function conflictRemediation(client){switch(client){case"opencode":return'set "compaction": { "auto": false } in your opencode config (or use bili opencode / bili plugin install opencode, which set it for you)';case"claude":return"launch through bili claude (it aligns CLAUDE_CODE_AUTO_COMPACT_WINDOW automatically), or set CLAUDE_CODE_AUTO_COMPACT_WINDOW to bili's effective window yourself";case"codex":return"BILI_CODEX_COMPACT=intercept by default: bili intercepts codex compaction in every form \u2014 explicit (/compact, /responses/compact, compaction_trigger) and the inline auto-compact that transits as an ordinary turn detected by its SUMMARIZATION_PROMPT template (#3008) \u2014 if you set pass, remove the override; a compaction bili merely observed (pass/gate) is rebased post-hoc (#2372)";case"pi":case"omp":return"the bili extension cancels the client's native auto-compaction while it carries the conversation \u2014 seeing this suggests missing carriage evidence or an old version; report client + bili version";default:return"disable the client's own auto-compaction (or route this session around bili), then start a fresh session \u2014 the ledger is per-session, so old entries clear with the old session"}}function fmtTime3(at2){return new Date(at2).toISOString().replace("T"," ").slice(0,19)+"Z"}function isSuspectedEvent(e){return e.kind==="third-party-plugin"&&e.detail.endsWith("[suspected]")}function isNeutralEvent(e){return e.kind==="third-party-plugin"&&(isSiblingConflictDetail(e.detail)||isDisplayOnlyConflictDetail(e.detail))}function isConfirmedConflictEvent(e){if(e.kind==="native-compaction-inferred")return true;if(e.kind!=="third-party-plugin")return false;return!isNeutralEvent(e)&&!isSuspectedEvent(e)}function formatConflictSection(events,now=Date.now(),client){const lines=[];const{active,historical}=splitConflictEvents(events,now);const meaningful=events.filter(e=>!isNeutralEvent(e));const confirmed=meaningful.filter(isConfirmedConflictEvent);const foreignConfirmed=confirmed.some(e=>e.kind==="third-party-plugin");const nativePresent=confirmed.some(e=>e.kind==="native-compaction-inferred");const signals=meaningful.filter(e=>e.kind==="unannounced-rewrite"||e.kind==="orphan-reap");const orphanOnly=meaningful.length>0&&meaningful.every(e=>e.kind==="identity-orphan");const handledNativeOnly=meaningful.length>0&&meaningful.every(e=>e.kind==="native-compaction");const activeConfirmed=confirmed.some(e=>now-e.at<=CONFLICT_ACTIVE_WINDOW_MS);lines.push(`COMPRESSION CONFLICTS \u2014 ${events.length} event(s) in this session (${active.length} active \xB7 ${historical.length} historical; active = within ${CONFLICT_ACTIVE_WINDOW_MS/864e5} days). ${foreignConfirmed||nativePresent?"Two compressors on one conversation (bili + another compression plugin \u2014 third-party or bili's own sibling \u2014 or client native compaction) double-compress and corrupt message refs:":"Diagnostic evidence that something outside bili touched this conversation \u2014 how strong that evidence is is tiered below:"}`);for(const e of events.slice(-10)){lines.push(` [${fmtTime3(e.at)}] ${e.kind} \u2014 ${e.detail}`)}if(events.length>10)lines.push(` \u2026 ${events.length-10} earlier event(s); full list: the conflicts field of GET /__bili/stats`);const suspectedCount=events.filter(isSuspectedEvent).length;if(suspectedCount>0){lines.push(" [suspected] = name-only keyword match \u2014 verify the plugin actually compresses before acting; a context dashboard/viewer/tool is NOT a compressor.")}let advice;if(meaningful.length===0){advice="Every event above names bili's OWN sibling extension (billion-context-pi / opencode-acp) or a verified non-compressing plugin (a read-only viewer/tool, or a protocol adapter whose name merely collides with a compression keyword \u2014 e.g. 'acp' meaning Agent Client Protocol): while bili drives the session the sibling stands down automatically (BILLION_CONTEXT_NATIVE marker in native mode, /bili/ baseUrl self-check otherwise) and the verified plugin does not compress anything, so no second compressor is active. Verify your bili/sibling versions are recent, then clear this ledger \u2014 Web UI conflict banner / session page, or POST /__bili/conflicts/clear."}else if(foreignConfirmed){advice=activeConfirmed?"Keep exactly ONE compressor per conversation: remove/disable the other plugin (or its native auto-compaction), then start a fresh session.":"The confirmed event(s) above are older than 7 days (historical stock): the double-compression risk may no longer be live. Verify the other compression plugin is removed or blocked by bili, then clear this ledger \u2014 Web UI conflict banner / session page, or POST /__bili/conflicts/clear?session=<id>."}else if(nativePresent){advice="The events above point at the client's OWN native compaction landing (host-side), not a third-party plugin \u2014 do not go hunting for a second plugin to disable. bili attributed this from its own witness (it refused the client's compaction calls this session) but did NOT see the checkpoint marker, so it could not rebuild the fold base onto the compacted view \u2014 this session's fold base is gone; start a fresh conversation."}else if(handledNativeOnly){advice=active.length>0?"The events above are client-native compaction landings bili ALREADY rebased onto (#2372/#2432): each detected checkpoint rebuilt the fold base, so there is no ongoing double-compression risk and nothing to disable. If you did not expect these sessions to auto-compact, review the client's own auto-compaction setting; otherwise clear this ledger \u2014 Web UI conflict banner / session page, or POST /__bili/conflicts/clear?session=<id>.":"All events above are client-native compaction landings older than 7 days (historical stock) that bili already rebased onto (#2372/#2432): handled at the time, no ongoing risk. Clear this ledger \u2014 Web UI conflict banner / session page, or POST /__bili/conflicts/clear?session=<id>."}else if(orphanOnly){advice=active.length>0?"The events above are identity-loss takeovers (#2791 family): the client's lane stopped stamping its conversation id mid-conversation, so a headerless replay minted a fresh anonymous fork and THIS session's fold continuity broke \u2014 there is NO second compressor to hunt for and no auto-compaction to disable. Restore the lane that stamps identity (host/plugin wiring \u2014 e.g. a profile wire-protocol switch the identity patch missed), or start a fresh conversation.":"All events above are identity-loss takeovers older than 7 days (historical stock): the anonymous forks named above already happened and the continuity loss is in the past. Verify the client's lane stamps its conversation id again (host/plugin wiring), then clear this ledger \u2014 Web UI conflict banner / session page, or POST /__bili/conflicts/clear?session=<id>."}else if(signals.length===0){advice=active.length>0?"Every event above is [suspected]: confirm each named plugin really compresses before removing anything \u2014 do not drop a read-only tool on the strength of its name.":"Every event above is [suspected] AND older than 7 days (historical stock): confirm each named plugin really compresses before removing anything \u2014 do not drop a read-only tool on the strength of its name. If none of them turns out to compress, clear this ledger \u2014 Web UI conflict banner / session page, or POST /__bili/conflicts/clear?session=<id>."}else{advice=active.length>0?"Every event above is an UNCONFIRMED signal: history changes were observed (rewrites without a recognized compaction marker, summarized blocks leaving the client history) and/or name-only [suspected] plugin matches, but nothing here identifies WHO rewrote the conversation \u2014 the cause is not confirmed. Do not drop a read-only tool or viewer on the strength of these records; verify the named plugins and the client's auto-compaction settings before acting.":"All events above are UNCONFIRMED signals older than 7 days (historical stock): history changes were observed but their cause was never identified, and no second compressor is confirmed. If the affected sessions are gone, clear this ledger \u2014 Web UI conflict banner / session page, or POST /__bili/conflicts/clear?session=<id>."}lines.push(advice);const pureSuspectedTier=meaningful.length>0&&confirmed.length===0&&signals.length===0&&!meaningful.some(e=>e.kind==="identity-orphan");if(meaningful.length>0&&!orphanOnly&&!pureSuspectedTier){lines.push("",`Fix${client?` (${client})`:""}: ${conflictRemediation(client)}`);lines.push(CONFLICT_DOCS_POINTER)}return lines}function summarizeConflicts(sessions2,now=Date.now()){const summary={sessions:0,events:0,active:0,historical:0,lastAt:null,kinds:{},latest:[],sibling:0,suspected:0,displayOnly:0,activeConfirmed:0,clients:[]};for(const s3 of sessions2){const events=conflictEventsOf(s3);if(events.length===0)continue;summary.sessions+=1;summary.events+=events.length;const c=conflictClientOf(s3);if(c&&!summary.clients.includes(c))summary.clients.push(c);for(const e of events){summary.kinds[e.kind]=(summary.kinds[e.kind]??0)+1;if(e.kind==="third-party-plugin"&&isSiblingConflictDetail(e.detail))summary.sibling+=1;if(e.kind==="third-party-plugin"&&isDisplayOnlyConflictDetail(e.detail))summary.displayOnly+=1;if(isSuspectedEvent(e))summary.suspected+=1;const isActive=now-e.at<=CONFLICT_ACTIVE_WINDOW_MS;if(isActive)summary.active+=1;else summary.historical+=1;if(isActive&&isConfirmedConflictEvent(e))summary.activeConfirmed+=1;if(summary.lastAt===null||e.at>summary.lastAt)summary.lastAt=e.at}const last=events[events.length-1];summary.latest.push({sessionId:s3.id,at:last.at,kind:last.kind,detail:last.detail})}summary.latest.sort((a,b3)=>b3.at-a.at);return summary}function clearConflictEvents(sessions2,sessionId){let events=0;let clearedSessions=0;for(const s3 of sessions2){if(sessionId!==void 0&&s3.id!==sessionId)continue;const raw=conflictEventsOf(s3);if(raw.length===0)continue;delete s3.metadata.conflictEvents;markDirty(s3);events+=raw.length;clearedSessions+=1}return{events,sessions:clearedSessions}}var LAUNCHER_DEFAULT_HOST="127.0.0.1";var HEALTH_PATH="/__bili/health";var HEALTH_POLL_INTERVAL_MS=200;var SPAWN_WAIT_MS=2e4;var 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(d2=>d2.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(err2){const e=err2;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(err2)}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(err2){return{ok:false,detail:describeProbeFailure(err2)}}finally{clearTimeout(t)}}async function fetchHealthInfoDefault(origin){try{const res=await fetch(healthUrl(origin),{signal:AbortSignal.timeout(PROBE_TIMEOUT_MS)});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(data.watchdog&&typeof data.watchdog==="object"&&typeof data.watchdog.armed==="boolean"){const wd=data.watchdog;const watchers=Array.isArray(wd.watchers)?wd.watchers.filter(w3=>typeof w3==="number"):void 0;info.watchdog={armed:wd.armed,watchers}}return info}catch{return void 0}}async function registerWatcherDefault(origin,pid){try{const res=await fetch(`${origin}/__bili/watcher`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({pid}),signal:AbortSignal.timeout(2e3)});if(!res.ok){if(res.status===409)return"refused";console.error(`bili: watcher registration returned HTTP ${res.status} \u2014 the shared proxy may exit when its first owner does`);return"failed"}return"ok"}catch(err2){console.error(`bili: watcher registration failed \u2014 the shared proxy may exit when its first owner does (${err2 instanceof Error?err2.message:String(err2)})`);return"failed"}}function isStartingMarkerActive(marker,nowMs2){return isPidAlive(marker.pid)&&nowMs2-marker.startedAt<STARTING_MARKER_TTL_MS}function recordedModelMap(passed,ambientRaw,parse4){return parse4(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!==opts.passthrough)return"host-or-passthrough-mismatch";const wantDomains=resolveRecordedMitmDomains(opts.mitmDomains);if(inst.mitmDomains.length!==wantDomains.length||inst.mitmDomains.some((d2,i)=>d2!==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 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){const busy=await isConnectable(c.origin);diag?.(busy?`native-attach: drop ${c.origin} (pid ${c.pid}): health probe failed but TCP connect succeeded \u2014 instance is BUSY (event loop saturated), not dead (#3654)`:`native-attach: drop ${c.origin} (pid ${c.pid}): health probe failed`);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}const incompatible=instanceCompatible(c.inst,opts,codeFingerprint,foreignLanes);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(!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=[]){const deadline=now()+SPAWN_BUDGET_MS;const probe=async()=>pickAttachable(await probeLiveInstances(readInstance,fetchHealthInfo,diag),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(debug2){return msg=>{logHostEvent("info","",msg);if(debug2)process.stderr.write(`${new Date().toISOString()} [info] [v=${VERSION}] ${msg}
829
- `)}}function pickEphemeralPort(host=LAUNCHER_DEFAULT_HOST){return new Promise((resolve,reject)=>{const srv=net3.createServer();srv.once("error",reject);srv.listen(0,host,()=>{const addr=srv.address();srv.close(()=>{if(addr&&typeof addr==="object")resolve(addr.port);else reject(new Error("could not allocate a free port"))})})})}var INHERITED_PROXY_VARS=["http_proxy","https_proxy","all_proxy","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","no_proxy","NO_PROXY"];var INTERNAL_LAUNCHER_CHANNEL_VARS=["BILI_LAUNCHER_LANE","BILI_LAUNCHER_MODEL_WINDOWS","BILI_LAUNCHER_MODEL_MAX_OUTPUTS","BILI_STRICT_PORT"];function stripInternalLauncherChannels(env){const cleaned={...env};for(const key2 of INTERNAL_LAUNCHER_CHANNEL_VARS)delete cleaned[key2];return cleaned}function stripInheritedProxy(env){const cleaned={...env};for(const key2 of INHERITED_PROXY_VARS)delete cleaned[key2];return stripInternalLauncherChannels(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 m3=/^v(\d+)\.\d+\.\d+/.exec(out.trim());return m3?Number(m3[1]):void 0}catch{return void 0}}var MIN_PROXY_NODE_MAJOR=20;function looksLikeNodeExecutable(p2,platform){if(platform==="win32"){if(!/^[a-zA-Z]:[\\/]/.test(p2))return false}else if(!p2.startsWith("/")){return false}const base=p2.split(/[\\/]/).pop()?.toLowerCase()??"";return base==="node"||base==="node.exe"}function resolveNodeRuntime(execPath=process.execPath,env=process.env,platform=process.platform,existsImpl=fs15.existsSync,electronVersion=typeof process.versions.electron==="string"?process.versions.electron:void 0,probeWrapper=probeNodeWrapperTarget,probeNode=probeNodeMajor){const base=path28.basename(execPath).toLowerCase();if(base==="node"||base==="node.exe")return execPath;const override=typeof env.BILLION_CONTEXT_NODE==="string"?env.BILLION_CONTEXT_NODE.trim():"";if(override.length>0&&existsImpl(override))return override;const resolveDiscovered=candidate=>{let subject=candidate;if(platform==="win32"){const probed=probeWrapper(candidate,env);const target=probed?.trim();if(target&&target.length>0&&looksLikeNodeExecutable(target,platform)&&existsImpl(target)){if(target.toLowerCase()!==candidate.toLowerCase()){log("info",`bili: ${candidate} is a Windows node wrapper resolving to ${target} \u2014 spawning the real Node directly (#1887)`);subject=target}}}const major=probeNode(subject,env);if(major===void 0||major<MIN_PROXY_NODE_MAJOR)return void 0;return subject};const sep2=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(sep2),...extraDirs]){if(!dir)continue;for(const name of names){const candidate=dir.endsWith("/")||dir.endsWith("\\")?dir+name:dir+"/"+name;if(!existsImpl(candidate))continue;const resolved=resolveDiscovered(candidate);if(resolved!==void 0)return resolved;log("warn",`bili: skipping ${candidate} \u2014 not a usable Node runtime (--version did not report v${MIN_PROXY_NODE_MAJOR}+; set BILLION_CONTEXT_NODE if this is wrong, #3383)`)}}if(electronVersion&&electronVersion.length>0){log("warn",`bili: no usable Node runtime found on PATH or install dirs \u2014 falling back to the Electron host binary ${execPath} run as Node via ELECTRON_RUN_AS_NODE=1 (#1429/#3383)`);return execPath}throw new Error("bili: cannot find a Node runtime to spawn the proxy (this process is not Node) \u2014 set BILLION_CONTEXT_NODE")}var PORT_LOG_MAX_BYTES=5*1024*1024;function rotatePortLogIfNeeded(logPath2){try{if(fs15.statSync(logPath2).size<PORT_LOG_MAX_BYTES)return;try{fs15.unlinkSync(`${logPath2}.old`)}catch{}fs15.renameSync(logPath2,`${logPath2}.old`)}catch{}}var STALE_ROTATION_WAIT_MS=12e3;var SHUTDOWN_REQUEST_TIMEOUT_MS=3e3;var OWNER_HEARTBEAT_INTERVAL_MS=5e3;var OWNER_HEARTBEAT_POST_TIMEOUT_MS=2e3;async function requestInstanceShutdown(origin){try{const res=await fetch(`${origin}/__bili/shutdown`,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(SHUTDOWN_REQUEST_TIMEOUT_MS)});return res.ok}catch{return false}}async function rotateStalePredecessor(probed,resolveTargetPort,opts,attachUrl,foreignLanes,fetchHealthInfo,now,sleep2,requestShutdown){if(attachUrl!==void 0)return;const stale=probed.filter(c=>!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 fetchHealthInfo(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 answers healthy; falling back to the normal spawn ladder`);return}await sleep2(HEALTH_POLL_INTERVAL_MS)}}function startOwnerHeartbeat(origin,pid,intervalMs=OWNER_HEARTBEAT_INTERVAL_MS,post=async body=>{await fetch(`${origin}/__bili/watcher`,{method:"POST",headers:{"content-type":"application/json"},body,signal:AbortSignal.timeout(OWNER_HEARTBEAT_POST_TIMEOUT_MS)})}){if(pid!==process.pid)return void 0;let stopped=false;const beat=async()=>{while(!stopped){await new Promise(r=>{const t=setTimeout(r,intervalMs);t.unref?.()});if(stopped)return;try{await post(JSON.stringify({pid,hb:true}))}catch{}}};void beat();return()=>{stopped=true}}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 attachTo=async inst=>{attachDiag(`bili: attaching to running proxy at ${inst.origin} (pid ${inst.pid})`);const reg=await registerWatcher(inst.origin,watchPid);startOwnerHeartbeat(inst.origin,watchPid);const handle2={origin:inst.origin,port:inst.port,attached:true};if(reg==="refused")handle2.refusedWatcher=true;return handle2};const script=deps.scriptPath??process.argv[1];const codeFingerprint=entryScriptFingerprint(script);const probed=await probeLiveInstances(readInstance,fetchHealthInfo,attachDiag);const existing=pickAttachable(probed,opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,attachDiag,foreignLanes);if(existing){return attachTo(existing)}{await rotateStalePredecessor(probed,()=>{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},opts,attachUrl,foreignLanes,fetchHealthInfo,now,sleepImpl,deps?.requestInstanceShutdown??requestInstanceShutdown)}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);if(waited){return attachTo(waited)}return void 0};const starterLaneMatches=m3=>opts.lane===void 0||m3.lane===void 0||m3.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=randomUUID5();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=path28.join(os8.tmpdir(),`bili-proxy-${port}.log`);rotatePortLogIfNeeded(logPath2);const logFd=fs15.openSync(logPath2,"a");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:{...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"}:{}}})}finally{try{fs15.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 fd=fs15.openSync(logPath2,"r");try{const buf=Buffer.alloc(256);const n=fs15.readSync(fd,buf,0,buf.length,0);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 head: "${s3}"`}finally{fs15.closeSync(fd)}}catch{return""}};const logTail=()=>{try{const size=fs15.statSync(logPath2).size;const rotated=fs15.existsSync(`${logPath2}.old`)?`; earlier output rotated to ${logPath2}.old`:"";return size===0?`, ${size} bytes \u2014 EMPTY, the child produced no output of its own${rotated}`:`, ${size} bytes${rotated}${logHeadSample()}`}catch{return""}};const diagnosePort=async childAlive=>{const origin=proxyOrigin(opts.host,port);let info;let det={ok:false,detail:"probe error"};try{const[i,d3]=await Promise.all([fetchHealthInfo(origin),fetchDetail(healthUrl(origin))]);info=i;det=d3}catch{}if(info?.ok){return info.pid===child.pid?`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`:`port ${port} is held by a different process${info.pid!==void 0?` (pid ${info.pid})`:""} \u2014 the spawned child never bound it`}if(det.ok){return`port ${port} answered but not with bili's health payload \u2014 a foreign service likely holds it`}const d2=det.detail??"unknown error";if(/^(ECONNREFUSED|ECONNRESET|EHOSTUNREACH|ENETUNREACH|EPIPE)$/i.test(d2)){return`nothing is listening on port ${port} \u2014 the spawned child (${childAlive?"still alive":"already exited"}, pid ${child.pid??"?"}) never bound it`}if(/^HTTP \d{3}$/.test(d2)){return`port ${port} answered ${d2} \u2014 the listener there is not reporting bili health`}if(/^timeout after \d+ms$/i.test(d2)&&await(deps.isConnectable??tcpConnectable)(origin)){return`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)`}return`last health probe failed with ${d2}`};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)}) (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`)}}}const adoptServingTwin=async()=>{const candidates=(deps.listAdoptCandidates??discoverLiveInstances)().filter(inst=>isPidAlive(inst.pid)&&instanceCompatible(inst,opts,codeFingerprint,foreignLanes)===void 0).sort((a,b3)=>Number(b3.port===port)-Number(a.port===port)||b3.startedAt-a.startedAt);for(const inst of candidates){if(!await(deps.isConnectable??tcpConnectable)(inst.origin))continue;attachDiag(`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);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)} (runtime: ${runtime}) (log: ${logPath2}${logTail()})`)}const diagnosis=await diagnosePort(true);killAbandonedChild(child);console.error(`bili: killed spawned proxy (pid ${child.pid??"?"}) after ${SPAWN_BUDGET_MS}ms without health \u2014 ${diagnosis} (log: ${logPath2}${logTail()})`);throw new Error(`bili: proxy did not become healthy within ${SPAWN_BUDGET_MS}ms \u2014 ${diagnosis} (runtime: ${runtime}) (log: ${logPath2}${logTail()})`)}finally{if(claimed)clearStartingMarker(launchToken)}}function killAbandonedChild(child){if(!child||child.pid===void 0||child.pid<=0)return;if(process.platform!=="win32"){try{process.kill(-child.pid,"SIGKILL")}catch{}}else{try{spawnSync3("taskkill",["/F","/T","/PID",String(child.pid)],{windowsHide:true,stdio:"ignore"})}catch{}}try{child.kill?.("SIGKILL")}catch{}}var PATH_EXTS=process.platform==="win32"?[".cmd",".bat",".exe",""]:[""];import fs18 from"fs";import path32 from"path";import{fileURLToPath as fileURLToPath5}from"url";import{createHash as createHash17}from"crypto";init_chunk_VEDGC5EH();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(v3){if(Array.isArray(v3))return v3.map(canonicalize2);if(v3!==null&&typeof v3==="object"){const src=v3;const out={};for(const k2 of Object.keys(src).sort())out[k2]=canonicalize2(src[k2]);return out}return v3}var idSalt=null;function deriveCanonicalMessageId(role,contentType,text2,options={}){const seed=`${idSalt?idSalt+"|":""}${role}|${contentType}||${options.toolName??""}|${text2}`+(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 extractSystem(system){if(!system)return"";if(typeof system==="string")return system;return system.map(b3=>b3.text).join("\n\n")}function buildSystem(text2,original){if(Array.isArray(original)&&original.length>0){const ccBlock=original.find(b3=>b3.cache_control);return[{type:"text",text:text2,...ccBlock?{cache_control:ccBlock.cache_control}:{}}]}return text2}function anthropicToCore(body){const msgs=[];const cacheControls=new Map;const clusters=new ClusterCounter;const toolNames=new Map;for(const[wireIndex,m3]of body.messages.entries()){const before=msgs.length;if(m3.role==="system"){const core=systemMessageCore(m3,clusters);core.wireIndex=wireIndex;msgs.push(core);const mark=systemMessageMark(m3);if(mark)cacheControls.set(core.id,mark);continue}const blocks=typeof m3.content==="string"?[{type:"text",text:m3.content}]:m3.content;for(const b3 of blocks){switch(b3.type){case"text":{const base=deriveCanonicalMessageId(m3.role,"text",b3.text);const id=clusters.next(base);msgs.push({id,role:m3.role,contentType:"text",text:b3.text});if(b3.cache_control)cacheControls.set(id,b3.cache_control);break}case"tool_use":{const base=deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(safeStringify(b3.input)),{toolName:b3.name});const id=clusters.next(base);msgs.push({id,role:"assistant",contentType:"tool-call",toolName:b3.name,toolCallId:b3.id,text:safeStringify(b3.input)});toolNames.set(b3.id,b3.name);if(b3.cache_control)cacheControls.set(id,b3.cache_control);break}case"tool_result":{const hasNonText=Array.isArray(b3.content)&&b3.content.some(c=>c.type!=="text");const text2=typeof b3.content==="string"?b3.content:b3.content.map(c=>c.type==="text"?c.text:"").join("\n");const name=toolNames.get(b3.tool_use_id);const base=deriveCanonicalMessageId("tool","tool-result",text2,{toolName:name});const id=clusters.next(base);msgs.push({id,role:"tool",contentType:"tool-result",toolCallId:b3.tool_use_id,text:text2,...name?{toolName:name}:{},...b3.is_error===true?{toolIsError:true}:{},...hasNonText?{rawAnthropicBlock:b3}:{}});if(b3.cache_control)cacheControls.set(id,b3.cache_control);break}case"thinking":{const base=deriveCanonicalMessageId("assistant","reasoning",b3.thinking);msgs.push({id:clusters.next(base),role:"assistant",contentType:"reasoning",text:b3.thinking,...b3.signature?{thinkingSignature:b3.signature}:{}});break}case"image":{const source=b3.source&&typeof b3.source==="object"&&!Array.isArray(b3.source)?b3.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(m3.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:m3.role,contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawAnthropicBlock:b3,...mediaSidecar});break}case"redacted_thinking":{const base=deriveCanonicalMessageId(m3.role,"text",CANONICAL_REDACTED_THINKING_TEXT);msgs.push({id:clusters.next(base),role:m3.role,contentType:"text",text:"[redacted_thinking]",rawAnthropicBlock:b3});break}default:{const unknownType=b3.type;const label=typeof unknownType==="string"?`[${unknownType}]`:"[unknown]";const base=deriveCanonicalMessageId(m3.role,"text",label);msgs.push({id:clusters.next(base),role:m3.role,contentType:"text",text:label,rawAnthropicBlock:b3});break}}}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}}return{msgs,cacheControls}}function systemMessageCore(m3,clusters){const label=systemMessageText(m3);const base=deriveCanonicalMessageId("system","text",label);return{id:clusters.next(base),role:"system",contentType:"text",text:label,rawAnthropicMessage:m3}}function systemMessageText(m3){const text2=typeof m3.content==="string"?m3.content:m3.content.map(b3=>b3.type==="text"?b3.text:`[${b3.type}]`).join("\n");return text2.length>0?text2:"[system]"}function systemMessageMark(m3){if(typeof m3.content==="string")return void 0;let mark;for(const b3 of m3.content)if(b3.cache_control)mark=b3.cache_control;return mark}function rebuildSystemMessage(m3,mark){const raw=m3.rawAnthropicMessage;const cc=mark?{cache_control:mark}:{};const text2=m3.text??"";if(text2!==systemMessageText(raw)&&isPlainTextSystemMessage(raw)){return{role:"system",content:[{type:"text",text:text2,...cc}]}}if(!mark||systemMessageMark(raw)||typeof raw.content==="string"){return raw}const last=raw.content.length-1;if(last<0)return raw;return{...raw,content:raw.content.map((b3,i)=>i===last?{...b3,...cc}:b3)}}function isDirectiveOnlySystem(e){return e.role==="system"&&Array.isArray(e.content)&&e.content.length===0&&e.output_config!=null}function revoiceFoldOrphanedSystems(out){for(let j3=out.length-1;j3>=0;j3--){const e=out[j3];if(!e||e.role!=="system")break;if(isDirectiveOnlySystem(e))continue;out[j3]={...e,role:"user"}}}function coreToAnthropic(messages,cacheControls){const out=[];let current=null;const flush=()=>{if(current&&current.blocks.length>0){out.push({role:current.role,content:current.blocks})}current=null};const cc=id=>{const v3=cacheControls?.get(id);return v3?{cache_control:v3}:{}};for(const m3 of messages){if(m3.rawAnthropicMessage){flush();out.push(rebuildSystemMessage(m3,cacheControls?.get(m3.id)));continue}if(m3.role==="system"&&current===null){revoiceFoldOrphanedSystems(out)}const target=m3.role==="assistant"?"assistant":"user";if(!current||current.role!==target){flush();current={role:target,blocks:[]}}switch(m3.contentType){case"text":{if(m3.rawAnthropicBlock){current.blocks.push(m3.rawAnthropicBlock);break}current.blocks.push({type:"text",text:m3.text??"",...cc(m3.id)});break}case"tool-call":current.blocks.push({type:"tool_use",id:m3.toolCallId??`call_${m3.id}`,name:m3.toolName??"unknown",input:safeParse(m3.text),...cc(m3.id)});break;case"tool-result":if(m3.rawAnthropicBlock){current.blocks.push(m3.rawAnthropicBlock);break}current.blocks.push({type:"tool_result",tool_use_id:m3.toolCallId??"",content:m3.text??"",...m3.toolIsError?{is_error:true}:{},...cc(m3.id)});break;case"reasoning":current.blocks.push({type:"thinking",thinking:m3.text??"",...m3.thinkingSignature?{signature:m3.thinkingSignature}:{}});break}}flush();return out}function conversationSignalAnthropic(body,headerValue3){if(headerValue3&&headerValue3.trim())return headerValue3.trim();const msgs=Array.isArray(body?.messages)?body.messages:[];const firstUser=msgs.find(m3=>m3?.role==="user");const seed=firstUser?JSON.stringify(firstUser.content):"default";return hashId2(seed)}function safeStringify(v3){try{return JSON.stringify(v3??{})}catch{return"{}"}}function safeParse(s3){if(!s3)return{};try{return JSON.parse(s3)}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 m3=/^data:([^;,]+)(?:;base64)?,(.+)$/i.exec(url);if(!m3)return void 0;return{mediaType:m3[1],base64:m3[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,m3]of body.messages.entries()){const before=msgs.length;switch(m3.role){case"system":case"developer":{if(msgs.length===0){systemParts.push(stringContent(m3.content));break}const base=deriveCanonicalMessageId(m3.role,"text",stringContent(m3.content));msgs.push({id:clusters.next(base),role:"system",contentType:"text",text:stringContent(m3.content),originalRole:m3.role,rawOpenaiMessage:m3});break}case"user":{if(typeof m3.content==="string"||m3.content==null||!Array.isArray(m3.content)){const base=deriveCanonicalMessageId("user","text",typeof m3.content==="string"?m3.content:"");msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:typeof m3.content==="string"?m3.content:""});break}let lastTextCore=null;let leadingOpaque=[];let sawText=false;for(const part of m3.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=m3.reasoning_content;const fieldPresent=typeof rawReasoning==="string";const fieldReasoning=fieldPresent?rawReasoning:"";let reasoning=fieldReasoning;let text2=stringContent(m3.content);if(!reasoning){const split=splitDemotedThinking(text2);if(split){reasoning=split.reasoning;text2=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(text2){const base=deriveCanonicalMessageId("assistant","text",text2);msgs.push({id:clusters.next(base),role:"assistant",contentType:"text",text:text2,...blankEcho?{reasoningPresent:true}:{}})}if(Array.isArray(m3.tool_calls)){for(const tc of m3.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(m3.content),{toolName:m3.name||toolNames.get(m3.tool_call_id??"")});const name=m3.name||toolNames.get(m3.tool_call_id??"");msgs.push({id:clusters.next(base),role:"tool",contentType:"tool-result",toolCallId:m3.tool_call_id??"",text:stringContent(m3.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 coreToOpenai(messages){const out=[];let userRun=[];const flushUserRun=()=>{if(userRun.length===0)return;const parts=[];let plain=true;for(const m3 of userRun){if(m3.rawOpenaiContentParts&&m3.rawOpenaiContentParts.length>0){if(m3.text)parts.push({type:"text",text:m3.text});for(const part of m3.rawOpenaiContentParts)parts.push(part);plain=false}else if(m3.rawOpenaiContent){if(m3.text&&!m3.imagePart)parts.push({type:"text",text:m3.text});parts.push(m3.rawOpenaiContent);plain=false}else if(m3.imageBase64&&m3.imageMediaType){parts.push({type:"image_url",image_url:{url:`data:${m3.imageMediaType};base64,${m3.imageBase64}`}});plain=false}else{parts.push({type:"text",text:m3.text??""})}}if(plain&&userRun.length===1){out.push({role:"user",content:userRun[0].text??""})}else{out.push({role:"user",content:parts})}userRun=[]};let pending=null;const flush=()=>{if(!pending)return;const reasoning=pending.reasoning!==null&&pending.reasoning.length>0?pending.reasoning:void 0;const reasoningField=reasoning!==void 0?{reasoning_content:reasoning}:pending.reasoningPresent?{reasoning_content:""}:{};if(pending.toolCalls.length>0){out.push({role:"assistant",content:pending.text??null,tool_calls:pending.toolCalls,...reasoningField})}else if(pending.text!==null){out.push({role:"assistant",content:pending.text,...reasoningField})}else if(reasoning){out.push({role:"assistant",content:null,reasoning_content:reasoning})}pending=null};for(const m3 of messages){if(m3.role==="assistant"){flushUserRun();if(!pending)pending={text:null,toolCalls:[],reasoning:null,reasoningPresent:false};if(m3.reasoningPresent)pending.reasoningPresent=true;if(m3.contentType==="reasoning"){pending.reasoning=(pending.reasoning??"")+(m3.reasoningContent??m3.text??"")}else if(m3.contentType==="text"){pending.text=(pending.text??"")+(m3.text??"")}else if(m3.contentType==="tool-call"){pending.toolCalls.push({id:m3.toolCallId??`call_${m3.id}`,type:"function",function:{name:m3.toolName??"unknown",arguments:m3.text??""}})}}else{if(m3.role!=="user"){flush();flushUserRun()}if(m3.role==="system"){const raw=m3.rawOpenaiMessage;if(raw){const text2=m3.text??"";if(text2!==stringContent(raw.content)&&isPlainStringOrTextParts(raw.content)){out.push({role:m3.originalRole==="developer"?"developer":"system",content:typeof raw.content==="string"?text2:[{type:"text",text:text2}]})}else{out.push(raw)}}else{out.push({role:m3.originalRole==="developer"?"developer":"system",content:m3.text??""})}}else if(m3.role==="user"&&isSummaryMessageId(m3.id)&&m3.contentType==="text"){flush();flushUserRun();out.push({role:"user",content:m3.text??""})}else if(m3.role==="user"){flush();const prev=userRun[userRun.length-1];if(prev&&prev.wireIndex!==void 0&&m3.wireIndex!==void 0&&prev.wireIndex!==m3.wireIndex){flushUserRun()}userRun.push(m3)}else if(m3.role==="tool"){out.push({role:"tool",tool_call_id:m3.toolCallId??"",content:m3.text??""})}}}flush();flushUserRun();return out}function injectOpenaiSystem(messages,parts){if(parts.length===0)return messages;const extra=parts.join("\n\n");if(messages.length>0&&(messages[0]?.role==="system"||messages[0]?.role==="developer")){const head=messages[0];const base=stringContent(head.content);const merged=base?`${base}
829
+ `)}}function pickEphemeralPort(host=LAUNCHER_DEFAULT_HOST){return new Promise((resolve,reject)=>{const srv=net3.createServer();srv.once("error",reject);srv.listen(0,host,()=>{const addr=srv.address();srv.close(()=>{if(addr&&typeof addr==="object")resolve(addr.port);else reject(new Error("could not allocate a free port"))})})})}var INHERITED_PROXY_VARS=["http_proxy","https_proxy","all_proxy","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","no_proxy","NO_PROXY"];var INTERNAL_LAUNCHER_CHANNEL_VARS=["BILI_LAUNCHER_LANE","BILI_LAUNCHER_MODEL_WINDOWS","BILI_LAUNCHER_MODEL_MAX_OUTPUTS","BILI_STRICT_PORT"];function stripInternalLauncherChannels(env){const cleaned={...env};for(const key2 of INTERNAL_LAUNCHER_CHANNEL_VARS)delete cleaned[key2];return cleaned}function stripInheritedProxy(env){const cleaned={...env};for(const key2 of INHERITED_PROXY_VARS)delete cleaned[key2];return stripInternalLauncherChannels(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 m3=/^v(\d+)\.\d+\.\d+/.exec(out.trim());return m3?Number(m3[1]):void 0}catch{return void 0}}var MIN_PROXY_NODE_MAJOR=20;function looksLikeNodeExecutable(p2,platform){if(platform==="win32"){if(!/^[a-zA-Z]:[\\/]/.test(p2))return false}else if(!p2.startsWith("/")){return false}const base=p2.split(/[\\/]/).pop()?.toLowerCase()??"";return base==="node"||base==="node.exe"}function resolveNodeRuntime(execPath=process.execPath,env=process.env,platform=process.platform,existsImpl=fs15.existsSync,electronVersion=typeof process.versions.electron==="string"?process.versions.electron:void 0,probeWrapper=probeNodeWrapperTarget,probeNode=probeNodeMajor){const base=path28.basename(execPath).toLowerCase();if(base==="node"||base==="node.exe")return execPath;const override=typeof env.BILLION_CONTEXT_NODE==="string"?env.BILLION_CONTEXT_NODE.trim():"";if(override.length>0&&existsImpl(override))return override;const resolveDiscovered=candidate=>{let subject=candidate;if(platform==="win32"){const probed=probeWrapper(candidate,env);const target=probed?.trim();if(target&&target.length>0&&looksLikeNodeExecutable(target,platform)&&existsImpl(target)){if(target.toLowerCase()!==candidate.toLowerCase()){log("info",`bili: ${candidate} is a Windows node wrapper resolving to ${target} \u2014 spawning the real Node directly (#1887)`);subject=target}}}const major=probeNode(subject,env);if(major===void 0||major<MIN_PROXY_NODE_MAJOR)return void 0;return subject};const sep2=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(sep2),...extraDirs]){if(!dir)continue;for(const name of names){const candidate=dir.endsWith("/")||dir.endsWith("\\")?dir+name:dir+"/"+name;if(!existsImpl(candidate))continue;const resolved=resolveDiscovered(candidate);if(resolved!==void 0)return resolved;log("warn",`bili: skipping ${candidate} \u2014 not a usable Node runtime (--version did not report v${MIN_PROXY_NODE_MAJOR}+; set BILLION_CONTEXT_NODE if this is wrong, #3383)`)}}if(electronVersion&&electronVersion.length>0){log("warn",`bili: no usable Node runtime found on PATH or install dirs \u2014 falling back to the Electron host binary ${execPath} run as Node via ELECTRON_RUN_AS_NODE=1 (#1429/#3383)`);return execPath}throw new Error("bili: cannot find a Node runtime to spawn the proxy (this process is not Node) \u2014 set BILLION_CONTEXT_NODE")}var PORT_LOG_MAX_BYTES=5*1024*1024;function rotatePortLogIfNeeded(logPath2){try{if(fs15.statSync(logPath2).size<PORT_LOG_MAX_BYTES)return;try{fs15.unlinkSync(`${logPath2}.old`)}catch{}fs15.renameSync(logPath2,`${logPath2}.old`)}catch{}}var STALE_ROTATION_WAIT_MS=12e3;var SHUTDOWN_REQUEST_TIMEOUT_MS=3e3;var OWNER_HEARTBEAT_INTERVAL_MS=5e3;var OWNER_HEARTBEAT_POST_TIMEOUT_MS=2e3;async function requestInstanceShutdown(origin){try{const res=await fetch(`${origin}/__bili/shutdown`,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(SHUTDOWN_REQUEST_TIMEOUT_MS)});return res.ok}catch{return false}}async function rotateStalePredecessor(probed,resolveTargetPort,opts,attachUrl,foreignLanes,fetchHealthInfo,now,sleep2,requestShutdown){if(attachUrl!==void 0)return;const stale=probed.filter(c=>!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 fetchHealthInfo(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 answers healthy; falling back to the normal spawn ladder`);return}await sleep2(HEALTH_POLL_INTERVAL_MS)}}function startOwnerHeartbeat(origin,pid,intervalMs=OWNER_HEARTBEAT_INTERVAL_MS,post=async body=>{await fetch(`${origin}/__bili/watcher`,{method:"POST",headers:{"content-type":"application/json"},body,signal:AbortSignal.timeout(OWNER_HEARTBEAT_POST_TIMEOUT_MS)})}){if(pid!==process.pid)return void 0;let stopped=false;const beat=async()=>{while(!stopped){await new Promise(r=>{const t=setTimeout(r,intervalMs);t.unref?.()});if(stopped)return;try{await post(JSON.stringify({pid,hb:true}))}catch{}}};void beat();return()=>{stopped=true}}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 attachTo=async inst=>{attachDiag(`bili: attaching to running proxy at ${inst.origin} (pid ${inst.pid})`);const reg=await registerWatcher(inst.origin,watchPid);startOwnerHeartbeat(inst.origin,watchPid);const handle2={origin:inst.origin,port:inst.port,attached:true};if(reg==="refused")handle2.refusedWatcher=true;return handle2};const script=deps.scriptPath??process.argv[1];const codeFingerprint=entryScriptFingerprint(script);const probed=await probeLiveInstances(readInstance,fetchHealthInfo,attachDiag);const existing=pickAttachable(probed,opts,codeFingerprint,attachExternal,attachPolicy,attachUrl,refusedLog,attachDiag,foreignLanes);if(existing){return attachTo(existing)}{await rotateStalePredecessor(probed,()=>{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},opts,attachUrl,foreignLanes,fetchHealthInfo,now,sleepImpl,deps?.requestInstanceShutdown??requestInstanceShutdown)}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);if(waited){return attachTo(waited)}return void 0};const starterLaneMatches=m3=>opts.lane===void 0||m3.lane===void 0||m3.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=randomUUID5();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=path28.join(os8.tmpdir(),`bili-proxy-${port}.log`);rotatePortLogIfNeeded(logPath2);const logFd=fs15.openSync(logPath2,"a");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:{...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"}:{}}})}finally{try{fs15.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 fd=fs15.openSync(logPath2,"r");try{const buf=Buffer.alloc(256);const n=fs15.readSync(fd,buf,0,buf.length,0);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 head: "${s3}"`}finally{fs15.closeSync(fd)}}catch{return""}};const logTail=()=>{try{const size=fs15.statSync(logPath2).size;const rotated=fs15.existsSync(`${logPath2}.old`)?`; earlier output rotated to ${logPath2}.old`:"";return size===0?`, ${size} bytes \u2014 EMPTY, the child produced no output of its own${rotated}`:`, ${size} bytes${rotated}${logHeadSample()}`}catch{return""}};const diagnosePort=async childAlive=>{const origin=proxyOrigin(opts.host,port);let info;let det={ok:false,detail:"probe error"};try{const[i,d3]=await Promise.all([fetchHealthInfo(origin),fetchDetail(healthUrl(origin))]);info=i;det=d3}catch{}if(info?.ok){return info.pid===child.pid?`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`:`port ${port} is held by a different process${info.pid!==void 0?` (pid ${info.pid})`:""} \u2014 the spawned child never bound it`}if(det.ok){return`port ${port} answered but not with bili's health payload \u2014 a foreign service likely holds it`}const d2=det.detail??"unknown error";if(/^(ECONNREFUSED|ECONNRESET|EHOSTUNREACH|ENETUNREACH|EPIPE)$/i.test(d2)){return`nothing is listening on port ${port} \u2014 the spawned child (${childAlive?"still alive":"already exited"}, pid ${child.pid??"?"}) never bound it`}if(/^HTTP \d{3}$/.test(d2)){return`port ${port} answered ${d2} \u2014 the listener there is not reporting bili health`}if(/^timeout after \d+ms$/i.test(d2)&&await(deps.isConnectable??tcpConnectable)(origin)){return`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)`}return`last health probe failed with ${d2}`};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)}) (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`)}}}const adoptServingTwin=async()=>{const candidates=(deps.listAdoptCandidates??discoverLiveInstances)().filter(inst=>isPidAlive(inst.pid)&&instanceCompatible(inst,opts,codeFingerprint,foreignLanes)===void 0).sort((a,b3)=>Number(b3.port===port)-Number(a.port===port)||b3.startedAt-a.startedAt);for(const inst of candidates){if(!await(deps.isConnectable??tcpConnectable)(inst.origin))continue;attachDiag(`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);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)} (runtime: ${runtime}) (log: ${logPath2}${logTail()})`)}const diagnosis=await diagnosePort(true);killAbandonedChild(child);console.error(`bili: killed spawned proxy (pid ${child.pid??"?"}) after ${SPAWN_BUDGET_MS}ms without health \u2014 ${diagnosis} (log: ${logPath2}${logTail()})`);throw new Error(`bili: proxy did not become healthy within ${SPAWN_BUDGET_MS}ms \u2014 ${diagnosis} (runtime: ${runtime}) (log: ${logPath2}${logTail()})`)}finally{if(claimed)clearStartingMarker(launchToken)}}function killAbandonedChild(child){if(!child||child.pid===void 0||child.pid<=0)return;if(process.platform!=="win32"){try{process.kill(-child.pid,"SIGKILL")}catch{}}else{try{spawnSync3("taskkill",["/F","/T","/PID",String(child.pid)],{windowsHide:true,stdio:"ignore"})}catch{}}try{child.kill?.("SIGKILL")}catch{}}var PATH_EXTS=process.platform==="win32"?[".cmd",".bat",".exe",""]:[""];import fs18 from"fs";import path32 from"path";import{fileURLToPath as fileURLToPath5}from"url";import{createHash as createHash17}from"crypto";init_chunk_VEDGC5EH();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(v3){if(Array.isArray(v3))return v3.map(canonicalize2);if(v3!==null&&typeof v3==="object"){const src=v3;const out={};for(const k2 of Object.keys(src).sort())out[k2]=canonicalize2(src[k2]);return out}return v3}var idSalt=null;function deriveCanonicalMessageId(role,contentType,text2,options={}){const seed=`${idSalt?idSalt+"|":""}${role}|${contentType}||${options.toolName??""}|${text2}`+(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 extractSystem(system){if(!system)return"";if(typeof system==="string")return system;return system.map(b3=>b3.text).join("\n\n")}function buildSystem(text2,original){if(Array.isArray(original)&&original.length>0){const ccBlock=original.find(b3=>b3.cache_control);return[{type:"text",text:text2,...ccBlock?{cache_control:ccBlock.cache_control}:{}}]}return text2}function anthropicToCore(body){const msgs=[];const cacheControls=new Map;const clusters=new ClusterCounter;const toolNames=new Map;for(const[wireIndex,m3]of body.messages.entries()){const before=msgs.length;if(m3.role==="system"){const core=systemMessageCore(m3,clusters);core.wireIndex=wireIndex;msgs.push(core);const mark=systemMessageMark(m3);if(mark)cacheControls.set(core.id,mark);continue}const blocks=typeof m3.content==="string"?[{type:"text",text:m3.content}]:m3.content;for(const b3 of blocks){switch(b3.type){case"text":{const base=deriveCanonicalMessageId(m3.role,"text",b3.text);const id=clusters.next(base);msgs.push({id,role:m3.role,contentType:"text",text:b3.text});if(b3.cache_control)cacheControls.set(id,b3.cache_control);break}case"tool_use":{const base=deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(safeStringify(b3.input)),{toolName:b3.name});const id=clusters.next(base);msgs.push({id,role:"assistant",contentType:"tool-call",toolName:b3.name,toolCallId:b3.id,text:safeStringify(b3.input)});toolNames.set(b3.id,b3.name);if(b3.cache_control)cacheControls.set(id,b3.cache_control);break}case"tool_result":{const hasNonText=Array.isArray(b3.content)&&b3.content.some(c=>c.type!=="text");const text2=typeof b3.content==="string"?b3.content:b3.content.map(c=>c.type==="text"?c.text:"").join("\n");const name=toolNames.get(b3.tool_use_id);const base=deriveCanonicalMessageId("tool","tool-result",text2,{toolName:name});const id=clusters.next(base);msgs.push({id,role:"tool",contentType:"tool-result",toolCallId:b3.tool_use_id,text:text2,...name?{toolName:name}:{},...b3.is_error===true?{toolIsError:true}:{},...hasNonText?{rawAnthropicBlock:b3}:{}});if(b3.cache_control)cacheControls.set(id,b3.cache_control);break}case"thinking":{const base=deriveCanonicalMessageId("assistant","reasoning",b3.thinking);msgs.push({id:clusters.next(base),role:"assistant",contentType:"reasoning",text:b3.thinking,...b3.signature?{thinkingSignature:b3.signature}:{}});break}case"image":{const source=b3.source&&typeof b3.source==="object"&&!Array.isArray(b3.source)?b3.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(m3.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:m3.role,contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawAnthropicBlock:b3,...mediaSidecar});break}case"redacted_thinking":{const base=deriveCanonicalMessageId(m3.role,"text",CANONICAL_REDACTED_THINKING_TEXT);msgs.push({id:clusters.next(base),role:m3.role,contentType:"text",text:"[redacted_thinking]",rawAnthropicBlock:b3});break}default:{const unknownType=b3.type;const label=typeof unknownType==="string"?`[${unknownType}]`:"[unknown]";const base=deriveCanonicalMessageId(m3.role,"text",label);msgs.push({id:clusters.next(base),role:m3.role,contentType:"text",text:label,rawAnthropicBlock:b3});break}}}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}}return{msgs,cacheControls}}function systemMessageCore(m3,clusters){const label=systemMessageText(m3);const base=deriveCanonicalMessageId("system","text",label);return{id:clusters.next(base),role:"system",contentType:"text",text:label,rawAnthropicMessage:m3}}function systemMessageText(m3){const text2=typeof m3.content==="string"?m3.content:m3.content.map(b3=>b3.type==="text"?b3.text:`[${b3.type}]`).join("\n");return text2.length>0?text2:"[system]"}function systemMessageMark(m3){if(typeof m3.content==="string")return void 0;let mark;for(const b3 of m3.content)if(b3.cache_control)mark=b3.cache_control;return mark}function rebuildSystemMessage(m3,mark){const raw=m3.rawAnthropicMessage;const cc=mark?{cache_control:mark}:{};const text2=m3.text??"";if(text2!==systemMessageText(raw)&&isPlainTextSystemMessage(raw)){return{role:"system",content:[{type:"text",text:text2,...cc}]}}if(!mark||systemMessageMark(raw)||typeof raw.content==="string"){return raw}const last=raw.content.length-1;if(last<0)return raw;return{...raw,content:raw.content.map((b3,i)=>i===last?{...b3,...cc}:b3)}}function isDirectiveOnlySystem(e){return e.role==="system"&&Array.isArray(e.content)&&e.content.length===0&&e.output_config!=null}function isToolUpdateBlock(b3){return b3.type==="tool_addition"||b3.type==="tool_removal"}function healIllegalSystemPositions(out){for(let j3=0;j3<out.length;j3++){const e=out[j3];if(!e||e.role!=="system"||isDirectiveOnlySystem(e))continue;let k2=j3+1;while(k2<out.length&&out[k2].role==="system")k2++;const next=out[k2];if(!next||next.role==="assistant")continue;if(typeof e.content==="string"){if(e.content===""){out.splice(j3,1);j3--}else{out[j3]={role:"user",content:e.content}}continue}const kept=e.content.filter(b3=>!isToolUpdateBlock(b3));if(kept.length===0){out.splice(j3,1);j3--;continue}out[j3]={role:"user",content:kept}}}function coreToAnthropic(messages,cacheControls){const out=[];let current=null;const flush=()=>{if(current&&current.blocks.length>0){out.push({role:current.role,content:current.blocks})}current=null};const cc=id=>{const v3=cacheControls?.get(id);return v3?{cache_control:v3}:{}};for(const m3 of messages){if(m3.rawAnthropicMessage){flush();out.push(rebuildSystemMessage(m3,cacheControls?.get(m3.id)));continue}const target=m3.role==="assistant"?"assistant":"user";if(!current||current.role!==target){flush();current={role:target,blocks:[]}}switch(m3.contentType){case"text":{if(m3.rawAnthropicBlock){current.blocks.push(m3.rawAnthropicBlock);break}current.blocks.push({type:"text",text:m3.text??"",...cc(m3.id)});break}case"tool-call":current.blocks.push({type:"tool_use",id:m3.toolCallId??`call_${m3.id}`,name:m3.toolName??"unknown",input:safeParse(m3.text),...cc(m3.id)});break;case"tool-result":if(m3.rawAnthropicBlock){current.blocks.push(m3.rawAnthropicBlock);break}current.blocks.push({type:"tool_result",tool_use_id:m3.toolCallId??"",content:m3.text??"",...m3.toolIsError?{is_error:true}:{},...cc(m3.id)});break;case"reasoning":current.blocks.push({type:"thinking",thinking:m3.text??"",...m3.thinkingSignature?{signature:m3.thinkingSignature}:{}});break}}flush();healIllegalSystemPositions(out);return out}function conversationSignalAnthropic(body,headerValue3){if(headerValue3&&headerValue3.trim())return headerValue3.trim();const msgs=Array.isArray(body?.messages)?body.messages:[];const firstUser=msgs.find(m3=>m3?.role==="user");const seed=firstUser?JSON.stringify(firstUser.content):"default";return hashId2(seed)}function safeStringify(v3){try{return JSON.stringify(v3??{})}catch{return"{}"}}function safeParse(s3){if(!s3)return{};try{return JSON.parse(s3)}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 m3=/^data:([^;,]+)(?:;base64)?,(.+)$/i.exec(url);if(!m3)return void 0;return{mediaType:m3[1],base64:m3[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,m3]of body.messages.entries()){const before=msgs.length;switch(m3.role){case"system":case"developer":{if(msgs.length===0){systemParts.push(stringContent(m3.content));break}const base=deriveCanonicalMessageId(m3.role,"text",stringContent(m3.content));msgs.push({id:clusters.next(base),role:"system",contentType:"text",text:stringContent(m3.content),originalRole:m3.role,rawOpenaiMessage:m3});break}case"user":{if(typeof m3.content==="string"||m3.content==null||!Array.isArray(m3.content)){const base=deriveCanonicalMessageId("user","text",typeof m3.content==="string"?m3.content:"");msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:typeof m3.content==="string"?m3.content:""});break}let lastTextCore=null;let leadingOpaque=[];let sawText=false;for(const part of m3.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=m3.reasoning_content;const fieldPresent=typeof rawReasoning==="string";const fieldReasoning=fieldPresent?rawReasoning:"";let reasoning=fieldReasoning;let text2=stringContent(m3.content);if(!reasoning){const split=splitDemotedThinking(text2);if(split){reasoning=split.reasoning;text2=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(text2){const base=deriveCanonicalMessageId("assistant","text",text2);msgs.push({id:clusters.next(base),role:"assistant",contentType:"text",text:text2,...blankEcho?{reasoningPresent:true}:{}})}if(Array.isArray(m3.tool_calls)){for(const tc of m3.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(m3.content),{toolName:m3.name||toolNames.get(m3.tool_call_id??"")});const name=m3.name||toolNames.get(m3.tool_call_id??"");msgs.push({id:clusters.next(base),role:"tool",contentType:"tool-result",toolCallId:m3.tool_call_id??"",text:stringContent(m3.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 coreToOpenai(messages){const out=[];let userRun=[];const flushUserRun=()=>{if(userRun.length===0)return;const parts=[];let plain=true;for(const m3 of userRun){if(m3.rawOpenaiContentParts&&m3.rawOpenaiContentParts.length>0){if(m3.text)parts.push({type:"text",text:m3.text});for(const part of m3.rawOpenaiContentParts)parts.push(part);plain=false}else if(m3.rawOpenaiContent){if(m3.text&&!m3.imagePart)parts.push({type:"text",text:m3.text});parts.push(m3.rawOpenaiContent);plain=false}else if(m3.imageBase64&&m3.imageMediaType){parts.push({type:"image_url",image_url:{url:`data:${m3.imageMediaType};base64,${m3.imageBase64}`}});plain=false}else{parts.push({type:"text",text:m3.text??""})}}if(plain&&userRun.length===1){out.push({role:"user",content:userRun[0].text??""})}else{out.push({role:"user",content:parts})}userRun=[]};let pending=null;const flush=()=>{if(!pending)return;const reasoning=pending.reasoning!==null&&pending.reasoning.length>0?pending.reasoning:void 0;const reasoningField=reasoning!==void 0?{reasoning_content:reasoning}:pending.reasoningPresent?{reasoning_content:""}:{};if(pending.toolCalls.length>0){out.push({role:"assistant",content:pending.text??null,tool_calls:pending.toolCalls,...reasoningField})}else if(pending.text!==null){out.push({role:"assistant",content:pending.text,...reasoningField})}else if(reasoning){out.push({role:"assistant",content:null,reasoning_content:reasoning})}pending=null};for(const m3 of messages){if(m3.role==="assistant"){flushUserRun();if(!pending)pending={text:null,toolCalls:[],reasoning:null,reasoningPresent:false};if(m3.reasoningPresent)pending.reasoningPresent=true;if(m3.contentType==="reasoning"){pending.reasoning=(pending.reasoning??"")+(m3.reasoningContent??m3.text??"")}else if(m3.contentType==="text"){pending.text=(pending.text??"")+(m3.text??"")}else if(m3.contentType==="tool-call"){pending.toolCalls.push({id:m3.toolCallId??`call_${m3.id}`,type:"function",function:{name:m3.toolName??"unknown",arguments:m3.text??""}})}}else{if(m3.role!=="user"){flush();flushUserRun()}if(m3.role==="system"){const raw=m3.rawOpenaiMessage;if(raw){const text2=m3.text??"";if(text2!==stringContent(raw.content)&&isPlainStringOrTextParts(raw.content)){out.push({role:m3.originalRole==="developer"?"developer":"system",content:typeof raw.content==="string"?text2:[{type:"text",text:text2}]})}else{out.push(raw)}}else{out.push({role:m3.originalRole==="developer"?"developer":"system",content:m3.text??""})}}else if(m3.role==="user"&&isSummaryMessageId(m3.id)&&m3.contentType==="text"){flush();flushUserRun();out.push({role:"user",content:m3.text??""})}else if(m3.role==="user"){flush();const prev=userRun[userRun.length-1];if(prev&&prev.wireIndex!==void 0&&m3.wireIndex!==void 0&&prev.wireIndex!==m3.wireIndex){flushUserRun()}userRun.push(m3)}else if(m3.role==="tool"){out.push({role:"tool",tool_call_id:m3.toolCallId??"",content:m3.text??""})}}}flush();flushUserRun();return out}function injectOpenaiSystem(messages,parts){if(parts.length===0)return messages;const extra=parts.join("\n\n");if(messages.length>0&&(messages[0]?.role==="system"||messages[0]?.role==="developer")){const head=messages[0];const base=stringContent(head.content);const merged=base?`${base}
830
830
 
831
831
  ---
832
832
 
@@ -6239,7 +6239,7 @@ ${bodyBuffer.toString("utf8")}`);gcDumpDirIfConfigured(rawDir)}catch(err2){logDu
6239
6239
 
6240
6240
  `,"utf8")};const buildFinish=(finishReason,usage)=>Buffer.from(`data: ${JSON.stringify({...makeBase(),choices:[{index:0,delta:{},finish_reason:finishReason}],...usage?{usage}:{}})}
6241
6241
 
6242
- `,"utf8");return{buildRequest(coreMessages,systemPrompt,body){const messages=hardenOpenaiAssistantContent(coreToOpenai(systemToUser(coreMessages,m3=>isRenderedSummaryMessage(m3))));const withSys=injectOpenaiSystem(messages,[clientSystem,systemPrompt].filter(p2=>typeof p2==="string"&&p2.length>0));const withNotes=notes&&notes.length>0?[...withSys,...notes.map(text2=>({role:"user",content:text2}))]:withSys;return{...body,messages:withNotes}},async*parseStream(upstream,round){const pending=new Map;const absorbArmedLocal=absorbName!==void 0;const requestText2=JSON.stringify(requestBody);const makeFieldFilter=()=>composeStreamFilters(composeStreamFilters(createTagEchoFilter(snippet=>{log("warn",`[tag-echo] stripped model-emitted render tag: ${snippet.slice(0,80).replace(/\n/g," ")}`)},snippet=>{log("warn",`[tag-echo] filter released echo-residue-shaped bytes (#2190): ${snippet.slice(0,80).replace(/\n/g," ")}`)},absorbArmedLocal,requestText2),createMarkerLineFilter(snippet=>{log("warn",`[marker-echo] stripped model-emitted ACP confirmation marker: ${snippet.slice(0,80).replace(/\n/g," ")}`)})),createBiliArtifactFilter(snippet=>{log("warn",`[bili-artifact] stripped model-emitted internal artifact: ${snippet.slice(0,80).replace(/\n/g," ")}`)}));const contentFilter=makeFieldFilter();const reasoningFilter=createIdentityStreamFilter();const flushFilter=function*(){const ct2=contentFilter.flush();if(ct2.length>0)yield{kind:"text",delta:ct2,raw:buildContent(ct2)};const rt3=reasoningFilter.flush();if(rt3.length>0)yield{kind:"reasoning",delta:rt3,raw:buildReasoning(rt3)}};let sawReasoning=false;let toolCallsEmitted=0;let degenerateWarned=false;const maybeWarnDegenerate=reason=>{if(degenerateWarned)return;const msg=degenerateTurnWarning({reason,terminalReason:"stop",toolCalls:toolCallsEmitted,text:contentFilter.stats(),sawThinking:sawReasoning,wire:"openai"});if(msg){degenerateWarned=true;log("warn",msg)}};let stripSummarized=false;const maybeSummarizeStrips=()=>{if(stripSummarized)return;stripSummarized=true;const total=contentFilter.stats().dropCount;if(total>1)log("warn",`[tag-echo] stripped ${total} occurrence(s) total in this response`)};const rawToolChunks=[];let sawRealToolCall=false;const absorbToolCallDeltas=tcs=>{for(const tc of tcs){const idx=typeof tc.index==="number"?tc.index:0;const fn=tc.function;const name=typeof fn?.name==="string"?fn.name:"";const id=typeof tc.id==="string"?tc.id:"";const rawArgs=fn?.arguments;const args=typeof rawArgs==="string"?rawArgs:rawArgs!==null&&typeof rawArgs==="object"?JSON.stringify(rawArgs):"";let buf=pending.get(idx);if(!buf){buf={index:idx,id,name,arguments:args,frags:1,nameInFirst:name.length>0};pending.set(idx,buf)}else{if(id)buf.id=id;buf.name+=name;buf.arguments+=args;buf.frags+=1}}};const flushPendingAsStructured=function*(){for(const[idx,tc]of pending){if(tc.name.length>0||tc.id.length>0){toolCallsEmitted++;yield{kind:"tool_call",name:tc.name,callId:tc.id,arguments:tc.arguments}}else if(tc.arguments.length>0){log("warn",`[acp-openai] dropping orphan tool_call buffer idx=${idx} argsLen=${tc.arguments.length} (#1306)`)}}pending.clear()};const settleToolCalls=function*(){if(pending.size===0)return;const realIndexes=new Set;for(const[idx,tc]of pending){if(tc.name.length>0&&!PROXY_TOOL_SET.has(tc.name)&&tc.name!==absorbName)realIndexes.add(idx)}sawRealToolCall=realIndexes.size>0;{const parts=[];let anyNameless=false;for(const idx of[...pending.keys()].sort((a,b3)=>a-b3)){const tc=pending.get(idx);if(tc.name.length===0)anyNameless=true;const disp=realIndexes.has(idx)?"replayed":tc.name.length===0?"nameless":"proxy";parts.push(`idx=${idx} name=${tc.name.length>0?JSON.stringify(tc.name):"<none>"}${tc.id?` id=${tc.id}`:""} argsLen=${tc.arguments.length} frags=${tc.frags}${tc.nameInFirst===false?" name-split":""} \u2192 ${disp}`)}yield{kind:"diag",level:anyNameless?"warn":"info",message:`[acp-openai] round ${round} tool-frame settle (${parts.length}): ${parts.join(" | ")}`}}if(!sawRealToolCall){yield*flushPendingAsStructured();for(const{parsed}of rawToolChunks){const prose=withheldProseFrame(parsed);if(prose)yield{kind:"meta",chunk:prose}}return}for(const[idx,tc]of pending){if(realIndexes.has(idx)&&(tc.name.length>0||tc.id.length>0)){toolCallsEmitted++;yield{kind:"tool_call",name:tc.name,callId:tc.id,arguments:tc.arguments,passthrough:true}}}for(const{json,parsed}of rawToolChunks){const filtered=filterRealToolFragments(parsed,realIndexes);if(filtered==="keep"){yield{kind:"meta",chunk:Buffer.from("data: "+json+"\n\n","utf8")}}else if(filtered!==null){yield{kind:"meta",chunk:Buffer.from("data: "+JSON.stringify(filtered)+"\n\n","utf8")}}else{const prose=withheldProseFrame(parsed);if(prose)yield{kind:"meta",chunk:prose}}}for(const[idx,tc]of pending){if(!realIndexes.has(idx)&&tc.name.length>0){toolCallsEmitted++;yield{kind:"tool_call",name:tc.name,callId:tc.id,arguments:tc.arguments}}}pending.clear()};for await(const eventStr of iterSseChunks(upstream)){const dataLine2=eventStr.split("\n").find(l3=>l3.startsWith("data:"));if(!dataLine2)continue;const jsonStr=dataLine2.slice(5).trim();if(jsonStr==="[DONE]"){yield*flushFilter();if(sawRealToolCall){yield{kind:"meta",chunk:Buffer.from(eventStr+"\n\n","utf8")};continue}yield*settleToolCalls();if(sawRealToolCall){yield{kind:"meta",chunk:Buffer.from(eventStr+"\n\n","utf8")}}maybeWarnDegenerate("stop");maybeSummarizeStrips();yield{kind:"done",finishReason:"stop",thinking:sawReasoning,...sawRealToolCall?{suppressCompletion:true}:{}};continue}let parsed;try{parsed=JSON.parse(jsonStr)}catch{continue}const rawBuf=Buffer.from(eventStr+"\n\n","utf8");const streamError=parsed.error;if(streamError!==void 0&&streamError!==null){let message;if(typeof streamError==="string"){message=streamError}else if(typeof streamError==="object"){const error=streamError;const detail=typeof error.message==="string"?error.message:JSON.stringify(streamError);const code=typeof error.code==="string"?error.code:void 0;message=code&&detail?`${code}: ${detail}`:detail}else{message=String(streamError)}yield{kind:"error",message};return}const choices=parsed.choices;const choice=choices?.[0];if(!choice){if(parsed.usage){const u2=parsed.usage;yield{kind:"usage",inputTokens:typeof u2.prompt_tokens==="number"?u2.prompt_tokens:void 0,outputTokens:typeof u2.completion_tokens==="number"?u2.completion_tokens:void 0,cachedTokens:openaiCachedTokens(u2)};if(sawRealToolCall){yield{kind:"meta",chunk:rawBuf}}}continue}const delta=choice.delta;const finishReason=typeof choice.finish_reason==="string"?choice.finish_reason:void 0;const frameToolCalls=delta?.tool_calls;if(frameToolCalls)absorbToolCallDeltas(frameToolCalls);if(finishReason){yield*flushFilter();const hadToolCalls=[...pending.values()].some(tc=>tc.name.length>0||tc.id.length>0);yield*settleToolCalls();const u2=parsed.usage;yield{kind:"usage",inputTokens:typeof u2?.prompt_tokens==="number"?u2.prompt_tokens:void 0,outputTokens:typeof u2?.completion_tokens==="number"?u2.completion_tokens:void 0,cachedTokens:u2?openaiCachedTokens(u2):void 0};if(sawRealToolCall){const chunk=rawBuf;yield{kind:"meta",chunk};maybeWarnDegenerate(finishReason);maybeSummarizeStrips();yield{kind:"done",finishReason,suppressCompletion:true,thinking:sawReasoning};continue}else{maybeWarnDegenerate(finishReason);maybeSummarizeStrips();yield{kind:"done",finishReason:hadToolCalls&&finishReason==="stop"?"tool_calls":finishReason,thinking:sawReasoning}}}if(!delta)continue;const rcIn=typeof delta.reasoning_content==="string"&&delta.reasoning_content.length>0?delta.reasoning_content:null;const ctIn=typeof delta.content==="string"&&delta.content.length>0?delta.content:null;let rcOut=rcIn;let ctOut=ctIn;if(rcIn!==null){sawReasoning=true;rcOut=reasoningFilter.push(rcIn)}if(ctIn!==null){ctOut=contentFilter.push(ctIn)}const rcChanged=rcIn!==null&&rcOut!==rcIn;const ctChanged=ctIn!==null&&ctOut!==ctIn;if(frameToolCalls){let json=jsonStr;let obj=parsed;if(rcChanged||ctChanged){const fields={};if(ctIn!==null)fields["content"]=ctOut??"";if(rcIn!==null)fields["reasoning_content"]=rcOut??"";obj=applyDeltaFields(parsed,fields);json=JSON.stringify(obj)}rawToolChunks.push({json,parsed:obj});if(rcOut!==null&&rcOut.length>0){yield{kind:"reasoning",delta:rcOut}}if(ctOut!==null&&ctOut.length>0){yield{kind:"text",delta:ctOut}}continue}const fin=b3=>finishReason?stripFinishReasonChunk(b3):b3;if(rcIn!==null&&ctIn!==null){const raw=rcChanged||ctChanged?rewriteDeltaFields(parsed,{content:ctOut??"",reasoning_content:rcOut??""}):rawBuf;const fwd=fin(raw);const hasText=ctOut!==null&&ctOut.length>0;const hasReason=rcOut!==null&&rcOut.length>0;if(hasReason&&hasText){yield{kind:"reasoning",delta:rcOut,raw:fwd};yield{kind:"text",delta:ctOut}}else if(hasReason){yield{kind:"reasoning",delta:rcOut,raw:fwd}}else if(hasText){yield{kind:"text",delta:ctOut,raw:fwd}}}else if(rcIn!==null){const raw=rcChanged?rewriteDeltaFields(parsed,{reasoning_content:rcOut??""}):rawBuf;yield{kind:"reasoning",delta:rcOut??"",raw:fin(raw)}}else if(ctIn!==null){const raw=ctChanged?rewriteDeltaFields(parsed,{content:ctOut??""}):rawBuf;yield{kind:"text",delta:ctOut??"",raw:fin(raw)}}else if(delta.role||Object.keys(delta).length===0&&!finishReason){yield{kind:"meta",chunk:fin(rawBuf),firstRoundOnly:true}}}},emitText(delta){return buildContent(delta)},emitReasoning(delta){return buildReasoning(delta)},emitToolCall(call){return buildToolCall(call)},emitMarker(toolName,result){return buildContent(buildVisibilityMarker(toolName,result))},emitCompletion(opts){const finishReason=opts?.finishReason??"stop";const usage=opts?.usage?{prompt_tokens:opts.usage.inputTokens??0,completion_tokens:opts.usage.outputTokens??0,total_tokens:(opts.usage.inputTokens??0)+(opts.usage.outputTokens??0),...typeof opts.usage.cachedTokens==="number"?{prompt_tokens_details:{cached_tokens:opts.usage.cachedTokens}}:{}}:null;return Buffer.concat([buildFinish(finishReason,usage),Buffer.from("data: [DONE]\n\n","utf8")])},emitError(message){if(errorShape==="completion"){return Buffer.concat([buildContent(`
6242
+ `,"utf8");return{buildRequest(coreMessages,systemPrompt,body){const messages=hardenOpenaiAssistantContent(coreToOpenai(systemToUser(coreMessages,m3=>isRenderedSummaryMessage(m3))));const withSys=injectOpenaiSystem(messages,[clientSystem,systemPrompt].filter(p2=>typeof p2==="string"&&p2.length>0));const withNotes=notes&&notes.length>0?[...withSys,...notes.map(text2=>({role:"user",content:text2}))]:withSys;return{...body,messages:withNotes}},async*parseStream(upstream,round){const pending=new Map;const absorbArmedLocal=absorbName!==void 0;const requestText2=JSON.stringify(requestBody);const makeFieldFilter=()=>composeStreamFilters(composeStreamFilters(createTagEchoFilter(snippet=>{log("warn",`[tag-echo] stripped model-emitted render tag: ${snippet.slice(0,80).replace(/\n/g," ")}`)},snippet=>{log("warn",`[tag-echo] filter released echo-residue-shaped bytes (#2190): ${snippet.slice(0,80).replace(/\n/g," ")}`)},absorbArmedLocal,requestText2),createMarkerLineFilter(snippet=>{log("warn",`[marker-echo] stripped model-emitted ACP confirmation marker: ${snippet.slice(0,80).replace(/\n/g," ")}`)})),createBiliArtifactFilter(snippet=>{log("warn",`[bili-artifact] stripped model-emitted internal artifact: ${snippet.slice(0,80).replace(/\n/g," ")}`)}));const contentFilter=makeFieldFilter();const reasoningFilter=createIdentityStreamFilter();const flushFilter=function*(){const ct2=contentFilter.flush();if(ct2.length>0)yield{kind:"text",delta:ct2,raw:buildContent(ct2)};const rt3=reasoningFilter.flush();if(rt3.length>0)yield{kind:"reasoning",delta:rt3,raw:buildReasoning(rt3)}};let sawReasoning=false;let toolCallsEmitted=0;let degenerateWarned=false;const maybeWarnDegenerate=reason=>{if(degenerateWarned)return;const msg=degenerateTurnWarning({reason,terminalReason:"stop",toolCalls:toolCallsEmitted,text:contentFilter.stats(),sawThinking:sawReasoning,wire:"openai"});if(msg){degenerateWarned=true;log("warn",msg)}};let stripSummarized=false;const maybeSummarizeStrips=()=>{if(stripSummarized)return;stripSummarized=true;const total=contentFilter.stats().dropCount;if(total>1)log("warn",`[tag-echo] stripped ${total} occurrence(s) total in this response`)};const rawToolChunks=[];let sawRealToolCall=false;const absorbToolCallDeltas=tcs=>{for(const tc of tcs){const idx=typeof tc.index==="number"?tc.index:0;const fn=tc.function;const name=typeof fn?.name==="string"?fn.name:"";const id=typeof tc.id==="string"?tc.id:"";const rawArgs=fn?.arguments;const args=typeof rawArgs==="string"?rawArgs:rawArgs!==null&&typeof rawArgs==="object"?JSON.stringify(rawArgs):"";let buf=pending.get(idx);if(!buf){buf={index:idx,id,name,arguments:args,frags:1,nameInFirst:name.length>0};pending.set(idx,buf)}else{if(id)buf.id=id;buf.name+=name;buf.arguments+=args;buf.frags+=1}}};const flushPendingAsStructured=function*(){for(const[idx,tc]of pending){if(tc.name.length>0||tc.id.length>0){toolCallsEmitted++;yield{kind:"tool_call",name:tc.name,callId:tc.id,arguments:tc.arguments}}else if(tc.arguments.length>0){log("warn",`[acp-openai] dropping orphan tool_call buffer idx=${idx} argsLen=${tc.arguments.length} (#1306)`)}}pending.clear()};const settleToolCalls=function*(){if(pending.size===0)return;const realIndexes=new Set;for(const[idx,tc]of pending){if(tc.name.length>0&&!PROXY_TOOL_SET.has(tc.name)&&tc.name!==absorbName)realIndexes.add(idx)}sawRealToolCall=realIndexes.size>0;{const parts=[];let anyNameless=false;for(const idx of[...pending.keys()].sort((a,b3)=>a-b3)){const tc=pending.get(idx);if(tc.name.length===0)anyNameless=true;const disp=realIndexes.has(idx)?"replayed":tc.name.length===0?"nameless":"proxy";parts.push(`idx=${idx} name=${tc.name.length>0?JSON.stringify(tc.name):"<none>"}${tc.id?` id=${tc.id}`:""} argsLen=${tc.arguments.length} frags=${tc.frags}${tc.nameInFirst===false?" name-split":""} \u2192 ${disp}`)}yield{kind:"diag",level:anyNameless?"warn":"info",message:`[acp-openai] round ${round} tool-frame settle (${parts.length}): ${parts.join(" | ")}`}}if(!sawRealToolCall){yield*flushPendingAsStructured();for(const{parsed}of rawToolChunks){const prose=withheldProseFrame(parsed);if(prose)yield{kind:"meta",chunk:prose}}return}for(const[idx,tc]of pending){if(realIndexes.has(idx)&&(tc.name.length>0||tc.id.length>0)){toolCallsEmitted++;yield{kind:"tool_call",name:tc.name,callId:tc.id,arguments:tc.arguments,passthrough:true}}}for(const{json,parsed}of rawToolChunks){const filtered=filterRealToolFragments(parsed,realIndexes);if(filtered==="keep"){yield{kind:"meta",chunk:Buffer.from("data: "+json+"\n\n","utf8")}}else if(filtered!==null){yield{kind:"meta",chunk:Buffer.from("data: "+JSON.stringify(filtered)+"\n\n","utf8")}}else{const prose=withheldProseFrame(parsed);if(prose)yield{kind:"meta",chunk:prose}}}for(const[idx,tc]of pending){if(!realIndexes.has(idx)&&tc.name.length>0){toolCallsEmitted++;yield{kind:"tool_call",name:tc.name,callId:tc.id,arguments:tc.arguments}}}pending.clear()};for await(const eventStr of iterSseChunks(upstream)){const dataLine2=eventStr.split("\n").find(l3=>l3.startsWith("data:"));if(!dataLine2)continue;const jsonStr=dataLine2.slice(5).trim();if(jsonStr==="[DONE]"){yield*flushFilter();if(sawRealToolCall){yield{kind:"meta",chunk:Buffer.from(eventStr+"\n\n","utf8")};continue}yield*settleToolCalls();if(sawRealToolCall){yield{kind:"meta",chunk:Buffer.from(eventStr+"\n\n","utf8")}}maybeWarnDegenerate("stop");maybeSummarizeStrips();yield{kind:"done",finishReason:"stop",thinking:sawReasoning,...sawRealToolCall?{suppressCompletion:true}:{}};continue}let parsed;try{parsed=JSON.parse(jsonStr)}catch{continue}const rawBuf=Buffer.from(eventStr+"\n\n","utf8");const streamError=parsed.error;if(streamError!==void 0&&streamError!==null){let message;if(typeof streamError==="string"){message=streamError}else if(typeof streamError==="object"){const error=streamError;const detail=typeof error.message==="string"?error.message:JSON.stringify(streamError);const code=typeof error.code==="string"?error.code:void 0;message=code&&detail?`${code}: ${detail}`:detail}else{message=String(streamError)}yield{kind:"error",message};return}const choices=parsed.choices;const choice=choices?.[0];if(!choice){if(parsed.usage){const u2=parsed.usage;yield{kind:"usage",inputTokens:typeof u2.prompt_tokens==="number"?u2.prompt_tokens:void 0,outputTokens:typeof u2.completion_tokens==="number"?u2.completion_tokens:void 0,cachedTokens:openaiCachedTokens(u2)};if(sawRealToolCall){yield{kind:"meta",chunk:rawBuf}}}continue}const delta=choice.delta;const finishReason=typeof choice.finish_reason==="string"?choice.finish_reason:void 0;const frameToolCalls=Array.isArray(delta?.tool_calls)&&delta.tool_calls.length>0?delta.tool_calls:void 0;if(frameToolCalls)absorbToolCallDeltas(frameToolCalls);if(finishReason){yield*flushFilter();const hadToolCalls=[...pending.values()].some(tc=>tc.name.length>0||tc.id.length>0);yield*settleToolCalls();const u2=parsed.usage;yield{kind:"usage",inputTokens:typeof u2?.prompt_tokens==="number"?u2.prompt_tokens:void 0,outputTokens:typeof u2?.completion_tokens==="number"?u2.completion_tokens:void 0,cachedTokens:u2?openaiCachedTokens(u2):void 0};if(sawRealToolCall){const chunk=rawBuf;yield{kind:"meta",chunk};maybeWarnDegenerate(finishReason);maybeSummarizeStrips();yield{kind:"done",finishReason,suppressCompletion:true,thinking:sawReasoning};continue}else{maybeWarnDegenerate(finishReason);maybeSummarizeStrips();yield{kind:"done",finishReason:hadToolCalls&&finishReason==="stop"?"tool_calls":finishReason,thinking:sawReasoning}}}if(!delta)continue;const rcIn=typeof delta.reasoning_content==="string"&&delta.reasoning_content.length>0?delta.reasoning_content:null;const ctIn=typeof delta.content==="string"&&delta.content.length>0?delta.content:null;let rcOut=rcIn;let ctOut=ctIn;if(rcIn!==null){sawReasoning=true;rcOut=reasoningFilter.push(rcIn)}if(ctIn!==null){ctOut=contentFilter.push(ctIn)}const rcChanged=rcIn!==null&&rcOut!==rcIn;const ctChanged=ctIn!==null&&ctOut!==ctIn;if(frameToolCalls){let json=jsonStr;let obj=parsed;if(rcChanged||ctChanged){const fields={};if(ctIn!==null)fields["content"]=ctOut??"";if(rcIn!==null)fields["reasoning_content"]=rcOut??"";obj=applyDeltaFields(parsed,fields);json=JSON.stringify(obj)}rawToolChunks.push({json,parsed:obj});if(rcOut!==null&&rcOut.length>0){yield{kind:"reasoning",delta:rcOut}}if(ctOut!==null&&ctOut.length>0){yield{kind:"text",delta:ctOut}}continue}const fin=b3=>finishReason?stripFinishReasonChunk(b3):b3;if(rcIn!==null&&ctIn!==null){const raw=rcChanged||ctChanged?rewriteDeltaFields(parsed,{content:ctOut??"",reasoning_content:rcOut??""}):rawBuf;const fwd=fin(raw);const hasText=ctOut!==null&&ctOut.length>0;const hasReason=rcOut!==null&&rcOut.length>0;if(hasReason&&hasText){yield{kind:"reasoning",delta:rcOut,raw:fwd};yield{kind:"text",delta:ctOut}}else if(hasReason){yield{kind:"reasoning",delta:rcOut,raw:fwd}}else if(hasText){yield{kind:"text",delta:ctOut,raw:fwd}}}else if(rcIn!==null){const raw=rcChanged?rewriteDeltaFields(parsed,{reasoning_content:rcOut??""}):rawBuf;yield{kind:"reasoning",delta:rcOut??"",raw:fin(raw)}}else if(ctIn!==null){const raw=ctChanged?rewriteDeltaFields(parsed,{content:ctOut??""}):rawBuf;yield{kind:"text",delta:ctOut??"",raw:fin(raw)}}else if(delta.role||Object.keys(delta).length===0&&!finishReason){yield{kind:"meta",chunk:fin(rawBuf),firstRoundOnly:true}}}},emitText(delta){return buildContent(delta)},emitReasoning(delta){return buildReasoning(delta)},emitToolCall(call){return buildToolCall(call)},emitMarker(toolName,result){return buildContent(buildVisibilityMarker(toolName,result))},emitCompletion(opts){const finishReason=opts?.finishReason??"stop";const usage=opts?.usage?{prompt_tokens:opts.usage.inputTokens??0,completion_tokens:opts.usage.outputTokens??0,total_tokens:(opts.usage.inputTokens??0)+(opts.usage.outputTokens??0),...typeof opts.usage.cachedTokens==="number"?{prompt_tokens_details:{cached_tokens:opts.usage.cachedTokens}}:{}}:null;return Buffer.concat([buildFinish(finishReason,usage),Buffer.from("data: [DONE]\n\n","utf8")])},emitError(message){if(errorShape==="completion"){return Buffer.concat([buildContent(`
6243
6243
  [acp-proxy: ${message}]
6244
6244
  `),buildFinish("stop",null),Buffer.from("data: [DONE]\n\n","utf8")])}return Buffer.concat([Buffer.from(`data: ${JSON.stringify({error:{type:"server_error",code:"upstream_error",message:`[acp-proxy: ${message}]`}})}
6245
6245
 
@@ -1,3 +1,3 @@
1
1
  {
2
- "commit": "e5183631"
2
+ "commit": "f161c518"
3
3
  }