sliccy 5.31.3 → 5.31.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.
- package/dist/ui/assets/{account-store-SL9GSzVk.js → account-store-Bk7BU4R2.js} +2 -2
- package/dist/ui/assets/account-store-CWYCPgAg.js +103 -0
- package/dist/ui/assets/adobe-b9KONAKs.js +2 -0
- package/dist/ui/assets/{adobe-oauth-state-X5E5a44s.js → adobe-oauth-state-mA3vu6Bf.js} +1 -1
- package/dist/ui/assets/adobe-xFuU2zCa.js +1 -0
- package/dist/ui/assets/{agent-message-to-chat-C1C-ZYPB.js → agent-message-to-chat-D7tDL1mh.js} +1 -1
- package/dist/ui/assets/anthropic-messages-DP3-Xd3J.js +39 -0
- package/dist/ui/assets/{anthropic-LjoeX6v-.js → anthropic-messages-DSmP2_-Q.js} +6 -6
- package/dist/ui/assets/{apps-BQ_qFSmZ.js → apps-DjoNkGOL.js} +1 -1
- package/dist/ui/assets/azure-openai-DbeGNEJJ.js +1 -0
- package/dist/ui/assets/{azure-openai-g-MISqMy.js → azure-openai-r8cj7flx.js} +1 -1
- package/dist/ui/assets/azure-openai-responses-CEEm6_Xn.js +1 -0
- package/dist/ui/assets/azure-openai-responses-YO8iO-Ch.js +1 -0
- package/dist/ui/assets/bedrock-camp-DVKDCEuf.js +1 -0
- package/dist/ui/assets/bedrock-camp-DbZ6Mjym.js +1 -0
- package/dist/ui/assets/cerebras-DHXm2Opl.js +1 -0
- package/dist/ui/assets/cerebras-DSz7FIO_.js +1 -0
- package/dist/ui/assets/compat-DADQxxLV.js +2 -0
- package/dist/ui/assets/completionchunk-B2eUYPOo.js +40 -0
- package/dist/ui/assets/completionchunk-BsT4qCtf.js +40 -0
- package/dist/ui/assets/{connect-surface-C37aNu3W.js → connect-surface-Ce0cz8Sc.js} +1 -1
- package/dist/ui/assets/{context-compaction-DvlXtgVG.js → context-compaction-DaxQExZG.js} +1 -1
- package/dist/ui/assets/dip-7kvHeBSg.js +1 -0
- package/dist/ui/assets/{dist-Z_lsorao.js → dist-Bp_iacBp.js} +1 -1
- package/dist/ui/assets/{dist-Crm-xEtc.js → dist-ClXA2s8_.js} +1 -1
- package/dist/ui/assets/{ensure-speech-assets-C16fjyEc.js → ensure-speech-assets-CBkFedDM.js} +1 -1
- package/dist/ui/assets/esp8266-BuqxV-Rf.js +1 -0
- package/dist/ui/assets/{esptool-operations-DS77K1xA.js → esptool-operations-Dyb_KlG3.js} +2 -2
- package/dist/ui/assets/{fs-CJe7ORQQ.js → fs-CtR0lVGQ.js} +1 -1
- package/dist/ui/assets/{fs-4jha6tKU.js → fs-Cza4C_VI.js} +2 -2
- package/dist/ui/assets/{github-bHdfOCia.js → github-CyuBASDb.js} +2 -2
- package/dist/ui/assets/{github-B7MJQ6o8.js → github-D6l0k87E.js} +1 -1
- package/dist/ui/assets/github-copilot-BxtkvNkA.js +2 -0
- package/dist/ui/assets/github-copilot-CgxdBB7O.js +1 -0
- package/dist/ui/assets/github-copilot-headers-DRgtIyTm.js +1 -0
- package/dist/ui/assets/google-generative-ai-Cz3VHJVe.js +1 -0
- package/dist/ui/assets/google-generative-ai-DRLjqQHr.js +1 -0
- package/dist/ui/assets/{google-shared-CwjAeP6N.js → google-shared-0Fg2dFO2.js} +1 -1
- package/dist/ui/assets/{google-shared-CFmFmYdk.js → google-shared-mehyRjje.js} +1 -1
- package/dist/ui/assets/google-vertex-C8F4Q-3-.js +1 -0
- package/dist/ui/assets/google-vertex-DI_ybVGc.js +1 -0
- package/dist/ui/assets/headers-CbDaTl3c.js +1 -0
- package/dist/ui/assets/{hear-DVfG4tMB.js → hear-DPr4m8os.js} +1 -1
- package/dist/ui/assets/{kernel-worker-DU_V0U3r.js → kernel-worker-DZdJjW09.js} +1193 -1193
- package/dist/ui/assets/{kokoro-engine-BCF6RB67.js → kokoro-engine-DtX15dky.js} +1 -1
- package/dist/ui/assets/{lick-ws-bridge-CWz8ua2f.js → lick-ws-bridge-DW_om-XF.js} +1 -1
- package/dist/ui/assets/{lick-ws-bridge-Bw7A25PO.js → lick-ws-bridge-F1bk9Ndr.js} +1 -1
- package/dist/ui/assets/{local-llm-CUYHWkoy.js → local-llm-BUh467MT.js} +2 -2
- package/dist/ui/assets/main-DVF1KaMV.js +24 -0
- package/dist/ui/assets/mistral-conversations-BD1LHG49.js +8 -0
- package/dist/ui/assets/mistral-conversations-CoropYyn.js +7 -0
- package/dist/ui/assets/models-ByRUWfA-.js +1 -0
- package/dist/ui/assets/{mount-COvarpEy.js → mount-BJAgT6cd.js} +2 -2
- package/dist/ui/assets/{mount-DhKiCtt7.js → mount-CAEbJLup.js} +1 -1
- package/dist/ui/assets/{new-session-COz75sHo.js → new-session-DuIKoj8h.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-BRe2dg9j.js → oauth-bootstrap-C1t3F5l9.js} +2 -2
- package/dist/ui/assets/{openai-codex-Bg862N5_.js → openai-codex-7a3yMxhL.js} +1 -1
- package/dist/ui/assets/openai-codex-BNJ1y0s8.js +1 -0
- package/dist/ui/assets/openai-codex-responses-DUWTsNB0.js +7 -0
- package/dist/ui/assets/openai-codex-responses-DcE8b3Us.js +7 -0
- package/dist/ui/assets/openai-completions-2m5htnw8.js +5 -0
- package/dist/ui/assets/openai-completions-CPxuOo6h.js +5 -0
- package/dist/ui/assets/openai-responses-BIaF8Olv.js +1 -0
- package/dist/ui/assets/openai-responses-D3YJWUR5.js +1 -0
- package/dist/ui/assets/openai-responses-shared-1KvKQf-4.js +12 -0
- package/dist/ui/assets/openai-responses-shared-CEQMR7Nx.js +12 -0
- package/dist/ui/assets/openrouter-images-CHaqAs_0.js +1 -0
- package/dist/ui/assets/openrouter-images-CIagBWVL.js +1 -0
- package/dist/ui/assets/otel-BvlmHUjk.js +3 -0
- package/dist/ui/assets/otel-CCT7TRJr.js +3 -0
- package/dist/ui/assets/{page-follower-tray-CKjmGVTI.js → page-follower-tray-wxp2UQxg.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-DV_SVK7O.js → panel-rpc-handlers-CfN2Vxm8.js} +2 -2
- package/dist/ui/assets/{provider-C1MeNgf6.js → provider-CDfndD9E.js} +2 -2
- package/dist/ui/assets/{provider-CH9Vg0CP.js → provider-CYVtAuph.js} +1 -1
- package/dist/ui/assets/provider-env-D37PhSJu.js +1 -0
- package/dist/ui/assets/provider-env-DwY8YuMk.js +1 -0
- package/dist/ui/assets/provider-store-access-BCxDzrP_.js +1 -0
- package/dist/ui/assets/provider-store-access-C0J_PJos.js +1 -0
- package/dist/ui/assets/providers-BrRzKc33.js +2 -0
- package/dist/ui/assets/{providers-DTc9cavg.js → providers-CzILNNm-.js} +1 -1
- package/dist/ui/assets/quick-llm-C3DL1kkz.js +1 -0
- package/dist/ui/assets/session-freezer-BAlnZq3r.js +1 -0
- package/dist/ui/assets/{speak-qQJqxyY_.js → speak-BvV9R1Ep.js} +1 -1
- package/dist/ui/assets/{sprinkle-manager-DqB-1sMP.js → sprinkle-manager-WFdDIrH2.js} +1 -1
- package/dist/ui/assets/{sprinkle-renderer-Bc0oWiBK.js → sprinkle-renderer-Bd0WVTH3.js} +1 -1
- package/dist/ui/assets/{store-CQZC3J0e.js → store-DYEVj3Mn.js} +1 -1
- package/dist/ui/assets/{sudo-DDua5CDS.js → sudo-Dov5vvU-.js} +1 -1
- package/dist/ui/assets/transform-messages-CQuDksPz.js +1 -0
- package/dist/ui/assets/transform-messages-D7OsqBmU.js +1 -0
- package/dist/ui/assets/{transformers-env-Bd5uUAET.js → transformers-env-DtlYTSDz.js} +1 -1
- package/dist/ui/assets/{tray-leader-tUG5SYx1.js → tray-leader-DYLxucjO.js} +1 -1
- package/dist/ui/assets/{tray-leave-runtime-DFSM2v0u.js → tray-leave-runtime-bo512Gb_.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-SjHrqVRd.js → upgrade-detection-ssTKZKw3.js} +1 -1
- package/dist/ui/assets/{voice-reply-Cfv2GJPY.js → voice-reply-C7IdeZWx.js} +1 -1
- package/dist/ui/assets/{wc-attach-BLShAwZU.js → wc-attach-DqUMF3SN.js} +2 -2
- package/dist/ui/assets/wc-extension-C4v5cPUY.js +2 -0
- package/dist/ui/assets/{wc-follower-DcPEJsCg.js → wc-follower-Crqux2kQ.js} +3 -3
- package/dist/ui/assets/wc-live-DQFQdors.js +258 -0
- package/dist/ui/assets/{wc-nav-BipzeLE6.js → wc-nav-CaLNkUtj.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-CcG_XrLd.js → wc-onboarding-Dl79TUXT.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-BYxtEGbt.js → wc-placeholder-CbKpW6j0.js} +3 -3
- package/dist/ui/assets/{wc-settings-CdRw8sxH.js → wc-settings-BCItZ-R5.js} +2 -2
- package/dist/ui/assets/{wc-shell-CrTQtlJQ.js → wc-shell-BPSFQuzD.js} +4 -4
- package/dist/ui/assets/{wc-sprinkles-CiD8jtkB.js → wc-sprinkles-DFSkoMFZ.js} +2 -2
- package/dist/ui/assets/{wc-tray-CSrI5SrA.js → wc-tray-CB5grpTa.js} +2 -2
- package/dist/ui/assets/{whisper-engine-6ZaZ9EaS.js → whisper-engine-CDLEuuEq.js} +1 -1
- package/dist/ui/assets/xai-grok-BHUG3fUE.js +1 -0
- package/dist/ui/assets/{xai-grok-Bjh8Mg84.js → xai-grok-CwvM0E_f.js} +1 -1
- package/dist/ui/index.html +9 -9
- package/dist/ui/packages/webapp/index.html +9 -9
- package/package.json +2 -2
- package/dist/ui/assets/account-store-BSEcudvg.js +0 -99
- package/dist/ui/assets/adobe-DbSSf4Ld.js +0 -1
- package/dist/ui/assets/adobe-SNd1IfRO.js +0 -2
- package/dist/ui/assets/anthropic-BOEkIcb-.js +0 -39
- package/dist/ui/assets/azure-openai-C4FPpKAs.js +0 -1
- package/dist/ui/assets/azure-openai-responses-CbJrQGi8.js +0 -1
- package/dist/ui/assets/azure-openai-responses-DPSrcT4o.js +0 -1
- package/dist/ui/assets/bedrock-camp-DjKgax8m.js +0 -1
- package/dist/ui/assets/bedrock-camp-DlP7CPgV.js +0 -5
- package/dist/ui/assets/cerebras-D2PjlO7P.js +0 -1
- package/dist/ui/assets/cerebras-zumaaXYF.js +0 -1
- package/dist/ui/assets/diagnostics-DRDFDs4d.js +0 -1
- package/dist/ui/assets/diagnostics-mI-AnKx_.js +0 -1
- package/dist/ui/assets/dip-CZO83CmG.js +0 -1
- package/dist/ui/assets/dist-D69OmKNn.js +0 -4
- package/dist/ui/assets/esp8266-f57A77mF.js +0 -1
- package/dist/ui/assets/event-stream-BJI_nGaK.js +0 -1
- package/dist/ui/assets/github-copilot-B3U5ZsUu.js +0 -1
- package/dist/ui/assets/github-copilot-Brb8tPWW.js +0 -2
- package/dist/ui/assets/github-copilot-headers-DZtWWv8W.js +0 -1
- package/dist/ui/assets/google-C3U0TK_l.js +0 -1
- package/dist/ui/assets/google-DPvIPcfE.js +0 -1
- package/dist/ui/assets/google-vertex-BbeV3aSP.js +0 -1
- package/dist/ui/assets/google-vertex-CEGsokz8.js +0 -1
- package/dist/ui/assets/headers-DO1UzNKu.js +0 -1
- package/dist/ui/assets/main-LqqRM1F-.js +0 -24
- package/dist/ui/assets/mistral-CLF3Mo4W.js +0 -46
- package/dist/ui/assets/mistral-DkJAVbOW.js +0 -46
- package/dist/ui/assets/openai-codex-BYbsJPYQ.js +0 -1
- package/dist/ui/assets/openai-codex-responses-B2oZ1hgB.js +0 -7
- package/dist/ui/assets/openai-codex-responses-Dumyd9t2.js +0 -7
- package/dist/ui/assets/openai-completions-B2n4Op2S.js +0 -5
- package/dist/ui/assets/openai-completions-aHU8w14d.js +0 -5
- package/dist/ui/assets/openai-responses-4ryIAXQS.js +0 -1
- package/dist/ui/assets/openai-responses-BurVahs3.js +0 -1
- package/dist/ui/assets/openai-responses-shared-BebU8o_f.js +0 -12
- package/dist/ui/assets/openai-responses-shared-D9O9OCYB.js +0 -12
- package/dist/ui/assets/openrouter-B1ruTb6k.js +0 -1
- package/dist/ui/assets/openrouter-XmffhsNH.js +0 -1
- package/dist/ui/assets/provider-store-access-DEnkpFQB.js +0 -1
- package/dist/ui/assets/provider-store-access-hYm5ykP5.js +0 -1
- package/dist/ui/assets/providers-BYABmiE-.js +0 -2
- package/dist/ui/assets/quick-llm-CpQ7FC1y.js +0 -1
- package/dist/ui/assets/session-freezer-ClZHZ4rq.js +0 -1
- package/dist/ui/assets/transform-messages-BjP6vDPY.js +0 -1
- package/dist/ui/assets/transform-messages-DiIjWKhh.js +0 -1
- package/dist/ui/assets/wc-extension-9BJC8pnc.js +0 -2
- package/dist/ui/assets/wc-live-CpCIXFgr.js +0 -258
- package/dist/ui/assets/xai-grok-BClQ5lXS.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./preload-helper-CZgWQFsJ.js";var t=class{queue=[];waiting=[];done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(e,t){this.isComplete=e,this.extractResult=t,this.finalResultPromise=new Promise(e=>{this.resolveFinalResult=e})}push(e){if(this.done)return;this.isComplete(e)&&(this.done=!0,this.resolveFinalResult(this.extractResult(e)));let t=this.waiting.shift();t?t({value:e,done:!1}):this.queue.push(e)}end(e){for(this.done=!0,e!==void 0&&this.resolveFinalResult(e);this.waiting.length>0;)this.waiting.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.shift();else if(this.done)return;else{let e=await new Promise(e=>this.waiting.push(e));if(e.done)return;yield e.value}}result(){return this.finalResultPromise}},n=class extends t{constructor(){super(e=>e.type===`done`||e.type===`error`,e=>{if(e.type===`done`)return e.message;if(e.type===`error`)return e.error;throw Error(`Unexpected event type for final result`)})}};function r(){return new n}function i(e,t){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:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}function a(e,t){(async()=>{for await(let n of t)e.push(n);e.end()})()}function o(e,t){let r=new n;return t().then(e=>{a(r,e)}).catch(t=>{let n=i(e,t);r.push({type:`error`,reason:`error`,error:n}),r.end(n)}),r}function s(e){return{stream:(t,n,r)=>o(t,async()=>(await e()).stream(t,n,r)),streamSimple:(t,n,r)=>o(t,async()=>(await e()).streamSimple(t,n,r))}}var c=function(e,t){return typeof e==`string`&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,n,r,i,a){return n?t?`.jsx`:`.js`:r&&(!i||!a)?e:r+i+`.`+a.toLowerCase()+`js`}):e},l=t=>e(()=>import(c(t)),[]);function u(){return globalThis.process?.env}function d(){return{async env(e){let t=u()?.[e];return typeof t==`string`&&t.trim().length>0?t:void 0},async fileExists(e){try{let t=await l(`node:fs/promises`),n=e;return n.startsWith(`~`)&&(n=(await l(`node:os`)).homedir()+n.slice(1)),await t.access(n),!0}catch{return!1}}}}var f=class{credentials=new Map;chains=new Map;enqueue(e,t){let n=this.chains.get(e)??Promise.resolve(),r=(async()=>(await n.catch(()=>{}),t()))();return this.chains.set(e,r.catch(()=>{})),r}async read(e){return this.credentials.get(e)}modify(e,t){return this.enqueue(e,async()=>{let n=this.credentials.get(e),r=await t(n);return r!==void 0&&this.credentials.set(e,r),r??n})}delete(e){return this.enqueue(e,async()=>{this.credentials.delete(e)})}},p=class extends Error{code;constructor(e,t,n){super(t,n),this.name=`ModelsError`,this.code=e}};async function m(e,t,n,r,i){let a=i?.env?h(r,i.env):r;if(i?.apiKey!==void 0&&e.auth.apiKey)return _(a,e.auth.apiKey,t,{type:`api_key`,key:i.apiKey,env:i.env});let o=await v(n,e.id);if(o){if(o.type===`oauth`&&e.auth.oauth)return g(n,e.id,e.auth.oauth,o);if(o.type===`api_key`&&e.auth.apiKey){let n=i?.env?{...o,env:{...o.env,...i.env}}:o;return _(a,e.auth.apiKey,t,n)}return}return e.auth.apiKey?_(a,e.auth.apiKey,t,void 0):void 0}function h(e,t){return{env:async n=>t[n]||await e.env(n),fileExists:t=>e.fileExists(t)}}async function g(e,t,n,r){let i=r;if(Date.now()>=i.expires){let r;try{r=await e.modify(t,async e=>{if(e?.type===`oauth`&&!(Date.now()<e.expires))try{return await n.refresh(e)}catch(e){throw new p(`oauth`,`OAuth refresh failed for ${t}`,{cause:e})}})}catch(e){throw e instanceof p?e:new p(`auth`,`Credential store modify failed for ${t}`,{cause:e})}if(r?.type!==`oauth`)return;i=r}try{return{auth:await n.toAuth(i),source:`OAuth`}}catch(e){throw new p(`oauth`,`OAuth auth derivation failed for ${t}`,{cause:e})}}async function _(e,t,n,r){try{return await t.resolve({model:n,ctx:e,credential:r})}catch(e){throw new p(`auth`,`API key auth failed for provider ${n.provider}`,{cause:e})}}async function v(e,t){try{return await e.read(t)}catch(e){throw new p(`auth`,`Credential store read failed for ${t}`,{cause:e})}}var y=class{providers=new Map;credentials;authContext;constructor(e){this.credentials=e?.credentials??new f,this.authContext=e?.authContext??d()}setProvider(e){this.providers.set(e.id,e)}deleteProvider(e){this.providers.delete(e)}clearProviders(){this.providers.clear()}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}getModels(e){if(e!==void 0){let t=this.providers.get(e);if(!t)return[];try{return t.getModels()}catch{return[]}}let t=[];for(let e of this.providers.values())try{t.push(...e.getModels())}catch{}return t}getModel(e,t){return this.getModels(e).find(e=>e.id===t)}async refresh(e){if(e!==void 0){let t=this.providers.get(e);if(!t?.refreshModels)return;try{await t.refreshModels()}catch(t){throw t instanceof p?t:new p(`model_source`,`Model refresh failed for ${e}`,{cause:t})}return}await Promise.allSettled(Array.from(this.providers.values(),async e=>e.refreshModels?.()))}async getAuth(e){let t=this.providers.get(e.provider);if(t)return m(t,e,this.credentials,this.authContext)}requireProvider(e){let t=this.providers.get(e.provider);if(!t)throw new p(`provider`,`Unknown provider: ${e.provider}`);return t}async applyAuth(e,t){let n=await m(this.requireProvider(e),e,this.credentials,this.authContext,{apiKey:t?.apiKey,env:t?.env}),r=n?.auth;if(!r)return{requestModel:e,requestOptions:t};let i=r.baseUrl?{...e,baseUrl:r.baseUrl}:e,a=t?.apiKey??r.apiKey,o=r.headers||t?.headers?{...r.headers,...t?.headers}:void 0,s=n.env||t?.env?{...n.env??{},...t?.env??{}}:void 0;return{requestModel:i,requestOptions:{...t,apiKey:a,headers:o,env:s}}}stream(e,t,n){return o(e,async()=>{let r=this.requireProvider(e),{requestModel:i,requestOptions:a}=await this.applyAuth(e,n);return r.stream(i,t,a)})}async complete(e,t,n){return this.stream(e,t,n).result()}streamSimple(e,t,n){return o(e,async()=>{let r=this.requireProvider(e),{requestModel:i,requestOptions:a}=await this.applyAuth(e,n);return r.streamSimple(i,t,a)})}async completeSimple(e,t,n){return this.streamSimple(e,t,n).result()}};function b(e){return new y(e)}function x(e){let t=e.models,n,r=e.refreshModels,i=typeof e.api.stream==`function`?e.api:void 0,a=i?void 0:e.api,s=e=>i??a?.[e.api],c=(t,n)=>{let r=s(t);return r?n(r):o(t,async()=>{throw new p(`stream`,`Provider ${e.id} has no API implementation for "${t.api}"`)})};return{id:e.id,name:e.name??e.id,baseUrl:e.baseUrl,headers:e.headers,auth:e.auth,getModels:()=>t,refreshModels:r?()=>(n??=(async()=>{try{t=await r()}finally{n=void 0}})(),n):void 0,stream:(e,t,n)=>c(e,r=>r.stream(e,t,n)),streamSimple:(e,t,n)=>c(e,r=>r.streamSimple(e,t,n))}}function S(e,t){let n=t.cacheWrite1h??0,r=t.cacheWrite-n;return t.cost.input=e.cost.input/1e6*t.input,t.cost.output=e.cost.output/1e6*t.output,t.cost.cacheRead=e.cost.cacheRead/1e6*t.cacheRead,t.cost.cacheWrite=(e.cost.cacheWrite*r+e.cost.input*2*n)/1e6,t.cost.total=t.cost.input+t.cost.output+t.cost.cacheRead+t.cost.cacheWrite,t.cost}var C=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`];function w(e){return e.reasoning?C.filter(t=>{let n=e.thinkingLevelMap?.[t];return n===null?!1:t===`xhigh`?n!==void 0:!0}):[`off`]}function T(e,t){let n=w(e);if(n.includes(t))return t;let r=C.indexOf(t);if(r===-1)return n[0]??`off`;for(let e=r;e<C.length;e++){let t=C[e];if(n.includes(t))return t}for(let e=r-1;e>=0;e--){let t=C[e];if(n.includes(t))return t}return n[0]??`off`}export{s as a,x as i,T as n,n as o,b as r,r as s,S as t};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/account-store-
|
|
2
|
-
import{t as e}from"./preload-helper-CZgWQFsJ.js";import{t}from"./mime-types-ugOWOUZ9.js";import{a as n,o as r}from"./src-BdPw21ST.js";import{a as i,n as a,t as o}from"./proxied-fetch-iGqLvoxh.js";import{t as s}from"./types-idfTVsM8.js";import"./backend-local-BgTSBOxM.js";import"./mount-table-store-CfQUN_2R.js";import{t as c}from"./mount-bridge-client-DHpxu7lQ.js";function l(e,t,n){let r=`----DaMount${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,i=new TextEncoder,a=i.encode(`--${r}\r\nContent-Disposition: form-data; name="data"; filename="${e}"\r\nContent-Type: ${t}\r\n\r\n`),o=i.encode(`\r\n--${r}--\r\n`),s=new Uint8Array(a.byteLength+n.byteLength+o.byteLength);return s.set(a,0),s.set(n,a.byteLength),s.set(o,a.byteLength+n.byteLength),{contentType:`multipart/form-data; boundary=${r}`,body:s}}function u(e){return e.split(`/`).pop()||`data`}function d(e){let t=e.match(/^da:\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid DA source '${e}' — expected da://org/repo[/path]`);return{org:t[1],repo:t[2],path:(t[3]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var f=5*1024*1024,p=class{kind=`da`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=d(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??f,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new s(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toSourcePath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/source/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}toListPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/list/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,path:this.toSourcePath(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new s(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new s(`EACCES`,`da access denied`,e);if(i.status>=400)throw new s(`EIO`,`da readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),o=a?Number(a):void 0;if(o!==void 0&&o>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let c=new Uint8Array(await i.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``,u=l.startsWith(`W/`)?l.slice(2):l;return await this.cache.putBody(t,c,u),c}async writeFile(e,n){if(this.assertOpen(e),n.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let r=this.toMountRelative(e),i=await this.cache.getBody(r),a=l(u(e),t(e),n),o={"content-type":a.contentType,"content-length":String(a.body.byteLength)};i?.etag?o[`if-match`]=i.etag.startsWith(`W/`)?i.etag.slice(2):i.etag:i||(o[`if-none-match`]=`*`);let c=()=>this.transport({method:`POST`,path:this.toSourcePath(r),headers:o,body:a.body}),d,f=1;try{d=await c()}catch{f=2,d=await c()}if(d.status===412){if(f===2){let t=await this.transport({method:`HEAD`,path:this.toSourcePath(r)});if(t.status>=400)throw new s(`EIO`,`da reconcile HEAD failed: ${t.status}`,e);let i=t.headers.get(`etag`)??``;await this.cache.putBody(r,n,i);let a=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(r);try{await this.readFile(e)}catch{}throw new s(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(d.status===401||d.status===403)throw new s(`EACCES`,`da write denied`,e);if(d.status>=400)throw new s(`EIO`,`da writeFile failed: ${d.status}`,e);let p=d.headers.get(`etag`)??``;await this.cache.putBody(r,n,p);let m=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(m)}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.transport({method:`GET`,path:this.toListPath(t)});if(r.status===404)throw new s(`ENOENT`,`no such directory`,e);if(r.status>=400)throw new s(`EIO`,`da list failed: ${r.status}`,e);let i=(await r.json()).map(e=>e.ext?{name:`${e.name}.${e.ext}`,kind:`file`,etag:e.etag,lastModified:e.lastModified}:{name:e.name,kind:`directory`,lastModified:e.lastModified});return await this.cache.putListing(t,i),i}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.size,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),o=await this.cache.getListing(a);if(o&&!this.cache.isStale(o.cachedAt)){let t=o.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??o.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??o.cachedAt};if(!t)throw new s(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,path:this.toSourcePath(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`),r=n?Date.parse(n):0;if(o){let n=o.entries.map(n=>n.name===i&&n.kind===`file`?{...n,size:e,etag:t,lastModified:r}:n);await this.cache.putListing(a,n)}return{kind:`file`,size:e,mtime:r,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new s(`ENOENT`,`no such file or directory`,e)}throw new s(`EIO`,`da stat failed: ${c.status}`,e)}async mkdir(e){}async remove(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.transport({method:`DELETE`,path:this.toSourcePath(t)});if(n.status===404)throw new s(`ENOENT`,`no such file`,e);if(n.status===401||n.status===403)throw new s(`EACCES`,`da delete denied`,e);if(n.status>=400)throw new s(`EIO`,`da delete failed: ${n.status}`,e);await this.cache.invalidateBody(t);let r=t.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(r)}async refresh(e){this.assertOpen(`/`);let t={added:[],removed:[],changed:[],unchanged:0,errors:[]},n=[``];for(;n.length>0;){let e=n.pop();try{await this.refreshDir(e,t,n)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}}return e?.bodies&&await this.refreshBodies(t),t}async classifyFile(e,t,n){let r=await this.cache.getBody(e);r?t&&r.etag!==t?(await this.cache.invalidateBody(e),n.changed.push(e)):n.unchanged++:n.added.push(e)}async refreshDir(e,t,n){let r=await this.transport({method:`GET`,path:this.toListPath(e)});if(r.status>=400){t.errors.push({path:e,message:`list failed: ${r.status}`});return}let i=await r.json(),a=[];for(let r of i)if(r.ext){let n=e?`${e}/${r.name}.${r.ext}`:`${r.name}.${r.ext}`;a.push({name:`${r.name}.${r.ext}`,kind:`file`,etag:r.etag,lastModified:r.lastModified}),await this.classifyFile(n,r.etag,t)}else a.push({name:r.name,kind:`directory`}),n.push(e?`${e}/${r.name}`:r.name);await this.cache.putListing(e,a)}async refreshBodies(e){for(let t of e.changed)try{await this.readFile(t)}catch(n){e.errors.push({path:t,message:n instanceof Error?n.message:String(n)})}}describe(){return{displayName:`${this.parsed.org}/${this.parsed.repo}${this.parsed.path?`/${this.parsed.path}`:``}`,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function m(e){let t=e.match(/^s3:\/\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid S3 source '${e}' — expected s3://bucket[/prefix]`);return{bucket:t[1],prefix:(t[2]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var h=25*1024*1024,g=class{kind=`s3`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=m(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??h,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new s(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toS3Key(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``);return[this.parsed.prefix,t].filter(e=>e.length>0).join(`/`)}toMountRelativeKey(e){return this.parsed.prefix?e.slice(this.parsed.prefix.length+1):e}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:this.toS3Key(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new s(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new s(`EACCES`,`s3 access denied`,e);if(i.status>=400)throw new s(`EIO`,`s3 readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),o=a?Number(a):void 0;if(o!==void 0&&o>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes (${o} > ${this.maxBodyBytes})`,e);let c=new Uint8Array(await i.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``;return await this.cache.putBody(t,c,l),c}async writeFile(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let r=await this.cache.getBody(n),i={"content-type":`application/octet-stream`,"content-length":String(t.byteLength)};r?i[`if-match`]=r.etag:i[`if-none-match`]=`*`;let a=()=>this.transport({method:`PUT`,bucket:this.parsed.bucket,key:this.toS3Key(n),headers:i,body:t}),o,c=1;try{o=await a()}catch{c=2,o=await a()}if(o.status===412){if(c===2){let r=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status>=400)throw new s(`EIO`,`s3 reconcile HEAD failed: ${r.status}`,e);let i=r.headers.get(`etag`)??``;await this.cache.putBody(n,t,i);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new s(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(o.status===401||o.status===403)throw new s(`EACCES`,`s3 write denied`,e);if(o.status>=400)throw new s(`EIO`,`s3 writeFile failed: ${o.status}`,e);let l=o.headers.get(`etag`)??``;await this.cache.putBody(n,t,l);let u=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(u)}async listObjectsV2(){let e=[],t;do{let n={"list-type":`2`};this.parsed.prefix&&(n.prefix=`${this.parsed.prefix}/`),t&&(n[`continuation-token`]=t);let r=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:``,query:n});if(r.status>=400)throw new s(`EIO`,`s3 list failed: ${r.status}`,`/`);let i=await r.text(),a=this.parseListingXml(i);e.push(...a.contents),t=a.nextContinuationToken}while(t);return e}parseListingXml(e){let t=[];for(let n of e.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)){let e=n[1],r=e.match(/<Key>([^<]+)<\/Key>/)?.[1]??``,i=e.match(/<ETag>([^<]+)<\/ETag>/)?.[1]??``,a=e.match(/<Size>([^<]+)<\/Size>/)?.[1]??`0`,o=e.match(/<LastModified>([^<]+)<\/LastModified>/)?.[1]??``;t.push({key:r,etag:i,size:Number(a),lastModified:o?Date.parse(o):0})}return{contents:t,nextContinuationToken:e.match(/<IsTruncated>([^<]+)<\/IsTruncated>/)?.[1]===`true`?e.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]:void 0}}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.listObjectsV2(),i=this.groupByDir(r);for(let[e,t]of i)await this.cache.putListing(e,t);return i.get(t)??[]}groupByDir(e){let t=new Map,n=e=>(t.has(e)||t.set(e,[]),t.get(e));n(``);for(let t of e){let e=this.toMountRelativeKey(t.key).split(`/`),r=e.pop();n(e.join(`/`)).push({name:r,kind:`file`,size:t.size,etag:t.etag,lastModified:t.lastModified});let i=``;for(let t of e){let e=i;i=i?`${i}/${t}`:t;let r=n(e);r.find(e=>e.name===t&&e.kind===`directory`)||r.push({name:t,kind:`directory`}),n(i)}}return t}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.body.byteLength,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),o=await this.cache.getListing(a);if(o&&!this.cache.isStale(o.cachedAt)){let t=o.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??o.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??o.cachedAt};if(!t)throw new s(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`);return{kind:`file`,size:e,mtime:n?Date.parse(n):0,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new s(`ENOENT`,`no such file or directory`,e)}throw new s(`EIO`,`s3 stat failed: ${c.status}`,e)}async refresh(e){this.assertOpen(`/`);let t=await this.listObjectsV2(),n=new Set(t.map(e=>this.toMountRelativeKey(e.key))),r=new Map(t.map(e=>[this.toMountRelativeKey(e.key),e.etag])),i={added:[],removed:[],changed:[],unchanged:0,errors:[]};for(let e of n){let t=await this.cache.getBody(e),n=r.get(e);t?t.etag===n?i.unchanged++:(await this.cache.invalidateBody(e),i.changed.push(e)):i.added.push(e)}let a=this.groupByDir(t);for(let[e,t]of a)await this.cache.putListing(e,t);if(e?.bodies)for(let e of i.changed)try{await this.readFile(e)}catch(t){i.errors.push({path:e,message:t instanceof Error?t.message:String(t)})}return i}async mkdir(e){}async remove(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t?.recursive)throw new s(`EINVAL`,`recursive remove not yet supported on S3`,e);let r=await this.transport({method:`DELETE`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status===404)throw new s(`ENOENT`,`no such file`,e);if(r.status===401||r.status===403)throw new s(`EACCES`,`s3 delete denied`,e);if(r.status>=400)throw new s(`EIO`,`s3 delete failed: ${r.status}`,e);await this.cache.invalidateBody(n);let i=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(i)}describe(){return{displayName:this.parsed.prefix?`${this.parsed.bucket}/${this.parsed.prefix}`:this.parsed.bucket,source:this.source,profile:this.profile}}async close(){this.closed||=!0}},_=class extends Error{constructor(e){super(e),this.name=`ProfileNotConfiguredError`}};async function v(){let{getAccounts:t}=await e(async()=>{let{getAccounts:e}=await import(`./account-store-SL9GSzVk.js`).then(e=>e.r);return{getAccounts:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19])),n=t().find(e=>e.providerId===`adobe`);if(!n?.accessToken)throw new _(`No Adobe IMS account found. Log in via Settings → Providers → Adobe first.`);return{identity:`adobe-ims`,getBearerToken:async()=>n.accessToken}}var y=`slicc-mount-cache`,b=`listings`,x=`bodies`,S=class{mountId;ttlMs;dbName;dbPromise=null;constructor(e){this.mountId=e.mountId,this.ttlMs=e.ttlMs,this.dbName=e.dbName??y}isStale(e,t){return Date.now()-e>=(t??this.ttlMs)}async openDb(){return this.dbPromise||=new Promise((e,t)=>{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(b)||e.createObjectStore(b),e.objectStoreNames.contains(x)||e.createObjectStore(x)},n.onsuccess=()=>{let t=n.result;t.onversionchange=()=>{t.close(),this.dbPromise=null},t.onclose=()=>{this.dbPromise=null},e(t)},n.onerror=()=>t(n.error)}),this.dbPromise}key(e){return`${this.mountId}::${e}`}async getListing(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(b,`readonly`).objectStore(b).get(this.key(e));i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async putListing(e,t){let n=await this.openDb();return new Promise((r,i)=>{let a=n.transaction(b,`readwrite`),o={entries:t,cachedAt:Date.now()};a.objectStore(b).put(o,this.key(e)),a.oncomplete=()=>r(),a.onerror=()=>i(a.error)})}async invalidateListing(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(b,`readwrite`);i.objectStore(b).delete(this.key(e)),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async getBody(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(x,`readonly`).objectStore(x).get(this.key(e));i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async putBody(e,t,n){let r=await this.openDb(),i={body:t,etag:n,size:t.byteLength,cachedAt:Date.now()};try{await this.txPut(r,x,this.key(e),i)}catch(t){if(t instanceof DOMException&&t.name===`QuotaExceededError`){await this.evictLru(.25);try{await this.txPut(r,x,this.key(e),i)}catch{}return}throw t}}async invalidateBody(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(x,`readwrite`);i.objectStore(x).delete(this.key(e)),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async clearMount(){let e=await this.openDb(),t=`${this.mountId}::`,n=n=>new Promise((r,i)=>{let a=e.transaction(n,`readwrite`),o=a.objectStore(n),s=o.getAllKeys();s.onsuccess=()=>{for(let e of s.result)typeof e==`string`&&e.startsWith(t)&&o.delete(e)},a.oncomplete=()=>r(),a.onerror=()=>i(a.error)});await Promise.all([n(b),n(x)])}txPut(e,t,n,r){return new Promise((i,a)=>{let o=e.transaction(t,`readwrite`);o.objectStore(t).put(r,n),o.oncomplete=()=>i(),o.onerror=()=>a(o.error)})}async evictLru(e){let t=await this.openDb(),n=`${this.mountId}::`,r=await new Promise((e,r)=>{let i=t.transaction(x,`readonly`).objectStore(x),a=[],o=i.openCursor();o.onsuccess=()=>{let t=o.result;if(!t){e(a);return}if(typeof t.key==`string`&&t.key.startsWith(n)){let e=t.value;a.push({key:t.key,cachedAt:e.cachedAt})}t.continue()},o.onerror=()=>r(o.error)});r.sort((e,t)=>e.cachedAt-t.cachedAt);let i=Math.max(1,Math.ceil(r.length*e)),a=r.slice(0,i);await new Promise((e,n)=>{let r=t.transaction(x,`readwrite`),i=r.objectStore(x);for(let{key:e}of a)i.delete(e);r.oncomplete=()=>e(),r.onerror=()=>n(r.error)})}};function C(){return typeof chrome<`u`&&!!chrome?.runtime?.id}var w=n,T=r,E=new Set([`invalid_profile`,`invalid_request`,`profile_not_configured`,`fetch_failed`,`internal`]),D=new Set([101,103,204,205,304]);function O(e){if(!e.ok)throw e.errorCode===`profile_not_configured`||e.errorCode===`invalid_profile`?new s(`EACCES`,e.error):e.errorCode===`invalid_request`?new s(`EINVAL`,e.error):e.errorCode===`fetch_failed`||e.errorCode===`internal`||E.has(String(e.errorCode))?new s(`EIO`,e.error):new s(`EINVAL`,`mount transport returned unrecognized errorCode '${e.errorCode}': ${e.error}`);let t;try{t=w(e.bodyBase64)}catch(e){throw new s(`EIO`,`mount transport: response body decode failed: ${e instanceof Error?e.message:String(e)}`)}let n=D.has(e.status)?null:t;return new Response(n,{status:e.status,headers:new Headers(e.headers)})}async function k(e,t){let n;try{n=await fetch(i(e),{method:`POST`,headers:o({"content-type":`application/json`}),body:JSON.stringify(t)})}catch(e){throw new s(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (SLICC backend at localhost may not be running)`)}try{return await n.json()}catch(e){throw new s(`EIO`,`mount transport: response is not a JSON envelope (status ${n.status}): ${e instanceof Error?e.message:String(e)}`)}}async function A(e,t){try{return await chrome.runtime.sendMessage({type:e,envelope:t})}catch(e){throw new s(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (extension service worker not responding)`)}}async function j(e,t,n){return C()?A(e,n):a()?c(e,n):k(t,n)}function M(e){return async t=>O(await j(`mount.s3-sign-and-forward`,`/api/s3-sign-and-forward`,{profile:e,method:t.method,bucket:t.bucket,key:t.key,query:t.query,headers:t.headers,bodyBase64:t.body?T(t.body):void 0}))}function N(e){let t=e?.getImsToken??(async()=>(await v()).getBearerToken());return async e=>{let n;try{n=await t()}catch(e){throw new s(`EACCES`,`DA mount: ${e instanceof Error?e.message:String(e)}`)}return O(await j(`mount.da-sign-and-forward`,`/api/da-sign-and-forward`,{imsToken:n,method:e.method,path:e.path,query:e.query,headers:e.headers,bodyBase64:e.body?T(e.body):void 0}))}}export{p as DaMountBackend,S as RemoteMountCache,g as S3MountBackend,N as makeSignedFetchDa,M as makeSignedFetchS3};
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/account-store-Bk7BU4R2.js","assets/rolldown-runtime-aKtaBQYM.js","assets/preload-helper-CZgWQFsJ.js","assets/compat-DADQxxLV.js","assets/models-ByRUWfA-.js","assets/provider-env-D37PhSJu.js","assets/__vite-browser-external-SwrSgYTf.js","assets/context-compaction-DaxQExZG.js","assets/logger-DDBAeTLF.js","assets/src-BdPw21ST.js","assets/proxied-fetch-iGqLvoxh.js","assets/fetch-body-D2PwksUW.js","assets/secret-topology-DnYeyyJY.js","assets/secrets-bridge-client-x_puVSDN.js","assets/port-bridge-client-BJ5rcoKH.js","assets/tool-ui-DfXu6quJ.js","assets/providers-BrRzKc33.js","assets/panel-rpc-DmJSNs0I.js","assets/bedrock-camp-DbZ6Mjym.js","assets/transform-messages-D7OsqBmU.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as e}from"./preload-helper-CZgWQFsJ.js";import{t}from"./mime-types-ugOWOUZ9.js";import{a as n,o as r}from"./src-BdPw21ST.js";import{a as i,n as a,t as o}from"./proxied-fetch-iGqLvoxh.js";import{t as s}from"./types-idfTVsM8.js";import"./backend-local-BgTSBOxM.js";import"./mount-table-store-CfQUN_2R.js";import{t as c}from"./mount-bridge-client-DHpxu7lQ.js";function l(e,t,n){let r=`----DaMount${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,i=new TextEncoder,a=i.encode(`--${r}\r\nContent-Disposition: form-data; name="data"; filename="${e}"\r\nContent-Type: ${t}\r\n\r\n`),o=i.encode(`\r\n--${r}--\r\n`),s=new Uint8Array(a.byteLength+n.byteLength+o.byteLength);return s.set(a,0),s.set(n,a.byteLength),s.set(o,a.byteLength+n.byteLength),{contentType:`multipart/form-data; boundary=${r}`,body:s}}function u(e){return e.split(`/`).pop()||`data`}function d(e){let t=e.match(/^da:\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid DA source '${e}' — expected da://org/repo[/path]`);return{org:t[1],repo:t[2],path:(t[3]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var f=5*1024*1024,p=class{kind=`da`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=d(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??f,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new s(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toSourcePath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/source/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}toListPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/list/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,path:this.toSourcePath(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new s(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new s(`EACCES`,`da access denied`,e);if(i.status>=400)throw new s(`EIO`,`da readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),o=a?Number(a):void 0;if(o!==void 0&&o>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let c=new Uint8Array(await i.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``,u=l.startsWith(`W/`)?l.slice(2):l;return await this.cache.putBody(t,c,u),c}async writeFile(e,n){if(this.assertOpen(e),n.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let r=this.toMountRelative(e),i=await this.cache.getBody(r),a=l(u(e),t(e),n),o={"content-type":a.contentType,"content-length":String(a.body.byteLength)};i?.etag?o[`if-match`]=i.etag.startsWith(`W/`)?i.etag.slice(2):i.etag:i||(o[`if-none-match`]=`*`);let c=()=>this.transport({method:`POST`,path:this.toSourcePath(r),headers:o,body:a.body}),d,f=1;try{d=await c()}catch{f=2,d=await c()}if(d.status===412){if(f===2){let t=await this.transport({method:`HEAD`,path:this.toSourcePath(r)});if(t.status>=400)throw new s(`EIO`,`da reconcile HEAD failed: ${t.status}`,e);let i=t.headers.get(`etag`)??``;await this.cache.putBody(r,n,i);let a=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(r);try{await this.readFile(e)}catch{}throw new s(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(d.status===401||d.status===403)throw new s(`EACCES`,`da write denied`,e);if(d.status>=400)throw new s(`EIO`,`da writeFile failed: ${d.status}`,e);let p=d.headers.get(`etag`)??``;await this.cache.putBody(r,n,p);let m=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(m)}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.transport({method:`GET`,path:this.toListPath(t)});if(r.status===404)throw new s(`ENOENT`,`no such directory`,e);if(r.status>=400)throw new s(`EIO`,`da list failed: ${r.status}`,e);let i=(await r.json()).map(e=>e.ext?{name:`${e.name}.${e.ext}`,kind:`file`,etag:e.etag,lastModified:e.lastModified}:{name:e.name,kind:`directory`,lastModified:e.lastModified});return await this.cache.putListing(t,i),i}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.size,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),o=await this.cache.getListing(a);if(o&&!this.cache.isStale(o.cachedAt)){let t=o.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??o.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??o.cachedAt};if(!t)throw new s(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,path:this.toSourcePath(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`),r=n?Date.parse(n):0;if(o){let n=o.entries.map(n=>n.name===i&&n.kind===`file`?{...n,size:e,etag:t,lastModified:r}:n);await this.cache.putListing(a,n)}return{kind:`file`,size:e,mtime:r,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new s(`ENOENT`,`no such file or directory`,e)}throw new s(`EIO`,`da stat failed: ${c.status}`,e)}async mkdir(e){}async remove(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.transport({method:`DELETE`,path:this.toSourcePath(t)});if(n.status===404)throw new s(`ENOENT`,`no such file`,e);if(n.status===401||n.status===403)throw new s(`EACCES`,`da delete denied`,e);if(n.status>=400)throw new s(`EIO`,`da delete failed: ${n.status}`,e);await this.cache.invalidateBody(t);let r=t.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(r)}async refresh(e){this.assertOpen(`/`);let t={added:[],removed:[],changed:[],unchanged:0,errors:[]},n=[``];for(;n.length>0;){let e=n.pop();try{await this.refreshDir(e,t,n)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}}return e?.bodies&&await this.refreshBodies(t),t}async classifyFile(e,t,n){let r=await this.cache.getBody(e);r?t&&r.etag!==t?(await this.cache.invalidateBody(e),n.changed.push(e)):n.unchanged++:n.added.push(e)}async refreshDir(e,t,n){let r=await this.transport({method:`GET`,path:this.toListPath(e)});if(r.status>=400){t.errors.push({path:e,message:`list failed: ${r.status}`});return}let i=await r.json(),a=[];for(let r of i)if(r.ext){let n=e?`${e}/${r.name}.${r.ext}`:`${r.name}.${r.ext}`;a.push({name:`${r.name}.${r.ext}`,kind:`file`,etag:r.etag,lastModified:r.lastModified}),await this.classifyFile(n,r.etag,t)}else a.push({name:r.name,kind:`directory`}),n.push(e?`${e}/${r.name}`:r.name);await this.cache.putListing(e,a)}async refreshBodies(e){for(let t of e.changed)try{await this.readFile(t)}catch(n){e.errors.push({path:t,message:n instanceof Error?n.message:String(n)})}}describe(){return{displayName:`${this.parsed.org}/${this.parsed.repo}${this.parsed.path?`/${this.parsed.path}`:``}`,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function m(e){let t=e.match(/^s3:\/\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid S3 source '${e}' — expected s3://bucket[/prefix]`);return{bucket:t[1],prefix:(t[2]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var h=25*1024*1024,g=class{kind=`s3`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=m(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??h,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new s(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toS3Key(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``);return[this.parsed.prefix,t].filter(e=>e.length>0).join(`/`)}toMountRelativeKey(e){return this.parsed.prefix?e.slice(this.parsed.prefix.length+1):e}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:this.toS3Key(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new s(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new s(`EACCES`,`s3 access denied`,e);if(i.status>=400)throw new s(`EIO`,`s3 readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),o=a?Number(a):void 0;if(o!==void 0&&o>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes (${o} > ${this.maxBodyBytes})`,e);let c=new Uint8Array(await i.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``;return await this.cache.putBody(t,c,l),c}async writeFile(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let r=await this.cache.getBody(n),i={"content-type":`application/octet-stream`,"content-length":String(t.byteLength)};r?i[`if-match`]=r.etag:i[`if-none-match`]=`*`;let a=()=>this.transport({method:`PUT`,bucket:this.parsed.bucket,key:this.toS3Key(n),headers:i,body:t}),o,c=1;try{o=await a()}catch{c=2,o=await a()}if(o.status===412){if(c===2){let r=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status>=400)throw new s(`EIO`,`s3 reconcile HEAD failed: ${r.status}`,e);let i=r.headers.get(`etag`)??``;await this.cache.putBody(n,t,i);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new s(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(o.status===401||o.status===403)throw new s(`EACCES`,`s3 write denied`,e);if(o.status>=400)throw new s(`EIO`,`s3 writeFile failed: ${o.status}`,e);let l=o.headers.get(`etag`)??``;await this.cache.putBody(n,t,l);let u=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(u)}async listObjectsV2(){let e=[],t;do{let n={"list-type":`2`};this.parsed.prefix&&(n.prefix=`${this.parsed.prefix}/`),t&&(n[`continuation-token`]=t);let r=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:``,query:n});if(r.status>=400)throw new s(`EIO`,`s3 list failed: ${r.status}`,`/`);let i=await r.text(),a=this.parseListingXml(i);e.push(...a.contents),t=a.nextContinuationToken}while(t);return e}parseListingXml(e){let t=[];for(let n of e.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)){let e=n[1],r=e.match(/<Key>([^<]+)<\/Key>/)?.[1]??``,i=e.match(/<ETag>([^<]+)<\/ETag>/)?.[1]??``,a=e.match(/<Size>([^<]+)<\/Size>/)?.[1]??`0`,o=e.match(/<LastModified>([^<]+)<\/LastModified>/)?.[1]??``;t.push({key:r,etag:i,size:Number(a),lastModified:o?Date.parse(o):0})}return{contents:t,nextContinuationToken:e.match(/<IsTruncated>([^<]+)<\/IsTruncated>/)?.[1]===`true`?e.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]:void 0}}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.listObjectsV2(),i=this.groupByDir(r);for(let[e,t]of i)await this.cache.putListing(e,t);return i.get(t)??[]}groupByDir(e){let t=new Map,n=e=>(t.has(e)||t.set(e,[]),t.get(e));n(``);for(let t of e){let e=this.toMountRelativeKey(t.key).split(`/`),r=e.pop();n(e.join(`/`)).push({name:r,kind:`file`,size:t.size,etag:t.etag,lastModified:t.lastModified});let i=``;for(let t of e){let e=i;i=i?`${i}/${t}`:t;let r=n(e);r.find(e=>e.name===t&&e.kind===`directory`)||r.push({name:t,kind:`directory`}),n(i)}}return t}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.body.byteLength,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),o=await this.cache.getListing(a);if(o&&!this.cache.isStale(o.cachedAt)){let t=o.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??o.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??o.cachedAt};if(!t)throw new s(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`);return{kind:`file`,size:e,mtime:n?Date.parse(n):0,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new s(`ENOENT`,`no such file or directory`,e)}throw new s(`EIO`,`s3 stat failed: ${c.status}`,e)}async refresh(e){this.assertOpen(`/`);let t=await this.listObjectsV2(),n=new Set(t.map(e=>this.toMountRelativeKey(e.key))),r=new Map(t.map(e=>[this.toMountRelativeKey(e.key),e.etag])),i={added:[],removed:[],changed:[],unchanged:0,errors:[]};for(let e of n){let t=await this.cache.getBody(e),n=r.get(e);t?t.etag===n?i.unchanged++:(await this.cache.invalidateBody(e),i.changed.push(e)):i.added.push(e)}let a=this.groupByDir(t);for(let[e,t]of a)await this.cache.putListing(e,t);if(e?.bodies)for(let e of i.changed)try{await this.readFile(e)}catch(t){i.errors.push({path:e,message:t instanceof Error?t.message:String(t)})}return i}async mkdir(e){}async remove(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t?.recursive)throw new s(`EINVAL`,`recursive remove not yet supported on S3`,e);let r=await this.transport({method:`DELETE`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status===404)throw new s(`ENOENT`,`no such file`,e);if(r.status===401||r.status===403)throw new s(`EACCES`,`s3 delete denied`,e);if(r.status>=400)throw new s(`EIO`,`s3 delete failed: ${r.status}`,e);await this.cache.invalidateBody(n);let i=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(i)}describe(){return{displayName:this.parsed.prefix?`${this.parsed.bucket}/${this.parsed.prefix}`:this.parsed.bucket,source:this.source,profile:this.profile}}async close(){this.closed||=!0}},_=class extends Error{constructor(e){super(e),this.name=`ProfileNotConfiguredError`}};async function v(){let{getAccounts:t}=await e(async()=>{let{getAccounts:e}=await import(`./account-store-Bk7BU4R2.js`).then(e=>e.r);return{getAccounts:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19])),n=t().find(e=>e.providerId===`adobe`);if(!n?.accessToken)throw new _(`No Adobe IMS account found. Log in via Settings → Providers → Adobe first.`);return{identity:`adobe-ims`,getBearerToken:async()=>n.accessToken}}var y=`slicc-mount-cache`,b=`listings`,x=`bodies`,S=class{mountId;ttlMs;dbName;dbPromise=null;constructor(e){this.mountId=e.mountId,this.ttlMs=e.ttlMs,this.dbName=e.dbName??y}isStale(e,t){return Date.now()-e>=(t??this.ttlMs)}async openDb(){return this.dbPromise||=new Promise((e,t)=>{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(b)||e.createObjectStore(b),e.objectStoreNames.contains(x)||e.createObjectStore(x)},n.onsuccess=()=>{let t=n.result;t.onversionchange=()=>{t.close(),this.dbPromise=null},t.onclose=()=>{this.dbPromise=null},e(t)},n.onerror=()=>t(n.error)}),this.dbPromise}key(e){return`${this.mountId}::${e}`}async getListing(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(b,`readonly`).objectStore(b).get(this.key(e));i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async putListing(e,t){let n=await this.openDb();return new Promise((r,i)=>{let a=n.transaction(b,`readwrite`),o={entries:t,cachedAt:Date.now()};a.objectStore(b).put(o,this.key(e)),a.oncomplete=()=>r(),a.onerror=()=>i(a.error)})}async invalidateListing(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(b,`readwrite`);i.objectStore(b).delete(this.key(e)),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async getBody(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(x,`readonly`).objectStore(x).get(this.key(e));i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async putBody(e,t,n){let r=await this.openDb(),i={body:t,etag:n,size:t.byteLength,cachedAt:Date.now()};try{await this.txPut(r,x,this.key(e),i)}catch(t){if(t instanceof DOMException&&t.name===`QuotaExceededError`){await this.evictLru(.25);try{await this.txPut(r,x,this.key(e),i)}catch{}return}throw t}}async invalidateBody(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(x,`readwrite`);i.objectStore(x).delete(this.key(e)),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async clearMount(){let e=await this.openDb(),t=`${this.mountId}::`,n=n=>new Promise((r,i)=>{let a=e.transaction(n,`readwrite`),o=a.objectStore(n),s=o.getAllKeys();s.onsuccess=()=>{for(let e of s.result)typeof e==`string`&&e.startsWith(t)&&o.delete(e)},a.oncomplete=()=>r(),a.onerror=()=>i(a.error)});await Promise.all([n(b),n(x)])}txPut(e,t,n,r){return new Promise((i,a)=>{let o=e.transaction(t,`readwrite`);o.objectStore(t).put(r,n),o.oncomplete=()=>i(),o.onerror=()=>a(o.error)})}async evictLru(e){let t=await this.openDb(),n=`${this.mountId}::`,r=await new Promise((e,r)=>{let i=t.transaction(x,`readonly`).objectStore(x),a=[],o=i.openCursor();o.onsuccess=()=>{let t=o.result;if(!t){e(a);return}if(typeof t.key==`string`&&t.key.startsWith(n)){let e=t.value;a.push({key:t.key,cachedAt:e.cachedAt})}t.continue()},o.onerror=()=>r(o.error)});r.sort((e,t)=>e.cachedAt-t.cachedAt);let i=Math.max(1,Math.ceil(r.length*e)),a=r.slice(0,i);await new Promise((e,n)=>{let r=t.transaction(x,`readwrite`),i=r.objectStore(x);for(let{key:e}of a)i.delete(e);r.oncomplete=()=>e(),r.onerror=()=>n(r.error)})}};function C(){return typeof chrome<`u`&&!!chrome?.runtime?.id}var w=n,T=r,E=new Set([`invalid_profile`,`invalid_request`,`profile_not_configured`,`fetch_failed`,`internal`]),D=new Set([101,103,204,205,304]);function O(e){if(!e.ok)throw e.errorCode===`profile_not_configured`||e.errorCode===`invalid_profile`?new s(`EACCES`,e.error):e.errorCode===`invalid_request`?new s(`EINVAL`,e.error):e.errorCode===`fetch_failed`||e.errorCode===`internal`||E.has(String(e.errorCode))?new s(`EIO`,e.error):new s(`EINVAL`,`mount transport returned unrecognized errorCode '${e.errorCode}': ${e.error}`);let t;try{t=w(e.bodyBase64)}catch(e){throw new s(`EIO`,`mount transport: response body decode failed: ${e instanceof Error?e.message:String(e)}`)}let n=D.has(e.status)?null:t;return new Response(n,{status:e.status,headers:new Headers(e.headers)})}async function k(e,t){let n;try{n=await fetch(i(e),{method:`POST`,headers:o({"content-type":`application/json`}),body:JSON.stringify(t)})}catch(e){throw new s(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (SLICC backend at localhost may not be running)`)}try{return await n.json()}catch(e){throw new s(`EIO`,`mount transport: response is not a JSON envelope (status ${n.status}): ${e instanceof Error?e.message:String(e)}`)}}async function A(e,t){try{return await chrome.runtime.sendMessage({type:e,envelope:t})}catch(e){throw new s(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (extension service worker not responding)`)}}async function j(e,t,n){return C()?A(e,n):a()?c(e,n):k(t,n)}function M(e){return async t=>O(await j(`mount.s3-sign-and-forward`,`/api/s3-sign-and-forward`,{profile:e,method:t.method,bucket:t.bucket,key:t.key,query:t.query,headers:t.headers,bodyBase64:t.body?T(t.body):void 0}))}function N(e){let t=e?.getImsToken??(async()=>(await v()).getBearerToken());return async e=>{let n;try{n=await t()}catch(e){throw new s(`EACCES`,`DA mount: ${e instanceof Error?e.message:String(e)}`)}return O(await j(`mount.da-sign-and-forward`,`/api/da-sign-and-forward`,{imsToken:n,method:e.method,path:e.path,query:e.query,headers:e.headers,bodyBase64:e.body?T(e.body):void 0}))}}export{p as DaMountBackend,S as RemoteMountCache,g as S3MountBackend,N as makeSignedFetchDa,M as makeSignedFetchS3};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{_ as t,g as n,o as r,r as i,t as a}from"./proxied-fetch-BVw2cmL4.js";import"./backend-local-mrUgrni5.js";import{t as o}from"./types-idfTVsM8.js";import{t as s}from"./mime-types-BqLkKWa7.js";import{t as c}from"./remote-cache-D59F5FOx.js";import{t as l}from"./port-bridge-client-vT8ubtB-.js";function u(e,t,n){let r=`----DaMount${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,i=new TextEncoder,a=i.encode(`--${r}\r\nContent-Disposition: form-data; name="data"; filename="${e}"\r\nContent-Type: ${t}\r\n\r\n`),o=i.encode(`\r\n--${r}--\r\n`),s=new Uint8Array(a.byteLength+n.byteLength+o.byteLength);return s.set(a,0),s.set(n,a.byteLength),s.set(o,a.byteLength+n.byteLength),{contentType:`multipart/form-data; boundary=${r}`,body:s}}function d(e){return e.split(`/`).pop()||`data`}function f(e){let t=e.match(/^da:\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid DA source '${e}' — expected da://org/repo[/path]`);return{org:t[1],repo:t[2],path:(t[3]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var p=class{kind=`da`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=f(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??5242880,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new o(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toSourcePath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/source/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}toListPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/list/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,path:this.toSourcePath(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new o(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new o(`EACCES`,`da access denied`,e);if(i.status>=400)throw new o(`EIO`,`da readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),s=a?Number(a):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new o(`EFBIG`,`body exceeds maxBodyBytes`,e);let c=new Uint8Array(await i.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new o(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``,u=l.startsWith(`W/`)?l.slice(2):l;return await this.cache.putBody(t,c,u),c}async writeFile(e,t){if(this.assertOpen(e),t.byteLength>this.maxBodyBytes)throw new o(`EFBIG`,`body exceeds maxBodyBytes`,e);let n=this.toMountRelative(e),r=await this.cache.getBody(n),i=u(d(e),s(e),t),a={"content-type":i.contentType,"content-length":String(i.body.byteLength)};r?.etag?a[`if-match`]=r.etag.startsWith(`W/`)?r.etag.slice(2):r.etag:r||(a[`if-none-match`]=`*`);let c=()=>this.transport({method:`POST`,path:this.toSourcePath(n),headers:a,body:i.body}),l,f=1;try{l=await c()}catch{f=2,l=await c()}if(l.status===412){if(f===2){let r=await this.transport({method:`HEAD`,path:this.toSourcePath(n)});if(r.status>=400)throw new o(`EIO`,`da reconcile HEAD failed: ${r.status}`,e);let i=r.headers.get(`etag`)??``;await this.cache.putBody(n,t,i);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new o(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(l.status===401||l.status===403)throw new o(`EACCES`,`da write denied`,e);if(l.status>=400)throw new o(`EIO`,`da writeFile failed: ${l.status}`,e);let p=l.headers.get(`etag`)??``;await this.cache.putBody(n,t,p);let m=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(m)}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.transport({method:`GET`,path:this.toListPath(t)});if(r.status===404)throw new o(`ENOENT`,`no such directory`,e);if(r.status>=400)throw new o(`EIO`,`da list failed: ${r.status}`,e);let i=(await r.json()).map(e=>e.ext?{name:`${e.name}.${e.ext}`,kind:`file`,etag:e.etag,lastModified:e.lastModified}:{name:e.name,kind:`directory`,lastModified:e.lastModified});return await this.cache.putListing(t,i),i}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.size,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),s=await this.cache.getListing(a);if(s&&!this.cache.isStale(s.cachedAt)){let t=s.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??s.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??s.cachedAt};if(!t)throw new o(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,path:this.toSourcePath(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`),r=n?Date.parse(n):0;if(s){let n=s.entries.map(n=>n.name===i&&n.kind===`file`?{...n,size:e,etag:t,lastModified:r}:n);await this.cache.putListing(a,n)}return{kind:`file`,size:e,mtime:r,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new o(`ENOENT`,`no such file or directory`,e)}throw new o(`EIO`,`da stat failed: ${c.status}`,e)}async mkdir(e){}async remove(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.transport({method:`DELETE`,path:this.toSourcePath(t)});if(n.status===404)throw new o(`ENOENT`,`no such file`,e);if(n.status===401||n.status===403)throw new o(`EACCES`,`da delete denied`,e);if(n.status>=400)throw new o(`EIO`,`da delete failed: ${n.status}`,e);await this.cache.invalidateBody(t);let r=t.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(r)}async refresh(e){this.assertOpen(`/`);let t={added:[],removed:[],changed:[],unchanged:0,errors:[]},n=[``];for(;n.length>0;){let e=n.pop();try{await this.refreshDir(e,t,n)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}}return e?.bodies&&await this.refreshBodies(t),t}async classifyFile(e,t,n){let r=await this.cache.getBody(e);r?t&&r.etag!==t?(await this.cache.invalidateBody(e),n.changed.push(e)):n.unchanged++:n.added.push(e)}async refreshDir(e,t,n){let r=await this.transport({method:`GET`,path:this.toListPath(e)});if(r.status>=400){t.errors.push({path:e,message:`list failed: ${r.status}`});return}let i=await r.json(),a=[];for(let r of i)if(r.ext){let n=e?`${e}/${r.name}.${r.ext}`:`${r.name}.${r.ext}`;a.push({name:`${r.name}.${r.ext}`,kind:`file`,etag:r.etag,lastModified:r.lastModified}),await this.classifyFile(n,r.etag,t)}else a.push({name:r.name,kind:`directory`}),n.push(e?`${e}/${r.name}`:r.name);await this.cache.putListing(e,a)}async refreshBodies(e){for(let t of e.changed)try{await this.readFile(t)}catch(n){e.errors.push({path:t,message:n instanceof Error?n.message:String(n)})}}describe(){return{displayName:`${this.parsed.org}/${this.parsed.repo}${this.parsed.path?`/${this.parsed.path}`:``}`,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function m(e){let t=e.match(/^s3:\/\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid S3 source '${e}' — expected s3://bucket[/prefix]`);return{bucket:t[1],prefix:(t[2]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var h=class{kind=`s3`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=m(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??26214400,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new o(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toS3Key(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``);return[this.parsed.prefix,t].filter(e=>e.length>0).join(`/`)}toMountRelativeKey(e){return this.parsed.prefix?e.slice(this.parsed.prefix.length+1):e}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:this.toS3Key(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new o(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new o(`EACCES`,`s3 access denied`,e);if(i.status>=400)throw new o(`EIO`,`s3 readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),s=a?Number(a):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new o(`EFBIG`,`body exceeds maxBodyBytes (${s} > ${this.maxBodyBytes})`,e);let c=new Uint8Array(await i.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new o(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``;return await this.cache.putBody(t,c,l),c}async writeFile(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t.byteLength>this.maxBodyBytes)throw new o(`EFBIG`,`body exceeds maxBodyBytes`,e);let r=await this.cache.getBody(n),i={"content-type":`application/octet-stream`,"content-length":String(t.byteLength)};r?i[`if-match`]=r.etag:i[`if-none-match`]=`*`;let a=()=>this.transport({method:`PUT`,bucket:this.parsed.bucket,key:this.toS3Key(n),headers:i,body:t}),s,c=1;try{s=await a()}catch{c=2,s=await a()}if(s.status===412){if(c===2){let r=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status>=400)throw new o(`EIO`,`s3 reconcile HEAD failed: ${r.status}`,e);let i=r.headers.get(`etag`)??``;await this.cache.putBody(n,t,i);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new o(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(s.status===401||s.status===403)throw new o(`EACCES`,`s3 write denied`,e);if(s.status>=400)throw new o(`EIO`,`s3 writeFile failed: ${s.status}`,e);let l=s.headers.get(`etag`)??``;await this.cache.putBody(n,t,l);let u=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(u)}async listObjectsV2(){let e=[],t;do{let n={"list-type":`2`};this.parsed.prefix&&(n.prefix=`${this.parsed.prefix}/`),t&&(n[`continuation-token`]=t);let r=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:``,query:n});if(r.status>=400)throw new o(`EIO`,`s3 list failed: ${r.status}`,`/`);let i=await r.text(),a=this.parseListingXml(i);e.push(...a.contents),t=a.nextContinuationToken}while(t);return e}parseListingXml(e){let t=[];for(let n of e.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)){let e=n[1],r=e.match(/<Key>([^<]+)<\/Key>/)?.[1]??``,i=e.match(/<ETag>([^<]+)<\/ETag>/)?.[1]??``,a=e.match(/<Size>([^<]+)<\/Size>/)?.[1]??`0`,o=e.match(/<LastModified>([^<]+)<\/LastModified>/)?.[1]??``;t.push({key:r,etag:i,size:Number(a),lastModified:o?Date.parse(o):0})}return{contents:t,nextContinuationToken:e.match(/<IsTruncated>([^<]+)<\/IsTruncated>/)?.[1]===`true`?e.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]:void 0}}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.listObjectsV2(),i=this.groupByDir(r);for(let[e,t]of i)await this.cache.putListing(e,t);return i.get(t)??[]}groupByDir(e){let t=new Map,n=e=>(t.has(e)||t.set(e,[]),t.get(e));n(``);for(let t of e){let e=this.toMountRelativeKey(t.key).split(`/`),r=e.pop();n(e.join(`/`)).push({name:r,kind:`file`,size:t.size,etag:t.etag,lastModified:t.lastModified});let i=``;for(let t of e){let e=i;i=i?`${i}/${t}`:t;let r=n(e);r.find(e=>e.name===t&&e.kind===`directory`)||r.push({name:t,kind:`directory`}),n(i)}}return t}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.body.byteLength,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),s=await this.cache.getListing(a);if(s&&!this.cache.isStale(s.cachedAt)){let t=s.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??s.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??s.cachedAt};if(!t)throw new o(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`);return{kind:`file`,size:e,mtime:n?Date.parse(n):0,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new o(`ENOENT`,`no such file or directory`,e)}throw new o(`EIO`,`s3 stat failed: ${c.status}`,e)}async refresh(e){this.assertOpen(`/`);let t=await this.listObjectsV2(),n=new Set(t.map(e=>this.toMountRelativeKey(e.key))),r=new Map(t.map(e=>[this.toMountRelativeKey(e.key),e.etag])),i={added:[],removed:[],changed:[],unchanged:0,errors:[]};for(let e of n){let t=await this.cache.getBody(e),n=r.get(e);t?t.etag===n?i.unchanged++:(await this.cache.invalidateBody(e),i.changed.push(e)):i.added.push(e)}let a=this.groupByDir(t);for(let[e,t]of a)await this.cache.putListing(e,t);if(e?.bodies)for(let e of i.changed)try{await this.readFile(e)}catch(t){i.errors.push({path:e,message:t instanceof Error?t.message:String(t)})}return i}async mkdir(e){}async remove(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t?.recursive)throw new o(`EINVAL`,`recursive remove not yet supported on S3`,e);let r=await this.transport({method:`DELETE`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status===404)throw new o(`ENOENT`,`no such file`,e);if(r.status===401||r.status===403)throw new o(`EACCES`,`s3 delete denied`,e);if(r.status>=400)throw new o(`EIO`,`s3 delete failed: ${r.status}`,e);await this.cache.invalidateBody(n);let i=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(i)}describe(){return{displayName:this.parsed.prefix?`${this.parsed.bucket}/${this.parsed.prefix}`:this.parsed.bucket,source:this.source,profile:this.profile}}async close(){this.closed||=!0}},g=class extends Error{constructor(e){super(e),this.name=`ProfileNotConfiguredError`}};async function _(){let{getAccounts:e}=await import(`./account-store-BSEcudvg.js`).then(e=>e.n),t=e().find(e=>e.providerId===`adobe`);if(!t?.accessToken)throw new g(`No Adobe IMS account found. Log in via Settings → Providers → Adobe first.`);return{identity:`adobe-ims`,getBearerToken:async()=>t.accessToken}}const v=l({portName:`mount.sign-and-forward`,panelRpcOp:`mount-sign-and-forward`,timeoutMs:12e4,onUnavailable:`reject`,makeError:e=>new o(`EIO`,`mount transport failed: ${e}`),logNamespace:`mount-bridge`,toPortMessage:({type:e,envelope:t})=>({type:e,envelope:t}),toPanelRpcPayload:({type:e,envelope:t})=>({type:e,envelope:t})});function y(e,t){return v({type:e,envelope:t})}function b(){return typeof chrome<`u`&&!!chrome?.runtime?.id}const x=n,S=t,C=new Set([`invalid_profile`,`invalid_request`,`profile_not_configured`,`fetch_failed`,`internal`]),w=new Set([101,103,204,205,304]);function T(e){if(!e.ok)throw e.errorCode===`profile_not_configured`||e.errorCode===`invalid_profile`?new o(`EACCES`,e.error):e.errorCode===`invalid_request`?new o(`EINVAL`,e.error):e.errorCode===`fetch_failed`||e.errorCode===`internal`||C.has(String(e.errorCode))?new o(`EIO`,e.error):new o(`EINVAL`,`mount transport returned unrecognized errorCode '${e.errorCode}': ${e.error}`);let t;try{t=x(e.bodyBase64)}catch(e){throw new o(`EIO`,`mount transport: response body decode failed: ${e instanceof Error?e.message:String(e)}`)}let n=w.has(e.status)?null:t;return new Response(n,{status:e.status,headers:new Headers(e.headers)})}async function E(e,t){let n;try{n=await fetch(r(e),{method:`POST`,headers:a({"content-type":`application/json`}),body:JSON.stringify(t)})}catch(e){throw new o(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (SLICC backend at localhost may not be running)`)}try{return await n.json()}catch(e){throw new o(`EIO`,`mount transport: response is not a JSON envelope (status ${n.status}): ${e instanceof Error?e.message:String(e)}`)}}async function D(e,t){try{return await chrome.runtime.sendMessage({type:e,envelope:t})}catch(e){throw new o(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (extension service worker not responding)`)}}async function O(e,t,n){return b()?D(e,n):i()?y(e,n):E(t,n)}function k(e){return async t=>T(await O(`mount.s3-sign-and-forward`,`/api/s3-sign-and-forward`,{profile:e,method:t.method,bucket:t.bucket,key:t.key,query:t.query,headers:t.headers,bodyBase64:t.body?S(t.body):void 0}))}function A(e){let t=e?.getImsToken??(async()=>(await _()).getBearerToken());return async e=>{let n;try{n=await t()}catch(e){throw new o(`EACCES`,`DA mount: ${e instanceof Error?e.message:String(e)}`)}return T(await O(`mount.da-sign-and-forward`,`/api/da-sign-and-forward`,{imsToken:n,method:e.method,path:e.path,query:e.query,headers:e.headers,bodyBase64:e.body?S(e.body):void 0}))}}var j=e({DaMountBackend:()=>p,RemoteMountCache:()=>c,S3MountBackend:()=>h,makeSignedFetchDa:()=>A,makeSignedFetchS3:()=>k});export{p as a,h as i,A as n,k as r,j as t};
|
|
1
|
+
import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{_ as t,g as n,o as r,r as i,t as a}from"./proxied-fetch-BVw2cmL4.js";import"./backend-local-mrUgrni5.js";import{t as o}from"./types-idfTVsM8.js";import{t as s}from"./mime-types-BqLkKWa7.js";import{t as c}from"./remote-cache-D59F5FOx.js";import{t as l}from"./port-bridge-client-vT8ubtB-.js";function u(e,t,n){let r=`----DaMount${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,i=new TextEncoder,a=i.encode(`--${r}\r\nContent-Disposition: form-data; name="data"; filename="${e}"\r\nContent-Type: ${t}\r\n\r\n`),o=i.encode(`\r\n--${r}--\r\n`),s=new Uint8Array(a.byteLength+n.byteLength+o.byteLength);return s.set(a,0),s.set(n,a.byteLength),s.set(o,a.byteLength+n.byteLength),{contentType:`multipart/form-data; boundary=${r}`,body:s}}function d(e){return e.split(`/`).pop()||`data`}function f(e){let t=e.match(/^da:\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid DA source '${e}' — expected da://org/repo[/path]`);return{org:t[1],repo:t[2],path:(t[3]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var p=class{kind=`da`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=f(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??5242880,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new o(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toSourcePath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/source/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}toListPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/list/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,path:this.toSourcePath(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new o(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new o(`EACCES`,`da access denied`,e);if(i.status>=400)throw new o(`EIO`,`da readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),s=a?Number(a):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new o(`EFBIG`,`body exceeds maxBodyBytes`,e);let c=new Uint8Array(await i.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new o(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``,u=l.startsWith(`W/`)?l.slice(2):l;return await this.cache.putBody(t,c,u),c}async writeFile(e,t){if(this.assertOpen(e),t.byteLength>this.maxBodyBytes)throw new o(`EFBIG`,`body exceeds maxBodyBytes`,e);let n=this.toMountRelative(e),r=await this.cache.getBody(n),i=u(d(e),s(e),t),a={"content-type":i.contentType,"content-length":String(i.body.byteLength)};r?.etag?a[`if-match`]=r.etag.startsWith(`W/`)?r.etag.slice(2):r.etag:r||(a[`if-none-match`]=`*`);let c=()=>this.transport({method:`POST`,path:this.toSourcePath(n),headers:a,body:i.body}),l,f=1;try{l=await c()}catch{f=2,l=await c()}if(l.status===412){if(f===2){let r=await this.transport({method:`HEAD`,path:this.toSourcePath(n)});if(r.status>=400)throw new o(`EIO`,`da reconcile HEAD failed: ${r.status}`,e);let i=r.headers.get(`etag`)??``;await this.cache.putBody(n,t,i);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new o(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(l.status===401||l.status===403)throw new o(`EACCES`,`da write denied`,e);if(l.status>=400)throw new o(`EIO`,`da writeFile failed: ${l.status}`,e);let p=l.headers.get(`etag`)??``;await this.cache.putBody(n,t,p);let m=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(m)}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.transport({method:`GET`,path:this.toListPath(t)});if(r.status===404)throw new o(`ENOENT`,`no such directory`,e);if(r.status>=400)throw new o(`EIO`,`da list failed: ${r.status}`,e);let i=(await r.json()).map(e=>e.ext?{name:`${e.name}.${e.ext}`,kind:`file`,etag:e.etag,lastModified:e.lastModified}:{name:e.name,kind:`directory`,lastModified:e.lastModified});return await this.cache.putListing(t,i),i}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.size,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),s=await this.cache.getListing(a);if(s&&!this.cache.isStale(s.cachedAt)){let t=s.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??s.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??s.cachedAt};if(!t)throw new o(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,path:this.toSourcePath(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`),r=n?Date.parse(n):0;if(s){let n=s.entries.map(n=>n.name===i&&n.kind===`file`?{...n,size:e,etag:t,lastModified:r}:n);await this.cache.putListing(a,n)}return{kind:`file`,size:e,mtime:r,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new o(`ENOENT`,`no such file or directory`,e)}throw new o(`EIO`,`da stat failed: ${c.status}`,e)}async mkdir(e){}async remove(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.transport({method:`DELETE`,path:this.toSourcePath(t)});if(n.status===404)throw new o(`ENOENT`,`no such file`,e);if(n.status===401||n.status===403)throw new o(`EACCES`,`da delete denied`,e);if(n.status>=400)throw new o(`EIO`,`da delete failed: ${n.status}`,e);await this.cache.invalidateBody(t);let r=t.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(r)}async refresh(e){this.assertOpen(`/`);let t={added:[],removed:[],changed:[],unchanged:0,errors:[]},n=[``];for(;n.length>0;){let e=n.pop();try{await this.refreshDir(e,t,n)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}}return e?.bodies&&await this.refreshBodies(t),t}async classifyFile(e,t,n){let r=await this.cache.getBody(e);r?t&&r.etag!==t?(await this.cache.invalidateBody(e),n.changed.push(e)):n.unchanged++:n.added.push(e)}async refreshDir(e,t,n){let r=await this.transport({method:`GET`,path:this.toListPath(e)});if(r.status>=400){t.errors.push({path:e,message:`list failed: ${r.status}`});return}let i=await r.json(),a=[];for(let r of i)if(r.ext){let n=e?`${e}/${r.name}.${r.ext}`:`${r.name}.${r.ext}`;a.push({name:`${r.name}.${r.ext}`,kind:`file`,etag:r.etag,lastModified:r.lastModified}),await this.classifyFile(n,r.etag,t)}else a.push({name:r.name,kind:`directory`}),n.push(e?`${e}/${r.name}`:r.name);await this.cache.putListing(e,a)}async refreshBodies(e){for(let t of e.changed)try{await this.readFile(t)}catch(n){e.errors.push({path:t,message:n instanceof Error?n.message:String(n)})}}describe(){return{displayName:`${this.parsed.org}/${this.parsed.repo}${this.parsed.path?`/${this.parsed.path}`:``}`,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function m(e){let t=e.match(/^s3:\/\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid S3 source '${e}' — expected s3://bucket[/prefix]`);return{bucket:t[1],prefix:(t[2]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var h=class{kind=`s3`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=m(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??26214400,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new o(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toS3Key(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``);return[this.parsed.prefix,t].filter(e=>e.length>0).join(`/`)}toMountRelativeKey(e){return this.parsed.prefix?e.slice(this.parsed.prefix.length+1):e}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:this.toS3Key(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new o(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new o(`EACCES`,`s3 access denied`,e);if(i.status>=400)throw new o(`EIO`,`s3 readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),s=a?Number(a):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new o(`EFBIG`,`body exceeds maxBodyBytes (${s} > ${this.maxBodyBytes})`,e);let c=new Uint8Array(await i.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new o(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``;return await this.cache.putBody(t,c,l),c}async writeFile(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t.byteLength>this.maxBodyBytes)throw new o(`EFBIG`,`body exceeds maxBodyBytes`,e);let r=await this.cache.getBody(n),i={"content-type":`application/octet-stream`,"content-length":String(t.byteLength)};r?i[`if-match`]=r.etag:i[`if-none-match`]=`*`;let a=()=>this.transport({method:`PUT`,bucket:this.parsed.bucket,key:this.toS3Key(n),headers:i,body:t}),s,c=1;try{s=await a()}catch{c=2,s=await a()}if(s.status===412){if(c===2){let r=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status>=400)throw new o(`EIO`,`s3 reconcile HEAD failed: ${r.status}`,e);let i=r.headers.get(`etag`)??``;await this.cache.putBody(n,t,i);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new o(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(s.status===401||s.status===403)throw new o(`EACCES`,`s3 write denied`,e);if(s.status>=400)throw new o(`EIO`,`s3 writeFile failed: ${s.status}`,e);let l=s.headers.get(`etag`)??``;await this.cache.putBody(n,t,l);let u=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(u)}async listObjectsV2(){let e=[],t;do{let n={"list-type":`2`};this.parsed.prefix&&(n.prefix=`${this.parsed.prefix}/`),t&&(n[`continuation-token`]=t);let r=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:``,query:n});if(r.status>=400)throw new o(`EIO`,`s3 list failed: ${r.status}`,`/`);let i=await r.text(),a=this.parseListingXml(i);e.push(...a.contents),t=a.nextContinuationToken}while(t);return e}parseListingXml(e){let t=[];for(let n of e.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)){let e=n[1],r=e.match(/<Key>([^<]+)<\/Key>/)?.[1]??``,i=e.match(/<ETag>([^<]+)<\/ETag>/)?.[1]??``,a=e.match(/<Size>([^<]+)<\/Size>/)?.[1]??`0`,o=e.match(/<LastModified>([^<]+)<\/LastModified>/)?.[1]??``;t.push({key:r,etag:i,size:Number(a),lastModified:o?Date.parse(o):0})}return{contents:t,nextContinuationToken:e.match(/<IsTruncated>([^<]+)<\/IsTruncated>/)?.[1]===`true`?e.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]:void 0}}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.listObjectsV2(),i=this.groupByDir(r);for(let[e,t]of i)await this.cache.putListing(e,t);return i.get(t)??[]}groupByDir(e){let t=new Map,n=e=>(t.has(e)||t.set(e,[]),t.get(e));n(``);for(let t of e){let e=this.toMountRelativeKey(t.key).split(`/`),r=e.pop();n(e.join(`/`)).push({name:r,kind:`file`,size:t.size,etag:t.etag,lastModified:t.lastModified});let i=``;for(let t of e){let e=i;i=i?`${i}/${t}`:t;let r=n(e);r.find(e=>e.name===t&&e.kind===`directory`)||r.push({name:t,kind:`directory`}),n(i)}}return t}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.body.byteLength,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),s=await this.cache.getListing(a);if(s&&!this.cache.isStale(s.cachedAt)){let t=s.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??s.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??s.cachedAt};if(!t)throw new o(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`);return{kind:`file`,size:e,mtime:n?Date.parse(n):0,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new o(`ENOENT`,`no such file or directory`,e)}throw new o(`EIO`,`s3 stat failed: ${c.status}`,e)}async refresh(e){this.assertOpen(`/`);let t=await this.listObjectsV2(),n=new Set(t.map(e=>this.toMountRelativeKey(e.key))),r=new Map(t.map(e=>[this.toMountRelativeKey(e.key),e.etag])),i={added:[],removed:[],changed:[],unchanged:0,errors:[]};for(let e of n){let t=await this.cache.getBody(e),n=r.get(e);t?t.etag===n?i.unchanged++:(await this.cache.invalidateBody(e),i.changed.push(e)):i.added.push(e)}let a=this.groupByDir(t);for(let[e,t]of a)await this.cache.putListing(e,t);if(e?.bodies)for(let e of i.changed)try{await this.readFile(e)}catch(t){i.errors.push({path:e,message:t instanceof Error?t.message:String(t)})}return i}async mkdir(e){}async remove(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t?.recursive)throw new o(`EINVAL`,`recursive remove not yet supported on S3`,e);let r=await this.transport({method:`DELETE`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status===404)throw new o(`ENOENT`,`no such file`,e);if(r.status===401||r.status===403)throw new o(`EACCES`,`s3 delete denied`,e);if(r.status>=400)throw new o(`EIO`,`s3 delete failed: ${r.status}`,e);await this.cache.invalidateBody(n);let i=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(i)}describe(){return{displayName:this.parsed.prefix?`${this.parsed.bucket}/${this.parsed.prefix}`:this.parsed.bucket,source:this.source,profile:this.profile}}async close(){this.closed||=!0}},g=class extends Error{constructor(e){super(e),this.name=`ProfileNotConfiguredError`}};async function _(){let{getAccounts:e}=await import(`./account-store-CWYCPgAg.js`).then(e=>e.n),t=e().find(e=>e.providerId===`adobe`);if(!t?.accessToken)throw new g(`No Adobe IMS account found. Log in via Settings → Providers → Adobe first.`);return{identity:`adobe-ims`,getBearerToken:async()=>t.accessToken}}const v=l({portName:`mount.sign-and-forward`,panelRpcOp:`mount-sign-and-forward`,timeoutMs:12e4,onUnavailable:`reject`,makeError:e=>new o(`EIO`,`mount transport failed: ${e}`),logNamespace:`mount-bridge`,toPortMessage:({type:e,envelope:t})=>({type:e,envelope:t}),toPanelRpcPayload:({type:e,envelope:t})=>({type:e,envelope:t})});function y(e,t){return v({type:e,envelope:t})}function b(){return typeof chrome<`u`&&!!chrome?.runtime?.id}const x=n,S=t,C=new Set([`invalid_profile`,`invalid_request`,`profile_not_configured`,`fetch_failed`,`internal`]),w=new Set([101,103,204,205,304]);function T(e){if(!e.ok)throw e.errorCode===`profile_not_configured`||e.errorCode===`invalid_profile`?new o(`EACCES`,e.error):e.errorCode===`invalid_request`?new o(`EINVAL`,e.error):e.errorCode===`fetch_failed`||e.errorCode===`internal`||C.has(String(e.errorCode))?new o(`EIO`,e.error):new o(`EINVAL`,`mount transport returned unrecognized errorCode '${e.errorCode}': ${e.error}`);let t;try{t=x(e.bodyBase64)}catch(e){throw new o(`EIO`,`mount transport: response body decode failed: ${e instanceof Error?e.message:String(e)}`)}let n=w.has(e.status)?null:t;return new Response(n,{status:e.status,headers:new Headers(e.headers)})}async function E(e,t){let n;try{n=await fetch(r(e),{method:`POST`,headers:a({"content-type":`application/json`}),body:JSON.stringify(t)})}catch(e){throw new o(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (SLICC backend at localhost may not be running)`)}try{return await n.json()}catch(e){throw new o(`EIO`,`mount transport: response is not a JSON envelope (status ${n.status}): ${e instanceof Error?e.message:String(e)}`)}}async function D(e,t){try{return await chrome.runtime.sendMessage({type:e,envelope:t})}catch(e){throw new o(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (extension service worker not responding)`)}}async function O(e,t,n){return b()?D(e,n):i()?y(e,n):E(t,n)}function k(e){return async t=>T(await O(`mount.s3-sign-and-forward`,`/api/s3-sign-and-forward`,{profile:e,method:t.method,bucket:t.bucket,key:t.key,query:t.query,headers:t.headers,bodyBase64:t.body?S(t.body):void 0}))}function A(e){let t=e?.getImsToken??(async()=>(await _()).getBearerToken());return async e=>{let n;try{n=await t()}catch(e){throw new o(`EACCES`,`DA mount: ${e instanceof Error?e.message:String(e)}`)}return T(await O(`mount.da-sign-and-forward`,`/api/da-sign-and-forward`,{imsToken:n,method:e.method,path:e.path,query:e.query,headers:e.headers,bodyBase64:e.body?S(e.body):void 0}))}}var j=e({DaMountBackend:()=>p,RemoteMountCache:()=>c,S3MountBackend:()=>h,makeSignedFetchDa:()=>A,makeSignedFetchS3:()=>k});export{p as a,h as i,A as n,k as r,j as t};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/quick-llm-
|
|
2
|
-
import{t as e}from"./preload-helper-CZgWQFsJ.js";import{F as t,m as n}from"./account-store-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/quick-llm-C3DL1kkz.js","assets/rolldown-runtime-aKtaBQYM.js","assets/compat-DADQxxLV.js","assets/models-ByRUWfA-.js","assets/preload-helper-CZgWQFsJ.js","assets/provider-env-D37PhSJu.js","assets/__vite-browser-external-SwrSgYTf.js","assets/account-store-Bk7BU4R2.js","assets/context-compaction-DaxQExZG.js","assets/logger-DDBAeTLF.js","assets/src-BdPw21ST.js","assets/proxied-fetch-iGqLvoxh.js","assets/fetch-body-D2PwksUW.js","assets/secret-topology-DnYeyyJY.js","assets/secrets-bridge-client-x_puVSDN.js","assets/port-bridge-client-BJ5rcoKH.js","assets/tool-ui-DfXu6quJ.js","assets/providers-BrRzKc33.js","assets/panel-rpc-DmJSNs0I.js","assets/bedrock-camp-DbZ6Mjym.js","assets/transform-messages-D7OsqBmU.js","assets/llm-session-id-bZQs6gBN.js","assets/icons-C5g936Qd.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as e}from"./preload-helper-CZgWQFsJ.js";import{F as t,m as n}from"./account-store-Bk7BU4R2.js";import{t as r}from"./logger-DDBAeTLF.js";import"./main-DVF1KaMV.js";import{t as i}from"./llm-session-id-bZQs6gBN.js";import{SessionStore as a}from"./session-store-DAM8GRJ0.js";import{a as o,i as s}from"./wc-live-DQFQdors.js";var c=r(`new-session`),l=`ui-new-session`,u=2e4,d=250;async function f(r){let d=r.enrichmentRaceMs??u,f=n()??void 0,m;try{m=t()}catch(e){c.info(`No active model — freezing without LLM enrichment`,{error:e instanceof Error?e.message:String(e)})}let h=m?.provider===`adobe`?{"X-Session-Id":i(l)}:void 0,g=new a;try{await g.init()}catch(e){return c.warn(`SessionStore init failed — cannot freeze`,{error:e instanceof Error?e.message:String(e)}),null}let _=await o({sessionStore:g,vfs:r.vfs,mode:`quick`});if(!_)return null;if(!f||!m)return c.info(`Frozen without enrichment (no LLM credentials) — left pending`,{filename:_.filename}),_;let v=m,y=s(r.vfs,_,{model:v,apiKey:f,headers:h,pickIcon:t=>e(async()=>{let{pickLucideIcon:e}=await import(`./quick-llm-C3DL1kkz.js`).then(e=>e.n);return{pickLucideIcon:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22])).then(({pickLucideIcon:e})=>e(t))}).catch(e=>(c.warn(`Single-click enrichment threw (entry stays pending)`,{filename:_.filename,error:e instanceof Error?e.message:String(e)}),null)),b=await p(y,d,r.onProgress);return b.kind===`llm`?b.updated?{...b.updated,archive:_.archive}:_:(y.then(e=>{c.info(`Background enrichment resolved after race window`,{filename:_.filename,enriched:e?.filename??null}),r.onBackgroundEnriched?.(e)}),_)}async function p(e,t,n){let r=Date.now(),i,a;n?.(0),n&&(i=setInterval(()=>{n(Math.min(1,(Date.now()-r)/t))},d));let o=new Promise(e=>{a=setTimeout(()=>e({kind:`timer`}),t)}),s=e.then(e=>({kind:`llm`,updated:e}));try{return await Promise.race([s,o])}finally{i&&clearInterval(i),a&&clearTimeout(a),n?.(null)}}async function m(e){let t=new a;try{await t.init()}catch(e){return c.warn(`SessionStore init failed — cannot quick-freeze`,{error:e instanceof Error?e.message:String(e)}),null}return o({sessionStore:t,vfs:e.vfs,mode:`quick`})}export{f as runNewSessionFreeze,m as runNewSessionFreezeQuick};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/provider-
|
|
2
|
-
import{t as e}from"./preload-helper-CZgWQFsJ.js";import{R as t,d as n}from"./account-store-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/provider-CDfndD9E.js","assets/preload-helper-CZgWQFsJ.js","assets/account-store-Bk7BU4R2.js","assets/rolldown-runtime-aKtaBQYM.js","assets/compat-DADQxxLV.js","assets/models-ByRUWfA-.js","assets/provider-env-D37PhSJu.js","assets/__vite-browser-external-SwrSgYTf.js","assets/context-compaction-DaxQExZG.js","assets/logger-DDBAeTLF.js","assets/src-BdPw21ST.js","assets/proxied-fetch-iGqLvoxh.js","assets/fetch-body-D2PwksUW.js","assets/secret-topology-DnYeyyJY.js","assets/secrets-bridge-client-x_puVSDN.js","assets/port-bridge-client-BJ5rcoKH.js","assets/tool-ui-DfXu6quJ.js","assets/providers-BrRzKc33.js","assets/panel-rpc-DmJSNs0I.js","assets/bedrock-camp-DbZ6Mjym.js","assets/transform-messages-D7OsqBmU.js","assets/global-db-CbuLl-zx.js","assets/types-idfTVsM8.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as e}from"./preload-helper-CZgWQFsJ.js";import{R as t,d as n}from"./account-store-Bk7BU4R2.js";import{t as r}from"./logger-DDBAeTLF.js";import{t as i}from"./providers-BrRzKc33.js";import"./main-DVF1KaMV.js";var a=r(`oauth-bootstrap`),o=6e4;async function s(){try{let{ensureAllMcpProvidersRegistered:t}=await e(async()=>{let{ensureAllMcpProvidersRegistered:e}=await import(`./provider-CDfndD9E.js`);return{ensureAllMcpProvidersRegistered:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22])),n=await t();n.length>0&&a.debug(`Pre-registered MCP providers for OAuth bootstrap`,{count:n.length})}catch(e){a.warn(`Failed to pre-register MCP providers for OAuth bootstrap`,{error:e instanceof Error?e.message:String(e)})}let r=n();a.info(`Bootstrap OAuth replicas`,{count:r.length});for(let e of r){if(!e.accessToken){a.debug(`Skipping account without token`,{providerId:e.providerId});continue}if((e.tokenExpiresAt??1/0)-Date.now()<=o){let t=i(e.providerId);if(t?.onSilentRenew)try{if(await t.onSilentRenew()){a.info(`Silently renewed OAuth token`,{providerId:e.providerId});continue}a.warn(`Silent renewal yielded no token; user must re-authenticate`,{providerId:e.providerId});continue}catch(t){a.warn(`Silent renewal failed`,{providerId:e.providerId,error:t instanceof Error?t.message:String(t)});continue}a.debug(`Skipping expired account (no silent-renew hook)`,{providerId:e.providerId});continue}try{await t({providerId:e.providerId,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenExpiresAt:e.tokenExpiresAt,userName:e.userName,userAvatar:e.userAvatar}),a.debug(`Bootstrapped OAuth replica`,{providerId:e.providerId})}catch(t){a.error(`OAuth bootstrap failed`,{providerId:e.providerId,error:t instanceof Error?t.message:String(t)})}}}export{s as bootstrapOAuthReplicas};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{O as e,i as t}from"./account-store-
|
|
1
|
+
import{O as e,i as t}from"./account-store-CWYCPgAg.js";import{f as n}from"./transform-messages-CQuDksPz.js";import{f as r,h as i,y as a}from"./bedrock-camp-DVKDCEuf.js";import"./kernel-worker-DZdJjW09.js";const o=`openai-codex`,s=`app_EMoamEEZ73f0CkXaXp7hrann`,c=`https://auth.openai.com/oauth/token`,l=`http://localhost:1455/auth/callback`,u=`https://chatgpt.com/backend-api`,d=`openai-codex-responses`,f=`${o}-openai`,p={xhigh:`xhigh`,minimal:`low`},m=[{id:`gpt-5.5`,name:`GPT-5.5`,input:[`text`,`image`]},{id:`gpt-5.4`,name:`GPT-5.4`,input:[`text`,`image`]},{id:`gpt-5.4-mini`,name:`GPT-5.4 mini`,input:[`text`,`image`]},{id:`gpt-5.3-codex`,name:`GPT-5.3 Codex`,input:[`text`,`image`]},{id:`gpt-5.3-codex-spark`,name:`GPT-5.3 Codex Spark`,input:[`text`]},{id:`gpt-5.2`,name:`GPT-5.2`,input:[`text`,`image`]}].map(e=>({...e,api:`openai`,reasoning:!0,context_window:272e3,max_tokens:128e3,thinkingLevelMap:p}));function h(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function g(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),t}function _(){return h(g(32))}async function v(e){let t=new TextEncoder().encode(e);return h(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}function y(){return h(g(16))}async function b(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,client_id:s,code:e,code_verifier:t,redirect_uri:l}),r=await fetch(c,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw Error(`OpenAI Codex token exchange failed: ${r.status} ${await r.text()}`);let i=await r.json();if(!i.access_token)throw Error(`OpenAI Codex token exchange did not return access_token.`);return i}async function x(e){try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:s}),n=await fetch(c,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});return n.ok?await n.json():(console.error(`[openai-codex] refresh failed:`,n.status,await n.text()),null)}catch(e){return console.error(`[openai-codex] refresh error:`,e instanceof Error?e.message:String(e)),null}}function S(e){try{let t=e.split(`.`);if(t.length!==3)return;let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`);return n.length%4&&(n+=`=`.repeat(4-n.length%4)),JSON.parse(atob(n))}catch{return}}function C(e){let t=S(e)?.[`https://api.openai.com/profile`];return typeof t?.email==`string`?t.email:void 0}function w(e){let t=S(e)?.[`https://api.openai.com/auth`],n=C(e),r=typeof t?.chatgpt_plan_type==`string`?t.chatgpt_plan_type:void 0,i=r?r.charAt(0).toUpperCase()+r.slice(1):void 0;if(n&&i)return`${n} (${i})`;if(n)return n;if(i)return`ChatGPT ${i}`}async function T(e){let t=C(e);if(t)try{let e=t.trim().toLowerCase(),n=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)));return`https://www.gravatar.com/avatar/${Array.from(n).map(e=>e.toString(16).padStart(2,`0`)).join(``)}?s=128&d=404`}catch{return}}function E(){return t().find(e=>e.providerId===o)}async function D(){let t=E();if(!t?.accessToken)throw Error("Not signed in to OpenAI Codex — run `oauth-token openai-codex` or /login");let n=t.tokenExpiresAt??0;if(n&&Date.now()+6e4<n)return t.accessToken;if(t.refreshToken){let n=await x(t.refreshToken);if(n?.access_token)return await e({providerId:o,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??3600)*1e3,baseUrl:u,userName:w(n.access_token),userAvatar:await T(n.access_token)}),n.access_token}return t.accessToken}function O(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:f,provider:o,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:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}const k=(e,t,r={})=>{let a=n();return(async()=>{try{let n=await D(),o=i({...e,baseUrl:u,api:d},t,{...r,apiKey:n,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),a.push(O(e,t)),a.end()}})(),a},A=(e,t,r)=>{let i=n();return(async()=>{try{let n=await D(),o=a({...e,baseUrl:u,api:d},t,{...r,apiKey:n,transport:`sse`});for await(let e of o)i.push(e);i.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),i.push(O(e,t)),i.end()}})(),i},j={id:o,name:`OpenAI Codex (ChatGPT Subscription)`,description:`GPT-5 Codex via your ChatGPT Plus/Pro/Business subscription — OAuth login, no API key needed. Default model is GPT-5.5.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`gpt-5.5`,oauthTokenDomains:[`chatgpt.com`,`*.chatgpt.com`,`auth.openai.com`,`api.openai.com`],getModelIds:()=>m,onOAuthLoginIntercepted:async(t,n,r)=>{let i=_(),a=await v(i),c=y(),d=new URL(`https://auth.openai.com/oauth/authorize`);d.searchParams.set(`response_type`,`code`),d.searchParams.set(`client_id`,s),d.searchParams.set(`redirect_uri`,l),d.searchParams.set(`scope`,r?.scopes??`openid profile email offline_access`),d.searchParams.set(`code_challenge`,a),d.searchParams.set(`code_challenge_method`,`S256`),d.searchParams.set(`state`,c),d.searchParams.set(`id_token_add_organizations`,`true`),d.searchParams.set(`codex_cli_simplified_flow`,`true`),d.searchParams.set(`originator`,`pi`);let f=await t({authorizeUrl:d.toString(),redirectUriPattern:`http://localhost:1455/auth/callback*`,onCapture:`close`});if(!f)throw Error(`OpenAI Codex OAuth login was cancelled or timed out`);let p=new URL(f),m=p.searchParams.get(`code`),h=p.searchParams.get(`state`);if(!m)throw Error(`OpenAI Codex OAuth redirect did not include a code`);if(h!==c)throw Error(`OpenAI Codex OAuth state mismatch — possible CSRF, aborting`);let g=await b(m,i);await e({providerId:o,accessToken:g.access_token,refreshToken:g.refresh_token,tokenExpiresAt:Date.now()+(g.expires_in??3600)*1e3,baseUrl:u,userName:w(g.access_token),userAvatar:await T(g.access_token)}),n()},onOAuthLogout:async()=>{await e({providerId:o,accessToken:``})},onSilentRenew:async()=>{let t=E();if(!t?.refreshToken)return null;let n=await x(t.refreshToken);return n?.access_token?(await e({providerId:o,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??3600)*1e3,baseUrl:u,userName:w(n.access_token),userAvatar:await T(n.access_token)}),n.access_token):null}};function M(){r({api:f,stream:k,streamSimple:A})}export{j as config,M as register};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{s as e}from"./models-ByRUWfA-.js";import{a as t,d as n,s as r}from"./compat-DADQxxLV.js";import{R as i,d as a}from"./account-store-Bk7BU4R2.js";import"./main-DVF1KaMV.js";var o=`openai-codex`,s=`app_EMoamEEZ73f0CkXaXp7hrann`,c=`https://auth.openai.com/oauth/authorize`,l=`https://auth.openai.com/oauth/token`,u=`openid profile email offline_access`,d=`http://localhost:1455/auth/callback`,f=`http://localhost:1455/auth/callback*`,p=`https://chatgpt.com/backend-api`,m=`openai-codex-responses`,h=`${o}-openai`,g={xhigh:`xhigh`,minimal:`low`},_=[{id:`gpt-5.5`,name:`GPT-5.5`,input:[`text`,`image`]},{id:`gpt-5.4`,name:`GPT-5.4`,input:[`text`,`image`]},{id:`gpt-5.4-mini`,name:`GPT-5.4 mini`,input:[`text`,`image`]},{id:`gpt-5.3-codex`,name:`GPT-5.3 Codex`,input:[`text`,`image`]},{id:`gpt-5.3-codex-spark`,name:`GPT-5.3 Codex Spark`,input:[`text`]},{id:`gpt-5.2`,name:`GPT-5.2`,input:[`text`,`image`]}].map(e=>({...e,api:`openai`,reasoning:!0,context_window:272e3,max_tokens:128e3,thinkingLevelMap:g}));function v(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function y(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),t}function b(){return v(y(32))}async function x(e){let t=new TextEncoder().encode(e);return v(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}function S(){return v(y(16))}async function C(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,client_id:s,code:e,code_verifier:t,redirect_uri:d}),r=await fetch(l,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw Error(`OpenAI Codex token exchange failed: ${r.status} ${await r.text()}`);let i=await r.json();if(!i.access_token)throw Error(`OpenAI Codex token exchange did not return access_token.`);return i}async function w(e){try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:s}),n=await fetch(l,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});return n.ok?await n.json():(console.error(`[openai-codex] refresh failed:`,n.status,await n.text()),null)}catch(e){return console.error(`[openai-codex] refresh error:`,e instanceof Error?e.message:String(e)),null}}function T(e){try{let t=e.split(`.`);if(t.length!==3)return;let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`);return n.length%4&&(n+=`=`.repeat(4-n.length%4)),JSON.parse(atob(n))}catch{return}}function E(e){let t=T(e)?.[`https://api.openai.com/profile`];return typeof t?.email==`string`?t.email:void 0}function D(e){let t=T(e)?.[`https://api.openai.com/auth`],n=E(e),r=typeof t?.chatgpt_plan_type==`string`?t.chatgpt_plan_type:void 0,i=r?r.charAt(0).toUpperCase()+r.slice(1):void 0;if(n&&i)return`${n} (${i})`;if(n)return n;if(i)return`ChatGPT ${i}`}async function O(e){let t=E(e);if(t)try{let e=t.trim().toLowerCase(),n=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)));return`https://www.gravatar.com/avatar/${Array.from(n).map(e=>e.toString(16).padStart(2,`0`)).join(``)}?s=128&d=404`}catch{return}}function k(){return a().find(e=>e.providerId===o)}async function A(){let e=k();if(!e?.accessToken)throw Error("Not signed in to OpenAI Codex — run `oauth-token openai-codex` or /login");let t=e.tokenExpiresAt??0;if(t&&Date.now()+6e4<t)return e.accessToken;if(e.refreshToken){let t=await w(e.refreshToken);if(t?.access_token)return await i({providerId:o,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??3600)*1e3,baseUrl:p,userName:D(t.access_token),userAvatar:await O(t.access_token)}),t.access_token}return e.accessToken}function j(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:h,provider:o,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:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}var M=(t,n,i={})=>{let a=e();return(async()=>{try{let e=await A(),o=r({...t,baseUrl:p,api:m},n,{...i,apiKey:e,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(e){console.error(`[openai-codex] Stream error:`,e instanceof Error?e.message:String(e)),a.push(j(t,e)),a.end()}})(),a},N=(t,r,i)=>{let a=e();return(async()=>{try{let e=await A(),o=n({...t,baseUrl:p,api:m},r,{...i,apiKey:e,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(e){console.error(`[openai-codex] Stream error:`,e instanceof Error?e.message:String(e)),a.push(j(t,e)),a.end()}})(),a},P={id:o,name:`OpenAI Codex (ChatGPT Subscription)`,description:`GPT-5 Codex via your ChatGPT Plus/Pro/Business subscription — OAuth login, no API key needed. Default model is GPT-5.5.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`gpt-5.5`,oauthTokenDomains:[`chatgpt.com`,`*.chatgpt.com`,`auth.openai.com`,`api.openai.com`],getModelIds:()=>_,onOAuthLoginIntercepted:async(e,t,n)=>{let r=b(),a=await x(r),l=S(),m=new URL(c);m.searchParams.set(`response_type`,`code`),m.searchParams.set(`client_id`,s),m.searchParams.set(`redirect_uri`,d),m.searchParams.set(`scope`,n?.scopes??u),m.searchParams.set(`code_challenge`,a),m.searchParams.set(`code_challenge_method`,`S256`),m.searchParams.set(`state`,l),m.searchParams.set(`id_token_add_organizations`,`true`),m.searchParams.set(`codex_cli_simplified_flow`,`true`),m.searchParams.set(`originator`,`pi`);let h=await e({authorizeUrl:m.toString(),redirectUriPattern:f,onCapture:`close`});if(!h)throw Error(`OpenAI Codex OAuth login was cancelled or timed out`);let g=new URL(h),_=g.searchParams.get(`code`),v=g.searchParams.get(`state`);if(!_)throw Error(`OpenAI Codex OAuth redirect did not include a code`);if(v!==l)throw Error(`OpenAI Codex OAuth state mismatch — possible CSRF, aborting`);let y=await C(_,r);await i({providerId:o,accessToken:y.access_token,refreshToken:y.refresh_token,tokenExpiresAt:Date.now()+(y.expires_in??3600)*1e3,baseUrl:p,userName:D(y.access_token),userAvatar:await O(y.access_token)}),t()},onOAuthLogout:async()=>{await i({providerId:o,accessToken:``})},onSilentRenew:async()=>{let e=k();if(!e?.refreshToken)return null;let t=await w(e.refreshToken);return t?.access_token?(await i({providerId:o,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??3600)*1e3,baseUrl:p,userName:D(t.access_token),userAvatar:await O(t.access_token)}),t.access_token):null}};function F(){t({api:h,stream:M,streamSimple:N})}export{P as config,F as register};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{n as e,o as t}from"./models-ByRUWfA-.js";import{t as n}from"./preload-helper-CZgWQFsJ.js";import{t as r}from"./provider-env-D37PhSJu.js";import{r as i}from"./transform-messages-D7OsqBmU.js";import{t as a}from"./headers-CbDaTl3c.js";import{t as o}from"./openai-prompt-cache-DXo9f3w5.js";import{n as s,r as c,t as l}from"./openai-responses-shared-1KvKQf-4.js";var u=new Set;function d(e){return u.add(e),()=>{u.delete(e)}}function f(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:String(e)}function p(e){if(!(e instanceof Error))return{name:`ThrownValue`,message:f(e)};let t=e.code;return{name:e.name||void 0,message:e.message||e.name,stack:e.stack,code:typeof t==`string`||typeof t==`number`?t:void 0}}function m(e,t,n){return{type:e,timestamp:Date.now(),error:p(t),details:n}}function h(e,t){e.diagnostics=[...e.diagnostics??[],t]}function g(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)}}}var _={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function v(e,t){let n=e.toLowerCase(),i=e.toUpperCase();return t?.[n]||t?.[i]||r(n)||r(i)||``}function y(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function b(e,t,n){let r=v(`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 x(e,t){let n=y(e);if(!n?.protocol||!n.host)return``;let r=n.protocol.split(`:`,1)[0];if(!b(n.host.replace(/:\d*$/,``),Number.parseInt(n.port,10)||_[r]||0,t))return``;let i=v(`${r}_proxy`,t)||v(`all_proxy`,t);return i&&!i.includes(`://`)&&(i=`${r}://${i}`),i}var S=`Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.`;function C(e,t){let n=x(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(`${S} Got ${r.protocol}`);return r}var ee=function(e,t){return typeof e==`string`&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,n,r,i,a){return n?t?`.jsx`:`.js`:r&&(!i||!a)?e:r+i+`.`+a.toLowerCase()+`js`}):e},w=null;typeof process<`u`&&(process.versions?.node||process.versions?.bun)&&(e=>n(()=>import(ee(e)),[]))(`node:os`).then(e=>{w=e});var te=`https://chatgpt.com/backend-api`,ne=`https://api.openai.com/auth`,re=0,T=1e3,ie=6e4,E=2e4,ae=15e3,D=new Set([`openai`,`openai-codex`,`opencode`]),oe=1009,se=`websocket_connection_limit_reached`,ce=new Set([`completed`,`incomplete`,`failed`,`cancelled`,`queued`,`in_progress`]);function le(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function ue(e,t){return e===429&&le(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 de(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())}function fe(e,t){let n=t?.maxRetryDelayMs??ie;return n>0?Math.min(e,n):e}function O(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 k(e){if(e!==void 0){if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}}function pe(){let e=new AbortController,t,n=setTimeout(()=>{t=Error(`Codex SSE response headers timed out after ${E}ms`),e.abort(t)},E);return{signal:e.signal,clear:()=>clearTimeout(n),error:()=>t}}var A=(e,n,r)=>{let i=new t;return(async()=>{let t={role:`assistant`,content:[],api:`openai-codex-responses`,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{let o=r?.apiKey;if(!o)throw Error(`No API key for provider: ${e.provider}`);let s=Ve(o),c=he(e,n,r),l=await r?.onPayload?.(c,e);l!==void 0&&(c=l);let u=r?.sessionId||He(),d=Ue(e.headers,r?.headers,s,o,r?.sessionId),f=We(e.headers,r?.headers,s,o,u),p=JSON.stringify(c),_=k(r?.timeoutMs),v=k(r?.websocketConnectTimeoutMs),y=r?.transport||`auto`,b=y!==`sse`&&H(r?.sessionId);if(b&&U(r?.sessionId),y!==`sse`&&!b){let n=!1,a=!1;for(;;){n=!1;try{if(await ze(_e(e.baseUrl),c,f,t,i,e,()=>{n=!0},_,v,r),r?.signal?.aborted)throw Error(`Request was aborted`);i.push({type:`done`,reason:t.stopReason,message:t}),i.end();return}catch(e){let i=r?.signal?.aborted,o=!n&&be(e);if(!i&&o&&!a){a=!0;continue}if(i||ye(e)&&!o||(h(t,m(`provider_transport_failure`,e,{configuredTransport:y,fallbackTransport:n?void 0:`sse`,eventsEmitted:n,phase:n?`after_message_stream_start`:`before_message_stream_start`,requestBytes:new TextEncoder().encode(p).byteLength})),Oe(r?.sessionId,e),n))throw e;U(r?.sessionId);break}}}let x,S,C=r?.maxRetries??re;for(let t=0;t<=C;t++){if(r?.signal?.aborted)throw Error(`Request was aborted`);try{let n=pe(),i=g([r?.signal,n.signal]);try{x=await fetch(N(e.baseUrl),{method:`POST`,headers:d,body:p,signal:i.signal})}catch(e){let t=n.error();throw t&&!r?.signal?.aborted?t:e}finally{i.cleanup(),n.clear()}if(await r?.onResponse?.({status:x.status,headers:a(x.headers)},e),x.ok)break;let o=await x.text();if(t<C&&ue(x.status,o)){let e=de(x.headers);await O(e===void 0?T*2**t:x.status===429?fe(e,r):e,r?.signal);continue}let s=await Be(new Response(o,{status:x.status,statusText:x.statusText}));throw Error(s.friendlyMessage||s.message)}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.message===`Request was aborted`))throw Error(`Request was aborted`);if(S=e instanceof Error?e:Error(String(e)),t<C&&!S.message.includes(`usage limit`)){await O(T*2**t,r?.signal);continue}throw S}}if(!x?.ok)throw S??Error(`Failed after retries`);if(!x.body)throw Error(`No response body`);if(i.push({type:`start`,partial:t}),await ve(x,t,i,e,r),r?.signal?.aborted)throw Error(`Request was aborted`);i.push({type:`done`,reason:t.stopReason,message:t}),i.end()}catch(e){for(let e of t.content)delete e.partialJson;t.stopReason=r?.signal?.aborted?`aborted`:`error`,t.errorMessage=e instanceof Error?e.message:String(e),i.push({type:`error`,reason:t.stopReason,error:t}),i.end()}})(),i},me=(t,n,r)=>{let a=r?.apiKey;if(!a)throw Error(`No API key for provider: ${t.provider}`);let o=i(t,r,a),s=r?.reasoning?e(t,r.reasoning):void 0,c=s===`off`?void 0:s;return A(t,n,{...o,reasoningEffort:c})};function he(e,t,n){let r=l(e,t,D,{includeSystemPrompt:!1}),i={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||`You are a helpful assistant.`,input:r,text:{verbosity:n?.textVerbosity||`low`},include:[`reasoning.encrypted_content`],prompt_cache_key:o(n?.sessionId),tool_choice:`auto`,parallel_tool_calls:!0};if(n?.temperature!==void 0&&(i.temperature=n.temperature),n?.serviceTier!==void 0&&(i.service_tier=n.serviceTier),t.tools&&t.tools.length>0&&(i.tools=s(t.tools,{strict:null})),n?.reasoningEffort!==void 0){let t=n.reasoningEffort===`none`?e.thinkingLevelMap?.off??`none`:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;t!==null&&(i.reasoning={effort:t,summary:n.reasoningSummary??`auto`})}return i}function ge(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=ge(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 M(e,t){return e==="default"&&(t===`flex`||t===`priority`)?t:e??t}function N(e){let t=(e&&e.trim().length>0?e:te).replace(/\/+$/,``);return t.endsWith(`/codex/responses`)?t:t.endsWith(`/codex`)?`${t}/responses`:`${t}/codex/responses`}function _e(e){let t=new URL(N(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function ve(e,t,n,r,i){await c(I(Ce(e,i?.signal)),t,n,r,{serviceTier:i?.serviceTier,resolveServiceTier:M,applyServiceTierPricing:(e,t)=>j(e,t,r)})}var P=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}},F=class extends Error{payload;constructor(e,t){super(e),this.name=`CodexProtocolError`,this.payload=t?.payload,this.cause=t?.cause}};function ye(e){return e instanceof P||e instanceof F}function be(e){return e instanceof P&&e.code===se}function xe(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*I(e){for await(let t of e){let e=typeof t.type==`string`?t.type:void 0;if(e){if(e===`error`){let{code:e,message:n}=xe(t);throw new P(`Codex error: ${n||e||JSON.stringify(t)}`,{code:e,payload:t})}if(e===`response.failed`){let e=t.response,n=e?.error?.code,r=e?.error?.message;throw new P(r||`Codex response failed`,{code:n,payload:t})}if(e===`response.done`||e===`response.completed`||e===`response.incomplete`){let e=t.response,n=e&&{...e,status:Se(e.status)};yield{...t,type:`response.completed`,response:n};return}yield t}}}function Se(e){if(typeof e==`string`)return ce.has(e)?e:void 0}async function*Ce(e,t){if(!e.body)return;let n=e.body.getReader(),r=new TextDecoder,i=``,a=()=>{n.cancel().catch(()=>{})};t?.addEventListener(`abort`,a,{once:!0});try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);let{done:e,value:a}=await n.read();if(t?.aborted)throw Error(`Request was aborted`);if(e)break;i+=r.decode(a,{stream:!0});let o=i.indexOf(`
|
|
2
|
+
|
|
3
|
+
`);for(;o!==-1;){let e=i.slice(0,o);i=i.slice(o+2);let t=e.split(`
|
|
4
|
+
`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());if(t.length>0){let e=t.join(`
|
|
5
|
+
`).trim();if(e&&e!==`[DONE]`)try{yield JSON.parse(e)}catch(t){throw new F(`Invalid Codex SSE JSON: ${f(t)}`,{cause:t,payload:e})}}o=i.indexOf(`
|
|
6
|
+
|
|
7
|
+
`)}}}finally{t?.removeEventListener(`abort`,a);try{await n.cancel()}catch{}try{n.releaseLock()}catch{}}}var we=`responses_websockets=2026-02-06`,Te=300*1e3,L=new Map,R=new Map,z=new Set;function B(e){let t=R.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},R.set(e,t)),t}function Ee(e){let t=R.get(e);return t?{...t}:void 0}function De(e){if(e){R.delete(e),z.delete(e);return}R.clear(),z.clear()}function V(e){let t=e=>{e.idleTimer&&clearTimeout(e.idleTimer),K(e.socket,1e3,`debug_close`)};if(e){let n=L.get(e);n&&t(n),L.delete(e);return}for(let e of L.values())t(e);L.clear()}d(V);function H(e){return e?z.has(e):!1}function U(e){if(!e)return;let t=B(e);t.sseFallbacks++,t.websocketFallbackActive=H(e)}function Oe(e,t){if(!e)return;z.add(e);let n=B(e);n.websocketFailures++,n.lastWebSocketError=f(t),n.websocketFallbackActive=!0}var W=null;async function ke(e){if(!e&&W)return W;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=C(t.toString().replace(/^wss:/,`https:`).replace(/^ws:/,`http:`),e);super(t,{...r,...i?{proxy:i.toString()}:{}})}};return e||(W=t),t}let t=globalThis.WebSocket;return typeof t==`function`?t:null}var Ae=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 je(e){let t=e.readyState;return typeof t==`number`?t:void 0}function G(e){let t=je(e);return t===void 0||t===1}function K(e,t=1e3,n=`done`){try{e.close(t,n)}catch{}}function q(e,t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{t.busy||(K(t.socket,1e3,`idle_timeout`),L.delete(e))},Te)}async function J(e,t,n,r=ae,i){let o=await ke(i);if(!o)throw Error(`WebSocket transport is not available in this runtime`);let s=a(t);return delete s[`OpenAI-Beta`],new Promise((t,i)=>{let a=!1,c,l;try{l=new o(e,{headers:s})}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)=>{a||(a=!0,u(),t&&K(l,1e3,t),i(e))},f=()=>{a||(a=!0,u(),t(l))},p=e=>{d(Y(e))},m=e=>{d(X(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 Me(e,t,n,r,i,a){if(!n){let n=await J(e,t,r,i,a);return{socket:n,reused:!1,release:()=>K(n)}}let o=L.get(n);if(o){if(o.idleTimer&&=(clearTimeout(o.idleTimer),void 0),!o.busy&&G(o.socket))return o.busy=!0,{socket:o.socket,entry:o,reused:!0,release:({keep:e}={})=>{if(!e||!G(o.socket)){K(o.socket),L.delete(n);return}o.busy=!1,q(n,o)}};if(o.busy){let n=await J(e,t,r,i,a);return{socket:n,reused:!1,release:()=>{K(n)}}}G(o.socket)||(K(o.socket),L.delete(n))}let s=await J(e,t,r,i,a),c={socket:s,busy:!0};return L.set(n,c),{socket:s,entry:c,reused:!1,release:({keep:e}={})=>{if(!e||!G(c.socket)){K(c.socket),c.idleTimer&&clearTimeout(c.idleTimer),L.get(n)===c&&L.delete(n);return}c.busy=!1,q(n,c)}}}function Y(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 X(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===oe&&(a=` message too big`),new Ae(`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 Ne(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*Pe(e,t,n){let r=[],i=null,a=!1,o=null,s=!1,c=()=>{if(!i)return;let e=i;i=null,e()},l=e=>{(async()=>{let t=null;try{if(!e||typeof e!=`object`||!(`data`in e)||(t=await Ne(e.data),!t))return;let n=JSON.parse(t),i=typeof n.type==`string`?n.type:``;(i===`response.completed`||i===`response.done`||i===`response.incomplete`)&&(s=!0,a=!0),r.push(n),c()}catch(e){o=new F(`Invalid Codex WebSocket JSON: ${f(e)}`,{cause:e,payload:t}),a=!0,c()}})()},u=e=>{o=Y(e),a=!0,c()},d=e=>{if(s){a=!0,c();return}o||=X(e),a=!0,c()},p=()=>{o=Error(`Request was aborted`),a=!0,c()};e.addEventListener(`message`,l),e.addEventListener(`error`,u),e.addEventListener(`close`,d),t?.addEventListener(`abort`,p);try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);if(r.length>0){yield r.shift();continue}if(a)break;let s;await new Promise((t,r)=>{i=t,n!==void 0&&n>0&&(s=setTimeout(()=>{let t=Error(`WebSocket idle timeout after ${n}ms`);o=t,a=!0,i=null,K(e,1e3,`idle_timeout`),r(t)},n))}).finally(()=>{s&&clearTimeout(s)})}if(o)throw o;if(!s)throw Error(`WebSocket stream closed before response.completed`)}finally{e.removeEventListener(`message`,l),e.removeEventListener(`error`,u),e.removeEventListener(`close`,d),t?.removeEventListener(`abort`,p)}}function Z(e){let{input:t,previous_response_id:n,...r}=e;return r}function Fe(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function Q(e,t){return JSON.stringify(Z(e))===JSON.stringify(Z(t))}function Ie(e,t){if(!Q(e,t.lastRequestBody))return;let n=e.input??[],r=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(!(n.length<r.length)&&Fe(n.slice(0,r.length),r))return n.slice(r.length)}function Le(e,t){let n=e.continuation;if(!n)return t;let r=Ie(t,n);return!r||!n.lastResponseId?(e.continuation=void 0,t):{...t,previous_response_id:n.lastResponseId,input:r}}async function*Re(e,t,n,r){let i=!1;for await(let a of e)i||(i=!0,r(),n.push({type:`start`,partial:t})),yield a}async function ze(e,t,n,r,i,a,o,s,u,d){let{socket:f,entry:p,reused:m,release:h}=await Me(e,n,d?.sessionId,d?.signal,u,d?.env),g=!0,_=d?.transport===`websocket-cached`||d?.transport===`auto`,v=t,y=_&&p?Le(p,v):v,b=d?.sessionId?B(d.sessionId):void 0;b&&(b.requests++,m?b.connectionsReused++:b.connectionsCreated++,_&&b.cachedContextRequests++,y.store===!0&&b.storeTrueRequests++,b.lastInputItems=y.input?.length??0,y.previous_response_id?(b.deltaRequests++,b.lastDeltaInputItems=y.input?.length??0,b.lastPreviousResponseId=y.previous_response_id):(b.fullContextRequests++,b.lastDeltaInputItems=void 0,b.lastPreviousResponseId=void 0));try{if(f.send(JSON.stringify({type:`response.create`,...y})),await c(Re(I(Pe(f,d?.signal,s)),r,i,o),r,i,a,{serviceTier:d?.serviceTier,resolveServiceTier:M,applyServiceTierPricing:(e,t)=>j(e,t,a)}),d?.signal?.aborted)g=!1;else if(_&&p&&r.responseId){let e=l(a,{messages:[r]},D,{includeSystemPrompt:!1}).filter(e=>e.type!==`function_call_output`);p.continuation={lastRequestBody:v,lastResponseId:r.responseId,lastResponseItems:e}}}catch(e){throw p&&(p.continuation=void 0),g=!1,e}finally{h({keep:g})}}async function Be(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 Ve(e){try{let t=e.split(`.`);if(t.length!==3)throw Error(`Invalid token`);let n=JSON.parse(atob(t[1]))?.[ne]?.chatgpt_account_id;if(!n)throw Error(`No account ID in token`);return n}catch{throw Error(`Failed to extract accountId from token`)}}function He(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`codex_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function $(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);i.set(`Authorization`,`Bearer ${r}`),i.set(`chatgpt-account-id`,n),i.set(`originator`,`pi`);let a=w?`pi (${w.platform()} ${w.release()}; ${w.arch()})`:`pi (browser)`;return i.set(`User-Agent`,a),i}function Ue(e,t,n,r,i){let a=$(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 We(e,t,n,r,i){let a=$(e,t,n,r);return a.delete(`accept`),a.delete(`content-type`),a.delete(`OpenAI-Beta`),a.delete(`openai-beta`),a.set(`OpenAI-Beta`,we),a.set(`x-client-request-id`,i),a.set(`session-id`,i),a}export{V as closeOpenAICodexWebSocketSessions,Ee as getOpenAICodexWebSocketDebugStats,De as resetOpenAICodexWebSocketDebugStats,A as stream,me as streamSimple};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{d as e,o as t,r as n}from"./transform-messages-CQuDksPz.js";import{t as r}from"./provider-env-DwY8YuMk.js";import{t as i}from"./headers-CbDaTl3c.js";import{t as a}from"./openai-prompt-cache-DXo9f3w5.js";import{n as o,r as s,t as c}from"./openai-responses-shared-CEQMR7Nx.js";const l=new Set;function u(e){return l.add(e),()=>{l.delete(e)}}function d(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:String(e)}function f(e){if(!(e instanceof Error))return{name:`ThrownValue`,message:d(e)};let t=e.code;return{name:e.name||void 0,message:e.message||e.name,stack:e.stack,code:typeof t==`string`||typeof t==`number`?t:void 0}}function p(e,t,n){return{type:e,timestamp:Date.now(),error:f(t),details:n}}function m(e,t){e.diagnostics=[...e.diagnostics??[],t]}function h(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 g={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function _(e,t){let n=e.toLowerCase(),i=e.toUpperCase();return t?.[n]||t?.[i]||r(n)||r(i)||``}function v(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function y(e,t,n){let r=_(`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 b(e,t){let n=v(e);if(!n?.protocol||!n.host)return``;let r=n.protocol.split(`:`,1)[0];if(!y(n.host.replace(/:\d*$/,``),Number.parseInt(n.port,10)||g[r]||0,t))return``;let i=_(`${r}_proxy`,t)||_(`all_proxy`,t);return i&&!i.includes(`://`)&&(i=`${r}://${i}`),i}function x(e,t){let n=b(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}var S=function(e,t){return typeof e==`string`&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,n,r,i,a){return n?t?`.jsx`:`.js`:r&&(!i||!a)?e:r+i+`.`+a.toLowerCase()+`js`}):e};let C=null;typeof process<`u`&&(process.versions?.node||process.versions?.bun)&&(e=>import(S(e)))(`node:os`).then(e=>{C=e});const w=1e3,T=2e4,E=new Set([`openai`,`openai-codex`,`opencode`]),ee=new Set([`completed`,`incomplete`,`failed`,`cancelled`,`queued`,`in_progress`]);function te(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&&te(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())}function ie(e,t){let n=t?.maxRetryDelayMs??6e4;return n>0?Math.min(e,n):e}function D(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 O(e){if(e!==void 0){if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}}function ae(){let e=new AbortController,t,n=setTimeout(()=>{t=Error(`Codex SSE response headers timed out after ${T}ms`),e.abort(t)},T);return{signal:e.signal,clear:()=>clearTimeout(n),error:()=>t}}const k=(t,n,r)=>{let a=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:`stop`,timestamp:Date.now()};try{let o=r?.apiKey;if(!o)throw Error(`No API key for provider: ${t.provider}`);let s=Ae(o),c=se(t,n,r),l=await r?.onPayload?.(c,t);l!==void 0&&(c=l);let u=r?.sessionId||je(),d=Me(t.headers,r?.headers,s,o,r?.sessionId),f=Ne(t.headers,r?.headers,s,o,u),g=JSON.stringify(c),_=O(r?.timeoutMs),v=O(r?.websocketConnectTimeoutMs),y=r?.transport||`auto`,b=y!==`sse`&&H(r?.sessionId);if(b&&U(r?.sessionId),y!==`sse`&&!b){let n=!1,i=!1;for(;;){n=!1;try{if(await Q(ce(t.baseUrl),c,f,e,a,t,()=>{n=!0},_,v,r),r?.signal?.aborted)throw Error(`Request was aborted`);a.push({type:`done`,reason:e.stopReason,message:e}),a.end();return}catch(t){let a=r?.signal?.aborted,o=!n&&de(t);if(!a&&o&&!i){i=!0;continue}if(a||ue(t)&&!o||(m(e,p(`provider_transport_failure`,t,{configuredTransport:y,fallbackTransport:n?void 0:`sse`,eventsEmitted:n,phase:n?`after_message_stream_start`:`before_message_stream_start`,requestBytes:new TextEncoder().encode(g).byteLength})),_e(r?.sessionId,t),n))throw t;U(r?.sessionId);break}}}let x,S,C=r?.maxRetries??0;for(let e=0;e<=C;e++){if(r?.signal?.aborted)throw Error(`Request was aborted`);try{let n=ae(),a=h([r?.signal,n.signal]);try{x=await fetch(N(t.baseUrl),{method:`POST`,headers:d,body:g,signal:a.signal})}catch(e){let t=n.error();throw t&&!r?.signal?.aborted?t:e}finally{a.cleanup(),n.clear()}if(await r?.onResponse?.({status:x.status,headers:i(x.headers)},t),x.ok)break;let o=await x.text();if(e<C&&ne(x.status,o)){let t=re(x.headers);await D(t===void 0?w*2**e:x.status===429?ie(t,r):t,r?.signal);continue}let s=await ke(new Response(o,{status:x.status,statusText:x.statusText}));throw Error(s.friendlyMessage||s.message)}catch(t){if(t instanceof Error&&(t.name===`AbortError`||t.message===`Request was aborted`))throw Error(`Request was aborted`);if(S=t instanceof Error?t:Error(String(t)),e<C&&!S.message.includes(`usage limit`)){await D(w*2**e,r?.signal);continue}throw S}}if(!x?.ok)throw S??Error(`Failed after retries`);if(!x.body)throw Error(`No response body`);if(a.push({type:`start`,partial:e}),await le(x,e,a,t,r),r?.signal?.aborted)throw Error(`Request was aborted`);a.push({type:`done`,reason:e.stopReason,message:e}),a.end()}catch(t){for(let t of e.content)delete t.partialJson;e.stopReason=r?.signal?.aborted?`aborted`:`error`,e.errorMessage=t instanceof Error?t.message:String(t),a.push({type:`error`,reason:e.stopReason,error:e}),a.end()}})(),a},oe=(e,r,i)=>{let a=i?.apiKey;if(!a)throw Error(`No API key for provider: ${e.provider}`);let o=n(e,i,a),s=i?.reasoning?t(e,i.reasoning):void 0,c=s===`off`?void 0:s;return k(e,r,{...o,reasoningEffort:c})};function se(e,t,n){let r=c(e,t,E,{includeSystemPrompt:!1}),i={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||`You are a helpful assistant.`,input:r,text:{verbosity:n?.textVerbosity||`low`},include:[`reasoning.encrypted_content`],prompt_cache_key:a(n?.sessionId),tool_choice:`auto`,parallel_tool_calls:!0};if(n?.temperature!==void 0&&(i.temperature=n.temperature),n?.serviceTier!==void 0&&(i.service_tier=n.serviceTier),t.tools&&t.tools.length>0&&(i.tools=o(t.tools,{strict:null})),n?.reasoningEffort!==void 0){let t=n.reasoningEffort===`none`?e.thinkingLevelMap?.off??`none`:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;t!==null&&(i.reasoning={effort:t,summary:n.reasoningSummary??`auto`})}return i}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)}function M(e,t){return e==="default"&&(t===`flex`||t===`priority`)?t:e??t}function N(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 ce(e){let t=new URL(N(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function le(e,t,n,r,i){await s(I(me(e,i?.signal)),t,n,r,{serviceTier:i?.serviceTier,resolveServiceTier:M,applyServiceTierPricing:(e,t)=>j(e,t,r)})}var P=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}},F=class extends Error{payload;constructor(e,t){super(e),this.name=`CodexProtocolError`,this.payload=t?.payload,this.cause=t?.cause}};function ue(e){return e instanceof P||e instanceof F}function de(e){return e instanceof P&&e.code===`websocket_connection_limit_reached`}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*I(e){for await(let t of e){let e=typeof t.type==`string`?t.type:void 0;if(e){if(e===`error`){let{code:e,message:n}=fe(t);throw new P(`Codex error: ${n||e||JSON.stringify(t)}`,{code:e,payload:t})}if(e===`response.failed`){let e=t.response,n=e?.error?.code,r=e?.error?.message;throw new P(r||`Codex response failed`,{code:n,payload:t})}if(e===`response.done`||e===`response.completed`||e===`response.incomplete`){let e=t.response,n=e&&{...e,status:pe(e.status)};yield{...t,type:`response.completed`,response:n};return}yield t}}}function pe(e){if(typeof e==`string`)return ee.has(e)?e:void 0}async function*me(e,t){if(!e.body)return;let n=e.body.getReader(),r=new TextDecoder,i=``,a=()=>{n.cancel().catch(()=>{})};t?.addEventListener(`abort`,a,{once:!0});try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);let{done:e,value:a}=await n.read();if(t?.aborted)throw Error(`Request was aborted`);if(e)break;i+=r.decode(a,{stream:!0});let o=i.indexOf(`
|
|
2
|
+
|
|
3
|
+
`);for(;o!==-1;){let e=i.slice(0,o);i=i.slice(o+2);let t=e.split(`
|
|
4
|
+
`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());if(t.length>0){let e=t.join(`
|
|
5
|
+
`).trim();if(e&&e!==`[DONE]`)try{yield JSON.parse(e)}catch(t){throw new F(`Invalid Codex SSE JSON: ${d(t)}`,{cause:t,payload:e})}}o=i.indexOf(`
|
|
6
|
+
|
|
7
|
+
`)}}}finally{t?.removeEventListener(`abort`,a);try{await n.cancel()}catch{}try{n.releaseLock()}catch{}}}const L=new Map,R=new Map,z=new Set;function B(e){let t=R.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},R.set(e,t)),t}function he(e){let t=R.get(e);return t?{...t}:void 0}function ge(e){if(e){R.delete(e),z.delete(e);return}R.clear(),z.clear()}function V(e){let t=e=>{e.idleTimer&&clearTimeout(e.idleTimer),K(e.socket,1e3,`debug_close`)};if(e){let n=L.get(e);n&&t(n),L.delete(e);return}for(let e of L.values())t(e);L.clear()}u(V);function H(e){return e?z.has(e):!1}function U(e){if(!e)return;let t=B(e);t.sseFallbacks++,t.websocketFallbackActive=H(e)}function _e(e,t){if(!e)return;z.add(e);let n=B(e);n.websocketFailures++,n.lastWebSocketError=d(t),n.websocketFallbackActive=!0}let W=null;async function ve(e){if(!e&&W)return W;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=x(t.toString().replace(/^wss:/,`https:`).replace(/^ws:/,`http:`),e);super(t,{...r,...i?{proxy:i.toString()}:{}})}};return e||(W=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 G(e){let t=be(e);return t===void 0||t===1}function K(e,t=1e3,n=`done`){try{e.close(t,n)}catch{}}function q(e,t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{t.busy||(K(t.socket,1e3,`idle_timeout`),L.delete(e))},3e5)}async function J(e,t,n,r=15e3,a){let o=await ve(a);if(!o)throw Error(`WebSocket transport is not available in this runtime`);let s=i(t);return delete s[`OpenAI-Beta`],new Promise((t,i)=>{let a=!1,c,l;try{l=new o(e,{headers:s})}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)=>{a||(a=!0,u(),t&&K(l,1e3,t),i(e))},f=()=>{a||(a=!0,u(),t(l))},p=e=>{d(Y(e))},m=e=>{d(X(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 xe(e,t,n,r,i,a){if(!n){let n=await J(e,t,r,i,a);return{socket:n,reused:!1,release:()=>K(n)}}let o=L.get(n);if(o){if(o.idleTimer&&=(clearTimeout(o.idleTimer),void 0),!o.busy&&G(o.socket))return o.busy=!0,{socket:o.socket,entry:o,reused:!0,release:({keep:e}={})=>{if(!e||!G(o.socket)){K(o.socket),L.delete(n);return}o.busy=!1,q(n,o)}};if(o.busy){let n=await J(e,t,r,i,a);return{socket:n,reused:!1,release:()=>{K(n)}}}G(o.socket)||(K(o.socket),L.delete(n))}let s=await J(e,t,r,i,a),c={socket:s,busy:!0};return L.set(n,c),{socket:s,entry:c,reused:!1,release:({keep:e}={})=>{if(!e||!G(c.socket)){K(c.socket),c.idleTimer&&clearTimeout(c.idleTimer),L.get(n)===c&&L.delete(n);return}c.busy=!1,q(n,c)}}}function Y(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 X(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 Se(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*Ce(e,t,n){let r=[],i=null,a=!1,o=null,s=!1,c=()=>{if(!i)return;let e=i;i=null,e()},l=e=>{(async()=>{let t=null;try{if(!e||typeof e!=`object`||!(`data`in e)||(t=await Se(e.data),!t))return;let n=JSON.parse(t),i=typeof n.type==`string`?n.type:``;(i===`response.completed`||i===`response.done`||i===`response.incomplete`)&&(s=!0,a=!0),r.push(n),c()}catch(e){o=new F(`Invalid Codex WebSocket JSON: ${d(e)}`,{cause:e,payload:t}),a=!0,c()}})()},u=e=>{o=Y(e),a=!0,c()},f=e=>{if(s){a=!0,c();return}o||=X(e),a=!0,c()},p=()=>{o=Error(`Request was aborted`),a=!0,c()};e.addEventListener(`message`,l),e.addEventListener(`error`,u),e.addEventListener(`close`,f),t?.addEventListener(`abort`,p);try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);if(r.length>0){yield r.shift();continue}if(a)break;let s;await new Promise((t,r)=>{i=t,n!==void 0&&n>0&&(s=setTimeout(()=>{let t=Error(`WebSocket idle timeout after ${n}ms`);o=t,a=!0,i=null,K(e,1e3,`idle_timeout`),r(t)},n))}).finally(()=>{s&&clearTimeout(s)})}if(o)throw o;if(!s)throw Error(`WebSocket stream closed before response.completed`)}finally{e.removeEventListener(`message`,l),e.removeEventListener(`error`,u),e.removeEventListener(`close`,f),t?.removeEventListener(`abort`,p)}}function Z(e){let{input:t,previous_response_id:n,...r}=e;return r}function we(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function Te(e,t){return JSON.stringify(Z(e))===JSON.stringify(Z(t))}function Ee(e,t){if(!Te(e,t.lastRequestBody))return;let n=e.input??[],r=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(!(n.length<r.length)&&we(n.slice(0,r.length),r))return n.slice(r.length)}function De(e,t){let n=e.continuation;if(!n)return t;let r=Ee(t,n);return!r||!n.lastResponseId?(e.continuation=void 0,t):{...t,previous_response_id:n.lastResponseId,input:r}}async function*Oe(e,t,n,r){let i=!1;for await(let a of e)i||(i=!0,r(),n.push({type:`start`,partial:t})),yield a}async function Q(e,t,n,r,i,a,o,l,u,d){let{socket:f,entry:p,reused:m,release:h}=await xe(e,n,d?.sessionId,d?.signal,u,d?.env),g=!0,_=d?.transport===`websocket-cached`||d?.transport===`auto`,v=t,y=_&&p?De(p,v):v,b=d?.sessionId?B(d.sessionId):void 0;b&&(b.requests++,m?b.connectionsReused++:b.connectionsCreated++,_&&b.cachedContextRequests++,y.store===!0&&b.storeTrueRequests++,b.lastInputItems=y.input?.length??0,y.previous_response_id?(b.deltaRequests++,b.lastDeltaInputItems=y.input?.length??0,b.lastPreviousResponseId=y.previous_response_id):(b.fullContextRequests++,b.lastDeltaInputItems=void 0,b.lastPreviousResponseId=void 0));try{if(f.send(JSON.stringify({type:`response.create`,...y})),await s(Oe(I(Ce(f,d?.signal,l)),r,i,o),r,i,a,{serviceTier:d?.serviceTier,resolveServiceTier:M,applyServiceTierPricing:(e,t)=>j(e,t,a)}),d?.signal?.aborted)g=!1;else if(_&&p&&r.responseId){let e=c(a,{messages:[r]},E,{includeSystemPrompt:!1}).filter(e=>e.type!==`function_call_output`);p.continuation={lastRequestBody:v,lastResponseId:r.responseId,lastResponseItems:e}}}catch(e){throw p&&(p.continuation=void 0),g=!1,e}finally{h({keep:g})}}async function ke(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 Ae(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 je(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`codex_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function $(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);i.set(`Authorization`,`Bearer ${r}`),i.set(`chatgpt-account-id`,n),i.set(`originator`,`pi`);let a=C?`pi (${C.platform()} ${C.release()}; ${C.arch()})`:`pi (browser)`;return i.set(`User-Agent`,a),i}function Me(e,t,n,r,i){let a=$(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 Ne(e,t,n,r,i){let a=$(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{V as closeOpenAICodexWebSocketSessions,he as getOpenAICodexWebSocketDebugStats,ge as resetOpenAICodexWebSocketDebugStats,k as stream,oe as streamSimple};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{n as e,o as t,t as n}from"./models-ByRUWfA-.js";import{t as r}from"./provider-env-D37PhSJu.js";import{n as i}from"./json-parse-C7d6hyOc.js";import{r as a,t as o}from"./transform-messages-D7OsqBmU.js";import{t as s}from"./headers-CbDaTl3c.js";import{t as c}from"./sanitize-unicode-DmIE6hZJ.js";import{n as l,t as u}from"./github-copilot-headers-DRgtIyTm.js";import{n as d}from"./openai-BeH6aC_-.js";import{t as f}from"./openai-prompt-cache-DXo9f3w5.js";function p(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 m(e,t,n){if(t)return t;if(p(n,`authorization`)||p(n,`cf-aig-authorization`))return`unused`;throw Error(`No API key for provider: ${e}`)}function h(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 g(e){return e.type===`text`}function _(e){return e.type===`thinking`}function v(e){return e.type===`toolCall`}function y(e){return e.type===`image`}function b(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.type===`reasoning.encrypted`&&typeof t.id==`string`&&t.id.length>0&&typeof t.data==`string`&&t.data.length>0}function x(e,t){return e||(r(`PI_CACHE_RETENTION`,t)===`long`?`long`:`short`)}var S=(e,n,r)=>{let a=new t;return(async()=>{let t={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{let o=m(e.provider,r?.apiKey,r?.headers),c=V(e),l=x(r?.cacheRetention,r?.env),u=l===`none`?void 0:r?.sessionId,d=w(e,n,o,r?.headers,u,c),f=T(e,n,r,c,l),p=await r?.onPayload?.(f,e);p!==void 0&&(f=p);let h={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs===void 0?{}:{timeout:r.timeoutMs},maxRetries:r?.maxRetries??0},{data:g,response:_}=await d.chat.completions.create(f,h).withResponse();await r?.onResponse?.({status:_.status,headers:s(_.headers)},e),a.push({type:`start`,partial:t});let v=null,y=null,S=!1,C=new Map,E=new Map,D=new Map,O=t.content,k=e=>O.indexOf(e),A=e=>{let n=k(e);n!==-1&&(e.type===`text`?a.push({type:`text_end`,contentIndex:n,content:e.text,partial:t}):e.type===`thinking`?a.push({type:`thinking_end`,contentIndex:n,content:e.thinking,partial:t}):e.type===`toolCall`&&(e.arguments=i(e.partialArgs),delete e.partialArgs,delete e.streamIndex,a.push({type:`toolcall_end`,contentIndex:n,toolCall:e,partial:t})))},j=()=>(v||(v={type:`text`,text:``},O.push(v),a.push({type:`text_start`,contentIndex:k(v),partial:t})),v),M=e=>(y||(y={type:`thinking`,thinking:``,thinkingSignature:e},O.push(y),a.push({type:`thinking_start`,contentIndex:k(y),partial:t})),y),N=e=>{if(!e.id)return;let t=D.get(e.id);t&&(e.thoughtSignature=t,D.delete(e.id))},P=e=>{let n=typeof e.index==`number`?e.index:void 0,r=n===void 0?void 0:C.get(n);return!r&&e.id&&(r=E.get(e.id)),r||(r={type:`toolCall`,id:e.id||``,name:e.function?.name||``,arguments:{},partialArgs:``,streamIndex:n},n!==void 0&&C.set(n,r),e.id&&E.set(e.id,r),O.push(r),a.push({type:`toolcall_start`,contentIndex:k(r),partial:t})),n!==void 0&&r.streamIndex===void 0&&(r.streamIndex=n,C.set(n,r)),e.id&&E.set(e.id,r),N(r),r};for await(let n of g){if(!n||typeof n!=`object`)continue;t.responseId||=n.id,typeof n.model==`string`&&n.model.length>0&&n.model!==e.id&&(t.responseModel||=n.model),n.usage&&(t.usage=R(n.usage,e));let r=Array.isArray(n.choices)?n.choices[0]:void 0;if(r){if(!n.usage&&r.usage&&(t.usage=R(r.usage,e)),r.finish_reason){let e=z(r.finish_reason);t.stopReason=e.stopReason,e.errorMessage&&(t.errorMessage=e.errorMessage),S=!0}if(r.delta){if(r.delta.content!==null&&r.delta.content!==void 0&&r.delta.content.length>0){let e=j();e.text+=r.delta.content,a.push({type:`text_delta`,contentIndex:k(e),delta:r.delta.content,partial:t})}let n=[`reasoning_content`,`reasoning`,`reasoning_text`],o=r.delta,s=null;for(let e of n){let t=o[e];if(typeof t==`string`&&t.length>0){s=e;break}}if(s){let n=o[s];if(typeof n==`string`&&n.length>0){let r=M(e.provider===`opencode-go`&&s===`reasoning`?`reasoning_content`:s);r.thinking+=n,a.push({type:`thinking_delta`,contentIndex:k(r),delta:n,partial:t})}}if(r?.delta?.tool_calls)for(let e of r.delta.tool_calls){let n=P(e);!n.id&&e.id&&(n.id=e.id,E.set(e.id,n)),!n.name&&e.function?.name&&(n.name=e.function.name);let r=``;e.function?.arguments&&(r=e.function.arguments,n.partialArgs=(n.partialArgs??``)+e.function.arguments,n.arguments=i(n.partialArgs)),a.push({type:`toolcall_delta`,contentIndex:k(n),delta:r,partial:t})}let c=r.delta.reasoning_details;if(Array.isArray(c)){for(let e of c)if(b(e)){let t=JSON.stringify(e),n=E.get(e.id);n?n.thoughtSignature=t:D.set(e.id,t)}}}}}for(let e of O)A(e);if(r?.signal?.aborted||t.stopReason===`aborted`)throw Error(`Request was aborted`);if(t.stopReason===`error`)throw Error(t.errorMessage||`Provider returned an error stop reason`);if(!S)throw Error(`Stream ended without finish_reason`);a.push({type:`done`,reason:t.stopReason,message:t}),a.end()}catch(e){for(let e of t.content)delete e.index,delete e.partialArgs,delete e.streamIndex;t.stopReason=r?.signal?.aborted?`aborted`:`error`,t.errorMessage=e instanceof Error?e.message:JSON.stringify(e);let n=e?.error?.metadata?.raw;n&&(t.errorMessage+=`\n${n}`),a.push({type:`error`,reason:t.stopReason,error:t}),a.end()}})(),a},C=(t,n,r)=>{m(t.provider,r?.apiKey,r?.headers);let i=a(t,r,r?.apiKey),o=r?.reasoning?e(t,r.reasoning):void 0,s=o===`off`?void 0:o,c=r?.toolChoice;return S(t,n,{...i,reasoningEffort:s,toolChoice:c})};function w(e,t,n,r,i,a=V(e)){let o={...e.headers};if(e.provider===`github-copilot`){let e=l(t.messages),n=u({messages:t.messages,hasImages:e});Object.assign(o,n)}return i&&a.sendSessionAffinityHeaders&&(o.session_id=i,o[`x-client-request-id`]=i,o[`x-session-affinity`]=i),r&&Object.assign(o,r),new d({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:o})}function T(e,t,n,r=V(e),i=x(n?.cacheRetention,n?.env)){let a=I(e,t,r),o=O(r,i),s={model:e.id,messages:a,stream:!0,prompt_cache_key:e.baseUrl.includes(`api.openai.com`)&&i!==`none`||i===`long`&&r.supportsLongCacheRetention?f(n?.sessionId):void 0,prompt_cache_retention:i===`long`&&r.supportsLongCacheRetention?`24h`:void 0};if(r.supportsUsageInStreaming!==!1&&(s.stream_options={include_usage:!0}),r.supportsStore&&(s.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?s.max_tokens=n.maxTokens:s.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(s.temperature=n.temperature),t.tools&&t.tools.length>0?(s.tools=L(t.tools,r),r.zaiToolStream&&(s.tool_stream=!0)):h(t.messages)&&(s.tools=[]),o&&k(a,s.tools,o),n?.toolChoice&&(s.tool_choice=n.toolChoice),r.thinkingFormat===`zai`&&e.reasoning){let t=s;if(t.thinking={type:n?.reasoningEffort?`enabled`:`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)s.enable_thinking=!!n?.reasoningEffort;else if(r.thinkingFormat===`qwen-chat-template`&&e.reasoning)s.chat_template_kwargs={enable_thinking:!!n?.reasoningEffort,preserve_thinking:!0};else if(r.thinkingFormat===`chat-template`&&e.reasoning){let t=E(e,n,r);t&&(s.chat_template_kwargs=t)}else if(r.thinkingFormat===`deepseek`&&e.reasoning)n?.reasoningEffort?s.thinking={type:`enabled`}:e.thinkingLevelMap?.off!==null&&(s.thinking={type:`disabled`}),n?.reasoningEffort&&r.supportsReasoningEffort&&(s.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort);else if(r.thinkingFormat===`openrouter`&&e.reasoning){let t=s;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`&&(s.reasoning={effort:t})}else if(r.thinkingFormat===`together`&&e.reasoning){let t=s;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=s;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)s.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;else if(!n?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort){let t=e.thinkingLevelMap?.off;typeof t==`string`&&(s.reasoning_effort=t)}if(e.compat?.openRouterRouting&&(s.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),s.providerOptions={gateway:e}}}return s}function E(e,t,n){let r={};for(let[i,a]of Object.entries(n.chatTemplateKwargs)){let n=D(e,t,a);n!==void 0&&(r[i]=n)}return Object.keys(r).length>0?r:void 0}function D(e,t,n){if(typeof n!=`object`||!n)return n;let r=t?.reasoningEffort;if(!r&&n.omitWhenOff)return;if(n.$var===`thinking.enabled`)return!!r;let i=r?e.thinkingLevelMap?.[r]:e.thinkingLevelMap?.off;return i===void 0?r:typeof i==`string`?i:void 0}function O(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){A(e,n),M(t,n),j(e,n)}function A(e,t){for(let n of e)if(n.role===`system`||n.role===`developer`){N(n,t);return}}function j(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if((r.role===`user`||r.role===`assistant`)&&P(r,t))return}}function M(e,t){if(!e||e.length===0)return;let n=e[e.length-1];n.cache_control=t}function N(e,t){return F(e,t)}function P(e,t){return e.role===`user`||e.role===`assistant`?F(e,t):!1}function F(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 I(e,t,n){let r=[],i=t=>{if(t.includes(`|`)){let[e]=t.split(`|`);return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,40)}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},a=o(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:c(t.systemPrompt)})}let s=null;for(let t=0;t<a.length;t++){let i=a[t];if(n.requiresAssistantAfterToolResult&&s===`toolResult`&&i.role===`user`&&r.push({role:`assistant`,content:`I have processed the tool results.`}),i.role===`user`)if(typeof i.content==`string`)r.push({role:`user`,content:c(i.content)});else{let e=i.content.map(e=>e.type===`text`?{type:`text`,text:c(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});if(e.length===0)continue;r.push({role:`user`,content:e})}else if(i.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=i.content.filter(g).filter(e=>e.text.trim().length>0).map(e=>({type:`text`,text:c(e.text)})),o=a.map(e=>e.text).join(``),s=i.content.filter(_).filter(e=>e.thinking.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText)t.content=[{type:`text`,text:s.map(e=>c(e.thinking)).join(`
|
|
2
|
+
|
|
3
|
+
`)},...a];else{o.length>0&&(t.content=o);let n=s[0].thinkingSignature;e.provider===`opencode-go`&&n===`reasoning`&&(n=`reasoning_content`),n&&n.length>0&&(t[n]=s.map(e=>e.thinking).join(`
|
|
4
|
+
`))}else o.length>0&&(t.content=o);let l=i.content.filter(v);if(l.length>0){t.tool_calls=l.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}));let e=l.filter(e=>e.thoughtSignature).map(e=>{try{return JSON.parse(e.thoughtSignature)}catch{return null}}).filter(Boolean);e.length>0&&(t.reasoning_details=e)}n.requiresReasoningContentOnAssistantMessages&&e.reasoning&&t.reasoning_content===void 0&&(t.reasoning_content=``);let u=t.content;if(!(u!=null&&u.length>0)&&!t.tool_calls)continue;r.push(t)}else if(i.role===`toolResult`){let i=[],o=t;for(;o<a.length&&a[o].role===`toolResult`;o++){let t=a[o],s=t.content.filter(g).map(e=>e.text).join(`
|
|
5
|
+
`),l=t.content.some(e=>e.type===`image`),u={role:`tool`,content:c(s.length>0?s:`(see attached image)`),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(u.name=t.toolName),r.push(u),l&&e.input.includes(`image`))for(let e of t.content)y(e)&&i.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}t=o-1,i.length>0?(n.requiresAssistantAfterToolResult&&r.push({role:`assistant`,content:`I have processed the tool results.`}),r.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...i]}),s=`user`):s=`toolResult`;continue}s=i.role}return r}function L(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function R(e,t){let r=e.prompt_tokens||0,i=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_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,totalTokens:o+s+i+a,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return n(t,c),c}function z(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 B(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=l||t===`cerebras`||n.includes(`cerebras.ai`)||t===`xai`||n.includes(`api.x.ai`)||i||n.includes(`chutes.ai`)||n.includes(`deepseek.com`)||r||a||t===`opencode`||n.includes(`opencode.ai`)||s||c||u,f=n.includes(`chutes.ai`)||a||c||i||l||u,p=t===`xai`||n.includes(`api.x.ai`),m=t===`deepseek`||n.includes(`deepseek.com`),h=o&&(e.id.startsWith(`anthropic/`)||e.id.startsWith(`openai/`)),g=t===`openrouter`&&e.id.startsWith(`anthropic/`)?`anthropic`:void 0;return{supportsStore:!d,supportsDeveloperRole:h||!d&&!o,supportsReasoningEffort:!p&&!r&&!a&&!i&&!c&&!l&&!u,supportsUsageInStreaming:!0,maxTokensField:f?`max_tokens`:`max_completion_tokens`,requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:m,thinkingFormat:m?`deepseek`:r?`zai`:i?`together`:u?`ant-ling`:o?`openrouter`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},zaiToolStream:!1,supportsStrictMode:!a&&!i&&!c&&!l,cacheControlFormat:g,sendSessionAffinityHeaders:!1,supportsLongCacheRetention:!(i||s||c||l||u)}}function V(e){let t=B(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,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,zaiToolStream:e.compat.zaiToolStream??t.zaiToolStream,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode,cacheControlFormat:e.compat.cacheControlFormat??t.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??t.sendSessionAffinityHeaders,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??t.supportsLongCacheRetention}:t}export{I as convertMessages,S as stream,C as streamSimple};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{a as e,d as t,o as n,r,t as i}from"./transform-messages-CQuDksPz.js";import{t as a}from"./provider-env-DwY8YuMk.js";import{n as o}from"./json-parse-B51EftGA.js";import{t as s}from"./headers-CbDaTl3c.js";import{t as c}from"./sanitize-unicode-DmIE6hZJ.js";import{n as l,t as u}from"./github-copilot-headers-DRgtIyTm.js";import{n as d}from"./openai-BvKpRLAG.js";import{t as f}from"./openai-prompt-cache-DXo9f3w5.js";function p(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 m(e,t,n){if(t)return t;if(p(n,`authorization`)||p(n,`cf-aig-authorization`))return`unused`;throw Error(`No API key for provider: ${e}`)}function h(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 g(e){return e.type===`text`}function _(e){return e.type===`thinking`}function v(e){return e.type===`toolCall`}function y(e){return e.type===`image`}function b(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.type===`reasoning.encrypted`&&typeof t.id==`string`&&t.id.length>0&&typeof t.data==`string`&&t.data.length>0}function x(e,t){return e||(a(`PI_CACHE_RETENTION`,t)===`long`?`long`:`short`)}const S=(e,n,r)=>{let i=new t;return(async()=>{let t={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{let a=m(e.provider,r?.apiKey,r?.headers),c=V(e),l=x(r?.cacheRetention,r?.env),u=l===`none`?void 0:r?.sessionId,d=w(e,n,a,r?.headers,u,c),f=T(e,n,r,c,l),p=await r?.onPayload?.(f,e);p!==void 0&&(f=p);let h={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs===void 0?{}:{timeout:r.timeoutMs},maxRetries:r?.maxRetries??0},{data:g,response:_}=await d.chat.completions.create(f,h).withResponse();await r?.onResponse?.({status:_.status,headers:s(_.headers)},e),i.push({type:`start`,partial:t});let v=null,y=null,S=!1,C=new Map,E=new Map,D=new Map,O=t.content,k=e=>O.indexOf(e),A=e=>{let n=k(e);n!==-1&&(e.type===`text`?i.push({type:`text_end`,contentIndex:n,content:e.text,partial:t}):e.type===`thinking`?i.push({type:`thinking_end`,contentIndex:n,content:e.thinking,partial:t}):e.type===`toolCall`&&(e.arguments=o(e.partialArgs),delete e.partialArgs,delete e.streamIndex,i.push({type:`toolcall_end`,contentIndex:n,toolCall:e,partial:t})))},j=()=>(v||(v={type:`text`,text:``},O.push(v),i.push({type:`text_start`,contentIndex:k(v),partial:t})),v),M=e=>(y||(y={type:`thinking`,thinking:``,thinkingSignature:e},O.push(y),i.push({type:`thinking_start`,contentIndex:k(y),partial:t})),y),N=e=>{if(!e.id)return;let t=D.get(e.id);t&&(e.thoughtSignature=t,D.delete(e.id))},P=e=>{let n=typeof e.index==`number`?e.index:void 0,r=n===void 0?void 0:C.get(n);return!r&&e.id&&(r=E.get(e.id)),r||(r={type:`toolCall`,id:e.id||``,name:e.function?.name||``,arguments:{},partialArgs:``,streamIndex:n},n!==void 0&&C.set(n,r),e.id&&E.set(e.id,r),O.push(r),i.push({type:`toolcall_start`,contentIndex:k(r),partial:t})),n!==void 0&&r.streamIndex===void 0&&(r.streamIndex=n,C.set(n,r)),e.id&&E.set(e.id,r),N(r),r};for await(let n of g){if(!n||typeof n!=`object`)continue;t.responseId||=n.id,typeof n.model==`string`&&n.model.length>0&&n.model!==e.id&&(t.responseModel||=n.model),n.usage&&(t.usage=R(n.usage,e));let r=Array.isArray(n.choices)?n.choices[0]:void 0;if(r){if(!n.usage&&r.usage&&(t.usage=R(r.usage,e)),r.finish_reason){let e=z(r.finish_reason);t.stopReason=e.stopReason,e.errorMessage&&(t.errorMessage=e.errorMessage),S=!0}if(r.delta){if(r.delta.content!==null&&r.delta.content!==void 0&&r.delta.content.length>0){let e=j();e.text+=r.delta.content,i.push({type:`text_delta`,contentIndex:k(e),delta:r.delta.content,partial:t})}let n=[`reasoning_content`,`reasoning`,`reasoning_text`],a=r.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(e.provider===`opencode-go`&&s===`reasoning`?`reasoning_content`:s);r.thinking+=n,i.push({type:`thinking_delta`,contentIndex:k(r),delta:n,partial:t})}}if(r?.delta?.tool_calls)for(let e of r.delta.tool_calls){let n=P(e);!n.id&&e.id&&(n.id=e.id,E.set(e.id,n)),!n.name&&e.function?.name&&(n.name=e.function.name);let r=``;e.function?.arguments&&(r=e.function.arguments,n.partialArgs=(n.partialArgs??``)+e.function.arguments,n.arguments=o(n.partialArgs)),i.push({type:`toolcall_delta`,contentIndex:k(n),delta:r,partial:t})}let c=r.delta.reasoning_details;if(Array.isArray(c)){for(let e of c)if(b(e)){let t=JSON.stringify(e),n=E.get(e.id);n?n.thoughtSignature=t:D.set(e.id,t)}}}}}for(let e of O)A(e);if(r?.signal?.aborted||t.stopReason===`aborted`)throw Error(`Request was aborted`);if(t.stopReason===`error`)throw Error(t.errorMessage||`Provider returned an error stop reason`);if(!S)throw Error(`Stream ended without finish_reason`);i.push({type:`done`,reason:t.stopReason,message:t}),i.end()}catch(e){for(let e of t.content)delete e.index,delete e.partialArgs,delete e.streamIndex;t.stopReason=r?.signal?.aborted?`aborted`:`error`,t.errorMessage=e instanceof Error?e.message:JSON.stringify(e);let n=e?.error?.metadata?.raw;n&&(t.errorMessage+=`\n${n}`),i.push({type:`error`,reason:t.stopReason,error:t}),i.end()}})(),i},C=(e,t,i)=>{m(e.provider,i?.apiKey,i?.headers);let a=r(e,i,i?.apiKey),o=i?.reasoning?n(e,i.reasoning):void 0,s=o===`off`?void 0:o,c=i?.toolChoice;return S(e,t,{...a,reasoningEffort:s,toolChoice:c})};function w(e,t,n,r,i,a=V(e)){let o={...e.headers};if(e.provider===`github-copilot`){let e=l(t.messages),n=u({messages:t.messages,hasImages:e});Object.assign(o,n)}return i&&a.sendSessionAffinityHeaders&&(o.session_id=i,o[`x-client-request-id`]=i,o[`x-session-affinity`]=i),r&&Object.assign(o,r),new d({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:o})}function T(e,t,n,r=V(e),i=x(n?.cacheRetention,n?.env)){let a=I(e,t,r),o=O(r,i),s={model:e.id,messages:a,stream:!0,prompt_cache_key:e.baseUrl.includes(`api.openai.com`)&&i!==`none`||i===`long`&&r.supportsLongCacheRetention?f(n?.sessionId):void 0,prompt_cache_retention:i===`long`&&r.supportsLongCacheRetention?`24h`:void 0};if(r.supportsUsageInStreaming!==!1&&(s.stream_options={include_usage:!0}),r.supportsStore&&(s.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?s.max_tokens=n.maxTokens:s.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(s.temperature=n.temperature),t.tools&&t.tools.length>0?(s.tools=L(t.tools,r),r.zaiToolStream&&(s.tool_stream=!0)):h(t.messages)&&(s.tools=[]),o&&k(a,s.tools,o),n?.toolChoice&&(s.tool_choice=n.toolChoice),r.thinkingFormat===`zai`&&e.reasoning){let t=s;if(t.thinking={type:n?.reasoningEffort?`enabled`:`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)s.enable_thinking=!!n?.reasoningEffort;else if(r.thinkingFormat===`qwen-chat-template`&&e.reasoning)s.chat_template_kwargs={enable_thinking:!!n?.reasoningEffort,preserve_thinking:!0};else if(r.thinkingFormat===`chat-template`&&e.reasoning){let t=E(e,n,r);t&&(s.chat_template_kwargs=t)}else if(r.thinkingFormat===`deepseek`&&e.reasoning)n?.reasoningEffort?s.thinking={type:`enabled`}:e.thinkingLevelMap?.off!==null&&(s.thinking={type:`disabled`}),n?.reasoningEffort&&r.supportsReasoningEffort&&(s.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort);else if(r.thinkingFormat===`openrouter`&&e.reasoning){let t=s;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`&&(s.reasoning={effort:t})}else if(r.thinkingFormat===`together`&&e.reasoning){let t=s;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=s;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)s.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;else if(!n?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort){let t=e.thinkingLevelMap?.off;typeof t==`string`&&(s.reasoning_effort=t)}if(e.compat?.openRouterRouting&&(s.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),s.providerOptions={gateway:e}}}return s}function E(e,t,n){let r={};for(let[i,a]of Object.entries(n.chatTemplateKwargs)){let n=D(e,t,a);n!==void 0&&(r[i]=n)}return Object.keys(r).length>0?r:void 0}function D(e,t,n){if(typeof n!=`object`||!n)return n;let r=t?.reasoningEffort;if(!r&&n.omitWhenOff)return;if(n.$var===`thinking.enabled`)return!!r;let i=r?e.thinkingLevelMap?.[r]:e.thinkingLevelMap?.off;return i===void 0?r:typeof i==`string`?i:void 0}function O(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){A(e,n),M(t,n),j(e,n)}function A(e,t){for(let n of e)if(n.role===`system`||n.role===`developer`){N(n,t);return}}function j(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if((r.role===`user`||r.role===`assistant`)&&P(r,t))return}}function M(e,t){if(!e||e.length===0)return;let n=e[e.length-1];n.cache_control=t}function N(e,t){return F(e,t)}function P(e,t){return e.role===`user`||e.role===`assistant`?F(e,t):!1}function F(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 I(e,t,n){let r=[],a=t=>{if(t.includes(`|`)){let[e]=t.split(`|`);return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,40)}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},o=i(t.messages,e,e=>a(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:c(t.systemPrompt)})}let s=null;for(let t=0;t<o.length;t++){let i=o[t];if(n.requiresAssistantAfterToolResult&&s===`toolResult`&&i.role===`user`&&r.push({role:`assistant`,content:`I have processed the tool results.`}),i.role===`user`)if(typeof i.content==`string`)r.push({role:`user`,content:c(i.content)});else{let e=i.content.map(e=>e.type===`text`?{type:`text`,text:c(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});if(e.length===0)continue;r.push({role:`user`,content:e})}else if(i.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=i.content.filter(g).filter(e=>e.text.trim().length>0).map(e=>({type:`text`,text:c(e.text)})),o=a.map(e=>e.text).join(``),s=i.content.filter(_).filter(e=>e.thinking.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText)t.content=[{type:`text`,text:s.map(e=>c(e.thinking)).join(`
|
|
2
|
+
|
|
3
|
+
`)},...a];else{o.length>0&&(t.content=o);let n=s[0].thinkingSignature;e.provider===`opencode-go`&&n===`reasoning`&&(n=`reasoning_content`),n&&n.length>0&&(t[n]=s.map(e=>e.thinking).join(`
|
|
4
|
+
`))}else o.length>0&&(t.content=o);let l=i.content.filter(v);if(l.length>0){t.tool_calls=l.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}));let e=l.filter(e=>e.thoughtSignature).map(e=>{try{return JSON.parse(e.thoughtSignature)}catch{return null}}).filter(Boolean);e.length>0&&(t.reasoning_details=e)}n.requiresReasoningContentOnAssistantMessages&&e.reasoning&&t.reasoning_content===void 0&&(t.reasoning_content=``);let u=t.content;if(!(u!=null&&u.length>0)&&!t.tool_calls)continue;r.push(t)}else if(i.role===`toolResult`){let i=[],a=t;for(;a<o.length&&o[a].role===`toolResult`;a++){let t=o[a],s=t.content.filter(g).map(e=>e.text).join(`
|
|
5
|
+
`),l=t.content.some(e=>e.type===`image`),u={role:`tool`,content:c(s.length>0?s:`(see attached image)`),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(u.name=t.toolName),r.push(u),l&&e.input.includes(`image`))for(let e of t.content)y(e)&&i.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}t=a-1,i.length>0?(n.requiresAssistantAfterToolResult&&r.push({role:`assistant`,content:`I have processed the tool results.`}),r.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...i]}),s=`user`):s=`toolResult`;continue}s=i.role}return r}function L(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function R(t,n){let r=t.prompt_tokens||0,i=t.prompt_tokens_details?.cached_tokens??t.prompt_cache_hit_tokens??0,a=t.prompt_tokens_details?.cache_write_tokens||0,o=Math.max(0,r-i-a),s=t.completion_tokens||0,c={input:o,output:s,cacheRead:i,cacheWrite:a,totalTokens:o+s+i+a,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return e(n,c),c}function z(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 B(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=l||t===`cerebras`||n.includes(`cerebras.ai`)||t===`xai`||n.includes(`api.x.ai`)||i||n.includes(`chutes.ai`)||n.includes(`deepseek.com`)||r||a||t===`opencode`||n.includes(`opencode.ai`)||s||c||u,f=n.includes(`chutes.ai`)||a||c||i||l||u,p=t===`xai`||n.includes(`api.x.ai`),m=t===`deepseek`||n.includes(`deepseek.com`),h=o&&(e.id.startsWith(`anthropic/`)||e.id.startsWith(`openai/`)),g=t===`openrouter`&&e.id.startsWith(`anthropic/`)?`anthropic`:void 0;return{supportsStore:!d,supportsDeveloperRole:h||!d&&!o,supportsReasoningEffort:!p&&!r&&!a&&!i&&!c&&!l&&!u,supportsUsageInStreaming:!0,maxTokensField:f?`max_tokens`:`max_completion_tokens`,requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:m,thinkingFormat:m?`deepseek`:r?`zai`:i?`together`:u?`ant-ling`:o?`openrouter`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},zaiToolStream:!1,supportsStrictMode:!a&&!i&&!c&&!l,cacheControlFormat:g,sendSessionAffinityHeaders:!1,supportsLongCacheRetention:!(i||s||c||l||u)}}function V(e){let t=B(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,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,zaiToolStream:e.compat.zaiToolStream??t.zaiToolStream,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode,cacheControlFormat:e.compat.cacheControlFormat??t.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??t.sendSessionAffinityHeaders,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??t.supportsLongCacheRetention}:t}export{I as convertMessages,S as stream,C as streamSimple};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,o as t}from"./models-ByRUWfA-.js";import{t as n}from"./provider-env-D37PhSJu.js";import{r}from"./transform-messages-D7OsqBmU.js";import{t as i}from"./headers-CbDaTl3c.js";import{n as a,t as o}from"./github-copilot-headers-DRgtIyTm.js";import{n as s}from"./openai-BeH6aC_-.js";import{t as c}from"./openai-prompt-cache-DXo9f3w5.js";import{n as l,r as u,t as d}from"./openai-responses-shared-1KvKQf-4.js";var f=new Set([`openai`,`openai-codex`,`opencode`]);function p(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 m(e,t,n){if(t)return t;if(p(n,`authorization`)||p(n,`cf-aig-authorization`))return`unused`;throw Error(`No API key for provider: ${e}`)}function h(e,t){return e||(n(`PI_CACHE_RETENTION`,t)===`long`?`long`:`short`)}function g(e){return{supportsDeveloperRole:e.compat?.supportsDeveloperRole??!0,sendSessionIdHeader:e.compat?.sendSessionIdHeader??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0}}function _(e,t){return t===`long`&&e.supportsLongCacheRetention?`24h`:void 0}function v(e){if(e instanceof Error){let t=e.status,n=typeof t==`number`?t:void 0;return n===void 0?e.message:`OpenAI API error (${n}): ${e.message}`}try{return JSON.stringify(e)}catch{return String(e)}}var y=(e,n,r)=>{let a=new t;return(async()=>{let t={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{let o=m(e.provider,r?.apiKey,r?.headers),s=h(r?.cacheRetention,r?.env)===`none`?void 0:r?.sessionId,c=x(e,n,o,r?.headers,s),l=S(e,n,r),d=await r?.onPayload?.(l,e);d!==void 0&&(l=d);let f={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs===void 0?{}:{timeout:r.timeoutMs},maxRetries:r?.maxRetries??0},{data:p,response:g}=await c.responses.create(l,f).withResponse();if(await r?.onResponse?.({status:g.status,headers:i(g.headers)},e),a.push({type:`start`,partial:t}),await u(p,t,a,e,{serviceTier:r?.serviceTier,applyServiceTierPricing:(t,n)=>w(t,n,e)}),r?.signal?.aborted)throw Error(`Request was aborted`);if(t.stopReason===`aborted`||t.stopReason===`error`)throw Error(`An unknown error occurred`);a.push({type:`done`,reason:t.stopReason,message:t}),a.end()}catch(e){for(let e of t.content)delete e.index,delete e.partialJson;t.stopReason=r?.signal?.aborted?`aborted`:`error`,t.errorMessage=v(e),a.push({type:`error`,reason:t.stopReason,error:t}),a.end()}})(),a},b=(t,n,i)=>{m(t.provider,i?.apiKey,i?.headers);let a=r(t,i,i?.apiKey),o=i?.reasoning?e(t,i.reasoning):void 0,s=o===`off`?void 0:o;return y(t,n,{...a,reasoningEffort:s})};function x(e,t,n,r,i){let c=g(e),l={...e.headers};if(e.provider===`github-copilot`){let e=a(t.messages),n=o({messages:t.messages,hasImages:e});Object.assign(l,n)}return i&&(c.sendSessionIdHeader&&(l.session_id=i),l[`x-client-request-id`]=i),r&&Object.assign(l,r),new s({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:l})}function S(e,t,n){let r=d(e,t,f),i=h(n?.cacheRetention,n?.env),a=g(e),o={model:e.id,input:r,stream:!0,prompt_cache_key:i===`none`?void 0:c(n?.sessionId),prompt_cache_retention:_(a,i),store:!1};return n?.maxTokens&&(o.max_output_tokens=n?.maxTokens),n?.temperature!==void 0&&(o.temperature=n?.temperature),n?.serviceTier!==void 0&&(o.service_tier=n.serviceTier),t.tools&&t.tools.length>0&&(o.tools=l(t.tools)),e.reasoning&&(n?.reasoningEffort||n?.reasoningSummary?(o.reasoning={effort:n?.reasoningEffort?e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:`medium`,summary:n?.reasoningSummary||`auto`},o.include=[`reasoning.encrypted_content`]):e.provider!==`github-copilot`&&e.thinkingLevelMap?.off!==null&&(o.reasoning={effort:e.thinkingLevelMap?.off??`none`})),o}function C(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function w(e,t,n){let r=C(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{y as stream,b as streamSimple};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as e,o as t,r as n}from"./transform-messages-CQuDksPz.js";import{t as r}from"./provider-env-DwY8YuMk.js";import{t as i}from"./headers-CbDaTl3c.js";import{n as a,t as o}from"./github-copilot-headers-DRgtIyTm.js";import{n as s}from"./openai-BvKpRLAG.js";import{t as c}from"./openai-prompt-cache-DXo9f3w5.js";import{n as l,r as u,t as d}from"./openai-responses-shared-CEQMR7Nx.js";const f=new Set([`openai`,`openai-codex`,`opencode`]);function p(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 m(e,t,n){if(t)return t;if(p(n,`authorization`)||p(n,`cf-aig-authorization`))return`unused`;throw Error(`No API key for provider: ${e}`)}function h(e,t){return e||(r(`PI_CACHE_RETENTION`,t)===`long`?`long`:`short`)}function g(e){return{supportsDeveloperRole:e.compat?.supportsDeveloperRole??!0,sendSessionIdHeader:e.compat?.sendSessionIdHeader??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0}}function _(e,t){return t===`long`&&e.supportsLongCacheRetention?`24h`:void 0}function v(e){if(e instanceof Error){let t=e.status,n=typeof t==`number`?t:void 0;return n===void 0?e.message:`OpenAI API error (${n}): ${e.message}`}try{return JSON.stringify(e)}catch{return String(e)}}const y=(t,n,r)=>{let a=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:`stop`,timestamp:Date.now()};try{let o=m(t.provider,r?.apiKey,r?.headers),s=h(r?.cacheRetention,r?.env)===`none`?void 0:r?.sessionId,c=x(t,n,o,r?.headers,s),l=S(t,n,r),d=await r?.onPayload?.(l,t);d!==void 0&&(l=d);let f={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs===void 0?{}:{timeout:r.timeoutMs},maxRetries:r?.maxRetries??0},{data:p,response:g}=await c.responses.create(l,f).withResponse();if(await r?.onResponse?.({status:g.status,headers:i(g.headers)},t),a.push({type:`start`,partial:e}),await u(p,e,a,t,{serviceTier:r?.serviceTier,applyServiceTierPricing:(e,n)=>w(e,n,t)}),r?.signal?.aborted)throw Error(`Request was aborted`);if(e.stopReason===`aborted`||e.stopReason===`error`)throw Error(`An unknown error occurred`);a.push({type:`done`,reason:e.stopReason,message:e}),a.end()}catch(t){for(let t of e.content)delete t.index,delete t.partialJson;e.stopReason=r?.signal?.aborted?`aborted`:`error`,e.errorMessage=v(t),a.push({type:`error`,reason:e.stopReason,error:e}),a.end()}})(),a},b=(e,r,i)=>{m(e.provider,i?.apiKey,i?.headers);let a=n(e,i,i?.apiKey),o=i?.reasoning?t(e,i.reasoning):void 0,s=o===`off`?void 0:o;return y(e,r,{...a,reasoningEffort:s})};function x(e,t,n,r,i){let c=g(e),l={...e.headers};if(e.provider===`github-copilot`){let e=a(t.messages),n=o({messages:t.messages,hasImages:e});Object.assign(l,n)}return i&&(c.sendSessionIdHeader&&(l.session_id=i),l[`x-client-request-id`]=i),r&&Object.assign(l,r),new s({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:l})}function S(e,t,n){let r=d(e,t,f),i=h(n?.cacheRetention,n?.env),a=g(e),o={model:e.id,input:r,stream:!0,prompt_cache_key:i===`none`?void 0:c(n?.sessionId),prompt_cache_retention:_(a,i),store:!1};return n?.maxTokens&&(o.max_output_tokens=n?.maxTokens),n?.temperature!==void 0&&(o.temperature=n?.temperature),n?.serviceTier!==void 0&&(o.service_tier=n.serviceTier),t.tools&&t.tools.length>0&&(o.tools=l(t.tools)),e.reasoning&&(n?.reasoningEffort||n?.reasoningSummary?(o.reasoning={effort:n?.reasoningEffort?e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:`medium`,summary:n?.reasoningSummary||`auto`},o.include=[`reasoning.encrypted_content`]):e.provider!==`github-copilot`&&e.thinkingLevelMap?.off!==null&&(o.reasoning={effort:e.thinkingLevelMap?.off??`none`})),o}function C(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function w(e,t,n){let r=C(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{y as stream,b as streamSimple};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{t as e}from"./models-ByRUWfA-.js";import{n as t}from"./json-parse-C7d6hyOc.js";import{t as n}from"./transform-messages-D7OsqBmU.js";import{t as r}from"./sanitize-unicode-DmIE6hZJ.js";import{t as i}from"./hash-yQufAZII.js";function a(e,t){let n={v:1,id:e};return t&&(n.phase=t),JSON.stringify(n)}function o(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 s(e,t,a,s){let c=[],l=e=>{let t=e.replace(/[^a-zA-Z0-9_-]/g,`_`);return(t.length>64?t.slice(0,64):t).replace(/_+$/,``)},u=e=>{let t=`fc_${i(e)}`;return t.length>64?t.slice(0,64):t},d=n(t.messages,e,(t,n,r)=>{if(!a.has(e.provider)||!t.includes(`|`))return l(t);let[i,o]=t.split(`|`),s=l(i),c=r.provider!==e.provider||r.api!==e.api?u(o):l(o);return c.startsWith(`fc_`)||(c=l(`fc_${c}`)),`${s}|${c}`});if((s?.includeSystemPrompt??!0)&&t.systemPrompt){let n=e.compat,i=e.reasoning&&n?.supportsDeveloperRole!==!1?`developer`:`system`;c.push({role:i,content:r(t.systemPrompt)})}let f=0;for(let t of d){if(t.role===`user`)if(typeof t.content==`string`)c.push({role:`user`,content:[{type:`input_text`,text:r(t.content)}]});else{let e=t.content.map(e=>e.type===`text`?{type:`input_text`,text:r(e.text)}:{type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`});if(e.length===0)continue;c.push({role:`user`,content:e})}else if(t.role===`assistant`){let n=[],a=t,s=a.model!==e.id&&a.provider===e.provider&&a.api===e.api,l=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,a=o(t.textSignature),s=l===0?`msg_pi_${f}`:`msg_pi_${f}_${l}`;l++;let c=a?.id;c?c.length>64&&(c=`msg_${i(c)}`):c=s,n.push({type:`message`,role:`assistant`,content:[{type:`output_text`,text:r(t.text),annotations:[]}],status:`completed`,id:c,phase:a?.phase})}else if(e.type===`toolCall`){let t=e,[r,i]=t.id.split(`|`),a=i;s&&a?.startsWith(`fc_`)&&(a=void 0),n.push({type:`function_call`,id:a,call_id:r,name:t.name,arguments:JSON.stringify(t.arguments)})}if(n.length===0)continue;c.push(...n)}else if(t.role===`toolResult`){let n=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2
|
+
`),i=t.content.some(e=>e.type===`image`),a=n.length>0,[o]=t.toolCallId.split(`|`),s;if(i&&e.input.includes(`image`)){let e=[];a&&e.push({type:`input_text`,text:r(n)});for(let n of t.content)n.type===`image`&&e.push({type:`input_image`,detail:`auto`,image_url:`data:${n.mimeType};base64,${n.data}`});s=e}else s=r(a?n:`(see attached image)`);c.push({type:`function_call_output`,call_id:o,output:s})}f++}return c}function c(e,t){let n=t?.strict===void 0?!1:t.strict;return e.map(e=>({type:`function`,name:e.name,description:e.description,parameters:e.parameters,strict:n}))}async function l(n,r,i,o,s){let c=null,l=null,d=!1,f=r.content,p=()=>f.length-1,m=t=>{if(d=!0,t?.id&&(r.responseId=t.id),t?.usage){let e=t.usage.input_tokens_details?.cached_tokens||0;r.usage={input:(t.usage.input_tokens||0)-e,output:t.usage.output_tokens||0,cacheRead:e,cacheWrite:0,totalTokens:t.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(e(o,r.usage),s?.applyServiceTierPricing){let e=s.resolveServiceTier?s.resolveServiceTier(t?.service_tier,s.serviceTier):t?.service_tier??s.serviceTier;s.applyServiceTierPricing(r.usage,e)}r.stopReason=u(t?.status),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`){let t=e.item;t.type===`reasoning`?(c=t,l={type:`thinking`,thinking:``},r.content.push(l),i.push({type:`thinking_start`,contentIndex:p(),partial:r})):t.type===`message`?(c=t,l={type:`text`,text:``},r.content.push(l),i.push({type:`text_start`,contentIndex:p(),partial:r})):t.type===`function_call`&&(c=t,l={type:`toolCall`,id:`${t.call_id}|${t.id}`,name:t.name,arguments:{},partialJson:t.arguments||``},r.content.push(l),i.push({type:`toolcall_start`,contentIndex:p(),partial:r}))}else if(e.type===`response.reasoning_summary_part.added`)c&&c.type===`reasoning`&&(c.summary=c.summary||[],c.summary.push(e.part));else if(e.type===`response.reasoning_summary_text.delta`){if(c?.type===`reasoning`&&l?.type===`thinking`){c.summary=c.summary||[];let t=c.summary[c.summary.length-1];t&&(l.thinking+=e.delta,t.text+=e.delta,i.push({type:`thinking_delta`,contentIndex:p(),delta:e.delta,partial:r}))}}else if(e.type===`response.reasoning_summary_part.done`){if(c?.type===`reasoning`&&l?.type===`thinking`){c.summary=c.summary||[];let e=c.summary[c.summary.length-1];e&&(l.thinking+=`
|
|
3
|
+
|
|
4
|
+
`,e.text+=`
|
|
5
|
+
|
|
6
|
+
`,i.push({type:`thinking_delta`,contentIndex:p(),delta:`
|
|
7
|
+
|
|
8
|
+
`,partial:r}))}}else if(e.type===`response.reasoning_text.delta`)c?.type===`reasoning`&&l?.type===`thinking`&&(l.thinking+=e.delta,i.push({type:`thinking_delta`,contentIndex:p(),delta:e.delta,partial:r}));else if(e.type===`response.content_part.added`)c?.type===`message`&&(c.content=c.content||[],(e.part.type===`output_text`||e.part.type===`refusal`)&&c.content.push(e.part));else if(e.type===`response.output_text.delta`){if(c?.type===`message`&&l?.type===`text`){if(!c.content||c.content.length===0)continue;let t=c.content[c.content.length-1];t?.type===`output_text`&&(l.text+=e.delta,t.text+=e.delta,i.push({type:`text_delta`,contentIndex:p(),delta:e.delta,partial:r}))}}else if(e.type===`response.refusal.delta`){if(c?.type===`message`&&l?.type===`text`){if(!c.content||c.content.length===0)continue;let t=c.content[c.content.length-1];t?.type===`refusal`&&(l.text+=e.delta,t.refusal+=e.delta,i.push({type:`text_delta`,contentIndex:p(),delta:e.delta,partial:r}))}}else if(e.type===`response.function_call_arguments.delta`)c?.type===`function_call`&&l?.type===`toolCall`&&(l.partialJson+=e.delta,l.arguments=t(l.partialJson),i.push({type:`toolcall_delta`,contentIndex:p(),delta:e.delta,partial:r}));else if(e.type===`response.function_call_arguments.done`){if(c?.type===`function_call`&&l?.type===`toolCall`){let n=l.partialJson;if(l.partialJson=e.arguments,l.arguments=t(l.partialJson),e.arguments.startsWith(n)){let t=e.arguments.slice(n.length);t.length>0&&i.push({type:`toolcall_delta`,contentIndex:p(),delta:t,partial:r})}}}else if(e.type===`response.output_item.done`){let n=e.item;if(n.type===`reasoning`&&l?.type===`thinking`){let e=n.summary?.map(e=>e.text).join(`
|
|
9
|
+
|
|
10
|
+
`)||``,t=n.content?.map(e=>e.text).join(`
|
|
11
|
+
|
|
12
|
+
`)||``;l.thinking=e||t||l.thinking,l.thinkingSignature=JSON.stringify(n),i.push({type:`thinking_end`,contentIndex:p(),content:l.thinking,partial:r}),l=null}else if(n.type===`message`&&l?.type===`text`)l.text=n.content?.map(e=>e.type===`output_text`?e.text:e.refusal).join(``)||``,l.textSignature=a(n.id,n.phase??void 0),i.push({type:`text_end`,contentIndex:p(),content:l.text,partial:r}),l=null;else if(n.type===`function_call`){let e=l?.type===`toolCall`&&l.partialJson?t(l.partialJson):t(n.arguments||`{}`),a;l?.type===`toolCall`?(l.arguments=e,delete l.partialJson,a=l):a={type:`toolCall`,id:`${n.call_id}|${n.id}`,name:n.name,arguments:e},l=null,i.push({type:`toolcall_end`,contentIndex:p(),toolCall:a,partial:r})}}else if(e.type===`response.completed`||e.type===`response.incomplete`)m(e.response);else if(e.type===`error`)throw Error(`Error Code ${e.code}: ${e.message}`||`Unknown error`);else if(e.type===`response.failed`){d=!0;let t=e.response?.error,n=e.response?.incomplete_details,r=t?`${t.code||`unknown`}: ${t.message||`no message`}`:n?.reason?`incomplete: ${n.reason}`:`Unknown error (no error details in response)`;throw Error(r)}if(!d)throw Error(`OpenAI Responses stream ended before a terminal response event`)}function u(e){if(!e)return`stop`;switch(e){case`completed`:return`stop`;case`incomplete`:return`length`;case`failed`:case`cancelled`:return`error`;case`in_progress`:case`queued`:return`stop`;default:throw Error(`Unhandled stop reason: ${e}`)}}export{c as n,l as r,s as t};
|