@wengine-ai/llms 2.3.12 → 2.3.13

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.
@@ -71,7 +71,7 @@ ${this.toMarkdown(o,n+1)}`:`${r}- ${o}`).join(`
71
71
  ${this.toMarkdown(s,n+1)}`:`${r}${o}: ${s}`).join(`
72
72
  `):`${r}${e}`}async output(e,n={}){try{let r=this.formatData(e,n);switch(this.config.level||"log"){case"info":console.info(r);break;case"warn":console.warn(r);break;case"error":console.error(r);break;case"debug":console.debug(r);break;case"log":default:console.log(r);break}return!0}catch(r){return console.error("[ConsoleOutputHandler] Output failed:",r),!1}}}});var bs,pf=Le(()=>{"use strict";bs=class{type="webhook";config;defaultTimeout=3e4;constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let n=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${n}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,n){let{format:r="json",timestamp:o=!0,prefix:s,metadata:a}=n||{},u={data:e};return o&&(u.timestamp=new Date().toISOString()),s&&(u.prefix=s),a&&Object.keys(a).length>0&&(u.metadata=a),u}async sendRequest(e,n,r,o,s){let a=new AbortController,u=setTimeout(()=>a.abort(),s);try{let l=await fetch(e,{method:n,headers:r,body:JSON.stringify(o),signal:a.signal});if(clearTimeout(u),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(u),l}}delay(e){return new Promise(n=>setTimeout(n,e))}async sendWithRetry(e,n,r,o,s,a){let u=null;for(let l=1;l<=a.maxAttempts;l++)try{return await this.sendRequest(e,n,r,o,s)}catch(d){if(u=d,l===a.maxAttempts)break;let f=a.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${a.maxAttempts}), retrying in ${f}ms...`,d.message),await this.delay(f)}throw u}async output(e,n={}){let r=n.timeout||this.defaultTimeout;try{let o=this.buildHeaders(),s=this.buildBody(e,n),a=await this.sendWithRetry(this.config.url,this.config.method,o,s,r,this.config.retry);return!0}catch(o){let s=o instanceof Error?o.message:String(o);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});import{writeFileSync as HR,existsSync as WR,mkdirSync as GR}from"fs";import{join as f_}from"path";import{tmpdir as JR}from"os";var Cs,mf=Le(()=>{"use strict";Cs=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let n=JR();this.baseDir=f_(n,this.config.subdirectory),this.ensureDir()}ensureDir(){try{WR(this.baseDir)||GR(this.baseDir,{recursive:!0})}catch{}}getFilePath(e){let n=this.config.prefix||"session",r=this.config.extension?`.${this.config.extension}`:"",o;if(this.config.includeTimestamp){let s=Date.now();o=`${n}-${e}-${s}${r}`}else o=`${n}-${e}${r}`;return f_(this.baseDir,o)}async output(e,n={}){try{let r=n.metadata?.sessionId;if(!r)return!1;let o={...e,timestamp:Date.now(),sessionId:r},s=this.getFilePath(r);return HR(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var gf,Eo,h_=Le(()=>{"use strict";hf();pf();mf();gf=class{handlers=new Map;defaultOptions={};registerHandler(e,n){this.handlers.set(e,n)}registerHandlers(e){for(let n of e)if(n.enabled!==!1)try{let r=this.createHandler(n),o=n.type+"_"+Date.now();this.registerHandler(o,r)}catch(r){console.error(`[OutputManager] Failed to register ${n.type} handler:`,r)}}createHandler(e){switch(e.type){case"console":return new _s(e.config);case"webhook":return new bs(e.config);case"temp-file":return new Cs(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,n){let r={...this.defaultOptions,...n},o={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,u])=>{try{await u.output(e,r)?o.success.push(a):o.failed.push(a)}catch(l){console.error(`[OutputManager] Handler ${a} failed:`,l),o.failed.push(a)}});return await Promise.all(s),o}async outputTo(e,n,r){let o={...this.defaultOptions,...r},s={success:[],failed:[]},a=e.map(async u=>{let l=this.handlers.get(u);if(!l){console.warn(`[OutputManager] Handler ${u} not found`),s.failed.push(u);return}try{await l.output(n,o)?s.success.push(u):s.failed.push(u)}catch(d){console.error(`[OutputManager] Handler ${u} failed:`,d),s.failed.push(u)}});return await Promise.all(a),s}async outputToType(e,n,r){let o=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(o,n,r)}},Eo=new gf});import KR from"fastify";import YR from"@fastify/cors";var Ih=Ln(Wu(),1);import{readFileSync as hC,existsSync as Ph}from"fs";import{join as Fh}from"path";import{config as pC}from"dotenv";var Ir=class{config={};options;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:Fh(process.cwd(),this.options.jsonPath);if(Ph(e))try{let n=hC(e,"utf-8"),r=Ih.default.parse(n);this.config={...this.config,...r},console.log(`Loaded JSON config from: ${e}`)}catch(n){console.warn(`Failed to load JSON config from ${e}:`,n)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:Fh(process.cwd(),this.options.envPath);if(Ph(e))try{let n=pC({path:e});n.parsed&&(this.config={...this.config,...this.parseEnvConfig(n.parsed)})}catch(n){console.warn(`Failed to load .env config from ${e}:`,n)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let n={};return Object.assign(n,e),n}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,n){let r=this.config[e];return r!==void 0?r:n}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}has(e){return this.config[e]!==void 0}set(e,n){this.config[e]=n}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}};function He(t,e=500,n="internal_error",r="api_error"){let o=new Error(t);return o.statusCode=e,o.code=n,o.type=r,o}async function Nh(t,e,n){e.log.error(t);let r=t.statusCode||500;if(t.rawBody)try{let s=JSON.parse(t.rawBody);return n.code(r).send(s)}catch{return n.code(r).send(t.rawBody)}let o={error:{message:t.message+(t.stack||"Internal Server Error"),type:t.type||"api_error",code:t.code||"internal_error"}};return n.code(r).send(o)}import{ProxyAgent as mC}from"undici";function Bh(t,e,n,r,o){let s=new Headers({"Content-Type":"application/json"});n.headers&&Object.entries(n.headers).forEach(([d,f])=>{f&&s.set(d,f)});let a,u=AbortSignal.timeout(n.TIMEOUT??60*1e3*60);if(n.signal){let d=new AbortController,f=()=>d.abort();n.signal.addEventListener("abort",f),u.addEventListener("abort",f),a=d.signal}else a=u;let l={method:"POST",headers:s,body:JSON.stringify(e),signal:a};return n.httpsProxy&&(l.dispatcher=new mC(new URL(n.httpsProxy).toString())),o?.debug({reqId:r.req.id,request:l,headers:Object.fromEntries(s.entries()),requestUrl:typeof t=="string"?t:t.toString(),useProxy:n.httpsProxy},"final request"),fetch(typeof t=="string"?t:t.toString(),l)}var gC=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Nr={maxBodyLength:4096,maxStreamChunks:100},Gu=!1;function yC(t){Gu=t}function _C(){return Gu}function ti(t){return Gu||t.get("DEBUG_LOG")===!0}function jh(t){let e=t.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Nr:{maxBodyLength:e.maxBodyLength??Nr.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Nr.maxStreamChunks}}function Uh(t){let e={};for(let[n,r]of Object.entries(t))gC.has(n.toLowerCase())?e[n]="***MASKED***":e[n]=r;return e}function ni(t,e){return t.length<=e?t:t.slice(0,e)+`...[truncated, total ${t.length} bytes]`}function $h(t,e,n){let r=typeof n.body=="string"?n.body:JSON.stringify(n.body);t.info({debug_log:!0,reqId:e,phase:"provider_request",url:n.url,headers:Uh(n.headers),body:ni(r,Nr.maxBodyLength)})}function qh(t,e,n){t.info({debug_log:!0,reqId:e,phase:"provider_response",status:n.status,headers:Uh(n.headers),...n.body!==void 0?{body:ni(n.body,Nr.maxBodyLength)}:{}})}function Mh(t,e,n,r){let o=bC(r);t.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:n,...o?{usage_monitor:o}:{},data:ni(r,Nr.maxBodyLength)})}function bC(t){let e=[];for(let n of t.split(/\r?\n/)){if(!n.startsWith("data:"))continue;let r=n.slice(5).trim();if(!(!r||r==="[DONE]"))try{let o=JSON.parse(r),s=o?.usage||o?.response?.usage;s&&e.push({path:o?.usage?"usage":"response.usage",usage:s,choicesLength:Array.isArray(o?.choices)?o.choices.length:void 0,finishReason:o?.choices?.[0]?.finish_reason})}catch{e.push({parseError:!0,data:ni(r,512)})}}if(e.length)return e.length===1?e[0]:e}function Lh(t,e,n){t.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:n})}function zh(t,e,n,r){(async()=>{let o=t.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:u,value:l}=await o.read();if(u)break;a+=l;let d=a.split(`
73
73
 
74
- `);a=d.pop()||"";for(let f of d)f.trim()&&(s<r.maxStreamChunks?Mh(e,n,s,f):s===r.maxStreamChunks&&e.info({debug_log:!0,reqId:n,phase:"provider_stream_chunk_omitted",message:`[chunks after #${s} omitted, maxStreamChunks=${r.maxStreamChunks}]`}),s++)}a.trim()&&(s<r.maxStreamChunks&&Mh(e,n,s,a.trim()),s++),Lh(e,n,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${n}:`,a),Lh(e,n,s)}finally{o.releaseLock()}})()}var ri="2.3.12";Un();import{existsSync as Xh,mkdirSync as OC,readFileSync as PC,writeFileSync as FC}from"fs";import{join as Zh}from"path";import{HOME_DIR as IC}from"@wengine-ai/claude-code-router-shared";var Zu=Zh(IC,"runtime"),ec=Zh(Zu,"rate-limit.json"),Br=new Map,Kh=!1,NC=null,BC=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],MC=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],LC=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"];function Io(t,e,n){let r=u=>{if(n instanceof Headers)return n.get(u);let l=Object.keys(n).find(d=>d.toLowerCase()===u);return l?n[l]:null},o=Xu(r,BC),s=Xu(r,MC),a=Xu(r,LC);(o||s||a)&&Br.set(t,{provider:t,remaining:Yh(o),limit:Yh(s),reset:$C(a),capturedAt:Date.now()})}function jC(t){return Br.get(t)}function UC(){return Array.from(Br.values())}function Xu(t,e){for(let n of e){let r=t(n);if(r)return r}return null}function Yh(t){if(!t)return null;let e=Number(t.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function $C(t){if(!t)return null;let e=t.trim();if(!e)return null;let n=Number(e);if(Number.isFinite(n))return n>1e12?Math.floor(n/1e3):n>1e9?Math.floor(n):Math.floor(Date.now()/1e3+n);let r=Date.parse(e);if(Number.isFinite(r))return Math.floor(r/1e3);let o=qC(e);return o===null?null:Math.floor((Date.now()+o)/1e3)}function qC(t){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,n=0,r=!1;for(let o of t.matchAll(e)){r=!0;let s=Number(o[1]),a=o[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":n+=s;break;case"s":n+=s*1e3;break;case"m":n+=s*60*1e3;break;case"h":n+=s*60*60*1e3;break;case"d":n+=s*24*60*60*1e3;break}}return r?n:null}function zC(){try{if(!Xh(ec))return;let t=JSON.parse(PC(ec,"utf-8"));if(!Array.isArray(t))return;let e=Date.now();for(let n of t)if(n&&n.provider){if(n.capturedAt&&e-n.capturedAt>3600*1e3)continue;Br.set(n.provider,n)}}catch{}}function Qh(){try{if(Br.size===0)return;Xh(Zu)||OC(Zu,{recursive:!0}),FC(ec,JSON.stringify(Array.from(Br.values()),null,2),"utf-8")}catch{}}function tc(){Kh||(Kh=!0,zC(),NC=setInterval(Qh,6e4),process.on("exit",Qh))}oi();var Mr=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let n=e?.input_tokens??e?.prompt_tokens??0,r=e?.output_tokens??e?.completion_tokens??0,o=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:n,output_tokens:r,total_tokens:e?.total_tokens??n+r,input_tokens_details:{cached_tokens:o,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:o,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let n=[],r=e.messages.filter(o=>o.role==="system");if(r.length>0){let o=r[0];Array.isArray(o.content)?o.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),n.push({role:"system",content:a})}):e.instructions=o.content}if(e.messages.forEach(o=>{if(o.role!=="system"){if(Array.isArray(o.content)){let s=o.content.map(a=>this.normalizeRequestContent(a,o.role)).filter(a=>a!==null);s.length>0?o.content=s:delete o.content}if(o.role==="tool"){let s={...o};s.type="function_call_output",s.call_id=o.tool_call_id,s.output=o.content,delete s.cache_control,delete s.role,delete s.tool_call_id,delete s.content,n.push(s);return}if(o.role==="assistant"&&Array.isArray(o.tool_calls)){o.tool_calls.forEach(s=>{n.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}n.push(o)}}),e.input=n,delete e.messages,Array.isArray(e.tools)){let o=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),o&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(n.includes("application/json")){let r=await e.json();if(r.object==="response"&&r.output){let o=this.convertResponseToChat(r);return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return r.type==="message"&&Array.isArray(r.content)?new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(n.includes("text/event-stream")){if(!e.body)return e;let[r,o]=e.body.tee(),s=r.getReader(),a="";try{let{value:g,done:_}=await s.read();!_&&g&&(a=new TextDecoder().decode(g))}finally{s.releaseLock()}if(r.cancel().catch(()=>{}),a.includes("message_start")||a.includes("content_block_start")){let g=this.prependToStream(a,o);return new Response(g,{status:e.status,statusText:e.statusText,headers:e.headers})}if(a.includes("response.created")||a.includes("response.output_text.delta")||a.includes("response.in_progress")||a.includes("response.output_item.added")){let g=this.prependToStream(a,o);return new Response(g,{status:e.status,statusText:e.statusText,headers:e.headers})}let d=this.prependToStream(a,o),f=new TextDecoder,p=new TextEncoder,m="",b=!1,w=this,y=new ReadableStream({async start(g){let _=d.getReader(),A=-1,C="",S=T=>(T!==C&&(A++,C=T),A);try{for(;;){let{done:T,value:R}=await _.read();if(T){b||g.enqueue(p.encode(`data: [DONE]
74
+ `);a=d.pop()||"";for(let f of d)f.trim()&&(s<r.maxStreamChunks?Mh(e,n,s,f):s===r.maxStreamChunks&&e.info({debug_log:!0,reqId:n,phase:"provider_stream_chunk_omitted",message:`[chunks after #${s} omitted, maxStreamChunks=${r.maxStreamChunks}]`}),s++)}a.trim()&&(s<r.maxStreamChunks&&Mh(e,n,s,a.trim()),s++),Lh(e,n,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${n}:`,a),Lh(e,n,s)}finally{o.releaseLock()}})()}var ri="2.3.13";Un();import{existsSync as Xh,mkdirSync as OC,readFileSync as PC,writeFileSync as FC}from"fs";import{join as Zh}from"path";import{HOME_DIR as IC}from"@wengine-ai/claude-code-router-shared";var Zu=Zh(IC,"runtime"),ec=Zh(Zu,"rate-limit.json"),Br=new Map,Kh=!1,NC=null,BC=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],MC=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],LC=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"];function Io(t,e,n){let r=u=>{if(n instanceof Headers)return n.get(u);let l=Object.keys(n).find(d=>d.toLowerCase()===u);return l?n[l]:null},o=Xu(r,BC),s=Xu(r,MC),a=Xu(r,LC);(o||s||a)&&Br.set(t,{provider:t,remaining:Yh(o),limit:Yh(s),reset:$C(a),capturedAt:Date.now()})}function jC(t){return Br.get(t)}function UC(){return Array.from(Br.values())}function Xu(t,e){for(let n of e){let r=t(n);if(r)return r}return null}function Yh(t){if(!t)return null;let e=Number(t.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function $C(t){if(!t)return null;let e=t.trim();if(!e)return null;let n=Number(e);if(Number.isFinite(n))return n>1e12?Math.floor(n/1e3):n>1e9?Math.floor(n):Math.floor(Date.now()/1e3+n);let r=Date.parse(e);if(Number.isFinite(r))return Math.floor(r/1e3);let o=qC(e);return o===null?null:Math.floor((Date.now()+o)/1e3)}function qC(t){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,n=0,r=!1;for(let o of t.matchAll(e)){r=!0;let s=Number(o[1]),a=o[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":n+=s;break;case"s":n+=s*1e3;break;case"m":n+=s*60*1e3;break;case"h":n+=s*60*60*1e3;break;case"d":n+=s*24*60*60*1e3;break}}return r?n:null}function zC(){try{if(!Xh(ec))return;let t=JSON.parse(PC(ec,"utf-8"));if(!Array.isArray(t))return;let e=Date.now();for(let n of t)if(n&&n.provider){if(n.capturedAt&&e-n.capturedAt>3600*1e3)continue;Br.set(n.provider,n)}}catch{}}function Qh(){try{if(Br.size===0)return;Xh(Zu)||OC(Zu,{recursive:!0}),FC(ec,JSON.stringify(Array.from(Br.values()),null,2),"utf-8")}catch{}}function tc(){Kh||(Kh=!0,zC(),NC=setInterval(Qh,6e4),process.on("exit",Qh))}oi();var Mr=class{name="openai-responses";endPoint="/v1/responses";getCacheReadInputTokens(e){return e?.cache_read_input_tokens??e?.input_tokens_details?.cached_tokens??e?.prompt_tokens_details?.cached_tokens??0}getCacheCreationInputTokens(e){return e?.cache_creation_input_tokens??e?.input_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.prompt_tokens_details?.cache_write_tokens??0}buildResponsesUsage(e){let n=e?.input_tokens??e?.prompt_tokens??0,r=e?.output_tokens??e?.completion_tokens??0,o=this.getCacheReadInputTokens(e),s=this.getCacheCreationInputTokens(e);return{input_tokens:n,output_tokens:r,total_tokens:e?.total_tokens??n+r,input_tokens_details:{cached_tokens:o,cache_creation_tokens:s},output_tokens_details:{reasoning_tokens:e?.output_tokens_details?.reasoning_tokens??0},cache_read_input_tokens:o,cache_creation_input_tokens:s}}async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:e.reasoning.summary||"auto"});let n=[],r=e.messages.filter(o=>o.role==="system");if(r.length>0){let o=r[0];Array.isArray(o.content)?o.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),n.push({role:"system",content:a})}):e.instructions=o.content}if(e.messages.forEach(o=>{if(o.role!=="system"){if(Array.isArray(o.content)){let s=o.content.map(a=>this.normalizeRequestContent(a,o.role)).filter(a=>a!==null);s.length>0?o.content=s:delete o.content}if(o.role==="tool"){let s={...o};s.type="function_call_output",s.call_id=o.tool_call_id,s.output=o.content,delete s.cache_control,delete s.role,delete s.tool_call_id,delete s.content,n.push(s);return}if(o.role==="assistant"&&Array.isArray(o.tool_calls)){o.tool_calls.forEach(s=>{n.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}n.push(o)}}),e.input=n,delete e.messages,Array.isArray(e.tools)){let o=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),o&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(n.includes("application/json")){let r=await e.json();if(r.object==="response"&&r.output){let o=this.convertResponseToChat(r);return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return r.type==="message"&&Array.isArray(r.content)?new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers}):new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(n.includes("text/event-stream")){if(!e.body)return e;let[r,o]=e.body.tee(),s=r.getReader(),a="";try{let{value:g,done:_}=await s.read();!_&&g&&(a=new TextDecoder().decode(g))}finally{s.releaseLock()}if(r.cancel().catch(()=>{}),a.includes("message_start")||a.includes("content_block_start")){let g=this.prependToStream(a,o);return new Response(g,{status:e.status,statusText:e.statusText,headers:e.headers})}if(a.includes("response.created")||a.includes("response.output_text.delta")||a.includes("response.in_progress")||a.includes("response.output_item.added")){let g=this.prependToStream(a,o);return new Response(g,{status:e.status,statusText:e.statusText,headers:e.headers})}let d=this.prependToStream(a,o),f=new TextDecoder,p=new TextEncoder,m="",b=!1,w=this,y=new ReadableStream({async start(g){let _=d.getReader(),A=-1,C="",S=T=>(T!==C&&(A++,C=T),A);try{for(;;){let{done:T,value:R}=await _.read();if(T){b||g.enqueue(p.encode(`data: [DONE]
75
75
 
76
76
  `));break}let $=f.decode(R,{stream:!0});m+=$;let V=m.split(/\r?\n/);m=V.pop()||"";for(let P of V)if(P.trim())try{if(P.startsWith("event: "))continue;if(P.startsWith("data: ")){let Y=P.slice(5).trim();if(Y==="[DONE]"){b=!0,g.enqueue(p.encode(`data: [DONE]
77
77