import{O as w}from"./client-Sq9UPDIz.js";import{g as h}from"./env-api-keys.browser-DGvvjVWg.js";import{A as y,a as _}from"./index-3wjvth7D.js";import{h as A}from"./headers-CgnjaPPL.js";import{h as I,b,i as O,r as P}from"./github-copilot-headers-CVWOSrQr.js";import{p as S,c as T,a as C}from"./openai-responses-shared-BucGzOCO.js";import{b as k}from"./transform-messages-B_np3yTy.js";import"./vendor-katex-6s3QXDY8.js";import"./vendor-pdfjs-9liOkivS.js";import"./vendor-automerge-Dpota_ma.js";import"./vendor-socket-BkL6vOXg.js";import"./hash-Cxk8sEP2.js";import"./json-parse-DUjbyQwB.js";import"./sanitize-unicode-B62XMGgN.js";var u={};const L=new Set(["openai","openai-codex","opencode"]);function g(e){return e||(typeof process<"u"&&u.PI_CACHE_RETENTION==="long"?"long":"short")}function m(e){return{sendSessionIdHeader:e.compat?.sendSessionIdHeader??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0}}function M(e,n){return n==="long"&&e.supportsLongCacheRetention?"24h":void 0}const N=(e,n,r)=>{const t=new y;return(async()=>{const a={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:"stop",timestamp:Date.now()};try{const o=r?.apiKey||h(e.provider)||"",i=g(r?.cacheRetention)==="none"?void 0:r?.sessionId,p=x(e,n,o,r?.headers,i);let c=H(e,n,r);const f=await r?.onPayload?.(c,e);f!==void 0&&(c=f);const l={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs!==void 0?{timeout:r.timeoutMs}:{},...r?.maxRetries!==void 0?{maxRetries:r.maxRetries}:{}},{data:v,response:d}=await p.responses.create(c,l).withResponse();if(await r?.onResponse?.({status:d.status,headers:A(d.headers)},e),t.push({type:"start",partial:a}),await S(v,a,t,e,{serviceTier:r?.serviceTier,applyServiceTierPricing:(R,E)=>q(R,E,e)}),r?.signal?.aborted)throw new Error("Request was aborted");if(a.stopReason==="aborted"||a.stopReason==="error")throw new Error("An unknown error occurred");t.push({type:"done",reason:a.stopReason,message:a}),t.end()}catch(o){for(const s of a.content)delete s.index,delete s.partialJson;a.stopReason=r?.signal?.aborted?"aborted":"error",a.errorMessage=o instanceof Error?o.message:JSON.stringify(o),t.push({type:"error",reason:a.stopReason,error:a}),t.end()}})(),t},Z=(e,n,r)=>{const t=r?.apiKey||h(e.provider);if(!t)throw new Error(`No API key for provider: ${e.provider}`);const a=k(e,r,t),o=r?.reasoning?_(e,r.reasoning):void 0;return N(e,n,{...a,reasoningEffort:o==="off"?void 0:o})};function x(e,n,r,t,a){if(!r){if(!u.OPENAI_API_KEY)throw new Error("OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.");r=u.OPENAI_API_KEY}const o=m(e),s={...e.headers};if(e.provider==="github-copilot"){const p=I(n.messages),c=b({messages:n.messages,hasImages:p});Object.assign(s,c)}a&&(o.sendSessionIdHeader&&(s.session_id=a),s["x-client-request-id"]=a),t&&Object.assign(s,t);const i=e.provider==="cloudflare-ai-gateway"?{...s,Authorization:s.Authorization??null,"cf-aig-authorization":`Bearer ${r}`}:s;return new w({apiKey:r,baseURL:O(e.provider)?P(e):e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function H(e,n,r){const t=T(e,n,L),a=g(r?.cacheRetention),o=m(e),s={model:e.id,input:t,stream:!0,prompt_cache_key:a==="none"?void 0:r?.sessionId,prompt_cache_retention:M(o,a),store:!1};if(r?.maxTokens&&(s.max_output_tokens=r?.maxTokens),r?.temperature!==void 0&&(s.temperature=r?.temperature),r?.serviceTier!==void 0&&(s.service_tier=r.serviceTier),n.tools&&n.tools.length>0&&(s.tools=C(n.tools)),e.reasoning)if(r?.reasoningEffort||r?.reasoningSummary){const i=r?.reasoningEffort?e.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort:"medium";s.reasoning={effort:i,summary:r?.reasoningSummary||"auto"},s.include=["reasoning.encrypted_content"]}else e.provider!=="github-copilot"&&e.thinkingLevelMap?.off!==null&&(s.reasoning={effort:e.thinkingLevelMap?.off??"none"});return s}function K(e,n){switch(n){case"flex":return .5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function q(e,n,r){const t=K(r,n);t!==1&&(e.cost.input*=t,e.cost.output*=t,e.cost.cacheRead*=t,e.cost.cacheWrite*=t,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}export{N as streamOpenAIResponses,Z as streamSimpleOpenAIResponses};
