@pen.dev/cli 0.3.4 → 0.3.5

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.
Files changed (51) hide show
  1. package/dist/anthropic-messages-xcJLXjiT.mjs +40 -0
  2. package/dist/azure-openai-responses-CoA9_5_J.mjs +2 -0
  3. package/dist/browserAll-8jKh1NRi.mjs +2 -0
  4. package/dist/dist-Dmu1Pp1Y.mjs +1580 -0
  5. package/dist/google-generative-ai-CFHCNDEQ.mjs +2 -0
  6. package/dist/{google-shared-DXgnvvDU.mjs → google-shared-DolBdAGX.mjs} +4 -4
  7. package/dist/google-vertex-tT_ymu8S.mjs +2 -0
  8. package/dist/index.mjs +2 -2
  9. package/dist/lib-EA7A-_Pc.mjs +9 -0
  10. package/dist/mistral-conversations-CsN5eF3B.mjs +5 -0
  11. package/dist/{multipart-parser-BdmM0fdd.mjs → multipart-parser-DX5ZDxQv.mjs} +1 -1
  12. package/dist/openai-codex-responses-BIh-ZL5a.mjs +8 -0
  13. package/dist/openai-completions-CLJSzdfY.mjs +6 -0
  14. package/dist/openai-responses-DKbl253t.mjs +2 -0
  15. package/dist/{openai-responses-shared-DKseiGAg.mjs → openai-responses-shared-Brqyk2bc.mjs} +2 -2
  16. package/dist/{openrouter-images-gArAwqnL.mjs → openrouter-images-C8mOFqx9.mjs} +1 -1
  17. package/dist/{pi-messages-CSXUHkjV.mjs → pi-messages-CucvyzBS.mjs} +2 -2
  18. package/dist/{src-KoDMTA_Q.mjs → src-B_lvnEtX.mjs} +1 -1
  19. package/dist/transform-messages-1ulTEFY1.mjs +2 -0
  20. package/dist/typescript-D0uAMumm.mjs +6 -0
  21. package/dist/webworkerAll-BD-7VH16.mjs +2 -0
  22. package/package.json +1 -1
  23. package/dist/anthropic-messages-COZrsSdY.mjs +0 -40
  24. package/dist/azure-openai-responses-Dmf1EaVz.mjs +0 -2
  25. package/dist/browserAll-BZYrVO32.mjs +0 -2
  26. package/dist/dist-D9ROAuw3.mjs +0 -1587
  27. package/dist/google-generative-ai-BMEzR_34.mjs +0 -2
  28. package/dist/google-vertex-In7qdx36.mjs +0 -2
  29. package/dist/mistral-conversations-DdYjdrRy.mjs +0 -5
  30. package/dist/openai-codex-responses-CD-2hfWB.mjs +0 -8
  31. package/dist/openai-completions-DamtYjy7.mjs +0 -6
  32. package/dist/openai-responses-DgeWdtm-.mjs +0 -2
  33. package/dist/pi-user-agent-m9a4CjJo.mjs +0 -2
  34. package/dist/transform-messages-BHnJzowk.mjs +0 -2
  35. package/dist/webworkerAll-CB00nbs9.mjs +0 -2
  36. /package/dist/{deferred-tools-D8j2Ra6f.mjs → deferred-tools-CozAnCQL.mjs} +0 -0
  37. /package/dist/{dist-D8tvRm1b.mjs → dist-BnoSGZKP.mjs} +0 -0
  38. /package/dist/{dist-DGrygXHh.mjs → dist-L3CkgNK3.mjs} +0 -0
  39. /package/dist/{emscripten-module.browser-F76W5DM6-DWhj_jYh.mjs → emscripten-module.browser-F76W5DM6-CNibWX-6.mjs} +0 -0
  40. /package/dist/{emscripten-module.browser-XIKQQPVU-Dmh4no3c.mjs → emscripten-module.browser-XIKQQPVU-BNfdGnMe.mjs} +0 -0
  41. /package/dist/{ffi-DwdyvnFx.mjs → ffi-BuJ13coi.mjs} +0 -0
  42. /package/dist/{ffi-BroAqW9B.mjs → ffi-C5tLdQO9.mjs} +0 -0
  43. /package/dist/{from-Choxbpmr.mjs → from-py2TfO8m.mjs} +0 -0
  44. /package/dist/{headers-BvGum5dc.mjs → headers-DlpC0ues.mjs} +0 -0
  45. /package/dist/{html-DEPARSNH.mjs → html-GGJ1fTRB.mjs} +0 -0
  46. /package/dist/{init-DwIpBeuP.mjs → init-B9LSomNH.mjs} +0 -0
  47. /package/dist/{module-ES6BEMUI-DUGQwtIb.mjs → module-ES6BEMUI-DwQ9nTMF.mjs} +0 -0
  48. /package/dist/{module-asyncify-2EFITU5U-U7fqmMTF.mjs → module-asyncify-2EFITU5U-B54Mkt6K.mjs} +0 -0
  49. /package/dist/{provider-retry-wOYAq0sa.mjs → provider-retry-GaV_ioT7.mjs} +0 -0
  50. /package/dist/{sanitize-unicode-Byz9nlLd.mjs → sanitize-unicode-D-15laVS.mjs} +0 -0
  51. /package/dist/{standalone-DwaYVpTH.mjs → standalone-DYT2Zg6I.mjs} +0 -0
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import{a as e}from"./diagnostics-B0j2bfEp.mjs";import{n as t,t as n}from"./models-BBd5zwn6.mjs";import{n as r}from"./json-parse-BzRcyI3e.mjs";import{t as i}from"./headers-DlpC0ues.mjs";import{f as a,p as o,r as s,t as c,u as l}from"./transform-messages-1ulTEFY1.mjs";import{t as u}from"./sanitize-unicode-D-15laVS.mjs";import{t as d}from"./hash-DNYCELl4.mjs";const f=(t,n,r)=>{let i=new e;return(async()=>{let e=m(t);try{let a=r?.apiKey;if(!a)throw Error(`No API key for provider: ${t.provider}`);let o=h(),s=P(t,n,c(n.messages,t,e=>o(e)),r),l=await r?.onPayload?.(s,t);l!==void 0&&(s=l);let u=await b(t,s,a,r);if(i.push({type:`start`,partial:e}),await L(t,e,i,u),r?.signal?.aborted)throw Error(`Request was aborted`);if(e.stopReason===`pending`)throw Error(`Mistral stream ended without a finish reason`);if(e.stopReason===`aborted`||e.stopReason===`error`)throw Error(e.errorMessage||`An unknown error occurred`);i.push({type:`done`,reason:e.stopReason,message:e}),i.end()}catch(t){for(let t of e.content)delete t.partialArgs;e.stopReason=r?.signal?.aborted?`aborted`:`error`,e.errorMessage=_(t),i.push({type:`error`,reason:e.stopReason,error:e}),i.end()}})(),i},p=(e,n,r)=>{let i=r?.apiKey;if(!i)throw Error(`No API key for provider: ${e.provider}`);let a={...s(e,n,r,i),toolChoice:r?.toolChoice},o=r?.reasoning?t(e,r.reasoning):void 0,c=o===`off`?void 0:o,l=e.reasoning&&c!==void 0;return f(e,n,{...a,promptMode:l&&U(e)?`reasoning`:void 0,reasoningEffort:l&&H(e)?W(e,c):void 0})};function m(e){return{role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`pending`,timestamp:Date.now()}}function h(){let e=new Map,t=new Map;return n=>{let r=e.get(n);if(r)return r;let i=0;for(;;){let r=g(n,i),a=t.get(r);if(!a||a===n)return e.set(n,r),t.set(r,n),r;i++}}}function g(e,t){let n=e.replace(/[^a-zA-Z0-9]/g,``);if(t===0&&n.length===9)return n;let r=n||e;return d(t===0?r:`${r}:${t}`).replace(/[^a-zA-Z0-9]/g,``).slice(0,9)}function _(e){if(e instanceof Error){let t=e,n=typeof t.statusCode==`number`?t.statusCode:void 0,r=typeof t.body==`string`?t.body.trim():void 0;return n!==void 0&&r?`Mistral API error (${n}): ${v(r,4e3)}`:n===void 0?e.message:`Mistral API error (${n}): ${e.message}`}return y(e)}function v(e,t){return e.length<=t?e:`${e.slice(0,t)}... [truncated ${e.length-t} chars]`}function y(e){try{let t=JSON.stringify(e);return t===void 0?String(e):t}catch{return String(e)}}async function b(e,t,n,r){let a=new URL(e.baseUrl);a.pathname=`${a.pathname.replace(/\/+$/u,``)}/`;let o=new URL(`v1/chat/completions`,a),s=S(e,n,r),c=AbortSignal.timeout(r?.timeoutMs??6e4),l=r?.signal?AbortSignal.any([r.signal,c]):c,u=await(r?.fetch??globalThis.fetch)(o,{method:`POST`,headers:s,body:JSON.stringify(T(t)),signal:l});if(await r?.onResponse?.({status:u.status,headers:i(u.headers)},e),!u.ok){let e=await u.text();throw new x(u.status,e,u.statusText)}if(!u.body)throw Error(`Mistral response has no body`);return j(u.body,l)}var x=class extends Error{statusCode;body;constructor(e,t,n){super(n||`Request failed with status ${e}`),this.name=`MistralHttpError`,this.statusCode=e,this.body=t}};function S(e,t,n){let r=new Headers({"User-Agent":o(),accept:`text/event-stream`,authorization:`Bearer ${t}`,"content-type":`application/json`});C(r,e.headers),C(r,n?.headers);let i=w(e.headers,`x-affinity`)||w(n?.headers,`x-affinity`);return F(n)&&!i&&r.set(`x-affinity`,n.sessionId),r}function C(e,t){if(t)for(let[n,r]of Object.entries(t))r===null?e.delete(n):e.set(n,r)}function w(e,t){return!!e&&Object.keys(e).some(e=>e.toLowerCase()===t)}function T(e){let t={...e};for(let[e,n]of[[`topP`,`top_p`],[`maxTokens`,`max_tokens`],[`randomSeed`,`random_seed`],[`responseFormat`,`response_format`],[`toolChoice`,`tool_choice`],[`presencePenalty`,`presence_penalty`],[`frequencyPenalty`,`frequency_penalty`],[`parallelToolCalls`,`parallel_tool_calls`],[`reasoningEffort`,`reasoning_effort`],[`promptMode`,`prompt_mode`],[`promptCacheKey`,`prompt_cache_key`],[`safePrompt`,`safe_prompt`]])O(t,e,n);t.messages=e.messages.map(e=>E(e));let n=t.response_format;if(k(n)){let e={...n};O(e,`jsonSchema`,`json_schema`);let r=e.json_schema;if(k(r)){let t={...r};O(t,`schemaDefinition`,`schema`),e.json_schema=t}t.response_format=e}return t}function E(e){let t={...e};return O(t,`toolCalls`,`tool_calls`),O(t,`toolCallId`,`tool_call_id`),Array.isArray(e.content)&&(t.content=e.content.map(e=>D(e))),t}function D(e){let t={...e};for(let[e,n]of[[`imageUrl`,`image_url`],[`documentUrl`,`document_url`],[`documentName`,`document_name`],[`fileId`,`file_id`],[`referenceIds`,`reference_ids`],[`inputAudio`,`input_audio`]])O(t,e,n);return t}function O(e,t,n){t in e&&(e[n]=e[t],delete e[t])}function k(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const A=Symbol(`mistral-stream-done`);async function*j(e,t){let n=e.getReader(),r=new TextDecoder,i=``,a=()=>{n.cancel().catch(()=>{})};t.addEventListener(`abort`,a,{once:!0});try{for(;;){if(t.aborted)throw t.reason;let{done:e,value:a}=await n.read();if(t.aborted)throw t.reason;i+=e?r.decode():r.decode(a,{stream:!0});let o=M(i);for(;o;){let e=N(i.slice(0,o.index));if(i=i.slice(o.index+o.length),e===A)return;e&&(yield e),o=M(i)}if(e)break}if(i.trim()){let e=N(i);e!==A&&e&&(yield e)}}finally{t.removeEventListener(`abort`,a);try{await n.cancel()}catch{}try{n.releaseLock()}catch{}}}function M(e){let t=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(e);return t?.index===void 0?void 0:{index:t.index,length:t[0].length}}function N(e){let t=e.split(/\r\n|\r|\n/u).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trimStart()).join(`
3
+ `).trim();if(!t)return;if(t===`[DONE]`)return A;let n=JSON.parse(t);if(!k(n)||!Array.isArray(n.choices))throw Error(`Invalid Mistral streaming event`);return{data:n}}function P(e,t,n,r){let i={model:e.id,stream:!0,messages:B(n,e.input.includes(`image`))};return t.tools?.length&&(i.tools=R(t.tools)),r?.temperature!==void 0&&(i.temperature=r.temperature),r?.maxTokens!==void 0&&(i.maxTokens=r.maxTokens),r?.toolChoice&&(i.toolChoice=G(r.toolChoice)),r?.promptMode&&(i.promptMode=r.promptMode),r?.reasoningEffort&&(i.reasoningEffort=r.reasoningEffort),F(r)&&(i.promptCacheKey=r.sessionId),t.systemPrompt&&i.messages.unshift({role:`system`,content:u(t.systemPrompt)}),i}function F(e){return e?.cacheRetention!==`none`&&!!e?.sessionId}function I(e,t){let n=e,r=n.promptTokensDetails?.cachedTokens??n.prompt_tokens_details?.cached_tokens??n.promptTokenDetails?.cachedTokens??n.prompt_token_details?.cached_tokens??n.numCachedTokens??n.num_cached_tokens??0,i=typeof r==`number`&&Number.isFinite(r)?r:0;return Math.min(t,Math.max(0,i))}async function L(e,t,i,a){let o=null,s=t.content,c=()=>s.length-1,l=new Map,d=e=>{if(e){if(e.type===`text`){i.push({type:`text_end`,contentIndex:c(),content:e.text,partial:t});return}e.type===`thinking`&&i.push({type:`thinking_end`,contentIndex:c(),content:e.thinking,partial:t})}};for await(let s of a){let a=s.data;if(t.responseId||=a.id,a.usage){let r=a.usage.prompt_tokens||0,i=I(a.usage,r);t.usage.input=Math.max(0,r-i),t.usage.output=a.usage.completion_tokens||0,t.usage.cacheRead=i,t.usage.cacheWrite=0,t.usage.totalTokens=a.usage.total_tokens||t.usage.input+t.usage.output+t.usage.cacheRead+t.usage.cacheWrite,n(e,t.usage)}let f=a.choices[0];if(!f)continue;if(f.finish_reason){t.rawStopReason=f.finish_reason;let e=K(f.finish_reason);t.stopReason=e.stopReason,e.errorMessage&&(t.errorMessage=e.errorMessage)}let p=f.delta;if(p.content!==null&&p.content!==void 0){let e=typeof p.content==`string`?[p.content]:p.content;for(let n of e){if(typeof n==`string`){let e=u(n);(!o||o.type!==`text`)&&(d(o),o={type:`text`,text:``},t.content.push(o),i.push({type:`text_start`,contentIndex:c(),partial:t})),o.text+=e,i.push({type:`text_delta`,contentIndex:c(),delta:e,partial:t});continue}if(n.type===`thinking`){let e=u((n.thinking??[]).map(e=>e.text??``).filter(e=>e.length>0).join(``));if(!e)continue;(!o||o.type!==`thinking`)&&(d(o),o={type:`thinking`,thinking:``},t.content.push(o),i.push({type:`thinking_start`,contentIndex:c(),partial:t})),o.thinking+=e,i.push({type:`thinking_delta`,contentIndex:c(),delta:e,partial:t});continue}if(n.type===`text`){let e=u(n.text??``);(!o||o.type!==`text`)&&(d(o),o={type:`text`,text:``},t.content.push(o),i.push({type:`text_start`,contentIndex:c(),partial:t})),o.text+=e,i.push({type:`text_delta`,contentIndex:c(),delta:e,partial:t})}}}let m=p.tool_calls||[];for(let e of m){o&&=(d(o),null);let n=e.id&&e.id!==`null`?e.id:g(`toolcall:${e.index??0}`,0),a=`${n}:${e.index||0}`,s=l.get(a),c;if(s!==void 0){let e=t.content[s];e?.type===`toolCall`&&(c=e)}c||(c={type:`toolCall`,id:n,name:e.function.name,arguments:{},partialArgs:``},t.content.push(c),l.set(a,t.content.length-1),i.push({type:`toolcall_start`,contentIndex:t.content.length-1,partial:t}));let u=typeof e.function.arguments==`string`?e.function.arguments:JSON.stringify(e.function.arguments||{});c.partialArgs=(c.partialArgs||``)+u,c.arguments=r(c.partialArgs),i.push({type:`toolcall_delta`,contentIndex:l.get(a),delta:u,partial:t})}}d(o);for(let e of l.values()){let n=t.content[e];if(n.type!==`toolCall`)continue;let a=n;a.arguments=r(a.partialArgs),delete a.partialArgs,i.push({type:`toolcall_end`,contentIndex:e,toolCall:a,partial:t})}}function R(e){return e.map(e=>{let t=a(e,!0);return{type:`function`,function:{name:e.name,description:e.description,parameters:z(l(e,t)),strict:t??!1}}})}function z(e){if(Array.isArray(e))return e.map(e=>z(e));if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=z(r);return t}return e}function B(e,t){let n=[];for(let r of e){if(r.role===`user`){if(typeof r.content==`string`){n.push({role:`user`,content:u(r.content)});continue}let e=r.content.some(e=>e.type===`image`),i=r.content.filter(e=>e.type===`text`||t).map(e=>e.type===`text`?{type:`text`,text:u(e.text)}:{type:`image_url`,imageUrl:`data:${e.mimeType};base64,${e.data}`});if(i.length>0){n.push({role:`user`,content:i});continue}e&&!t&&n.push({role:`user`,content:`(image omitted: model does not support images)`});continue}if(r.role===`assistant`){let e=[],t=[];for(let n of r.content){if(n.type===`text`){n.text.trim().length>0&&e.push({type:`text`,text:u(n.text)});continue}if(n.type===`thinking`){n.thinking.trim().length>0&&e.push({type:`thinking`,thinking:[{type:`text`,text:u(n.thinking)}]});continue}t.push({id:n.id,type:`function`,function:{name:n.name,arguments:JSON.stringify(n.arguments||{})},index:0})}let i={role:`assistant`,prefix:!1};e.length>0&&(i.content=e),t.length>0&&(i.toolCalls=t),(e.length>0||t.length>0)&&n.push(i);continue}let e=[],i=V(r.content.filter(e=>e.type===`text`).map(e=>e.type===`text`?u(e.text):``).join(`
4
+ `),r.content.some(e=>e.type===`image`),t,r.isError);e.push({type:`text`,text:i});for(let n of r.content)t&&n.type===`image`&&e.push({type:`image_url`,imageUrl:`data:${n.mimeType};base64,${n.data}`});n.push({role:`tool`,toolCallId:r.toolCallId,name:r.toolName,content:e})}return n}function V(e,t,n,r){let i=e.trim(),a=r?`[tool error] `:``;return i.length>0?`${a}${i}${t&&!n?`
5
+ [tool image omitted: model does not support images]`:``}`:t?n?r?`[tool error] (see attached image)`:`(see attached image)`:r?`[tool error] (image omitted: model does not support images)`:`(image omitted: model does not support images)`:r?`[tool error] (no tool output)`:`(no tool output)`}function H(e){return e.id===`mistral-small-2603`||e.id===`mistral-small-latest`||e.id===`mistral-medium-3.5`}function U(e){return e.reasoning&&!H(e)}function W(e,t){return e.thinkingLevelMap?.[t]??`high`}function G(e){if(e)return e===`auto`||e===`none`||e===`any`||e===`required`?e:{type:`function`,function:{name:e.function.name}}}function K(e){if(e===null)return{stopReason:`stop`};switch(e){case`stop`:return{stopReason:`stop`};case`length`:case`model_length`:return{stopReason:`length`};case`tool_calls`:return{stopReason:`toolUse`};case`error`:return{stopReason:`error`,errorMessage:`Provider stopped with: error`};default:return{stopReason:`error`,errorMessage:`Provider stopped with: ${e}`}}}export{f as stream,p as streamSimple};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{lt as e}from"./index.mjs";import{a as t,i as n,n as r,t as i}from"./from-Choxbpmr.mjs";function a(e){let t=e.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!t)return;let n=t[2]||t[3]||``,r=n.slice(n.lastIndexOf(`\\`)+1);return r=r.replace(/%22/g,`"`),r=r.replace(/&#(\d{4});/g,(e,t)=>String.fromCharCode(t)),r}async function o(e,n){if(!/multipart/i.test(n))throw TypeError(`Failed to fetch`);let i=n.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!i)throw TypeError(`no or bad content-type header, no multipart boundary`);let o=new b(i[1]||i[2]),s,c,l,u,d,f,p=[],m=new r,h=e=>{l+=y.decode(e,{stream:!0})},g=e=>{p.push(e)},_=()=>{let e=new t(p,f,{type:d});m.append(u,e)},v=()=>{m.append(u,l)},y=new TextDecoder(`utf-8`);y.decode(),o.onPartBegin=function(){o.onPartData=h,o.onPartEnd=v,s=``,c=``,l=``,u=``,d=``,f=null,p.length=0},o.onHeaderField=function(e){s+=y.decode(e,{stream:!0})},o.onHeaderValue=function(e){c+=y.decode(e,{stream:!0})},o.onHeaderEnd=function(){if(c+=y.decode(),s=s.toLowerCase(),s===`content-disposition`){let e=c.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);e&&(u=e[2]||e[3]||``),f=a(c),f&&(o.onPartData=g,o.onPartEnd=_)}else s===`content-type`&&(d=c);c=``,s=``};for await(let t of e)o.write(t);return o.end(),m}var s,c,l,u,d,f,p,m,h,g,_,v,y,b;e((()=>{i(),n(),s=0,c={START_BOUNDARY:s++,HEADER_FIELD_START:s++,HEADER_FIELD:s++,HEADER_VALUE_START:s++,HEADER_VALUE:s++,HEADER_VALUE_ALMOST_DONE:s++,HEADERS_ALMOST_DONE:s++,PART_DATA_START:s++,PART_DATA:s++,END:s++},l=1,u={PART_BOUNDARY:l,LAST_BOUNDARY:l*=2},d=10,f=13,p=32,m=45,h=58,g=97,_=122,v=e=>e|32,y=()=>{},b=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=y,this.onHeaderField=y,this.onHeadersEnd=y,this.onHeaderValue=y,this.onPartBegin=y,this.onPartData=y,this.onPartEnd=y,this.boundaryChars={},e=`\r
2
+ import{lt as e}from"./index.mjs";import{a as t,i as n,n as r,t as i}from"./from-py2TfO8m.mjs";function a(e){let t=e.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!t)return;let n=t[2]||t[3]||``,r=n.slice(n.lastIndexOf(`\\`)+1);return r=r.replace(/%22/g,`"`),r=r.replace(/&#(\d{4});/g,(e,t)=>String.fromCharCode(t)),r}async function o(e,n){if(!/multipart/i.test(n))throw TypeError(`Failed to fetch`);let i=n.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!i)throw TypeError(`no or bad content-type header, no multipart boundary`);let o=new b(i[1]||i[2]),s,c,l,u,d,f,p=[],m=new r,h=e=>{l+=y.decode(e,{stream:!0})},g=e=>{p.push(e)},_=()=>{let e=new t(p,f,{type:d});m.append(u,e)},v=()=>{m.append(u,l)},y=new TextDecoder(`utf-8`);y.decode(),o.onPartBegin=function(){o.onPartData=h,o.onPartEnd=v,s=``,c=``,l=``,u=``,d=``,f=null,p.length=0},o.onHeaderField=function(e){s+=y.decode(e,{stream:!0})},o.onHeaderValue=function(e){c+=y.decode(e,{stream:!0})},o.onHeaderEnd=function(){if(c+=y.decode(),s=s.toLowerCase(),s===`content-disposition`){let e=c.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);e&&(u=e[2]||e[3]||``),f=a(c),f&&(o.onPartData=g,o.onPartEnd=_)}else s===`content-type`&&(d=c);c=``,s=``};for await(let t of e)o.write(t);return o.end(),m}var s,c,l,u,d,f,p,m,h,g,_,v,y,b;e((()=>{i(),n(),s=0,c={START_BOUNDARY:s++,HEADER_FIELD_START:s++,HEADER_FIELD:s++,HEADER_VALUE_START:s++,HEADER_VALUE:s++,HEADER_VALUE_ALMOST_DONE:s++,HEADERS_ALMOST_DONE:s++,PART_DATA_START:s++,PART_DATA:s++,END:s++},l=1,u={PART_BOUNDARY:l,LAST_BOUNDARY:l*=2},d=10,f=13,p=32,m=45,h=58,g=97,_=122,v=e=>e|32,y=()=>{},b=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=y,this.onHeaderField=y,this.onHeadersEnd=y,this.onHeaderValue=y,this.onPartBegin=y,this.onPartData=y,this.onPartEnd=y,this.boundaryChars={},e=`\r
3
3
  --`+e;let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n),this.boundaryChars[t[n]]=!0;this.boundary=t,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=c.START_BOUNDARY}write(e){let t=0,n=e.length,r=this.index,{lookbehind:i,boundary:a,boundaryChars:o,index:s,state:l,flags:y}=this,b=this.boundary.length,x=b-1,S=e.length,C,w,T=e=>{this[e+`Mark`]=t},E=e=>{delete this[e+`Mark`]},D=(e,t,n,r)=>{(t===void 0||t!==n)&&this[e](r&&r.subarray(t,n))},O=(n,r)=>{let i=n+`Mark`;i in this&&(r?(D(n,this[i],t,e),delete this[i]):(D(n,this[i],e.length,e),this[i]=0))};for(t=0;t<n;t++)switch(C=e[t],l){case c.START_BOUNDARY:if(s===a.length-2){if(C===m)y|=u.LAST_BOUNDARY;else if(C!==f)return;s++;break}else if(s-1==a.length-2){if(y&u.LAST_BOUNDARY&&C===m)l=c.END,y=0;else if(!(y&u.LAST_BOUNDARY)&&C===d)s=0,D(`onPartBegin`),l=c.HEADER_FIELD_START;else return;break}C!==a[s+2]&&(s=-2),C===a[s+2]&&s++;break;case c.HEADER_FIELD_START:l=c.HEADER_FIELD,T(`onHeaderField`),s=0;case c.HEADER_FIELD:if(C===f){E(`onHeaderField`),l=c.HEADERS_ALMOST_DONE;break}if(s++,C===m)break;if(C===h){if(s===1)return;O(`onHeaderField`,!0),l=c.HEADER_VALUE_START;break}if(w=v(C),w<g||w>_)return;break;case c.HEADER_VALUE_START:if(C===p)break;T(`onHeaderValue`),l=c.HEADER_VALUE;case c.HEADER_VALUE:C===f&&(O(`onHeaderValue`,!0),D(`onHeaderEnd`),l=c.HEADER_VALUE_ALMOST_DONE);break;case c.HEADER_VALUE_ALMOST_DONE:if(C!==d)return;l=c.HEADER_FIELD_START;break;case c.HEADERS_ALMOST_DONE:if(C!==d)return;D(`onHeadersEnd`),l=c.PART_DATA_START;break;case c.PART_DATA_START:l=c.PART_DATA,T(`onPartData`);case c.PART_DATA:if(r=s,s===0){for(t+=x;t<S&&!(e[t]in o);)t+=b;t-=x,C=e[t]}if(s<a.length)a[s]===C?(s===0&&O(`onPartData`,!0),s++):s=0;else if(s===a.length)s++,C===f?y|=u.PART_BOUNDARY:C===m?y|=u.LAST_BOUNDARY:s=0;else if(s-1===a.length)if(y&u.PART_BOUNDARY){if(s=0,C===d){y&=~u.PART_BOUNDARY,D(`onPartEnd`),D(`onPartBegin`),l=c.HEADER_FIELD_START;break}}else y&u.LAST_BOUNDARY&&C===m?(D(`onPartEnd`),l=c.END,y=0):s=0;if(s>0)i[s-1]=C;else if(r>0){let e=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);D(`onPartData`,0,r,e),r=0,T(`onPartData`),t--}break;case c.END:break;default:throw Error(`Unexpected state entered: ${l}`)}O(`onHeaderField`),O(`onHeaderValue`),O(`onPartData`),this.index=s,this.state=l,this.flags=y}end(){if(this.state===c.HEADER_FIELD_START&&this.index===0||this.state===c.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==c.END)throw Error(`MultipartParser.end(): stream ended unexpectedly`)}}}))();export{o as toFormData};
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import{a as e,i as t,n,t as r}from"./diagnostics-B0j2bfEp.mjs";import{n as i}from"./models-BBd5zwn6.mjs";import{r as a,t as o}from"./uuid-CwuSNv96.mjs";import"./json-parse-BzRcyI3e.mjs";import{t as s}from"./provider-env-CL5ShLlj.mjs";import{t as c}from"./deferred-tools-CozAnCQL.mjs";import{t as l}from"./headers-DlpC0ues.mjs";import{c as u,p as d,r as f}from"./transform-messages-1ulTEFY1.mjs";import{n as p,t as m}from"./error-body-BBlqjbe7.mjs";import{t as h}from"./openai-prompt-cache-tVHrB8oW.mjs";import{n as g,r as _,t as v}from"./openai-responses-shared-Brqyk2bc.mjs";function y(e){let t=e.filter(e=>e!==void 0);if(t.length===0)return{cleanup:()=>{}};if(t.length===1)return{signal:t[0],cleanup:()=>{}};let n=new AbortController,r=[],i=e=>{n.signal.aborted||n.abort(e.reason)};for(let e of t){if(e.aborted){i(e);break}let t=()=>i(e);e.addEventListener(`abort`,t,{once:!0}),r.push({signal:e,listener:t})}return{signal:n.signal,cleanup:()=>{for(let{signal:e,listener:t}of r)e.removeEventListener(`abort`,t)}}}const b={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function x(e,t){let n=e.toLowerCase(),r=e.toUpperCase();return t?.[n]||t?.[r]||s(n)||s(r)||``}function S(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function C(e,t,n){let r=x(`no_proxy`,n).toLowerCase();return r?r===`*`?!1:r.split(/[,\s]/).every(n=>{if(!n)return!0;let r=n.match(/^(.+):(\d+)$/),i=r?r[1]:n,a=r?Number.parseInt(r[2],10):0;return a&&a!==t?!0:/^[.*]/.test(i)?(i.startsWith(`*`)&&(i=i.slice(1)),!e.endsWith(i)):e!==i}):!0}function ee(e,t){let n=S(e);if(!n?.protocol||!n.host)return``;let r=n.protocol.split(`:`,1)[0];if(!C(n.host.replace(/:\d*$/,``),Number.parseInt(n.port,10)||b[r]||0,t))return``;let i=x(`${r}_proxy`,t)||x(`all_proxy`,t);return i&&!i.includes(`://`)&&(i=`${r}://${i}`),i}function w(e,t){let n=ee(e,t);if(!n)return;let r;try{r=new URL(n)}catch(e){throw Error(`Invalid proxy URL ${JSON.stringify(n)}: ${e instanceof Error?e.message:String(e)}`)}if(r.protocol!==`http:`&&r.protocol!==`https:`)throw Error(`Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL. Got ${r.protocol}`);return r}const T=1e3,E=new Set([`openai`,`openai-codex`,`opencode`]),D=new Set([`completed`,`incomplete`,`failed`,`cancelled`,`queued`,`in_progress`]);function te(e){if(e.stopReason===`pending`)throw Error(`Codex stream ended without a stop reason`);if(e.stopReason===`error`||e.stopReason===`aborted`)throw Error(e.errorMessage||`An unknown error occurred`)}function O(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function ne(e,t){return e===429&&O(t)?!1:e===429||e===500||e===502||e===503||e===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function re(e){let t=e.get(`retry-after-ms`);if(t!==null){let e=Number(t);if(Number.isFinite(e))return Math.max(0,e)}let n=e.get(`retry-after`);if(!n)return;let r=Number(n);if(Number.isFinite(r))return Math.max(0,r*1e3);let i=Date.parse(n);if(!Number.isNaN(i))return Math.max(0,i-Date.now())}var k=class extends Error{};function ie(e,t){let n=t?.maxRetryDelayMs??6e4;if(n>0&&e>n)throw new k(`Server requested ${Math.ceil(e/1e3)}s retry delay (max: ${Math.ceil(n/1e3)}s)`);return e}function A(e,t){return new Promise((n,r)=>{if(t?.aborted){r(Error(`Request was aborted`));return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Request was aborted`))})})}function j(e){if(e!==void 0){if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}}function M(){return typeof process>`u`||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.(`node:zlib`)??null}function ae(e){let t=M();if(!t||typeof t.zstdCompressSync!=`function`)return null;try{let n=t.zstdCompressSync(e,{params:{[t.constants.ZSTD_c_compressionLevel]:3}});return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}catch{return null}}const N=(t,i,a)=>{let s=new e;return(async()=>{let e={role:`assistant`,content:[],api:`openai-codex-responses`,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`pending`,timestamp:Date.now()};try{let c=a?.apiKey;if(!c)throw Error(`No API key for provider: ${t.provider}`);let d=Fe(c),f=u(i.tools,t.compat?.supportsOpenAIGrammarTools??!1),p=a?.cacheRetention===`none`?void 0:a?.sessionId,m=h(p),g=oe(t,i,a,m,f),_=await a?.onPayload?.(g,t);_!==void 0&&(g=_);let v=m||o(),b=Le(t.headers,a?.headers,d,c,m),x=Re(t.headers,a?.headers,d,c,v),S=JSON.stringify(g),C=j(a?.timeoutMs),ee=j(a?.websocketConnectTimeoutMs),w=a?.transport||`auto`,E=!1,D=w!==`sse`&&q(p);if(D&&J(p),w!==`sse`&&!D){let i=!1,o=!1,c=!1;for(;;){i=!1;try{if(await Ne(se(t.baseUrl),g,x,e,s,t,()=>{i=!0,E||(E=!0,s.push({type:`start`,partial:e}))},C,ee,p,d,f,a),a?.signal?.aborted)throw Error(`Request was aborted`);te(e),s.push({type:`done`,reason:e.stopReason,message:e}),s.end();return}catch(t){let s=a?.signal?.aborted,l=!i&&ue(t),u=de(t);if(!s&&u&&!c){c=!0;continue}if(!s&&l&&!o){o=!0;continue}if(s||le(t)&&!l||(r(e,n(`provider_transport_failure`,t,{configuredTransport:w,fallbackTransport:i?void 0:`sse`,eventsEmitted:i,phase:i?`after_message_stream_start`:`before_message_stream_start`,requestBytes:new TextEncoder().encode(S).byteLength})),_e(p,t),i))throw t;J(p);break}}}let O=ae(S);O&&b.set(`content-encoding`,`zstd`);let M=O??S,N,P,F=a?.maxRetries??0;for(let e=0;e<=F;e++){if(a?.signal?.aborted)throw Error(`Request was aborted`);try{let n=C!==void 0&&C>0?AbortSignal.timeout(C):void 0,r=y([a?.signal,n]);try{N=await(a?.fetch??globalThis.fetch)(R(t.baseUrl),{method:`POST`,headers:b,body:M,signal:r.signal})}catch(e){throw n?.aborted&&!a?.signal?.aborted?Error(`Codex SSE response headers timed out after ${C}ms`):e}finally{r.cleanup()}if(await a?.onResponse?.({status:N.status,headers:l(N.headers)},t),N.ok)break;let i=await N.text();if(e<F&&ne(N.status,i)){let t=re(N.headers);await A(t===void 0?T*2**e:ie(t,a),a?.signal);continue}let o=await Pe(new Response(i,{status:N.status,statusText:N.statusText}));throw Error(o.friendlyMessage||o.message)}catch(t){if(t instanceof Error&&(t.name===`AbortError`||t.message===`Request was aborted`))throw Error(`Request was aborted`);if(P=t instanceof Error?t:Error(String(t)),e<F&&!(P instanceof k)&&!P.message.includes(`usage limit`)){await A(T*2**e,a?.signal);continue}throw P}}if(!N?.ok)throw P??Error(`Failed after retries`);if(!N.body)throw Error(`No response body`);if(E||(E=!0,s.push({type:`start`,partial:e})),await ce(N,e,s,t,f,a),a?.signal?.aborted)throw Error(`Request was aborted`);te(e),s.push({type:`done`,reason:e.stopReason,message:e}),s.end()}catch(t){for(let t of e.content)delete t.partialJson,delete t.customInput;e.stopReason=a?.signal?.aborted?`aborted`:`error`,e.errorMessage=m(p(t)),s.push({type:`error`,reason:e.stopReason,error:e}),s.end()}})(),s},P=(e,t,n)=>{let r=n?.apiKey;if(!r)throw Error(`No API key for provider: ${e.provider}`);let a={...f(e,t,n,r),toolChoice:n?.toolChoice},o=n?.reasoning?i(e,n.reasoning):void 0,s=o===`off`?void 0:o;return N(e,t,{...a,reasoningEffort:s})};function oe(e,t,n,r,i=u(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let a=e.compat?.supportsStrictMode??!0,o=e.compat?.supportsOpenAIGrammarTools??!1,s=e.compat?.supportsAdditionalTools?`additional-tools`:e.compat?.supportsToolSearch?`tool-search`:void 0,l=c(t,s!==void 0),d=v(e,t,E,{includeSystemPrompt:!1,grammarToolInputProperties:i,deferredTools:l.deferred,deferredToolsMode:s,toolOptions:{strict:null,supportsStrictMode:a,supportsOpenAIGrammarTools:o}}),f={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||`You are a helpful assistant.`,input:d,text:{verbosity:n?.textVerbosity||`low`},include:[`reasoning.encrypted_content`],prompt_cache_key:r,tool_choice:n?.toolChoice??`auto`,parallel_tool_calls:!0};if(n?.temperature!==void 0&&(f.temperature=n.temperature),n?.serviceTier!==void 0&&(f.service_tier=n.serviceTier),l.immediate.length>0&&(f.tools=g(l.immediate,{strict:null,supportsStrictMode:a,supportsOpenAIGrammarTools:o})),n?.reasoningEffort!==void 0){let t=n.reasoningEffort===`none`?e.thinkingLevelMap?.off??`none`:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;t!==null&&(f.reasoning={effort:t,summary:n.reasoningSummary??`auto`})}return f}function F(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function I(e,t,n){let r=F(n,t);r!==1&&(e.cost.input*=r,e.cost.output*=r,e.cost.cacheRead*=r,e.cost.cacheWrite*=r,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}function L(e,t){return e===`default`&&(t===`flex`||t===`priority`)?t:e??t}function R(e){let t=(e&&e.trim().length>0?e:`https://chatgpt.com/backend-api`).replace(/\/+$/,``);return t.endsWith(`/codex/responses`)?t:t.endsWith(`/codex`)?`${t}/responses`:`${t}/codex/responses`}function se(e){let t=new URL(R(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function ce(e,t,n,r,i,a){await _(V(me(e,a?.signal),t),t,n,r,{serviceTier:a?.serviceTier,grammarToolInputProperties:i,resolveServiceTier:L,applyServiceTierPricing:(e,t)=>I(e,t,r)})}var z=class extends Error{code;payload;constructor(e,t){super(e),this.name=`CodexApiError`,this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}},B=class extends Error{payload;constructor(e,t){super(e),this.name=`CodexProtocolError`,this.payload=t?.payload,this.cause=t?.cause}};function le(e){return e instanceof z||e instanceof B}function ue(e){return e instanceof z&&e.code===`websocket_connection_limit_reached`}function de(e){return e instanceof z&&e.code===`previous_response_not_found`}function fe(e){let t=e.error&&typeof e.error==`object`?e.error:void 0;return{code:typeof e.code==`string`?e.code:typeof t?.code==`string`?t.code:void 0,message:typeof e.message==`string`?e.message:typeof t?.message==`string`?t.message:void 0}}async function*V(e,t){for await(let n of e){let e=typeof n.type==`string`?n.type:void 0;if(e){if(e===`error`){let{code:e,message:t}=fe(n);throw new z(`Codex error: ${t||e||JSON.stringify(n)}`,{code:e,payload:n})}if(e===`response.failed`){let e=n.response,t=e?.error?.code,r=e?.error?.message;throw new z(r||`Codex response failed`,{code:t,payload:n})}if(e===`response.done`||e===`response.completed`||e===`response.incomplete`){let e=n.response;typeof e?.end_turn==`boolean`&&(t.endTurn=e.end_turn);let r=e&&{...e,status:pe(e.status)};yield{...n,type:`response.completed`,response:r};return}yield n}}}function pe(e){if(typeof e==`string`)return D.has(e)?e:void 0}async function*me(e,n){if(!e.body)return;let r=e.body.getReader(),i=new TextDecoder,a=``,o=()=>{r.cancel().catch(()=>{})};n?.addEventListener(`abort`,o,{once:!0});try{for(;;){if(n?.aborted)throw Error(`Request was aborted`);let{done:e,value:o}=await r.read();if(n?.aborted)throw Error(`Request was aborted`);if(e)break;a+=i.decode(o,{stream:!0});let s=a.indexOf(`
3
+
4
+ `);for(;s!==-1;){let e=a.slice(0,s);a=a.slice(s+2);let n=e.split(`
5
+ `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());if(n.length>0){let e=n.join(`
6
+ `).trim();if(e&&e!==`[DONE]`)try{yield JSON.parse(e)}catch(n){throw new B(`Invalid Codex SSE JSON: ${t(n)}`,{cause:n,payload:e})}}s=a.indexOf(`
7
+
8
+ `)}}}finally{n?.removeEventListener(`abort`,o);try{await r.cancel()}catch{}try{r.releaseLock()}catch{}}}const H=new Map,U=new Map,W=new Set;function G(e){let t=U.get(e);return t||(t={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},U.set(e,t)),t}function he(e){let t=U.get(e);return t?{...t}:void 0}function ge(e){if(e){U.delete(e),W.delete(e);return}U.clear(),W.clear()}function K(e){let t=e=>{e.idleTimer&&clearTimeout(e.idleTimer),Z(e.socket,1e3,`debug_close`)};if(e){for(let n of H.get(e)?.values()??[])t(n);H.delete(e);return}for(let e of H.values())for(let n of e.values())t(n);H.clear()}a(K);function q(e){return e?W.has(e):!1}function J(e){if(!e)return;let t=G(e);t.sseFallbacks++,t.websocketFallbackActive=q(e)}function _e(e,n){if(!e)return;W.add(e);let r=G(e);r.websocketFailures++,r.lastWebSocketError=t(n),r.websocketFallbackActive=!0}let Y=null;async function ve(e){if(!e&&Y)return Y;if(typeof process<`u`&&process.versions?.bun){let t=class extends WebSocket{constructor(t,n){let r={};r=Array.isArray(n)||typeof n==`string`?{protocols:n}:{...n};let i=w(t.toString().replace(/^wss:/,`https:`).replace(/^ws:/,`http:`),e);super(t,{...r,...i?{proxy:i.toString()}:{}})}};return e||(Y=t),t}let t=globalThis.WebSocket;return typeof t==`function`?t:null}var ye=class extends Error{code;reason;wasClean;constructor(e,t){super(e),this.name=`WebSocketCloseError`,this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}};function be(e){let t=e.readyState;return typeof t==`number`?t:void 0}function X(e){let t=be(e);return t===void 0||t===1}function xe(e){return Date.now()-e.createdAt>=33e5}function Z(e,t=1e3,n=`done`){try{e.close(t,n)}catch{}}function Se(e,t,n){n.idleTimer&&clearTimeout(n.idleTimer),n.idleTimer=setTimeout(()=>{if(n.busy)return;Z(n.socket,1e3,`idle_timeout`);let r=H.get(e);r?.get(t)===n&&r.delete(t),r?.size===0&&H.delete(e)},3e5)}async function Q(e,t,n,r=15e3,i){let a=await ve(i);if(!a)throw Error(`WebSocket transport is not available in this runtime`);let o=l(t);return delete o[`OpenAI-Beta`],new Promise((t,i)=>{let s=!1,c,l;try{l=new a(e,{headers:o})}catch(e){i(e instanceof Error?e:Error(String(e)));return}let u=()=>{c&&=(clearTimeout(c),void 0),l.removeEventListener(`open`,f),l.removeEventListener(`error`,p),l.removeEventListener(`close`,m),n?.removeEventListener(`abort`,h)},d=(e,t)=>{s||(s=!0,u(),t&&Z(l,1e3,t),i(e))},f=()=>{s||(s=!0,u(),t(l))},p=e=>{d($(e))},m=e=>{d(we(e))},h=()=>{d(Error(`Request was aborted`),`aborted`)};l.addEventListener(`open`,f),l.addEventListener(`error`,p),l.addEventListener(`close`,m),n?.addEventListener(`abort`,h),r>0&&(c=setTimeout(()=>{d(Error(`WebSocket connect timeout after ${r}ms`),`connect_timeout`)},r)),n?.aborted&&h()})}async function Ce(e,t,n,r,i,a,o){if(!n){let n=await Q(e,t,i,a,o);return{socket:n,reused:!1,release:()=>Z(n)}}let s=H.get(n),c=s?.get(r);if(c){if(c.idleTimer&&=(clearTimeout(c.idleTimer),void 0),!c.busy&&xe(c))Z(c.socket,1e3,`connection_age_limit`),s?.delete(r),s?.size===0&&H.delete(n);else if(!c.busy&&X(c.socket))return c.busy=!0,{socket:c.socket,entry:c,reused:!0,release:({keep:e}={})=>{if(!e||!X(c.socket)){Z(c.socket);let e=H.get(n);e?.get(r)===c&&e.delete(r),e?.size===0&&H.delete(n);return}c.busy=!1,Se(n,r,c)}};if(c.busy){let n=await Q(e,t,i,a,o);return{socket:n,reused:!1,release:()=>{Z(n)}}}X(c.socket)||(Z(c.socket),s?.delete(r),s?.size===0&&H.delete(n))}let l=await Q(e,t,i,a,o),u={socket:l,busy:!0,createdAt:Date.now()};return s=H.get(n),s||(s=new Map,H.set(n,s)),s.set(r,u),{socket:l,entry:u,reused:!1,release:({keep:e}={})=>{if(!e||!X(u.socket)){Z(u.socket),u.idleTimer&&clearTimeout(u.idleTimer);let e=H.get(n);e?.get(r)===u&&e.delete(r),e?.size===0&&H.delete(n);return}u.busy=!1,Se(n,r,u)}}}function $(e){if(e&&typeof e==`object`){let t=`message`in e?e.message:void 0;if(typeof t==`string`&&t.length>0)return Error(t);let n=`error`in e?e.error:void 0;if(n instanceof Error&&n.message.length>0)return n;if(n&&typeof n==`object`&&`message`in n){let e=n.message;if(typeof e==`string`&&e.length>0)return Error(e)}}return Error(`WebSocket error`)}function we(e){if(e&&typeof e==`object`){let t=`code`in e?e.code:void 0,n=`reason`in e?e.reason:void 0,r=`wasClean`in e?e.wasClean:void 0,i=typeof t==`number`?` ${t}`:``,a=typeof n==`string`&&n.length>0?` ${n}`:``;return!a&&t===1009&&(a=` message too big`),new ye(`WebSocket closed${i}${a}`.trim(),{code:typeof t==`number`?t:void 0,reason:typeof n==`string`&&n.length>0?n:void 0,wasClean:typeof r==`boolean`?r:void 0})}return Error(`WebSocket closed`)}async function Te(e){if(typeof e==`string`)return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(e&&typeof e==`object`&&`arrayBuffer`in e){let t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*Ee(e,n,r){let i=[],a=null,o=!1,s=null,c=!1,l=()=>{if(!a)return;let e=a;a=null,e()},u=e=>{(async()=>{let n=null;try{if(!e||typeof e!=`object`||!(`data`in e)||(n=await Te(e.data),!n))return;let t=JSON.parse(n),r=typeof t.type==`string`?t.type:``;(r===`response.completed`||r===`response.done`||r===`response.incomplete`)&&(c=!0,o=!0),i.push(t),l()}catch(e){s=new B(`Invalid Codex WebSocket JSON: ${t(e)}`,{cause:e,payload:n}),o=!0,l()}})()},d=e=>{s=$(e),o=!0,l()},f=e=>{if(c){o=!0,l();return}s||=we(e),o=!0,l()},p=()=>{s=Error(`Request was aborted`),o=!0,l()};e.addEventListener(`message`,u),e.addEventListener(`error`,d),e.addEventListener(`close`,f),n?.addEventListener(`abort`,p);try{for(;;){if(n?.aborted)throw Error(`Request was aborted`);if(i.length>0){yield i.shift();continue}if(o)break;let t;await new Promise((n,i)=>{a=n,r!==void 0&&r>0&&(t=setTimeout(()=>{let t=Error(`WebSocket idle timeout after ${r}ms`);s=t,o=!0,a=null,Z(e,1e3,`idle_timeout`),i(t)},r))}).finally(()=>{t&&clearTimeout(t)})}if(s)throw s;if(!c)throw Error(`WebSocket stream closed before response.completed`)}finally{e.removeEventListener(`message`,u),e.removeEventListener(`error`,d),e.removeEventListener(`close`,f),n?.removeEventListener(`abort`,p)}}function De(e){let{input:t,previous_response_id:n,...r}=e;return r}function Oe(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function ke(e,t){return JSON.stringify(De(e))===JSON.stringify(De(t))}function Ae(e,t){if(!ke(e,t.lastRequestBody))return;let n=e.input??[],r=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(!(n.length<r.length)&&Oe(n.slice(0,r.length),r))return n.slice(r.length)}function je(e,t){let n=e.continuation;if(!n)return t;let r=Ae(t,n);return!r||!n.lastResponseId?(e.continuation=void 0,t):{...t,previous_response_id:n.lastResponseId,input:r}}async function*Me(e,t){let n=!1;for await(let r of e)n||(n=!0,t()),yield r}async function Ne(e,t,n,r,i,a,o,s,c,l,u,d,f){let{socket:p,entry:m,reused:h,release:g}=await Ce(e,n,l,u,f?.signal,c,f?.env),y=!0,b=f?.transport===`websocket-cached`||f?.transport===`auto`,x=t,S=b&&m?je(m,x):x,C=l?G(l):void 0;C&&(C.requests++,h?C.connectionsReused++:C.connectionsCreated++,b&&C.cachedContextRequests++,S.store===!0&&C.storeTrueRequests++,C.lastInputItems=S.input?.length??0,S.previous_response_id?(C.deltaRequests++,C.lastDeltaInputItems=S.input?.length??0,C.lastPreviousResponseId=S.previous_response_id):(C.fullContextRequests++,C.lastDeltaInputItems=void 0,C.lastPreviousResponseId=void 0));try{if(p.send(JSON.stringify({type:`response.create`,...S})),await _(Me(V(Ee(p,f?.signal,s),r),o),r,i,a,{serviceTier:f?.serviceTier,grammarToolInputProperties:d,resolveServiceTier:L,applyServiceTierPricing:(e,t)=>I(e,t,a)}),f?.signal?.aborted)y=!1;else if(b&&m&&r.responseId){let e=v(a,{messages:[r]},E,{includeSystemPrompt:!1,grammarToolInputProperties:d}).filter(e=>e.type!==`function_call_output`&&e.type!==`custom_tool_call_output`);m.continuation={lastRequestBody:x,lastResponseId:r.responseId,lastResponseItems:e}}}catch(e){throw m&&(m.continuation=void 0),y=!1,e}finally{g({keep:y})}}async function Pe(e){let t=await e.text(),n=t||e.statusText||`Request failed`,r;try{let i=JSON.parse(t)?.error;if(i){let t=i.code||i.type||``;if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(t)||e.status===429){let e=i.plan_type?` (${i.plan_type.toLowerCase()} plan)`:``,t=i.resets_at?Math.max(0,Math.round((i.resets_at*1e3-Date.now())/6e4)):void 0;r=`You have hit your ChatGPT usage limit${e}.${t===void 0?``:` Try again in ~${t} min.`}`.trim()}n=i.message||r||n}}catch{}return{message:n,friendlyMessage:r}}function Fe(e){try{let t=e.split(`.`);if(t.length!==3)throw Error(`Invalid token`);let n=JSON.parse(atob(t[1]))?.[`https://api.openai.com/auth`]?.chatgpt_account_id;if(!n)throw Error(`No account ID in token`);return n}catch{throw Error(`Failed to extract accountId from token`)}}function Ie(e,t,n,r){let i=new Headers(e);for(let[e,n]of Object.entries(t||{}))n===null?i.delete(e):i.set(e,n);return i.set(`Authorization`,`Bearer ${r}`),i.set(`chatgpt-account-id`,n),i.set(`originator`,`pi`),i.set(`User-Agent`,d()),i}function Le(e,t,n,r,i){let a=Ie(e,t,n,r);return a.set(`OpenAI-Beta`,`responses=experimental`),a.set(`accept`,`text/event-stream`),a.set(`content-type`,`application/json`),i&&(a.set(`session-id`,i),a.set(`x-client-request-id`,i)),a}function Re(e,t,n,r,i){let a=Ie(e,t,n,r);return a.delete(`accept`),a.delete(`content-type`),a.delete(`OpenAI-Beta`),a.delete(`openai-beta`),a.set(`OpenAI-Beta`,`responses_websockets=2026-02-06`),a.set(`x-client-request-id`,i),a.set(`session-id`,i),a}export{K as closeOpenAICodexWebSocketSessions,he as getOpenAICodexWebSocketDebugStats,ge as resetOpenAICodexWebSocketDebugStats,N as stream,P as streamSimple};
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import{a as e}from"./diagnostics-B0j2bfEp.mjs";import{n as t,t as n}from"./models-BBd5zwn6.mjs";import{n as r}from"./json-parse-BzRcyI3e.mjs";import{t as i}from"./provider-env-CL5ShLlj.mjs";import{t as a}from"./headers-DlpC0ues.mjs";import{a as o,c as s,d as c,f as l,l as u,o as d,p as f,r as p,s as m,t as h,u as g}from"./transform-messages-1ulTEFY1.mjs";import{t as ee}from"./provider-retry-GaV_ioT7.mjs";import{t as _}from"./sanitize-unicode-D-15laVS.mjs";import{n as v,t as y}from"./github-copilot-headers-DCj7hJoC.mjs";import{n as b}from"./openai-CbFQ5q5I.mjs";import{n as x,t as S}from"./error-body-BBlqjbe7.mjs";import{t as C}from"./openai-prompt-cache-tVHrB8oW.mjs";import{t as w}from"./hash-DNYCELl4.mjs";function T(e,t){if(!e)return!1;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n&&r!==null&&r.trim().length>0)return!0;return!1}function E(e,t,n){if(t)return t;if(T(n,`authorization`)||T(n,`cf-aig-authorization`))return`unused`;throw Error(`No API key for provider: ${e}`)}function D(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function O(e){let t=new Set;for(let n of e)if(n.role===`toolResult`)for(let e of n.addedToolNames??[])t.add(e);return t}function k(e,t){if(!e)return[];let n=new Map(e.map(e=>[e.name,e]));return Array.from(t).map(e=>n.get(e)).filter(e=>e!==void 0)}function A(e){return e.type===`text`}function j(e){return e.type===`thinking`}function M(e){return e.type===`toolCall`}function N(e){return e.type===`image`}function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function te(e){return(e.id===void 0||e.id===null||typeof e.id==`string`)&&(e.format===void 0||typeof e.format==`string`)&&(e.index===void 0||typeof e.index==`number`)}function F(e){if(!P(e)||!te(e))return!1;switch(e.type){case`reasoning.summary`:return typeof e.summary==`string`;case`reasoning.encrypted`:return typeof e.data==`string`;case`reasoning.text`:return typeof e.text==`string`&&(e.signature===void 0||e.signature===null||typeof e.signature==`string`);default:return!1}}function I(e){if(e)try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0&&t.every(F)?t:void 0}catch{return}}function ne(e){if(e)try{let t=JSON.parse(e);return F(t)&&t.type===`reasoning.encrypted`&&typeof t.id==`string`&&t.id.length>0&&t.data.length>0?t:void 0}catch{return}}const re=[`reasoning`,`reasoning_content`,`reasoning_text`];function ie(e){return re.includes(e)}function L(e,t){return e||(i(`PI_CACHE_RETENTION`,t)===`long`?`long`:`short`)}const R=(t,n,i)=>{let o=new e;return(async()=>{let e={role:`assistant`,content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`pending`,timestamp:Date.now()};try{let c=E(t.provider,i?.apiKey,i?.headers),l=$(t),u=s(n.tools,l.supportsOpenAIGrammarTools),d=L(i?.cacheRetention,i?.env),f=d===`none`?void 0:i?.sessionId,p=z(t,n,c,i?.headers,i?.fetch,f,l),h=B(t,n,i,l,d,u),g=await i?.onPayload?.(h,t);g!==void 0&&(h=g);let _={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},maxRetries:0},{data:v,response:y}=await ee(()=>p.chat.completions.create(h,_).withResponse(),{maxRetries:i?.maxRetries,maxRetryDelayMs:i?.maxRetryDelayMs,signal:i?.signal});await i?.onResponse?.({status:y.status,headers:a(y.headers)},t),o.push({type:`start`,partial:e});let b=null,x=null,S=!1,C=new Map,w=new Map,T=e.content,D=e=>T.indexOf(e),O=e=>{let t=e.customInput?.property;if(t===void 0)return``;let n=e.arguments[t];return typeof n==`string`?n:``},k=(e,t,n)=>{let r=e.customInput;if(!r)return;let i=m(r.jsonBuffer,r.property,t,n);return e.arguments={[r.property]:t},i},A=t=>{let n=D(t);if(n!==-1){if(t.type===`text`)o.push({type:`text_end`,contentIndex:n,content:t.text,partial:e});else if(t.type===`thinking`)o.push({type:`thinking_end`,contentIndex:n,content:t.thinking,partial:e});else if(t.type===`toolCall`){if(t.customInput){let r=k(t,O(t),!0);r!==void 0&&o.push({type:`toolcall_delta`,contentIndex:n,delta:r,partial:e})}else t.arguments=r(t.partialArgs);delete t.partialArgs,delete t.customInput,delete t.streamIndex,o.push({type:`toolcall_end`,contentIndex:n,toolCall:t,partial:e})}}},j=()=>(b||(b={type:`text`,text:``},T.push(b),o.push({type:`text_start`,contentIndex:D(b),partial:e})),b),M=t=>(x||(x={type:`thinking`,thinking:``,thinkingSignature:t},T.push(x),o.push({type:`thinking_start`,contentIndex:D(x),partial:e})),x),N=t=>{let n=typeof t.index==`number`?t.index:void 0,r=t.function?.name??t.custom?.name??``,i=n===void 0?void 0:C.get(n);if(!i&&t.id&&(i=w.get(t.id)),!i){let a=t.custom&&!t.function?u.get(r)??`input`:void 0,s=a!==void 0;i={type:`toolCall`,id:t.id||``,name:r,arguments:s?{[a]:``}:{},partialArgs:s?void 0:``,customInput:s?{property:a,jsonBuffer:{input:``,started:!1,closed:!1}}:void 0,streamIndex:n},n!==void 0&&C.set(n,i),t.id&&w.set(t.id,i),T.push(i),o.push({type:`toolcall_start`,contentIndex:D(i),partial:e})}if(n!==void 0&&i.streamIndex===void 0&&(i.streamIndex=n,C.set(n,i)),t.id&&w.set(t.id,i),!i.name&&r&&(i.name=r),t.custom&&!t.function&&!i.customInput){let e=u.get(i.name)??`input`;i.arguments={[e]:``},i.customInput={property:e,jsonBuffer:{input:``,started:!1,closed:!1}},delete i.partialArgs}return i};for await(let n of v){if(!n||typeof n!=`object`)continue;e.responseId||=n.id,typeof n.model==`string`&&n.model.length>0&&n.model!==t.id&&(e.responseModel||=n.model),n.usage&&(e.usage=Z(n.usage,t));let i=Array.isArray(n.choices)?n.choices[0]:void 0;if(i){if(!n.usage&&i.usage&&(e.usage=Z(i.usage,t)),i.finish_reason){e.rawStopReason=i.finish_reason;let t=ue(i.finish_reason);e.stopReason=t.stopReason,t.errorMessage&&(e.errorMessage=t.errorMessage),S=!0}if(i.delta){if(i.delta.content!==null&&i.delta.content!==void 0&&i.delta.content.length>0){let t=j();t.text+=i.delta.content,o.push({type:`text_delta`,contentIndex:D(t),delta:i.delta.content,partial:e})}let n=[`reasoning_content`,`reasoning`,`reasoning_text`],a=i.delta,s=null;for(let e of n){let t=a[e];if(typeof t==`string`&&t.length>0){s=e;break}}if(s){let n=a[s];if(typeof n==`string`&&n.length>0){let r=M(t.provider===`opencode-go`&&s===`reasoning`?`reasoning_content`:s);r.thinking+=n,o.push({type:`thinking_delta`,contentIndex:D(r),delta:n,partial:e})}}if(i?.delta?.tool_calls)for(let t of i.delta.tool_calls){let n=N(t);!n.id&&t.id&&(n.id=t.id,w.set(t.id,n));let i=t.function?.name??t.custom?.name;!n.name&&i&&(n.name=i);let a=``;t.function?.arguments?(a=t.function.arguments,n.partialArgs=(n.partialArgs??``)+t.function.arguments,n.arguments=r(n.partialArgs)):t.custom?.input&&(a=k(n,O(n)+t.custom.input,!1)??``),o.push({type:`toolcall_delta`,contentIndex:D(n),delta:a,partial:e})}let c=i.delta.reasoning_details;if(Array.isArray(c))for(let e of c){if(!F(e))continue;let t=M(``),n=I(t.thinkingSignature)??[];n.push(e),t.thinkingSignature=JSON.stringify(n)}}}}for(let e of T)A(e);if(i?.signal?.aborted||e.stopReason===`aborted`)throw Error(`Request was aborted`);if(!S&&!l.supportsFinishReason&&(e.stopReason=e.content.some(e=>e.type===`toolCall`)?`toolUse`:`stop`),e.stopReason===`error`)throw Error(e.errorMessage||`Provider returned an error stop reason`);if(l.supportsFinishReason&&!S||e.stopReason===`pending`)throw Error(`Stream ended without finish_reason`);o.push({type:`done`,reason:e.stopReason,message:e}),o.end()}catch(t){for(let t of e.content)delete t.index,delete t.partialArgs,delete t.customInput,delete t.streamIndex;e.stopReason=i?.signal?.aborted?`aborted`:`error`,e.errorMessage=S(x(t));let n=t?.error?.metadata?.raw;n&&!e.errorMessage.includes(String(n))&&(e.errorMessage+=`\n${n}`),o.push({type:`error`,reason:e.stopReason,error:e}),o.end()}})(),o},ae=(e,n,r)=>{E(e.provider,r?.apiKey,r?.headers);let i={...p(e,n,r,r?.apiKey),toolChoice:r?.toolChoice},a=r?.reasoning?t(e,r.reasoning):void 0,o=a===`off`?void 0:a;return R(e,n,{...i,reasoningEffort:o,thinkingBudgets:r?.thinkingBudgets})};function z(e,t,n,r,i,a,o=$(e)){let s={"User-Agent":f(),...e.headers};if(e.provider===`github-copilot`){let e=v(t.messages),n=y({messages:t.messages,hasImages:e});Object.assign(s,n)}return a&&o.sendSessionAffinityHeaders&&(o.sessionAffinityFormat===`openrouter`?s[`x-session-id`]=a:(o.sessionAffinityFormat===`openai`&&(s.session_id=a),s[`x-client-request-id`]=a,s[`x-session-affinity`]=a)),r&&Object.assign(s,r),new b({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:i,defaultHeaders:s})}function B(e,t,n,r=$(e),i=L(n?.cacheRetention,n?.env),a=s(t.tools,r.supportsOpenAIGrammarTools)){let o=Y(e,t,r,{grammarToolInputProperties:a}),c=G(r,i),l={model:e.id,messages:o,stream:!0,prompt_cache_key:e.baseUrl.includes(`api.openai.com`)&&i!==`none`||i===`long`&&r.supportsLongCacheRetention?C(n?.sessionId):void 0,prompt_cache_retention:i===`long`&&r.supportsLongCacheRetention?`24h`:void 0};r.supportsUsageInStreaming!==!1&&(l.stream_options={include_usage:!0}),r.supportsStore&&(l.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?l.max_tokens=n.maxTokens:l.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(l.temperature=n.temperature);let u=r.deferredToolsMode===`kimi`?O(t.messages):new Set,d=t.tools?.filter(e=>!u.has(e.name));d&&d.length>0?(l.tools=X(d,r),r.zaiToolStream&&(l.tool_stream=!0)):D(t.messages)&&(l.tools=[]),c&&K(o,l.tools,c),n?.toolChoice&&(l.tool_choice=n.toolChoice);let f=V(r),p=H(e,n,l);if(r.thinkingFormat===`zai`&&e.reasoning){let t=l;if(t.thinking=n?.reasoningEffort?{type:`enabled`,clear_thinking:!1}:{type:`disabled`},n?.reasoningEffort&&r.supportsReasoningEffort){let r=e.thinkingLevelMap?.[n.reasoningEffort],i=r===void 0?n.reasoningEffort:r;typeof i==`string`&&(t.reasoning_effort=i)}}else if(r.thinkingFormat===`qwen`&&e.reasoning){if(l.enable_thinking=!!n?.reasoningEffort,n?.reasoningEffort&&r.supportsReasoningEffort){let t=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;typeof t==`string`&&(l.reasoning_effort=t)}}else if(r.thinkingFormat===`qwen-chat-template`&&e.reasoning)l.chat_template_kwargs={enable_thinking:!!n?.reasoningEffort,preserve_thinking:!0};else if(r.thinkingFormat===`chat-template`&&e.reasoning){let t=U(e,n,r.chatTemplateKwargs,p);t&&(l.chat_template_kwargs=t)}else if(r.thinkingFormat===`baseten`&&e.reasoning){let t=l,i=U(e,n,r.chatTemplateArgs,p);if(i&&(t.chat_template_args=i),r.supportsReasoningEffort){let r=n?.reasoningEffort,i=r?e.thinkingLevelMap?.[r]:e.thinkingLevelMap?.off,a=i===void 0?r:i;typeof a==`string`&&(t.reasoning_effort=a)}}else if(r.thinkingFormat===`deepseek`&&e.reasoning)n?.reasoningEffort?l.thinking={type:`enabled`}:e.thinkingLevelMap?.off!==null&&(l.thinking={type:`disabled`}),n?.reasoningEffort&&r.supportsReasoningEffort&&(l.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort);else if(r.thinkingFormat===`openrouter`&&e.reasoning){let t=l;n?.reasoningEffort?t.reasoning={effort:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort}:e.thinkingLevelMap?.off!==null&&(t.reasoning={effort:e.thinkingLevelMap?.off??`none`})}else if(r.thinkingFormat===`ant-ling`&&e.reasoning&&n?.reasoningEffort){let t=e.thinkingLevelMap?.[n.reasoningEffort];typeof t==`string`&&(l.reasoning={effort:t})}else if(r.thinkingFormat===`together`&&e.reasoning){let t=l;t.reasoning={enabled:!!n?.reasoningEffort},n?.reasoningEffort&&r.supportsReasoningEffort&&(t.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort)}else if(r.thinkingFormat===`string-thinking`&&e.reasoning){let t=l;n?.reasoningEffort?t.thinking=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:e.thinkingLevelMap?.off!==null&&(t.thinking=e.thinkingLevelMap?.off??`none`)}else if(n?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort)l.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;else if(!n?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort){let t=e.thinkingLevelMap?.off;typeof t==`string`&&(l.reasoning_effort=t)}if(f&&p!==void 0&&Object.assign(l,{[f]:p}),e.compat?.openRouterRouting&&(l.provider=e.compat.openRouterRouting),e.compat?.vercelGatewayRouting){let t=e.compat.vercelGatewayRouting;if(t.only||t.order){let e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),l.providerOptions={gateway:e}}}return n?.samplingParams&&Object.assign(l,n.samplingParams),l}function V(e){if(e.thinkingTokenBudgetField)return e.thinkingTokenBudgetField;if(e.supportsThinkingTokenBudget)return`thinking_token_budget`}function H(e,t,n){if(!t?.reasoningEffort||!e.reasoning)return;let r=n.max_tokens??n.max_completion_tokens??e.maxTokens,i=o(d(t.reasoningEffort,t.thinkingBudgets),r);return i>0?i:void 0}function U(e,t,n,r){let i={};for(let[a,o]of Object.entries(n)){let n=W(e,t,o,r);n!==void 0&&(i[a]=n)}return Object.keys(i).length>0?i:void 0}function W(e,t,n,r){if(typeof n!=`object`||!n)return n;let i=t?.reasoningEffort;if(!i&&n.omitWhenOff)return;if(n.$var===`thinking.enabled`)return!!i;if(n.$var===`thinking.budget`)return r;let a=i?e.thinkingLevelMap?.[i]:e.thinkingLevelMap?.off;return a===void 0?i:typeof a==`string`?a:void 0}function G(e,t){if(e.cacheControlFormat!==`anthropic`||t===`none`)return;let n=t===`long`&&e.supportsLongCacheRetention?`1h`:void 0;return{type:`ephemeral`,...n?{ttl:n}:{}}}function K(e,t,n){q(e,n),se(t,n),oe(e,n)}function q(e,t){for(let n of e)if(n.role===`system`||n.role===`developer`){ce(n,t);return}}function oe(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if((r.role===`user`||r.role===`assistant`||r.role===`tool`)&&le(r,t))return}}function se(e,t){if(!e||e.length===0)return;let n=e[e.length-1];n.cache_control=t}function ce(e,t){return J(e,t)}function le(e,t){return e.role===`user`||e.role===`assistant`||e.role===`tool`?J(e,t):!1}function J(e,t){let n=e.content;if(typeof n==`string`)return n.length===0?!1:(e.content=[{type:`text`,text:n,cache_control:t}],!0);if(!Array.isArray(n))return!1;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r?.type===`text`){let e=r;return e.cache_control=t,!0}}return!1}function Y(e,t,n,r){let i=[],a=t=>{if(t.includes(`|`)){let e=t.indexOf(`|`),n=t.slice(0,e).replace(/[^a-zA-Z0-9_-]/g,`_`),r=t.slice(e+1).replace(/[^a-zA-Z0-9_-]/g,`_`),i=r.length>0?`${n}_${r}`:n;if(i.length<=40)return i;let a=w(t).slice(0,8);return`${n.slice(0,Math.max(1,40-a.length-1))}_${a}`}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},o=h(t.messages,e,e=>a(e));if(t.systemPrompt){let r=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;i.push({role:r,content:_(t.systemPrompt)})}let s=null;for(let a=0;a<o.length;a++){let c=o[a];if(n.requiresAssistantAfterToolResult&&s===`toolResult`&&c.role===`user`&&i.push({role:`assistant`,content:`I have processed the tool results.`}),c.role===`user`)if(typeof c.content==`string`)i.push({role:`user`,content:_(c.content)});else{let e=c.content.map(e=>e.type===`text`?{type:`text`,text:_(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});if(e.length===0)continue;i.push({role:`user`,content:e})}else if(c.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=c.content.filter(A).filter(e=>e.text.trim().length>0).map(e=>({type:`text`,text:_(e.text)})),o=a.map(e=>e.text).join(``),s=c.content.filter(j),l=c.content.filter(M),d=s.map(e=>I(e.thinkingSignature)).find(e=>e!==void 0),f=l.map(e=>ne(e.thoughtSignature)).filter(e=>e!==void 0),p=d??(f.length>0?f:void 0),m=s.filter(e=>e.thinking.trim().length>0);if(m.length>0){if(n.requiresThinkingAsText)t.content=[{type:`text`,text:m.map(e=>_(e.thinking)).join(`
3
+
4
+ `)},...a];else if(o.length>0&&(t.content=o),!p){let n=m[0].thinkingSignature;e.provider===`opencode-go`&&n===`reasoning`&&(n=`reasoning_content`),n&&ie(n)&&(t[n]=m.map(e=>e.thinking).join(`
5
+ `))}}else o.length>0&&(t.content=o);l.length>0&&(t.tool_calls=l.map(e=>{let t=r?.grammarToolInputProperties?.get(e.name);return t===void 0?{id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}:{id:e.id,type:`custom`,custom:{name:e.name,input:_(u(e.name,e.arguments,t))}}})),p&&(t.reasoning_details=p),n.requiresReasoningContentOnAssistantMessages&&e.reasoning&&t.reasoning_content===void 0&&(t.reasoning_content=``);let h=t.content;if(!(h!=null&&h.length>0)&&!t.tool_calls)continue;i.push(t)}else if(c.role===`toolResult`){let r=[],c=new Set,l=a;for(;l<o.length&&o[l].role===`toolResult`;l++){let t=o[l],a=t.content.filter(A).map(e=>e.text).join(`
6
+ `),s=t.content.some(e=>e.type===`image`),u={role:`tool`,content:_(a.length>0?a:s?`(see attached image)`:`(no tool output)`),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(u.name=t.toolName),i.push(u),n.deferredToolsMode===`kimi`)for(let e of t.addedToolNames??[])c.add(e);if(s&&e.input.includes(`image`))for(let e of t.content)N(e)&&r.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}if(a=l-1,r.length>0?(n.requiresAssistantAfterToolResult&&i.push({role:`assistant`,content:`I have processed the tool results.`}),i.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...r]}),s=`user`):s=`toolResult`,c.size>0){let e=k(t.tools,c);if(e.length>0){let t={role:`system`,tools:X(e,n)};i.push(t)}}continue}s=c.role}return i}function X(e,t){return e.map(e=>{let n=c(e,t.supportsOpenAIGrammarTools);if(n)return{type:`custom`,custom:{name:e.name,description:e.description,format:{type:`grammar`,grammar:{syntax:n.format,definition:n.definition}}}};let r=l(e,t.supportsStrictMode!==!1);return{type:`function`,function:{name:e.name,description:e.description,parameters:g(e,r),...t.supportsStrictMode!==!1&&{strict:r??!1}}}})}function Z(e,t){let r=e.prompt_tokens||0,i=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_tokens??e.cached_tokens??0,a=e.prompt_tokens_details?.cache_write_tokens||0,o=Math.max(0,r-i-a),s=e.completion_tokens||0,c={input:o,output:s,cacheRead:i,cacheWrite:a,reasoning:e.completion_tokens_details?.reasoning_tokens||0,totalTokens:o+s+i+a,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return n(t,c),c}function ue(e){if(e===null)return{stopReason:`stop`};switch(e){case`stop`:case`end`:return{stopReason:`stop`};case`length`:return{stopReason:`length`};case`function_call`:case`tool_calls`:return{stopReason:`toolUse`};case`content_filter`:return{stopReason:`error`,errorMessage:`Provider finish_reason: content_filter`};case`network_error`:return{stopReason:`error`,errorMessage:`Provider finish_reason: network_error`};default:return{stopReason:`error`,errorMessage:`Provider finish_reason: ${e}`}}}function Q(e){let t=e.provider,n=e.baseUrl,r=t===`zai`||t===`zai-coding-cn`||n.includes(`api.z.ai`)||n.includes(`open.bigmodel.cn`),i=t===`together`||n.includes(`api.together.ai`)||n.includes(`api.together.xyz`),a=t===`moonshotai`||t===`moonshotai-cn`||n.includes(`api.moonshot.`),o=t===`openrouter`||n.includes(`openrouter.ai`),s=t===`cloudflare-workers-ai`||n.includes(`api.cloudflare.com`),c=t===`cloudflare-ai-gateway`||n.includes(`gateway.ai.cloudflare.com`),l=t===`nvidia`||n.includes(`integrate.api.nvidia.com`),u=t===`ant-ling`||n.includes(`api.ant-ling.com`),d=t===`deepseek`||n.toLowerCase().includes(`deepseek.com`),f=l||t===`cerebras`||n.includes(`cerebras.ai`)||t===`xai`||n.includes(`api.x.ai`)||i||n.includes(`chutes.ai`)||d||r||a||t===`opencode`||n.includes(`opencode.ai`)||s||c||u,p=n.includes(`chutes.ai`)||d||a||c||i||l||u||r,m=t===`xai`||n.includes(`api.x.ai`),h=o&&(e.id.startsWith(`anthropic/`)||e.id.startsWith(`openai/`)),g=t===`openrouter`&&e.id.startsWith(`anthropic/`)?`anthropic`:void 0;return{supportsStore:!f,supportsDeveloperRole:h||!f&&!o,supportsReasoningEffort:!m&&!r&&!a&&!i&&!c&&!l&&!u,supportsUsageInStreaming:!0,supportsFinishReason:!0,maxTokensField:p?`max_tokens`:`max_completion_tokens`,requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:d,thinkingFormat:d?`deepseek`:r?`zai`:i?`together`:u?`ant-ling`:o?`openrouter`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},chatTemplateArgs:{},zaiToolStream:!1,supportsThinkingTokenBudget:!1,thinkingTokenBudgetField:void 0,supportsStrictMode:!a&&!i&&!c&&!l,supportsOpenAIGrammarTools:!1,cacheControlFormat:g,sendSessionAffinityHeaders:!1,deferredToolsMode:void 0,sessionAffinityFormat:o?`openrouter`:`openai`,supportsLongCacheRetention:!(i||s||c||l||u)}}function $(e){let t=Q(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,supportsFinishReason:e.compat.supportsFinishReason??t.supportsFinishReason,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??t.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,chatTemplateKwargs:e.compat.chatTemplateKwargs??t.chatTemplateKwargs,chatTemplateArgs:e.compat.chatTemplateArgs??t.chatTemplateArgs,zaiToolStream:e.compat.zaiToolStream??t.zaiToolStream,supportsThinkingTokenBudget:e.compat.supportsThinkingTokenBudget??t.supportsThinkingTokenBudget,thinkingTokenBudgetField:e.compat.thinkingTokenBudgetField??t.thinkingTokenBudgetField,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode,supportsOpenAIGrammarTools:e.compat.supportsOpenAIGrammarTools??t.supportsOpenAIGrammarTools,cacheControlFormat:e.compat.cacheControlFormat??t.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??t.sendSessionAffinityHeaders,deferredToolsMode:e.compat.deferredToolsMode??t.deferredToolsMode,sessionAffinityFormat:e.compat.sessionAffinityFormat??t.sessionAffinityFormat,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??t.supportsLongCacheRetention}:t}export{Y as convertMessages,R as stream,ae as streamSimple};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import{a as e}from"./diagnostics-B0j2bfEp.mjs";import{n as t}from"./models-BBd5zwn6.mjs";import"./json-parse-BzRcyI3e.mjs";import{t as n}from"./provider-env-CL5ShLlj.mjs";import{t as r}from"./deferred-tools-CozAnCQL.mjs";import{t as i}from"./headers-DlpC0ues.mjs";import{c as a,p as o,r as s}from"./transform-messages-1ulTEFY1.mjs";import{t as c}from"./provider-retry-GaV_ioT7.mjs";import{n as l,t as u}from"./github-copilot-headers-DCj7hJoC.mjs";import{n as d}from"./openai-CbFQ5q5I.mjs";import{n as f,t as p}from"./error-body-BBlqjbe7.mjs";import{t as m}from"./openai-prompt-cache-tVHrB8oW.mjs";import{n as h,r as g,t as _}from"./openai-responses-shared-Brqyk2bc.mjs";const v=new Set([`openai`,`openai-codex`,`opencode`]);function y(e,t){if(!e)return!1;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n&&r!==null&&r.trim().length>0)return!0;return!1}function b(e,t,n){if(t)return t;if(y(n,`authorization`)||y(n,`cf-aig-authorization`))return`unused`;throw Error(`No API key for provider: ${e}`)}function x(e){return e.provider===`openrouter`||e.baseUrl.includes(`openrouter.ai`)?`openrouter`:`openai`}function S(e,t){return e||(n(`PI_CACHE_RETENTION`,t)===`long`?`long`:`short`)}function C(e){return{supportsDeveloperRole:e.compat?.supportsDeveloperRole??!0,sessionAffinityFormat:e.compat?.sessionAffinityFormat??x(e),supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0,supportsStrictMode:e.compat?.supportsStrictMode??!1,supportsOpenAIGrammarTools:e.compat?.supportsOpenAIGrammarTools??!1,supportsAdditionalTools:e.compat?.supportsAdditionalTools??!1,supportsToolSearch:e.compat?.supportsToolSearch??!1,supportsExplicitPromptCacheMode:e.compat?.supportsExplicitPromptCacheMode??!1}}function w(e,t){return t===`long`&&e.supportsLongCacheRetention?`24h`:void 0}function T(e){return p(f(e),`OpenAI API error`)}const E=(t,n,r)=>{let o=new e;return(async()=>{let e={role:`assistant`,content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`pending`,timestamp:Date.now()};try{let s=b(t.provider,r?.apiKey,r?.headers),l=S(r?.cacheRetention,r?.env)===`none`?void 0:r?.sessionId,u=C(t),d=a(n.tools,u.supportsOpenAIGrammarTools),f=O(t,n,s,r?.headers,r?.fetch,l),p=k(t,n,r,u,d),m=await r?.onPayload?.(p,t);m!==void 0&&(p=m);let h={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs===void 0?{}:{timeout:r.timeoutMs},maxRetries:0},{data:_,response:v}=await c(()=>f.responses.create(p,h).withResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});if(await r?.onResponse?.({status:v.status,headers:i(v.headers)},t),o.push({type:`start`,partial:e}),await g(_,e,o,t,{serviceTier:r?.serviceTier,grammarToolInputProperties:d,applyServiceTierPricing:(e,n)=>j(e,n,t)}),r?.signal?.aborted)throw Error(`Request was aborted`);if(e.stopReason===`pending`)throw Error(`OpenAI Responses stream ended without a stop reason`);if(e.stopReason===`aborted`||e.stopReason===`error`)throw Error(e.errorMessage||`An unknown error occurred`);o.push({type:`done`,reason:e.stopReason,message:e}),o.end()}catch(t){for(let t of e.content)delete t.index,delete t.partialJson,delete t.customInput;e.stopReason=r?.signal?.aborted?`aborted`:`error`,e.errorMessage=T(t),o.push({type:`error`,reason:e.stopReason,error:e}),o.end()}})(),o},D=(e,n,r)=>{b(e.provider,r?.apiKey,r?.headers);let i={...s(e,n,r,r?.apiKey),toolChoice:r?.toolChoice},a=r?.reasoning?t(e,r.reasoning):void 0,o=a===`off`?void 0:a;return E(e,n,{...i,reasoningEffort:o})};function O(e,t,n,r,i,a){let s=C(e),c={"User-Agent":o(),...e.headers};if(e.provider===`github-copilot`){let e=l(t.messages),n=u({messages:t.messages,hasImages:e});Object.assign(c,n)}return a&&(s.sessionAffinityFormat===`openrouter`?c[`x-session-id`]=a:(s.sessionAffinityFormat===`openai`&&(c.session_id=a),c[`x-client-request-id`]=a)),r&&Object.assign(c,r),new d({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:i,defaultHeaders:c})}function k(e,t,n,i=C(e),o=a(t.tools,i.supportsOpenAIGrammarTools)){let s=i.supportsAdditionalTools?`additional-tools`:i.supportsToolSearch?`tool-search`:void 0,c=r(t,s!==void 0),l=_(e,t,v,{grammarToolInputProperties:o,deferredTools:c.deferred,deferredToolsMode:s,toolOptions:{supportsStrictMode:i.supportsStrictMode,supportsOpenAIGrammarTools:i.supportsOpenAIGrammarTools}}),u=S(n?.cacheRetention,n?.env),d=u===`none`&&i.supportsExplicitPromptCacheMode,f={model:e.id,input:l,stream:!0,prompt_cache_key:u===`none`?void 0:m(n?.sessionId),prompt_cache_retention:w(i,u),prompt_cache_options:d?{mode:`explicit`}:void 0,store:!1};return n?.maxTokens&&(f.max_output_tokens=Math.max(n.maxTokens,16)),n?.temperature!==void 0&&(f.temperature=n?.temperature),n?.serviceTier!==void 0&&(f.service_tier=n.serviceTier),c.immediate.length>0&&(f.tools=h(c.immediate,{supportsStrictMode:i.supportsStrictMode,supportsOpenAIGrammarTools:i.supportsOpenAIGrammarTools})),n?.toolChoice!==void 0&&(f.tool_choice=n.toolChoice),e.reasoning&&(n?.reasoningEffort||n?.reasoningSummary?(f.reasoning={effort:n?.reasoningEffort?e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:`medium`,summary:n?.reasoningSummary||`auto`},f.include=[`reasoning.encrypted_content`]):e.provider!==`github-copilot`&&e.thinkingLevelMap?.off!==null&&(f.reasoning={effort:e.thinkingLevelMap?.off??`none`}),e.provider===`xai`&&(f.include=[`reasoning.encrypted_content`])),n?.samplingParams&&Object.assign(f,n.samplingParams),f}function A(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function j(e,t,n){let r=A(n,t);r!==1&&(e.cost.input*=r,e.cost.output*=r,e.cost.cacheRead*=r,e.cost.cacheWrite*=r,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}export{E as stream,D as streamSimple};
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{t as e}from"./models-BBd5zwn6.mjs";import{n as t}from"./json-parse-BzRcyI3e.mjs";import{t as n}from"./sanitize-unicode-Byz9nlLd.mjs";import{d as r,f as i,l as a,s as o,t as s,u as c}from"./transform-messages-BHnJzowk.mjs";import{t as l}from"./hash-DNYCELl4.mjs";function u(e,t){let n={v:1,id:e};return t&&(n.phase=t),JSON.stringify(n)}function d(e){if(e){if(e.startsWith(`{`))try{let t=JSON.parse(e);if(t.v===1&&typeof t.id==`string`)return t.phase===`commentary`||t.phase===`final_answer`?{id:t.id,phase:t.phase}:{id:t.id}}catch{}return{id:e}}}function f(e,t){let r=t.filter(e=>e.type===`text`).map(e=>e.text).join(`
3
- `),i=t.filter(e=>e.type===`image`),a=r.length>0;if(i.length===0||!e.input.includes(`image`))return n(a?r:i.length>0?`(see attached image)`:`(no tool output)`);let o=[];a&&o.push({type:`input_text`,text:n(r)});for(let e of i)o.push({type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`});return o}function p(e,t,r,i){let o=[],c=new Set,u=e=>{let t=e.replace(/[^a-zA-Z0-9_-]/g,`_`);return(t.length>64?t.slice(0,64):t).replace(/_+$/,``)},p=e=>{let t=`fc_${l(e)}`;return t.length>64?t.slice(0,64):t},h=s(t.messages,e,(t,n,i)=>{if(!r.has(e.provider)||!t.includes(`|`))return u(t);let[a,o]=t.split(`|`),s=u(a),c=i.provider!==e.provider||i.api!==e.api?p(o):u(o);return c.startsWith(`fc_`)||(c=u(`fc_${c}`)),`${s}|${c}`});if((i?.includeSystemPrompt??!0)&&t.systemPrompt){let r=e.compat,i=e.reasoning&&r?.supportsDeveloperRole!==!1?`developer`:`system`;o.push({role:i,content:n(t.systemPrompt)})}let g=0;for(let t of h){if(t.role===`user`)if(typeof t.content==`string`)o.push({role:`user`,content:[{type:`input_text`,text:n(t.content)}]});else{let e=t.content.map(e=>e.type===`text`?{type:`input_text`,text:n(e.text)}:{type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`});if(e.length===0)continue;o.push({role:`user`,content:e})}else if(t.role===`assistant`){let r=[],s=t,c=s.provider===e.provider&&s.api===e.api,u=c&&s.model===e.id,f=c&&s.model!==e.id,p=0;for(let e of t.content)if(e.type===`thinking`){if(e.thinkingSignature){let t=JSON.parse(e.thinkingSignature);r.push(t)}}else if(e.type===`text`){let t=e,i=d(t.textSignature),a=p===0?`msg_pi_${g}`:`msg_pi_${g}_${p}`;p++;let o=i?.id;o?o.length>64&&(o=`msg_${l(o)}`):o=a,r.push({type:`message`,role:`assistant`,content:[{type:`output_text`,text:n(t.text),annotations:[]}],status:`completed`,id:o,phase:i?.phase})}else if(e.type===`toolCall`){let t=e,[o,s]=t.id.split(`|`),c=i?.grammarToolInputProperties?.get(t.name),l=s;(f&&l?.startsWith(`fc_`)||c===void 0&&!l?.startsWith(`fc_`))&&(l=void 0);let d=u||i?.deferredTools?.has(t.name)===!0;c===void 0?r.push({type:`function_call`,id:l,call_id:o,name:t.name,arguments:JSON.stringify(t.arguments),...d&&t.namespace!==void 0?{namespace:t.namespace}:{}}):r.push({type:`custom_tool_call`,id:l,call_id:o,name:t.name,input:n(a(t.name,t.arguments,c)),...d&&t.namespace!==void 0?{namespace:t.namespace}:{}})}if(r.length===0)continue;o.push(...r)}else if(t.role===`toolResult`){let[n]=t.toolCallId.split(`|`),r=f(e,t.content);i?.grammarToolInputProperties?.has(t.toolName)?o.push({type:`custom_tool_call_output`,call_id:n,output:r}):o.push({type:`function_call_output`,call_id:n,output:r});let a=[];for(let e of t.addedToolNames??[]){let t=i?.deferredTools?.get(e);!t||c.has(e)||(c.add(e),a.push(t))}if(a.length>0&&i?.deferredToolsMode===`additional-tools`)o.push({type:`additional_tools`,role:`developer`,tools:m(a,i.toolOptions)});else if(a.length>0&&i?.deferredToolsMode===`tool-search`){let e=a.map(e=>e.name),n=`pi_tool_load_${l(`${t.toolCallId}:${e.join(`,`)}`)}`;o.push({type:`tool_search_call`,call_id:n,execution:`client`,status:`completed`,arguments:{query:e.join(` `),limit:e.length}}),o.push({type:`tool_search_output`,call_id:n,execution:`client`,status:`completed`,tools:m(a,{...i.toolOptions,deferLoading:!0})})}}g++}return o}function m(e,t){let n=t?.strict===void 0?!1:t.strict,a=t?.supportsStrictMode??!0,o=t?.supportsOpenAIGrammarTools??!1;return e.map(e=>{let s=r(e,o);if(s)return{type:`custom`,name:e.name,description:e.description,format:{type:`grammar`,syntax:s.format,definition:s.definition},...t?.deferLoading?{defer_loading:!0}:{}};let l=i(e,a)??n,u={type:`function`,name:e.name,description:e.description,parameters:c(e,l===!0),...t?.deferLoading?{defer_loading:!0}:{}};return a&&(u.strict=l),u})}function h(e){let t=e.customInput?.property;if(t===void 0)return``;let n=e.arguments[t];return typeof n==`string`?n:``}function g(e,t,n){let r=e.customInput;if(!r)return;let i=o(r.jsonBuffer,r.property,t,n);return e.arguments={[r.property]:t},i}async function _(n,r,i,a,o){let s=!1,c=new Map,l=new Map,d=e=>{e.type===`message`&&e.phase===`final_answer`&&(r.stopReason=`stop`)},f=(e,t)=>{let n=c.get(e);return n?.type===t?n:void 0},p=(e,t)=>{t!==void 0&&i.push({type:`toolcall_delta`,contentIndex:e.contentIndex,delta:t,partial:r})},m=(e,t)=>{if(t.type===`reasoning`){let t={type:`thinking`,thinking:``};r.content.push(t);let n={type:`thinking`,block:t,contentIndex:r.content.length-1};return c.set(e,n),i.push({type:`thinking_start`,contentIndex:n.contentIndex,partial:r}),n}if(t.type===`message`){d(t);let n={type:`text`,text:``};r.content.push(n);let a={type:`text`,block:n,contentIndex:r.content.length-1};return c.set(e,a),i.push({type:`text_start`,contentIndex:a.contentIndex,partial:r}),a}if(t.type===`function_call`){let n={type:`toolCall`,id:`${t.call_id}|${t.id}`,name:t.name,arguments:{},...t.namespace===void 0?{}:{namespace:t.namespace},partialJson:t.arguments||``};r.content.push(n);let a={type:`toolCall`,block:n,contentIndex:r.content.length-1};return c.set(e,a),i.push({type:`toolcall_start`,contentIndex:a.contentIndex,partial:r}),a}if(t.type===`custom_tool_call`){let n=o?.grammarToolInputProperties?.get(t.name)??`input`,a=t.input||``,s={type:`toolCall`,id:`${t.call_id}|${t.id}`,name:t.name,arguments:{[n]:a},...t.namespace===void 0?{}:{namespace:t.namespace},customInput:{property:n,jsonBuffer:{input:``,started:!1,closed:!1}}};r.content.push(s);let l={type:`toolCall`,block:s,contentIndex:r.content.length-1};return c.set(e,l),i.push({type:`toolcall_start`,contentIndex:l.contentIndex,partial:r}),l}},_=(e,t)=>c.get(e)??m(e,t),y=e=>{for(let t of e){if(t.type!==`reasoning`||!t.encrypted_content)continue;let e=l.get(t.id);if(!e?.thinkingSignature)continue;let n=JSON.parse(e.thinkingSignature);n.encrypted_content||(e.thinkingSignature=JSON.stringify({...n,encrypted_content:t.encrypted_content}))}},b=t=>{if(s=!0,y(t.output??[]),t?.id&&(r.responseId=t.id),t?.usage){let e=t.usage.input_tokens_details,n=e?.cached_tokens||0,i=e?.cache_write_tokens||0;r.usage={input:Math.max(0,(t.usage.input_tokens||0)-n-i),output:t.usage.output_tokens||0,cacheRead:n,cacheWrite:i,reasoning:t.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:t.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(e(a,r.usage),o?.applyServiceTierPricing){let e=o.resolveServiceTier?o.resolveServiceTier(t?.service_tier,o.serviceTier):t?.service_tier??o.serviceTier;o.applyServiceTierPricing(r.usage,e)}let n=t?.status,i=t?.incomplete_details,c=typeof i?.reason==`string`?i.reason:void 0;r.rawStopReason=c?`${n}.${c}`:n;let l=v(n,c);r.stopReason=l.stopReason,r.errorMessage=l.errorMessage,r.content.some(e=>e.type===`toolCall`)&&r.stopReason===`stop`&&(r.stopReason=`toolUse`)};for await(let e of n)if(e.type===`response.created`)r.responseId=e.response.id;else if(e.type===`response.output_item.added`)m(e.output_index,e.item);else if(e.type===`response.reasoning_summary_text.delta`){let t=f(e.output_index,`thinking`);if(!t)continue;t.block.thinking+=e.delta,i.push({type:`thinking_delta`,contentIndex:t.contentIndex,delta:e.delta,partial:r})}else if(e.type===`response.reasoning_summary_part.done`){let t=f(e.output_index,`thinking`);if(!t)continue;t.block.thinking+=`
2
+ import{t as e}from"./models-BBd5zwn6.mjs";import{n as t}from"./json-parse-BzRcyI3e.mjs";import{d as n,f as r,l as i,s as a,t as o,u as s}from"./transform-messages-1ulTEFY1.mjs";import{t as c}from"./sanitize-unicode-D-15laVS.mjs";import{t as l}from"./hash-DNYCELl4.mjs";function u(e,t){let n={v:1,id:e};return t&&(n.phase=t),JSON.stringify(n)}function d(e){if(e){if(e.startsWith(`{`))try{let t=JSON.parse(e);if(t.v===1&&typeof t.id==`string`)return t.phase===`commentary`||t.phase===`final_answer`?{id:t.id,phase:t.phase}:{id:t.id}}catch{}return{id:e}}}function f(e,t){let n=t.filter(e=>e.type===`text`).map(e=>e.text).join(`
3
+ `),r=t.filter(e=>e.type===`image`),i=n.length>0;if(r.length===0||!e.input.includes(`image`))return c(i?n:r.length>0?`(see attached image)`:`(no tool output)`);let a=[];i&&a.push({type:`input_text`,text:c(n)});for(let e of r)a.push({type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`});return a}function p(e,t,n,r){let a=[],s=new Set,u=e=>{let t=e.replace(/[^a-zA-Z0-9_-]/g,`_`);return(t.length>64?t.slice(0,64):t).replace(/_+$/,``)},p=e=>{let t=`fc_${l(e)}`;return t.length>64?t.slice(0,64):t},h=o(t.messages,e,(t,r,i)=>{if(!n.has(e.provider)||!t.includes(`|`))return u(t);let[a,o]=t.split(`|`),s=u(a),c=i.provider!==e.provider||i.api!==e.api?p(o):u(o);return c.startsWith(`fc_`)||(c=u(`fc_${c}`)),`${s}|${c}`});if((r?.includeSystemPrompt??!0)&&t.systemPrompt){let n=e.compat,r=e.reasoning&&n?.supportsDeveloperRole!==!1?`developer`:`system`;a.push({role:r,content:c(t.systemPrompt)})}let g=0;for(let t of h){if(t.role===`user`)if(typeof t.content==`string`)a.push({role:`user`,content:[{type:`input_text`,text:c(t.content)}]});else{let e=t.content.map(e=>e.type===`text`?{type:`input_text`,text:c(e.text)}:{type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`});if(e.length===0)continue;a.push({role:`user`,content:e})}else if(t.role===`assistant`){let n=[],o=t,s=o.provider===e.provider&&o.api===e.api,u=s&&o.model===e.id,f=s&&o.model!==e.id,p=0;for(let e of t.content)if(e.type===`thinking`){if(e.thinkingSignature){let t=JSON.parse(e.thinkingSignature);n.push(t)}}else if(e.type===`text`){let t=e,r=d(t.textSignature),i=p===0?`msg_pi_${g}`:`msg_pi_${g}_${p}`;p++;let a=r?.id;a?a.length>64&&(a=`msg_${l(a)}`):a=i,n.push({type:`message`,role:`assistant`,content:[{type:`output_text`,text:c(t.text),annotations:[]}],status:`completed`,id:a,phase:r?.phase})}else if(e.type===`toolCall`){let t=e,[a,o]=t.id.split(`|`),s=r?.grammarToolInputProperties?.get(t.name),l=o;(f&&l?.startsWith(`fc_`)||s===void 0&&!l?.startsWith(`fc_`))&&(l=void 0);let d=u||r?.deferredTools?.has(t.name)===!0;s===void 0?n.push({type:`function_call`,id:l,call_id:a,name:t.name,arguments:JSON.stringify(t.arguments),...d&&t.namespace!==void 0?{namespace:t.namespace}:{}}):n.push({type:`custom_tool_call`,id:l,call_id:a,name:t.name,input:c(i(t.name,t.arguments,s)),...d&&t.namespace!==void 0?{namespace:t.namespace}:{}})}if(n.length===0)continue;a.push(...n)}else if(t.role===`toolResult`){let[n]=t.toolCallId.split(`|`),i=f(e,t.content);r?.grammarToolInputProperties?.has(t.toolName)?a.push({type:`custom_tool_call_output`,call_id:n,output:i}):a.push({type:`function_call_output`,call_id:n,output:i});let o=[];for(let e of t.addedToolNames??[]){let t=r?.deferredTools?.get(e);!t||s.has(e)||(s.add(e),o.push(t))}if(o.length>0&&r?.deferredToolsMode===`additional-tools`)a.push({type:`additional_tools`,role:`developer`,tools:m(o,r.toolOptions)});else if(o.length>0&&r?.deferredToolsMode===`tool-search`){let e=o.map(e=>e.name),n=`pi_tool_load_${l(`${t.toolCallId}:${e.join(`,`)}`)}`;a.push({type:`tool_search_call`,call_id:n,execution:`client`,status:`completed`,arguments:{query:e.join(` `),limit:e.length}}),a.push({type:`tool_search_output`,call_id:n,execution:`client`,status:`completed`,tools:m(o,{...r.toolOptions,deferLoading:!0})})}}g++}return a}function m(e,t){let i=t?.strict===void 0?!1:t.strict,a=t?.supportsStrictMode??!0,o=t?.supportsOpenAIGrammarTools??!1;return e.map(e=>{let c=n(e,o);if(c)return{type:`custom`,name:e.name,description:e.description,format:{type:`grammar`,syntax:c.format,definition:c.definition},...t?.deferLoading?{defer_loading:!0}:{}};let l=r(e,a)??i,u={type:`function`,name:e.name,description:e.description,parameters:s(e,l===!0),...t?.deferLoading?{defer_loading:!0}:{}};return a&&(u.strict=l),u})}function h(e){let t=e.customInput?.property;if(t===void 0)return``;let n=e.arguments[t];return typeof n==`string`?n:``}function g(e,t,n){let r=e.customInput;if(!r)return;let i=a(r.jsonBuffer,r.property,t,n);return e.arguments={[r.property]:t},i}async function _(n,r,i,a,o){let s=!1,c=new Map,l=new Map,d=e=>{e.type===`message`&&e.phase===`final_answer`&&(r.stopReason=`stop`)},f=(e,t)=>{let n=c.get(e);return n?.type===t?n:void 0},p=(e,t)=>{t!==void 0&&i.push({type:`toolcall_delta`,contentIndex:e.contentIndex,delta:t,partial:r})},m=(e,t)=>{if(t.type===`reasoning`){let t={type:`thinking`,thinking:``};r.content.push(t);let n={type:`thinking`,block:t,contentIndex:r.content.length-1};return c.set(e,n),i.push({type:`thinking_start`,contentIndex:n.contentIndex,partial:r}),n}if(t.type===`message`){d(t);let n={type:`text`,text:``};r.content.push(n);let a={type:`text`,block:n,contentIndex:r.content.length-1};return c.set(e,a),i.push({type:`text_start`,contentIndex:a.contentIndex,partial:r}),a}if(t.type===`function_call`){let n={type:`toolCall`,id:`${t.call_id}|${t.id}`,name:t.name,arguments:{},...t.namespace===void 0?{}:{namespace:t.namespace},partialJson:t.arguments||``};r.content.push(n);let a={type:`toolCall`,block:n,contentIndex:r.content.length-1};return c.set(e,a),i.push({type:`toolcall_start`,contentIndex:a.contentIndex,partial:r}),a}if(t.type===`custom_tool_call`){let n=o?.grammarToolInputProperties?.get(t.name)??`input`,a=t.input||``,s={type:`toolCall`,id:`${t.call_id}|${t.id}`,name:t.name,arguments:{[n]:a},...t.namespace===void 0?{}:{namespace:t.namespace},customInput:{property:n,jsonBuffer:{input:``,started:!1,closed:!1}}};r.content.push(s);let l={type:`toolCall`,block:s,contentIndex:r.content.length-1};return c.set(e,l),i.push({type:`toolcall_start`,contentIndex:l.contentIndex,partial:r}),l}},_=(e,t)=>c.get(e)??m(e,t),y=e=>{for(let t of e){if(t.type!==`reasoning`||!t.encrypted_content)continue;let e=l.get(t.id);if(!e?.thinkingSignature)continue;let n=JSON.parse(e.thinkingSignature);n.encrypted_content||(e.thinkingSignature=JSON.stringify({...n,encrypted_content:t.encrypted_content}))}},b=t=>{if(s=!0,y(t.output??[]),t?.id&&(r.responseId=t.id),t?.usage){let e=t.usage.input_tokens_details,n=e?.cached_tokens||0,i=e?.cache_write_tokens||0;r.usage={input:Math.max(0,(t.usage.input_tokens||0)-n-i),output:t.usage.output_tokens||0,cacheRead:n,cacheWrite:i,reasoning:t.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:t.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(e(a,r.usage),o?.applyServiceTierPricing){let e=o.resolveServiceTier?o.resolveServiceTier(t?.service_tier,o.serviceTier):t?.service_tier??o.serviceTier;o.applyServiceTierPricing(r.usage,e)}let n=t?.status,i=t?.incomplete_details,c=typeof i?.reason==`string`?i.reason:void 0;r.rawStopReason=c?`${n}.${c}`:n;let l=v(n,c);r.stopReason=l.stopReason,r.errorMessage=l.errorMessage,r.content.some(e=>e.type===`toolCall`)&&r.stopReason===`stop`&&(r.stopReason=`toolUse`)};for await(let e of n)if(e.type===`response.created`)r.responseId=e.response.id;else if(e.type===`response.output_item.added`)m(e.output_index,e.item);else if(e.type===`response.reasoning_summary_text.delta`){let t=f(e.output_index,`thinking`);if(!t)continue;t.block.thinking+=e.delta,i.push({type:`thinking_delta`,contentIndex:t.contentIndex,delta:e.delta,partial:r})}else if(e.type===`response.reasoning_summary_part.done`){let t=f(e.output_index,`thinking`);if(!t)continue;t.block.thinking+=`
4
4
 
5
5
  `,i.push({type:`thinking_delta`,contentIndex:t.contentIndex,delta:`
6
6
 
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{n as e,t}from"./headers-BvGum5dc.mjs";import{t as n}from"./provider-retry-wOYAq0sa.mjs";import{t as r}from"./sanitize-unicode-Byz9nlLd.mjs";import{n as i}from"./openai-CbFQ5q5I.mjs";import{n as a,t as o}from"./error-body-BBlqjbe7.mjs";const s=async(e,r,i)=>{let s={api:e.api,provider:e.provider,model:e.id,output:[],stopReason:`stop`,timestamp:Date.now()};try{let a=i?.apiKey;if(!a)throw Error(`No API key for provider: ${e.provider}`);let o=c(e,a,i?.headers,i?.fetch),d=l(e,r),f=await i?.onPayload?.(d,e);f!==void 0&&(d=f);let p={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},maxRetries:0},{data:m,response:h}=await n(()=>o.chat.completions.create(d,p).withResponse(),{maxRetries:i?.maxRetries,maxRetryDelayMs:i?.maxRetryDelayMs,signal:i?.signal});await i?.onResponse?.({status:h.status,headers:t(h.headers)},e);let g=m;s.responseId=g.id,g.usage&&(s.usage=u(g.usage,e));let _=g.choices[0];if(_){let e=_.message.content;typeof e==`string`&&e.length>0&&s.output.push({type:`text`,text:e});for(let e of _.message.images??[]){let t=typeof e.image_url==`string`?e.image_url:e.image_url?.url;if(!t?.startsWith(`data:`))continue;let n=t.match(/^data:([^;]+);base64,(.+)$/);n&&s.output.push({type:`image`,mimeType:n[1],data:n[2]})}}return s}catch(e){return s.stopReason=i?.signal?.aborted?`aborted`:`error`,s.errorMessage=o(a(e)),s}};function c(t,n,r,a){return new i({apiKey:n,baseURL:t.baseUrl,dangerouslyAllowBrowser:!0,fetch:a,defaultHeaders:e({...t.headers,...r})})}function l(e,t){let n=t.input.map(e=>e.type===`text`?{type:`text`,text:r(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});return{model:e.id,messages:[{role:`user`,content:n}],stream:!1,modalities:e.output.includes(`text`)?[`image`,`text`]:[`image`]}}function u(e,t){let n=e.prompt_tokens||0,r=e.prompt_tokens_details?.cached_tokens||0,i=e.prompt_tokens_details?.cache_write_tokens||0,a=i>0?Math.max(0,r-i):r,o=Math.max(0,n-a-i),s=e.completion_tokens||0,c={input:o,output:s,cacheRead:a,cacheWrite:i,totalTokens:o+s+a+i,cost:{input:t.cost.input/1e6*o,output:t.cost.output/1e6*s,cacheRead:t.cost.cacheRead/1e6*a,cacheWrite:t.cost.cacheWrite/1e6*i,total:0}};return c.cost.total=c.cost.input+c.cost.output+c.cost.cacheRead+c.cost.cacheWrite,c}export{s as generateImages};
2
+ import{n as e,t}from"./headers-DlpC0ues.mjs";import{t as n}from"./provider-retry-GaV_ioT7.mjs";import{t as r}from"./sanitize-unicode-D-15laVS.mjs";import{n as i}from"./openai-CbFQ5q5I.mjs";import{n as a,t as o}from"./error-body-BBlqjbe7.mjs";const s=async(e,r,i)=>{let s={api:e.api,provider:e.provider,model:e.id,output:[],stopReason:`stop`,timestamp:Date.now()};try{let a=i?.apiKey;if(!a)throw Error(`No API key for provider: ${e.provider}`);let o=c(e,a,i?.headers,i?.fetch),d=l(e,r),f=await i?.onPayload?.(d,e);f!==void 0&&(d=f);let p={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},maxRetries:0},{data:m,response:h}=await n(()=>o.chat.completions.create(d,p).withResponse(),{maxRetries:i?.maxRetries,maxRetryDelayMs:i?.maxRetryDelayMs,signal:i?.signal});await i?.onResponse?.({status:h.status,headers:t(h.headers)},e);let g=m;s.responseId=g.id,g.usage&&(s.usage=u(g.usage,e));let _=g.choices[0];if(_){let e=_.message.content;typeof e==`string`&&e.length>0&&s.output.push({type:`text`,text:e});for(let e of _.message.images??[]){let t=typeof e.image_url==`string`?e.image_url:e.image_url?.url;if(!t?.startsWith(`data:`))continue;let n=t.match(/^data:([^;]+);base64,(.+)$/);n&&s.output.push({type:`image`,mimeType:n[1],data:n[2]})}}return s}catch(e){return s.stopReason=i?.signal?.aborted?`aborted`:`error`,s.errorMessage=o(a(e)),s}};function c(t,n,r,a){return new i({apiKey:n,baseURL:t.baseUrl,dangerouslyAllowBrowser:!0,fetch:a,defaultHeaders:e({...t.headers,...r})})}function l(e,t){let n=t.input.map(e=>e.type===`text`?{type:`text`,text:r(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});return{model:e.id,messages:[{role:`user`,content:n}],stream:!1,modalities:e.output.includes(`text`)?[`image`,`text`]:[`image`]}}function u(e,t){let n=e.prompt_tokens||0,r=e.prompt_tokens_details?.cached_tokens||0,i=e.prompt_tokens_details?.cache_write_tokens||0,a=i>0?Math.max(0,r-i):r,o=Math.max(0,n-a-i),s=e.completion_tokens||0,c={input:o,output:s,cacheRead:a,cacheWrite:i,totalTokens:o+s+a+i,cost:{input:t.cost.input/1e6*o,output:t.cost.output/1e6*s,cacheRead:t.cost.cacheRead/1e6*a,cacheWrite:t.cost.cacheWrite/1e6*i,total:0}};return c.cost.total=c.cost.input+c.cost.output+c.cost.cacheRead+c.cost.cacheWrite,c}export{s as generateImages};
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import{a as e,n as t,t as n}from"./diagnostics-B0j2bfEp.mjs";import{n as r}from"./json-parse-BzRcyI3e.mjs";import{t as i}from"./provider-env-CL5ShLlj.mjs";import{n as a,t as o}from"./headers-BvGum5dc.mjs";var s=class extends Error{code;diagnosticDetails;constructor(e,t,n){super(e),this.name=`PiMessagesResponseError`,this.code=t,this.diagnosticDetails=n}};function c(e){try{let t=JSON.parse(e),n=t?.error;return t&&typeof n==`object`&&n&&!Array.isArray(n)?t:void 0}catch{return}}function l(e){let t=8192;return e.length>t?`${e.slice(0,t)}…`:e}function u(e,t,n){let r=typeof n?.error?.message==`string`?n.error.message:void 0,i=typeof n?.error?.code==`string`?n.error.code:void 0,a=r??t,o=i?` (${i})`:``;return`${e.status} ${e.statusText}: ${a}${o}`}function d(e,t,n,r){let i=c(r),a=typeof i?.error?.code==`string`?i.error.code:void 0;return new s(u(n,r,i),a,{version:1,provider:e.provider,model:e.id,url:t.toString(),status:n.status,statusText:n.statusText,error:i?.error,body:i?void 0:l(r),timestampMs:Date.now()})}function f(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function p(e,t){t&&n(e,{type:`pi_messages_rewrite`,timestamp:Date.now(),details:{...t}})}function m(e){let t={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:f(),stopReason:`pending`,timestamp:Date.now()},n=new Map;return e=>{switch(e.type){case`done`:return Object.assign(t,{stopReason:e.reason,usage:e.usage,responseId:e.responseId}),p(t,e.rewrite),{type:`done`,reason:e.reason,message:t};case`error`:return Object.assign(t,{stopReason:e.reason,usage:e.usage,errorMessage:e.errorMessage,responseId:e.responseId}),p(t,e.rewrite),{type:`error`,reason:e.reason,error:t};case`start`:break;case`text_start`:t.content[e.contentIndex]={type:`text`,text:``};break;case`text_delta`:t.content[e.contentIndex].text+=e.delta;break;case`text_end`:Object.assign(t.content[e.contentIndex],{text:e.content,textSignature:e.contentSignature});break;case`thinking_start`:t.content[e.contentIndex]={type:`thinking`,thinking:``};break;case`thinking_delta`:t.content[e.contentIndex].thinking+=e.delta;break;case`thinking_end`:Object.assign(t.content[e.contentIndex],{thinking:e.content,thinkingSignature:e.contentSignature,redacted:e.redacted});break;case`toolcall_start`:t.content[e.contentIndex]={type:`toolCall`,id:e.id,name:e.toolName,arguments:{}},n.set(e.contentIndex,``);break;case`toolcall_delta`:{let i=`${n.get(e.contentIndex)??``}${e.delta}`;n.set(e.contentIndex,i),t.content[e.contentIndex].arguments=r(i);break}case`toolcall_end`:return Object.assign(t.content[e.contentIndex],e.toolCall),n.delete(e.contentIndex),{type:`toolcall_end`,contentIndex:e.contentIndex,toolCall:t.content[e.contentIndex],partial:t}}return{...e,partial:t}}}async function*h(e){let t=new TextDecoder,n=e.getReader(),r=``;try{for(;;){let{done:e,value:i}=await n.read();r+=e?t.decode():t.decode(i,{stream:!0}),r=r.replace(/\r\n/g,`
2
+ import{a as e,n as t,t as n}from"./diagnostics-B0j2bfEp.mjs";import{n as r}from"./json-parse-BzRcyI3e.mjs";import{t as i}from"./provider-env-CL5ShLlj.mjs";import{n as a,t as o}from"./headers-DlpC0ues.mjs";var s=class extends Error{code;diagnosticDetails;constructor(e,t,n){super(e),this.name=`PiMessagesResponseError`,this.code=t,this.diagnosticDetails=n}};function c(e){try{let t=JSON.parse(e),n=t?.error;return t&&typeof n==`object`&&n&&!Array.isArray(n)?t:void 0}catch{return}}function l(e){let t=8192;return e.length>t?`${e.slice(0,t)}…`:e}function u(e,t,n){let r=typeof n?.error?.message==`string`?n.error.message:void 0,i=typeof n?.error?.code==`string`?n.error.code:void 0,a=r??t,o=i?` (${i})`:``;return`${e.status} ${e.statusText}: ${a}${o}`}function d(e,t,n,r){let i=c(r),a=typeof i?.error?.code==`string`?i.error.code:void 0;return new s(u(n,r,i),a,{version:1,provider:e.provider,model:e.id,url:t.toString(),status:n.status,statusText:n.statusText,error:i?.error,body:i?void 0:l(r),timestampMs:Date.now()})}function f(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function p(e,t){t&&n(e,{type:`pi_messages_rewrite`,timestamp:Date.now(),details:{...t}})}function m(e){let t={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:f(),stopReason:`pending`,timestamp:Date.now()},n=new Map;return e=>{switch(e.type){case`done`:return Object.assign(t,{stopReason:e.reason,usage:e.usage,responseId:e.responseId}),p(t,e.rewrite),{type:`done`,reason:e.reason,message:t};case`error`:return Object.assign(t,{stopReason:e.reason,usage:e.usage,errorMessage:e.errorMessage,responseId:e.responseId}),p(t,e.rewrite),{type:`error`,reason:e.reason,error:t};case`start`:break;case`text_start`:t.content[e.contentIndex]={type:`text`,text:``};break;case`text_delta`:t.content[e.contentIndex].text+=e.delta;break;case`text_end`:Object.assign(t.content[e.contentIndex],{text:e.content,textSignature:e.contentSignature});break;case`thinking_start`:t.content[e.contentIndex]={type:`thinking`,thinking:``};break;case`thinking_delta`:t.content[e.contentIndex].thinking+=e.delta;break;case`thinking_end`:Object.assign(t.content[e.contentIndex],{thinking:e.content,thinkingSignature:e.contentSignature,redacted:e.redacted});break;case`toolcall_start`:t.content[e.contentIndex]={type:`toolCall`,id:e.id,name:e.toolName,arguments:{}},n.set(e.contentIndex,``);break;case`toolcall_delta`:{let i=`${n.get(e.contentIndex)??``}${e.delta}`;n.set(e.contentIndex,i),t.content[e.contentIndex].arguments=r(i);break}case`toolcall_end`:return Object.assign(t.content[e.contentIndex],e.toolCall),n.delete(e.contentIndex),{type:`toolcall_end`,contentIndex:e.contentIndex,toolCall:t.content[e.contentIndex],partial:t}}return{...e,partial:t}}}async function*h(e){let t=new TextDecoder,n=e.getReader(),r=``;try{for(;;){let{done:e,value:i}=await n.read();r+=e?t.decode():t.decode(i,{stream:!0}),r=r.replace(/\r\n/g,`
3
3
  `);let a=r.indexOf(`
4
4
 
5
5
  `);for(;a!==-1;){let e=g(r.slice(0,a));e&&(yield e),r=r.slice(a+2),a=r.indexOf(`
6
6
 
7
7
  `)}if(e)break}if(r.trim()){let e=g(r);e&&(yield e)}}finally{n.releaseLock()}}function g(e){let t=e.split(`
8
- `).find(e=>e.startsWith(`data:`))?.slice(5).trim();return t&&t!==`[DONE]`?JSON.parse(t):void 0}function _(e,r,i){let a=i?`aborted`:`error`,o={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:f(),stopReason:a,errorMessage:r instanceof Error?r.message:String(r),timestamp:Date.now()};return!i&&r instanceof s&&n(o,t(`pi_messages_response_failure`,r,r.diagnosticDetails)),{type:`error`,reason:a,error:o}}function v(e,t){return e||(i(`PI_CACHE_RETENTION`,t)===`long`?`long`:void 0)}const y=(t,n,r)=>{let i=new e,s=m(t);return(async()=>{try{let e=r?.apiKey;if(!e)throw Error(`No API key provided for provider "${t.provider}"`);let c=new URL(`${t.baseUrl.replace(/\/+$/u,``)}/messages`);r?.debug&&c.searchParams.set(`debug`,`1`);let l={model:t.id,context:n,options:{temperature:r?.temperature,maxTokens:r?.maxTokens,reasoning:r?.reasoning,cacheRetention:v(r?.cacheRetention,r?.env),sessionId:r?.sessionId,toolChoice:r?.toolChoice}},u=await r?.onPayload?.(l,t);u!==void 0&&(l=u);let f=await(r?.fetch??globalThis.fetch)(c,{method:`POST`,headers:{authorization:`Bearer ${e}`,accept:`text/event-stream`,"content-type":`application/json`,...a(r?.headers)},body:JSON.stringify(l),signal:r?.signal});if(await r?.onResponse?.({status:f.status,headers:o(f.headers)},t),!f.ok)throw d(t,c,f,await f.text());if(!f.body)throw Error(`${t.provider} response has no body`);for await(let e of h(f.body)){let t=s(e);if(i.push(t),t.type===`done`||t.type===`error`)return}throw Error(`${t.provider} stream ended without a terminal event`)}catch(e){i.push(_(t,e,r?.signal?.aborted??!1))}})(),i},b=(e,t,n)=>{let r=n;return y(e,t,{...n,reasoning:n?.reasoning,toolChoice:r?.toolChoice,debug:r?.debug})};export{s as PiMessagesResponseError,y as stream,b as streamSimple};
8
+ `).find(e=>e.startsWith(`data:`))?.slice(5).trim();return t&&t!==`[DONE]`?JSON.parse(t):void 0}function _(e,r,i){let a=i?`aborted`:`error`,o={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:f(),stopReason:a,errorMessage:r instanceof Error?r.message:String(r),timestamp:Date.now()};return!i&&r instanceof s&&n(o,t(`pi_messages_response_failure`,r,r.diagnosticDetails)),{type:`error`,reason:a,error:o}}function v(e,t){return e||(i(`PI_CACHE_RETENTION`,t)===`long`?`long`:void 0)}const y=(t,n,r)=>{let i=new e,s=m(t);return(async()=>{try{let e=r?.apiKey;if(!e)throw Error(`No API key provided for provider "${t.provider}"`);let c=new URL(`${t.baseUrl.replace(/\/+$/u,``)}/messages`);r?.debug&&c.searchParams.set(`debug`,`1`);let l={model:t.id,context:n,options:{temperature:r?.temperature,maxTokens:r?.maxTokens,reasoning:r?.reasoning,cacheRetention:v(r?.cacheRetention,r?.env),sessionId:r?.sessionId,toolChoice:r?.toolChoice}},u=await r?.onPayload?.(l,t);u!==void 0&&(l=u);let f=await(r?.fetch??globalThis.fetch)(c,{method:`POST`,headers:{authorization:`Bearer ${e}`,accept:`text/event-stream`,"content-type":`application/json`,...a(r?.headers)},body:JSON.stringify(l),signal:r?.signal});if(await r?.onResponse?.({status:f.status,headers:o(f.headers)},t),!f.ok)throw d(t,c,f,await f.text());if(!f.body)throw Error(`${t.provider} response has no body`);for await(let e of h(f.body)){let t=s(e);if(i.push(t),t.type===`done`||t.type===`error`)return}throw Error(`${t.provider} stream ended without a terminal event`)}catch(e){i.push(_(t,e,r?.signal?.aborted??!1))}})(),i},b=(e,t,n)=>{let r=n;return y(e,t,{...n,reasoning:n?.reasoning,toolChoice:n?.toolChoice,debug:r?.debug})};export{s as PiMessagesResponseError,y as stream,b as streamSimple};
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import{lt as e}from"./index.mjs";import{a as t,i as n,n as r,o as i,r as a,s as o,t as s}from"./from-Choxbpmr.mjs";import{format as c}from"node:url";import{Buffer as l}from"node:buffer";import u,{PassThrough as d,pipeline as f}from"node:stream";import{deprecate as p,promisify as m,types as h}from"node:util";import g from"node:zlib";import{isIP as _}from"node:net";import v from"node:http";import ee from"node:https";function te(e){if(!/^data:/i.test(e))throw TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');e=e.replace(/\r?\n/g,``);let t=e.indexOf(`,`);if(t===-1||t<=4)throw TypeError(`malformed data: URI`);let n=e.substring(5,t).split(`;`),r=``,i=!1,a=n[0]||`text/plain`,o=a;for(let e=1;e<n.length;e++)n[e]===`base64`?i=!0:n[e]&&(o+=`;${n[e]}`,n[e].indexOf(`charset=`)===0&&(r=n[e].substring(8)));!n[0]&&!r.length&&(o+=`;charset=US-ASCII`,r=`US-ASCII`);let s=i?`base64`:`ascii`,c=unescape(e.substring(t+1)),l=Buffer.from(c,s);return l.type=a,l.typeFull=o,l.charset=r,l}var ne=e((()=>{})),y,b=e((()=>{y=class extends Error{constructor(e,t){super(e),Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}})),x,re=e((()=>{b(),x=class extends y{constructor(e,t,n){super(e,t),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}}})),S,C,w,T,E,ie,D=e((()=>{S=Symbol.toStringTag,C=e=>typeof e==`object`&&typeof e.append==`function`&&typeof e.delete==`function`&&typeof e.get==`function`&&typeof e.getAll==`function`&&typeof e.has==`function`&&typeof e.set==`function`&&typeof e.sort==`function`&&e[S]===`URLSearchParams`,w=e=>e&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&typeof e.constructor==`function`&&/^(Blob|File)$/.test(e[S]),T=e=>typeof e==`object`&&(e[S]===`AbortSignal`||e[S]===`EventTarget`),E=(e,t)=>{let n=new URL(t).hostname,r=new URL(e).hostname;return n===r||n.endsWith(`.${r}`)},ie=(e,t)=>new URL(t).protocol===new URL(e).protocol}));async function O(e){if(e[A].disturbed)throw TypeError(`body used already for: ${e.url}`);if(e[A].disturbed=!0,e[A].error)throw e[A].error;let{body:t}=e;if(t===null||!(t instanceof u))return l.alloc(0);let n=[],r=0;try{for await(let i of t){if(e.size>0&&r+i.length>e.size){let n=new x(`content size at ${e.url} over limit: ${e.size}`,`max-size`);throw t.destroy(n),n}r+=i.length,n.push(i)}}catch(t){throw t instanceof y?t:new x(`Invalid response body while trying to fetch ${e.url}: ${t.message}`,`system`,t)}if(t.readableEnded===!0||t._readableState.ended===!0)try{return n.every(e=>typeof e==`string`)?l.from(n.join(``)):l.concat(n,r)}catch(t){throw new x(`Could not create Buffer from response body for ${e.url}: ${t.message}`,`system`,t)}else throw new x(`Premature close of server response while trying to fetch ${e.url}`)}var k,A,j,M,N,P,F,ae,I=e((()=>{o(),n(),re(),b(),D(),k=m(u.pipeline),A=Symbol(`Body internals`),j=class{constructor(e,{size:t=0}={}){let n=null;e===null?e=null:C(e)?e=l.from(e.toString()):w(e)||l.isBuffer(e)||(h.isAnyArrayBuffer(e)?e=l.from(e):ArrayBuffer.isView(e)?e=l.from(e.buffer,e.byteOffset,e.byteLength):e instanceof u||(e instanceof r?(e=a(e),n=e.type.split(`=`)[1]):e=l.from(String(e))));let i=e;l.isBuffer(e)?i=u.Readable.from(e):w(e)&&(i=u.Readable.from(e.stream())),this[A]={body:e,stream:i,boundary:n,disturbed:!1,error:null},this.size=t,e instanceof u&&e.on(`error`,e=>{let t=e instanceof y?e:new x(`Invalid response body while trying to fetch ${this.url}: ${e.message}`,`system`,e);this[A].error=t})}get body(){return this[A].stream}get bodyUsed(){return this[A].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:n}=await O(this);return e.slice(t,t+n)}async formData(){let e=this.headers.get(`content-type`);if(e.startsWith(`application/x-www-form-urlencoded`)){let e=new r,t=new URLSearchParams(await this.text());for(let[n,r]of t)e.append(n,r);return e}let{toFormData:t}=await import(`./multipart-parser-BdmM0fdd.mjs`);return t(this.body,e)}async blob(){let e=this.headers&&this.headers.get(`content-type`)||this[A].body&&this[A].body.type||``;return new i([await this.arrayBuffer()],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await O(this);return new TextDecoder().decode(e)}buffer(){return O(this)}},j.prototype.buffer=p(j.prototype.buffer,`Please use 'response.arrayBuffer()' instead of 'response.buffer()'`,`node-fetch#buffer`),Object.defineProperties(j.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:p(()=>{},`data doesn't exist, use json(), text(), arrayBuffer(), or body instead`,`https://github.com/node-fetch/node-fetch/issues/1000 (response)`)}}),M=(e,t)=>{let n,r,{body:i}=e[A];if(e.bodyUsed)throw Error(`cannot clone body after it is used`);return i instanceof u&&typeof i.getBoundary!=`function`&&(n=new d({highWaterMark:t}),r=new d({highWaterMark:t}),i.pipe(n),i.pipe(r),e[A].stream=n,i=r),i},N=p(e=>e.getBoundary(),`form-data doesn't follow the spec and requires special treatment. Use alternative package`,`https://github.com/node-fetch/node-fetch/issues/1167`),P=(e,t)=>e===null?null:typeof e==`string`?`text/plain;charset=UTF-8`:C(e)?`application/x-www-form-urlencoded;charset=UTF-8`:w(e)?e.type||null:l.isBuffer(e)||h.isAnyArrayBuffer(e)||ArrayBuffer.isView(e)?null:e instanceof r?`multipart/form-data; boundary=${t[A].boundary}`:e&&typeof e.getBoundary==`function`?`multipart/form-data;boundary=${N(e)}`:e instanceof u?null:`text/plain;charset=UTF-8`,F=e=>{let{body:t}=e[A];return t===null?0:w(t)?t.size:l.isBuffer(t)?t.length:t&&typeof t.getLengthSync==`function`&&t.hasKnownLength&&t.hasKnownLength()?t.getLengthSync():null},ae=async(e,{body:t})=>{t===null?e.end():await k(t,e)}}));function oe(e=[]){return new z(e.reduce((e,t,n,r)=>(n%2==0&&e.push(r.slice(n,n+2)),e),[]).filter(([e,t])=>{try{return L(e),R(e,String(t)),!0}catch{return!1}}))}var L,R,z,B=e((()=>{L=typeof v.validateHeaderName==`function`?v.validateHeaderName:e=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(e)){let t=TypeError(`Header name must be a valid HTTP token [${e}]`);throw Object.defineProperty(t,`code`,{value:`ERR_INVALID_HTTP_TOKEN`}),t}},R=typeof v.validateHeaderValue==`function`?v.validateHeaderValue:(e,t)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(t)){let t=TypeError(`Invalid character in header content ["${e}"]`);throw Object.defineProperty(t,`code`,{value:`ERR_INVALID_CHAR`}),t}},z=class e extends URLSearchParams{constructor(t){let n=[];if(t instanceof e){let e=t.raw();for(let[t,r]of Object.entries(e))n.push(...r.map(e=>[t,e]))}else if(t!=null)if(typeof t==`object`&&!h.isBoxedPrimitive(t)){let e=t[Symbol.iterator];if(e==null)n.push(...Object.entries(t));else{if(typeof e!=`function`)throw TypeError(`Header pairs must be iterable`);n=[...t].map(e=>{if(typeof e!=`object`||h.isBoxedPrimitive(e))throw TypeError(`Each header pair must be an iterable object`);return[...e]}).map(e=>{if(e.length!==2)throw TypeError(`Each header pair must be a name/value tuple`);return[...e]})}}else throw TypeError(`Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)`);return n=n.length>0?n.map(([e,t])=>(L(e),R(e,String(t)),[String(e).toLowerCase(),String(t)])):void 0,super(n),new Proxy(this,{get(e,t,n){switch(t){case`append`:case`set`:return(n,r)=>(L(n),R(n,String(r)),URLSearchParams.prototype[t].call(e,String(n).toLowerCase(),String(r)));case`delete`:case`has`:case`getAll`:return n=>(L(n),URLSearchParams.prototype[t].call(e,String(n).toLowerCase()));case`keys`:return()=>(e.sort(),new Set(URLSearchParams.prototype.keys.call(e)).keys());default:return Reflect.get(e,t,n)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let t=this.getAll(e);if(t.length===0)return null;let n=t.join(`, `);return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}forEach(e,t=void 0){for(let n of this.keys())Reflect.apply(e,t,[this.get(n),n,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,t)=>(e[t]=this.getAll(t),e),{})}[Symbol.for(`nodejs.util.inspect.custom`)](){return[...this.keys()].reduce((e,t)=>{let n=this.getAll(t);return t===`host`?e[t]=n[0]:e[t]=n.length>1?n:n[0],e},{})}},Object.defineProperties(z.prototype,[`get`,`entries`,`forEach`,`values`].reduce((e,t)=>(e[t]={enumerable:!0},e),{}))})),V,H,U=e((()=>{V=new Set([301,302,303,307,308]),H=e=>V.has(e)})),W,G,se=e((()=>{B(),I(),U(),W=Symbol(`Response internals`),G=class e extends j{constructor(e=null,t={}){super(e,t);let n=t.status==null?200:t.status,r=new z(t.headers);if(e!==null&&!r.has(`Content-Type`)){let t=P(e,this);t&&r.append(`Content-Type`,t)}this[W]={type:`default`,url:t.url,status:n,statusText:t.statusText||``,headers:r,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[W].type}get url(){return this[W].url||``}get status(){return this[W].status}get ok(){return this[W].status>=200&&this[W].status<300}get redirected(){return this[W].counter>0}get statusText(){return this[W].statusText}get headers(){return this[W].headers}get highWaterMark(){return this[W].highWaterMark}clone(){return new e(M(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(t,n=302){if(!H(n))throw RangeError(`Failed to execute "redirect" on "response": Invalid status code`);return new e(null,{headers:{location:new URL(t).toString()},status:n})}static error(){let t=new e(null,{status:0,statusText:``});return t[W].type=`error`,t}static json(t=void 0,n={}){let r=JSON.stringify(t);if(r===void 0)throw TypeError(`data is not JSON serializable`);let i=new z(n&&n.headers);return i.has(`content-type`)||i.set(`content-type`,`application/json`),new e(r,{...n,headers:i})}get[Symbol.toStringTag](){return`Response`}},Object.defineProperties(G.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}})})),K,ce=e((()=>{K=e=>{if(e.search)return e.search;let t=e.href.length-1,n=e.hash||(e.href[t]===`#`?`#`:``);return e.href[t-n.length]===`?`?`?`:``}}));function q(e,t=!1){return e==null||(e=new URL(e),/^(about|blob|data):$/.test(e.protocol))?`no-referrer`:(e.username=``,e.password=``,e.hash=``,t&&(e.pathname=``,e.search=``),e)}function le(e){if(!Y.has(e))throw TypeError(`Invalid referrerPolicy: ${e}`);return e}function ue(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;let t=e.host.replace(/(^\[)|(]$)/g,``),n=_(t);return n===4&&/^127\./.test(t)||n===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(t)?!0:e.host===`localhost`||e.host.endsWith(`.localhost`)?!1:e.protocol===`file:`}function J(e){return/^about:(blank|srcdoc)$/.test(e)||e.protocol===`data:`||/^(blob|filesystem):$/.test(e.protocol)?!0:ue(e)}function de(e,{referrerURLCallback:t,referrerOriginCallback:n}={}){if(e.referrer===`no-referrer`||e.referrerPolicy===``)return null;let r=e.referrerPolicy;if(e.referrer===`about:client`)return`no-referrer`;let i=e.referrer,a=q(i),o=q(i,!0);a.toString().length>4096&&(a=o),t&&(a=t(a)),n&&(o=n(o));let s=new URL(e.url);switch(r){case`no-referrer`:return`no-referrer`;case`origin`:return o;case`unsafe-url`:return a;case`strict-origin`:return J(a)&&!J(s)?`no-referrer`:o.toString();case`strict-origin-when-cross-origin`:return a.origin===s.origin?a:J(a)&&!J(s)?`no-referrer`:o;case`same-origin`:return a.origin===s.origin?a:`no-referrer`;case`origin-when-cross-origin`:return a.origin===s.origin?a:o;case`no-referrer-when-downgrade`:return J(a)&&!J(s)?`no-referrer`:a;default:throw TypeError(`Invalid referrerPolicy: ${r}`)}}function fe(e){let t=(e.get(`referrer-policy`)||``).split(/[,\s]+/),n=``;for(let e of t)e&&Y.has(e)&&(n=e);return n}var Y,X,pe=e((()=>{Y=new Set([``,`no-referrer`,`no-referrer-when-downgrade`,`same-origin`,`origin`,`strict-origin`,`origin-when-cross-origin`,`strict-origin-when-cross-origin`,`unsafe-url`]),X=`strict-origin-when-cross-origin`})),Z,Q,me,$,he,ge=e((()=>{B(),I(),D(),ce(),pe(),Z=Symbol(`Request internals`),Q=e=>typeof e==`object`&&typeof e[Z]==`object`,me=p(()=>{},`.data is not a valid RequestInit property, use .body instead`,`https://github.com/node-fetch/node-fetch/issues/1000 (request)`),$=class e extends j{constructor(e,t={}){let n;if(Q(e)?n=new URL(e.url):(n=new URL(e),e={}),n.username!==``||n.password!==``)throw TypeError(`${n} is an url with embedded credentials.`);let r=t.method||e.method||`GET`;if(/^(delete|get|head|options|post|put)$/i.test(r)&&(r=r.toUpperCase()),!Q(t)&&`data`in t&&me(),(t.body!=null||Q(e)&&e.body!==null)&&(r===`GET`||r===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body`);let i=t.body?t.body:Q(e)&&e.body!==null?M(e):null;super(i,{size:t.size||e.size||0});let a=new z(t.headers||e.headers||{});if(i!==null&&!a.has(`Content-Type`)){let e=P(i,this);e&&a.set(`Content-Type`,e)}let o=Q(e)?e.signal:null;if(`signal`in t&&(o=t.signal),o!=null&&!T(o))throw TypeError(`Expected signal to be an instanceof AbortSignal or EventTarget`);let s=t.referrer==null?e.referrer:t.referrer;if(s===``)s=`no-referrer`;else if(s){let e=new URL(s);s=/^about:(\/\/)?client$/.test(e)?`client`:e}else s=void 0;this[Z]={method:r,redirect:t.redirect||e.redirect||`follow`,headers:a,parsedURL:n,signal:o,referrer:s},this.follow=t.follow===void 0?e.follow===void 0?20:e.follow:t.follow,this.compress=t.compress===void 0?e.compress===void 0?!0:e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||``}get method(){return this[Z].method}get url(){return c(this[Z].parsedURL)}get headers(){return this[Z].headers}get redirect(){return this[Z].redirect}get signal(){return this[Z].signal}get referrer(){if(this[Z].referrer===`no-referrer`)return``;if(this[Z].referrer===`client`)return`about:client`;if(this[Z].referrer)return this[Z].referrer.toString()}get referrerPolicy(){return this[Z].referrerPolicy}set referrerPolicy(e){this[Z].referrerPolicy=le(e)}clone(){return new e(this)}get[Symbol.toStringTag](){return`Request`}},Object.defineProperties($.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}}),he=e=>{let{parsedURL:t}=e[Z],n=new z(e[Z].headers);n.has(`Accept`)||n.set(`Accept`,`*/*`);let r=null;if(e.body===null&&/^(post|put)$/i.test(e.method)&&(r=`0`),e.body!==null){let t=F(e);typeof t==`number`&&!Number.isNaN(t)&&(r=String(t))}r&&n.set(`Content-Length`,r),e.referrerPolicy===``&&(e.referrerPolicy=X),e.referrer&&e.referrer!==`no-referrer`?e[Z].referrer=de(e):e[Z].referrer=`no-referrer`,e[Z].referrer instanceof URL&&n.set(`Referer`,e.referrer),n.has(`User-Agent`)||n.set(`User-Agent`,`node-fetch`),e.compress&&!n.has(`Accept-Encoding`)&&n.set(`Accept-Encoding`,`gzip, deflate, br`);let{agent:i}=e;typeof i==`function`&&(i=i(t));let a=K(t);return{parsedURL:t,options:{path:t.pathname+a,method:e.method,headers:n[Symbol.for(`nodejs.util.inspect.custom`)](),insecureHTTPParser:e.insecureHTTPParser,agent:i}}}})),_e,ve=e((()=>{b(),_e=class extends y{constructor(e,t=`aborted`){super(e,t)}}}));async function ye(e,t){return new Promise((n,r)=>{let i=new $(e,t),{parsedURL:a,options:o}=he(i);if(!xe.has(a.protocol))throw TypeError(`node-fetch cannot load ${e}. URL scheme "${a.protocol.replace(/:$/,``)}" is not supported.`);if(a.protocol===`data:`){let e=te(i.url);n(new G(e,{headers:{"Content-Type":e.typeFull}}));return}let s=(a.protocol===`https:`?ee:v).request,{signal:c}=i,l=null,p=()=>{let e=new _e(`The operation was aborted.`);r(e),i.body&&i.body instanceof u.Readable&&i.body.destroy(e),!(!l||!l.body)&&l.body.emit(`error`,e)};if(c&&c.aborted){p();return}let m=()=>{p(),_()},h=s(a.toString(),o);c&&c.addEventListener(`abort`,m);let _=()=>{h.abort(),c&&c.removeEventListener(`abort`,m)};h.on(`error`,e=>{r(new x(`request to ${i.url} failed, reason: ${e.message}`,`system`,e)),_()}),be(h,e=>{l&&l.body&&l.body.destroy(e)}),process.version<`v14`&&h.on(`socket`,e=>{let t;e.prependListener(`end`,()=>{t=e._eventsCount}),e.prependListener(`close`,n=>{if(l&&t<e._eventsCount&&!n){let e=Error(`Premature close`);e.code=`ERR_STREAM_PREMATURE_CLOSE`,l.body.emit(`error`,e)}})}),h.on(`response`,e=>{h.setTimeout(0);let a=oe(e.rawHeaders);if(H(e.statusCode)){let o=a.get(`Location`),s=null;try{s=o===null?null:new URL(o,i.url)}catch{if(i.redirect!==`manual`){r(new x(`uri requested responds with an invalid redirect URL: ${o}`,`invalid-redirect`)),_();return}}switch(i.redirect){case`error`:r(new x(`uri requested responds with a redirect, redirect mode is set to error: ${i.url}`,`no-redirect`)),_();return;case`manual`:break;case`follow`:{if(s===null)break;if(i.counter>=i.follow){r(new x(`maximum redirect reached at: ${i.url}`,`max-redirect`)),_();return}let o={headers:new z(i.headers),follow:i.follow,counter:i.counter+1,agent:i.agent,compress:i.compress,method:i.method,body:M(i),signal:i.signal,size:i.size,referrer:i.referrer,referrerPolicy:i.referrerPolicy};if(!E(i.url,s)||!ie(i.url,s))for(let e of[`authorization`,`www-authenticate`,`cookie`,`cookie2`])o.headers.delete(e);if(e.statusCode!==303&&i.body&&t.body instanceof u.Readable){r(new x(`Cannot follow redirect with body being a readable stream`,`unsupported-redirect`)),_();return}(e.statusCode===303||(e.statusCode===301||e.statusCode===302)&&i.method===`POST`)&&(o.method=`GET`,o.body=void 0,o.headers.delete(`content-length`));let c=fe(a);c&&(o.referrerPolicy=c),n(ye(new $(s,o))),_();return}default:return r(TypeError(`Redirect option '${i.redirect}' is not a valid value of RequestRedirect`))}}c&&e.once(`end`,()=>{c.removeEventListener(`abort`,m)});let o=f(e,new d,e=>{e&&r(e)});process.version<`v12.10`&&e.on(`aborted`,m);let s={url:i.url,status:e.statusCode,statusText:e.statusMessage,headers:a,size:i.size,counter:i.counter,highWaterMark:i.highWaterMark},p=a.get(`Content-Encoding`);if(!i.compress||i.method===`HEAD`||p===null||e.statusCode===204||e.statusCode===304){l=new G(o,s),n(l);return}let v={flush:g.Z_SYNC_FLUSH,finishFlush:g.Z_SYNC_FLUSH};if(p===`gzip`||p===`x-gzip`){o=f(o,g.createGunzip(v),e=>{e&&r(e)}),l=new G(o,s),n(l);return}if(p===`deflate`||p===`x-deflate`){let t=f(e,new d,e=>{e&&r(e)});t.once(`data`,e=>{o=(e[0]&15)==8?f(o,g.createInflate(),e=>{e&&r(e)}):f(o,g.createInflateRaw(),e=>{e&&r(e)}),l=new G(o,s),n(l)}),t.once(`end`,()=>{l||(l=new G(o,s),n(l))});return}if(p===`br`){o=f(o,g.createBrotliDecompress(),e=>{e&&r(e)}),l=new G(o,s),n(l);return}l=new G(o,s),n(l)}),ae(h,i).catch(r)})}function be(e,t){let n=l.from(`0\r
2
+ import{lt as e}from"./index.mjs";import{a as t,i as n,n as r,o as i,r as a,s as o,t as s}from"./from-py2TfO8m.mjs";import{format as c}from"node:url";import{Buffer as l}from"node:buffer";import u,{PassThrough as d,pipeline as f}from"node:stream";import{deprecate as p,promisify as m,types as h}from"node:util";import g from"node:zlib";import{isIP as _}from"node:net";import v from"node:http";import ee from"node:https";function te(e){if(!/^data:/i.test(e))throw TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');e=e.replace(/\r?\n/g,``);let t=e.indexOf(`,`);if(t===-1||t<=4)throw TypeError(`malformed data: URI`);let n=e.substring(5,t).split(`;`),r=``,i=!1,a=n[0]||`text/plain`,o=a;for(let e=1;e<n.length;e++)n[e]===`base64`?i=!0:n[e]&&(o+=`;${n[e]}`,n[e].indexOf(`charset=`)===0&&(r=n[e].substring(8)));!n[0]&&!r.length&&(o+=`;charset=US-ASCII`,r=`US-ASCII`);let s=i?`base64`:`ascii`,c=unescape(e.substring(t+1)),l=Buffer.from(c,s);return l.type=a,l.typeFull=o,l.charset=r,l}var ne=e((()=>{})),y,b=e((()=>{y=class extends Error{constructor(e,t){super(e),Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}})),x,re=e((()=>{b(),x=class extends y{constructor(e,t,n){super(e,t),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}}})),S,C,w,T,E,ie,D=e((()=>{S=Symbol.toStringTag,C=e=>typeof e==`object`&&typeof e.append==`function`&&typeof e.delete==`function`&&typeof e.get==`function`&&typeof e.getAll==`function`&&typeof e.has==`function`&&typeof e.set==`function`&&typeof e.sort==`function`&&e[S]===`URLSearchParams`,w=e=>e&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&typeof e.constructor==`function`&&/^(Blob|File)$/.test(e[S]),T=e=>typeof e==`object`&&(e[S]===`AbortSignal`||e[S]===`EventTarget`),E=(e,t)=>{let n=new URL(t).hostname,r=new URL(e).hostname;return n===r||n.endsWith(`.${r}`)},ie=(e,t)=>new URL(t).protocol===new URL(e).protocol}));async function O(e){if(e[A].disturbed)throw TypeError(`body used already for: ${e.url}`);if(e[A].disturbed=!0,e[A].error)throw e[A].error;let{body:t}=e;if(t===null||!(t instanceof u))return l.alloc(0);let n=[],r=0;try{for await(let i of t){if(e.size>0&&r+i.length>e.size){let n=new x(`content size at ${e.url} over limit: ${e.size}`,`max-size`);throw t.destroy(n),n}r+=i.length,n.push(i)}}catch(t){throw t instanceof y?t:new x(`Invalid response body while trying to fetch ${e.url}: ${t.message}`,`system`,t)}if(t.readableEnded===!0||t._readableState.ended===!0)try{return n.every(e=>typeof e==`string`)?l.from(n.join(``)):l.concat(n,r)}catch(t){throw new x(`Could not create Buffer from response body for ${e.url}: ${t.message}`,`system`,t)}else throw new x(`Premature close of server response while trying to fetch ${e.url}`)}var k,A,j,M,N,P,F,ae,I=e((()=>{o(),n(),re(),b(),D(),k=m(u.pipeline),A=Symbol(`Body internals`),j=class{constructor(e,{size:t=0}={}){let n=null;e===null?e=null:C(e)?e=l.from(e.toString()):w(e)||l.isBuffer(e)||(h.isAnyArrayBuffer(e)?e=l.from(e):ArrayBuffer.isView(e)?e=l.from(e.buffer,e.byteOffset,e.byteLength):e instanceof u||(e instanceof r?(e=a(e),n=e.type.split(`=`)[1]):e=l.from(String(e))));let i=e;l.isBuffer(e)?i=u.Readable.from(e):w(e)&&(i=u.Readable.from(e.stream())),this[A]={body:e,stream:i,boundary:n,disturbed:!1,error:null},this.size=t,e instanceof u&&e.on(`error`,e=>{let t=e instanceof y?e:new x(`Invalid response body while trying to fetch ${this.url}: ${e.message}`,`system`,e);this[A].error=t})}get body(){return this[A].stream}get bodyUsed(){return this[A].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:n}=await O(this);return e.slice(t,t+n)}async formData(){let e=this.headers.get(`content-type`);if(e.startsWith(`application/x-www-form-urlencoded`)){let e=new r,t=new URLSearchParams(await this.text());for(let[n,r]of t)e.append(n,r);return e}let{toFormData:t}=await import(`./multipart-parser-DX5ZDxQv.mjs`);return t(this.body,e)}async blob(){let e=this.headers&&this.headers.get(`content-type`)||this[A].body&&this[A].body.type||``;return new i([await this.arrayBuffer()],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await O(this);return new TextDecoder().decode(e)}buffer(){return O(this)}},j.prototype.buffer=p(j.prototype.buffer,`Please use 'response.arrayBuffer()' instead of 'response.buffer()'`,`node-fetch#buffer`),Object.defineProperties(j.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:p(()=>{},`data doesn't exist, use json(), text(), arrayBuffer(), or body instead`,`https://github.com/node-fetch/node-fetch/issues/1000 (response)`)}}),M=(e,t)=>{let n,r,{body:i}=e[A];if(e.bodyUsed)throw Error(`cannot clone body after it is used`);return i instanceof u&&typeof i.getBoundary!=`function`&&(n=new d({highWaterMark:t}),r=new d({highWaterMark:t}),i.pipe(n),i.pipe(r),e[A].stream=n,i=r),i},N=p(e=>e.getBoundary(),`form-data doesn't follow the spec and requires special treatment. Use alternative package`,`https://github.com/node-fetch/node-fetch/issues/1167`),P=(e,t)=>e===null?null:typeof e==`string`?`text/plain;charset=UTF-8`:C(e)?`application/x-www-form-urlencoded;charset=UTF-8`:w(e)?e.type||null:l.isBuffer(e)||h.isAnyArrayBuffer(e)||ArrayBuffer.isView(e)?null:e instanceof r?`multipart/form-data; boundary=${t[A].boundary}`:e&&typeof e.getBoundary==`function`?`multipart/form-data;boundary=${N(e)}`:e instanceof u?null:`text/plain;charset=UTF-8`,F=e=>{let{body:t}=e[A];return t===null?0:w(t)?t.size:l.isBuffer(t)?t.length:t&&typeof t.getLengthSync==`function`&&t.hasKnownLength&&t.hasKnownLength()?t.getLengthSync():null},ae=async(e,{body:t})=>{t===null?e.end():await k(t,e)}}));function oe(e=[]){return new z(e.reduce((e,t,n,r)=>(n%2==0&&e.push(r.slice(n,n+2)),e),[]).filter(([e,t])=>{try{return L(e),R(e,String(t)),!0}catch{return!1}}))}var L,R,z,B=e((()=>{L=typeof v.validateHeaderName==`function`?v.validateHeaderName:e=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(e)){let t=TypeError(`Header name must be a valid HTTP token [${e}]`);throw Object.defineProperty(t,`code`,{value:`ERR_INVALID_HTTP_TOKEN`}),t}},R=typeof v.validateHeaderValue==`function`?v.validateHeaderValue:(e,t)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(t)){let t=TypeError(`Invalid character in header content ["${e}"]`);throw Object.defineProperty(t,`code`,{value:`ERR_INVALID_CHAR`}),t}},z=class e extends URLSearchParams{constructor(t){let n=[];if(t instanceof e){let e=t.raw();for(let[t,r]of Object.entries(e))n.push(...r.map(e=>[t,e]))}else if(t!=null)if(typeof t==`object`&&!h.isBoxedPrimitive(t)){let e=t[Symbol.iterator];if(e==null)n.push(...Object.entries(t));else{if(typeof e!=`function`)throw TypeError(`Header pairs must be iterable`);n=[...t].map(e=>{if(typeof e!=`object`||h.isBoxedPrimitive(e))throw TypeError(`Each header pair must be an iterable object`);return[...e]}).map(e=>{if(e.length!==2)throw TypeError(`Each header pair must be a name/value tuple`);return[...e]})}}else throw TypeError(`Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)`);return n=n.length>0?n.map(([e,t])=>(L(e),R(e,String(t)),[String(e).toLowerCase(),String(t)])):void 0,super(n),new Proxy(this,{get(e,t,n){switch(t){case`append`:case`set`:return(n,r)=>(L(n),R(n,String(r)),URLSearchParams.prototype[t].call(e,String(n).toLowerCase(),String(r)));case`delete`:case`has`:case`getAll`:return n=>(L(n),URLSearchParams.prototype[t].call(e,String(n).toLowerCase()));case`keys`:return()=>(e.sort(),new Set(URLSearchParams.prototype.keys.call(e)).keys());default:return Reflect.get(e,t,n)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let t=this.getAll(e);if(t.length===0)return null;let n=t.join(`, `);return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}forEach(e,t=void 0){for(let n of this.keys())Reflect.apply(e,t,[this.get(n),n,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,t)=>(e[t]=this.getAll(t),e),{})}[Symbol.for(`nodejs.util.inspect.custom`)](){return[...this.keys()].reduce((e,t)=>{let n=this.getAll(t);return t===`host`?e[t]=n[0]:e[t]=n.length>1?n:n[0],e},{})}},Object.defineProperties(z.prototype,[`get`,`entries`,`forEach`,`values`].reduce((e,t)=>(e[t]={enumerable:!0},e),{}))})),V,H,U=e((()=>{V=new Set([301,302,303,307,308]),H=e=>V.has(e)})),W,G,se=e((()=>{B(),I(),U(),W=Symbol(`Response internals`),G=class e extends j{constructor(e=null,t={}){super(e,t);let n=t.status==null?200:t.status,r=new z(t.headers);if(e!==null&&!r.has(`Content-Type`)){let t=P(e,this);t&&r.append(`Content-Type`,t)}this[W]={type:`default`,url:t.url,status:n,statusText:t.statusText||``,headers:r,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[W].type}get url(){return this[W].url||``}get status(){return this[W].status}get ok(){return this[W].status>=200&&this[W].status<300}get redirected(){return this[W].counter>0}get statusText(){return this[W].statusText}get headers(){return this[W].headers}get highWaterMark(){return this[W].highWaterMark}clone(){return new e(M(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(t,n=302){if(!H(n))throw RangeError(`Failed to execute "redirect" on "response": Invalid status code`);return new e(null,{headers:{location:new URL(t).toString()},status:n})}static error(){let t=new e(null,{status:0,statusText:``});return t[W].type=`error`,t}static json(t=void 0,n={}){let r=JSON.stringify(t);if(r===void 0)throw TypeError(`data is not JSON serializable`);let i=new z(n&&n.headers);return i.has(`content-type`)||i.set(`content-type`,`application/json`),new e(r,{...n,headers:i})}get[Symbol.toStringTag](){return`Response`}},Object.defineProperties(G.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}})})),K,ce=e((()=>{K=e=>{if(e.search)return e.search;let t=e.href.length-1,n=e.hash||(e.href[t]===`#`?`#`:``);return e.href[t-n.length]===`?`?`?`:``}}));function q(e,t=!1){return e==null||(e=new URL(e),/^(about|blob|data):$/.test(e.protocol))?`no-referrer`:(e.username=``,e.password=``,e.hash=``,t&&(e.pathname=``,e.search=``),e)}function le(e){if(!Y.has(e))throw TypeError(`Invalid referrerPolicy: ${e}`);return e}function ue(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;let t=e.host.replace(/(^\[)|(]$)/g,``),n=_(t);return n===4&&/^127\./.test(t)||n===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(t)?!0:e.host===`localhost`||e.host.endsWith(`.localhost`)?!1:e.protocol===`file:`}function J(e){return/^about:(blank|srcdoc)$/.test(e)||e.protocol===`data:`||/^(blob|filesystem):$/.test(e.protocol)?!0:ue(e)}function de(e,{referrerURLCallback:t,referrerOriginCallback:n}={}){if(e.referrer===`no-referrer`||e.referrerPolicy===``)return null;let r=e.referrerPolicy;if(e.referrer===`about:client`)return`no-referrer`;let i=e.referrer,a=q(i),o=q(i,!0);a.toString().length>4096&&(a=o),t&&(a=t(a)),n&&(o=n(o));let s=new URL(e.url);switch(r){case`no-referrer`:return`no-referrer`;case`origin`:return o;case`unsafe-url`:return a;case`strict-origin`:return J(a)&&!J(s)?`no-referrer`:o.toString();case`strict-origin-when-cross-origin`:return a.origin===s.origin?a:J(a)&&!J(s)?`no-referrer`:o;case`same-origin`:return a.origin===s.origin?a:`no-referrer`;case`origin-when-cross-origin`:return a.origin===s.origin?a:o;case`no-referrer-when-downgrade`:return J(a)&&!J(s)?`no-referrer`:a;default:throw TypeError(`Invalid referrerPolicy: ${r}`)}}function fe(e){let t=(e.get(`referrer-policy`)||``).split(/[,\s]+/),n=``;for(let e of t)e&&Y.has(e)&&(n=e);return n}var Y,X,pe=e((()=>{Y=new Set([``,`no-referrer`,`no-referrer-when-downgrade`,`same-origin`,`origin`,`strict-origin`,`origin-when-cross-origin`,`strict-origin-when-cross-origin`,`unsafe-url`]),X=`strict-origin-when-cross-origin`})),Z,Q,me,$,he,ge=e((()=>{B(),I(),D(),ce(),pe(),Z=Symbol(`Request internals`),Q=e=>typeof e==`object`&&typeof e[Z]==`object`,me=p(()=>{},`.data is not a valid RequestInit property, use .body instead`,`https://github.com/node-fetch/node-fetch/issues/1000 (request)`),$=class e extends j{constructor(e,t={}){let n;if(Q(e)?n=new URL(e.url):(n=new URL(e),e={}),n.username!==``||n.password!==``)throw TypeError(`${n} is an url with embedded credentials.`);let r=t.method||e.method||`GET`;if(/^(delete|get|head|options|post|put)$/i.test(r)&&(r=r.toUpperCase()),!Q(t)&&`data`in t&&me(),(t.body!=null||Q(e)&&e.body!==null)&&(r===`GET`||r===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body`);let i=t.body?t.body:Q(e)&&e.body!==null?M(e):null;super(i,{size:t.size||e.size||0});let a=new z(t.headers||e.headers||{});if(i!==null&&!a.has(`Content-Type`)){let e=P(i,this);e&&a.set(`Content-Type`,e)}let o=Q(e)?e.signal:null;if(`signal`in t&&(o=t.signal),o!=null&&!T(o))throw TypeError(`Expected signal to be an instanceof AbortSignal or EventTarget`);let s=t.referrer==null?e.referrer:t.referrer;if(s===``)s=`no-referrer`;else if(s){let e=new URL(s);s=/^about:(\/\/)?client$/.test(e)?`client`:e}else s=void 0;this[Z]={method:r,redirect:t.redirect||e.redirect||`follow`,headers:a,parsedURL:n,signal:o,referrer:s},this.follow=t.follow===void 0?e.follow===void 0?20:e.follow:t.follow,this.compress=t.compress===void 0?e.compress===void 0?!0:e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||``}get method(){return this[Z].method}get url(){return c(this[Z].parsedURL)}get headers(){return this[Z].headers}get redirect(){return this[Z].redirect}get signal(){return this[Z].signal}get referrer(){if(this[Z].referrer===`no-referrer`)return``;if(this[Z].referrer===`client`)return`about:client`;if(this[Z].referrer)return this[Z].referrer.toString()}get referrerPolicy(){return this[Z].referrerPolicy}set referrerPolicy(e){this[Z].referrerPolicy=le(e)}clone(){return new e(this)}get[Symbol.toStringTag](){return`Request`}},Object.defineProperties($.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}}),he=e=>{let{parsedURL:t}=e[Z],n=new z(e[Z].headers);n.has(`Accept`)||n.set(`Accept`,`*/*`);let r=null;if(e.body===null&&/^(post|put)$/i.test(e.method)&&(r=`0`),e.body!==null){let t=F(e);typeof t==`number`&&!Number.isNaN(t)&&(r=String(t))}r&&n.set(`Content-Length`,r),e.referrerPolicy===``&&(e.referrerPolicy=X),e.referrer&&e.referrer!==`no-referrer`?e[Z].referrer=de(e):e[Z].referrer=`no-referrer`,e[Z].referrer instanceof URL&&n.set(`Referer`,e.referrer),n.has(`User-Agent`)||n.set(`User-Agent`,`node-fetch`),e.compress&&!n.has(`Accept-Encoding`)&&n.set(`Accept-Encoding`,`gzip, deflate, br`);let{agent:i}=e;typeof i==`function`&&(i=i(t));let a=K(t);return{parsedURL:t,options:{path:t.pathname+a,method:e.method,headers:n[Symbol.for(`nodejs.util.inspect.custom`)](),insecureHTTPParser:e.insecureHTTPParser,agent:i}}}})),_e,ve=e((()=>{b(),_e=class extends y{constructor(e,t=`aborted`){super(e,t)}}}));async function ye(e,t){return new Promise((n,r)=>{let i=new $(e,t),{parsedURL:a,options:o}=he(i);if(!xe.has(a.protocol))throw TypeError(`node-fetch cannot load ${e}. URL scheme "${a.protocol.replace(/:$/,``)}" is not supported.`);if(a.protocol===`data:`){let e=te(i.url);n(new G(e,{headers:{"Content-Type":e.typeFull}}));return}let s=(a.protocol===`https:`?ee:v).request,{signal:c}=i,l=null,p=()=>{let e=new _e(`The operation was aborted.`);r(e),i.body&&i.body instanceof u.Readable&&i.body.destroy(e),!(!l||!l.body)&&l.body.emit(`error`,e)};if(c&&c.aborted){p();return}let m=()=>{p(),_()},h=s(a.toString(),o);c&&c.addEventListener(`abort`,m);let _=()=>{h.abort(),c&&c.removeEventListener(`abort`,m)};h.on(`error`,e=>{r(new x(`request to ${i.url} failed, reason: ${e.message}`,`system`,e)),_()}),be(h,e=>{l&&l.body&&l.body.destroy(e)}),process.version<`v14`&&h.on(`socket`,e=>{let t;e.prependListener(`end`,()=>{t=e._eventsCount}),e.prependListener(`close`,n=>{if(l&&t<e._eventsCount&&!n){let e=Error(`Premature close`);e.code=`ERR_STREAM_PREMATURE_CLOSE`,l.body.emit(`error`,e)}})}),h.on(`response`,e=>{h.setTimeout(0);let a=oe(e.rawHeaders);if(H(e.statusCode)){let o=a.get(`Location`),s=null;try{s=o===null?null:new URL(o,i.url)}catch{if(i.redirect!==`manual`){r(new x(`uri requested responds with an invalid redirect URL: ${o}`,`invalid-redirect`)),_();return}}switch(i.redirect){case`error`:r(new x(`uri requested responds with a redirect, redirect mode is set to error: ${i.url}`,`no-redirect`)),_();return;case`manual`:break;case`follow`:{if(s===null)break;if(i.counter>=i.follow){r(new x(`maximum redirect reached at: ${i.url}`,`max-redirect`)),_();return}let o={headers:new z(i.headers),follow:i.follow,counter:i.counter+1,agent:i.agent,compress:i.compress,method:i.method,body:M(i),signal:i.signal,size:i.size,referrer:i.referrer,referrerPolicy:i.referrerPolicy};if(!E(i.url,s)||!ie(i.url,s))for(let e of[`authorization`,`www-authenticate`,`cookie`,`cookie2`])o.headers.delete(e);if(e.statusCode!==303&&i.body&&t.body instanceof u.Readable){r(new x(`Cannot follow redirect with body being a readable stream`,`unsupported-redirect`)),_();return}(e.statusCode===303||(e.statusCode===301||e.statusCode===302)&&i.method===`POST`)&&(o.method=`GET`,o.body=void 0,o.headers.delete(`content-length`));let c=fe(a);c&&(o.referrerPolicy=c),n(ye(new $(s,o))),_();return}default:return r(TypeError(`Redirect option '${i.redirect}' is not a valid value of RequestRedirect`))}}c&&e.once(`end`,()=>{c.removeEventListener(`abort`,m)});let o=f(e,new d,e=>{e&&r(e)});process.version<`v12.10`&&e.on(`aborted`,m);let s={url:i.url,status:e.statusCode,statusText:e.statusMessage,headers:a,size:i.size,counter:i.counter,highWaterMark:i.highWaterMark},p=a.get(`Content-Encoding`);if(!i.compress||i.method===`HEAD`||p===null||e.statusCode===204||e.statusCode===304){l=new G(o,s),n(l);return}let v={flush:g.Z_SYNC_FLUSH,finishFlush:g.Z_SYNC_FLUSH};if(p===`gzip`||p===`x-gzip`){o=f(o,g.createGunzip(v),e=>{e&&r(e)}),l=new G(o,s),n(l);return}if(p===`deflate`||p===`x-deflate`){let t=f(e,new d,e=>{e&&r(e)});t.once(`data`,e=>{o=(e[0]&15)==8?f(o,g.createInflate(),e=>{e&&r(e)}):f(o,g.createInflateRaw(),e=>{e&&r(e)}),l=new G(o,s),n(l)}),t.once(`end`,()=>{l||(l=new G(o,s),n(l))});return}if(p===`br`){o=f(o,g.createBrotliDecompress(),e=>{e&&r(e)}),l=new G(o,s),n(l);return}l=new G(o,s),n(l)}),ae(h,i).catch(r)})}function be(e,t){let n=l.from(`0\r
3
3
  \r
4
4
  `),r=!1,i=!1,a;e.on(`response`,e=>{let{headers:t}=e;r=t[`transfer-encoding`]===`chunked`&&!t[`content-length`]}),e.on(`socket`,o=>{let s=()=>{if(r&&!i){let e=Error(`Premature close`);e.code=`ERR_STREAM_PREMATURE_CLOSE`,t(e)}},c=e=>{i=l.compare(e.slice(-5),n)===0,!i&&a&&(i=l.compare(a.slice(-3),n.slice(0,3))===0&&l.compare(e.slice(-2),n.slice(3))===0),a=e};o.prependListener(`close`,s),o.on(`data`,c),e.on(`close`,()=>{o.removeListener(`close`,s),o.removeListener(`data`,c)})})}var xe;e((()=>{ne(),I(),se(),B(),ge(),re(),ve(),U(),n(),D(),pe(),s(),xe=new Set([`data:`,`http:`,`https:`])}))();export{ye as default};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ function e(){return typeof process>`u`||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.(`node:os`)??null}const t=e();function n(){return t?`pi (${t.platform()} ${t.release()}; ${t.arch()})`:`pi (browser)`}var r=class extends Error{};const i=[`$ref`,`$defs`,`definitions`,`allOf`,`oneOf`,`patternProperties`,`dependentSchemas`,`dependencies`,`unevaluatedProperties`,`propertyNames`,`contains`,`prefixItems`,`not`,`if`,`then`,`else`];function a(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function o(e){if(!a(e))return!1;let t=typeof e.type==`string`?[e.type]:Array.isArray(e.type)?e.type:[];return t.includes(`object`)||t.includes(`array`)||e.properties!==void 0||e.items!==void 0}function s(e){return a(e)?e.type===`null`||Array.isArray(e.type)&&e.type.includes(`null`)||e.const===null||Array.isArray(e.enum)&&e.enum.includes(null)?!0:Array.isArray(e.anyOf)&&e.anyOf.some(e=>s(e)):!1}function c(e){if(!a(e))throw new r(`boolean schemas are unsupported`);for(let t of i)if(e[t]!==void 0)throw new r(`${t} schemas are unsupported`);if(e.anyOf!==void 0){if(!Array.isArray(e.anyOf)||e.anyOf.length===0)throw new r(`anyOf must contain at least one schema`);for(let t of e.anyOf){if(o(t))throw new r(`object and array unions are unsupported`);c(t)}}if(e.items!==void 0){if(Array.isArray(e.items))throw new r(`tuple schemas are unsupported`);c(e.items)}let t=e.type===`object`;if(e.properties!==void 0&&!t)throw new r(`properties require type object`);if(!t)return;if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new r(`schema-valued or true additionalProperties is unsupported`);if(e.properties!==void 0&&!a(e.properties))throw new r(`object properties must be a schema map`);if(e.required!==void 0&&(!Array.isArray(e.required)||e.required.some(e=>typeof e!=`string`)))throw new r(`object required must be a string array`);let n=e.properties??{},l=Object.keys(n),u=new Set(Array.isArray(e.required)?e.required:[]);if([...u].some(e=>!l.includes(e)))throw new r(`required contains an unknown property`);for(let[e,t]of Object.entries(n))c(t),!u.has(e)&&!s(t)&&(n[e]={anyOf:[t,{type:`null`}]});e.required=l,e.additionalProperties=!1}function l(e){let t=structuredClone(e);if(!a(t)||(c(t),t.type!==`object`))throw new r(`root schema must have type object`);return t}function u(e,t){return t===!0?l(e.parameters):e.parameters}function d(e,t,n){let r=t[n];if(typeof r!=`string`)throw Error(`Grammar tool call "${e}" requires argument "${n}" to be a string.`);return r}function f(e,t,n,r){if(e.closed){if(r&&n===e.input)return;throw Error(`grammar tool input for property "${t}" changed after it was closed`)}if(!n.startsWith(e.input))throw Error(`grammar tool input for property "${t}" changed non-monotonically`);let i=n.slice(e.input.length);if(!r&&i.length===0)return;let a=``;return e.started||=(a+=`{${JSON.stringify(t)}:"`,!0),a+=JSON.stringify(i).slice(1,-1),e.input=n,r&&(a+=`"}`,e.closed=!0),a}function p(e){let t=e.parameters;if(t.type!==`object`)throw Error(`grammar constrained sampling requires an object parameter schema`);if(!Array.isArray(t.required)||t.required.length!==1||typeof t.required[0]!=`string`)throw Error(`grammar constrained sampling requires exactly one required string property`);let n=t.required[0];if(!t.properties?.[n])throw Error(`grammar constrained sampling requires a properties entry for ${n}`);if(t.properties[n]?.type!==`string`)throw Error(`grammar constrained sampling property ${n} must have type string`);return n}function m(e,t){let n=e.constrainedSampling;if(!(!n||n.type!==`json_schema`)){if(t)try{return l(e.parameters),!0}catch(t){if(!(t instanceof r))throw t;if(n.strict!==`require`)return;throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but ${t.message}.`)}if(n.strict===`require`)throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function h(e,t){let n=e.constrainedSampling;if(!n||n.type!==`grammar`||!t)return;let r=n.variants.openai_lark,i=n.variants.openai_regex,a=typeof r==`string`&&r.trim().length>0,o=typeof i==`string`&&i.trim().length>0;if(!a&&!o)throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:a?`lark`:`regex`,definition:a?r:i,inputProperty:p(e)}}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${n}.`)}}function g(e,t){let n=new Map;for(let r of e??[]){let e=h(r,t);e&&n.set(r.name,e.inputProperty)}return n}function _(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function v(e){try{return JSON.stringify(e)??`undefined`}catch{return`[unserializable]`}}function y(e){if(typeof e==`string`)return e.length;let t=0;for(let n of e)t+=n.type===`text`?n.text.length:4800;return t}function b(e){return Math.ceil(e.length/4)}function x(e){return Math.ceil(y(e)/4)}function S(e){let t=0;if(e.role===`user`||e.role===`toolResult`)return x(e.content);for(let n of e.content)n.type===`text`?t+=n.text.length:n.type===`thinking`?t+=n.thinking.length:t+=n.name.length+v(n.arguments).length;return Math.ceil(t/4)}function C(e){let t=-1/0,n;for(let r=0;r<e.length;r++){let i=e[r];if(i.role===`assistant`){let e=i;e.timestamp>=t&&e.stopReason!==`aborted`&&e.stopReason!==`error`&&_(e.usage)>0&&(n={usage:e.usage,index:r})}t=Math.max(t,i.timestamp)}return n}function w(e){let t=C(e);if(t){let n=_(t.usage),r=0;for(let n=t.index+1;n<e.length;n++)r+=S(e[n]);return{tokens:n+r,usageTokens:n,trailingTokens:r,lastUsageIndex:t.index}}let n=0;for(let t of e)n+=S(t);return{tokens:n,usageTokens:0,trailingTokens:n,lastUsageIndex:null}}function T(e){return!e||e.length===0?0:b(v(e))}function E(e){return Array.isArray(e)}function D(e){if(E(e))return w(e);let t=w(e.messages);if(t.lastUsageIndex!==null){let n=new Set(e.messages.slice(t.lastUsageIndex+1).filter(e=>e.role===`toolResult`).flatMap(e=>e.addedToolNames??[])),r=T(e.tools?.filter(e=>n.has(e.name)));return{tokens:t.tokens+r,usageTokens:t.usageTokens,trailingTokens:t.trailingTokens+r,lastUsageIndex:t.lastUsageIndex}}let n=(e.systemPrompt?b(e.systemPrompt):0)+T(e.tools);return{tokens:t.tokens+n,usageTokens:t.usageTokens,trailingTokens:t.trailingTokens+n,lastUsageIndex:t.lastUsageIndex}}function O(e,t,n){if(e.contextWindow<=0)return Math.max(1,n);let r=e.contextWindow-D(t).tokens-4096;return Math.min(n,Math.max(1,r))}function k(e,t,n,r){let i=e.samplingParams||n?.samplingParams?{...e.samplingParams,...n?.samplingParams}:void 0;return{temperature:n?.temperature,samplingParams:i,maxTokens:O(e,t,n?.maxTokens??e.maxTokens),signal:n?.signal,telemetryContext:n?.telemetryContext,apiKey:r||n?.apiKey,fetch:n?.fetch,transport:n?.transport,cacheRetention:n?.cacheRetention,sessionId:n?.sessionId,headers:n?.headers,onPayload:n?.onPayload,onResponse:n?.onResponse,timeoutMs:n?.timeoutMs,websocketConnectTimeoutMs:n?.websocketConnectTimeoutMs,maxRetries:n?.maxRetries,maxRetryDelayMs:n?.maxRetryDelayMs,metadata:n?.metadata,env:n?.env}}const A={minimal:1024,low:2048,medium:8192,high:16384};function j(e){return e===`xhigh`||e===`max`?`high`:e}function M(e,t){return{...A,...t}[j(e)]}function N(e,t){return Math.min(e,Math.max(0,t-1024))}function P(e,t,n,r){let i=M(n,r),a=e===void 0?t:Math.min(e+i,t);return a<=i&&(i=N(i,a)),{maxTokens:a,thinkingBudget:i}}function F(e,t){let n=[],r=!1;for(let i of e){if(i.type===`image`){r||n.push({type:`text`,text:t}),r=!0;continue}n.push(i),r=i.text===t}return n}function I(e,t){return t.input.includes(`image`)?e:e.map(e=>e.role===`user`&&Array.isArray(e.content)?{...e,content:F(e.content,`(image omitted: model does not support images)`)}:e.role===`toolResult`?{...e,content:F(e.content,`(tool image omitted: model does not support images)`)}:e)}function L(e,t,n){let r=new Map,i=I(e.map(e=>e.content==null?{...e,content:[]}:e),t).map(e=>{if(e.role===`user`)return e;if(e.role===`toolResult`){let t=r.get(e.toolCallId);return t&&t!==e.toolCallId?{...e,toolCallId:t}:e}if(e.role===`assistant`){let i=e,a=i.provider===t.provider&&i.api===t.api&&i.model===t.id,o=i.content.flatMap(e=>{if(e.type===`thinking`)return e.redacted?a?e:[]:a&&e.thinkingSignature?e:!e.thinking||e.thinking.trim()===``?[]:a?e:{type:`text`,text:e.thinking};if(e.type===`text`)return a?e:{type:`text`,text:e.text};if(e.type===`toolCall`){let o=e,s=o;if(!a&&o.thoughtSignature&&(s={...o},delete s.thoughtSignature),!a&&n){let e=n(o.id,t,i);e!==o.id&&(r.set(o.id,e),s={...s,id:e})}return s}return e});return{...i,content:o}}return e}),a=[],o=[],s=new Set,c=()=>{if(o.length>0){for(let e of o)s.has(e.id)||a.push({role:`toolResult`,toolCallId:e.id,toolName:e.name,content:[{type:`text`,text:`No result provided`}],isError:!0,timestamp:Date.now()});o=[],s=new Set}};for(let e=0;e<i.length;e++){let t=i[e];if(t.role===`assistant`){c();let e=t;if(e.stopReason===`error`||e.stopReason===`aborted`)continue;let n=e.content.filter(e=>e.type===`toolCall`);n.length>0&&(o=n,s=new Set),a.push(t)}else t.role===`toolResult`?(s.add(t.toolCallId),a.push(t)):(t.role===`user`&&c(),a.push(t))}return c(),a}export{N as a,g as c,h as d,m as f,O as i,d as l,P as n,M as o,n as p,k as r,f as s,L as t,u};